diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscovererTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscovererTests.java index 3e95e6ed4f8..b038595061a 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscovererTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscovererTests.java @@ -23,9 +23,8 @@ import org.junit.Test; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Unit tests for the {@link AspectJAdviceParameterNameDiscoverer} class. @@ -236,8 +235,7 @@ public class AspectJAdviceParameterNameDiscovererTests { protected void assertParameterNames( Method method, String pointcut, String returning, String throwing, String[] parameterNames) { - assertEquals("bad test specification, must have same number of parameter names as method arguments", - method.getParameterCount(), parameterNames.length); + assertThat(parameterNames.length).as("bad test specification, must have same number of parameter names as method arguments").isEqualTo(method.getParameterCount()); AspectJAdviceParameterNameDiscoverer discoverer = new AspectJAdviceParameterNameDiscoverer(pointcut); discoverer.setRaiseExceptions(true); @@ -248,16 +246,14 @@ public class AspectJAdviceParameterNameDiscovererTests { String formattedExpectedNames = format(parameterNames); 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 + - " '" + formattedActualNames + "'", - parameterNames.length, discoveredNames.length); + " '" + formattedActualNames + "'").isEqualTo(parameterNames.length); for (int i = 0; i < discoveredNames.length; i++) { - assertNotNull("Parameter names must never be null", discoveredNames[i]); - assertEquals("Expecting parameter " + i + " to be named '" + - parameterNames[i] + "' but was '" + discoveredNames[i] + "'", - parameterNames[i], discoveredNames[i]); + assertThat(discoveredNames[i]).as("Parameter names must never be null").isNotNull(); + assertThat(discoveredNames[i]).as("Expecting parameter " + i + " to be named '" + + parameterNames[i] + "' but was '" + discoveredNames[i] + "'").isEqualTo(parameterNames[i]); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java index fc85c27ee73..d1170b3cd78 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java @@ -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.assertThatIllegalArgumentException; 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 @@ -81,9 +78,9 @@ public class AspectJExpressionPointcutTests { // not currently testable in a reliable fashion //assertDoesNotMatchStringClass(classFilter); - assertFalse("Should not be a runtime match", methodMatcher.isRuntime()); + assertThat(methodMatcher.isRuntime()).as("Should not be a runtime match").isFalse(); 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 @@ -99,9 +96,9 @@ public class AspectJExpressionPointcutTests { // not currently testable in a reliable fashion //assertDoesNotMatchStringClass(classFilter); - assertFalse("Should not be a runtime match", methodMatcher.isRuntime()); + assertThat(methodMatcher.isRuntime()).as("Should not be a runtime match").isFalse(); 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(); iOtherPc.setExpression(matchesIOther); - assertTrue(testBeanPc.matches(TestBean.class)); - assertTrue(testBeanPc.matches(getAge, TestBean.class)); - assertTrue(iOtherPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)); - assertFalse(testBeanPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)); + assertThat(testBeanPc.matches(TestBean.class)).isTrue(); + assertThat(testBeanPc.matches(getAge, TestBean.class)).isTrue(); + assertThat(iOtherPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)).isTrue(); + assertThat(testBeanPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)).isFalse(); } @Test @@ -154,13 +151,13 @@ public class AspectJExpressionPointcutTests { AspectJExpressionPointcut withinBeansPc = new AspectJExpressionPointcut(); withinBeansPc.setExpression(withinBeansPackage); - assertTrue(withinBeansPc.matches(TestBean.class)); - assertTrue(withinBeansPc.matches(getAge, TestBean.class)); - assertEquals(matchSubpackages, withinBeansPc.matches(DeepBean.class)); - assertEquals(matchSubpackages, withinBeansPc.matches( - DeepBean.class.getMethod("aMethod", String.class), DeepBean.class)); - assertFalse(withinBeansPc.matches(String.class)); - assertFalse(withinBeansPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)); + assertThat(withinBeansPc.matches(TestBean.class)).isTrue(); + assertThat(withinBeansPc.matches(getAge, TestBean.class)).isTrue(); + assertThat(withinBeansPc.matches(DeepBean.class)).isEqualTo(matchSubpackages); + assertThat(withinBeansPc.matches( + DeepBean.class.getMethod("aMethod", String.class), DeepBean.class)).isEqualTo(matchSubpackages); + assertThat(withinBeansPc.matches(String.class)).isFalse(); + assertThat(withinBeansPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)).isFalse(); } @Test @@ -201,12 +198,10 @@ public class AspectJExpressionPointcutTests { // not currently testable in a reliable fashion //assertDoesNotMatchStringClass(classFilter); - assertTrue("Should match with setSomeNumber with Double input", - methodMatcher.matches(setSomeNumber, TestBean.class, new Double(12))); - assertFalse("Should not match setSomeNumber with Integer input", - methodMatcher.matches(setSomeNumber, TestBean.class, new Integer(11))); - assertFalse("Should not match getAge", methodMatcher.matches(getAge, TestBean.class)); - assertTrue("Should be a runtime match", methodMatcher.isRuntime()); + assertThat(methodMatcher.matches(setSomeNumber, TestBean.class, new Double(12))).as("Should match with setSomeNumber with Double input").isTrue(); + assertThat(methodMatcher.matches(setSomeNumber, TestBean.class, new Integer(11))).as("Should not match setSomeNumber with Integer input").isFalse(); + assertThat(methodMatcher.matches(getAge, TestBean.class)).as("Should not match getAge").isFalse(); + assertThat(methodMatcher.isRuntime()).as("Should be a runtime match").isTrue(); } @Test @@ -215,11 +210,11 @@ public class AspectJExpressionPointcutTests { CallCountingInterceptor interceptor = new CallCountingInterceptor(); 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(); - assertEquals("Calls should be 1", 1, interceptor.getCount()); + assertThat(interceptor.getCount()).as("Calls should be 1").isEqualTo(1); testBean.setAge(90); - assertEquals("Calls should still be 1", 1, interceptor.getCount()); + assertThat(interceptor.getCount()).as("Calls should still be 1").isEqualTo(1); } @Test @@ -228,12 +223,12 @@ public class AspectJExpressionPointcutTests { CallCountingInterceptor interceptor = new CallCountingInterceptor(); 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)); - assertEquals("Calls should be 1", 1, interceptor.getCount()); + assertThat(interceptor.getCount()).as("Calls should be 1").isEqualTo(1); testBean.setSomeNumber(new Integer(90)); - assertEquals("Calls should be 1", 1, interceptor.getCount()); + assertThat(interceptor.getCount()).as("Calls should be 1").isEqualTo(1); } @Test @@ -260,11 +255,11 @@ public class AspectJExpressionPointcutTests { } 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) { - assertTrue("Expression should match TestBean class", classFilter.matches(TestBean.class)); + assertThat(classFilter.matches(TestBean.class)).as("Expression should match TestBean class").isTrue(); } @Test @@ -279,14 +274,14 @@ public class AspectJExpressionPointcutTests { public void testAndSubstitution() { Pointcut pc = getPointcut("execution(* *(..)) and args(String)"); PointcutExpression expr = ((AspectJExpressionPointcut) pc).getPointcutExpression(); - assertEquals("execution(* *(..)) && args(String)",expr.getPointcutExpression()); + assertThat(expr.getPointcutExpression()).isEqualTo("execution(* *(..)) && args(String)"); } @Test public void testMultipleAndSubstitutions() { Pointcut pc = getPointcut("execution(* *(..)) and args(String) and this(Object)"); 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) { diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutMatchingTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutMatchingTests.java index 2bad732cd6e..44ba97915db 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutMatchingTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutMatchingTests.java @@ -20,8 +20,7 @@ import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for matching of bean() pointcut designator. @@ -80,13 +79,11 @@ public class BeanNamePointcutMatchingTests { private void assertMatch(String beanName, String pcExpression) { - assertTrue("Unexpected mismatch for bean \"" + beanName + "\" for pcExpression \"" + pcExpression + "\"", - matches(beanName, pcExpression)); + assertThat(matches(beanName, pcExpression)).as("Unexpected mismatch for bean \"" + beanName + "\" for pcExpression \"" + pcExpression + "\"").isTrue(); } private void assertMisMatch(String beanName, String pcExpression) { - assertFalse("Unexpected match for bean \"" + beanName + "\" for pcExpression \"" + pcExpression + "\"", - matches(beanName, pcExpression)); + assertThat(matches(beanName, pcExpression)).as("Unexpected match for bean \"" + beanName + "\" for pcExpression \"" + pcExpression + "\"").isFalse(); } private static boolean matches(final String beanName, String pcExpression) { diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java index 0b42c4e7c75..c60861cf1df 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java @@ -37,13 +37,9 @@ import org.springframework.lang.Nullable; import org.springframework.tests.sample.beans.ITestBean; 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.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 @@ -80,21 +76,21 @@ public class MethodInvocationProceedingJoinPointTests { @Override public void before(Method method, Object[] args, @Nullable Object target) throws Throwable { 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 jp.toShortString(); jp.toLongString(); - assertSame(target, AbstractAspectJAdvice.currentJoinPoint().getTarget()); - assertFalse(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getTarget())); + assertThat(AbstractAspectJAdvice.currentJoinPoint().getTarget()).isSameAs(target); + assertThat(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getTarget())).isFalse(); 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 - assertSame(thisProxy, AbstractAspectJAdvice.currentJoinPoint().getThis()); + assertThat(AbstractAspectJAdvice.currentJoinPoint().getThis()).isSameAs(thisProxy); // Try reentrant call--will go through this advice. // Be sure to increment depth to avoid infinite recursion @@ -103,29 +99,29 @@ public class MethodInvocationProceedingJoinPointTests { thisProxy.toString(); // Change age, so this will be returned by invocation thisProxy.setAge(newAge); - assertEquals(newAge, thisProxy.getAge()); + assertThat(thisProxy.getAge()).isEqualTo(newAge); } - assertSame(AopContext.currentProxy(), thisProxy); - assertSame(target, raw); + assertThat(thisProxy).isSameAs(AopContext.currentProxy()); + assertThat(raw).isSameAs(target); - assertSame(method.getName(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getName()); - assertEquals(method.getModifiers(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getModifiers()); + assertThat(AbstractAspectJAdvice.currentJoinPoint().getSignature().getName()).isSameAs(method.getName()); + assertThat(AbstractAspectJAdvice.currentJoinPoint().getSignature().getModifiers()).isEqualTo(method.getModifiers()); MethodSignature msig = (MethodSignature) AbstractAspectJAdvice.currentJoinPoint().getSignature(); - assertSame("Return same MethodSignature repeatedly", msig, AbstractAspectJAdvice.currentJoinPoint().getSignature()); - assertSame("Return same JoinPoint repeatedly", AbstractAspectJAdvice.currentJoinPoint(), AbstractAspectJAdvice.currentJoinPoint()); - assertEquals(method.getDeclaringClass(), msig.getDeclaringType()); - assertTrue(Arrays.equals(method.getParameterTypes(), msig.getParameterTypes())); - assertEquals(method.getReturnType(), msig.getReturnType()); - assertTrue(Arrays.equals(method.getExceptionTypes(), msig.getExceptionTypes())); + assertThat(AbstractAspectJAdvice.currentJoinPoint().getSignature()).as("Return same MethodSignature repeatedly").isSameAs(msig); + assertThat(AbstractAspectJAdvice.currentJoinPoint()).as("Return same JoinPoint repeatedly").isSameAs(AbstractAspectJAdvice.currentJoinPoint()); + assertThat(msig.getDeclaringType()).isEqualTo(method.getDeclaringClass()); + assertThat(Arrays.equals(method.getParameterTypes(), msig.getParameterTypes())).isTrue(); + assertThat(msig.getReturnType()).isEqualTo(method.getReturnType()); + assertThat(Arrays.equals(method.getExceptionTypes(), msig.getExceptionTypes())).isTrue(); msig.toLongString(); msig.toShortString(); } }); ITestBean itb = (ITestBean) pf.getProxy(); // Any call will do - assertEquals("Advice reentrantly set age", newAge, itb.getAge()); + assertThat(itb.getAge()).as("Advice reentrantly set age").isEqualTo(newAge); } @Test @@ -137,8 +133,8 @@ public class MethodInvocationProceedingJoinPointTests { @Override public void before(Method method, Object[] args, @Nullable Object target) throws Throwable { SourceLocation sloc = AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(); - assertEquals("Same source location must be returned on subsequent requests", sloc, AbstractAspectJAdvice.currentJoinPoint().getSourceLocation()); - assertEquals(TestBean.class, sloc.getWithinType()); + assertThat(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation()).as("Same source location must be returned on subsequent requests").isEqualTo(sloc); + assertThat(sloc.getWithinType()).isEqualTo(TestBean.class); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(sloc::getLine); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(sloc::getFileName); } @@ -157,10 +153,10 @@ public class MethodInvocationProceedingJoinPointTests { @Override public void before(Method method, Object[] args, @Nullable Object target) throws Throwable { StaticPart staticPart = AbstractAspectJAdvice.currentJoinPoint().getStaticPart(); - assertEquals("Same static part must be returned on subsequent requests", staticPart, AbstractAspectJAdvice.currentJoinPoint().getStaticPart()); - assertEquals(ProceedingJoinPoint.METHOD_EXECUTION, staticPart.getKind()); - assertSame(AbstractAspectJAdvice.currentJoinPoint().getSignature(), staticPart.getSignature()); - assertEquals(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(), staticPart.getSourceLocation()); + assertThat(AbstractAspectJAdvice.currentJoinPoint().getStaticPart()).as("Same static part must be returned on subsequent requests").isEqualTo(staticPart); + assertThat(staticPart.getKind()).isEqualTo(ProceedingJoinPoint.METHOD_EXECUTION); + assertThat(staticPart.getSignature()).isSameAs(AbstractAspectJAdvice.currentJoinPoint().getSignature()); + assertThat(staticPart.getSourceLocation()).isEqualTo(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation()); } }); ITestBean itb = (ITestBean) pf.getProxy(); @@ -181,13 +177,13 @@ public class MethodInvocationProceedingJoinPointTests { JoinPoint.StaticPart aspectJVersionJp = Factory.makeEncSJP(method); JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint(); - assertEquals(aspectJVersionJp.getSignature().toLongString(), jp.getSignature().toLongString()); - assertEquals(aspectJVersionJp.getSignature().toShortString(), jp.getSignature().toShortString()); - assertEquals(aspectJVersionJp.getSignature().toString(), jp.getSignature().toString()); + assertThat(jp.getSignature().toLongString()).isEqualTo(aspectJVersionJp.getSignature().toLongString()); + assertThat(jp.getSignature().toShortString()).isEqualTo(aspectJVersionJp.getSignature().toShortString()); + assertThat(jp.getSignature().toString()).isEqualTo(aspectJVersionJp.getSignature().toString()); - assertEquals(aspectJVersionJp.toLongString(), jp.toLongString()); - assertEquals(aspectJVersionJp.toShortString(), jp.toShortString()); - assertEquals(aspectJVersionJp.toString(), jp.toString()); + assertThat(jp.toLongString()).isEqualTo(aspectJVersionJp.toLongString()); + assertThat(jp.toShortString()).isEqualTo(aspectJVersionJp.toShortString()); + assertThat(jp.toString()).isEqualTo(aspectJVersionJp.toString()); } }); ITestBean itb = (ITestBean) pf.getProxy(); diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java index 8dbbfac3c3b..5f75a3de435 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java @@ -29,8 +29,7 @@ import test.annotation.transaction.Tx; import org.springframework.aop.framework.ProxyFactory; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Java 5 specific {@link AspectJExpressionPointcutTests}. @@ -66,12 +65,12 @@ public class TigerAspectJExpressionPointcutTests { //assertFalse(ajexp.matches(TestBean.class)); Method takesGenericList = methodsOnHasGeneric.get("setFriends"); - assertTrue(ajexp.matches(takesGenericList, HasGeneric.class)); - assertTrue(ajexp.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class)); - assertFalse(ajexp.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class)); - assertFalse(ajexp.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class)); + assertThat(ajexp.matches(takesGenericList, HasGeneric.class)).isTrue(); + assertThat(ajexp.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class)).isTrue(); + assertThat(ajexp.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class)).isFalse(); + assertThat(ajexp.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class)).isFalse(); - assertFalse(ajexp.matches(getAge, TestBean.class)); + assertThat(ajexp.matches(getAge, TestBean.class)).isFalse(); } @Test @@ -88,16 +87,16 @@ public class TigerAspectJExpressionPointcutTests { AspectJExpressionPointcut jdbcVarArgs = new AspectJExpressionPointcut(); jdbcVarArgs.setExpression(expression); - assertTrue(jdbcVarArgs.matches( + assertThat(jdbcVarArgs.matches( MyTemplate.class.getMethod("queryForInt", String.class, Object[].class), - MyTemplate.class)); + MyTemplate.class)).isTrue(); Method takesGenericList = methodsOnHasGeneric.get("setFriends"); - assertFalse(jdbcVarArgs.matches(takesGenericList, HasGeneric.class)); - assertFalse(jdbcVarArgs.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class)); - assertFalse(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class)); - assertFalse(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class)); - assertFalse(jdbcVarArgs.matches(getAge, TestBean.class)); + assertThat(jdbcVarArgs.matches(takesGenericList, HasGeneric.class)).isFalse(); + assertThat(jdbcVarArgs.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class)).isFalse(); + assertThat(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class)).isFalse(); + assertThat(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class)).isFalse(); + assertThat(jdbcVarArgs.matches(getAge, TestBean.class)).isFalse(); } @Test @@ -116,12 +115,12 @@ public class TigerAspectJExpressionPointcutTests { public void testMatchAnnotationOnClassWithSubpackageWildcard() throws Exception { String expression = "within(@(test.annotation..*) *)"; AspectJExpressionPointcut springAnnotatedPc = testMatchAnnotationOnClass(expression); - assertFalse(springAnnotatedPc.matches(TestBean.class.getMethod("setName", String.class), TestBean.class)); - assertTrue(springAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo"), SpringAnnotated.class)); + assertThat(springAnnotatedPc.matches(TestBean.class.getMethod("setName", String.class), TestBean.class)).isFalse(); + assertThat(springAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo"), SpringAnnotated.class)).isTrue(); expression = "within(@(test.annotation.transaction..*) *)"; AspectJExpressionPointcut springTxAnnotatedPc = testMatchAnnotationOnClass(expression); - assertFalse(springTxAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo"), SpringAnnotated.class)); + assertThat(springTxAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo"), SpringAnnotated.class)).isFalse(); } @Test @@ -134,11 +133,11 @@ public class TigerAspectJExpressionPointcutTests { AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut(); ajexp.setExpression(expression); - assertFalse(ajexp.matches(getAge, TestBean.class)); - assertTrue(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)); - assertTrue(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)); - assertTrue(ajexp.matches(BeanB.class.getMethod("setName", String.class), BeanB.class)); - assertFalse(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); + assertThat(ajexp.matches(getAge, TestBean.class)).isFalse(); + assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isTrue(); + assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isTrue(); + assertThat(ajexp.matches(BeanB.class.getMethod("setName", String.class), BeanB.class)).isTrue(); + assertThat(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse(); return ajexp; } @@ -148,12 +147,12 @@ public class TigerAspectJExpressionPointcutTests { AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut(); ajexp.setExpression(expression); - assertFalse(ajexp.matches(getAge, TestBean.class)); - assertFalse(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)); - assertFalse(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)); - assertFalse(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); - assertTrue(ajexp.matches(BeanA.class.getMethod("getAge"), BeanA.class)); - assertFalse(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); + assertThat(ajexp.matches(getAge, TestBean.class)).isFalse(); + assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse(); + assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse(); + assertThat(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse(); + assertThat(ajexp.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isTrue(); + assertThat(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse(); } @Test @@ -165,7 +164,7 @@ public class TigerAspectJExpressionPointcutTests { ProxyFactory factory = new ProxyFactory(new BeanA()); factory.setProxyTargetClass(true); 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 @@ -177,7 +176,7 @@ public class TigerAspectJExpressionPointcutTests { ProxyFactory factory = new ProxyFactory(new BeanA()); factory.setProxyTargetClass(false); 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 @@ -186,14 +185,14 @@ public class TigerAspectJExpressionPointcutTests { AspectJExpressionPointcut anySpringMethodAnnotation = new AspectJExpressionPointcut(); anySpringMethodAnnotation.setExpression(expression); - assertFalse(anySpringMethodAnnotation.matches(getAge, TestBean.class)); - assertFalse(anySpringMethodAnnotation.matches( - HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)); - assertFalse(anySpringMethodAnnotation.matches( - HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)); - assertFalse(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); - assertTrue(anySpringMethodAnnotation.matches(BeanA.class.getMethod("getAge"), BeanA.class)); - assertFalse(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); + assertThat(anySpringMethodAnnotation.matches(getAge, TestBean.class)).isFalse(); + assertThat(anySpringMethodAnnotation.matches( + HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse(); + assertThat(anySpringMethodAnnotation.matches( + HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse(); + assertThat(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse(); + assertThat(anySpringMethodAnnotation.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isTrue(); + assertThat(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse(); } @Test @@ -202,28 +201,27 @@ public class TigerAspectJExpressionPointcutTests { AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut(); takesSpringAnnotatedArgument2.setExpression(expression); - assertFalse(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class)); - assertFalse(takesSpringAnnotatedArgument2.matches( - HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)); - assertFalse(takesSpringAnnotatedArgument2.matches( - HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)); - assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); - assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class)); - assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); + assertThat(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class)).isFalse(); + assertThat(takesSpringAnnotatedArgument2.matches( + HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse(); + assertThat(takesSpringAnnotatedArgument2.matches( + HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse(); + assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse(); + assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isFalse(); + 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)); + ProcessesSpringAnnotatedParameters.class)).isTrue(); // True because it maybeMatches with potential argument subtypes - assertTrue(takesSpringAnnotatedArgument2.matches( + assertThat(takesSpringAnnotatedArgument2.matches( 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, new TestBean(), new BeanA()) - ); + ProcessesSpringAnnotatedParameters.class, new TestBean(), new BeanA())).isFalse(); } @Test @@ -232,21 +230,21 @@ public class TigerAspectJExpressionPointcutTests { AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut(); takesSpringAnnotatedArgument2.setExpression(expression); - assertFalse(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class)); - assertFalse(takesSpringAnnotatedArgument2.matches( - HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)); - assertFalse(takesSpringAnnotatedArgument2.matches( - HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)); - assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); - assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class)); - assertFalse(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)); + assertThat(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class)).isFalse(); + assertThat(takesSpringAnnotatedArgument2.matches( + HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse(); + assertThat(takesSpringAnnotatedArgument2.matches( + HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse(); + assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse(); + assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isFalse(); + 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)); - assertFalse(takesSpringAnnotatedArgument2.matches( + ProcessesSpringAnnotatedParameters.class)).isTrue(); + assertThat(takesSpringAnnotatedArgument2.matches( 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 { + @SuppressWarnings("unused") private String name; private int age; @@ -320,6 +319,7 @@ public class TigerAspectJExpressionPointcutTests { @Tx static class BeanB { + @SuppressWarnings("unused") private String name; public void setName(String name) { diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java index ef5276a2ad5..0652d51f940 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java @@ -34,8 +34,8 @@ import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.core.OverridingClassLoader; import org.springframework.lang.Nullable; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Dave Syer @@ -111,10 +111,10 @@ public class TrickyAspectJPointcutExpressionTests { factory.addAdvisor(advisor); TestService bean = (TestService) factory.getProxy(); - assertEquals(0, logAdvice.getCountThrows()); + assertThat(logAdvice.getCountThrows()).isEqualTo(0); assertThatExceptionOfType(TestException.class).isThrownBy( bean::sayHello).withMessageContaining(message); - assertEquals(1, logAdvice.getCountThrows()); + assertThat(logAdvice.getCountThrows()).isEqualTo(1); } diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java index ec16c5187f1..544976127ec 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java @@ -26,10 +26,9 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Unit tests for the {@link TypePatternClassFilter} class. @@ -50,36 +49,36 @@ public class TypePatternClassFilterTests { @Test public void testValidPatternMatching() { TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.tests.sample.beans.*"); - assertTrue("Must match: in package", tpcf.matches(TestBean.class)); - assertTrue("Must match: in package", tpcf.matches(ITestBean.class)); - assertTrue("Must match: in package", tpcf.matches(IOther.class)); - assertFalse("Must be excluded: in wrong package", tpcf.matches(DeepBean.class)); - assertFalse("Must be excluded: in wrong package", tpcf.matches(BeanFactory.class)); - assertFalse("Must be excluded: in wrong package", tpcf.matches(DefaultListableBeanFactory.class)); + assertThat(tpcf.matches(TestBean.class)).as("Must match: in package").isTrue(); + assertThat(tpcf.matches(ITestBean.class)).as("Must match: in package").isTrue(); + assertThat(tpcf.matches(IOther.class)).as("Must match: in package").isTrue(); + assertThat(tpcf.matches(DeepBean.class)).as("Must be excluded: in wrong package").isFalse(); + assertThat(tpcf.matches(BeanFactory.class)).as("Must be excluded: in wrong package").isFalse(); + assertThat(tpcf.matches(DefaultListableBeanFactory.class)).as("Must be excluded: in wrong package").isFalse(); } @Test public void testSubclassMatching() { TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.tests.sample.beans.ITestBean+"); - assertTrue("Must match: in package", tpcf.matches(TestBean.class)); - assertTrue("Must match: in package", tpcf.matches(ITestBean.class)); - assertTrue("Must match: in package", tpcf.matches(CountingTestBean.class)); - assertFalse("Must be excluded: not subclass", tpcf.matches(IOther.class)); - assertFalse("Must be excluded: not subclass", tpcf.matches(DefaultListableBeanFactory.class)); + assertThat(tpcf.matches(TestBean.class)).as("Must match: in package").isTrue(); + assertThat(tpcf.matches(ITestBean.class)).as("Must match: in package").isTrue(); + assertThat(tpcf.matches(CountingTestBean.class)).as("Must match: in package").isTrue(); + assertThat(tpcf.matches(IOther.class)).as("Must be excluded: not subclass").isFalse(); + assertThat(tpcf.matches(DefaultListableBeanFactory.class)).as("Must be excluded: not subclass").isFalse(); } @Test public void testAndOrNotReplacement() { TypePatternClassFilter tpcf = new TypePatternClassFilter("java.lang.Object or java.lang.String"); - assertFalse("matches Number",tpcf.matches(Number.class)); - assertTrue("matches Object",tpcf.matches(Object.class)); - assertTrue("matchesString",tpcf.matches(String.class)); + assertThat(tpcf.matches(Number.class)).as("matches Number").isFalse(); + assertThat(tpcf.matches(Object.class)).as("matches Object").isTrue(); + assertThat(tpcf.matches(String.class)).as("matchesString").isTrue(); tpcf = new TypePatternClassFilter("java.lang.Number+ and java.lang.Float"); - assertTrue("matches Float",tpcf.matches(Float.class)); - assertFalse("matches Double",tpcf.matches(Double.class)); + assertThat(tpcf.matches(Float.class)).as("matches Float").isTrue(); + assertThat(tpcf.matches(Double.class)).as("matches Double").isFalse(); tpcf = new TypePatternClassFilter("java.lang.Number+ and not java.lang.Float"); - assertFalse("matches Float",tpcf.matches(Float.class)); - assertTrue("matches Double",tpcf.matches(Double.class)); + assertThat(tpcf.matches(Float.class)).as("matches Float").isFalse(); + assertThat(tpcf.matches(Double.class)).as("matches Double").isTrue(); } @Test diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java index 97f9a9e558c..8fc79006e1b 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java @@ -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.assertThatIllegalArgumentException; 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. @@ -108,28 +104,28 @@ public abstract class AbstractAspectJAdvisorFactoryTests { TestBean itb = (TestBean) createProxy(target, getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerTargetAspect(), "someBean")), 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; ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor sia = (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]; LazySingletonAspectInstanceFactoryDecorator maaif = (LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory(); - assertFalse(maaif.isMaterialized()); + assertThat(maaif.isMaterialized()).isFalse(); // Check that the perclause pointcut is valid - assertTrue(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)); - assertNotSame(imapa.getDeclaredPointcut(), imapa.getPointcut()); + assertThat(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue(); + assertThat(imapa.getPointcut()).isNotSameAs(imapa.getDeclaredPointcut()); // Hit the method in the per clause to instantiate the aspect itb.getSpouse(); - assertTrue(maaif.isMaterialized()); + assertThat(maaif.isMaterialized()).isTrue(); - assertEquals("Around advice must apply", 0, itb.getAge()); - assertEquals("Around advice must apply", 1, itb.getAge()); + assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0); + assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1); } @Test @@ -151,13 +147,13 @@ public abstract class AbstractAspectJAdvisorFactoryTests { Collections.sort(advisors, new OrderComparator()); 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 itb.getSpouse(); - assertEquals("Around advice must apply", 0, itb.getAge()); - assertEquals("Around advice must apply", 1, itb.getAge()); + assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0); + assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1); } @Test @@ -177,13 +173,13 @@ public abstract class AbstractAspectJAdvisorFactoryTests { Collections.sort(advisors, new OrderComparator()); 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 itb.getSpouse(); - assertEquals("Around advice must apply", 0, itb.getAge()); - assertEquals("Around advice must apply", 1, itb.getAge()); + assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0); + assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1); } @Test @@ -194,32 +190,32 @@ public abstract class AbstractAspectJAdvisorFactoryTests { TestBean itb = (TestBean) createProxy(target, getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerThisAspect(), "someBean")), 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; // 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) 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]; LazySingletonAspectInstanceFactoryDecorator maaif = (LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory(); - assertFalse(maaif.isMaterialized()); + assertThat(maaif.isMaterialized()).isFalse(); // Check that the perclause pointcut is valid - assertTrue(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)); - assertNotSame(imapa.getDeclaredPointcut(), imapa.getPointcut()); + assertThat(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue(); + assertThat(imapa.getPointcut()).isNotSameAs(imapa.getDeclaredPointcut()); // Hit the method in the per clause to instantiate the aspect 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()); - assertEquals("Around advice must apply", 1, itb.getAge()); + assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(0); + assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(1); } @Test @@ -229,38 +225,38 @@ public abstract class AbstractAspectJAdvisorFactoryTests { target.setAge(realAge); PerTypeWithinAspectInstanceFactory aif = new PerTypeWithinAspectInstanceFactory(); TestBean itb = (TestBean) createProxy(target, getFixture().getAdvisors(aif), TestBean.class); - assertEquals("No method calls", 0, aif.getInstantiationCount()); - assertEquals("Around advice must now apply", 0, itb.getAge()); + assertThat(aif.getInstantiationCount()).as("No method calls").isEqualTo(0); + assertThat(itb.getAge()).as("Around advice must now apply").isEqualTo(0); Advised advised = (Advised) itb; // 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) 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]; LazySingletonAspectInstanceFactoryDecorator maaif = (LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory(); - assertTrue(maaif.isMaterialized()); + assertThat(maaif.isMaterialized()).isTrue(); // Check that the perclause pointcut is valid - assertTrue(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)); - assertNotSame(imapa.getDeclaredPointcut(), imapa.getPointcut()); + assertThat(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue(); + assertThat(imapa.getPointcut()).isNotSameAs(imapa.getDeclaredPointcut()); // Hit the method in the per clause to instantiate the aspect 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()); - assertEquals("Around advice must still apply", 2, itb.getAge()); + assertThat(itb.getAge()).as("Around advice must still apply").isEqualTo(1); + assertThat(itb.getAge()).as("Around advice must still apply").isEqualTo(2); TestBean itb2 = (TestBean) createProxy(target, getFixture().getAdvisors(aif), TestBean.class); - assertEquals(1, aif.getInstantiationCount()); - assertEquals("Around advice be independent for second instance", 0, itb2.getAge()); - assertEquals(2, aif.getInstantiationCount()); + assertThat(aif.getInstantiationCount()).isEqualTo(1); + assertThat(itb2.getAge()).as("Around advice be independent for second instance").isEqualTo(0); + assertThat(aif.getInstantiationCount()).isEqualTo(2); } @Test @@ -286,8 +282,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests { new NamedPointcutAspectFromLibraryWithBinding(), "someBean")), ITestBean.class); itb.setAge(10); - assertEquals("Around advice must apply", 20, itb.getAge()); - assertEquals(20,target.getAge()); + assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(20); + assertThat(target.getAge()).isEqualTo(20); } private void testNamedPointcuts(Object aspectInstance) { @@ -297,8 +293,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests { ITestBean itb = (ITestBean) createProxy(target, getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspectInstance, "someBean")), ITestBean.class); - assertEquals("Around advice must apply", -1, itb.getAge()); - assertEquals(realAge, target.getAge()); + assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(-1); + assertThat(target.getAge()).isEqualTo(realAge); } @Test @@ -309,8 +305,8 @@ public abstract class AbstractAspectJAdvisorFactoryTests { new SingletonMetadataAwareAspectInstanceFactory(new BindingAspectWithSingleArg(), "someBean")), ITestBean.class); itb.setAge(10); - assertEquals("Around advice must apply", 20, itb.getAge()); - assertEquals(20,target.getAge()); + assertThat(itb.getAge()).as("Around advice must apply").isEqualTo(20); + assertThat(target.getAge()).isEqualTo(20); } @Test @@ -327,7 +323,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests { String d = "d"; StringBuffer e = new StringBuffer("stringbuf"); 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 public void testIntroductionOnTargetNotImplementingInterface() { NotLockable notLockableTarget = new NotLockable(); - assertFalse(notLockableTarget instanceof Lockable); + assertThat(notLockableTarget instanceof Lockable).isFalse(); NotLockable notLockable1 = (NotLockable) createProxy(notLockableTarget, getFixture().getAdvisors( new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")), NotLockable.class); - assertTrue(notLockable1 instanceof Lockable); + assertThat(notLockable1 instanceof Lockable).isTrue(); Lockable lockable = (Lockable) notLockable1; - assertFalse(lockable.locked()); + assertThat(lockable.locked()).isFalse(); lockable.lock(); - assertTrue(lockable.locked()); + assertThat(lockable.locked()).isTrue(); NotLockable notLockable2Target = new NotLockable(); NotLockable notLockable2 = (NotLockable) createProxy(notLockable2Target, getFixture().getAdvisors( new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")), NotLockable.class); - assertTrue(notLockable2 instanceof Lockable); + assertThat(notLockable2 instanceof Lockable).isTrue(); Lockable lockable2 = (Lockable) notLockable2; - assertFalse(lockable2.locked()); + assertThat(lockable2.locked()).isFalse(); notLockable2.setIntValue(1); lockable2.lock(); assertThatIllegalStateException().isThrownBy(() -> notLockable2.setIntValue(32)); - assertTrue(lockable2.locked()); + assertThat(lockable2.locked()).isTrue(); } @Test public void testIntroductionAdvisorExcludedFromTargetImplementingInterface() { - assertTrue(AopUtils.findAdvisorsThatCanApply( - getFixture().getAdvisors( - new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")), - CannotBeUnlocked.class).isEmpty()); - assertEquals(2, AopUtils.findAdvisorsThatCanApply(getFixture().getAdvisors( - new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")), NotLockable.class).size()); + assertThat(AopUtils.findAdvisorsThatCanApply( + getFixture().getAdvisors( + new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")), + CannotBeUnlocked.class).isEmpty()).isTrue(); + assertThat(AopUtils.findAdvisorsThatCanApply(getFixture().getAdvisors( + new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")), NotLockable.class).size()).isEqualTo(2); } @Test @@ -385,9 +381,9 @@ public abstract class AbstractAspectJAdvisorFactoryTests { CannotBeUnlocked.class); assertThat(proxy).isInstanceOf(Lockable.class); Lockable lockable = proxy; - assertTrue("Already locked", lockable.locked()); + assertThat(lockable.locked()).as("Already locked").isTrue(); lockable.lock(); - assertTrue("Real target ignores locking", lockable.locked()); + assertThat(lockable.locked()).as("Real target ignores locking").isTrue(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> lockable.unlock()); } @@ -401,7 +397,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests { 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 @@ -411,7 +407,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests { new SingletonMetadataAwareAspectInstanceFactory(new MakeAnnotatedTypeModifiable(), "someBean")); Object proxy = createProxy(target, advisors, AnnotatedTarget.class); System.out.println(advisors.get(1)); - assertTrue(proxy instanceof Lockable); + assertThat(proxy instanceof Lockable).isTrue(); Lockable lockable = (Lockable)proxy; lockable.locked(); } @@ -430,22 +426,22 @@ public abstract class AbstractAspectJAdvisorFactoryTests { Modifiable modifiable = (Modifiable) createProxy(target, advisors, ITestBean.class); assertThat(modifiable).isInstanceOf(Modifiable.class); Lockable lockable = (Lockable) modifiable; - assertFalse(lockable.locked()); + assertThat(lockable.locked()).isFalse(); ITestBean itb = (ITestBean) modifiable; - assertFalse(modifiable.isModified()); + assertThat(modifiable.isModified()).isFalse(); int oldAge = itb.getAge(); itb.setAge(oldAge + 1); - assertTrue(modifiable.isModified()); + assertThat(modifiable.isModified()).isTrue(); modifiable.acceptChanges(); - assertFalse(modifiable.isModified()); + assertThat(modifiable.isModified()).isFalse(); 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"); - assertTrue(modifiable.isModified()); + assertThat(modifiable.isModified()).isTrue(); lockable.lock(); - assertTrue(lockable.locked()); + assertThat(lockable.locked()).isTrue(); assertThatIllegalStateException().as("Should be locked").isThrownBy(() -> itb.setName("Else")); lockable.unlock(); @@ -458,7 +454,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests { UnsupportedOperationException expectedException = new UnsupportedOperationException(); List advisors = getFixture().getAdvisors( 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); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy( itb::getAge); @@ -472,7 +468,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests { RemoteException expectedException = new RemoteException(); List advisors = getFixture().getAdvisors( 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); assertThatExceptionOfType(UndeclaredThrowableException.class).isThrownBy( itb::getAge).withCause(expectedException); @@ -501,13 +497,13 @@ public abstract class AbstractAspectJAdvisorFactoryTests { TwoAdviceAspect twoAdviceAspect = new TwoAdviceAspect(); List advisors = getFixture().getAdvisors( 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); itb.setName(""); - assertEquals(0, itb.getAge()); + assertThat(itb.getAge()).isEqualTo(0); int newAge = 32; itb.setAge(newAge); - assertEquals(1, itb.getAge()); + assertThat(itb.getAge()).isEqualTo(1); } @Test @@ -517,15 +513,15 @@ public abstract class AbstractAspectJAdvisorFactoryTests { List advisors = getFixture().getAdvisors( new SingletonMetadataAwareAspectInstanceFactory(afterReturningAspect, "someBean")); Echo echo = (Echo) createProxy(target, advisors, Echo.class); - assertEquals(0, afterReturningAspect.successCount); - assertEquals("", echo.echo("")); - assertEquals(1, afterReturningAspect.successCount); - assertEquals(0, afterReturningAspect.failureCount); + assertThat(afterReturningAspect.successCount).isEqualTo(0); + assertThat(echo.echo("")).isEqualTo(""); + assertThat(afterReturningAspect.successCount).isEqualTo(1); + assertThat(afterReturningAspect.failureCount).isEqualTo(0); assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> echo.echo(new FileNotFoundException())); - assertEquals(1, afterReturningAspect.successCount); - assertEquals(1, afterReturningAspect.failureCount); - assertEquals(afterReturningAspect.failureCount + afterReturningAspect.successCount, afterReturningAspect.afterCount); + assertThat(afterReturningAspect.successCount).isEqualTo(1); + assertThat(afterReturningAspect.failureCount).isEqualTo(1); + assertThat(afterReturningAspect.afterCount).isEqualTo(afterReturningAspect.failureCount + afterReturningAspect.successCount); } @Test @@ -651,6 +647,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests { @Aspect public static class NamedPointcutAspectWithFQN { + @SuppressWarnings("unused") private ITestBean fieldThatShouldBeIgnoredBySpringAtAspectJProcessing = new TestBean(); @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") 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; } } @@ -1053,6 +1050,7 @@ class PerThisAspect { public int count; // Just to check that this doesn't cause problems with introduction processing + @SuppressWarnings("unused") private ITestBean fieldThatShouldBeIgnoredBySpringAtAspectJProcessing = new TestBean(); @Around("execution(int *.getAge())") diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java index 5add0dfed2f..d7d0c5504a7 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java @@ -30,9 +30,9 @@ import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer; import org.springframework.tests.sample.beans.ITestBean; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; /** * @author Adrian Colyer @@ -71,8 +71,8 @@ public class ArgumentBindingTests { Method methodUsedForParameterTypeDiscovery = getClass().getMethod("methodWithOneParam", String.class); String[] pnames = discoverer.getParameterNames(methodUsedForParameterTypeDiscovery); - assertEquals("one parameter name", 1, pnames.length); - assertEquals("formal", pnames[0]); + assertThat(pnames.length).as("one parameter name").isEqualTo(1); + assertThat(pnames[0]).isEqualTo("formal"); } diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java index 6e5c41e8dd2..40d0e7adf0a 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java @@ -25,11 +25,8 @@ import org.springframework.aop.aspectj.AspectJExpressionPointcutTests; import org.springframework.aop.framework.AopConfigException; 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.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -50,8 +47,8 @@ public class AspectJPointcutAdvisorTests { new SingletonMetadataAwareAspectInstanceFactory(new AbstractAspectJAdvisorFactoryTests.ExceptionAspect(null), "someBean"), 1, "someBean"); - assertSame(Pointcut.TRUE, ajpa.getAspectMetadata().getPerClausePointcut()); - assertFalse(ajpa.isPerInstance()); + assertThat(ajpa.getAspectMetadata().getPerClausePointcut()).isSameAs(Pointcut.TRUE); + assertThat(ajpa.isPerInstance()).isFalse(); } @Test @@ -64,16 +61,17 @@ public class AspectJPointcutAdvisorTests { new SingletonMetadataAwareAspectInstanceFactory(new PerTargetAspect(), "someBean"), 1, "someBean"); - assertNotSame(Pointcut.TRUE, ajpa.getAspectMetadata().getPerClausePointcut()); - assertTrue(ajpa.getAspectMetadata().getPerClausePointcut() instanceof AspectJExpressionPointcut); - assertTrue(ajpa.isPerInstance()); + assertThat(ajpa.getAspectMetadata().getPerClausePointcut()).isNotSameAs(Pointcut.TRUE); + boolean condition = ajpa.getAspectMetadata().getPerClausePointcut() instanceof AspectJExpressionPointcut; + assertThat(condition).isTrue(); + assertThat(ajpa.isPerInstance()).isTrue(); - assertTrue(ajpa.getAspectMetadata().getPerClausePointcut().getClassFilter().matches(TestBean.class)); - assertFalse(ajpa.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches( - TestBean.class.getMethod("getAge"), TestBean.class)); + assertThat(ajpa.getAspectMetadata().getPerClausePointcut().getClassFilter().matches(TestBean.class)).isTrue(); + assertThat(ajpa.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches( + TestBean.class.getMethod("getAge"), TestBean.class)).isFalse(); - assertTrue(ajpa.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches( - TestBean.class.getMethod("getSpouse"), TestBean.class)); + assertThat(ajpa.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches( + TestBean.class.getMethod("getSpouse"), TestBean.class)).isTrue(); } @Test diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectMetadataTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectMetadataTests.java index 2350c54251a..b12c0972b24 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectMetadataTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectMetadataTests.java @@ -23,12 +23,8 @@ import test.aop.PerTargetAspect; import org.springframework.aop.Pointcut; 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.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 @@ -46,24 +42,24 @@ public class AspectMetadataTests { @Test public void testSingletonAspect() { AspectMetadata am = new AspectMetadata(ExceptionAspect.class,"someBean"); - assertFalse(am.isPerThisOrPerTarget()); - assertSame(Pointcut.TRUE, am.getPerClausePointcut()); - assertEquals(PerClauseKind.SINGLETON, am.getAjType().getPerClause().getKind()); + assertThat(am.isPerThisOrPerTarget()).isFalse(); + assertThat(am.getPerClausePointcut()).isSameAs(Pointcut.TRUE); + assertThat(am.getAjType().getPerClause().getKind()).isEqualTo(PerClauseKind.SINGLETON); } @Test public void testPerTargetAspect() { AspectMetadata am = new AspectMetadata(PerTargetAspect.class,"someBean"); - assertTrue(am.isPerThisOrPerTarget()); - assertNotSame(Pointcut.TRUE, am.getPerClausePointcut()); - assertEquals(PerClauseKind.PERTARGET, am.getAjType().getPerClause().getKind()); + assertThat(am.isPerThisOrPerTarget()).isTrue(); + assertThat(am.getPerClausePointcut()).isNotSameAs(Pointcut.TRUE); + assertThat(am.getAjType().getPerClause().getKind()).isEqualTo(PerClauseKind.PERTARGET); } @Test public void testPerThisAspect() { AspectMetadata am = new AspectMetadata(PerThisAspect.class,"someBean"); - assertTrue(am.isPerThisOrPerTarget()); - assertNotSame(Pointcut.TRUE, am.getPerClausePointcut()); - assertEquals(PerClauseKind.PERTHIS, am.getAjType().getPerClause().getKind()); + assertThat(am.isPerThisOrPerTarget()).isTrue(); + assertThat(am.getPerClausePointcut()).isNotSameAs(Pointcut.TRUE); + assertThat(am.getAjType().getPerClause().getKind()).isEqualTo(PerClauseKind.PERTHIS); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java index c9e1a1e15c6..6779fa7e846 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java @@ -28,9 +28,8 @@ import test.aop.PerThisAspect; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Rob Harrop @@ -53,7 +52,7 @@ public class AspectProxyFactoryTests { AspectJProxyFactory proxyFactory = new AspectJProxyFactory(bean); proxyFactory.addAspect(MultiplyReturnValue.class); 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 @@ -70,10 +69,10 @@ public class AspectProxyFactoryTests { ITestBean proxy1 = pf1.getProxy(); ITestBean proxy2 = pf2.getProxy(); - assertEquals(0, proxy1.getAge()); - assertEquals(1, proxy1.getAge()); - assertEquals(0, proxy2.getAge()); - assertEquals(2, proxy1.getAge()); + assertThat(proxy1.getAge()).isEqualTo(0); + assertThat(proxy1.getAge()).isEqualTo(1); + assertThat(proxy2.getAge()).isEqualTo(0); + assertThat(proxy1.getAge()).isEqualTo(2); } @Test @@ -84,18 +83,16 @@ public class AspectProxyFactoryTests { } @Test - @SuppressWarnings("unchecked") public void testSerializable() throws Exception { AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean()); proxyFactory.addAspect(LoggingAspectOnVarargs.class); 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); - assertTrue(tb.doWithVarargs(MyEnum.A, MyOtherEnum.C)); + assertThat(tb.doWithVarargs(MyEnum.A, MyOtherEnum.C)).isTrue(); } @Test - @SuppressWarnings("unchecked") public void testWithInstance() throws Exception { MultiplyReturnValue aspect = new MultiplyReturnValue(); int multiple = 3; @@ -108,10 +105,10 @@ public class AspectProxyFactoryTests { proxyFactory.addAspect(aspect); ITestBean proxy = proxyFactory.getProxy(); - assertEquals(target.getAge() * multiple, proxy.getAge()); + assertThat(proxy.getAge()).isEqualTo((target.getAge() * multiple)); ITestBean serializedProxy = (ITestBean) SerializationTestUtils.serializeAndDeserialize(proxy); - assertEquals(target.getAge() * multiple, serializedProxy.getAge()); + assertThat(serializedProxy.getAge()).isEqualTo((target.getAge() * multiple)); } @Test @@ -122,21 +119,19 @@ public class AspectProxyFactoryTests { } @Test // SPR-13328 - @SuppressWarnings("unchecked") public void testProxiedVarargsWithEnumArray() throws Exception { AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean()); proxyFactory.addAspect(LoggingAspectOnVarargs.class); ITestBean proxy = proxyFactory.getProxy(); - assertTrue(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)); + assertThat(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)).isTrue(); } @Test // SPR-13328 - @SuppressWarnings("unchecked") public void testUnproxiedVarargsWithEnumArray() throws Exception { AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean()); proxyFactory.addAspect(LoggingAspectOnSetter.class); ITestBean proxy = proxyFactory.getProxy(); - assertTrue(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)); + assertThat(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)).isTrue(); } diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJNamespaceHandlerTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJNamespaceHandlerTests.java index ac26b6d64bf..79232a8b651 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJNamespaceHandlerTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJNamespaceHandlerTests.java @@ -31,7 +31,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.factory.xml.XmlReaderContext; import org.springframework.tests.beans.CollectingReaderEventListener; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -58,49 +58,46 @@ public class AspectJNamespaceHandlerTests { @Test public void testRegisterAutoProxyCreator() throws Exception { 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); - assertEquals("Incorrect number of definitions registered", 1, registry.getBeanDefinitionCount()); + assertThat(registry.getBeanDefinitionCount()).as("Incorrect number of definitions registered").isEqualTo(1); } @Test public void testRegisterAspectJAutoProxyCreator() throws Exception { 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); - 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); - assertEquals("Incorrect APC class", - AspectJAwareAdvisorAutoProxyCreator.class.getName(), definition.getBeanClassName()); + assertThat(definition.getBeanClassName()).as("Incorrect APC class").isEqualTo(AspectJAwareAdvisorAutoProxyCreator.class.getName()); } @Test public void testRegisterAspectJAutoProxyCreatorWithExistingAutoProxyCreator() throws Exception { AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null); - assertEquals(1, registry.getBeanDefinitionCount()); + assertThat(registry.getBeanDefinitionCount()).isEqualTo(1); 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); - assertEquals("APC class not switched", - AspectJAwareAdvisorAutoProxyCreator.class.getName(), definition.getBeanClassName()); + assertThat(definition.getBeanClassName()).as("APC class not switched").isEqualTo(AspectJAwareAdvisorAutoProxyCreator.class.getName()); } @Test public void testRegisterAutoProxyCreatorWhenAspectJAutoProxyCreatorAlreadyExists() throws Exception { AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null); - assertEquals(1, registry.getBeanDefinitionCount()); + assertThat(registry.getBeanDefinitionCount()).isEqualTo(1); 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); - assertEquals("Incorrect APC class", - AspectJAwareAdvisorAutoProxyCreator.class.getName(), definition.getBeanClassName()); + assertThat(definition.getBeanClassName()).as("Incorrect APC class").isEqualTo(AspectJAwareAdvisorAutoProxyCreator.class.getName()); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparatorTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparatorTests.java index 41bde835791..72859babc6c 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparatorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparatorTests.java @@ -35,7 +35,7 @@ import org.springframework.aop.aspectj.AspectJPointcutAdvisor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.lang.Nullable; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Adrian Colyer @@ -69,95 +69,95 @@ public class AspectJPrecedenceComparatorTests { public void testSameAspectNoAfterAdvice() { Advisor advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_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"); 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 public void testSameAspectAfterAdvice() { Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_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"); 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 public void testSameAspectOneOfEach() { Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_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 public void testSameAdvisorPrecedenceDifferentAspectNoAfterAdvice() { Advisor advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); 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"); 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 public void testSameAdvisorPrecedenceDifferentAspectAfterAdvice() { Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); 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"); 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 public void testHigherAdvisorPrecedenceNoAfterAdvice() { Advisor advisor1 = createSpringAOPBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER); 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"); 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 public void testHigherAdvisorPrecedenceAfterAdvice() { Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); 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"); 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 public void testLowerAdvisorPrecedenceNoAfterAdvice() { Advisor advisor1 = createAspectJBeforeAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); 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"); 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 public void testLowerAdvisorPrecedenceAfterAdvice() { Advisor advisor1 = createAspectJAfterAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); 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); 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); } diff --git a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests.java b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests.java index 1064923d9e2..9e1639f7e2c 100644 --- a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests.java @@ -32,9 +32,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; import org.springframework.tests.beans.CollectingReaderEventListener; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -69,14 +67,15 @@ public class AopNamespaceHandlerEventTests { public void testPointcutEvents() { this.reader.loadBeanDefinitions(POINTCUT_EVENTS_CONTEXT); ComponentDefinition[] componentDefinitions = this.eventListener.getComponentDefinitions(); - assertEquals("Incorrect number of events fired", 1, componentDefinitions.length); - assertTrue("No holder with nested components", componentDefinitions[0] instanceof CompositeComponentDefinition); + assertThat(componentDefinitions.length).as("Incorrect number of events fired").isEqualTo(1); + boolean condition = componentDefinitions[0] instanceof CompositeComponentDefinition; + assertThat(condition).as("No holder with nested components").isTrue(); CompositeComponentDefinition compositeDef = (CompositeComponentDefinition) componentDefinitions[0]; - assertEquals("aop:config", compositeDef.getName()); + assertThat(compositeDef.getName()).isEqualTo("aop:config"); 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; for (ComponentDefinition componentDefinition : nestedComponentDefs) { if (componentDefinition instanceof PointcutComponentDefinition) { @@ -84,22 +83,23 @@ public class AopNamespaceHandlerEventTests { break; } } - assertNotNull("PointcutComponentDefinition not found", pcd); - assertEquals("Incorrect number of BeanDefinitions", 1, pcd.getBeanDefinitions().length); + assertThat(pcd).as("PointcutComponentDefinition not found").isNotNull(); + assertThat(pcd.getBeanDefinitions().length).as("Incorrect number of BeanDefinitions").isEqualTo(1); } @Test public void testAdvisorEventsWithPointcutRef() { this.reader.loadBeanDefinitions(POINTCUT_REF_CONTEXT); 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]; - assertEquals("aop:config", compositeDef.getName()); + assertThat(compositeDef.getName()).isEqualTo("aop:config"); 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; for (int i = 0; i < nestedComponentDefs.length; i++) { ComponentDefinition componentDefinition = nestedComponentDefs[i]; @@ -108,27 +108,29 @@ public class AopNamespaceHandlerEventTests { break; } } - assertNotNull("AdvisorComponentDefinition not found", acd); - assertEquals(1, acd.getBeanDefinitions().length); - assertEquals(2, acd.getBeanReferences().length); + assertThat(acd).as("AdvisorComponentDefinition not found").isNotNull(); + assertThat(acd.getBeanDefinitions().length).isEqualTo(1); + 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]; - assertEquals("countingAdvice", adviceDef.getBeanName()); + assertThat(adviceDef.getBeanName()).isEqualTo("countingAdvice"); } @Test public void testAdvisorEventsWithDirectPointcut() { this.reader.loadBeanDefinitions(DIRECT_POINTCUT_EVENTS_CONTEXT); 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]; - assertEquals("aop:config", compositeDef.getName()); + assertThat(compositeDef.getName()).isEqualTo("aop:config"); 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; for (int i = 0; i < nestedComponentDefs.length; i++) { ComponentDefinition componentDefinition = nestedComponentDefs[i]; @@ -137,27 +139,29 @@ public class AopNamespaceHandlerEventTests { break; } } - assertNotNull("AdvisorComponentDefinition not found", acd); - assertEquals(2, acd.getBeanDefinitions().length); - assertEquals(1, acd.getBeanReferences().length); + assertThat(acd).as("AdvisorComponentDefinition not found").isNotNull(); + assertThat(acd.getBeanDefinitions().length).isEqualTo(2); + 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]; - assertEquals("countingAdvice", adviceDef.getBeanName()); + assertThat(adviceDef.getBeanName()).isEqualTo("countingAdvice"); } @Test public void testAspectEvent() { this.reader.loadBeanDefinitions(CONTEXT); 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]; - assertEquals("aop:config", compositeDef.getName()); + assertThat(compositeDef.getName()).isEqualTo("aop:config"); 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; for (ComponentDefinition componentDefinition : nestedComponentDefs) { 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(); - assertEquals(5, beanDefinitions.length); + assertThat(beanDefinitions.length).isEqualTo(5); BeanReference[] beanReferences = acd.getBeanReferences(); - assertEquals(6, beanReferences.length); + assertThat(beanReferences.length).isEqualTo(6); Set expectedReferences = new HashSet<>(); expectedReferences.add("pc"); @@ -178,17 +182,19 @@ public class AopNamespaceHandlerEventTests { for (BeanReference beanReference : beanReferences) { 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++) { - assertTrue(componentDefinitions[i] instanceof BeanComponentDefinition); + boolean condition1 = componentDefinitions[i] instanceof BeanComponentDefinition; + assertThat(condition1).isTrue(); } ComponentDefinition[] nestedComponentDefs2 = acd.getNestedComponents(); - assertEquals("Inner PointcutComponentDefinition not found", 1, nestedComponentDefs2.length); - assertTrue(nestedComponentDefs2[0] instanceof PointcutComponentDefinition); + assertThat(nestedComponentDefs2.length).as("Inner PointcutComponentDefinition not found").isEqualTo(1); + boolean condition1 = nestedComponentDefs2[0] instanceof PointcutComponentDefinition; + assertThat(condition1).isTrue(); 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); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/config/TopLevelAopTagTests.java b/spring-aop/src/test/java/org/springframework/aop/config/TopLevelAopTagTests.java index d472d1c8433..bbcdbe93680 100644 --- a/spring-aop/src/test/java/org/springframework/aop/config/TopLevelAopTagTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/config/TopLevelAopTagTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; 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; /** @@ -38,7 +38,7 @@ public class TopLevelAopTagTests { new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions( qualifiedResource(TopLevelAopTagTests.class, "context.xml")); - assertTrue(beanFactory.containsBeanDefinition("testPointcut")); + assertThat(beanFactory.containsBeanDefinition("testPointcut")).isTrue(); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java index 47584a2d718..eaa4e44e6c8 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java @@ -26,10 +26,8 @@ import org.springframework.aop.SpringProxy; import org.springframework.tests.sample.beans.ITestBean; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -41,10 +39,10 @@ public class AopProxyUtilsTests { public void testCompleteProxiedInterfacesWorksWithNull() { AdvisedSupport as = new AdvisedSupport(); Class[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as); - assertEquals(2, completedInterfaces.length); + assertThat(completedInterfaces.length).isEqualTo(2); List ifaces = Arrays.asList(completedInterfaces); - assertTrue(ifaces.contains(Advised.class)); - assertTrue(ifaces.contains(SpringProxy.class)); + assertThat(ifaces.contains(Advised.class)).isTrue(); + assertThat(ifaces.contains(SpringProxy.class)).isTrue(); } @Test @@ -52,7 +50,7 @@ public class AopProxyUtilsTests { AdvisedSupport as = new AdvisedSupport(); as.setOpaque(true); Class[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as); - assertEquals(1, completedInterfaces.length); + assertThat(completedInterfaces.length).isEqualTo(1); } @Test @@ -61,13 +59,13 @@ public class AopProxyUtilsTests { as.addInterface(ITestBean.class); as.addInterface(Comparable.class); Class[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as); - assertEquals(4, completedInterfaces.length); + assertThat(completedInterfaces.length).isEqualTo(4); // Can't assume ordering for others, so use a list List l = Arrays.asList(completedInterfaces); - assertTrue(l.contains(Advised.class)); - assertTrue(l.contains(ITestBean.class)); - assertTrue(l.contains(Comparable.class)); + assertThat(l.contains(Advised.class)).isTrue(); + assertThat(l.contains(ITestBean.class)).isTrue(); + assertThat(l.contains(Comparable.class)).isTrue(); } @Test @@ -77,13 +75,13 @@ public class AopProxyUtilsTests { as.addInterface(Comparable.class); as.addInterface(Advised.class); Class[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as); - assertEquals(4, completedInterfaces.length); + assertThat(completedInterfaces.length).isEqualTo(4); // Can't assume ordering for others, so use a list List l = Arrays.asList(completedInterfaces); - assertTrue(l.contains(Advised.class)); - assertTrue(l.contains(ITestBean.class)); - assertTrue(l.contains(Comparable.class)); + assertThat(l.contains(Advised.class)).isTrue(); + assertThat(l.contains(ITestBean.class)).isTrue(); + assertThat(l.contains(Comparable.class)).isTrue(); } @Test @@ -93,13 +91,13 @@ public class AopProxyUtilsTests { as.addInterface(ITestBean.class); as.addInterface(Comparable.class); Class[] completedInterfaces = AopProxyUtils.completeProxiedInterfaces(as); - assertEquals(3, completedInterfaces.length); + assertThat(completedInterfaces.length).isEqualTo(3); // Can't assume ordering for others, so use a list List l = Arrays.asList(completedInterfaces); - assertFalse(l.contains(Advised.class)); - assertTrue(l.contains(ITestBean.class)); - assertTrue(l.contains(Comparable.class)); + assertThat(l.contains(Advised.class)).isFalse(); + assertThat(l.contains(ITestBean.class)).isTrue(); + assertThat(l.contains(Comparable.class)).isTrue(); } @Test @@ -109,8 +107,8 @@ public class AopProxyUtilsTests { pf.addInterface(ITestBean.class); Object proxy = pf.getProxy(); Class[] userInterfaces = AopProxyUtils.proxiedUserInterfaces(proxy); - assertEquals(1, userInterfaces.length); - assertEquals(ITestBean.class, userInterfaces[0]); + assertThat(userInterfaces.length).isEqualTo(1); + assertThat(userInterfaces[0]).isEqualTo(ITestBean.class); } @Test @@ -121,9 +119,9 @@ public class AopProxyUtilsTests { pf.addInterface(Comparable.class); Object proxy = pf.getProxy(); Class[] userInterfaces = AopProxyUtils.proxiedUserInterfaces(proxy); - assertEquals(2, userInterfaces.length); - assertEquals(ITestBean.class, userInterfaces[0]); - assertEquals(Comparable.class, userInterfaces[1]); + assertThat(userInterfaces.length).isEqualTo(2); + assertThat(userInterfaces[0]).isEqualTo(ITestBean.class); + assertThat(userInterfaces[1]).isEqualTo(Comparable.class); } @Test diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/MethodInvocationTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/MethodInvocationTests.java index a3f9644fd4f..f78d9f9e912 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/MethodInvocationTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/MethodInvocationTests.java @@ -26,7 +26,7 @@ import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -51,7 +51,7 @@ public class MethodInvocationTests { m, null, null, is // list ); Object rv = invocation.proceed(); - assertTrue("correct response", rv == returnValue); + assertThat(rv == returnValue).as("correct response").isTrue(); } /** diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java index 3a29b163370..83406650890 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java @@ -24,7 +24,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; 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; /** @@ -47,8 +47,8 @@ public class PrototypeTargetTests { tb.doSomething(); } TestInterceptor interceptor = (TestInterceptor) bf.getBean("testInterceptor"); - assertEquals(10, TestBeanImpl.constructionCount); - assertEquals(10, interceptor.invocationCount); + assertThat(TestBeanImpl.constructionCount).isEqualTo(10); + assertThat(interceptor.invocationCount).isEqualTo(10); } @Test @@ -61,8 +61,8 @@ public class PrototypeTargetTests { tb.doSomething(); } TestInterceptor interceptor = (TestInterceptor) bf.getBean("testInterceptor"); - assertEquals(1, TestBeanImpl.constructionCount); - assertEquals(10, interceptor.invocationCount); + assertThat(TestBeanImpl.constructionCount).isEqualTo(1); + assertThat(interceptor.invocationCount).isEqualTo(10); } diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/ProxyFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/ProxyFactoryTests.java index d71c958dc50..0310a8bef1e 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/ProxyFactoryTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/ProxyFactoryTests.java @@ -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.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. @@ -70,10 +65,10 @@ public class ProxyFactoryTests { // Can use advised and ProxyFactory interchangeably advised.addAdvice(nop); pf.addAdvisor(advisor); - assertEquals(-1, pf.indexOf(new NopInterceptor())); - assertEquals(0, pf.indexOf(nop)); - assertEquals(1, pf.indexOf(advisor)); - assertEquals(-1, advised.indexOf(new DefaultPointcutAdvisor(null))); + assertThat(pf.indexOf(new NopInterceptor())).isEqualTo(-1); + assertThat(pf.indexOf(nop)).isEqualTo(0); + assertThat(pf.indexOf(advisor)).isEqualTo(1); + assertThat(advised.indexOf(new DefaultPointcutAdvisor(null))).isEqualTo(-1); } @Test @@ -87,13 +82,13 @@ public class ProxyFactoryTests { pf.addAdvisor(advisor); ITestBean proxied = (ITestBean) pf.getProxy(); proxied.setAge(5); - assertEquals(1, cba.getCalls()); - assertEquals(1, nop.getCount()); - assertTrue(pf.removeAdvisor(advisor)); - assertEquals(5, proxied.getAge()); - assertEquals(1, cba.getCalls()); - assertEquals(2, nop.getCount()); - assertFalse(pf.removeAdvisor(new DefaultPointcutAdvisor(null))); + assertThat(cba.getCalls()).isEqualTo(1); + assertThat(nop.getCount()).isEqualTo(1); + assertThat(pf.removeAdvisor(advisor)).isTrue(); + assertThat(proxied.getAge()).isEqualTo(5); + assertThat(cba.getCalls()).isEqualTo(1); + assertThat(nop.getCount()).isEqualTo(2); + assertThat(pf.removeAdvisor(new DefaultPointcutAdvisor(null))).isFalse(); } @Test @@ -109,21 +104,21 @@ public class ProxyFactoryTests { pf.addAdvice(nop2); ITestBean proxied = (ITestBean) pf.getProxy(); proxied.setAge(5); - assertEquals(1, cba.getCalls()); - assertEquals(1, nop.getCount()); - assertEquals(1, nop2.getCount()); + assertThat(cba.getCalls()).isEqualTo(1); + assertThat(nop.getCount()).isEqualTo(1); + assertThat(nop2.getCount()).isEqualTo(1); // Removes counting before advisor pf.removeAdvisor(1); - assertEquals(5, proxied.getAge()); - assertEquals(1, cba.getCalls()); - assertEquals(2, nop.getCount()); - assertEquals(2, nop2.getCount()); + assertThat(proxied.getAge()).isEqualTo(5); + assertThat(cba.getCalls()).isEqualTo(1); + assertThat(nop.getCount()).isEqualTo(2); + assertThat(nop2.getCount()).isEqualTo(2); // Removes Nop1 pf.removeAdvisor(0); - assertEquals(5, proxied.getAge()); - assertEquals(1, cba.getCalls()); - assertEquals(2, nop.getCount()); - assertEquals(3, nop2.getCount()); + assertThat(proxied.getAge()).isEqualTo(5); + assertThat(cba.getCalls()).isEqualTo(1); + assertThat(nop.getCount()).isEqualTo(2); + assertThat(nop2.getCount()).isEqualTo(3); // Check out of bounds try { @@ -140,8 +135,8 @@ public class ProxyFactoryTests { // Ok } - assertEquals(5, proxied.getAge()); - assertEquals(4, nop2.getCount()); + assertThat(proxied.getAge()).isEqualTo(5); + assertThat(nop2.getCount()).isEqualTo(4); } @Test @@ -160,17 +155,17 @@ public class ProxyFactoryTests { // Replace etc methods on advised should be same as on ProxyFactory Advised advised = (Advised) proxied; proxied.setAge(5); - assertEquals(1, cba1.getCalls()); - assertEquals(0, cba2.getCalls()); - assertEquals(1, nop.getCount()); - assertFalse(advised.replaceAdvisor(new DefaultPointcutAdvisor(new NopInterceptor()), advisor2)); - assertTrue(advised.replaceAdvisor(advisor1, advisor2)); - assertEquals(advisor2, pf.getAdvisors()[0]); - assertEquals(5, proxied.getAge()); - assertEquals(1, cba1.getCalls()); - assertEquals(2, nop.getCount()); - assertEquals(1, cba2.getCalls()); - assertFalse(pf.replaceAdvisor(new DefaultPointcutAdvisor(null), advisor1)); + assertThat(cba1.getCalls()).isEqualTo(1); + assertThat(cba2.getCalls()).isEqualTo(0); + assertThat(nop.getCount()).isEqualTo(1); + assertThat(advised.replaceAdvisor(new DefaultPointcutAdvisor(new NopInterceptor()), advisor2)).isFalse(); + assertThat(advised.replaceAdvisor(advisor1, advisor2)).isTrue(); + assertThat(pf.getAdvisors()[0]).isEqualTo(advisor2); + assertThat(proxied.getAge()).isEqualTo(5); + assertThat(cba1.getCalls()).isEqualTo(1); + assertThat(nop.getCount()).isEqualTo(2); + assertThat(cba2.getCalls()).isEqualTo(1); + assertThat(pf.replaceAdvisor(new DefaultPointcutAdvisor(null), advisor1)).isFalse(); } @Test @@ -201,11 +196,11 @@ public class ProxyFactoryTests { TestBeanSubclass raw = new TestBeanSubclass(); ProxyFactory factory = new ProxyFactory(raw); //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(); assertThat(tb).as("Picked up secondary interface").isInstanceOf(IOther.class); raw.setAge(25); - assertTrue(tb.getAge() == raw.getAge()); + assertThat(tb.getAge() == raw.getAge()).isTrue(); long t = 555555L; TimestampIntroductionInterceptor ti = new TimestampIntroductionInterceptor(t); @@ -215,10 +210,10 @@ public class ProxyFactoryTests { factory.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class)); 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(); - assertTrue(ts.getTimeStamp() == t); + assertThat(ts.getTimeStamp() == t).isTrue(); // Shouldn't fail; ((IOther) ts).absquatulate(); } @@ -237,14 +232,14 @@ public class ProxyFactoryTests { ProxyFactory factory = new ProxyFactory(new TestBean()); factory.addAdvice(0, di); assertThat(factory.getProxy()).isInstanceOf(ITestBean.class); - assertTrue(factory.adviceIncluded(di)); - assertTrue(!factory.adviceIncluded(diUnused)); - assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 1); - assertTrue(factory.countAdvicesOfType(MyInterceptor.class) == 0); + assertThat(factory.adviceIncluded(di)).isTrue(); + assertThat(!factory.adviceIncluded(diUnused)).isTrue(); + assertThat(factory.countAdvicesOfType(NopInterceptor.class) == 1).isTrue(); + assertThat(factory.countAdvicesOfType(MyInterceptor.class) == 0).isTrue(); factory.addAdvice(0, diUnused); - assertTrue(factory.adviceIncluded(diUnused)); - assertTrue(factory.countAdvicesOfType(NopInterceptor.class) == 2); + assertThat(factory.adviceIncluded(diUnused)).isTrue(); + assertThat(factory.countAdvicesOfType(NopInterceptor.class) == 2).isTrue(); } /** @@ -254,8 +249,7 @@ public class ProxyFactoryTests { public void testCanAddAndRemoveAspectInterfacesOnSingleton() { ProxyFactory config = new ProxyFactory(new TestBean()); - assertFalse("Shouldn't implement TimeStamped before manipulation", - config.getProxy() instanceof TimeStamped); + assertThat(config.getProxy() instanceof TimeStamped).as("Shouldn't implement TimeStamped before manipulation").isFalse(); long time = 666L; TimestampIntroductionInterceptor ti = new TimestampIntroductionInterceptor(); @@ -265,37 +259,36 @@ public class ProxyFactoryTests { int oldCount = config.getAdvisors().length; 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(); - assertTrue(ts.getTimeStamp() == time); + assertThat(ts.getTimeStamp() == time).isTrue(); // Can remove config.removeAdvice(ti); - assertTrue(config.getAdvisors().length == oldCount); + assertThat(config.getAdvisors().length == oldCount).isTrue(); assertThatExceptionOfType(RuntimeException.class) .as("Existing object won't implement this interface any more") .isThrownBy(ts::getTimeStamp); // Existing reference will fail - assertFalse("Should no longer implement TimeStamped", - config.getProxy() instanceof TimeStamped); + assertThat(config.getProxy() instanceof TimeStamped).as("Should no longer implement TimeStamped").isFalse(); // Now check non-effect of removing interceptor that isn't there config.removeAdvice(new DebugInterceptor()); - assertTrue(config.getAdvisors().length == oldCount); + assertThat(config.getAdvisors().length == oldCount).isTrue(); ITestBean it = (ITestBean) ts; DebugInterceptor debugInterceptor = new DebugInterceptor(); config.addAdvice(0, debugInterceptor); it.getSpouse(); - assertEquals(1, debugInterceptor.getCount()); + assertThat(debugInterceptor.getCount()).isEqualTo(1); config.removeAdvice(debugInterceptor); it.getSpouse(); // not invoked again - assertTrue(debugInterceptor.getCount() == 1); + assertThat(debugInterceptor.getCount() == 1).isTrue(); } @Test @@ -303,15 +296,15 @@ public class ProxyFactoryTests { ProxyFactory pf = new ProxyFactory(); pf.setTargetClass(ITestBean.class); Object proxy = pf.getProxy(); - assertTrue("Proxy is a JDK proxy", AopUtils.isJdkDynamicProxy(proxy)); - assertTrue(proxy instanceof ITestBean); - assertEquals(ITestBean.class, AopProxyUtils.ultimateTargetClass(proxy)); + assertThat(AopUtils.isJdkDynamicProxy(proxy)).as("Proxy is a JDK proxy").isTrue(); + assertThat(proxy instanceof ITestBean).isTrue(); + assertThat(AopProxyUtils.ultimateTargetClass(proxy)).isEqualTo(ITestBean.class); ProxyFactory pf2 = new ProxyFactory(proxy); Object proxy2 = pf2.getProxy(); - assertTrue("Proxy is a JDK proxy", AopUtils.isJdkDynamicProxy(proxy2)); - assertTrue(proxy2 instanceof ITestBean); - assertEquals(ITestBean.class, AopProxyUtils.ultimateTargetClass(proxy2)); + assertThat(AopUtils.isJdkDynamicProxy(proxy2)).as("Proxy is a JDK proxy").isTrue(); + assertThat(proxy2 instanceof ITestBean).isTrue(); + assertThat(AopProxyUtils.ultimateTargetClass(proxy2)).isEqualTo(ITestBean.class); } @Test @@ -319,16 +312,16 @@ public class ProxyFactoryTests { ProxyFactory pf = new ProxyFactory(); pf.setTargetClass(TestBean.class); Object proxy = pf.getProxy(); - assertTrue("Proxy is a CGLIB proxy", AopUtils.isCglibProxy(proxy)); - assertTrue(proxy instanceof TestBean); - assertEquals(TestBean.class, AopProxyUtils.ultimateTargetClass(proxy)); + assertThat(AopUtils.isCglibProxy(proxy)).as("Proxy is a CGLIB proxy").isTrue(); + assertThat(proxy instanceof TestBean).isTrue(); + assertThat(AopProxyUtils.ultimateTargetClass(proxy)).isEqualTo(TestBean.class); ProxyFactory pf2 = new ProxyFactory(proxy); pf2.setProxyTargetClass(true); Object proxy2 = pf2.getProxy(); - assertTrue("Proxy is a CGLIB proxy", AopUtils.isCglibProxy(proxy2)); - assertTrue(proxy2 instanceof TestBean); - assertEquals(TestBean.class, AopProxyUtils.ultimateTargetClass(proxy2)); + assertThat(AopUtils.isCglibProxy(proxy2)).as("Proxy is a CGLIB proxy").isTrue(); + assertThat(proxy2 instanceof TestBean).isTrue(); + assertThat(AopProxyUtils.ultimateTargetClass(proxy2)).isEqualTo(TestBean.class); } @Test @@ -337,8 +330,8 @@ public class ProxyFactoryTests { JFrame frame = new JFrame(); ProxyFactory proxyFactory = new ProxyFactory(frame); Object proxy = proxyFactory.getProxy(); - assertTrue(proxy instanceof RootPaneContainer); - assertTrue(proxy instanceof Accessible); + assertThat(proxy instanceof RootPaneContainer).isTrue(); + assertThat(proxy instanceof Accessible).isTrue(); } @Test @@ -349,8 +342,8 @@ public class ProxyFactoryTests { list.add(proxy1); list.add(proxy2); AnnotationAwareOrderComparator.sort(list); - assertSame(proxy2, list.get(0)); - assertSame(proxy1, list.get(1)); + assertThat(list.get(0)).isSameAs(proxy2); + assertThat(list.get(1)).isSameAs(proxy1); } @Test @@ -365,18 +358,18 @@ public class ProxyFactoryTests { list.add(proxy1); list.add(proxy2); AnnotationAwareOrderComparator.sort(list); - assertSame(proxy2, list.get(0)); - assertSame(proxy1, list.get(1)); + assertThat(list.get(0)).isSameAs(proxy2); + assertThat(list.get(1)).isSameAs(proxy1); } @Test public void testInterceptorWithoutJoinpoint() { final TestBean target = new TestBean("tb"); ITestBean proxy = ProxyFactory.getProxy(ITestBean.class, (MethodInterceptor) invocation -> { - assertNull(invocation.getThis()); + assertThat(invocation.getThis()).isNull(); return invocation.getMethod().invoke(target, invocation.getArguments()); }); - assertEquals("tb", proxy.getName()); + assertThat(proxy.getName()).isEqualTo("tb"); } diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java index 551540073c4..62eefa62563 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java @@ -28,9 +28,9 @@ import org.junit.Test; import org.springframework.aop.ThrowsAdvice; 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.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -54,22 +54,22 @@ public class ThrowsAdviceInterceptorTests { Object ret = new Object(); MethodInvocation mi = mock(MethodInvocation.class); given(mi.proceed()).willReturn(ret); - assertEquals(ret, ti.invoke(mi)); - assertEquals(0, th.getCalls()); + assertThat(ti.invoke(mi)).isEqualTo(ret); + assertThat(th.getCalls()).isEqualTo(0); } @Test public void testNoHandlerMethodForThrowable() throws Throwable { MyThrowsHandler th = new MyThrowsHandler(); ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th); - assertEquals(2, ti.getHandlerMethodCount()); + assertThat(ti.getHandlerMethodCount()).isEqualTo(2); Exception ex = new Exception(); MethodInvocation mi = mock(MethodInvocation.class); given(mi.proceed()).willThrow(ex); assertThatExceptionOfType(Exception.class).isThrownBy(() -> ti.invoke(mi)) .isSameAs(ex); - assertEquals(0, th.getCalls()); + assertThat(th.getCalls()).isEqualTo(0); } @Test @@ -84,8 +84,8 @@ public class ThrowsAdviceInterceptorTests { assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> ti.invoke(mi)) .isSameAs(ex); - assertEquals(1, th.getCalls()); - assertEquals(1, th.getCalls("ioException")); + assertThat(th.getCalls()).isEqualTo(1); + assertThat(th.getCalls("ioException")).isEqualTo(1); } @Test @@ -99,8 +99,8 @@ public class ThrowsAdviceInterceptorTests { assertThatExceptionOfType(ConnectException.class).isThrownBy(() -> ti.invoke(mi)) .isSameAs(ex); - assertEquals(1, th.getCalls()); - assertEquals(1, th.getCalls("remoteException")); + assertThat(th.getCalls()).isEqualTo(1); + assertThat(th.getCalls("remoteException")).isEqualTo(1); } @Test @@ -124,8 +124,8 @@ public class ThrowsAdviceInterceptorTests { assertThatExceptionOfType(Throwable.class).isThrownBy(() -> ti.invoke(mi)) .isSameAs(t); - assertEquals(1, th.getCalls()); - assertEquals(1, th.getCalls("remoteException")); + assertThat(th.getCalls()).isEqualTo(1); + assertThat(th.getCalls("remoteException")).isEqualTo(1); } diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java index 7dae7fc7e83..c3e8d888c83 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java @@ -27,7 +27,7 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -58,7 +58,7 @@ public class ConcurrencyThrottleInterceptorTests { Advised advised = (Advised) serializedProxy; ConcurrencyThrottleInterceptor serializedCti = (ConcurrencyThrottleInterceptor) advised.getAdvisors()[0].getAdvice(); - assertEquals(cti.getConcurrencyLimit(), serializedCti.getConcurrencyLimit()); + assertThat(serializedCti.getConcurrencyLimit()).isEqualTo(cti.getConcurrencyLimit()); serializedProxy.getAge(); } diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java index 47d092db3a5..fde013a4905 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java @@ -20,8 +20,8 @@ import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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.eq; import static org.mockito.BDDMockito.given; @@ -73,7 +73,7 @@ public class DebugInterceptorTests { } 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); } diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeBeanNameAdvisorsTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeBeanNameAdvisorsTests.java index 27cac8781cd..721c7b27dd3 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeBeanNameAdvisorsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeBeanNameAdvisorsTests.java @@ -23,9 +23,7 @@ import org.springframework.beans.factory.NamedBean; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -42,7 +40,7 @@ public class ExposeBeanNameAdvisorsTests { @Override public int getAge() { - assertEquals(beanName, ExposeBeanNameAdvisors.getBeanName()); + assertThat(ExposeBeanNameAdvisors.getBeanName()).isEqualTo(beanName); return super.getAge(); } } @@ -56,7 +54,8 @@ public class ExposeBeanNameAdvisorsTests { pf.addAdvisor(ExposeBeanNameAdvisors.createAdvisorWithoutIntroduction(beanName)); ITestBean proxy = (ITestBean) pf.getProxy(); - assertFalse("No introduction", proxy instanceof NamedBean); + boolean condition = proxy instanceof NamedBean; + assertThat(condition).as("No introduction").isFalse(); // Requires binding proxy.getAge(); } @@ -70,12 +69,13 @@ public class ExposeBeanNameAdvisorsTests { pf.addAdvisor(ExposeBeanNameAdvisors.createAdvisorIntroducingNamedBean(beanName)); 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 proxy.getAge(); NamedBean nb = (NamedBean) proxy; - assertEquals("Name returned correctly", beanName, nb.getBeanName()); + assertThat(nb.getBeanName()).as("Name returned correctly").isEqualTo(beanName); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java index e42076a59a8..f188ef1a475 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java @@ -24,8 +24,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -45,7 +44,7 @@ public class ExposeInvocationInterceptorTests { String name = "tony"; tb.setName(name); // Fires context checks - assertEquals(name, tb.getName()); + assertThat(tb.getName()).isEqualTo(name); } } @@ -75,8 +74,7 @@ class InvocationCheckExposedInvocationTestBean extends ExposedInvocationTestBean @Override protected void assertions(MethodInvocation invocation) { - assertTrue(invocation.getThis() == this); - assertTrue("Invocation should be on ITestBean: " + invocation.getMethod(), - ITestBean.class.isAssignableFrom(invocation.getMethod().getDeclaringClass())); + assertThat(invocation.getThis() == this).isTrue(); + assertThat(ITestBean.class.isAssignableFrom(invocation.getMethod().getDeclaringClass())).as("Invocation should be on ITestBean: " + invocation.getMethod()).isTrue(); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/JamonPerformanceMonitorInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/JamonPerformanceMonitorInterceptorTests.java index dfafaae31b3..8d52931442b 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/JamonPerformanceMonitorInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/JamonPerformanceMonitorInterceptorTests.java @@ -23,9 +23,8 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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.Mockito.mock; @@ -59,9 +58,8 @@ public class JamonPerformanceMonitorInterceptorTests { interceptor.invokeUnderTrace(mi, log); - assertTrue("jamon must track the method being invoked", MonitorFactory.getNumRows() > 0); - assertTrue("The jamon report must contain the toString method that was invoked", - MonitorFactory.getReport().contains("toString")); + assertThat(MonitorFactory.getNumRows() > 0).as("jamon must track the method being invoked").isTrue(); + assertThat(MonitorFactory.getReport().contains("toString")).as("The jamon report must contain the toString method that was invoked").isTrue(); } @Test @@ -72,14 +70,10 @@ public class JamonPerformanceMonitorInterceptorTests { assertThatIllegalArgumentException().isThrownBy(() -> interceptor.invokeUnderTrace(mi, log)); - assertEquals("Monitors must exist for the method invocation and 2 exceptions", - 3, MonitorFactory.getNumRows()); - assertTrue("The jamon report must contain the toString method that was invoked", - MonitorFactory.getReport().contains("toString")); - 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")); + assertThat(MonitorFactory.getNumRows()).as("Monitors must exist for the method invocation and 2 exceptions").isEqualTo(3); + assertThat(MonitorFactory.getReport().contains("toString")).as("The jamon report must contain the toString method that was invoked").isTrue(); + assertThat(MonitorFactory.getReport().contains(MonitorFactory.EXCEPTIONS_LABEL)).as("The jamon report must contain the generic exception: " + MonitorFactory.EXCEPTIONS_LABEL).isTrue(); + assertThat(MonitorFactory.getReport().contains("IllegalArgumentException")).as("The jamon report must contain the specific exception: IllegalArgumentException'").isTrue(); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java index c406ab89800..0f1e4b4b347 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java @@ -20,8 +20,8 @@ import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -38,14 +38,14 @@ public class PerformanceMonitorInterceptorTests { public void testSuffixAndPrefixAssignment() { PerformanceMonitorInterceptor interceptor = new PerformanceMonitorInterceptor(); - assertNotNull(interceptor.getPrefix()); - assertNotNull(interceptor.getSuffix()); + assertThat(interceptor.getPrefix()).isNotNull(); + assertThat(interceptor.getSuffix()).isNotNull(); interceptor.setPrefix(null); interceptor.setSuffix(null); - assertNotNull(interceptor.getPrefix()); - assertNotNull(interceptor.getSuffix()); + assertThat(interceptor.getPrefix()).isNotNull(); + assertThat(interceptor.getSuffix()).isNotNull(); } @Test diff --git a/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyAutowireTests.java b/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyAutowireTests.java index e0a5ca04bca..cf0992a22b6 100644 --- a/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyAutowireTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyAutowireTests.java @@ -23,9 +23,7 @@ import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -41,12 +39,12 @@ public class ScopedProxyAutowireTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions( qualifiedResource(ScopedProxyAutowireTests.class, "scopedAutowireFalse.xml")); - assertTrue(Arrays.asList(bf.getBeanNamesForType(TestBean.class, false, false)).contains("scoped")); - assertTrue(Arrays.asList(bf.getBeanNamesForType(TestBean.class, true, false)).contains("scoped")); - assertFalse(bf.containsSingleton("scoped")); + assertThat(Arrays.asList(bf.getBeanNamesForType(TestBean.class, false, false)).contains("scoped")).isTrue(); + assertThat(Arrays.asList(bf.getBeanNamesForType(TestBean.class, true, false)).contains("scoped")).isTrue(); + assertThat(bf.containsSingleton("scoped")).isFalse(); TestBean autowired = (TestBean) bf.getBean("autowired"); TestBean unscoped = (TestBean) bf.getBean("unscoped"); - assertSame(unscoped, autowired.getChild()); + assertThat(autowired.getChild()).isSameAs(unscoped); } @Test @@ -55,12 +53,12 @@ public class ScopedProxyAutowireTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions( qualifiedResource(ScopedProxyAutowireTests.class, "scopedAutowireTrue.xml")); - assertTrue(Arrays.asList(bf.getBeanNamesForType(TestBean.class, true, false)).contains("scoped")); - assertTrue(Arrays.asList(bf.getBeanNamesForType(TestBean.class, false, false)).contains("scoped")); - assertFalse(bf.containsSingleton("scoped")); + assertThat(Arrays.asList(bf.getBeanNamesForType(TestBean.class, true, false)).contains("scoped")).isTrue(); + assertThat(Arrays.asList(bf.getBeanNamesForType(TestBean.class, false, false)).contains("scoped")).isTrue(); + assertThat(bf.containsSingleton("scoped")).isFalse(); TestBean autowired = (TestBean) bf.getBean("autowired"); TestBean scoped = (TestBean) bf.getBean("scoped"); - assertSame(scoped, autowired.getChild()); + assertThat(autowired.getChild()).isSameAs(scoped); } diff --git a/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java index deab0237544..7b3e8b9455f 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java @@ -24,9 +24,7 @@ import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -56,9 +54,9 @@ public abstract class AbstractRegexpMethodPointcutTests { } protected void noPatternSuppliedTests(AbstractRegexpMethodPointcut rpc) throws Exception { - assertFalse(rpc.matches(Object.class.getMethod("hashCode"), String.class)); - assertFalse(rpc.matches(Object.class.getMethod("wait"), Object.class)); - assertEquals(0, rpc.getPatterns().length); + assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isFalse(); + assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse(); + assertThat(rpc.getPatterns().length).isEqualTo(0); } @Test @@ -71,46 +69,46 @@ public abstract class AbstractRegexpMethodPointcutTests { protected void exactMatchTests(AbstractRegexpMethodPointcut rpc) throws Exception { // assumes rpc.setPattern("java.lang.Object.hashCode"); - assertTrue(rpc.matches(Object.class.getMethod("hashCode"), String.class)); - assertTrue(rpc.matches(Object.class.getMethod("hashCode"), Object.class)); - assertFalse(rpc.matches(Object.class.getMethod("wait"), Object.class)); + assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue(); + assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isTrue(); + assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse(); } @Test public void testSpecificMatch() throws Exception { rpc.setPattern("java.lang.String.hashCode"); - assertTrue(rpc.matches(Object.class.getMethod("hashCode"), String.class)); - assertFalse(rpc.matches(Object.class.getMethod("hashCode"), Object.class)); + assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue(); + assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isFalse(); } @Test public void testWildcard() throws Exception { rpc.setPattern(".*Object.hashCode"); - assertTrue(rpc.matches(Object.class.getMethod("hashCode"), Object.class)); - assertFalse(rpc.matches(Object.class.getMethod("wait"), Object.class)); + assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isTrue(); + assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse(); } @Test public void testWildcardForOneClass() throws Exception { rpc.setPattern("java.lang.Object.*"); - assertTrue(rpc.matches(Object.class.getMethod("hashCode"), String.class)); - assertTrue(rpc.matches(Object.class.getMethod("wait"), String.class)); + assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue(); + assertThat(rpc.matches(Object.class.getMethod("wait"), String.class)).isTrue(); } @Test public void testMatchesObjectClass() throws Exception { 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 - assertFalse(rpc.matches(Exception.class.getMethod("getMessage"), Exception.class)); + assertThat(rpc.matches(Exception.class.getMethod("getMessage"), Exception.class)).isFalse(); } @Test public void testWithExclusion() throws Exception { this.rpc.setPattern(".*get.*"); this.rpc.setExcludedPattern(".*Age.*"); - assertTrue(this.rpc.matches(TestBean.class.getMethod("getName"), TestBean.class)); - assertFalse(this.rpc.matches(TestBean.class.getMethod("getAge"), TestBean.class)); + assertThat(this.rpc.matches(TestBean.class.getMethod("getName"), TestBean.class)).isTrue(); + assertThat(this.rpc.matches(TestBean.class.getMethod("getAge"), TestBean.class)).isFalse(); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/support/AopUtilsTests.java b/spring-aop/src/test/java/org/springframework/aop/support/AopUtilsTests.java index 77ec32c62e4..c9c40f57535 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/AopUtilsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/AopUtilsTests.java @@ -30,9 +30,7 @@ import org.springframework.tests.aop.interceptor.NopInterceptor; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -50,13 +48,13 @@ public class AopUtilsTests { } Pointcut no = new TestPointcut(); - assertFalse(AopUtils.canApply(no, Object.class)); + assertThat(AopUtils.canApply(no, Object.class)).isFalse(); } @Test public void testPointcutAlwaysApplies() { - assertTrue(AopUtils.canApply(new DefaultPointcutAdvisor(new NopInterceptor()), Object.class)); - assertTrue(AopUtils.canApply(new DefaultPointcutAdvisor(new NopInterceptor()), TestBean.class)); + assertThat(AopUtils.canApply(new DefaultPointcutAdvisor(new NopInterceptor()), Object.class)).isTrue(); + assertThat(AopUtils.canApply(new DefaultPointcutAdvisor(new NopInterceptor()), TestBean.class)).isTrue(); } @Test @@ -71,7 +69,7 @@ public class AopUtilsTests { Pointcut pc = new TestPointcut(); // 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 public void testCanonicalFrameworkClassesStillCanonicalOnDeserialization() throws Exception { - assertSame(MethodMatcher.TRUE, SerializationTestUtils.serializeAndDeserialize(MethodMatcher.TRUE)); - assertSame(ClassFilter.TRUE, SerializationTestUtils.serializeAndDeserialize(ClassFilter.TRUE)); - assertSame(Pointcut.TRUE, SerializationTestUtils.serializeAndDeserialize(Pointcut.TRUE)); - assertSame(EmptyTargetSource.INSTANCE, SerializationTestUtils.serializeAndDeserialize(EmptyTargetSource.INSTANCE)); - assertSame(Pointcuts.SETTERS, SerializationTestUtils.serializeAndDeserialize(Pointcuts.SETTERS)); - assertSame(Pointcuts.GETTERS, SerializationTestUtils.serializeAndDeserialize(Pointcuts.GETTERS)); - assertSame(ExposeInvocationInterceptor.INSTANCE, - SerializationTestUtils.serializeAndDeserialize(ExposeInvocationInterceptor.INSTANCE)); + assertThat(SerializationTestUtils.serializeAndDeserialize(MethodMatcher.TRUE)).isSameAs(MethodMatcher.TRUE); + assertThat(SerializationTestUtils.serializeAndDeserialize(ClassFilter.TRUE)).isSameAs(ClassFilter.TRUE); + assertThat(SerializationTestUtils.serializeAndDeserialize(Pointcut.TRUE)).isSameAs(Pointcut.TRUE); + assertThat(SerializationTestUtils.serializeAndDeserialize(EmptyTargetSource.INSTANCE)).isSameAs(EmptyTargetSource.INSTANCE); + assertThat(SerializationTestUtils.serializeAndDeserialize(Pointcuts.SETTERS)).isSameAs(Pointcuts.SETTERS); + assertThat(SerializationTestUtils.serializeAndDeserialize(Pointcuts.GETTERS)).isSameAs(Pointcuts.GETTERS); + assertThat(SerializationTestUtils.serializeAndDeserialize(ExposeInvocationInterceptor.INSTANCE)).isSameAs(ExposeInvocationInterceptor.INSTANCE); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/support/ClassFiltersTests.java b/spring-aop/src/test/java/org/springframework/aop/support/ClassFiltersTests.java index 2c7e134b0d2..bbc7ce9a8e5 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/ClassFiltersTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/ClassFiltersTests.java @@ -23,8 +23,7 @@ import org.springframework.core.NestedRuntimeException; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -40,23 +39,23 @@ public class ClassFiltersTests { @Test public void testUnion() { - assertTrue(exceptionFilter.matches(RuntimeException.class)); - assertFalse(exceptionFilter.matches(TestBean.class)); - assertFalse(itbFilter.matches(Exception.class)); - assertTrue(itbFilter.matches(TestBean.class)); + assertThat(exceptionFilter.matches(RuntimeException.class)).isTrue(); + assertThat(exceptionFilter.matches(TestBean.class)).isFalse(); + assertThat(itbFilter.matches(Exception.class)).isFalse(); + assertThat(itbFilter.matches(TestBean.class)).isTrue(); ClassFilter union = ClassFilters.union(exceptionFilter, itbFilter); - assertTrue(union.matches(RuntimeException.class)); - assertTrue(union.matches(TestBean.class)); + assertThat(union.matches(RuntimeException.class)).isTrue(); + assertThat(union.matches(TestBean.class)).isTrue(); } @Test public void testIntersection() { - assertTrue(exceptionFilter.matches(RuntimeException.class)); - assertTrue(hasRootCauseFilter.matches(NestedRuntimeException.class)); + assertThat(exceptionFilter.matches(RuntimeException.class)).isTrue(); + assertThat(hasRootCauseFilter.matches(NestedRuntimeException.class)).isTrue(); ClassFilter intersection = ClassFilters.intersection(exceptionFilter, hasRootCauseFilter); - assertFalse(intersection.matches(RuntimeException.class)); - assertFalse(intersection.matches(TestBean.class)); - assertTrue(intersection.matches(NestedRuntimeException.class)); + assertThat(intersection.matches(RuntimeException.class)).isFalse(); + assertThat(intersection.matches(TestBean.class)).isFalse(); + assertThat(intersection.matches(NestedRuntimeException.class)).isTrue(); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java b/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java index 17bcf55a334..3aa9f3abe2f 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java @@ -21,7 +21,7 @@ import org.springframework.aop.framework.ProxyFactory; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ClassUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Colin Sampaleanu @@ -39,6 +39,6 @@ public class ClassUtilsTests { pf.setProxyTargetClass(true); TestBean proxy = (TestBean) pf.getProxy(); String className = ClassUtils.getShortName(proxy.getClass()); - assertEquals("Class name did not match", "TestBean", className); + assertThat(className).as("Class name did not match").isEqualTo("TestBean"); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/support/ComposablePointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/support/ComposablePointcutTests.java index 9df9df4c7f7..36dcde9a825 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/ComposablePointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/ComposablePointcutTests.java @@ -27,9 +27,7 @@ import org.springframework.core.NestedRuntimeException; import org.springframework.lang.Nullable; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -69,68 +67,68 @@ public class ComposablePointcutTests { @Test public void testMatchAll() throws NoSuchMethodException { Pointcut pc = new ComposablePointcut(); - assertTrue(pc.getClassFilter().matches(Object.class)); - assertTrue(pc.getMethodMatcher().matches(Object.class.getMethod("hashCode"), Exception.class)); + assertThat(pc.getClassFilter().matches(Object.class)).isTrue(); + assertThat(pc.getMethodMatcher().matches(Object.class.getMethod("hashCode"), Exception.class)).isTrue(); } @Test public void testFilterByClass() throws NoSuchMethodException { ComposablePointcut pc = new ComposablePointcut(); - assertTrue(pc.getClassFilter().matches(Object.class)); + assertThat(pc.getClassFilter().matches(Object.class)).isTrue(); ClassFilter cf = new RootClassFilter(Exception.class); pc.intersection(cf); - assertFalse(pc.getClassFilter().matches(Object.class)); - assertTrue(pc.getClassFilter().matches(Exception.class)); + assertThat(pc.getClassFilter().matches(Object.class)).isFalse(); + assertThat(pc.getClassFilter().matches(Exception.class)).isTrue(); pc.intersection(new RootClassFilter(NestedRuntimeException.class)); - assertFalse(pc.getClassFilter().matches(Exception.class)); - assertTrue(pc.getClassFilter().matches(NestedRuntimeException.class)); - assertFalse(pc.getClassFilter().matches(String.class)); + assertThat(pc.getClassFilter().matches(Exception.class)).isFalse(); + assertThat(pc.getClassFilter().matches(NestedRuntimeException.class)).isTrue(); + assertThat(pc.getClassFilter().matches(String.class)).isFalse(); pc.union(new RootClassFilter(String.class)); - assertFalse(pc.getClassFilter().matches(Exception.class)); - assertTrue(pc.getClassFilter().matches(String.class)); - assertTrue(pc.getClassFilter().matches(NestedRuntimeException.class)); + assertThat(pc.getClassFilter().matches(Exception.class)).isFalse(); + assertThat(pc.getClassFilter().matches(String.class)).isTrue(); + assertThat(pc.getClassFilter().matches(NestedRuntimeException.class)).isTrue(); } @Test public void testUnionMethodMatcher() { // Matches the getAge() method in any class ComposablePointcut pc = new ComposablePointcut(ClassFilter.TRUE, GET_AGE_METHOD_MATCHER); - assertFalse(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); - assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); - assertFalse(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); pc.union(GETTER_METHOD_MATCHER); // Should now match all getter methods - assertFalse(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); - assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); - assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue(); pc.union(ABSQUATULATE_METHOD_MATCHER); // Should now match absquatulate() as well - assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); - assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); - assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue(); // 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 public void testIntersectionMethodMatcher() { ComposablePointcut pc = new ComposablePointcut(); - assertTrue(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); - assertTrue(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); - assertTrue(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); + assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue(); + assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue(); pc.intersection(GETTER_METHOD_MATCHER); - assertFalse(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); - assertTrue(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); - assertTrue(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); + assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); + assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(pc.getMethodMatcher().matches(PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isTrue(); pc.intersection(GET_AGE_METHOD_MATCHER); // Use the Pointcuts matches method - assertFalse(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)); - assertTrue(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)); - assertFalse(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(pc, PointcutsTests.TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); } @Test @@ -138,24 +136,24 @@ public class ComposablePointcutTests { ComposablePointcut pc1 = new ComposablePointcut(); ComposablePointcut pc2 = new ComposablePointcut(); - assertEquals(pc1, pc2); - assertEquals(pc1.hashCode(), pc2.hashCode()); + assertThat(pc2).isEqualTo(pc1); + assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode()); pc1.intersection(GETTER_METHOD_MATCHER); - assertFalse(pc1.equals(pc2)); - assertFalse(pc1.hashCode() == pc2.hashCode()); + assertThat(pc1.equals(pc2)).isFalse(); + assertThat(pc1.hashCode() == pc2.hashCode()).isFalse(); pc2.intersection(GETTER_METHOD_MATCHER); - assertEquals(pc1, pc2); - assertEquals(pc1.hashCode(), pc2.hashCode()); + assertThat(pc2).isEqualTo(pc1); + assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode()); pc1.union(GET_AGE_METHOD_MATCHER); pc2.union(GET_AGE_METHOD_MATCHER); - assertEquals(pc1, pc2); - assertEquals(pc1.hashCode(), pc2.hashCode()); + assertThat(pc2).isEqualTo(pc1); + assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode()); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/support/ControlFlowPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/support/ControlFlowPointcutTests.java index 0ce90283291..6c7a062657a 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/ControlFlowPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/ControlFlowPointcutTests.java @@ -24,8 +24,7 @@ import org.springframework.tests.aop.interceptor.NopInterceptor; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -44,17 +43,17 @@ public class ControlFlowPointcutTests { pf.addAdvisor(new DefaultPointcutAdvisor(cflow, nop)); // Not advised, not under One - assertEquals(target.getAge(), proxied.getAge()); - assertEquals(0, nop.getCount()); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); + assertThat(nop.getCount()).isEqualTo(0); // Will be advised - assertEquals(target.getAge(), new One().getAge(proxied)); - assertEquals(1, nop.getCount()); + assertThat(new One().getAge(proxied)).isEqualTo(target.getAge()); + assertThat(nop.getCount()).isEqualTo(1); // Won't be advised - assertEquals(target.getAge(), new One().nomatch(proxied)); - assertEquals(1, nop.getCount()); - assertEquals(3, cflow.getEvaluations()); + assertThat(new One().nomatch(proxied)).isEqualTo(target.getAge()); + assertThat(nop.getCount()).isEqualTo(1); + assertThat(cflow.getEvaluations()).isEqualTo(3); } /** @@ -77,28 +76,28 @@ public class ControlFlowPointcutTests { // Not advised, not under One target.setAge(16); - assertEquals(0, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(0); // Not advised; under One but not a setter - assertEquals(16, new One().getAge(proxied)); - assertEquals(0, nop.getCount()); + assertThat(new One().getAge(proxied)).isEqualTo(16); + assertThat(nop.getCount()).isEqualTo(0); // Won't be advised new One().set(proxied); - assertEquals(1, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(1); // We saved most evaluations - assertEquals(1, cflow.getEvaluations()); + assertThat(cflow.getEvaluations()).isEqualTo(1); } @Test public void testEqualsAndHashCode() throws Exception { - assertEquals(new ControlFlowPointcut(One.class), new ControlFlowPointcut(One.class)); - assertEquals(new ControlFlowPointcut(One.class, "getAge"), new ControlFlowPointcut(One.class, "getAge")); - assertFalse(new ControlFlowPointcut(One.class, "getAge").equals(new ControlFlowPointcut(One.class))); - assertEquals(new ControlFlowPointcut(One.class).hashCode(), new ControlFlowPointcut(One.class).hashCode()); - assertEquals(new ControlFlowPointcut(One.class, "getAge").hashCode(), new ControlFlowPointcut(One.class, "getAge").hashCode()); - assertFalse(new ControlFlowPointcut(One.class, "getAge").hashCode() == new ControlFlowPointcut(One.class).hashCode()); + assertThat(new ControlFlowPointcut(One.class)).isEqualTo(new ControlFlowPointcut(One.class)); + assertThat(new ControlFlowPointcut(One.class, "getAge")).isEqualTo(new ControlFlowPointcut(One.class, "getAge")); + assertThat(new ControlFlowPointcut(One.class, "getAge").equals(new ControlFlowPointcut(One.class))).isFalse(); + assertThat(new ControlFlowPointcut(One.class).hashCode()).isEqualTo(new ControlFlowPointcut(One.class).hashCode()); + assertThat(new ControlFlowPointcut(One.class, "getAge").hashCode()).isEqualTo(new ControlFlowPointcut(One.class, "getAge").hashCode()); + assertThat(new ControlFlowPointcut(One.class, "getAge").hashCode() == new ControlFlowPointcut(One.class).hashCode()).isFalse(); } public class One { diff --git a/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java index 2fbd09a4181..c4e6022b732 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java @@ -36,9 +36,6 @@ import org.springframework.util.SerializationTestUtils; import static org.assertj.core.api.Assertions.assertThat; 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.Mockito.mock; @@ -59,7 +56,7 @@ public class DelegatingIntroductionInterceptorTests { @Test public void testIntroductionInterceptorWithDelegation() throws Exception { TestBean raw = new TestBean(); - assertTrue(! (raw instanceof TimeStamped)); + assertThat(! (raw instanceof TimeStamped)).isTrue(); ProxyFactory factory = new ProxyFactory(raw); TimeStamped ts = mock(TimeStamped.class); @@ -69,13 +66,13 @@ public class DelegatingIntroductionInterceptorTests { factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts))); TimeStamped tsp = (TimeStamped) factory.getProxy(); - assertTrue(tsp.getTimeStamp() == timestamp); + assertThat(tsp.getTimeStamp() == timestamp).isTrue(); } @Test public void testIntroductionInterceptorWithInterfaceHierarchy() throws Exception { TestBean raw = new TestBean(); - assertTrue(! (raw instanceof SubTimeStamped)); + assertThat(! (raw instanceof SubTimeStamped)).isTrue(); ProxyFactory factory = new ProxyFactory(raw); TimeStamped ts = mock(SubTimeStamped.class); @@ -85,13 +82,13 @@ public class DelegatingIntroductionInterceptorTests { factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), SubTimeStamped.class)); SubTimeStamped tsp = (SubTimeStamped) factory.getProxy(); - assertTrue(tsp.getTimeStamp() == timestamp); + assertThat(tsp.getTimeStamp() == timestamp).isTrue(); } @Test public void testIntroductionInterceptorWithSuperInterface() throws Exception { TestBean raw = new TestBean(); - assertTrue(! (raw instanceof TimeStamped)); + assertThat(! (raw instanceof TimeStamped)).isTrue(); ProxyFactory factory = new ProxyFactory(raw); TimeStamped ts = mock(SubTimeStamped.class); @@ -101,8 +98,8 @@ public class DelegatingIntroductionInterceptorTests { factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), TimeStamped.class)); TimeStamped tsp = (TimeStamped) factory.getProxy(); - assertTrue(!(tsp instanceof SubTimeStamped)); - assertTrue(tsp.getTimeStamp() == timestamp); + assertThat(!(tsp instanceof SubTimeStamped)).isTrue(); + assertThat(tsp.getTimeStamp() == timestamp).isTrue(); } @Test @@ -128,7 +125,7 @@ public class DelegatingIntroductionInterceptorTests { //assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1); TimeStamped ts = (TimeStamped) pf.getProxy(); - assertTrue(ts.getTimeStamp() == t); + assertThat(ts.getTimeStamp() == t).isTrue(); ((ITester) ts).foo(); ((ITestBean) ts).getAge(); @@ -155,7 +152,7 @@ public class DelegatingIntroductionInterceptorTests { ProxyFactory pf = new ProxyFactory(target); IntroductionAdvisor ia = new DefaultIntroductionAdvisor(ii); - assertTrue(ia.isPerInstance()); + assertThat(ia.isPerInstance()).isTrue(); pf.addAdvisor(0, ia); //assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1); @@ -163,10 +160,10 @@ public class DelegatingIntroductionInterceptorTests { assertThat(ts).isInstanceOf(TimeStamped.class); // Shouldn't proxy framework interfaces - assertTrue(!(ts instanceof MethodInterceptor)); - assertTrue(!(ts instanceof IntroductionInterceptor)); + assertThat(!(ts instanceof MethodInterceptor)).isTrue(); + assertThat(!(ts instanceof IntroductionInterceptor)).isTrue(); - assertTrue(ts.getTimeStamp() == t); + assertThat(ts.getTimeStamp() == t).isTrue(); ((ITester) ts).foo(); ((ITestBean) ts).getAge(); @@ -177,14 +174,14 @@ public class DelegatingIntroductionInterceptorTests { pf = new ProxyFactory(target); pf.addAdvisor(0, new DefaultIntroductionAdvisor(ii)); Object o = pf.getProxy(); - assertTrue(!(o instanceof TimeStamped)); + assertThat(!(o instanceof TimeStamped)).isTrue(); } @SuppressWarnings("serial") @Test public void testIntroductionInterceptorDoesntReplaceToString() throws Exception { TestBean raw = new TestBean(); - assertTrue(! (raw instanceof TimeStamped)); + assertThat(! (raw instanceof TimeStamped)).isTrue(); ProxyFactory factory = new ProxyFactory(raw); TimeStamped ts = new SerializableTimeStamped(0); @@ -197,9 +194,9 @@ public class DelegatingIntroductionInterceptorTests { })); 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 @@ -217,10 +214,10 @@ public class DelegatingIntroductionInterceptorTests { pf.addAdvice(new DelegatingIntroductionInterceptor(delegate)); INestedTestBean proxy = (INestedTestBean) pf.getProxy(); - assertEquals(company, proxy.getCompany()); + assertThat(proxy.getCompany()).isEqualTo(company); ITestBean introduction = (ITestBean) proxy; - assertSame("Introduced method returning delegate returns proxy", introduction, introduction.getSpouse()); - assertTrue("Introduced method returning delegate returns proxy", AopUtils.isAopProxy(introduction.getSpouse())); + assertThat(introduction.getSpouse()).as("Introduced method returning delegate returns proxy").isSameAs(introduction); + assertThat(AopUtils.isAopProxy(introduction.getSpouse())).as("Introduced method returning delegate returns proxy").isTrue(); } @Test @@ -239,12 +236,12 @@ public class DelegatingIntroductionInterceptorTests { Person p = (Person) factory.getProxy(); - assertEquals(name, p.getName()); - assertEquals(time, ((TimeStamped) p).getTimeStamp()); + assertThat(p.getName()).isEqualTo(name); + assertThat(((TimeStamped) p).getTimeStamp()).isEqualTo(time); Person p1 = (Person) SerializationTestUtils.serializeAndDeserialize(p); - assertEquals(name, p1.getName()); - assertEquals(time, ((TimeStamped) p1).getTimeStamp()); + assertThat(p1.getName()).isEqualTo(name); + assertThat(((TimeStamped) p1).getTimeStamp()).isEqualTo(time); } // Test when target implements the interface: should get interceptor by preference. @@ -269,7 +266,7 @@ public class DelegatingIntroductionInterceptorTests { TimeStamped ts = (TimeStamped) pf.getProxy(); // From introduction interceptor, not target - assertTrue(ts.getTimeStamp() == t); + assertThat(ts.getTimeStamp() == t).isTrue(); } diff --git a/spring-aop/src/test/java/org/springframework/aop/support/MethodMatchersTests.java b/spring-aop/src/test/java/org/springframework/aop/support/MethodMatchersTests.java index e766bd146a9..3c90cdd8879 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/MethodMatchersTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/MethodMatchersTests.java @@ -27,9 +27,7 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -57,24 +55,24 @@ public class MethodMatchersTests { @Test public void testDefaultMatchesAll() throws Exception { MethodMatcher defaultMm = MethodMatcher.TRUE; - assertTrue(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)); - assertTrue(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)); + assertThat(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)).isTrue(); + assertThat(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)).isTrue(); } @Test public void testMethodMatcherTrueSerializable() throws Exception { - assertSame(SerializationTestUtils.serializeAndDeserialize(MethodMatcher.TRUE), MethodMatcher.TRUE); + assertThat(MethodMatcher.TRUE).isSameAs(SerializationTestUtils.serializeAndDeserialize(MethodMatcher.TRUE)); } @Test public void testSingle() throws Exception { MethodMatcher defaultMm = MethodMatcher.TRUE; - assertTrue(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)); - assertTrue(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)); + assertThat(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)).isTrue(); + assertThat(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)).isTrue(); defaultMm = MethodMatchers.intersection(defaultMm, new StartsWithMatcher("get")); - assertTrue(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)); - assertFalse(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)); + assertThat(defaultMm.matches(EXCEPTION_GETMESSAGE, Exception.class)).isTrue(); + assertThat(defaultMm.matches(ITESTBEAN_SETAGE, TestBean.class)).isFalse(); } @@ -83,14 +81,14 @@ public class MethodMatchersTests { MethodMatcher mm1 = MethodMatcher.TRUE; MethodMatcher mm2 = new TestDynamicMethodMatcherWhichMatches(); MethodMatcher intersection = MethodMatchers.intersection(mm1, mm2); - assertTrue("Intersection is a dynamic matcher", intersection.isRuntime()); - assertTrue("2Matched setAge method", intersection.matches(ITESTBEAN_SETAGE, TestBean.class)); - assertTrue("3Matched setAge method", intersection.matches(ITESTBEAN_SETAGE, TestBean.class, new Integer(5))); + assertThat(intersection.isRuntime()).as("Intersection is a dynamic matcher").isTrue(); + assertThat(intersection.matches(ITESTBEAN_SETAGE, TestBean.class)).as("2Matched setAge method").isTrue(); + assertThat(intersection.matches(ITESTBEAN_SETAGE, TestBean.class, new Integer(5))).as("3Matched setAge method").isTrue(); // Knock out dynamic part intersection = MethodMatchers.intersection(intersection, new TestDynamicMethodMatcherWhichDoesNotMatch()); - assertTrue("Intersection is a dynamic matcher", intersection.isRuntime()); - assertTrue("2Matched setAge method", intersection.matches(ITESTBEAN_SETAGE, TestBean.class)); - assertFalse("3 - not Matched setAge method", intersection.matches(ITESTBEAN_SETAGE, TestBean.class, new Integer(5))); + assertThat(intersection.isRuntime()).as("Intersection is a dynamic matcher").isTrue(); + assertThat(intersection.matches(ITESTBEAN_SETAGE, TestBean.class)).as("2Matched setAge method").isTrue(); + assertThat(intersection.matches(ITESTBEAN_SETAGE, TestBean.class, new Integer(5))).as("3 - not Matched setAge method").isFalse(); } @Test @@ -99,18 +97,18 @@ public class MethodMatchersTests { MethodMatcher setterMatcher = new StartsWithMatcher("set"); MethodMatcher union = MethodMatchers.union(getterMatcher, setterMatcher); - assertFalse("Union is a static matcher", union.isRuntime()); - assertTrue("Matched setAge method", union.matches(ITESTBEAN_SETAGE, TestBean.class)); - assertTrue("Matched getAge method", union.matches(ITESTBEAN_GETAGE, TestBean.class)); - assertFalse("Didn't matched absquatulate method", union.matches(IOTHER_ABSQUATULATE, TestBean.class)); + assertThat(union.isRuntime()).as("Union is a static matcher").isFalse(); + assertThat(union.matches(ITESTBEAN_SETAGE, TestBean.class)).as("Matched setAge method").isTrue(); + assertThat(union.matches(ITESTBEAN_GETAGE, TestBean.class)).as("Matched getAge method").isTrue(); + assertThat(union.matches(IOTHER_ABSQUATULATE, TestBean.class)).as("Didn't matched absquatulate method").isFalse(); } @Test public void testUnionEquals() { MethodMatcher first = MethodMatchers.union(MethodMatcher.TRUE, MethodMatcher.TRUE); MethodMatcher second = new ComposablePointcut(MethodMatcher.TRUE).union(new ComposablePointcut(MethodMatcher.TRUE)).getMethodMatcher(); - assertTrue(first.equals(second)); - assertTrue(second.equals(first)); + assertThat(first.equals(second)).isTrue(); + assertThat(second.equals(first)).isTrue(); } diff --git a/spring-aop/src/test/java/org/springframework/aop/support/NameMatchMethodPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/support/NameMatchMethodPointcutTests.java index b5753f3e191..83f2d8e99d3 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/NameMatchMethodPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/NameMatchMethodPointcutTests.java @@ -27,9 +27,7 @@ import org.springframework.tests.sample.beans.Person; import org.springframework.tests.sample.beans.SerializablePerson; import org.springframework.util.SerializationTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -60,21 +58,21 @@ public class NameMatchMethodPointcutTests { @Test public void testMatchingOnly() { // Can't do exact matching through isMatch - assertTrue(pc.isMatch("echo", "ech*")); - assertTrue(pc.isMatch("setName", "setN*")); - assertTrue(pc.isMatch("setName", "set*")); - assertFalse(pc.isMatch("getName", "set*")); - assertFalse(pc.isMatch("setName", "set")); - assertTrue(pc.isMatch("testing", "*ing")); + assertThat(pc.isMatch("echo", "ech*")).isTrue(); + assertThat(pc.isMatch("setName", "setN*")).isTrue(); + assertThat(pc.isMatch("setName", "set*")).isTrue(); + assertThat(pc.isMatch("getName", "set*")).isFalse(); + assertThat(pc.isMatch("setName", "set")).isFalse(); + assertThat(pc.isMatch("testing", "*ing")).isTrue(); } @Test public void testEmpty() throws Throwable { - assertEquals(0, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(0); proxied.getName(); proxied.setName(""); proxied.echo(null); - assertEquals(0, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(0); } @@ -82,29 +80,29 @@ public class NameMatchMethodPointcutTests { public void testMatchOneMethod() throws Throwable { pc.addMethodName("echo"); pc.addMethodName("set*"); - assertEquals(0, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(0); proxied.getName(); proxied.getName(); - assertEquals(0, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(0); proxied.echo(null); - assertEquals(1, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(1); proxied.setName(""); - assertEquals(2, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(2); proxied.setAge(25); - assertEquals(25, proxied.getAge()); - assertEquals(3, nop.getCount()); + assertThat(proxied.getAge()).isEqualTo(25); + assertThat(nop.getCount()).isEqualTo(3); } @Test public void testSets() throws Throwable { pc.setMappedNames("set*", "echo"); - assertEquals(0, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(0); proxied.getName(); proxied.setName(""); - assertEquals(1, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(1); proxied.echo(null); - assertEquals(2, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(2); } @Test @@ -114,9 +112,9 @@ public class NameMatchMethodPointcutTests { Person p2 = (Person) SerializationTestUtils.serializeAndDeserialize(proxied); NopInterceptor nop2 = (NopInterceptor) ((Advised) p2).getAdvisors()[0].getAdvice(); p2.getName(); - assertEquals(2, nop2.getCount()); + assertThat(nop2.getCount()).isEqualTo(2); p2.echo(null); - assertEquals(3, nop2.getCount()); + assertThat(nop2.getCount()).isEqualTo(3); } @Test @@ -126,16 +124,16 @@ public class NameMatchMethodPointcutTests { String foo = "foo"; - assertEquals(pc1, pc2); - assertEquals(pc1.hashCode(), pc2.hashCode()); + assertThat(pc2).isEqualTo(pc1); + assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode()); pc1.setMappedName(foo); - assertFalse(pc1.equals(pc2)); - assertTrue(pc1.hashCode() != pc2.hashCode()); + assertThat(pc1.equals(pc2)).isFalse(); + assertThat(pc1.hashCode() != pc2.hashCode()).isTrue(); pc2.setMappedName(foo); - assertEquals(pc1, pc2); - assertEquals(pc1.hashCode(), pc2.hashCode()); + assertThat(pc2).isEqualTo(pc1); + assertThat(pc2.hashCode()).isEqualTo(pc1.hashCode()); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/support/PointcutsTests.java b/spring-aop/src/test/java/org/springframework/aop/support/PointcutsTests.java index 413f59c6897..82066758654 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/PointcutsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/PointcutsTests.java @@ -25,8 +25,7 @@ import org.springframework.aop.Pointcut; import org.springframework.lang.Nullable; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -127,22 +126,22 @@ public class PointcutsTests { @Test public void testTrue() { - assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); - assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_GET_AGE, TestBean.class)); - assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_ABSQUATULATE, TestBean.class)); - assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); - assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_GET_AGE, TestBean.class)); - assertTrue(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_ABSQUATULATE, TestBean.class)); + assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isTrue(); + assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isTrue(); + assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue(); } @Test public void testMatches() { - assertTrue(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); - assertFalse(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)); - assertFalse(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_ABSQUATULATE, TestBean.class)); - assertFalse(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); - assertTrue(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)); - assertFalse(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_ABSQUATULATE, TestBean.class)); + assertThat(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isTrue(); + assertThat(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isFalse(); + assertThat(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); } /** @@ -151,29 +150,29 @@ public class PointcutsTests { @Test public void testUnionOfSettersAndGetters() { Pointcut union = Pointcuts.union(allClassGetterPointcut, allClassSetterPointcut); - assertTrue(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); - assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)); - assertFalse(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)); + assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isTrue(); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); } @Test public void testUnionOfSpecificGetters() { Pointcut union = Pointcuts.union(allClassGetAgePointcut, allClassGetNamePointcut); - assertFalse(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); - assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)); - assertFalse(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_NAME, TestBean.class)); - assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)); - assertFalse(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)); + assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isFalse(); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); // Union with all setters union = Pointcuts.union(union, allClassSetterPointcut); - assertTrue(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); - assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)); - assertFalse(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_NAME, TestBean.class)); - assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)); - assertFalse(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)); + assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isTrue(); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)).isTrue(); + 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 public void testUnionOfAllSettersAndSubclassSetters() { - assertFalse(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); - assertTrue(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_SET_AGE, MyTestBean.class, new Integer(6))); - assertFalse(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)); + assertThat(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isFalse(); + assertThat(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_SET_AGE, MyTestBean.class, new Integer(6))).isTrue(); + assertThat(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); Pointcut union = Pointcuts.union(myTestBeanSetterPointcut, allClassGetterPointcut); - assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)); - assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBean.class)); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue(); // Still doesn't match superclass setter - assertTrue(Pointcuts.matches(union, TEST_BEAN_SET_AGE, MyTestBean.class, new Integer(6))); - assertFalse(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); + assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, MyTestBean.class, new Integer(6))).isTrue(); + assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isFalse(); } /** @@ -200,44 +199,44 @@ public class PointcutsTests { */ @Test public void testIntersectionOfSpecificGettersAndSubclassGetters() { - assertTrue(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_AGE, TestBean.class)); - assertTrue(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_AGE, MyTestBean.class)); - assertFalse(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_NAME, TestBean.class)); - assertFalse(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)); - assertTrue(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_NAME, MyTestBean.class)); - assertTrue(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_AGE, MyTestBean.class)); + assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue(); + assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_NAME, MyTestBean.class)).isTrue(); + assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue(); Pointcut intersection = Pointcuts.intersection(allClassGetAgePointcut, myTestBeanGetterPointcut); - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, TestBean.class)); - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)); - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBean.class)); - assertTrue(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBean.class)); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBean.class)).isFalse(); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue(); // Matches subclass of MyTestBean - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)); - assertTrue(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)).isFalse(); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)).isTrue(); // Now intersection with MyTestBeanSubclass getters should eliminate MyTestBean target intersection = Pointcuts.intersection(intersection, myTestBeanSubclassGetterPointcut); - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, TestBean.class)); - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)); - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBean.class)); - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBean.class)); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBean.class)).isFalse(); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBean.class)).isFalse(); // Still matches subclass of MyTestBean - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)); - assertTrue(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)).isFalse(); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)).isTrue(); // Now union with all TestBean methods Pointcut union = Pointcuts.union(intersection, allTestBeanMethodsPointcut); - assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)); - assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)); - assertFalse(Pointcuts.matches(union, TEST_BEAN_GET_NAME, MyTestBean.class)); - assertFalse(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBean.class)); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, MyTestBean.class)).isFalse(); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBean.class)).isFalse(); // Still matches subclass of MyTestBean - assertFalse(Pointcuts.matches(union, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)); - assertTrue(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)).isFalse(); + assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)).isTrue(); - assertTrue(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)); - assertFalse(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, MyTestBean.class)); + assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue(); + assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, MyTestBean.class)).isFalse(); } @@ -247,9 +246,9 @@ public class PointcutsTests { @Test public void testSimpleIntersection() { Pointcut intersection = Pointcuts.intersection(allClassGetterPointcut, allClassSetterPointcut); - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))); - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)); - assertFalse(Pointcuts.matches(intersection, TEST_BEAN_ABSQUATULATE, TestBean.class)); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_SET_AGE, TestBean.class, new Integer(6))).isFalse(); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); + assertThat(Pointcuts.matches(intersection, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests.java b/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests.java index 203fce5dd48..d2f7c42e4c8 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests.java @@ -29,7 +29,7 @@ import org.springframework.tests.sample.beans.Person; import org.springframework.tests.sample.beans.TestBean; 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; /** @@ -49,16 +49,16 @@ public class RegexpMethodPointcutAdvisorIntegrationTests { ITestBean advised = (ITestBean) bf.getBean("settersAdvised"); // Interceptor behind regexp advisor NopInterceptor nop = (NopInterceptor) bf.getBean("nopInterceptor"); - assertEquals(0, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(0); int newAge = 12; // Not advised advised.exceptional(null); - assertEquals(0, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(0); advised.setAge(newAge); - assertEquals(newAge, advised.getAge()); + assertThat(advised.getAge()).isEqualTo(newAge); // Only setter fired - assertEquals(1, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(1); } @Test @@ -69,20 +69,20 @@ public class RegexpMethodPointcutAdvisorIntegrationTests { TestBean advised = (TestBean) bf.getBean("settersAndAbsquatulateAdvised"); // Interceptor behind regexp advisor NopInterceptor nop = (NopInterceptor) bf.getBean("nopInterceptor"); - assertEquals(0, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(0); int newAge = 12; // Not advised advised.exceptional(null); - assertEquals(0, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(0); // This is proxied advised.absquatulate(); - assertEquals(1, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(1); advised.setAge(newAge); - assertEquals(newAge, advised.getAge()); + assertThat(advised.getAge()).isEqualTo(newAge); // Only setter fired - assertEquals(2, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(2); } @Test @@ -93,31 +93,31 @@ public class RegexpMethodPointcutAdvisorIntegrationTests { Person p = (Person) bf.getBean("serializableSettersAdvised"); // Interceptor behind regexp advisor NopInterceptor nop = (NopInterceptor) bf.getBean("nopInterceptor"); - assertEquals(0, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(0); int newAge = 12; // Not advised - assertEquals(0, p.getAge()); - assertEquals(0, nop.getCount()); + assertThat(p.getAge()).isEqualTo(0); + assertThat(nop.getCount()).isEqualTo(0); // This is proxied p.setAge(newAge); - assertEquals(1, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(1); p.setAge(newAge); - assertEquals(newAge, p.getAge()); + assertThat(p.getAge()).isEqualTo(newAge); // Only setter fired - assertEquals(2, nop.getCount()); + assertThat(nop.getCount()).isEqualTo(2); // Serialize and continue... 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... nop = (SerializableNopInterceptor) ((Advised) p).getAdvisors()[0].getAdvice(); - assertEquals(2, nop.getCount()); - assertEquals("serializableSettersAdvised", p.getName()); + assertThat(nop.getCount()).isEqualTo(2); + assertThat(p.getName()).isEqualTo("serializableSettersAdvised"); p.setAge(newAge + 1); - assertEquals(3, nop.getCount()); - assertEquals(newAge + 1, p.getAge()); + assertThat(nop.getCount()).isEqualTo(3); + assertThat(p.getAge()).isEqualTo((newAge + 1)); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceProxyTests.java b/spring-aop/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceProxyTests.java index 723b7028acb..3c0cf04d2c3 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceProxyTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceProxyTests.java @@ -24,7 +24,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; 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; /** @@ -42,6 +42,6 @@ public class CommonsPool2TargetSourceProxyTests { reader.loadBeanDefinitions(CONTEXT); beanFactory.preInstantiateSingletons(); ITestBean bean = (ITestBean)beanFactory.getBean("testBean"); - assertTrue(AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).isTrue(); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java index 20ea139e51b..7e9b615a942 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java @@ -31,8 +31,8 @@ import org.springframework.tests.sample.beans.SerializablePerson; import org.springframework.tests.sample.beans.SideEffectBean; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -70,13 +70,13 @@ public class HotSwappableTargetSourceTests { @Test public void testBasicFunctionality() { SideEffectBean proxied = (SideEffectBean) beanFactory.getBean("swappable"); - assertEquals(INITIAL_COUNT, proxied.getCount()); + assertThat(proxied.getCount()).isEqualTo(INITIAL_COUNT); proxied.doWork(); - assertEquals(INITIAL_COUNT + 1, proxied.getCount()); + assertThat(proxied.getCount()).isEqualTo((INITIAL_COUNT + 1)); proxied = (SideEffectBean) beanFactory.getBean("swappable"); proxied.doWork(); - assertEquals(INITIAL_COUNT + 2, proxied.getCount()); + assertThat(proxied.getCount()).isEqualTo((INITIAL_COUNT + 2)); } @Test @@ -85,25 +85,25 @@ public class HotSwappableTargetSourceTests { SideEffectBean target2 = (SideEffectBean) beanFactory.getBean("target2"); SideEffectBean proxied = (SideEffectBean) beanFactory.getBean("swappable"); - assertEquals(target1.getCount(), proxied.getCount()); + assertThat(proxied.getCount()).isEqualTo(target1.getCount()); proxied.doWork(); - assertEquals(INITIAL_COUNT + 1, proxied.getCount()); + assertThat(proxied.getCount()).isEqualTo((INITIAL_COUNT + 1)); HotSwappableTargetSource swapper = (HotSwappableTargetSource) beanFactory.getBean("swapper"); 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 // in AdvisedSupport //assertEquals(target2, ((Advised) proxied).getTarget()); - assertEquals(20, proxied.getCount()); + assertThat(proxied.getCount()).isEqualTo(20); proxied.doWork(); - assertEquals(21, target2.getCount()); + assertThat(target2.getCount()).isEqualTo(21); // Swap it back swapper.swap(target1); - assertEquals(target1.getCount(), proxied.getCount()); + assertThat(proxied.getCount()).isEqualTo(target1.getCount()); } @Test @@ -130,16 +130,16 @@ public class HotSwappableTargetSourceTests { pf.addAdvisor(new DefaultPointcutAdvisor(new SerializableNopInterceptor())); Person p = (Person) pf.getProxy(); - assertEquals(sp1.getName(), p.getName()); + assertThat(p.getName()).isEqualTo(sp1.getName()); hts.swap(sp2); - assertEquals(sp2.getName(), p.getName()); + assertThat(p.getName()).isEqualTo(sp2.getName()); p = (Person) SerializationTestUtils.serializeAndDeserialize(p); // We need to get a reference to the client-side targetsource hts = (HotSwappableTargetSource) ((Advised) p).getTargetSource(); - assertEquals(sp2.getName(), p.getName()); + assertThat(p.getName()).isEqualTo(sp2.getName()); hts.swap(sp1); - assertEquals(sp1.getName(), p.getName()); + assertThat(p.getName()).isEqualTo(sp1.getName()); } diff --git a/spring-aop/src/test/java/org/springframework/aop/target/LazyCreationTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/LazyCreationTargetSourceTests.java index 9809f5beb3e..bf89cf1f55b 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/LazyCreationTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/LazyCreationTargetSourceTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.aop.TargetSource; import org.springframework.aop.framework.ProxyFactory; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -44,15 +44,15 @@ public class LazyCreationTargetSourceTests { }; InitCountingBean proxy = (InitCountingBean) ProxyFactory.getProxy(targetSource); - assertEquals("Init count should be 0", 0, InitCountingBean.initCount); - assertEquals("Target class incorrect", InitCountingBean.class, targetSource.getTargetClass()); - assertEquals("Init count should still be 0 after getTargetClass()", 0, InitCountingBean.initCount); + assertThat(InitCountingBean.initCount).as("Init count should be 0").isEqualTo(0); + assertThat(targetSource.getTargetClass()).as("Target class incorrect").isEqualTo(InitCountingBean.class); + assertThat(InitCountingBean.initCount).as("Init count should still be 0 after getTargetClass()").isEqualTo(0); 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(); - assertEquals("Init count should still be 1", 1, InitCountingBean.initCount); + assertThat(InitCountingBean.initCount).as("Init count should still be 1").isEqualTo(1); } diff --git a/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests.java index 100ea0ca68c..6e45f0eb7ab 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests.java @@ -25,9 +25,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -51,9 +49,9 @@ public class LazyInitTargetSourceTests { bf.preInstantiateSingletons(); ITestBean tb = (ITestBean) bf.getBean("proxy"); - assertFalse(bf.containsSingleton("target")); - assertEquals(10, tb.getAge()); - assertTrue(bf.containsSingleton("target")); + assertThat(bf.containsSingleton("target")).isFalse(); + assertThat(tb.getAge()).isEqualTo(10); + assertThat(bf.containsSingleton("target")).isTrue(); } @Test @@ -63,9 +61,9 @@ public class LazyInitTargetSourceTests { bf.preInstantiateSingletons(); ITestBean tb = (ITestBean) bf.getBean("proxy"); - assertFalse(bf.containsSingleton("target")); - assertEquals("Rob Harrop", tb.getName()); - assertTrue(bf.containsSingleton("target")); + assertThat(bf.containsSingleton("target")).isFalse(); + assertThat(tb.getName()).isEqualTo("Rob Harrop"); + assertThat(bf.containsSingleton("target")).isTrue(); } @Test @@ -75,14 +73,14 @@ public class LazyInitTargetSourceTests { bf.preInstantiateSingletons(); Set set1 = (Set) bf.getBean("proxy1"); - assertFalse(bf.containsSingleton("target1")); - assertTrue(set1.contains("10")); - assertTrue(bf.containsSingleton("target1")); + assertThat(bf.containsSingleton("target1")).isFalse(); + assertThat(set1.contains("10")).isTrue(); + assertThat(bf.containsSingleton("target1")).isTrue(); Set set2 = (Set) bf.getBean("proxy2"); - assertFalse(bf.containsSingleton("target2")); - assertTrue(set2.contains("20")); - assertTrue(bf.containsSingleton("target2")); + assertThat(bf.containsSingleton("target2")).isFalse(); + assertThat(set2.contains("20")).isTrue(); + assertThat(bf.containsSingleton("target2")).isTrue(); } diff --git a/spring-aop/src/test/java/org/springframework/aop/target/PrototypeBasedTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/PrototypeBasedTargetSourceTests.java index 8fbc883753c..8b771d068a5 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/PrototypeBasedTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/PrototypeBasedTargetSourceTests.java @@ -26,8 +26,7 @@ import org.springframework.tests.sample.beans.SerializablePerson; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests relating to the abstract {@link AbstractPrototypeBasedTargetSource} @@ -56,10 +55,10 @@ public class PrototypeBasedTargetSourceTests { TestTargetSource cpts = (TestTargetSource) bf.getBean("ts"); TargetSource serialized = (TargetSource) SerializationTestUtils.serializeAndDeserialize(cpts); - assertTrue("Changed to SingletonTargetSource on deserialization", - serialized instanceof SingletonTargetSource); + boolean condition = serialized instanceof SingletonTargetSource; + assertThat(condition).as("Changed to SingletonTargetSource on deserialization").isTrue(); 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 * state can't prevent serialization from working */ + @SuppressWarnings("unused") private TestBean thisFieldIsNotSerializable = new TestBean(); @Override diff --git a/spring-aop/src/test/java/org/springframework/aop/target/PrototypeTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/PrototypeTargetSourceTests.java index 4b19637c47b..c83fff14ac2 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/PrototypeTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/PrototypeTargetSourceTests.java @@ -23,7 +23,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; 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; /** @@ -54,14 +54,14 @@ public class PrototypeTargetSourceTests { @Test public void testPrototypeAndSingletonBehaveDifferently() { SideEffectBean singleton = (SideEffectBean) beanFactory.getBean("singleton"); - assertEquals(INITIAL_COUNT, singleton.getCount()); + assertThat(singleton.getCount()).isEqualTo(INITIAL_COUNT); singleton.doWork(); - assertEquals(INITIAL_COUNT + 1, singleton.getCount()); + assertThat(singleton.getCount()).isEqualTo((INITIAL_COUNT + 1)); SideEffectBean prototype = (SideEffectBean) beanFactory.getBean("prototype"); - assertEquals(INITIAL_COUNT, prototype.getCount()); + assertThat(prototype.getCount()).isEqualTo(INITIAL_COUNT); prototype.doWork(); - assertEquals(INITIAL_COUNT, prototype.getCount()); + assertThat(prototype.getCount()).isEqualTo(INITIAL_COUNT); } } diff --git a/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java index 75e3f4e7776..b15959f2679 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java @@ -24,8 +24,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.SideEffectBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -63,24 +62,24 @@ public class ThreadLocalTargetSourceTests { @Test public void testUseDifferentManagedInstancesInSameThread() { SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment"); - assertEquals(INITIAL_COUNT, apartment.getCount()); + assertThat(apartment.getCount()).isEqualTo(INITIAL_COUNT); apartment.doWork(); - assertEquals(INITIAL_COUNT + 1, apartment.getCount()); + assertThat(apartment.getCount()).isEqualTo((INITIAL_COUNT + 1)); ITestBean test = (ITestBean) beanFactory.getBean("threadLocal2"); - assertEquals("Rod", test.getName()); - assertEquals("Kerry", test.getSpouse().getName()); + assertThat(test.getName()).isEqualTo("Rod"); + assertThat(test.getSpouse().getName()).isEqualTo("Kerry"); } @Test public void testReuseInSameThread() { SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment"); - assertEquals(INITIAL_COUNT, apartment.getCount()); + assertThat(apartment.getCount()).isEqualTo(INITIAL_COUNT); apartment.doWork(); - assertEquals(INITIAL_COUNT + 1, apartment.getCount()); + assertThat(apartment.getCount()).isEqualTo((INITIAL_COUNT + 1)); 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() { ThreadLocalTargetSourceStats stats = (ThreadLocalTargetSourceStats) beanFactory.getBean("apartment"); // +1 because creating target for stats call counts - assertEquals(1, stats.getInvocationCount()); + assertThat(stats.getInvocationCount()).isEqualTo(1); SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment"); apartment.doWork(); // +1 again - assertEquals(3, stats.getInvocationCount()); + assertThat(stats.getInvocationCount()).isEqualTo(3); // + 1 for states call! - assertEquals(3, stats.getHitCount()); + assertThat(stats.getHitCount()).isEqualTo(3); apartment.doWork(); - assertEquals(6, stats.getInvocationCount()); - assertEquals(6, stats.getHitCount()); + assertThat(stats.getInvocationCount()).isEqualTo(6); + assertThat(stats.getHitCount()).isEqualTo(6); // Only one thread so only one object can have been bound - assertEquals(1, stats.getObjectCount()); + assertThat(stats.getObjectCount()).isEqualTo(1); } @Test public void testNewThreadHasOwnInstance() throws InterruptedException { SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment"); - assertEquals(INITIAL_COUNT, apartment.getCount()); + assertThat(apartment.getCount()).isEqualTo(INITIAL_COUNT); apartment.doWork(); apartment.doWork(); apartment.doWork(); - assertEquals(INITIAL_COUNT + 3, apartment.getCount()); + assertThat(apartment.getCount()).isEqualTo((INITIAL_COUNT + 3)); class Runner implements Runnable { public SideEffectBean mine; @Override public void run() { this.mine = (SideEffectBean) beanFactory.getBean("apartment"); - assertEquals(INITIAL_COUNT, mine.getCount()); + assertThat(mine.getCount()).isEqualTo(INITIAL_COUNT); mine.doWork(); - assertEquals(INITIAL_COUNT + 1, mine.getCount()); + assertThat(mine.getCount()).isEqualTo((INITIAL_COUNT + 1)); } } Runner r = new Runner(); @@ -128,17 +127,17 @@ public class ThreadLocalTargetSourceTests { t.start(); t.join(); - assertNotNull(r); + assertThat(r).isNotNull(); // 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 // it should behave like ours - assertEquals(INITIAL_COUNT + 3, r.mine.getCount()); + assertThat(r.mine.getCount()).isEqualTo((INITIAL_COUNT + 3)); // Bound to two threads - assertEquals(2, ((ThreadLocalTargetSourceStats) apartment).getObjectCount()); + assertThat(((ThreadLocalTargetSourceStats) apartment).getObjectCount()).isEqualTo(2); } /** diff --git a/spring-aop/src/test/java/org/springframework/aop/target/dynamic/RefreshableTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/dynamic/RefreshableTargetSourceTests.java index 0198989e24b..3787e4bc113 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/dynamic/RefreshableTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/dynamic/RefreshableTargetSourceTests.java @@ -21,11 +21,7 @@ import org.junit.Test; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; -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.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -45,8 +41,8 @@ public class RefreshableTargetSourceTests { Thread.sleep(1); Object b = ts.getTarget(); - assertEquals("Should be one call to freshTarget to get initial target", 1, ts.getCallCount()); - assertSame("Returned objects should be the same - no refresh should occur", a, b); + assertThat(ts.getCallCount()).as("Should be one call to freshTarget to get initial target").isEqualTo(1); + 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); Object b = ts.getTarget(); - assertEquals("Should have called freshTarget twice", 2, ts.getCallCount()); - assertNotSame("Should be different objects", a, b); + assertThat(ts.getCallCount()).as("Should have called freshTarget twice").isEqualTo(2); + assertThat(b).as("Should be different objects").isNotSameAs(a); } /** @@ -76,8 +72,8 @@ public class RefreshableTargetSourceTests { Object a = ts.getTarget(); Object b = ts.getTarget(); - assertEquals("Refresh target should only be called once", 1, ts.getCallCount()); - assertSame("Objects should be the same - refresh check delay not elapsed", a, b); + assertThat(ts.getCallCount()).as("Refresh target should only be called once").isEqualTo(1); + assertThat(b).as("Objects should be the same - refresh check delay not elapsed").isSameAs(a); } @Test @@ -89,26 +85,26 @@ public class RefreshableTargetSourceTests { Object a = 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); 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); Object d = ts.getTarget(); - assertNotNull("D should not be null", d); - assertFalse("A and D should not be equal", a.equals(d)); + assertThat(d).as("D should not be null").isNotNull(); + assertThat(a.equals(d)).as("A and D should not be equal").isFalse(); 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); 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(); } diff --git a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/XmlBeanConfigurerTests.java b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/XmlBeanConfigurerTests.java index 6547ecbfe9b..76dce4fd096 100644 --- a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/XmlBeanConfigurerTests.java +++ b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/XmlBeanConfigurerTests.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Chris Beams @@ -33,7 +33,7 @@ public class XmlBeanConfigurerTests { "org/springframework/beans/factory/aspectj/beanConfigurerTests.xml")) { ShouldBeConfiguredBySpring myObject = new ShouldBeConfiguredBySpring(); - assertEquals("Rod", myObject.getName()); + assertThat(myObject.getName()).isEqualTo("Rod"); } } diff --git a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJCacheAnnotationTests.java b/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJCacheAnnotationTests.java index ac9d41e8181..b7873c4c375 100644 --- a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJCacheAnnotationTests.java +++ b/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJCacheAnnotationTests.java @@ -24,9 +24,7 @@ import org.springframework.cache.config.CacheableService; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Costin Leau @@ -43,7 +41,7 @@ public class AspectJCacheAnnotationTests extends AbstractCacheAnnotationTests { public void testKeyStrategy() throws Exception { AnnotationCacheAspect aspect = ctx.getBean( "org.springframework.cache.config.internalCacheAspect", AnnotationCacheAspect.class); - assertSame(ctx.getBean("keyGenerator"), aspect.getKeyGenerator()); + assertThat(aspect.getKeyGenerator()).isSameAs(ctx.getBean("keyGenerator")); } @Override @@ -56,21 +54,21 @@ public class AspectJCacheAnnotationTests extends AbstractCacheAnnotationTests { Cache primary = cm.getCache("primary"); Cache secondary = cm.getCache("secondary"); - assertSame(r1, r2); - assertSame(r1, primary.get(o1).get()); - assertSame(r1, secondary.get(o1).get()); + assertThat(r2).isSameAs(r1); + assertThat(primary.get(o1).get()).isSameAs(r1); + assertThat(secondary.get(o1).get()).isSameAs(r1); service.multiEvict(o1); - assertNull(primary.get(o1)); - assertNull(secondary.get(o1)); + assertThat(primary.get(o1)).isNull(); + assertThat(secondary.get(o1)).isNull(); Object r3 = service.multiCache(o1); Object r4 = service.multiCache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); + assertThat(r3).isNotSameAs(r1); + assertThat(r4).isSameAs(r3); - assertSame(r3, primary.get(o1).get()); - assertSame(r4, secondary.get(o1).get()); + assertThat(primary.get(o1).get()).isSameAs(r3); + assertThat(secondary.get(o1).get()).isSameAs(r4); } } diff --git a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJEnableCachingIsolatedTests.java b/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJEnableCachingIsolatedTests.java index 2840ee9cdf6..92207ad0a29 100644 --- a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJEnableCachingIsolatedTests.java +++ b/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJEnableCachingIsolatedTests.java @@ -43,10 +43,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -72,14 +69,14 @@ public class AspectJEnableCachingIsolatedTests { public void testKeyStrategy() { load(EnableCachingConfig.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 public void testCacheErrorHandler() { load(EnableCachingConfig.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); } 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) { Throwable root = ex.getRootCause(); - assertTrue(root instanceof IllegalStateException); - assertTrue(ex.getMessage().contains("implementations of CachingConfigurer")); + boolean condition = root instanceof IllegalStateException; + assertThat(condition).isTrue(); + assertThat(ex.getMessage().contains("implementations of CachingConfigurer")).isTrue(); } } @@ -123,7 +121,7 @@ public class AspectJEnableCachingIsolatedTests { load(EmptyConfig.class); } 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() { load(EmptyConfigSupportConfig.class); AnnotationCacheAspect aspect = this.ctx.getBean(AnnotationCacheAspect.class); - assertNotNull(aspect.getCacheResolver()); - assertEquals(SimpleCacheResolver.class, aspect.getCacheResolver().getClass()); - assertSame(this.ctx.getBean(CacheManager.class), - ((SimpleCacheResolver) aspect.getCacheResolver()).getCacheManager()); + assertThat(aspect.getCacheResolver()).isNotNull(); + assertThat(aspect.getCacheResolver().getClass()).isEqualTo(SimpleCacheResolver.class); + assertThat(((SimpleCacheResolver) aspect.getCacheResolver()).getCacheManager()).isSameAs(this.ctx.getBean(CacheManager.class)); } @Test @@ -143,8 +140,8 @@ public class AspectJEnableCachingIsolatedTests { load(FullCachingConfig.class); AnnotationCacheAspect aspect = this.ctx.getBean(AnnotationCacheAspect.class); - assertSame(this.ctx.getBean("cacheResolver"), aspect.getCacheResolver()); - assertSame(this.ctx.getBean("keyGenerator"), aspect.getKeyGenerator()); + assertThat(aspect.getCacheResolver()).isSameAs(this.ctx.getBean("cacheResolver")); + assertThat(aspect.getKeyGenerator()).isSameAs(this.ctx.getBean("keyGenerator")); } diff --git a/spring-aspects/src/test/java/org/springframework/context/annotation/aspectj/AnnotationBeanConfigurerTests.java b/spring-aspects/src/test/java/org/springframework/context/annotation/aspectj/AnnotationBeanConfigurerTests.java index 2f962ca8aec..7eb1ec2cefc 100644 --- a/spring-aspects/src/test/java/org/springframework/context/annotation/aspectj/AnnotationBeanConfigurerTests.java +++ b/spring-aspects/src/test/java/org/springframework/context/annotation/aspectj/AnnotationBeanConfigurerTests.java @@ -23,7 +23,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Configuration; 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 @@ -39,7 +39,7 @@ public class AnnotationBeanConfigurerTests { public void injection() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class)) { ShouldBeConfiguredBySpring myObject = new ShouldBeConfiguredBySpring(); - assertEquals("Rod", myObject.getName()); + assertThat(myObject.getName()).isEqualTo("Rod"); } } diff --git a/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java b/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java index 2ad5f33fac9..02eb4b0c418 100644 --- a/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java +++ b/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java @@ -39,8 +39,6 @@ import org.springframework.util.ReflectionUtils; import org.springframework.util.concurrent.ListenableFuture; 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}. @@ -71,9 +69,9 @@ public class AnnotationAsyncExecutionAspectTests { ClassWithoutAsyncAnnotation obj = new ClassWithoutAsyncAnnotation(); obj.incrementAsync(); executor.waitForCompletion(); - assertEquals(1, obj.counter); - assertEquals(1, executor.submitStartCounter); - assertEquals(1, executor.submitCompleteCounter); + assertThat(obj.counter).isEqualTo(1); + assertThat(executor.submitStartCounter).isEqualTo(1); + assertThat(executor.submitCompleteCounter).isEqualTo(1); } @Test @@ -81,19 +79,19 @@ public class AnnotationAsyncExecutionAspectTests { ClassWithoutAsyncAnnotation obj = new ClassWithoutAsyncAnnotation(); Future future = obj.incrementReturningAFuture(); // No need to executor.waitForCompletion() as future.get() will have the same effect - assertEquals(5, future.get().intValue()); - assertEquals(1, obj.counter); - assertEquals(1, executor.submitStartCounter); - assertEquals(1, executor.submitCompleteCounter); + assertThat(future.get().intValue()).isEqualTo(5); + assertThat(obj.counter).isEqualTo(1); + assertThat(executor.submitStartCounter).isEqualTo(1); + assertThat(executor.submitCompleteCounter).isEqualTo(1); } @Test public void syncMethodGetsRoutedSynchronously() { ClassWithoutAsyncAnnotation obj = new ClassWithoutAsyncAnnotation(); obj.increment(); - assertEquals(1, obj.counter); - assertEquals(0, executor.submitStartCounter); - assertEquals(0, executor.submitCompleteCounter); + assertThat(obj.counter).isEqualTo(1); + assertThat(executor.submitStartCounter).isEqualTo(0); + assertThat(executor.submitCompleteCounter).isEqualTo(0); } @Test @@ -103,19 +101,19 @@ public class AnnotationAsyncExecutionAspectTests { ClassWithAsyncAnnotation obj = new ClassWithAsyncAnnotation(); obj.increment(); executor.waitForCompletion(); - assertEquals(1, obj.counter); - assertEquals(1, executor.submitStartCounter); - assertEquals(1, executor.submitCompleteCounter); + assertThat(obj.counter).isEqualTo(1); + assertThat(executor.submitStartCounter).isEqualTo(1); + assertThat(executor.submitCompleteCounter).isEqualTo(1); } @Test public void methodReturningFutureInAsyncClassGetsRoutedAsynchronouslyAndReturnsAFuture() throws InterruptedException, ExecutionException { ClassWithAsyncAnnotation obj = new ClassWithAsyncAnnotation(); Future future = obj.incrementReturningAFuture(); - assertEquals(5, future.get().intValue()); - assertEquals(1, obj.counter); - assertEquals(1, executor.submitStartCounter); - assertEquals(1, executor.submitCompleteCounter); + assertThat(future.get().intValue()).isEqualTo(5); + assertThat(obj.counter).isEqualTo(1); + assertThat(executor.submitStartCounter).isEqualTo(1); + assertThat(executor.submitCompleteCounter).isEqualTo(1); } /* @@ -154,7 +152,7 @@ public class AnnotationAsyncExecutionAspectTests { TestableAsyncUncaughtExceptionHandler exceptionHandler = new TestableAsyncUncaughtExceptionHandler(); AnnotationAsyncExecutionAspect.aspectOf().setExceptionHandler(exceptionHandler); 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(); obj.failWithVoid(); exceptionHandler.await(3000); @@ -171,7 +169,7 @@ public class AnnotationAsyncExecutionAspectTests { TestableAsyncUncaughtExceptionHandler exceptionHandler = new TestableAsyncUncaughtExceptionHandler(true); AnnotationAsyncExecutionAspect.aspectOf().setExceptionHandler(exceptionHandler); 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(); obj.failWithVoid(); exceptionHandler.await(3000); diff --git a/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationDrivenBeanDefinitionParserTests.java b/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationDrivenBeanDefinitionParserTests.java index bfe73e34b8a..9dc40e74bd9 100644 --- a/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationDrivenBeanDefinitionParserTests.java +++ b/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationDrivenBeanDefinitionParserTests.java @@ -27,8 +27,7 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.scheduling.config.TaskManagementConfigUtils; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -52,7 +51,7 @@ public class AnnotationDrivenBeanDefinitionParserTests { @Test public void asyncAspectRegistered() { - assertTrue(context.containsBean(TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME)); + assertThat(context.containsBean(TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME)).isTrue(); } @Test @@ -60,7 +59,7 @@ public class AnnotationDrivenBeanDefinitionParserTests { public void asyncPostProcessorExecutorReference() { Object executor = context.getBean("testExecutor"); 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 @@ -68,7 +67,7 @@ public class AnnotationDrivenBeanDefinitionParserTests { public void asyncPostProcessorExceptionHandlerReference() { Object exceptionHandler = context.getBean("testExceptionHandler"); 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); } } diff --git a/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/TestableAsyncUncaughtExceptionHandler.java b/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/TestableAsyncUncaughtExceptionHandler.java index abf387d0e43..616e4299608 100644 --- a/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/TestableAsyncUncaughtExceptionHandler.java +++ b/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/TestableAsyncUncaughtExceptionHandler.java @@ -22,8 +22,7 @@ import java.util.concurrent.TimeUnit; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * A {@link AsyncUncaughtExceptionHandler} implementation used for testing purposes. @@ -61,9 +60,9 @@ class TestableAsyncUncaughtExceptionHandler } public void assertCalledWith(Method expectedMethod, Class expectedExceptionType) { - assertNotNull("Handler not called", descriptor); - assertEquals("Wrong exception type", expectedExceptionType, descriptor.ex.getClass()); - assertEquals("Wrong method", expectedMethod, descriptor.method); + assertThat(descriptor).as("Handler not called").isNotNull(); + assertThat(descriptor.ex.getClass()).as("Wrong exception type").isEqualTo(expectedExceptionType); + assertThat(descriptor.method).as("Wrong method").isEqualTo(expectedMethod); } public void await(long timeout) { diff --git a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java index 6f2d42c2489..fbe41ae0d94 100644 --- a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java +++ b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java @@ -30,9 +30,9 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 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.assertThatIOException; -import static org.junit.Assert.assertEquals; /** * @author Stephane Nicoll @@ -51,66 +51,66 @@ public class JtaTransactionAspectsTests { @Test public void commitOnAnnotatedPublicMethod() throws Throwable { - assertEquals(0, this.txManager.begun); + assertThat(this.txManager.begun).isEqualTo(0); new JtaAnnotationPublicAnnotatedMember().echo(null); - assertEquals(1, this.txManager.commits); + assertThat(this.txManager.commits).isEqualTo(1); } @Test public void matchingRollbackOnApplied() throws Throwable { - assertEquals(0, this.txManager.begun); + assertThat(this.txManager.begun).isEqualTo(0); InterruptedException test = new InterruptedException(); assertThatExceptionOfType(InterruptedException.class).isThrownBy(() -> new JtaAnnotationPublicAnnotatedMember().echo(test)) .isSameAs(test); - assertEquals(1, this.txManager.rollbacks); - assertEquals(0, this.txManager.commits); + assertThat(this.txManager.rollbacks).isEqualTo(1); + assertThat(this.txManager.commits).isEqualTo(0); } @Test public void nonMatchingRollbackOnApplied() throws Throwable { - assertEquals(0, this.txManager.begun); + assertThat(this.txManager.begun).isEqualTo(0); IOException test = new IOException(); assertThatIOException().isThrownBy(() -> new JtaAnnotationPublicAnnotatedMember().echo(test)) .isSameAs(test); - assertEquals(1, this.txManager.commits); - assertEquals(0, this.txManager.rollbacks); + assertThat(this.txManager.commits).isEqualTo(1); + assertThat(this.txManager.rollbacks).isEqualTo(0); } @Test public void commitOnAnnotatedProtectedMethod() { - assertEquals(0, this.txManager.begun); + assertThat(this.txManager.begun).isEqualTo(0); new JtaAnnotationProtectedAnnotatedMember().doInTransaction(); - assertEquals(1, this.txManager.commits); + assertThat(this.txManager.commits).isEqualTo(1); } @Test public void nonAnnotatedMethodCallingProtectedMethod() { - assertEquals(0, this.txManager.begun); + assertThat(this.txManager.begun).isEqualTo(0); new JtaAnnotationProtectedAnnotatedMember().doSomething(); - assertEquals(1, this.txManager.commits); + assertThat(this.txManager.commits).isEqualTo(1); } @Test public void commitOnAnnotatedPrivateMethod() { - assertEquals(0, this.txManager.begun); + assertThat(this.txManager.begun).isEqualTo(0); new JtaAnnotationPrivateAnnotatedMember().doInTransaction(); - assertEquals(1, this.txManager.commits); + assertThat(this.txManager.commits).isEqualTo(1); } @Test public void nonAnnotatedMethodCallingPrivateMethod() { - assertEquals(0, this.txManager.begun); + assertThat(this.txManager.begun).isEqualTo(0); new JtaAnnotationPrivateAnnotatedMember().doSomething(); - assertEquals(1, this.txManager.commits); + assertThat(this.txManager.commits).isEqualTo(1); } @Test public void notTransactional() { - assertEquals(0, this.txManager.begun); + assertThat(this.txManager.begun).isEqualTo(0); new TransactionAspectTests.NotTransactional().noop(); - assertEquals(0, this.txManager.begun); + assertThat(this.txManager.begun).isEqualTo(0); } diff --git a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java index 05c6132fa14..28ca98d232e 100644 --- a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java +++ b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java @@ -21,8 +21,8 @@ import org.junit.Test; 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.junit.Assert.assertEquals; /** * @author Rod Johnson @@ -56,49 +56,49 @@ public class TransactionAspectTests { @Test public void testCommitOnAnnotatedClass() throws Throwable { txManager.clear(); - assertEquals(0, txManager.begun); + assertThat(txManager.begun).isEqualTo(0); annotationOnlyOnClassWithNoInterface.echo(null); - assertEquals(1, txManager.commits); + assertThat(txManager.commits).isEqualTo(1); } @Test public void commitOnAnnotatedProtectedMethod() throws Throwable { txManager.clear(); - assertEquals(0, txManager.begun); + assertThat(txManager.begun).isEqualTo(0); beanWithAnnotatedProtectedMethod.doInTransaction(); - assertEquals(1, txManager.commits); + assertThat(txManager.commits).isEqualTo(1); } @Test public void commitOnAnnotatedPrivateMethod() throws Throwable { txManager.clear(); - assertEquals(0, txManager.begun); + assertThat(txManager.begun).isEqualTo(0); beanWithAnnotatedPrivateMethod.doSomething(); - assertEquals(1, txManager.commits); + assertThat(txManager.commits).isEqualTo(1); } @Test public void commitOnNonAnnotatedNonPublicMethodInTransactionalType() throws Throwable { txManager.clear(); - assertEquals(0, txManager.begun); + assertThat(txManager.begun).isEqualTo(0); annotationOnlyOnClassWithNoInterface.nonTransactionalMethod(); - assertEquals(0, txManager.begun); + assertThat(txManager.begun).isEqualTo(0); } @Test public void commitOnAnnotatedMethod() throws Throwable { txManager.clear(); - assertEquals(0, txManager.begun); + assertThat(txManager.begun).isEqualTo(0); methodAnnotationOnly.echo(null); - assertEquals(1, txManager.commits); + assertThat(txManager.commits).isEqualTo(1); } @Test public void notTransactional() throws Throwable { txManager.clear(); - assertEquals(0, txManager.begun); + assertThat(txManager.begun).isEqualTo(0); new NotTransactional().noop(); - assertEquals(0, txManager.begun); + assertThat(txManager.begun).isEqualTo(0); } @Test @@ -149,23 +149,25 @@ public class TransactionAspectTests { protected void testRollback(TransactionOperationCallback toc, boolean rollback) throws Throwable { txManager.clear(); - assertEquals(0, txManager.begun); + assertThat(txManager.begun).isEqualTo(0); try { toc.performTransactionalOperation(); } finally { - assertEquals(1, txManager.begun); - assertEquals(rollback ? 0 : 1, txManager.commits); - assertEquals(rollback ? 1 : 0, txManager.rollbacks); + assertThat(txManager.begun).isEqualTo(1); + long expected1 = rollback ? 0 : 1; + assertThat(txManager.commits).isEqualTo(expected1); + long expected = rollback ? 1 : 0; + assertThat(txManager.rollbacks).isEqualTo(expected); } } protected void testNotTransactional(TransactionOperationCallback toc, Throwable expected) throws Throwable { txManager.clear(); - assertEquals(0, txManager.begun); + assertThat(txManager.begun).isEqualTo(0); assertThatExceptionOfType(Throwable.class).isThrownBy( toc::performTransactionalOperation).isSameAs(expected); - assertEquals(0, txManager.begun); + assertThat(txManager.begun).isEqualTo(0); } diff --git a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java index fd706fd1fa5..dd3d0ef02a2 100644 --- a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java @@ -61,10 +61,7 @@ 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.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.within; /** * Shared tests for property accessors. @@ -100,7 +97,7 @@ public abstract class AbstractPropertyAccessorTests { public void isReadablePropertyNotReadable() { AbstractPropertyAccessor accessor = createAccessor(new NoRead()); - assertFalse(accessor.isReadableProperty("age")); + assertThat(accessor.isReadableProperty("age")).isFalse(); } /** @@ -110,7 +107,7 @@ public abstract class AbstractPropertyAccessorTests { public void isReadablePropertyNoSuchProperty() { AbstractPropertyAccessor accessor = createAccessor(new NoRead()); - assertFalse(accessor.isReadableProperty("xxxxx")); + assertThat(accessor.isReadableProperty("xxxxx")).isFalse(); } @Test @@ -140,7 +137,7 @@ public abstract class AbstractPropertyAccessorTests { public void isWritablePropertyNoSuchProperty() { AbstractPropertyAccessor accessor = createAccessor(new NoRead()); - assertFalse(accessor.isWritableProperty("xxxxx")); + assertThat(accessor.isWritableProperty("xxxxx")).isFalse(); } @Test @@ -148,45 +145,45 @@ public abstract class AbstractPropertyAccessorTests { IndexedTestBean target = new IndexedTestBean(); AbstractPropertyAccessor accessor = createAccessor(target); - assertTrue(accessor.isReadableProperty("array")); - assertTrue(accessor.isReadableProperty("list")); - assertTrue(accessor.isReadableProperty("set")); - assertTrue(accessor.isReadableProperty("map")); - assertFalse(accessor.isReadableProperty("xxx")); + assertThat(accessor.isReadableProperty("array")).isTrue(); + assertThat(accessor.isReadableProperty("list")).isTrue(); + assertThat(accessor.isReadableProperty("set")).isTrue(); + assertThat(accessor.isReadableProperty("map")).isTrue(); + assertThat(accessor.isReadableProperty("xxx")).isFalse(); - assertTrue(accessor.isWritableProperty("array")); - assertTrue(accessor.isWritableProperty("list")); - assertTrue(accessor.isWritableProperty("set")); - assertTrue(accessor.isWritableProperty("map")); - assertFalse(accessor.isWritableProperty("xxx")); + assertThat(accessor.isWritableProperty("array")).isTrue(); + assertThat(accessor.isWritableProperty("list")).isTrue(); + assertThat(accessor.isWritableProperty("set")).isTrue(); + assertThat(accessor.isWritableProperty("map")).isTrue(); + assertThat(accessor.isWritableProperty("xxx")).isFalse(); - assertTrue(accessor.isReadableProperty("array[0]")); - assertTrue(accessor.isReadableProperty("array[0].name")); - assertTrue(accessor.isReadableProperty("list[0]")); - assertTrue(accessor.isReadableProperty("list[0].name")); - assertTrue(accessor.isReadableProperty("set[0]")); - assertTrue(accessor.isReadableProperty("set[0].name")); - assertTrue(accessor.isReadableProperty("map[key1]")); - assertTrue(accessor.isReadableProperty("map[key1].name")); - assertTrue(accessor.isReadableProperty("map[key4][0]")); - assertTrue(accessor.isReadableProperty("map[key4][0].name")); - assertTrue(accessor.isReadableProperty("map[key4][1]")); - assertTrue(accessor.isReadableProperty("map[key4][1].name")); - assertFalse(accessor.isReadableProperty("array[key1]")); + assertThat(accessor.isReadableProperty("array[0]")).isTrue(); + assertThat(accessor.isReadableProperty("array[0].name")).isTrue(); + assertThat(accessor.isReadableProperty("list[0]")).isTrue(); + assertThat(accessor.isReadableProperty("list[0].name")).isTrue(); + assertThat(accessor.isReadableProperty("set[0]")).isTrue(); + assertThat(accessor.isReadableProperty("set[0].name")).isTrue(); + assertThat(accessor.isReadableProperty("map[key1]")).isTrue(); + assertThat(accessor.isReadableProperty("map[key1].name")).isTrue(); + assertThat(accessor.isReadableProperty("map[key4][0]")).isTrue(); + assertThat(accessor.isReadableProperty("map[key4][0].name")).isTrue(); + assertThat(accessor.isReadableProperty("map[key4][1]")).isTrue(); + assertThat(accessor.isReadableProperty("map[key4][1].name")).isTrue(); + assertThat(accessor.isReadableProperty("array[key1]")).isFalse(); - assertTrue(accessor.isWritableProperty("array[0]")); - assertTrue(accessor.isWritableProperty("array[0].name")); - assertTrue(accessor.isWritableProperty("list[0]")); - assertTrue(accessor.isWritableProperty("list[0].name")); - assertTrue(accessor.isWritableProperty("set[0]")); - assertTrue(accessor.isWritableProperty("set[0].name")); - assertTrue(accessor.isWritableProperty("map[key1]")); - assertTrue(accessor.isWritableProperty("map[key1].name")); - assertTrue(accessor.isWritableProperty("map[key4][0]")); - assertTrue(accessor.isWritableProperty("map[key4][0].name")); - assertTrue(accessor.isWritableProperty("map[key4][1]")); - assertTrue(accessor.isWritableProperty("map[key4][1].name")); - assertFalse(accessor.isWritableProperty("array[key1]")); + assertThat(accessor.isWritableProperty("array[0]")).isTrue(); + assertThat(accessor.isWritableProperty("array[0].name")).isTrue(); + assertThat(accessor.isWritableProperty("list[0]")).isTrue(); + assertThat(accessor.isWritableProperty("list[0].name")).isTrue(); + assertThat(accessor.isWritableProperty("set[0]")).isTrue(); + assertThat(accessor.isWritableProperty("set[0].name")).isTrue(); + assertThat(accessor.isWritableProperty("map[key1]")).isTrue(); + assertThat(accessor.isWritableProperty("map[key1].name")).isTrue(); + assertThat(accessor.isWritableProperty("map[key4][0]")).isTrue(); + assertThat(accessor.isWritableProperty("map[key4][0].name")).isTrue(); + assertThat(accessor.isWritableProperty("map[key4][1]")).isTrue(); + assertThat(accessor.isWritableProperty("map[key4][1].name")).isTrue(); + assertThat(accessor.isWritableProperty("array[key1]")).isFalse(); } @Test @@ -218,11 +215,11 @@ public abstract class AbstractPropertyAccessorTests { kerry.setSpouse(target); AbstractPropertyAccessor accessor = createAccessor(target); Integer KA = (Integer) accessor.getPropertyValue("spouse.age"); - assertTrue("kerry is 35", KA == 35); + assertThat(KA == 35).as("kerry is 35").isTrue(); Integer RA = (Integer) accessor.getPropertyValue("spouse.spouse.age"); - assertTrue("rod is 31, not" + RA, RA == 31); + assertThat(RA == 31).as("rod is 31, not" + RA).isTrue(); ITestBean spousesSpouse = (ITestBean) accessor.getPropertyValue("spouse.spouse"); - assertTrue("spousesSpouse = initial point", target == spousesSpouse); + assertThat(target == spousesSpouse).as("spousesSpouse = initial point").isTrue(); } @Test @@ -245,7 +242,7 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setAutoGrowNestedPaths(true); - assertEquals("DefaultCountry", accessor.getPropertyValue("address.country.name")); + assertThat(accessor.getPropertyValue("address.country.name")).isEqualTo("DefaultCountry"); } @Test @@ -255,7 +252,7 @@ public abstract class AbstractPropertyAccessorTests { accessor.setConversionService(new DefaultConversionService()); accessor.setAutoGrowNestedPaths(true); accessor.setPropertyValue("listOfMaps[0]['luckyNumber']", "9"); - assertEquals("9", target.listOfMaps.get(0).get("luckyNumber")); + assertThat(target.listOfMaps.get(0).get("luckyNumber")).isEqualTo("9"); } @Test @@ -309,16 +306,15 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("spouse.age", new Integer(35)); accessor.setPropertyValue("spouse.name", "Kerry"); accessor.setPropertyValue("spouse.company", "Lewisham"); - assertTrue("kerry name is Kerry", kerry.getName().equals("Kerry")); + assertThat(kerry.getName().equals("Kerry")).as("kerry name is Kerry").isTrue(); - assertTrue("nested set worked", target.getSpouse() == kerry); - assertTrue("no back relation", kerry.getSpouse() == null); + assertThat(target.getSpouse() == kerry).as("nested set worked").isTrue(); + assertThat(kerry.getSpouse() == null).as("no back relation").isTrue(); accessor.setPropertyValue(new PropertyValue("spouse.spouse", target)); - assertTrue("nested set worked", kerry.getSpouse() == target); + assertThat(kerry.getSpouse() == target).as("nested set worked").isTrue(); AbstractPropertyAccessor kerryAccessor = createAccessor(kerry); - assertTrue("spouse.spouse.spouse.spouse.company=Lewisham", - "Lewisham".equals(kerryAccessor.getPropertyValue("spouse.spouse.spouse.spouse.company"))); + assertThat("Lewisham".equals(kerryAccessor.getPropertyValue("spouse.spouse.spouse.spouse.company"))).as("spouse.spouse.spouse.spouse.company=Lewisham").isTrue(); } @Test @@ -329,16 +325,16 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("spouse", kerry); - assertTrue("nested set worked", target.getSpouse() == kerry); - assertTrue("no back relation", kerry.getSpouse() == null); + assertThat(target.getSpouse() == kerry).as("nested set worked").isTrue(); + assertThat(kerry.getSpouse() == null).as("no back relation").isTrue(); accessor.setPropertyValue(new PropertyValue("spouse.spouse", target)); - assertTrue("nested set worked", kerry.getSpouse() == target); - assertTrue("kerry age not set", kerry.getAge() == 0); + assertThat(kerry.getSpouse() == target).as("nested set worked").isTrue(); + assertThat(kerry.getAge() == 0).as("kerry age not set").isTrue(); accessor.setPropertyValue(new PropertyValue("spouse.age", 35)); - assertTrue("Set primitive on spouse", kerry.getAge() == 35); + assertThat(kerry.getAge() == 35).as("Set primitive on spouse").isTrue(); - assertEquals(kerry, accessor.getPropertyValue("spouse")); - assertEquals(target, accessor.getPropertyValue("spouse.spouse")); + assertThat(accessor.getPropertyValue("spouse")).isEqualTo(kerry); + assertThat(accessor.getPropertyValue("spouse.spouse")).isEqualTo(target); } @Test @@ -349,8 +345,8 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("doctor.company", doctorCompany); accessor.setPropertyValue("lawyer.company", lawyerCompany); - assertEquals(doctorCompany, target.getDoctor().getCompany()); - assertEquals(lawyerCompany, target.getLawyer().getCompany()); + assertThat(target.getDoctor().getCompany()).isEqualTo(doctorCompany); + assertThat(target.getLawyer().getCompany()).isEqualTo(lawyerCompany); } @Test @@ -373,7 +369,7 @@ public abstract class AbstractPropertyAccessorTests { accessor.getPropertyValue("spouse.bla"); } catch (NotReadablePropertyException ex) { - assertTrue(ex.getMessage().contains(TestBean.class.getName())); + assertThat(ex.getMessage().contains(TestBean.class.getName())).isTrue(); } } @@ -411,7 +407,6 @@ public abstract class AbstractPropertyAccessorTests { assertThat(target.address.country.name).isEqualTo("UK"); } - @SuppressWarnings("AssertEqualsBetweenInconvertibleTypes") @Test public void setPropertyIntermediateListIsNullWithAutoGrow() { Foo target = new Foo(); @@ -421,7 +416,7 @@ public abstract class AbstractPropertyAccessorTests { Map map = new HashMap<>(); map.put("favoriteNumber", "9"); accessor.setPropertyValue("list[0]", map); - assertEquals(map, target.list.get(0)); + assertThat(target.list.get(0)).isEqualTo(map); } @Test @@ -430,7 +425,7 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setAutoGrowNestedPaths(true); accessor.setPropertyValue("listOfMaps[0]['luckyNumber']", "9"); - assertEquals("9", target.listOfMaps.get(0).get("luckyNumber")); + assertThat(target.listOfMaps.get(0).get("luckyNumber")).isEqualTo("9"); } @Test @@ -445,7 +440,7 @@ public abstract class AbstractPropertyAccessorTests { }); accessor.setAutoGrowNestedPaths(true); accessor.setPropertyValue("listOfMaps[0]['luckyNumber']", "9"); - assertEquals("9", target.listOfMaps.get(0).get("luckyNumber")); + assertThat(target.listOfMaps.get(0).get("luckyNumber")).isEqualTo("9"); } @@ -457,12 +452,12 @@ public abstract class AbstractPropertyAccessorTests { target.setAge(age); target.setName(name); AbstractPropertyAccessor accessor = createAccessor(target); - assertTrue("age is OK", target.getAge() == age); - assertTrue("name is OK", name.equals(target.getName())); + assertThat(target.getAge() == age).as("age is OK").isTrue(); + assertThat(name.equals(target.getName())).as("name is OK").isTrue(); accessor.setPropertyValues(new MutablePropertyValues()); // Check its unchanged - assertTrue("age is OK", target.getAge() == age); - assertTrue("name is OK", name.equals(target.getName())); + assertThat(target.getAge() == age).as("age is OK").isTrue(); + assertThat(name.equals(target.getName())).as("name is OK").isTrue(); } @@ -478,9 +473,9 @@ public abstract class AbstractPropertyAccessorTests { pvs.addPropertyValue(new PropertyValue("name", newName)); pvs.addPropertyValue(new PropertyValue("touchy", newTouchy)); accessor.setPropertyValues(pvs); - assertTrue("Name property should have changed", target.getName().equals(newName)); - assertTrue("Touchy property should have changed", target.getTouchy().equals(newTouchy)); - assertTrue("Age property should have changed", target.getAge() == newAge); + assertThat(target.getName().equals(newName)).as("Name property should have changed").isTrue(); + assertThat(target.getTouchy().equals(newTouchy)).as("Touchy property should have changed").isTrue(); + assertThat(target.getAge() == newAge).as("Age property should have changed").isTrue(); } @Test @@ -493,9 +488,9 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("age", new Integer(newAge)); accessor.setPropertyValue(new PropertyValue("name", newName)); accessor.setPropertyValue(new PropertyValue("touchy", newTouchy)); - assertTrue("Name property should have changed", target.getName().equals(newName)); - assertTrue("Touchy property should have changed", target.getTouchy().equals(newTouchy)); - assertTrue("Age property should have changed", target.getAge() == newAge); + assertThat(target.getName().equals(newName)).as("Name property should have changed").isTrue(); + assertThat(target.getTouchy().equals(newTouchy)).as("Touchy property should have changed").isTrue(); + assertThat(target.getAge() == newAge).as("Age property should have changed").isTrue(); } @Test @@ -505,8 +500,8 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); target.setAge(newAge); Object bwAge = accessor.getPropertyValue("age"); - assertTrue("Age is an integer", bwAge instanceof Integer); - assertTrue("Bean wrapper must pick up changes", (int) bwAge == newAge); + assertThat(bwAge instanceof Integer).as("Age is an integer").isTrue(); + assertThat(bwAge).as("Bean wrapper must pick up changes").isEqualTo(newAge); } @Test @@ -515,13 +510,13 @@ public abstract class AbstractPropertyAccessorTests { target.setName("Frank"); // we need to change it back target.setSpouse(target); AbstractPropertyAccessor accessor = createAccessor(target); - assertTrue("name is not null to start off", target.getName() != null); + assertThat(target.getName() != null).as("name is not null to start off").isTrue(); accessor.setPropertyValue("name", null); - assertTrue("name is now null", target.getName() == null); + assertThat(target.getName() == null).as("name is now null").isTrue(); // now test with non-string - assertTrue("spouse is not null to start off", target.getSpouse() != null); + assertThat(target.getSpouse() != null).as("spouse is not null to start off").isTrue(); accessor.setPropertyValue("spouse", null); - assertTrue("spouse is now null", target.getSpouse() == null); + assertThat(target.getSpouse() == null).as("spouse is now null").isTrue(); } @@ -540,7 +535,7 @@ public abstract class AbstractPropertyAccessorTests { TestBean target = new TestBean(); AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValues(values); - assertEquals("42", target.getName()); + assertThat(target.getName()).isEqualTo("42"); } @Test @@ -556,7 +551,7 @@ public abstract class AbstractPropertyAccessorTests { } }); accessor.setPropertyValues(values); - assertEquals(Integer.class.toString(), target.getName()); + assertThat(target.getName()).isEqualTo(Integer.class.toString()); } @Test @@ -575,11 +570,11 @@ public abstract class AbstractPropertyAccessorTests { } }); accessor.setPropertyValue("name", new String[] {}); - assertEquals("", target.getName()); + assertThat(target.getName()).isEqualTo(""); accessor.setPropertyValue("name", new String[] {"a1", "b2"}); - assertEquals("a1-b2", target.getName()); + assertThat(target.getName()).isEqualTo("a1-b2"); accessor.setPropertyValue("name", null); - assertEquals("", target.getName()); + assertThat(target.getName()).isEqualTo(""); } @Test @@ -588,12 +583,12 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("bool2", "true"); - assertTrue("Correct bool2 value", Boolean.TRUE.equals(accessor.getPropertyValue("bool2"))); - assertTrue("Correct bool2 value", target.getBool2()); + assertThat(Boolean.TRUE.equals(accessor.getPropertyValue("bool2"))).as("Correct bool2 value").isTrue(); + assertThat(target.getBool2()).as("Correct bool2 value").isTrue(); accessor.setPropertyValue("bool2", "false"); - assertTrue("Correct bool2 value", Boolean.FALSE.equals(accessor.getPropertyValue("bool2"))); - assertTrue("Correct bool2 value", !target.getBool2()); + assertThat(Boolean.FALSE.equals(accessor.getPropertyValue("bool2"))).as("Correct bool2 value").isTrue(); + assertThat(!target.getBool2()).as("Correct bool2 value").isTrue(); } @Test @@ -607,20 +602,20 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("float2", "8.1"); accessor.setPropertyValue("double2", "6.1"); accessor.setPropertyValue("bigDecimal", "4.0"); - assertTrue("Correct short2 value", new Short("2").equals(accessor.getPropertyValue("short2"))); - assertTrue("Correct short2 value", new Short("2").equals(target.getShort2())); - assertTrue("Correct int2 value", new Integer("8").equals(accessor.getPropertyValue("int2"))); - assertTrue("Correct int2 value", new Integer("8").equals(target.getInt2())); - assertTrue("Correct long2 value", new Long("6").equals(accessor.getPropertyValue("long2"))); - assertTrue("Correct long2 value", new Long("6").equals(target.getLong2())); - assertTrue("Correct bigInteger value", new BigInteger("3").equals(accessor.getPropertyValue("bigInteger"))); - assertTrue("Correct bigInteger value", new BigInteger("3").equals(target.getBigInteger())); - assertTrue("Correct float2 value", new Float("8.1").equals(accessor.getPropertyValue("float2"))); - assertTrue("Correct float2 value", new Float("8.1").equals(target.getFloat2())); - assertTrue("Correct double2 value", new Double("6.1").equals(accessor.getPropertyValue("double2"))); - assertTrue("Correct double2 value", new Double("6.1").equals(target.getDouble2())); - assertTrue("Correct bigDecimal value", new BigDecimal("4.0").equals(accessor.getPropertyValue("bigDecimal"))); - assertTrue("Correct bigDecimal value", new BigDecimal("4.0").equals(target.getBigDecimal())); + assertThat(new Short("2").equals(accessor.getPropertyValue("short2"))).as("Correct short2 value").isTrue(); + assertThat(new Short("2").equals(target.getShort2())).as("Correct short2 value").isTrue(); + assertThat(new Integer("8").equals(accessor.getPropertyValue("int2"))).as("Correct int2 value").isTrue(); + assertThat(new Integer("8").equals(target.getInt2())).as("Correct int2 value").isTrue(); + assertThat(new Long("6").equals(accessor.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); + assertThat(new Long("6").equals(target.getLong2())).as("Correct long2 value").isTrue(); + assertThat(new BigInteger("3").equals(accessor.getPropertyValue("bigInteger"))).as("Correct bigInteger value").isTrue(); + assertThat(new BigInteger("3").equals(target.getBigInteger())).as("Correct bigInteger value").isTrue(); + assertThat(new Float("8.1").equals(accessor.getPropertyValue("float2"))).as("Correct float2 value").isTrue(); + assertThat(new Float("8.1").equals(target.getFloat2())).as("Correct float2 value").isTrue(); + assertThat(new Double("6.1").equals(accessor.getPropertyValue("double2"))).as("Correct double2 value").isTrue(); + assertThat(new Double("6.1").equals(target.getDouble2())).as("Correct double2 value").isTrue(); + assertThat(new BigDecimal("4.0").equals(accessor.getPropertyValue("bigDecimal"))).as("Correct bigDecimal value").isTrue(); + assertThat(new BigDecimal("4.0").equals(target.getBigDecimal())).as("Correct bigDecimal value").isTrue(); } @Test @@ -634,20 +629,20 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("float2", new Double(8.1)); accessor.setPropertyValue("double2", new BigDecimal(6.1)); accessor.setPropertyValue("bigDecimal", new Float(4.0)); - assertTrue("Correct short2 value", new Short("2").equals(accessor.getPropertyValue("short2"))); - assertTrue("Correct short2 value", new Short("2").equals(target.getShort2())); - assertTrue("Correct int2 value", new Integer("8").equals(accessor.getPropertyValue("int2"))); - assertTrue("Correct int2 value", new Integer("8").equals(target.getInt2())); - assertTrue("Correct long2 value", new Long("6").equals(accessor.getPropertyValue("long2"))); - assertTrue("Correct long2 value", new Long("6").equals(target.getLong2())); - assertTrue("Correct bigInteger value", new BigInteger("3").equals(accessor.getPropertyValue("bigInteger"))); - assertTrue("Correct bigInteger value", new BigInteger("3").equals(target.getBigInteger())); - assertTrue("Correct float2 value", new Float("8.1").equals(accessor.getPropertyValue("float2"))); - assertTrue("Correct float2 value", new Float("8.1").equals(target.getFloat2())); - assertTrue("Correct double2 value", new Double("6.1").equals(accessor.getPropertyValue("double2"))); - assertTrue("Correct double2 value", new Double("6.1").equals(target.getDouble2())); - assertTrue("Correct bigDecimal value", new BigDecimal("4.0").equals(accessor.getPropertyValue("bigDecimal"))); - assertTrue("Correct bigDecimal value", new BigDecimal("4.0").equals(target.getBigDecimal())); + assertThat(new Short("2").equals(accessor.getPropertyValue("short2"))).as("Correct short2 value").isTrue(); + assertThat(new Short("2").equals(target.getShort2())).as("Correct short2 value").isTrue(); + assertThat(new Integer("8").equals(accessor.getPropertyValue("int2"))).as("Correct int2 value").isTrue(); + assertThat(new Integer("8").equals(target.getInt2())).as("Correct int2 value").isTrue(); + assertThat(new Long("6").equals(accessor.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); + assertThat(new Long("6").equals(target.getLong2())).as("Correct long2 value").isTrue(); + assertThat(new BigInteger("3").equals(accessor.getPropertyValue("bigInteger"))).as("Correct bigInteger value").isTrue(); + assertThat(new BigInteger("3").equals(target.getBigInteger())).as("Correct bigInteger value").isTrue(); + assertThat(new Float("8.1").equals(accessor.getPropertyValue("float2"))).as("Correct float2 value").isTrue(); + assertThat(new Float("8.1").equals(target.getFloat2())).as("Correct float2 value").isTrue(); + assertThat(new Double("6.1").equals(accessor.getPropertyValue("double2"))).as("Correct double2 value").isTrue(); + assertThat(new Double("6.1").equals(target.getDouble2())).as("Correct double2 value").isTrue(); + assertThat(new BigDecimal("4.0").equals(accessor.getPropertyValue("bigDecimal"))).as("Correct bigDecimal value").isTrue(); + assertThat(new BigDecimal("4.0").equals(target.getBigDecimal())).as("Correct bigDecimal value").isTrue(); } @Test @@ -680,23 +675,23 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("myPrimitiveDouble", doubleValue); accessor.setPropertyValue("myDouble", doubleValue); - assertEquals(Byte.MAX_VALUE, target.getMyPrimitiveByte()); - assertEquals(Byte.MAX_VALUE, target.getMyByte().byteValue()); + assertThat(target.getMyPrimitiveByte()).isEqualTo(Byte.MAX_VALUE); + assertThat(target.getMyByte().byteValue()).isEqualTo(Byte.MAX_VALUE); - assertEquals(Short.MAX_VALUE, target.getMyPrimitiveShort()); - assertEquals(Short.MAX_VALUE, target.getMyShort().shortValue()); + assertThat(target.getMyPrimitiveShort()).isEqualTo(Short.MAX_VALUE); + assertThat(target.getMyShort().shortValue()).isEqualTo(Short.MAX_VALUE); - assertEquals(Integer.MAX_VALUE, target.getMyPrimitiveInt()); - assertEquals(Integer.MAX_VALUE, target.getMyInteger().intValue()); + assertThat(target.getMyPrimitiveInt()).isEqualTo(Integer.MAX_VALUE); + assertThat(target.getMyInteger().intValue()).isEqualTo(Integer.MAX_VALUE); - assertEquals(Long.MAX_VALUE, target.getMyPrimitiveLong()); - assertEquals(Long.MAX_VALUE, target.getMyLong().longValue()); + assertThat(target.getMyPrimitiveLong()).isEqualTo(Long.MAX_VALUE); + assertThat(target.getMyLong().longValue()).isEqualTo(Long.MAX_VALUE); - assertEquals(Float.MAX_VALUE, target.getMyPrimitiveFloat(), 0.001); - assertEquals(Float.MAX_VALUE, target.getMyFloat().floatValue(), 0.001); + assertThat((double) target.getMyPrimitiveFloat()).isCloseTo(Float.MAX_VALUE, within(0.001)); + assertThat((double) target.getMyFloat().floatValue()).isCloseTo(Float.MAX_VALUE, within(0.001)); - assertEquals(Double.MAX_VALUE, target.getMyPrimitiveDouble(), 0.001); - assertEquals(Double.MAX_VALUE, target.getMyDouble().doubleValue(), 0.001); + assertThat(target.getMyPrimitiveDouble()).isCloseTo(Double.MAX_VALUE, within(0.001)); + assertThat(target.getMyDouble().doubleValue()).isCloseTo(Double.MAX_VALUE, within(0.001)); } @@ -706,10 +701,10 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("autowire", "BY_NAME"); - assertEquals(Autowire.BY_NAME, target.getAutowire()); + assertThat(target.getAutowire()).isEqualTo(Autowire.BY_NAME); accessor.setPropertyValue("autowire", " BY_TYPE "); - assertEquals(Autowire.BY_TYPE, target.getAutowire()); + assertThat(target.getAutowire()).isEqualTo(Autowire.BY_TYPE); assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() -> accessor.setPropertyValue("autowire", "NHERITED")); @@ -720,7 +715,7 @@ public abstract class AbstractPropertyAccessorTests { EnumConsumer target = new EnumConsumer(); AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("enumValue", TestEnum.class.getName() + ".TEST_VALUE"); - assertEquals(TestEnum.TEST_VALUE, target.getEnumValue()); + assertThat(target.getEnumValue()).isEqualTo(TestEnum.TEST_VALUE); } @Test @@ -728,7 +723,7 @@ public abstract class AbstractPropertyAccessorTests { WildcardEnumConsumer target = new WildcardEnumConsumer(); AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("enumValue", TestEnum.class.getName() + ".TEST_VALUE"); - assertEquals(TestEnum.TEST_VALUE, target.getEnumValue()); + assertThat(target.getEnumValue()).isEqualTo(TestEnum.TEST_VALUE); } @Test @@ -741,12 +736,12 @@ public abstract class AbstractPropertyAccessorTests { String ps = "peace=war\nfreedom=slavery"; accessor.setPropertyValue("properties", ps); - assertTrue("name was set", target.name.equals("ptest")); - assertTrue("properties non null", target.properties != null); + assertThat(target.name.equals("ptest")).as("name was set").isTrue(); + assertThat(target.properties != null).as("properties non null").isTrue(); String freedomVal = target.properties.getProperty("freedom"); String peaceVal = target.properties.getProperty("peace"); - assertTrue("peace==war", peaceVal.equals("war")); - assertTrue("Freedom==slavery", freedomVal.equals("slavery")); + assertThat(peaceVal.equals("war")).as("peace==war").isTrue(); + assertThat(freedomVal.equals("slavery")).as("Freedom==slavery").isTrue(); } @Test @@ -755,9 +750,9 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("stringArray", new String[] {"foo", "fi", "fi", "fum"}); - assertTrue("stringArray length = 4", target.stringArray.length == 4); - assertTrue("correct values", target.stringArray[0].equals("foo") && target.stringArray[1].equals("fi") && - target.stringArray[2].equals("fi") && target.stringArray[3].equals("fum")); + assertThat(target.stringArray.length == 4).as("stringArray length = 4").isTrue(); + assertThat(target.stringArray[0].equals("foo") && target.stringArray[1].equals("fi") && + target.stringArray[2].equals("fi") && target.stringArray[3].equals("fum")).as("correct values").isTrue(); List list = new ArrayList<>(); list.add("foo"); @@ -765,25 +760,25 @@ public abstract class AbstractPropertyAccessorTests { list.add("fi"); list.add("fum"); accessor.setPropertyValue("stringArray", list); - assertTrue("stringArray length = 4", target.stringArray.length == 4); - assertTrue("correct values", target.stringArray[0].equals("foo") && target.stringArray[1].equals("fi") && - target.stringArray[2].equals("fi") && target.stringArray[3].equals("fum")); + assertThat(target.stringArray.length == 4).as("stringArray length = 4").isTrue(); + assertThat(target.stringArray[0].equals("foo") && target.stringArray[1].equals("fi") && + target.stringArray[2].equals("fi") && target.stringArray[3].equals("fum")).as("correct values").isTrue(); Set set = new HashSet<>(); set.add("foo"); set.add("fi"); set.add("fum"); accessor.setPropertyValue("stringArray", set); - assertTrue("stringArray length = 3", target.stringArray.length == 3); + assertThat(target.stringArray.length == 3).as("stringArray length = 3").isTrue(); List result = Arrays.asList(target.stringArray); - assertTrue("correct values", result.contains("foo") && result.contains("fi") && result.contains("fum")); + assertThat(result.contains("foo") && result.contains("fi") && result.contains("fum")).as("correct values").isTrue(); accessor.setPropertyValue("stringArray", "one"); - assertTrue("stringArray length = 1", target.stringArray.length == 1); - assertTrue("stringArray elt is ok", target.stringArray[0].equals("one")); + assertThat(target.stringArray.length == 1).as("stringArray length = 1").isTrue(); + assertThat(target.stringArray[0].equals("one")).as("stringArray elt is ok").isTrue(); accessor.setPropertyValue("stringArray", null); - assertTrue("stringArray is null", target.stringArray == null); + assertThat(target.stringArray == null).as("stringArray is null").isTrue(); } @Test @@ -798,9 +793,9 @@ public abstract class AbstractPropertyAccessorTests { }); accessor.setPropertyValue("stringArray", new String[] {"4foo", "7fi", "6fi", "5fum"}); - assertTrue("stringArray length = 4", target.stringArray.length == 4); - assertTrue("correct values", target.stringArray[0].equals("foo") && target.stringArray[1].equals("fi") && - target.stringArray[2].equals("fi") && target.stringArray[3].equals("fum")); + assertThat(target.stringArray.length == 4).as("stringArray length = 4").isTrue(); + assertThat(target.stringArray[0].equals("foo") && target.stringArray[1].equals("fi") && + target.stringArray[2].equals("fi") && target.stringArray[3].equals("fum")).as("correct values").isTrue(); List list = new ArrayList<>(); list.add("4foo"); @@ -808,22 +803,22 @@ public abstract class AbstractPropertyAccessorTests { list.add("6fi"); list.add("5fum"); accessor.setPropertyValue("stringArray", list); - assertTrue("stringArray length = 4", target.stringArray.length == 4); - assertTrue("correct values", target.stringArray[0].equals("foo") && target.stringArray[1].equals("fi") && - target.stringArray[2].equals("fi") && target.stringArray[3].equals("fum")); + assertThat(target.stringArray.length == 4).as("stringArray length = 4").isTrue(); + assertThat(target.stringArray[0].equals("foo") && target.stringArray[1].equals("fi") && + target.stringArray[2].equals("fi") && target.stringArray[3].equals("fum")).as("correct values").isTrue(); Set set = new HashSet<>(); set.add("4foo"); set.add("7fi"); set.add("6fum"); accessor.setPropertyValue("stringArray", set); - assertTrue("stringArray length = 3", target.stringArray.length == 3); + assertThat(target.stringArray.length == 3).as("stringArray length = 3").isTrue(); List result = Arrays.asList(target.stringArray); - assertTrue("correct values", result.contains("foo") && result.contains("fi") && result.contains("fum")); + assertThat(result.contains("foo") && result.contains("fi") && result.contains("fum")).as("correct values").isTrue(); accessor.setPropertyValue("stringArray", "8one"); - assertTrue("stringArray length = 1", target.stringArray.length == 1); - assertTrue("correct values", target.stringArray[0].equals("one")); + assertThat(target.stringArray.length == 1).as("stringArray length = 1").isTrue(); + assertThat(target.stringArray[0].equals("one")).as("correct values").isTrue(); } @Test @@ -832,8 +827,8 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.useConfigValueEditors(); accessor.setPropertyValue("stringArray", "a1,b2"); - assertTrue("stringArray length = 2", target.stringArray.length == 2); - assertTrue("correct values", target.stringArray[0].equals("a1") && target.stringArray[1].equals("b2")); + assertThat(target.stringArray.length == 2).as("stringArray length = 2").isTrue(); + assertThat(target.stringArray[0].equals("a1") && target.stringArray[1].equals("b2")).as("correct values").isTrue(); } @Test @@ -842,8 +837,8 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.registerCustomEditor(String[].class, "stringArray", new StringArrayPropertyEditor("-")); accessor.setPropertyValue("stringArray", "a1-b2"); - assertTrue("stringArray length = 2", target.stringArray.length == 2); - assertTrue("correct values", target.stringArray[0].equals("a1") && target.stringArray[1].equals("b2")); + assertThat(target.stringArray.length == 2).as("stringArray length = 2").isTrue(); + assertThat(target.stringArray[0].equals("a1") && target.stringArray[1].equals("b2")).as("correct values").isTrue(); } @Test @@ -853,12 +848,12 @@ public abstract class AbstractPropertyAccessorTests { accessor.setAutoGrowNestedPaths(true); accessor.setPropertyValue("array[0]", "Test0"); - assertEquals(1, target.getArray().length); + assertThat(target.getArray().length).isEqualTo(1); accessor.setPropertyValue("array[2]", "Test2"); - assertEquals(3, target.getArray().length); - assertTrue("correct values", target.getArray()[0].equals("Test0") && target.getArray()[1] == null && - target.getArray()[2].equals("Test2")); + assertThat(target.getArray().length).isEqualTo(3); + assertThat(target.getArray()[0].equals("Test0") && target.getArray()[1] == null && + target.getArray()[2].equals("Test2")).as("correct values").isTrue(); } @Test @@ -867,14 +862,14 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("intArray", new int[] {4, 5, 2, 3}); - assertTrue("intArray length = 4", target.intArray.length == 4); - assertTrue("correct values", target.intArray[0] == 4 && target.intArray[1] == 5 && - target.intArray[2] == 2 && target.intArray[3] == 3); + assertThat(target.intArray.length == 4).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 4 && target.intArray[1] == 5 && + target.intArray[2] == 2 && target.intArray[3] == 3).as("correct values").isTrue(); accessor.setPropertyValue("intArray", new String[] {"4", "5", "2", "3"}); - assertTrue("intArray length = 4", target.intArray.length == 4); - assertTrue("correct values", target.intArray[0] == 4 && target.intArray[1] == 5 && - target.intArray[2] == 2 && target.intArray[3] == 3); + assertThat(target.intArray.length == 4).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 4 && target.intArray[1] == 5 && + target.intArray[2] == 2 && target.intArray[3] == 3).as("correct values").isTrue(); List list = new ArrayList<>(); list.add(4); @@ -882,38 +877,38 @@ public abstract class AbstractPropertyAccessorTests { list.add(2); list.add("3"); accessor.setPropertyValue("intArray", list); - assertTrue("intArray length = 4", target.intArray.length == 4); - assertTrue("correct values", target.intArray[0] == 4 && target.intArray[1] == 5 && - target.intArray[2] == 2 && target.intArray[3] == 3); + assertThat(target.intArray.length == 4).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 4 && target.intArray[1] == 5 && + target.intArray[2] == 2 && target.intArray[3] == 3).as("correct values").isTrue(); Set set = new HashSet<>(); set.add("4"); set.add(5); set.add("3"); accessor.setPropertyValue("intArray", set); - assertTrue("intArray length = 3", target.intArray.length == 3); + assertThat(target.intArray.length == 3).as("intArray length = 3").isTrue(); List result = new ArrayList<>(); result.add(target.intArray[0]); result.add(target.intArray[1]); result.add(target.intArray[2]); - assertTrue("correct values", result.contains(new Integer(4)) && result.contains(new Integer(5)) && - result.contains(new Integer(3))); + assertThat(result.contains(new Integer(4)) && result.contains(new Integer(5)) && + result.contains(new Integer(3))).as("correct values").isTrue(); accessor.setPropertyValue("intArray", new Integer[] {1}); - assertTrue("intArray length = 4", target.intArray.length == 1); - assertTrue("correct values", target.intArray[0] == 1); + assertThat(target.intArray.length == 1).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 1).as("correct values").isTrue(); accessor.setPropertyValue("intArray", new Integer(1)); - assertTrue("intArray length = 4", target.intArray.length == 1); - assertTrue("correct values", target.intArray[0] == 1); + assertThat(target.intArray.length == 1).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 1).as("correct values").isTrue(); accessor.setPropertyValue("intArray", new String[] {"1"}); - assertTrue("intArray length = 4", target.intArray.length == 1); - assertTrue("correct values", target.intArray[0] == 1); + assertThat(target.intArray.length == 1).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 1).as("correct values").isTrue(); accessor.setPropertyValue("intArray", "1"); - assertTrue("intArray length = 4", target.intArray.length == 1); - assertTrue("correct values", target.intArray[0] == 1); + assertThat(target.intArray.length == 1).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 1).as("correct values").isTrue(); } @Test @@ -928,26 +923,26 @@ public abstract class AbstractPropertyAccessorTests { }); accessor.setPropertyValue("intArray", new int[] {4, 5, 2, 3}); - assertTrue("intArray length = 4", target.intArray.length == 4); - assertTrue("correct values", target.intArray[0] == 4 && target.intArray[1] == 5 && - target.intArray[2] == 2 && target.intArray[3] == 3); + assertThat(target.intArray.length == 4).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 4 && target.intArray[1] == 5 && + target.intArray[2] == 2 && target.intArray[3] == 3).as("correct values").isTrue(); accessor.setPropertyValue("intArray", new String[] {"3", "4", "1", "2"}); - assertTrue("intArray length = 4", target.intArray.length == 4); - assertTrue("correct values", target.intArray[0] == 4 && target.intArray[1] == 5 && - target.intArray[2] == 2 && target.intArray[3] == 3); + assertThat(target.intArray.length == 4).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 4 && target.intArray[1] == 5 && + target.intArray[2] == 2 && target.intArray[3] == 3).as("correct values").isTrue(); accessor.setPropertyValue("intArray", new Integer(1)); - assertTrue("intArray length = 4", target.intArray.length == 1); - assertTrue("correct values", target.intArray[0] == 1); + assertThat(target.intArray.length == 1).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 1).as("correct values").isTrue(); accessor.setPropertyValue("intArray", new String[] {"0"}); - assertTrue("intArray length = 4", target.intArray.length == 1); - assertTrue("correct values", target.intArray[0] == 1); + assertThat(target.intArray.length == 1).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 1).as("correct values").isTrue(); accessor.setPropertyValue("intArray", "0"); - assertTrue("intArray length = 4", target.intArray.length == 1); - assertTrue("correct values", target.intArray[0] == 1); + assertThat(target.intArray.length == 1).as("intArray length = 4").isTrue(); + assertThat(target.intArray[0] == 1).as("correct values").isTrue(); } @Test @@ -956,8 +951,8 @@ public abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.useConfigValueEditors(); accessor.setPropertyValue("intArray", "4,5"); - assertTrue("intArray length = 2", target.intArray.length == 2); - assertTrue("correct values", target.intArray[0] == 4 && target.intArray[1] == 5); + assertThat(target.intArray.length == 2).as("intArray length = 2").isTrue(); + assertThat(target.intArray[0] == 4 && target.intArray[1] == 5).as("correct values").isTrue(); } @Test @@ -965,9 +960,9 @@ public abstract class AbstractPropertyAccessorTests { PrimitiveArrayBean target = new PrimitiveArrayBean(); AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("array", new String[] {"1", "2"}); - assertEquals(2, target.getArray().length); - assertEquals(1, target.getArray()[0]); - assertEquals(2, target.getArray()[1]); + assertThat(target.getArray().length).isEqualTo(2); + assertThat(target.getArray()[0]).isEqualTo(1); + assertThat(target.getArray()[1]).isEqualTo(2); } @Test @@ -984,10 +979,10 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("array", input); } sw.stop(); - assertEquals(1024, target.getArray().length); - assertEquals(0, target.getArray()[0]); + assertThat(target.getArray().length).isEqualTo(1024); + assertThat(target.getArray()[0]).isEqualTo(0); long time1 = sw.getLastTaskTimeMillis(); - assertTrue("Took too long", sw.getLastTaskTimeMillis() < 100); + assertThat(sw.getLastTaskTimeMillis() < 100).as("Took too long").isTrue(); accessor.registerCustomEditor(String.class, new StringTrimmerEditor(false)); sw.start("array2"); @@ -995,7 +990,7 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("array", input); } sw.stop(); - assertTrue("Took too long", sw.getLastTaskTimeMillis() < 125); + assertThat(sw.getLastTaskTimeMillis() < 125).as("Took too long").isTrue(); accessor.registerCustomEditor(int.class, "array.somePath", new CustomNumberEditor(Integer.class, false)); sw.start("array3"); @@ -1003,7 +998,7 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("array", input); } sw.stop(); - assertTrue("Took too long", sw.getLastTaskTimeMillis() < 100); + assertThat(sw.getLastTaskTimeMillis() < 100).as("Took too long").isTrue(); accessor.registerCustomEditor(int.class, "array[0].somePath", new CustomNumberEditor(Integer.class, false)); sw.start("array3"); @@ -1011,7 +1006,7 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("array", input); } sw.stop(); - assertTrue("Took too long", sw.getLastTaskTimeMillis() < 100); + assertThat(sw.getLastTaskTimeMillis() < 100).as("Took too long").isTrue(); accessor.registerCustomEditor(int.class, new CustomNumberEditor(Integer.class, false)); sw.start("array4"); @@ -1019,9 +1014,9 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("array", input); } sw.stop(); - assertEquals(1024, target.getArray().length); - assertEquals(0, target.getArray()[0]); - assertTrue("Took too long", sw.getLastTaskTimeMillis() > time1); + assertThat(target.getArray().length).isEqualTo(1024); + assertThat(target.getArray()[0]).isEqualTo(0); + assertThat(sw.getLastTaskTimeMillis() > time1).as("Took too long").isTrue(); } @Test @@ -1038,9 +1033,9 @@ public abstract class AbstractPropertyAccessorTests { }); int[] input = new int[1024]; accessor.setPropertyValue("array", input); - assertEquals(1024, target.getArray().length); - assertEquals(1, target.getArray()[0]); - assertEquals(1, target.getArray()[1]); + assertThat(target.getArray().length).isEqualTo(1024); + assertThat(target.getArray()[0]).isEqualTo(1); + assertThat(target.getArray()[1]).isEqualTo(1); } @Test @@ -1057,9 +1052,9 @@ public abstract class AbstractPropertyAccessorTests { }); int[] input = new int[1024]; accessor.setPropertyValue("array", input); - assertEquals(1024, target.getArray().length); - assertEquals(0, target.getArray()[0]); - assertEquals(1, target.getArray()[1]); + assertThat(target.getArray().length).isEqualTo(1024); + assertThat(target.getArray()[0]).isEqualTo(0); + assertThat(target.getArray()[1]).isEqualTo(1); } @Test @@ -1069,12 +1064,12 @@ public abstract class AbstractPropertyAccessorTests { accessor.setAutoGrowNestedPaths(true); accessor.setPropertyValue("array[0]", 1); - assertEquals(1, target.getArray().length); + assertThat(target.getArray().length).isEqualTo(1); accessor.setPropertyValue("array[2]", 3); - assertEquals(3, target.getArray().length); - assertTrue("correct values", target.getArray()[0] == 1 && target.getArray()[1] == 0 && - target.getArray()[2] == 3); + assertThat(target.getArray().length).isEqualTo(3); + assertThat(target.getArray()[0] == 1 && target.getArray()[1] == 0 && + target.getArray()[2] == 3).as("correct values").isTrue(); } @Test @@ -1089,11 +1084,11 @@ public abstract class AbstractPropertyAccessorTests { values.add("4"); accessor.setPropertyValue("items", values); Object[] result = target.items; - assertEquals(4, result.length); - assertEquals("1", result[0]); - assertEquals("2", result[1]); - assertEquals("3", result[2]); - assertEquals("4", result[3]); + assertThat(result.length).isEqualTo(4); + assertThat(result[0]).isEqualTo("1"); + assertThat(result[1]).isEqualTo("2"); + assertThat(result[2]).isEqualTo("3"); + assertThat(result[3]).isEqualTo("4"); } @Test @@ -1127,10 +1122,10 @@ public abstract class AbstractPropertyAccessorTests { List list = new LinkedList<>(); list.add("list1"); accessor.setPropertyValue("list", list); - assertSame(coll, target.getCollection()); - assertSame(set, target.getSet()); - assertSame(sortedSet, target.getSortedSet()); - assertSame(list, target.getList()); + assertThat(target.getCollection()).isSameAs(coll); + assertThat(target.getSet()).isSameAs(set); + assertThat(target.getSortedSet()).isSameAs(sortedSet); + assertThat((List) target.getList()).isSameAs(list); } @SuppressWarnings("unchecked") // list cannot be properly parameterized as it breaks other tests @@ -1150,14 +1145,14 @@ public abstract class AbstractPropertyAccessorTests { Set list = new HashSet<>(); list.add("list1"); accessor.setPropertyValue("list", list); - assertEquals(1, target.getCollection().size()); - assertTrue(target.getCollection().containsAll(coll)); - assertEquals(1, target.getSet().size()); - assertTrue(target.getSet().containsAll(set)); - assertEquals(1, target.getSortedSet().size()); - assertTrue(target.getSortedSet().containsAll(sortedSet)); - assertEquals(1, target.getList().size()); - assertTrue(target.getList().containsAll(list)); + assertThat(target.getCollection().size()).isEqualTo(1); + assertThat(target.getCollection().containsAll(coll)).isTrue(); + assertThat(target.getSet().size()).isEqualTo(1); + assertThat(target.getSet().containsAll(set)).isTrue(); + assertThat(target.getSortedSet().size()).isEqualTo(1); + assertThat(target.getSortedSet().containsAll(sortedSet)).isTrue(); + assertThat(target.getList().size()).isEqualTo(1); + assertThat(target.getList().containsAll(list)).isTrue(); } @SuppressWarnings("unchecked") // list cannot be properly parameterized as it breaks other tests @@ -1177,14 +1172,14 @@ public abstract class AbstractPropertyAccessorTests { Set list = new HashSet<>(); list.add("list1"); accessor.setPropertyValue("list", list.toArray()); - assertEquals(1, target.getCollection().size()); - assertTrue(target.getCollection().containsAll(coll)); - assertEquals(1, target.getSet().size()); - assertTrue(target.getSet().containsAll(set)); - assertEquals(1, target.getSortedSet().size()); - assertTrue(target.getSortedSet().containsAll(sortedSet)); - assertEquals(1, target.getList().size()); - assertTrue(target.getList().containsAll(list)); + assertThat(target.getCollection().size()).isEqualTo(1); + assertThat(target.getCollection().containsAll(coll)).isTrue(); + assertThat(target.getSet().size()).isEqualTo(1); + assertThat(target.getSet().containsAll(set)).isTrue(); + assertThat(target.getSortedSet().size()).isEqualTo(1); + assertThat(target.getSortedSet().containsAll(sortedSet)).isTrue(); + assertThat(target.getList().size()).isEqualTo(1); + assertThat(target.getList().containsAll(list)).isTrue(); } @SuppressWarnings("unchecked") // list cannot be properly parameterized as it breaks other tests @@ -1204,14 +1199,14 @@ public abstract class AbstractPropertyAccessorTests { Set list = new HashSet<>(); list.add(3); accessor.setPropertyValue("list", new int[] {3}); - assertEquals(1, target.getCollection().size()); - assertTrue(target.getCollection().containsAll(coll)); - assertEquals(1, target.getSet().size()); - assertTrue(target.getSet().containsAll(set)); - assertEquals(1, target.getSortedSet().size()); - assertTrue(target.getSortedSet().containsAll(sortedSet)); - assertEquals(1, target.getList().size()); - assertTrue(target.getList().containsAll(list)); + assertThat(target.getCollection().size()).isEqualTo(1); + assertThat(target.getCollection().containsAll(coll)).isTrue(); + assertThat(target.getSet().size()).isEqualTo(1); + assertThat(target.getSet().containsAll(set)).isTrue(); + assertThat(target.getSortedSet().size()).isEqualTo(1); + assertThat(target.getSortedSet().containsAll(sortedSet)).isTrue(); + assertThat(target.getList().size()).isEqualTo(1); + assertThat(target.getList().containsAll(list)).isTrue(); } @SuppressWarnings("unchecked") // list cannot be properly parameterized as it breaks other tests @@ -1231,14 +1226,14 @@ public abstract class AbstractPropertyAccessorTests { Set list = new HashSet<>(); list.add(3); accessor.setPropertyValue("list", new Integer(3)); - assertEquals(1, target.getCollection().size()); - assertTrue(target.getCollection().containsAll(coll)); - assertEquals(1, target.getSet().size()); - assertTrue(target.getSet().containsAll(set)); - assertEquals(1, target.getSortedSet().size()); - assertTrue(target.getSortedSet().containsAll(sortedSet)); - assertEquals(1, target.getList().size()); - assertTrue(target.getList().containsAll(list)); + assertThat(target.getCollection().size()).isEqualTo(1); + assertThat(target.getCollection().containsAll(coll)).isTrue(); + assertThat(target.getSet().size()).isEqualTo(1); + assertThat(target.getSet().containsAll(set)).isTrue(); + assertThat(target.getSortedSet().size()).isEqualTo(1); + assertThat(target.getSortedSet().containsAll(sortedSet)).isTrue(); + assertThat(target.getList().size()).isEqualTo(1); + assertThat(target.getList().containsAll(list)).isTrue(); } @SuppressWarnings("unchecked") // list cannot be properly parameterized as it breaks other tests @@ -1255,12 +1250,12 @@ public abstract class AbstractPropertyAccessorTests { Set list = new HashSet<>(); list.add("list1"); accessor.setPropertyValue("list", "list1"); - assertEquals(1, target.getSet().size()); - assertTrue(target.getSet().containsAll(set)); - assertEquals(1, target.getSortedSet().size()); - assertTrue(target.getSortedSet().containsAll(sortedSet)); - assertEquals(1, target.getList().size()); - assertTrue(target.getList().containsAll(list)); + assertThat(target.getSet().size()).isEqualTo(1); + assertThat(target.getSet().containsAll(set)).isTrue(); + assertThat(target.getSortedSet().size()).isEqualTo(1); + assertThat(target.getSortedSet().containsAll(sortedSet)).isTrue(); + assertThat(target.getList().size()).isEqualTo(1); + assertThat(target.getList().containsAll(list)).isTrue(); } @Test @@ -1273,15 +1268,15 @@ public abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("set", "set1 "); accessor.setPropertyValue("sortedSet", "sortedSet1"); accessor.setPropertyValue("list", "list1 "); - assertEquals(1, target.getSet().size()); - assertTrue(target.getSet().contains("set1")); - assertEquals(1, target.getSortedSet().size()); - assertTrue(target.getSortedSet().contains("sortedSet1")); - assertEquals(1, target.getList().size()); - assertTrue(target.getList().contains("list1")); + assertThat(target.getSet().size()).isEqualTo(1); + assertThat(target.getSet().contains("set1")).isTrue(); + assertThat(target.getSortedSet().size()).isEqualTo(1); + assertThat(target.getSortedSet().contains("sortedSet1")).isTrue(); + assertThat(target.getList().size()).isEqualTo(1); + assertThat(target.getList().contains("list1")).isTrue(); accessor.setPropertyValue("list", Collections.singletonList("list1 ")); - assertTrue(target.getList().contains("list1")); + assertThat(target.getList().contains("list1")).isTrue(); } @Test @@ -1294,8 +1289,8 @@ public abstract class AbstractPropertyAccessorTests { SortedMap sortedMap = new TreeMap<>(); map.put("sortedKey", "sortedValue"); accessor.setPropertyValue("sortedMap", sortedMap); - assertSame(map, target.getMap()); - assertSame(sortedMap, target.getSortedMap()); + assertThat((Map) target.getMap()).isSameAs(map); + assertThat((Map) target.getSortedMap()).isSameAs(sortedMap); } @Test @@ -1308,10 +1303,10 @@ public abstract class AbstractPropertyAccessorTests { Map sortedMap = new TreeMap<>(); sortedMap.put("sortedKey", "sortedValue"); accessor.setPropertyValue("sortedMap", sortedMap); - assertEquals(1, target.getMap().size()); - assertEquals("value", target.getMap().get("key")); - assertEquals(1, target.getSortedMap().size()); - assertEquals("sortedValue", target.getSortedMap().get("sortedKey")); + assertThat(target.getMap().size()).isEqualTo(1); + assertThat(target.getMap().get("key")).isEqualTo("value"); + assertThat(target.getSortedMap().size()).isEqualTo(1); + assertThat(target.getSortedMap().get("sortedKey")).isEqualTo("sortedValue"); } @Test @@ -1332,8 +1327,8 @@ public abstract class AbstractPropertyAccessorTests { goodValues.add("map[key1]", "rod"); goodValues.add("map[key2]", "rob"); accessor.setPropertyValues(goodValues); - assertEquals("rod", ((TestBean) target.getMap().get("key1")).getName()); - assertEquals("rob", ((TestBean) target.getMap().get("key2")).getName()); + assertThat(((TestBean) target.getMap().get("key1")).getName()).isEqualTo("rod"); + assertThat(((TestBean) target.getMap().get("key2")).getName()).isEqualTo("rob"); MutablePropertyValues badValues = new MutablePropertyValues(); badValues.add("map[key1]", "rod"); @@ -1363,8 +1358,8 @@ public abstract class AbstractPropertyAccessorTests { MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("map", Collections.unmodifiableMap(inputMap)); accessor.setPropertyValues(pvs); - assertEquals("rod", ((TestBean) target.getMap().get(1)).getName()); - assertEquals("rob", ((TestBean) target.getMap().get(2)).getName()); + assertThat(((TestBean) target.getMap().get(1)).getName()).isEqualTo("rod"); + assertThat(((TestBean) target.getMap().get(2)).getName()).isEqualTo("rob"); } @Test @@ -1387,8 +1382,8 @@ public abstract class AbstractPropertyAccessorTests { MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("map", new ReadOnlyMap<>(inputMap)); accessor.setPropertyValues(pvs); - assertEquals("rod", ((TestBean) target.getMap().get(1)).getName()); - assertEquals("rob", ((TestBean) target.getMap().get(2)).getName()); + assertThat(((TestBean) target.getMap().get(1)).getName()).isEqualTo("rod"); + assertThat(((TestBean) target.getMap().get(2)).getName()).isEqualTo("rob"); } @SuppressWarnings({ "unchecked", "rawtypes" }) // must work with raw map in this test @@ -1403,8 +1398,8 @@ public abstract class AbstractPropertyAccessorTests { MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("map", readOnlyMap); accessor.setPropertyValues(pvs); - assertSame(readOnlyMap, target.getMap()); - assertFalse(readOnlyMap.isAccessed()); + assertThat(target.getMap()).isSameAs(readOnlyMap); + assertThat(readOnlyMap.isAccessed()).isFalse(); } @Test @@ -1446,8 +1441,8 @@ public abstract class AbstractPropertyAccessorTests { DerivedFromProtectedBaseBean target = new DerivedFromProtectedBaseBean(); AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("someProperty", "someValue"); - assertEquals("someValue", accessor.getPropertyValue("someProperty")); - assertEquals("someValue", target.getSomeProperty()); + assertThat(accessor.getPropertyValue("someProperty")).isEqualTo("someValue"); + assertThat(target.getSomeProperty()).isEqualTo("someValue"); } @Test @@ -1484,7 +1479,7 @@ public abstract class AbstractPropertyAccessorTests { pvs.addPropertyValue(new PropertyValue("more.garbage", new Object())); AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValues(pvs, true); - assertTrue("Set valid and ignored invalid", target.getName().equals("rod")); + assertThat(target.getName().equals("rod")).as("Set valid and ignored invalid").isTrue(); assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() -> accessor.setPropertyValues(pvs, false)); // Don't ignore: should fail } @@ -1502,30 +1497,30 @@ public abstract class AbstractPropertyAccessorTests { TestBean tb4 = ((TestBean) target.getMap().get("key1")); TestBean tb5 = ((TestBean) target.getMap().get("key.3")); TestBean tb8 = ((TestBean) target.getMap().get("key5[foo]")); - assertEquals("name0", tb0.getName()); - assertEquals("name1", tb1.getName()); - assertEquals("name2", tb2.getName()); - assertEquals("name3", tb3.getName()); - assertEquals("name6", tb6.getName()); - assertEquals("name7", tb7.getName()); - assertEquals("name4", tb4.getName()); - assertEquals("name5", tb5.getName()); - assertEquals("name8", tb8.getName()); - assertEquals("name0", accessor.getPropertyValue("array[0].name")); - assertEquals("name1", accessor.getPropertyValue("array[1].name")); - assertEquals("name2", accessor.getPropertyValue("list[0].name")); - assertEquals("name3", accessor.getPropertyValue("list[1].name")); - assertEquals("name6", accessor.getPropertyValue("set[0].name")); - assertEquals("name7", accessor.getPropertyValue("set[1].name")); - assertEquals("name4", accessor.getPropertyValue("map[key1].name")); - assertEquals("name5", accessor.getPropertyValue("map[key.3].name")); - assertEquals("name4", accessor.getPropertyValue("map['key1'].name")); - assertEquals("name5", accessor.getPropertyValue("map[\"key.3\"].name")); - assertEquals("nameX", accessor.getPropertyValue("map[key4][0].name")); - assertEquals("nameY", accessor.getPropertyValue("map[key4][1].name")); - assertEquals("name8", accessor.getPropertyValue("map[key5[foo]].name")); - assertEquals("name8", accessor.getPropertyValue("map['key5[foo]'].name")); - assertEquals("name8", accessor.getPropertyValue("map[\"key5[foo]\"].name")); + assertThat(tb0.getName()).isEqualTo("name0"); + assertThat(tb1.getName()).isEqualTo("name1"); + assertThat(tb2.getName()).isEqualTo("name2"); + assertThat(tb3.getName()).isEqualTo("name3"); + assertThat(tb6.getName()).isEqualTo("name6"); + assertThat(tb7.getName()).isEqualTo("name7"); + assertThat(tb4.getName()).isEqualTo("name4"); + assertThat(tb5.getName()).isEqualTo("name5"); + assertThat(tb8.getName()).isEqualTo("name8"); + assertThat(accessor.getPropertyValue("array[0].name")).isEqualTo("name0"); + assertThat(accessor.getPropertyValue("array[1].name")).isEqualTo("name1"); + assertThat(accessor.getPropertyValue("list[0].name")).isEqualTo("name2"); + assertThat(accessor.getPropertyValue("list[1].name")).isEqualTo("name3"); + assertThat(accessor.getPropertyValue("set[0].name")).isEqualTo("name6"); + assertThat(accessor.getPropertyValue("set[1].name")).isEqualTo("name7"); + assertThat(accessor.getPropertyValue("map[key1].name")).isEqualTo("name4"); + assertThat(accessor.getPropertyValue("map[key.3].name")).isEqualTo("name5"); + assertThat(accessor.getPropertyValue("map['key1'].name")).isEqualTo("name4"); + assertThat(accessor.getPropertyValue("map[\"key.3\"].name")).isEqualTo("name5"); + assertThat(accessor.getPropertyValue("map[key4][0].name")).isEqualTo("nameX"); + assertThat(accessor.getPropertyValue("map[key4][1].name")).isEqualTo("nameY"); + assertThat(accessor.getPropertyValue("map[key5[foo]].name")).isEqualTo("name8"); + assertThat(accessor.getPropertyValue("map['key5[foo]'].name")).isEqualTo("name8"); + assertThat(accessor.getPropertyValue("map[\"key5[foo]\"].name")).isEqualTo("name8"); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0].name", "name5"); @@ -1540,23 +1535,23 @@ public abstract class AbstractPropertyAccessorTests { pvs.add("map[key4][1].name", "nameB"); pvs.add("map[key5[foo]].name", "name10"); accessor.setPropertyValues(pvs); - assertEquals("name5", tb0.getName()); - assertEquals("name4", tb1.getName()); - assertEquals("name3", tb2.getName()); - assertEquals("name2", tb3.getName()); - assertEquals("name1", tb4.getName()); - assertEquals("name0", tb5.getName()); - assertEquals("name5", accessor.getPropertyValue("array[0].name")); - assertEquals("name4", accessor.getPropertyValue("array[1].name")); - assertEquals("name3", accessor.getPropertyValue("list[0].name")); - assertEquals("name2", accessor.getPropertyValue("list[1].name")); - assertEquals("name8", accessor.getPropertyValue("set[0].name")); - assertEquals("name9", accessor.getPropertyValue("set[1].name")); - assertEquals("name1", accessor.getPropertyValue("map[\"key1\"].name")); - assertEquals("name0", accessor.getPropertyValue("map['key.3'].name")); - assertEquals("nameA", accessor.getPropertyValue("map[key4][0].name")); - assertEquals("nameB", accessor.getPropertyValue("map[key4][1].name")); - assertEquals("name10", accessor.getPropertyValue("map[key5[foo]].name")); + assertThat(tb0.getName()).isEqualTo("name5"); + assertThat(tb1.getName()).isEqualTo("name4"); + assertThat(tb2.getName()).isEqualTo("name3"); + assertThat(tb3.getName()).isEqualTo("name2"); + assertThat(tb4.getName()).isEqualTo("name1"); + assertThat(tb5.getName()).isEqualTo("name0"); + assertThat(accessor.getPropertyValue("array[0].name")).isEqualTo("name5"); + assertThat(accessor.getPropertyValue("array[1].name")).isEqualTo("name4"); + assertThat(accessor.getPropertyValue("list[0].name")).isEqualTo("name3"); + assertThat(accessor.getPropertyValue("list[1].name")).isEqualTo("name2"); + assertThat(accessor.getPropertyValue("set[0].name")).isEqualTo("name8"); + assertThat(accessor.getPropertyValue("set[1].name")).isEqualTo("name9"); + assertThat(accessor.getPropertyValue("map[\"key1\"].name")).isEqualTo("name1"); + assertThat(accessor.getPropertyValue("map['key.3'].name")).isEqualTo("name0"); + assertThat(accessor.getPropertyValue("map[key4][0].name")).isEqualTo("nameA"); + assertThat(accessor.getPropertyValue("map[key4][1].name")).isEqualTo("nameB"); + assertThat(accessor.getPropertyValue("map[key5[foo]].name")).isEqualTo("name10"); } @Test @@ -1571,16 +1566,16 @@ public abstract class AbstractPropertyAccessorTests { TestBean tb7 = ((TestBean) target.getSet().toArray()[1]); TestBean tb4 = ((TestBean) target.getMap().get("key1")); TestBean tb5 = ((TestBean) target.getMap().get("key2")); - assertEquals(tb0, accessor.getPropertyValue("array[0]")); - assertEquals(tb1, accessor.getPropertyValue("array[1]")); - assertEquals(tb2, accessor.getPropertyValue("list[0]")); - assertEquals(tb3, accessor.getPropertyValue("list[1]")); - assertEquals(tb6, accessor.getPropertyValue("set[0]")); - assertEquals(tb7, accessor.getPropertyValue("set[1]")); - assertEquals(tb4, accessor.getPropertyValue("map[key1]")); - assertEquals(tb5, accessor.getPropertyValue("map[key2]")); - assertEquals(tb4, accessor.getPropertyValue("map['key1']")); - assertEquals(tb5, accessor.getPropertyValue("map[\"key2\"]")); + assertThat(accessor.getPropertyValue("array[0]")).isEqualTo(tb0); + assertThat(accessor.getPropertyValue("array[1]")).isEqualTo(tb1); + assertThat(accessor.getPropertyValue("list[0]")).isEqualTo(tb2); + assertThat(accessor.getPropertyValue("list[1]")).isEqualTo(tb3); + assertThat(accessor.getPropertyValue("set[0]")).isEqualTo(tb6); + assertThat(accessor.getPropertyValue("set[1]")).isEqualTo(tb7); + assertThat(accessor.getPropertyValue("map[key1]")).isEqualTo(tb4); + assertThat(accessor.getPropertyValue("map[key2]")).isEqualTo(tb5); + assertThat(accessor.getPropertyValue("map['key1']")).isEqualTo(tb4); + assertThat(accessor.getPropertyValue("map[\"key2\"]")).isEqualTo(tb5); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0]", tb5); @@ -1594,28 +1589,28 @@ public abstract class AbstractPropertyAccessorTests { pvs.add("map[key5]", tb4); pvs.add("map['key9']", tb5); accessor.setPropertyValues(pvs); - assertEquals(tb5, target.getArray()[0]); - assertEquals(tb4, target.getArray()[1]); - assertEquals(tb3, (target.getList().get(0))); - assertEquals(tb2, (target.getList().get(1))); - assertEquals(tb0, (target.getList().get(2))); - assertEquals(null, (target.getList().get(3))); - assertEquals(tb1, (target.getList().get(4))); - assertEquals(tb1, (target.getMap().get("key1"))); - assertEquals(tb0, (target.getMap().get("key2"))); - assertEquals(tb4, (target.getMap().get("key5"))); - assertEquals(tb5, (target.getMap().get("key9"))); - assertEquals(tb5, accessor.getPropertyValue("array[0]")); - assertEquals(tb4, accessor.getPropertyValue("array[1]")); - assertEquals(tb3, accessor.getPropertyValue("list[0]")); - assertEquals(tb2, accessor.getPropertyValue("list[1]")); - assertEquals(tb0, accessor.getPropertyValue("list[2]")); - assertEquals(null, accessor.getPropertyValue("list[3]")); - assertEquals(tb1, accessor.getPropertyValue("list[4]")); - assertEquals(tb1, accessor.getPropertyValue("map[\"key1\"]")); - assertEquals(tb0, accessor.getPropertyValue("map['key2']")); - assertEquals(tb4, accessor.getPropertyValue("map[\"key5\"]")); - assertEquals(tb5, accessor.getPropertyValue("map['key9']")); + assertThat(target.getArray()[0]).isEqualTo(tb5); + assertThat(target.getArray()[1]).isEqualTo(tb4); + assertThat((target.getList().get(0))).isEqualTo(tb3); + assertThat((target.getList().get(1))).isEqualTo(tb2); + assertThat((target.getList().get(2))).isEqualTo(tb0); + assertThat((target.getList().get(3))).isEqualTo(null); + assertThat((target.getList().get(4))).isEqualTo(tb1); + assertThat((target.getMap().get("key1"))).isEqualTo(tb1); + assertThat((target.getMap().get("key2"))).isEqualTo(tb0); + assertThat((target.getMap().get("key5"))).isEqualTo(tb4); + assertThat((target.getMap().get("key9"))).isEqualTo(tb5); + assertThat(accessor.getPropertyValue("array[0]")).isEqualTo(tb5); + assertThat(accessor.getPropertyValue("array[1]")).isEqualTo(tb4); + assertThat(accessor.getPropertyValue("list[0]")).isEqualTo(tb3); + assertThat(accessor.getPropertyValue("list[1]")).isEqualTo(tb2); + assertThat(accessor.getPropertyValue("list[2]")).isEqualTo(tb0); + assertThat(accessor.getPropertyValue("list[3]")).isEqualTo(null); + assertThat(accessor.getPropertyValue("list[4]")).isEqualTo(tb1); + assertThat(accessor.getPropertyValue("map[\"key1\"]")).isEqualTo(tb1); + assertThat(accessor.getPropertyValue("map['key2']")).isEqualTo(tb0); + assertThat(accessor.getPropertyValue("map[\"key5\"]")).isEqualTo(tb4); + assertThat(accessor.getPropertyValue("map['key9']")).isEqualTo(tb5); } @Test @@ -1623,7 +1618,7 @@ public abstract class AbstractPropertyAccessorTests { Person target = createPerson("John", "Paris", "FR"); AbstractPropertyAccessor accessor = createAccessor(target); - assertEquals(String.class, accessor.getPropertyType("address.city")); + assertThat(accessor.getPropertyType("address.city")).isEqualTo(String.class); } @Test @@ -1654,15 +1649,15 @@ public abstract class AbstractPropertyAccessorTests { public void propertyTypeIndexedProperty() { IndexedTestBean target = new IndexedTestBean(); AbstractPropertyAccessor accessor = createAccessor(target); - assertEquals(null, accessor.getPropertyType("map[key0]")); + assertThat(accessor.getPropertyType("map[key0]")).isEqualTo(null); accessor = createAccessor(target); accessor.setPropertyValue("map[key0]", "my String"); - assertEquals(String.class, accessor.getPropertyType("map[key0]")); + assertThat(accessor.getPropertyType("map[key0]")).isEqualTo(String.class); accessor = createAccessor(target); accessor.registerCustomEditor(String.class, "map[key0]", new StringTrimmerEditor(false)); - assertEquals(String.class, accessor.getPropertyType("map[key0]")); + assertThat(accessor.getPropertyType("map[key0]")).isEqualTo(String.class); } @Test @@ -1670,7 +1665,7 @@ public abstract class AbstractPropertyAccessorTests { Spr10115Bean target = new Spr10115Bean(); AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("prop1", "val1"); - assertEquals("val1", Spr10115Bean.prop1); + assertThat(Spr10115Bean.prop1).isEqualTo("val1"); } @Test @@ -1678,7 +1673,7 @@ public abstract class AbstractPropertyAccessorTests { Spr13837Bean target = new Spr13837Bean(); AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("something", 42); - assertEquals(Integer.valueOf(42), target.something); + assertThat(target.something).isEqualTo(Integer.valueOf(42)); } diff --git a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyValuesTests.java b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyValuesTests.java index 0cdd6f4d7df..9f3bd08ec9f 100644 --- a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyValuesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyValuesTests.java @@ -19,7 +19,7 @@ package org.springframework.beans; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -31,11 +31,12 @@ public abstract class AbstractPropertyValuesTests { * Must contain: forname=Tony surname=Blair age=50 */ protected void doTestTony(PropertyValues pvs) { - assertTrue("Contains 3", pvs.getPropertyValues().length == 3); - assertTrue("Contains forname", pvs.contains("forname")); - assertTrue("Contains surname", pvs.contains("surname")); - assertTrue("Contains age", pvs.contains("age")); - assertTrue("Doesn't contain tory", !pvs.contains("tory")); + assertThat(pvs.getPropertyValues().length == 3).as("Contains 3").isTrue(); + assertThat(pvs.contains("forname")).as("Contains forname").isTrue(); + assertThat(pvs.contains("surname")).as("Contains surname").isTrue(); + assertThat(pvs.contains("age")).as("Contains age").isTrue(); + boolean condition1 = !pvs.contains("tory"); + assertThat(condition1).as("Doesn't contain tory").isTrue(); PropertyValue[] ps = pvs.getPropertyValues(); Map m = new HashMap<>(); @@ -44,12 +45,13 @@ public abstract class AbstractPropertyValuesTests { m.put("age", "50"); for (int i = 0; i < ps.length; i++) { Object val = m.get(ps[i].getName()); - assertTrue("Can't have unexpected value", val != null); - assertTrue("Val i string", val instanceof String); - assertTrue("val matches expected", val.equals(ps[i].getValue())); + assertThat(val != null).as("Can't have unexpected value").isTrue(); + boolean condition = val instanceof String; + assertThat(condition).as("Val i string").isTrue(); + assertThat(val.equals(ps[i].getValue())).as("val matches expected").isTrue(); m.remove(ps[i].getName()); } - assertTrue("Map size is 0", m.size() == 0); + assertThat(m.size() == 0).as("Map size is 0").isTrue(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java index d1a77392241..df45480893c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java @@ -33,12 +33,9 @@ import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.tests.sample.beans.ITestBean; 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.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}. @@ -68,18 +65,18 @@ public class BeanUtilsTests { Constructor ctor = BeanWithNullableTypes.class.getDeclaredConstructor( Integer.class, Boolean.class, String.class); BeanWithNullableTypes bean = BeanUtils.instantiateClass(ctor, null, null, "foo"); - assertNull(bean.getCounter()); - assertNull(bean.isFlag()); - assertEquals("foo", bean.getValue()); + assertThat(bean.getCounter()).isNull(); + assertThat(bean.isFlag()).isNull(); + assertThat(bean.getValue()).isEqualTo("foo"); } @Test // gh-22531 public void testInstantiateClassWithOptionalPrimitiveType() throws NoSuchMethodException { Constructor ctor = BeanWithPrimitiveTypes.class.getDeclaredConstructor(int.class, boolean.class, String.class); BeanWithPrimitiveTypes bean = BeanUtils.instantiateClass(ctor, null, null, "foo"); - assertEquals(0, bean.getCounter()); - assertEquals(false, bean.isFlag()); - assertEquals("foo", bean.getValue()); + assertThat(bean.getCounter()).isEqualTo(0); + assertThat(bean.isFlag()).isEqualTo(false); + assertThat(bean.getValue()).isEqualTo("foo"); } @Test // gh-22531 @@ -93,8 +90,8 @@ public class BeanUtilsTests { public void testGetPropertyDescriptors() throws Exception { PropertyDescriptor[] actual = Introspector.getBeanInfo(TestBean.class).getPropertyDescriptors(); PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(TestBean.class); - assertNotNull("Descriptors should not be null", descriptors); - assertEquals("Invalid number of descriptors returned", actual.length, descriptors.length); + assertThat(descriptors).as("Descriptors should not be null").isNotNull(); + assertThat(descriptors.length).as("Invalid number of descriptors returned").isEqualTo(actual.length); } @Test @@ -102,15 +99,15 @@ public class BeanUtilsTests { PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(ContainerBean.class); for (PropertyDescriptor descriptor : descriptors) { if ("containedBeans".equals(descriptor.getName())) { - assertTrue("Property should be an array", descriptor.getPropertyType().isArray()); - assertEquals(descriptor.getPropertyType().getComponentType(), ContainedBean.class); + assertThat(descriptor.getPropertyType().isArray()).as("Property should be an array").isTrue(); + assertThat(ContainedBean.class).isEqualTo(descriptor.getPropertyType().getComponentType()); } } } @Test public void testFindEditorByConvention() { - assertEquals(ResourceEditor.class, BeanUtils.findEditorByConvention(Resource.class).getClass()); + assertThat(BeanUtils.findEditorByConvention(Resource.class).getClass()).isEqualTo(ResourceEditor.class); } @Test @@ -120,13 +117,13 @@ public class BeanUtilsTests { tb.setAge(32); tb.setTouchy("touchy"); TestBean tb2 = new TestBean(); - assertTrue("Name empty", tb2.getName() == null); - assertTrue("Age empty", tb2.getAge() == 0); - assertTrue("Touchy empty", tb2.getTouchy() == null); + assertThat(tb2.getName() == null).as("Name empty").isTrue(); + assertThat(tb2.getAge() == 0).as("Age empty").isTrue(); + assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue(); BeanUtils.copyProperties(tb, tb2); - assertTrue("Name copied", tb2.getName().equals(tb.getName())); - assertTrue("Age copied", tb2.getAge() == tb.getAge()); - assertTrue("Touchy copied", tb2.getTouchy().equals(tb.getTouchy())); + assertThat(tb2.getName().equals(tb.getName())).as("Name copied").isTrue(); + assertThat(tb2.getAge() == tb.getAge()).as("Age copied").isTrue(); + assertThat(tb2.getTouchy().equals(tb.getTouchy())).as("Touchy copied").isTrue(); } @Test @@ -136,13 +133,13 @@ public class BeanUtilsTests { tb.setAge(32); tb.setTouchy("touchy"); TestBean tb2 = new TestBean(); - assertTrue("Name empty", tb2.getName() == null); - assertTrue("Age empty", tb2.getAge() == 0); - assertTrue("Touchy empty", tb2.getTouchy() == null); + assertThat(tb2.getName() == null).as("Name empty").isTrue(); + assertThat(tb2.getAge() == 0).as("Age empty").isTrue(); + assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue(); BeanUtils.copyProperties(tb, tb2); - assertTrue("Name copied", tb2.getName().equals(tb.getName())); - assertTrue("Age copied", tb2.getAge() == tb.getAge()); - assertTrue("Touchy copied", tb2.getTouchy().equals(tb.getTouchy())); + assertThat(tb2.getName().equals(tb.getName())).as("Name copied").isTrue(); + assertThat(tb2.getAge() == tb.getAge()).as("Age copied").isTrue(); + assertThat(tb2.getTouchy().equals(tb.getTouchy())).as("Touchy copied").isTrue(); } @Test @@ -152,49 +149,49 @@ public class BeanUtilsTests { tb.setAge(32); tb.setTouchy("touchy"); DerivedTestBean tb2 = new DerivedTestBean(); - assertTrue("Name empty", tb2.getName() == null); - assertTrue("Age empty", tb2.getAge() == 0); - assertTrue("Touchy empty", tb2.getTouchy() == null); + assertThat(tb2.getName() == null).as("Name empty").isTrue(); + assertThat(tb2.getAge() == 0).as("Age empty").isTrue(); + assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue(); BeanUtils.copyProperties(tb, tb2); - assertTrue("Name copied", tb2.getName().equals(tb.getName())); - assertTrue("Age copied", tb2.getAge() == tb.getAge()); - assertTrue("Touchy copied", tb2.getTouchy().equals(tb.getTouchy())); + assertThat(tb2.getName().equals(tb.getName())).as("Name copied").isTrue(); + assertThat(tb2.getAge() == tb.getAge()).as("Age copied").isTrue(); + assertThat(tb2.getTouchy().equals(tb.getTouchy())).as("Touchy copied").isTrue(); } @Test public void testCopyPropertiesWithEditable() throws Exception { TestBean tb = new TestBean(); - assertTrue("Name empty", tb.getName() == null); + assertThat(tb.getName() == null).as("Name empty").isTrue(); tb.setAge(32); tb.setTouchy("bla"); TestBean tb2 = new TestBean(); tb2.setName("rod"); - assertTrue("Age empty", tb2.getAge() == 0); - assertTrue("Touchy empty", tb2.getTouchy() == null); + assertThat(tb2.getAge() == 0).as("Age empty").isTrue(); + assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue(); // "touchy" should not be copied: it's not defined in ITestBean BeanUtils.copyProperties(tb, tb2, ITestBean.class); - assertTrue("Name copied", tb2.getName() == null); - assertTrue("Age copied", tb2.getAge() == 32); - assertTrue("Touchy still empty", tb2.getTouchy() == null); + assertThat(tb2.getName() == null).as("Name copied").isTrue(); + assertThat(tb2.getAge() == 32).as("Age copied").isTrue(); + assertThat(tb2.getTouchy() == null).as("Touchy still empty").isTrue(); } @Test public void testCopyPropertiesWithIgnore() throws Exception { TestBean tb = new TestBean(); - assertTrue("Name empty", tb.getName() == null); + assertThat(tb.getName() == null).as("Name empty").isTrue(); tb.setAge(32); tb.setTouchy("bla"); TestBean tb2 = new TestBean(); tb2.setName("rod"); - assertTrue("Age empty", tb2.getAge() == 0); - assertTrue("Touchy empty", tb2.getTouchy() == null); + assertThat(tb2.getAge() == 0).as("Age empty").isTrue(); + assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue(); // "spouse", "touchy", "age" should not be copied BeanUtils.copyProperties(tb, tb2, "spouse", "touchy", "age"); - assertTrue("Name copied", tb2.getName() == null); - assertTrue("Age still empty", tb2.getAge() == 0); - assertTrue("Touchy still empty", tb2.getTouchy() == null); + assertThat(tb2.getName() == null).as("Name copied").isTrue(); + assertThat(tb2.getAge() == 0).as("Age still empty").isTrue(); + assertThat(tb2.getTouchy() == null).as("Touchy still empty").isTrue(); } @Test @@ -203,7 +200,7 @@ public class BeanUtilsTests { source.setName("name"); TestBean target = new TestBean(); BeanUtils.copyProperties(source, target, "specialProperty"); - assertEquals(target.getName(), "name"); + assertThat("name").isEqualTo(target.getName()); } @Test @@ -214,9 +211,9 @@ public class BeanUtilsTests { source.setFlag2(true); InvalidProperty target = new InvalidProperty(); BeanUtils.copyProperties(source, target); - assertEquals("name", target.getName()); - assertTrue(target.getFlag1()); - assertTrue(target.getFlag2()); + assertThat(target.getName()).isEqualTo("name"); + assertThat((boolean) target.getFlag1()).isTrue(); + assertThat(target.getFlag2()).isTrue(); } @Test @@ -242,7 +239,7 @@ public class BeanUtilsTests { public void testResolveWithAndWithoutArgList() throws Exception { Method desiredMethod = MethodSignatureBean.class.getMethod("doSomethingElse", String.class, int.class); assertSignatureEquals(desiredMethod, "doSomethingElse"); - assertNull(BeanUtils.resolveSignature("doSomethingElse()", MethodSignatureBean.class)); + assertThat(BeanUtils.resolveSignature("doSomethingElse()", MethodSignatureBean.class)).isNull(); } @Test @@ -280,17 +277,16 @@ public class BeanUtilsTests { PropertyDescriptor[] descrs = BeanUtils.getPropertyDescriptors(Bean.class); PropertyDescriptor keyDescr = BeanUtils.getPropertyDescriptor(Bean.class, "value"); - assertEquals(String.class, keyDescr.getPropertyType()); + assertThat(keyDescr.getPropertyType()).isEqualTo(String.class); for (PropertyDescriptor propertyDescriptor : descrs) { if (propertyDescriptor.getName().equals(keyDescr.getName())) { - assertEquals(propertyDescriptor.getName() + " has unexpected type", - keyDescr.getPropertyType(), propertyDescriptor.getPropertyType()); + assertThat(propertyDescriptor.getPropertyType()).as(propertyDescriptor.getName() + " has unexpected type").isEqualTo(keyDescr.getPropertyType()); } } } private void assertSignatureEquals(Method desiredMethod, String signature) { - assertEquals(desiredMethod, BeanUtils.resolveSignature(signature, MethodSignatureBean.class)); + assertThat(BeanUtils.resolveSignature(signature, MethodSignatureBean.class)).isEqualTo(desiredMethod); } diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java index 57eb8760378..16a08701d83 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java @@ -24,9 +24,6 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; 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 @@ -47,13 +44,13 @@ public class BeanWrapperAutoGrowingTests { @Test public void getPropertyValueNullValueInNestedPath() { - assertNull(wrapper.getPropertyValue("nested.prop")); + assertThat(wrapper.getPropertyValue("nested.prop")).isNull(); } @Test public void setPropertyValueNullValueInNestedPath() { wrapper.setPropertyValue("nested.prop", "test"); - assertEquals("test", bean.getNested().getProp()); + assertThat(bean.getNested().getProp()).isEqualTo("test"); } @Test @@ -65,20 +62,25 @@ public class BeanWrapperAutoGrowingTests { @Test public void getPropertyValueAutoGrowArray() { assertNotNull(wrapper.getPropertyValue("array[0]")); - assertEquals(1, bean.getArray().length); + assertThat(bean.getArray().length).isEqualTo(1); assertThat(bean.getArray()[0]).isInstanceOf(Bean.class); } + private void assertNotNull(Object propertyValue) { + assertThat(propertyValue).isNotNull(); + } + + @Test public void setPropertyValueAutoGrowArray() { wrapper.setPropertyValue("array[0].prop", "test"); - assertEquals("test", bean.getArray()[0].getProp()); + assertThat(bean.getArray()[0].getProp()).isEqualTo("test"); } @Test public void getPropertyValueAutoGrowArrayBySeveralElements() { 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()[1]).isInstanceOf(Bean.class); assertThat(bean.getArray()[2]).isInstanceOf(Bean.class); @@ -93,27 +95,27 @@ public class BeanWrapperAutoGrowingTests { @Test public void getPropertyValueAutoGrowMultiDimensionalArray() { 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); } @Test public void getPropertyValueAutoGrowList() { assertNotNull(wrapper.getPropertyValue("list[0]")); - assertEquals(1, bean.getList().size()); + assertThat(bean.getList().size()).isEqualTo(1); assertThat(bean.getList().get(0)).isInstanceOf(Bean.class); } @Test public void setPropertyValueAutoGrowList() { wrapper.setPropertyValue("list[0].prop", "test"); - assertEquals("test", bean.getList().get(0).getProp()); + assertThat(bean.getList().get(0).getProp()).isEqualTo("test"); } @Test public void getPropertyValueAutoGrowListBySeveralElements() { 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(1)).isInstanceOf(Bean.class); assertThat(bean.getList().get(2)).isInstanceOf(Bean.class); @@ -136,7 +138,7 @@ public class BeanWrapperAutoGrowingTests { @Test public void getPropertyValueAutoGrowMultiDimensionalList() { 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); } diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java index cf69031275f..0b2457caa67 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java @@ -25,9 +25,7 @@ import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.tests.sample.beans.CustomEnum; import org.springframework.tests.sample.beans.GenericBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -40,7 +38,7 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("customEnum", "VALUE_1"); - assertEquals(CustomEnum.VALUE_1, gb.getCustomEnum()); + assertThat(gb.getCustomEnum()).isEqualTo(CustomEnum.VALUE_1); } @Test @@ -48,7 +46,7 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("customEnum", null); - assertEquals(null, gb.getCustomEnum()); + assertThat(gb.getCustomEnum()).isEqualTo(null); } @Test @@ -56,7 +54,7 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("customEnum", ""); - assertEquals(null, gb.getCustomEnum()); + assertThat(gb.getCustomEnum()).isEqualTo(null); } @Test @@ -64,8 +62,8 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("customEnumArray", "VALUE_1"); - assertEquals(1, gb.getCustomEnumArray().length); - assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]); + assertThat(gb.getCustomEnumArray().length).isEqualTo(1); + assertThat(gb.getCustomEnumArray()[0]).isEqualTo(CustomEnum.VALUE_1); } @Test @@ -73,9 +71,9 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("customEnumArray", new String[] {"VALUE_1", "VALUE_2"}); - assertEquals(2, gb.getCustomEnumArray().length); - assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]); - assertEquals(CustomEnum.VALUE_2, gb.getCustomEnumArray()[1]); + assertThat(gb.getCustomEnumArray().length).isEqualTo(2); + assertThat(gb.getCustomEnumArray()[0]).isEqualTo(CustomEnum.VALUE_1); + assertThat(gb.getCustomEnumArray()[1]).isEqualTo(CustomEnum.VALUE_2); } @Test @@ -83,9 +81,9 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("customEnumArray", "VALUE_1,VALUE_2"); - assertEquals(2, gb.getCustomEnumArray().length); - assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]); - assertEquals(CustomEnum.VALUE_2, gb.getCustomEnumArray()[1]); + assertThat(gb.getCustomEnumArray().length).isEqualTo(2); + assertThat(gb.getCustomEnumArray()[0]).isEqualTo(CustomEnum.VALUE_1); + assertThat(gb.getCustomEnumArray()[1]).isEqualTo(CustomEnum.VALUE_2); } @Test @@ -93,8 +91,8 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("customEnumSet", "VALUE_1"); - assertEquals(1, gb.getCustomEnumSet().size()); - assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)); + assertThat(gb.getCustomEnumSet().size()).isEqualTo(1); + assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)).isTrue(); } @Test @@ -102,9 +100,9 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("customEnumSet", new String[] {"VALUE_1", "VALUE_2"}); - assertEquals(2, gb.getCustomEnumSet().size()); - assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)); - assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)); + assertThat(gb.getCustomEnumSet().size()).isEqualTo(2); + assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)).isTrue(); + assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)).isTrue(); } @Test @@ -112,9 +110,9 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("customEnumSet", "VALUE_1,VALUE_2"); - assertEquals(2, gb.getCustomEnumSet().size()); - assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)); - assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)); + assertThat(gb.getCustomEnumSet().size()).isEqualTo(2); + assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)).isTrue(); + assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)).isTrue(); } @Test @@ -122,9 +120,9 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("customEnumSetMismatch", new String[] {"VALUE_1", "VALUE_2"}); - assertEquals(2, gb.getCustomEnumSet().size()); - assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)); - assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)); + assertThat(gb.getCustomEnumSet().size()).isEqualTo(2); + assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)).isTrue(); + assertThat(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)).isTrue(); } @Test @@ -132,11 +130,11 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setConversionService(new DefaultConversionService()); - assertNull(gb.getStandardEnumSet()); + assertThat(gb.getStandardEnumSet()).isNull(); bw.setPropertyValue("standardEnumSet", new String[] {"VALUE_1", "VALUE_2"}); - assertEquals(2, gb.getStandardEnumSet().size()); - assertTrue(gb.getStandardEnumSet().contains(CustomEnum.VALUE_1)); - assertTrue(gb.getStandardEnumSet().contains(CustomEnum.VALUE_2)); + assertThat(gb.getStandardEnumSet().size()).isEqualTo(2); + assertThat(gb.getStandardEnumSet().contains(CustomEnum.VALUE_1)).isTrue(); + assertThat(gb.getStandardEnumSet().contains(CustomEnum.VALUE_2)).isTrue(); } @Test @@ -144,9 +142,9 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setAutoGrowNestedPaths(true); - assertNull(gb.getStandardEnumSet()); + assertThat(gb.getStandardEnumSet()).isNull(); bw.getPropertyValue("standardEnumSet.class"); - assertEquals(0, gb.getStandardEnumSet().size()); + assertThat(gb.getStandardEnumSet().size()).isEqualTo(0); } @Test @@ -154,14 +152,14 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setConversionService(new DefaultConversionService()); - assertNull(gb.getStandardEnumMap()); + assertThat(gb.getStandardEnumMap()).isNull(); Map map = new LinkedHashMap<>(); map.put("VALUE_1", 1); map.put("VALUE_2", 2); bw.setPropertyValue("standardEnumMap", map); - assertEquals(2, gb.getStandardEnumMap().size()); - assertEquals(new Integer(1), gb.getStandardEnumMap().get(CustomEnum.VALUE_1)); - assertEquals(new Integer(2), gb.getStandardEnumMap().get(CustomEnum.VALUE_2)); + assertThat(gb.getStandardEnumMap().size()).isEqualTo(2); + assertThat(gb.getStandardEnumMap().get(CustomEnum.VALUE_1)).isEqualTo(new Integer(1)); + assertThat(gb.getStandardEnumMap().get(CustomEnum.VALUE_2)).isEqualTo(new Integer(2)); } @Test @@ -169,10 +167,10 @@ public class BeanWrapperEnumTests { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setAutoGrowNestedPaths(true); - assertNull(gb.getStandardEnumMap()); + assertThat(gb.getStandardEnumMap()).isNull(); bw.setPropertyValue("standardEnumMap[VALUE_1]", 1); - assertEquals(1, gb.getStandardEnumMap().size()); - assertEquals(new Integer(1), gb.getStandardEnumMap().get(CustomEnum.VALUE_1)); + assertThat(gb.getStandardEnumMap().size()).isEqualTo(1); + assertThat(gb.getStandardEnumMap().get(CustomEnum.VALUE_1)).isEqualTo(new Integer(1)); } @Test @@ -180,7 +178,7 @@ public class BeanWrapperEnumTests { NonPublicEnumHolder holder = new NonPublicEnumHolder(); BeanWrapper bw = new BeanWrapperImpl(holder); bw.setPropertyValue("nonPublicEnum", "VALUE_1"); - assertEquals(NonPublicEnum.VALUE_1, holder.getNonPublicEnum()); + assertThat(holder.getNonPublicEnum()).isEqualTo(NonPublicEnum.VALUE_1); } diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java index 8768b3cf124..b69082804b0 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java @@ -39,9 +39,8 @@ import org.springframework.tests.sample.beans.GenericIntegerBean; import org.springframework.tests.sample.beans.GenericSetOfIntegerBean; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -58,8 +57,8 @@ public class BeanWrapperGenericsTests { input.add("4"); input.add("5"); bw.setPropertyValue("integerSet", input); - assertTrue(gb.getIntegerSet().contains(new Integer(4))); - assertTrue(gb.getIntegerSet().contains(new Integer(5))); + assertThat(gb.getIntegerSet().contains(new Integer(4))).isTrue(); + assertThat(gb.getIntegerSet().contains(new Integer(5))).isTrue(); } @Test @@ -71,8 +70,8 @@ public class BeanWrapperGenericsTests { input.add("4"); input.add("5"); bw.setPropertyValue("numberSet", input); - assertTrue(gb.getNumberSet().contains(new Integer(4))); - assertTrue(gb.getNumberSet().contains(new Integer(5))); + assertThat(gb.getNumberSet().contains(new Integer(4))).isTrue(); + assertThat(gb.getNumberSet().contains(new Integer(5))).isTrue(); } @Test @@ -94,8 +93,8 @@ public class BeanWrapperGenericsTests { input.add("http://localhost:8080"); input.add("http://localhost:9090"); bw.setPropertyValue("resourceList", input); - assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0)); - assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1)); + assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080")); + assertThat(gb.getResourceList().get(1)).isEqualTo(new UrlResource("http://localhost:9090")); } @Test @@ -104,7 +103,7 @@ public class BeanWrapperGenericsTests { gb.setResourceList(new ArrayList<>()); BeanWrapper bw = new BeanWrapperImpl(gb); 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 @@ -115,8 +114,8 @@ public class BeanWrapperGenericsTests { input.put("4", "5"); input.put("6", "7"); bw.setPropertyValue("shortMap", input); - assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); - assertEquals(new Integer(7), gb.getShortMap().get(new Short("6"))); + assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5)); + assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(new Integer(7)); } @Test @@ -125,8 +124,8 @@ public class BeanWrapperGenericsTests { gb.setShortMap(new HashMap<>()); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("shortMap[4]", "5"); - assertEquals(new Integer(5), bw.getPropertyValue("shortMap[4]")); - assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); + assertThat(bw.getPropertyValue("shortMap[4]")).isEqualTo(new Integer(5)); + assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5)); } @Test @@ -137,8 +136,8 @@ public class BeanWrapperGenericsTests { input.put("4", "5"); input.put("6", "7"); bw.setPropertyValue("longMap", input); - assertEquals("5", gb.getLongMap().get(new Long("4"))); - assertEquals("7", gb.getLongMap().get(new Long("6"))); + assertThat(gb.getLongMap().get(new Long("4"))).isEqualTo("5"); + assertThat(gb.getLongMap().get(new Long("6"))).isEqualTo("7"); } @Test @@ -147,8 +146,8 @@ public class BeanWrapperGenericsTests { gb.setLongMap(new HashMap()); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("longMap[4]", "5"); - assertEquals("5", gb.getLongMap().get(new Long("4"))); - assertEquals("5", bw.getPropertyValue("longMap[4]")); + assertThat(gb.getLongMap().get(new Long("4"))).isEqualTo("5"); + assertThat(bw.getPropertyValue("longMap[4]")).isEqualTo("5"); } @Test @@ -164,8 +163,10 @@ public class BeanWrapperGenericsTests { value2.add(Boolean.TRUE); input.put("2", value2); bw.setPropertyValue("collectionMap", input); - assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet); - assertTrue(gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList); + boolean condition1 = gb.getCollectionMap().get(new Integer(1)) instanceof HashSet; + assertThat(condition1).isTrue(); + boolean condition = gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList; + assertThat(condition).isTrue(); } @Test @@ -177,7 +178,8 @@ public class BeanWrapperGenericsTests { HashSet value1 = new HashSet<>(); value1.add(new Integer(1)); 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 @@ -188,8 +190,8 @@ public class BeanWrapperGenericsTests { input.setProperty("4", "5"); input.setProperty("6", "7"); bw.setPropertyValue("shortMap", input); - assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); - assertEquals(new Integer(7), gb.getShortMap().get(new Short("6"))); + assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5)); + assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(new Integer(7)); } @Test @@ -200,8 +202,8 @@ public class BeanWrapperGenericsTests { gb.setListOfLists(list); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("listOfLists[0][0]", new Integer(5)); - assertEquals(new Integer(5), bw.getPropertyValue("listOfLists[0][0]")); - assertEquals(new Integer(5), gb.getListOfLists().get(0).get(0)); + assertThat(bw.getPropertyValue("listOfLists[0][0]")).isEqualTo(new Integer(5)); + assertThat(gb.getListOfLists().get(0).get(0)).isEqualTo(new Integer(5)); } @Test @@ -212,8 +214,8 @@ public class BeanWrapperGenericsTests { gb.setListOfLists(list); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("listOfLists[0][0]", "5"); - assertEquals(new Integer(5), bw.getPropertyValue("listOfLists[0][0]")); - assertEquals(new Integer(5), gb.getListOfLists().get(0).get(0)); + assertThat(bw.getPropertyValue("listOfLists[0][0]")).isEqualTo(new Integer(5)); + assertThat(gb.getListOfLists().get(0).get(0)).isEqualTo(new Integer(5)); } @Test @@ -224,8 +226,8 @@ public class BeanWrapperGenericsTests { gb.setListOfArrays(list); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("listOfArrays[0][1]", "str3 "); - assertEquals("str3 ", bw.getPropertyValue("listOfArrays[0][1]")); - assertEquals("str3 ", gb.getListOfArrays().get(0)[1]); + assertThat(bw.getPropertyValue("listOfArrays[0][1]")).isEqualTo("str3 "); + assertThat(gb.getListOfArrays().get(0)[1]).isEqualTo("str3 "); } @Test @@ -237,8 +239,8 @@ public class BeanWrapperGenericsTests { BeanWrapper bw = new BeanWrapperImpl(gb); bw.registerCustomEditor(String.class, new StringTrimmerEditor(false)); bw.setPropertyValue("listOfArrays[0][1]", "str3 "); - assertEquals("str3", bw.getPropertyValue("listOfArrays[0][1]")); - assertEquals("str3", gb.getListOfArrays().get(0)[1]); + assertThat(bw.getPropertyValue("listOfArrays[0][1]")).isEqualTo("str3"); + assertThat(gb.getListOfArrays().get(0)[1]).isEqualTo("str3"); } @Test @@ -249,8 +251,8 @@ public class BeanWrapperGenericsTests { gb.setListOfMaps(list); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("listOfMaps[0][10]", new Long(5)); - assertEquals(new Long(5), bw.getPropertyValue("listOfMaps[0][10]")); - assertEquals(new Long(5), gb.getListOfMaps().get(0).get(10)); + assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(new Long(5)); + assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(new Long(5)); } @Test @@ -261,8 +263,8 @@ public class BeanWrapperGenericsTests { gb.setListOfMaps(list); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("listOfMaps[0][10]", "5"); - assertEquals(new Long(5), bw.getPropertyValue("listOfMaps[0][10]")); - assertEquals(new Long(5), gb.getListOfMaps().get(0).get(10)); + assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(new Long(5)); + assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(new Long(5)); } @Test @@ -273,8 +275,8 @@ public class BeanWrapperGenericsTests { gb.setMapOfMaps(map); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("mapOfMaps[mykey][10]", new Long(5)); - assertEquals(new Long(5), bw.getPropertyValue("mapOfMaps[mykey][10]")); - assertEquals(new Long(5), gb.getMapOfMaps().get("mykey").get(10)); + assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(new Long(5)); + assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(new Long(5)); } @Test @@ -285,8 +287,8 @@ public class BeanWrapperGenericsTests { gb.setMapOfMaps(map); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("mapOfMaps[mykey][10]", "5"); - assertEquals(new Long(5), bw.getPropertyValue("mapOfMaps[mykey][10]")); - assertEquals(new Long(5), gb.getMapOfMaps().get("mykey").get(10)); + assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(new Long(5)); + assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(new Long(5)); } @Test @@ -297,8 +299,8 @@ public class BeanWrapperGenericsTests { gb.setMapOfLists(map); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("mapOfLists[1][0]", new Integer(5)); - assertEquals(new Integer(5), bw.getPropertyValue("mapOfLists[1][0]")); - assertEquals(new Integer(5), gb.getMapOfLists().get(new Integer(1)).get(0)); + assertThat(bw.getPropertyValue("mapOfLists[1][0]")).isEqualTo(new Integer(5)); + assertThat(gb.getMapOfLists().get(new Integer(1)).get(0)).isEqualTo(new Integer(5)); } @Test @@ -309,8 +311,8 @@ public class BeanWrapperGenericsTests { gb.setMapOfLists(map); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("mapOfLists[1][0]", "5"); - assertEquals(new Integer(5), bw.getPropertyValue("mapOfLists[1][0]")); - assertEquals(new Integer(5), gb.getMapOfLists().get(new Integer(1)).get(0)); + assertThat(bw.getPropertyValue("mapOfLists[1][0]")).isEqualTo(new Integer(5)); + assertThat(gb.getMapOfLists().get(new Integer(1)).get(0)).isEqualTo(new Integer(5)); } @Test @@ -323,7 +325,8 @@ public class BeanWrapperGenericsTests { bw.setPropertyValue("mapOfInteger", map); Object obj = gb.getMapOfInteger().get("testKey"); - assertTrue(obj instanceof Integer); + boolean condition = obj instanceof Integer; + assertThat(condition).isTrue(); } @Test @@ -337,8 +340,9 @@ public class BeanWrapperGenericsTests { bw.setPropertyValue("mapOfListOfInteger", map); Object obj = gb.getMapOfListOfInteger().get("testKey").get(0); - assertTrue(obj instanceof Integer); - assertEquals(1, ((Integer) obj).intValue()); + boolean condition = obj instanceof Integer; + assertThat(condition).isTrue(); + assertThat(((Integer) obj).intValue()).isEqualTo(1); } @Test @@ -353,8 +357,9 @@ public class BeanWrapperGenericsTests { bw.setPropertyValue("listOfMapOfInteger", list); Object obj = gb.getListOfMapOfInteger().get(0).get("testKey"); - assertTrue(obj instanceof Integer); - assertEquals(5, ((Integer) obj).intValue()); + boolean condition = obj instanceof Integer; + assertThat(condition).isTrue(); + assertThat(((Integer) obj).intValue()).isEqualTo(5); } @Test @@ -368,8 +373,9 @@ public class BeanWrapperGenericsTests { bw.setPropertyValue("mapOfListOfListOfInteger", map); Object obj = gb.getMapOfListOfListOfInteger().get("testKey").get(0).get(0); - assertTrue(obj instanceof Integer); - assertEquals(1, ((Integer) obj).intValue()); + boolean condition = obj instanceof Integer; + assertThat(condition).isTrue(); + assertThat(((Integer) obj).intValue()).isEqualTo(1); } @Test @@ -385,8 +391,8 @@ public class BeanWrapperGenericsTests { BeanWrapper bw = new BeanWrapperImpl(holder); bw.setPropertyValue("genericMap", inputMap); - assertEquals(new Integer(1), holder.getGenericMap().keySet().iterator().next().get(0)); - assertEquals(new Long(10), holder.getGenericMap().values().iterator().next().get(0)); + assertThat(holder.getGenericMap().keySet().iterator().next().get(0)).isEqualTo(new Integer(1)); + assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); } @Test @@ -402,8 +408,8 @@ public class BeanWrapperGenericsTests { BeanWrapper bw = new BeanWrapperImpl(holder); bw.setPropertyValue("genericMap", inputMap); - assertEquals(new Integer(1), holder.getGenericMap().keySet().iterator().next().get(0)); - assertEquals(new Long(10), holder.getGenericMap().values().iterator().next().get(0)); + assertThat(holder.getGenericMap().keySet().iterator().next().get(0)).isEqualTo(new Integer(1)); + assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); } @Test @@ -415,8 +421,8 @@ public class BeanWrapperGenericsTests { BeanWrapper bw = new BeanWrapperImpl(holder); bw.setPropertyValue("genericIndexedMap[1]", inputValue); - assertEquals(new Integer(1), holder.getGenericIndexedMap().keySet().iterator().next()); - assertEquals(new Long(10), holder.getGenericIndexedMap().values().iterator().next().get(0)); + assertThat(holder.getGenericIndexedMap().keySet().iterator().next()).isEqualTo(new Integer(1)); + assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); } @Test @@ -428,8 +434,8 @@ public class BeanWrapperGenericsTests { BeanWrapper bw = new BeanWrapperImpl(holder); bw.setPropertyValue("genericIndexedMap[1]", inputValue); - assertEquals(new Integer(1), holder.getGenericIndexedMap().keySet().iterator().next()); - assertEquals(new Long(10), holder.getGenericIndexedMap().values().iterator().next().get(0)); + assertThat(holder.getGenericIndexedMap().keySet().iterator().next()).isEqualTo(new Integer(1)); + assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); } @Test @@ -441,8 +447,8 @@ public class BeanWrapperGenericsTests { BeanWrapper bw = new BeanWrapperImpl(holder); bw.setPropertyValue("derivedIndexedMap[1]", inputValue); - assertEquals(new Integer(1), holder.getDerivedIndexedMap().keySet().iterator().next()); - assertEquals(new Long(10), holder.getDerivedIndexedMap().values().iterator().next().get(0)); + assertThat(holder.getDerivedIndexedMap().keySet().iterator().next()).isEqualTo(new Integer(1)); + assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); } @Test @@ -454,8 +460,8 @@ public class BeanWrapperGenericsTests { BeanWrapper bw = new BeanWrapperImpl(holder); bw.setPropertyValue("derivedIndexedMap[1]", inputValue); - assertEquals(new Integer(1), holder.getDerivedIndexedMap().keySet().iterator().next()); - assertEquals(new Long(10), holder.getDerivedIndexedMap().values().iterator().next().get(0)); + assertThat(holder.getDerivedIndexedMap().keySet().iterator().next()).isEqualTo(new Integer(1)); + assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); } @Test @@ -464,9 +470,9 @@ public class BeanWrapperGenericsTests { BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("genericProperty", "10"); bw.setPropertyValue("genericListProperty", new String[] {"20", "30"}); - assertEquals(new Integer(10), gb.getGenericProperty()); - assertEquals(new Integer(20), gb.getGenericListProperty().get(0)); - assertEquals(new Integer(30), gb.getGenericListProperty().get(1)); + assertThat(gb.getGenericProperty()).isEqualTo(new Integer(10)); + assertThat(gb.getGenericListProperty().get(0)).isEqualTo(new Integer(20)); + assertThat(gb.getGenericListProperty().get(1)).isEqualTo(new Integer(30)); } @Test @@ -475,9 +481,9 @@ public class BeanWrapperGenericsTests { BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("genericProperty", "10"); bw.setPropertyValue("genericListProperty", new String[] {"20", "30"}); - assertEquals(new Integer(10), gb.getGenericProperty().iterator().next()); - assertEquals(new Integer(20), gb.getGenericListProperty().get(0).iterator().next()); - assertEquals(new Integer(30), gb.getGenericListProperty().get(1).iterator().next()); + assertThat(gb.getGenericProperty().iterator().next()).isEqualTo(new Integer(10)); + assertThat(gb.getGenericListProperty().get(0).iterator().next()).isEqualTo(new Integer(20)); + assertThat(gb.getGenericListProperty().get(1).iterator().next()).isEqualTo(new Integer(30)); } @Test @@ -485,7 +491,7 @@ public class BeanWrapperGenericsTests { Bar bar = new Bar(); BeanWrapper bw = new BeanWrapperImpl(bar); bw.setPropertyValue("version", "10"); - assertEquals(new Double(10.0), bar.getVersion()); + assertThat(bar.getVersion()).isEqualTo(new Double(10.0)); } @Test @@ -493,7 +499,7 @@ public class BeanWrapperGenericsTests { Promotion bean = new Promotion(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.setPropertyValue("id", "10"); - assertEquals(new Long(10), bean.getId()); + assertThat(bean.getId()).isEqualTo(new Long(10)); } @Test @@ -514,10 +520,10 @@ public class BeanWrapperGenericsTests { Holder> context = new Holder<>(data); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(context); - assertEquals("y", bw.getPropertyValue("data['x']")); + assertThat(bw.getPropertyValue("data['x']")).isEqualTo("y"); bw.setPropertyValue("data['message']", "it works!"); - assertEquals("it works!", data.get("message")); + assertThat(data.get("message")).isEqualTo("it works!"); } diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java index bacdf4cff20..60f1828c705 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java @@ -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.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. @@ -54,8 +50,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { GetterBean target = new GetterBean(); BeanWrapper accessor = createAccessor(target); accessor.setPropertyValue("name", "tom"); - assertEquals("tom", target.getAliasedName()); - assertEquals("tom", accessor.getPropertyValue("aliasedName")); + assertThat(target.getAliasedName()).isEqualTo("tom"); + assertThat(accessor.getPropertyValue("aliasedName")).isEqualTo("tom"); } @Test @@ -64,8 +60,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { BeanWrapper accessor = createAccessor(target); accessor.setExtractOldValueForEditor(true); // This will call the getter accessor.setPropertyValue("name", "tom"); - assertEquals("tom", target.getAliasedName()); - assertEquals("tom", accessor.getPropertyValue("aliasedName")); + assertThat(target.getAliasedName()).isEqualTo("tom"); + assertThat(accessor.getPropertyValue("aliasedName")).isEqualTo("tom"); } @Test @@ -73,8 +69,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { GetterBean target = new GetterBean(); BeanWrapper accessor = createAccessor(target); accessor.setPropertyValue("aliasedName", "tom"); - assertEquals("tom", target.getAliasedName()); - assertEquals("tom", accessor.getPropertyValue("aliasedName")); + assertThat(target.getAliasedName()).isEqualTo("tom"); + assertThat(accessor.getPropertyValue("aliasedName")).isEqualTo("tom"); } @Test @@ -95,8 +91,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { .getNewValue()).isEqualTo(invalidTouchy); }); // Test validly set property matches - assertTrue("Valid set property must stick", target.getName().equals(newName)); - assertTrue("Invalid set property must retain old value", target.getAge() == 0); + assertThat(target.getName().equals(newName)).as("Valid set property must stick").isTrue(); + assertThat(target.getAge() == 0).as("Invalid set property must retain old value").isTrue(); } @Test @@ -124,8 +120,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { bw.setPropertyValue("names", "Alef"); } catch (NotWritablePropertyException ex) { - assertNotNull("Possible matches not determined", ex.getPossibleMatches()); - assertEquals("Invalid amount of alternatives", 1, ex.getPossibleMatches().length); + assertThat(ex.getPossibleMatches()).as("Possible matches not determined").isNotNull(); + assertThat(ex.getPossibleMatches().length).as("Invalid amount of alternatives").isEqualTo(1); } } @@ -137,8 +133,8 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { bw.setPropertyValue("mystring", "Arjen"); } catch (NotWritablePropertyException ex) { - assertNotNull("Possible matches not determined", ex.getPossibleMatches()); - assertEquals("Invalid amount of alternatives", 3, ex.getPossibleMatches().length); + assertThat(ex.getPossibleMatches()).as("Possible matches not determined").isNotNull(); + assertThat(ex.getPossibleMatches().length).as("Invalid amount of alternatives").isEqualTo(3); } } @@ -147,9 +143,9 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { PropertyTypeMismatch target = new PropertyTypeMismatch(); BeanWrapper accessor = createAccessor(target); accessor.setPropertyValue("object", "a String"); - assertEquals("a String", target.value); - assertTrue(target.getObject() == 8); - assertEquals(8, accessor.getPropertyValue("object")); + assertThat(target.value).isEqualTo("a String"); + assertThat(target.getObject() == 8).isTrue(); + assertThat(accessor.getPropertyValue("object")).isEqualTo(8); } @Test @@ -159,12 +155,12 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { BeanWrapper accessor = createAccessor(target); accessor.setPropertyValue("name", "a"); accessor.setPropertyValue("spouse.name", "b"); - assertEquals("a", target.getName()); - assertEquals("b", target.getSpouse().getName()); - assertEquals("a", accessor.getPropertyValue("name")); - assertEquals("b", accessor.getPropertyValue("spouse.name")); - assertEquals(String.class, accessor.getPropertyDescriptor("name").getPropertyType()); - assertEquals(String.class, accessor.getPropertyDescriptor("spouse.name").getPropertyType()); + assertThat(target.getName()).isEqualTo("a"); + assertThat(target.getSpouse().getName()).isEqualTo("b"); + assertThat(accessor.getPropertyValue("name")).isEqualTo("a"); + assertThat(accessor.getPropertyValue("spouse.name")).isEqualTo("b"); + assertThat(accessor.getPropertyDescriptor("name").getPropertyType()).isEqualTo(String.class); + assertThat(accessor.getPropertyDescriptor("spouse.name").getPropertyType()).isEqualTo(String.class); } @Test @@ -175,20 +171,20 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { BeanWrapper accessor = createAccessor(target); accessor.setPropertyValue("object", tb); - assertSame(tb, target.value); - assertSame(tb, target.getObject().get()); - assertSame(tb, ((Optional) accessor.getPropertyValue("object")).get()); - assertEquals("x", target.value.getName()); - assertEquals("x", target.getObject().get().getName()); - assertEquals("x", accessor.getPropertyValue("object.name")); + assertThat(target.value).isSameAs(tb); + assertThat(target.getObject().get()).isSameAs(tb); + assertThat(((Optional) accessor.getPropertyValue("object")).get()).isSameAs(tb); + assertThat(target.value.getName()).isEqualTo("x"); + assertThat(target.getObject().get().getName()).isEqualTo("x"); + assertThat(accessor.getPropertyValue("object.name")).isEqualTo("x"); accessor.setPropertyValue("object.name", "y"); - assertSame(tb, target.value); - assertSame(tb, target.getObject().get()); - assertSame(tb, ((Optional) accessor.getPropertyValue("object")).get()); - assertEquals("y", target.value.getName()); - assertEquals("y", target.getObject().get().getName()); - assertEquals("y", accessor.getPropertyValue("object.name")); + assertThat(target.value).isSameAs(tb); + assertThat(target.getObject().get()).isSameAs(tb); + assertThat(((Optional) accessor.getPropertyValue("object")).get()).isSameAs(tb); + assertThat(target.value.getName()).isEqualTo("y"); + assertThat(target.getObject().get().getName()).isEqualTo("y"); + assertThat(accessor.getPropertyValue("object.name")).isEqualTo("y"); } @Test @@ -198,9 +194,9 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests { accessor.setAutoGrowNestedPaths(true); accessor.setPropertyValue("object.name", "x"); - assertEquals("x", target.value.getName()); - assertEquals("x", target.getObject().get().getName()); - assertEquals("x", accessor.getPropertyValue("object.name")); + assertThat(target.value.getName()).isEqualTo("x"); + assertThat(target.getObject().get().getName()).isEqualTo("x"); + assertThat(accessor.getPropertyValue("object.name")).isEqualTo("x"); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java b/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java index cf96563d3b9..3a400126941 100644 --- a/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java @@ -26,8 +26,6 @@ import org.springframework.core.OverridingClassLoader; import org.springframework.tests.sample.beans.TestBean; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -39,30 +37,30 @@ public class CachedIntrospectionResultsTests { @Test public void acceptAndClearClassLoader() throws Exception { BeanWrapper bw = new BeanWrapperImpl(TestBean.class); - assertTrue(bw.isWritableProperty("name")); - assertTrue(bw.isWritableProperty("age")); - assertTrue(CachedIntrospectionResults.strongClassCache.containsKey(TestBean.class)); + assertThat(bw.isWritableProperty("name")).isTrue(); + assertThat(bw.isWritableProperty("age")).isTrue(); + assertThat(CachedIntrospectionResults.strongClassCache.containsKey(TestBean.class)).isTrue(); ClassLoader child = new OverridingClassLoader(getClass().getClassLoader()); Class tbClass = child.loadClass("org.springframework.tests.sample.beans.TestBean"); - assertFalse(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)); + assertThat(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)).isFalse(); CachedIntrospectionResults.acceptClassLoader(child); bw = new BeanWrapperImpl(tbClass); - assertTrue(bw.isWritableProperty("name")); - assertTrue(bw.isWritableProperty("age")); - assertTrue(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)); + assertThat(bw.isWritableProperty("name")).isTrue(); + assertThat(bw.isWritableProperty("age")).isTrue(); + assertThat(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)).isTrue(); 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 public void clearClassLoaderForSystemClassLoader() throws Exception { BeanUtils.getPropertyDescriptors(ArrayList.class); - assertTrue(CachedIntrospectionResults.strongClassCache.containsKey(ArrayList.class)); + assertThat(CachedIntrospectionResults.strongClassCache.containsKey(ArrayList.class)).isTrue(); CachedIntrospectionResults.clearClassLoader(ArrayList.class.getClassLoader()); - assertFalse(CachedIntrospectionResults.strongClassCache.containsKey(ArrayList.class)); + assertThat(CachedIntrospectionResults.strongClassCache.containsKey(ArrayList.class)).isFalse(); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java b/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java index 14244589ea5..fda482440e0 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java @@ -28,8 +28,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Guillaume Poirier @@ -83,7 +82,7 @@ public class ConcurrentBeanWrapperTests { 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();) { i.next(); @@ -104,7 +103,7 @@ public class ConcurrentBeanWrapperTests { BeanWrapperImpl wrapper = new BeanWrapperImpl(bean); wrapper.setPropertyValue("properties", value); - assertEquals(p, bean.getProperties()); + assertThat(bean.getProperties()).isEqualTo(p); } diff --git a/spring-beans/src/test/java/org/springframework/beans/DirectFieldAccessorTests.java b/spring-beans/src/test/java/org/springframework/beans/DirectFieldAccessorTests.java index 03bdf418df4..14e8640b283 100644 --- a/spring-beans/src/test/java/org/springframework/beans/DirectFieldAccessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/DirectFieldAccessorTests.java @@ -20,7 +20,7 @@ import org.junit.Test; 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. @@ -48,8 +48,8 @@ public class DirectFieldAccessorTests extends AbstractPropertyAccessorTests { }; DirectFieldAccessor dfa = createAccessor(target); - assertEquals(StringBuilder.class, dfa.getPropertyType("name")); - assertEquals(sb, dfa.getPropertyValue("name")); + assertThat(dfa.getPropertyType("name")).isEqualTo(StringBuilder.class); + assertThat(dfa.getPropertyValue("name")).isEqualTo(sb); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java index 8b1142d23ac..ab95675e544 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java @@ -28,7 +28,6 @@ import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * @author Chris Beams @@ -323,7 +322,7 @@ public class ExtendedBeanInfoTests { assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); - assertEquals(hasWriteMethodForProperty(bi, "foo"), hasWriteMethodForProperty(ebi, "foo")); + assertThat(hasWriteMethodForProperty(ebi, "foo")).isEqualTo(hasWriteMethodForProperty(bi, "foo")); } @Test @@ -338,7 +337,7 @@ public class ExtendedBeanInfoTests { assertThat(hasIndexedReadMethodForProperty(bi, "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... BeanInfo ebi = new ExtendedBeanInfo(bi); - assertEquals(hasReadMethod, hasReadMethodForProperty(ebi, "address")); - assertEquals(hasWriteMethod, hasWriteMethodForProperty(ebi, "address")); - assertEquals(hasIndexedReadMethod, hasIndexedReadMethodForProperty(ebi, "address")); - assertEquals(hasIndexedWriteMethod, hasIndexedWriteMethodForProperty(ebi, "address")); + assertThat(hasReadMethodForProperty(ebi, "address")).isEqualTo(hasReadMethod); + assertThat(hasWriteMethodForProperty(ebi, "address")).isEqualTo(hasWriteMethod); + assertThat(hasIndexedReadMethodForProperty(ebi, "address")).isEqualTo(hasIndexedReadMethod); + assertThat(hasIndexedWriteMethodForProperty(ebi, "address")).isEqualTo(hasIndexedWriteMethod); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/MutablePropertyValuesTests.java b/spring-beans/src/test/java/org/springframework/beans/MutablePropertyValuesTests.java index afca39f3427..fe930b748e7 100644 --- a/spring-beans/src/test/java/org/springframework/beans/MutablePropertyValuesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/MutablePropertyValuesTests.java @@ -22,9 +22,6 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; 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}. @@ -47,7 +44,7 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests { doTestTony(deepCopy); deepCopy.setPropertyValueAt(new PropertyValue("name", "Gordon"), 0); doTestTony(pvs); - assertEquals("Gordon", deepCopy.getPropertyValue("name").getValue()); + assertThat(deepCopy.getPropertyValue("name").getValue()).isEqualTo("Gordon"); } @Test @@ -59,10 +56,10 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests { doTestTony(pvs); PropertyValue addedPv = new PropertyValue("rod", "Rod"); pvs.addPropertyValue(addedPv); - assertTrue(pvs.getPropertyValue("rod").equals(addedPv)); + assertThat(pvs.getPropertyValue("rod").equals(addedPv)).isTrue(); PropertyValue changedPv = new PropertyValue("forname", "Greg"); pvs.addPropertyValue(changedPv); - assertTrue(pvs.getPropertyValue("forname").equals(changedPv)); + assertThat(pvs.getPropertyValue("forname").equals(changedPv)).isTrue(); } @Test @@ -73,7 +70,7 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests { pvs.addPropertyValue(new PropertyValue("age", "50")); MutablePropertyValues pvs2 = 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 @@ -85,29 +82,27 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests { MutablePropertyValues pvs2 = new MutablePropertyValues(pvs); PropertyValues changes = pvs2.changesSince(pvs); - assertTrue("changes are empty, not of length " + changes.getPropertyValues().length, - changes.getPropertyValues().length == 0); + assertThat(changes.getPropertyValues().length == 0).as("changes are empty, not of length " + changes.getPropertyValues().length).isTrue(); pvs2.addPropertyValue(new PropertyValue("forname", "Gordon")); 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"); - assertTrue("change is forname", fn != null); - assertTrue("new value is gordon", fn.getValue().equals("Gordon")); + assertThat(fn != null).as("change is forname").isTrue(); + assertThat(fn.getValue().equals("Gordon")).as("new value is gordon").isTrue(); MutablePropertyValues pvs3 = new MutablePropertyValues(pvs); changes = pvs3.changesSince(pvs); - assertTrue("changes are empty, not of length " + changes.getPropertyValues().length, - changes.getPropertyValues().length == 0); + assertThat(changes.getPropertyValues().length == 0).as("changes are empty, not of length " + changes.getPropertyValues().length).isTrue(); // add new pvs3.addPropertyValue(new PropertyValue("foo", "bar")); pvs3.addPropertyValue(new PropertyValue("fi", "fum")); changes = pvs3.changesSince(pvs); - assertTrue("2 change", changes.getPropertyValues().length == 2); + assertThat(changes.getPropertyValues().length == 2).as("2 change").isTrue(); fn = changes.getPropertyValue("foo"); - assertTrue("change in foo", fn != null); - assertTrue("new value is bar", fn.getValue().equals("bar")); + assertThat(fn != null).as("change in foo").isTrue(); + assertThat(fn.getValue().equals("bar")).as("new value is bar").isTrue(); } @Test @@ -116,19 +111,19 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests { pvs.add("foo", "bar"); Iterator it = pvs.iterator(); - assertTrue(it.hasNext()); + assertThat(it.hasNext()).isTrue(); PropertyValue pv = it.next(); - assertEquals("foo", pv.getName()); - assertEquals("bar", pv.getValue()); + assertThat(pv.getName()).isEqualTo("foo"); + assertThat(pv.getValue()).isEqualTo("bar"); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(it::remove); - assertFalse(it.hasNext()); + assertThat(it.hasNext()).isFalse(); } @Test public void iteratorIsEmptyForEmptyValues() { MutablePropertyValues pvs = new MutablePropertyValues(); Iterator it = pvs.iterator(); - assertFalse(it.hasNext()); + assertThat(it.hasNext()).isFalse(); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/PropertyAccessorUtilsTests.java b/spring-beans/src/test/java/org/springframework/beans/PropertyAccessorUtilsTests.java index 87003d6e46d..daa4cb829d2 100644 --- a/spring-beans/src/test/java/org/springframework/beans/PropertyAccessorUtilsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/PropertyAccessorUtilsTests.java @@ -20,8 +20,7 @@ import java.util.Arrays; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -31,15 +30,15 @@ public class PropertyAccessorUtilsTests { @Test public void testCanonicalPropertyName() { - assertEquals("map", PropertyAccessorUtils.canonicalPropertyName("map")); - assertEquals("map[key1]", PropertyAccessorUtils.canonicalPropertyName("map[key1]")); - assertEquals("map[key1]", PropertyAccessorUtils.canonicalPropertyName("map['key1']")); - assertEquals("map[key1]", PropertyAccessorUtils.canonicalPropertyName("map[\"key1\"]")); - assertEquals("map[key1][key2]", PropertyAccessorUtils.canonicalPropertyName("map[key1][key2]")); - assertEquals("map[key1][key2]", PropertyAccessorUtils.canonicalPropertyName("map['key1'][\"key2\"]")); - assertEquals("map[key1].name", PropertyAccessorUtils.canonicalPropertyName("map[key1].name")); - assertEquals("map[key1].name", PropertyAccessorUtils.canonicalPropertyName("map['key1'].name")); - assertEquals("map[key1].name", PropertyAccessorUtils.canonicalPropertyName("map[\"key1\"].name")); + assertThat(PropertyAccessorUtils.canonicalPropertyName("map")).isEqualTo("map"); + assertThat(PropertyAccessorUtils.canonicalPropertyName("map[key1]")).isEqualTo("map[key1]"); + assertThat(PropertyAccessorUtils.canonicalPropertyName("map['key1']")).isEqualTo("map[key1]"); + assertThat(PropertyAccessorUtils.canonicalPropertyName("map[\"key1\"]")).isEqualTo("map[key1]"); + assertThat(PropertyAccessorUtils.canonicalPropertyName("map[key1][key2]")).isEqualTo("map[key1][key2]"); + assertThat(PropertyAccessorUtils.canonicalPropertyName("map['key1'][\"key2\"]")).isEqualTo("map[key1][key2]"); + assertThat(PropertyAccessorUtils.canonicalPropertyName("map[key1].name")).isEqualTo("map[key1].name"); + assertThat(PropertyAccessorUtils.canonicalPropertyName("map['key1'].name")).isEqualTo("map[key1].name"); + assertThat(PropertyAccessorUtils.canonicalPropertyName("map[\"key1\"].name")).isEqualTo("map[key1].name"); } @Test @@ -51,7 +50,7 @@ public class PropertyAccessorUtilsTests { new String[] {"map", "map[key1]", "map[key1]", "map[key1]", "map[key1][key2]", "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(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java index bd4043bd643..e36c1a57180 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java @@ -36,8 +36,7 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.factory.DummyFactory; import org.springframework.util.ObjectUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -83,7 +82,7 @@ public class BeanFactoryUtilsTests { StaticListableBeanFactory lbf = new StaticListableBeanFactory(); lbf.addBean("t1", 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 public void testHierarchicalCountBeansWithOverride() throws Exception { // Leaf count - assertTrue(this.listableBeanFactory.getBeanDefinitionCount() == 1); + assertThat(this.listableBeanFactory.getBeanDefinitionCount() == 1).isTrue(); // Count minus duplicate - assertTrue("Should count 8 beans, not " + BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory), - BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory) == 8); + assertThat(BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory) == 8).as("Should count 8 beans, not " + BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory)).isTrue(); } @Test public void testHierarchicalNamesWithNoMatch() throws Exception { List names = Arrays.asList( BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, NoOp.class)); - assertEquals(0, names.size()); + assertThat(names.size()).isEqualTo(0); } @Test public void testHierarchicalNamesWithMatchOnlyInRoot() throws Exception { List names = Arrays.asList( BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, IndexedTestBean.class)); - assertEquals(1, names.size()); - assertTrue(names.contains("indexedBean")); + assertThat(names.size()).isEqualTo(1); + assertThat(names.contains("indexedBean")).isTrue(); // Distinguish from default ListableBeanFactory behavior - assertTrue(listableBeanFactory.getBeanNamesForType(IndexedTestBean.class).length == 0); + assertThat(listableBeanFactory.getBeanNamesForType(IndexedTestBean.class).length == 0).isTrue(); } @Test @@ -120,11 +118,11 @@ public class BeanFactoryUtilsTests { List names = Arrays.asList( BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class)); // includes 2 TestBeans from FactoryBeans (DummyFactory definitions) - assertEquals(4, names.size()); - assertTrue(names.contains("test")); - assertTrue(names.contains("test3")); - assertTrue(names.contains("testFactory1")); - assertTrue(names.contains("testFactory2")); + assertThat(names.size()).isEqualTo(4); + assertThat(names.contains("test")).isTrue(); + assertThat(names.contains("test3")).isTrue(); + assertThat(names.contains("testFactory1")).isTrue(); + assertThat(names.contains("testFactory2")).isTrue(); } @Test @@ -132,7 +130,7 @@ public class BeanFactoryUtilsTests { StaticListableBeanFactory lbf = new StaticListableBeanFactory(); lbf.addBean("foo", new Object()); Map beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, false); - assertTrue(beans.isEmpty()); + assertThat(beans.isEmpty()).isTrue(); } @Test @@ -149,21 +147,22 @@ public class BeanFactoryUtilsTests { lbf.addBean("t4", t4); Map beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, ITestBean.class, true, true); - assertEquals(4, beans.size()); - assertEquals(t1, beans.get("t1")); - assertEquals(t2, beans.get("t2")); - assertEquals(t3.getObject(), beans.get("t3")); - assertTrue(beans.get("t4") instanceof TestBean); + assertThat(beans.size()).isEqualTo(4); + assertThat(beans.get("t1")).isEqualTo(t1); + assertThat(beans.get("t2")).isEqualTo(t2); + assertThat(beans.get("t3")).isEqualTo(t3.getObject()); + boolean condition = beans.get("t4") instanceof TestBean; + assertThat(condition).isTrue(); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, DummyFactory.class, true, true); - assertEquals(2, beans.size()); - assertEquals(t3, beans.get("&t3")); - assertEquals(t4, beans.get("&t4")); + assertThat(beans.size()).isEqualTo(2); + assertThat(beans.get("&t3")).isEqualTo(t3); + assertThat(beans.get("&t4")).isEqualTo(t4); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, FactoryBean.class, true, true); - assertEquals(2, beans.size()); - assertEquals(t3, beans.get("&t3")); - assertEquals(t4, beans.get("&t4")); + assertThat(beans.size()).isEqualTo(2); + assertThat(beans.get("&t3")).isEqualTo(t3); + assertThat(beans.get("&t4")).isEqualTo(t4); } @Test @@ -183,50 +182,53 @@ public class BeanFactoryUtilsTests { Map beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, false); - assertEquals(6, beans.size()); - assertEquals(test3, beans.get("test3")); - assertEquals(test, beans.get("test")); - assertEquals(t1, beans.get("t1")); - assertEquals(t2, beans.get("t2")); - assertEquals(t3.getObject(), beans.get("t3")); - assertTrue(beans.get("t4") instanceof TestBean); + assertThat(beans.size()).isEqualTo(6); + assertThat(beans.get("test3")).isEqualTo(test3); + assertThat(beans.get("test")).isEqualTo(test); + assertThat(beans.get("t1")).isEqualTo(t1); + assertThat(beans.get("t2")).isEqualTo(t2); + assertThat(beans.get("t3")).isEqualTo(t3.getObject()); + 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 // singleton instances, while testFactory1 and testFactory are *not* found // because they are FactoryBean definitions that haven't been initialized yet. beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, true); Object testFactory1 = this.listableBeanFactory.getBean("testFactory1"); - assertEquals(5, beans.size()); - assertEquals(test, beans.get("test")); - assertEquals(testFactory1, beans.get("testFactory1")); - assertEquals(t1, beans.get("t1")); - assertEquals(t2, beans.get("t2")); - assertEquals(t3.getObject(), beans.get("t3")); + assertThat(beans.size()).isEqualTo(5); + assertThat(beans.get("test")).isEqualTo(test); + assertThat(beans.get("testFactory1")).isEqualTo(testFactory1); + assertThat(beans.get("t1")).isEqualTo(t1); + assertThat(beans.get("t2")).isEqualTo(t2); + assertThat(beans.get("t3")).isEqualTo(t3.getObject()); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, true); - assertEquals(8, beans.size()); - assertEquals(test3, beans.get("test3")); - assertEquals(test, beans.get("test")); - assertEquals(testFactory1, beans.get("testFactory1")); - assertTrue(beans.get("testFactory2") instanceof TestBean); - assertEquals(t1, beans.get("t1")); - assertEquals(t2, beans.get("t2")); - assertEquals(t3.getObject(), beans.get("t3")); - assertTrue(beans.get("t4") instanceof TestBean); + assertThat(beans.size()).isEqualTo(8); + assertThat(beans.get("test3")).isEqualTo(test3); + assertThat(beans.get("test")).isEqualTo(test); + assertThat(beans.get("testFactory1")).isEqualTo(testFactory1); + boolean condition1 = beans.get("testFactory2") instanceof TestBean; + assertThat(condition1).isTrue(); + assertThat(beans.get("t1")).isEqualTo(t1); + assertThat(beans.get("t2")).isEqualTo(t2); + 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); - assertEquals(4, beans.size()); - assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1")); - assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2")); - assertEquals(t3, beans.get("&t3")); - assertEquals(t4, beans.get("&t4")); + assertThat(beans.size()).isEqualTo(4); + assertThat(beans.get("&testFactory1")).isEqualTo(this.listableBeanFactory.getBean("&testFactory1")); + assertThat(beans.get("&testFactory2")).isEqualTo(this.listableBeanFactory.getBean("&testFactory2")); + assertThat(beans.get("&t3")).isEqualTo(t3); + assertThat(beans.get("&t4")).isEqualTo(t4); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, FactoryBean.class, true, true); - assertEquals(4, beans.size()); - assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1")); - assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2")); - assertEquals(t3, beans.get("&t3")); - assertEquals(t4, beans.get("&t4")); + assertThat(beans.size()).isEqualTo(4); + assertThat(beans.get("&testFactory1")).isEqualTo(this.listableBeanFactory.getBean("&testFactory1")); + assertThat(beans.get("&testFactory2")).isEqualTo(this.listableBeanFactory.getBean("&testFactory2")); + assertThat(beans.get("&t3")).isEqualTo(t3); + assertThat(beans.get("&t4")).isEqualTo(t4); } @Test @@ -236,53 +238,54 @@ public class BeanFactoryUtilsTests { Map beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, false); - assertEquals(2, beans.size()); - assertEquals(test3, beans.get("test3")); - assertEquals(test, beans.get("test")); + assertThat(beans.size()).isEqualTo(2); + assertThat(beans.get("test3")).isEqualTo(test3); + assertThat(beans.get("test")).isEqualTo(test); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, false); - assertEquals(1, beans.size()); - assertEquals(test, beans.get("test")); + assertThat(beans.size()).isEqualTo(1); + assertThat(beans.get("test")).isEqualTo(test); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, false, true); Object testFactory1 = this.listableBeanFactory.getBean("testFactory1"); - assertEquals(2, beans.size()); - assertEquals(test, beans.get("test")); - assertEquals(testFactory1, beans.get("testFactory1")); + assertThat(beans.size()).isEqualTo(2); + assertThat(beans.get("test")).isEqualTo(test); + assertThat(beans.get("testFactory1")).isEqualTo(testFactory1); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, ITestBean.class, true, true); - assertEquals(4, beans.size()); - assertEquals(test3, beans.get("test3")); - assertEquals(test, beans.get("test")); - assertEquals(testFactory1, beans.get("testFactory1")); - assertTrue(beans.get("testFactory2") instanceof TestBean); + assertThat(beans.size()).isEqualTo(4); + assertThat(beans.get("test3")).isEqualTo(test3); + assertThat(beans.get("test")).isEqualTo(test); + assertThat(beans.get("testFactory1")).isEqualTo(testFactory1); + boolean condition = beans.get("testFactory2") instanceof TestBean; + assertThat(condition).isTrue(); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, DummyFactory.class, true, true); - assertEquals(2, beans.size()); - assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1")); - assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2")); + assertThat(beans.size()).isEqualTo(2); + assertThat(beans.get("&testFactory1")).isEqualTo(this.listableBeanFactory.getBean("&testFactory1")); + assertThat(beans.get("&testFactory2")).isEqualTo(this.listableBeanFactory.getBean("&testFactory2")); beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.listableBeanFactory, FactoryBean.class, true, true); - assertEquals(2, beans.size()); - assertEquals(this.listableBeanFactory.getBean("&testFactory1"), beans.get("&testFactory1")); - assertEquals(this.listableBeanFactory.getBean("&testFactory2"), beans.get("&testFactory2")); + assertThat(beans.size()).isEqualTo(2); + assertThat(beans.get("&testFactory1")).isEqualTo(this.listableBeanFactory.getBean("&testFactory1")); + assertThat(beans.get("&testFactory2")).isEqualTo(this.listableBeanFactory.getBean("&testFactory2")); } @Test public void testHierarchicalNamesForAnnotationWithNoMatch() throws Exception { List names = Arrays.asList( BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.listableBeanFactory, Override.class)); - assertEquals(0, names.size()); + assertThat(names.size()).isEqualTo(0); } @Test public void testHierarchicalNamesForAnnotationWithMatchOnlyInRoot() throws Exception { List names = Arrays.asList( BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.listableBeanFactory, TestAnnotation.class)); - assertEquals(1, names.size()); - assertTrue(names.contains("annotatedBean")); + assertThat(names.size()).isEqualTo(1); + assertThat(names.contains("annotatedBean")).isTrue(); // Distinguish from default ListableBeanFactory behavior - assertTrue(listableBeanFactory.getBeanNamesForAnnotation(TestAnnotation.class).length == 0); + assertThat(listableBeanFactory.getBeanNamesForAnnotation(TestAnnotation.class).length == 0).isTrue(); } @Test @@ -291,33 +294,33 @@ public class BeanFactoryUtilsTests { this.listableBeanFactory.registerSingleton("anotherAnnotatedBean", annotatedBean); List names = Arrays.asList( BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.listableBeanFactory, TestAnnotation.class)); - assertEquals(2, names.size()); - assertTrue(names.contains("annotatedBean")); - assertTrue(names.contains("anotherAnnotatedBean")); + assertThat(names.size()).isEqualTo(2); + assertThat(names.contains("annotatedBean")).isTrue(); + assertThat(names.contains("anotherAnnotatedBean")).isTrue(); } @Test public void testADependencies() { String[] deps = this.dependentBeansFactory.getDependentBeans("a"); - assertTrue(ObjectUtils.isEmpty(deps)); + assertThat(ObjectUtils.isEmpty(deps)).isTrue(); } @Test public void testBDependencies() { String[] deps = this.dependentBeansFactory.getDependentBeans("b"); - assertTrue(Arrays.equals(new String[] { "c" }, deps)); + assertThat(Arrays.equals(new String[] { "c" }, deps)).isTrue(); } @Test public void testCDependencies() { String[] deps = this.dependentBeansFactory.getDependentBeans("c"); - assertTrue(Arrays.equals(new String[] { "int", "long" }, deps)); + assertThat(Arrays.equals(new String[] { "int", "long" }, deps)).isTrue(); } @Test public void testIntDependencies() { String[] deps = this.dependentBeansFactory.getDependentBeans("int"); - assertTrue(Arrays.equals(new String[] { "buffer" }, deps)); + assertThat(Arrays.equals(new String[] { "buffer" }, deps)).isTrue(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java index 965d760922d..ad8a597d4c8 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java @@ -36,7 +36,7 @@ import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.tests.Assume; 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; /** @@ -126,8 +126,8 @@ public class ConcurrentBeanFactoryTests { ConcurrentBean b1 = (ConcurrentBean) factory.getBean("bean1"); ConcurrentBean b2 = (ConcurrentBean) factory.getBean("bean2"); - assertEquals(DATE_1, b1.getDate()); - assertEquals(DATE_2, b2.getDate()); + assertThat(b1.getDate()).isEqualTo(DATE_1); + assertThat(b2.getDate()).isEqualTo(DATE_2); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java index 1574b77355e..b158a3601f9 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -103,14 +103,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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.assertNotEquals; -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; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; @@ -140,10 +132,10 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); Properties p = new Properties(); p.setProperty("x1.(class)", KnowsIfInstantiated.class.getName()); - assertTrue("singleton not instantiated", !KnowsIfInstantiated.wasInstantiated()); + assertThat(!KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isTrue(); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); lbf.preInstantiateSingletons(); - assertTrue("singleton was instantiated", KnowsIfInstantiated.wasInstantiated()); + assertThat(KnowsIfInstantiated.wasInstantiated()).as("singleton was instantiated").isTrue(); } @Test @@ -153,14 +145,14 @@ public class DefaultListableBeanFactoryTests { Properties p = new Properties(); p.setProperty("x1.(class)", KnowsIfInstantiated.class.getName()); p.setProperty("x1.(lazy-init)", "true"); - assertTrue("singleton not instantiated", !KnowsIfInstantiated.wasInstantiated()); + assertThat(!KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isTrue(); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); - assertTrue("singleton not instantiated", !KnowsIfInstantiated.wasInstantiated()); + assertThat(!KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isTrue(); lbf.preInstantiateSingletons(); - assertTrue("singleton not instantiated", !KnowsIfInstantiated.wasInstantiated()); + assertThat(!KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isTrue(); lbf.getBean("x1"); - assertTrue("singleton was instantiated", KnowsIfInstantiated.wasInstantiated()); + assertThat(KnowsIfInstantiated.wasInstantiated()).as("singleton was instantiated").isTrue(); } @Test @@ -171,18 +163,18 @@ public class DefaultListableBeanFactoryTests { // Reset static state DummyFactory.reset(); p.setProperty("x1.singleton", "false"); - assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); + assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); - assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); - assertEquals(TestBean.class, lbf.getType("x1")); + assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); + assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); lbf.preInstantiateSingletons(); - assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); + assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); lbf.getBean("x1"); - assertEquals(TestBean.class, lbf.getType("x1")); - assertTrue(lbf.containsBean("x1")); - assertTrue(lbf.containsBean("&x1")); - assertTrue("prototype was instantiated", DummyFactory.wasPrototypeCreated()); + assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); + assertThat(lbf.containsBean("x1")).isTrue(); + assertThat(lbf.containsBean("&x1")).isTrue(); + assertThat(DummyFactory.wasPrototypeCreated()).as("prototype was instantiated").isTrue(); } @Test @@ -196,28 +188,28 @@ public class DefaultListableBeanFactoryTests { p.setProperty("x1.singleton", "false"); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); - assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); + assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertEquals(0, beanNames.length); + assertThat(beanNames.length).isEqualTo(0); beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class); - assertEquals(0, beanNames.length); + assertThat(beanNames.length).isEqualTo(0); - assertFalse(lbf.containsSingleton("x1")); - assertTrue(lbf.containsBean("x1")); - assertTrue(lbf.containsBean("&x1")); - assertFalse(lbf.isSingleton("x1")); - assertFalse(lbf.isSingleton("&x1")); - assertTrue(lbf.isPrototype("x1")); - assertTrue(lbf.isPrototype("&x1")); - assertTrue(lbf.isTypeMatch("x1", TestBean.class)); - assertFalse(lbf.isTypeMatch("&x1", TestBean.class)); - assertTrue(lbf.isTypeMatch("&x1", DummyFactory.class)); - assertTrue(lbf.isTypeMatch("&x1", ResolvableType.forClass(DummyFactory.class))); - assertTrue(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class))); - assertFalse(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, String.class))); - assertEquals(TestBean.class, lbf.getType("x1")); - assertEquals(DummyFactory.class, lbf.getType("&x1")); - assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); + assertThat(lbf.containsSingleton("x1")).isFalse(); + assertThat(lbf.containsBean("x1")).isTrue(); + assertThat(lbf.containsBean("&x1")).isTrue(); + assertThat(lbf.isSingleton("x1")).isFalse(); + assertThat(lbf.isSingleton("&x1")).isFalse(); + assertThat(lbf.isPrototype("x1")).isTrue(); + assertThat(lbf.isPrototype("&x1")).isTrue(); + assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse(); + assertThat(lbf.isTypeMatch("&x1", DummyFactory.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", ResolvableType.forClass(DummyFactory.class))).isTrue(); + assertThat(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class))).isTrue(); + assertThat(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, String.class))).isFalse(); + assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); + assertThat(lbf.getType("&x1")).isEqualTo(DummyFactory.class); + assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); } @Test @@ -231,28 +223,28 @@ public class DefaultListableBeanFactoryTests { p.setProperty("x1.singleton", "true"); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); - assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); + assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertEquals(0, beanNames.length); + assertThat(beanNames.length).isEqualTo(0); beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class); - assertEquals(0, beanNames.length); + assertThat(beanNames.length).isEqualTo(0); - assertFalse(lbf.containsSingleton("x1")); - assertTrue(lbf.containsBean("x1")); - assertTrue(lbf.containsBean("&x1")); - assertFalse(lbf.isSingleton("x1")); - assertFalse(lbf.isSingleton("&x1")); - assertTrue(lbf.isPrototype("x1")); - assertTrue(lbf.isPrototype("&x1")); - assertTrue(lbf.isTypeMatch("x1", TestBean.class)); - assertFalse(lbf.isTypeMatch("&x1", TestBean.class)); - assertTrue(lbf.isTypeMatch("&x1", DummyFactory.class)); - assertTrue(lbf.isTypeMatch("&x1", ResolvableType.forClass(DummyFactory.class))); - assertTrue(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class))); - assertFalse(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, String.class))); - assertEquals(TestBean.class, lbf.getType("x1")); - assertEquals(DummyFactory.class, lbf.getType("&x1")); - assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); + assertThat(lbf.containsSingleton("x1")).isFalse(); + assertThat(lbf.containsBean("x1")).isTrue(); + assertThat(lbf.containsBean("&x1")).isTrue(); + assertThat(lbf.isSingleton("x1")).isFalse(); + assertThat(lbf.isSingleton("&x1")).isFalse(); + assertThat(lbf.isPrototype("x1")).isTrue(); + assertThat(lbf.isPrototype("&x1")).isTrue(); + assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse(); + assertThat(lbf.isTypeMatch("&x1", DummyFactory.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", ResolvableType.forClass(DummyFactory.class))).isTrue(); + assertThat(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class))).isTrue(); + assertThat(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, String.class))).isFalse(); + assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); + assertThat(lbf.getType("&x1")).isEqualTo(DummyFactory.class); + assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); } @Test @@ -265,28 +257,28 @@ public class DefaultListableBeanFactoryTests { p.setProperty("x1.singleton", "false"); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); - assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); + assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertEquals(0, beanNames.length); + assertThat(beanNames.length).isEqualTo(0); beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class); - assertEquals(0, beanNames.length); + assertThat(beanNames.length).isEqualTo(0); - assertFalse(lbf.containsSingleton("x1")); - assertTrue(lbf.containsBean("x1")); - assertTrue(lbf.containsBean("&x1")); - assertFalse(lbf.isSingleton("x1")); - assertTrue(lbf.isSingleton("&x1")); - assertTrue(lbf.isPrototype("x1")); - assertFalse(lbf.isPrototype("&x1")); - assertTrue(lbf.isTypeMatch("x1", TestBean.class)); - assertFalse(lbf.isTypeMatch("&x1", TestBean.class)); - assertTrue(lbf.isTypeMatch("&x1", DummyFactory.class)); - assertTrue(lbf.isTypeMatch("&x1", ResolvableType.forClass(DummyFactory.class))); - assertTrue(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class))); - assertFalse(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, String.class))); - assertEquals(TestBean.class, lbf.getType("x1")); - assertEquals(DummyFactory.class, lbf.getType("&x1")); - assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); + assertThat(lbf.containsSingleton("x1")).isFalse(); + assertThat(lbf.containsBean("x1")).isTrue(); + assertThat(lbf.containsBean("&x1")).isTrue(); + assertThat(lbf.isSingleton("x1")).isFalse(); + assertThat(lbf.isSingleton("&x1")).isTrue(); + assertThat(lbf.isPrototype("x1")).isTrue(); + assertThat(lbf.isPrototype("&x1")).isFalse(); + assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse(); + assertThat(lbf.isTypeMatch("&x1", DummyFactory.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", ResolvableType.forClass(DummyFactory.class))).isTrue(); + assertThat(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class))).isTrue(); + assertThat(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, String.class))).isFalse(); + assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); + assertThat(lbf.getType("&x1")).isEqualTo(DummyFactory.class); + assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); } @Test @@ -300,52 +292,52 @@ public class DefaultListableBeanFactoryTests { (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); lbf.preInstantiateSingletons(); - assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); + assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertEquals(1, beanNames.length); - assertEquals("x1", beanNames[0]); - assertTrue(lbf.containsSingleton("x1")); - assertTrue(lbf.containsBean("x1")); - assertTrue(lbf.containsBean("&x1")); - assertTrue(lbf.containsLocalBean("x1")); - assertTrue(lbf.containsLocalBean("&x1")); - assertFalse(lbf.isSingleton("x1")); - assertTrue(lbf.isSingleton("&x1")); - assertTrue(lbf.isPrototype("x1")); - assertFalse(lbf.isPrototype("&x1")); - assertTrue(lbf.isTypeMatch("x1", TestBean.class)); - assertFalse(lbf.isTypeMatch("&x1", TestBean.class)); - assertTrue(lbf.isTypeMatch("&x1", DummyFactory.class)); - assertTrue(lbf.isTypeMatch("x1", Object.class)); - assertTrue(lbf.isTypeMatch("&x1", Object.class)); - assertEquals(TestBean.class, lbf.getType("x1")); - assertEquals(DummyFactory.class, lbf.getType("&x1")); - assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("x1"); + assertThat(lbf.containsSingleton("x1")).isTrue(); + assertThat(lbf.containsBean("x1")).isTrue(); + assertThat(lbf.containsBean("&x1")).isTrue(); + assertThat(lbf.containsLocalBean("x1")).isTrue(); + assertThat(lbf.containsLocalBean("&x1")).isTrue(); + assertThat(lbf.isSingleton("x1")).isFalse(); + assertThat(lbf.isSingleton("&x1")).isTrue(); + assertThat(lbf.isPrototype("x1")).isTrue(); + assertThat(lbf.isPrototype("&x1")).isFalse(); + assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse(); + assertThat(lbf.isTypeMatch("&x1", DummyFactory.class)).isTrue(); + assertThat(lbf.isTypeMatch("x1", Object.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", Object.class)).isTrue(); + assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); + assertThat(lbf.getType("&x1")).isEqualTo(DummyFactory.class); + assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); lbf.registerAlias("x1", "x2"); - assertTrue(lbf.containsBean("x2")); - assertTrue(lbf.containsBean("&x2")); - assertTrue(lbf.containsLocalBean("x2")); - assertTrue(lbf.containsLocalBean("&x2")); - assertFalse(lbf.isSingleton("x2")); - assertTrue(lbf.isSingleton("&x2")); - assertTrue(lbf.isPrototype("x2")); - assertFalse(lbf.isPrototype("&x2")); - assertTrue(lbf.isTypeMatch("x2", TestBean.class)); - assertFalse(lbf.isTypeMatch("&x2", TestBean.class)); - assertTrue(lbf.isTypeMatch("&x2", DummyFactory.class)); - assertTrue(lbf.isTypeMatch("x2", Object.class)); - assertTrue(lbf.isTypeMatch("&x2", Object.class)); - assertEquals(TestBean.class, lbf.getType("x2")); - assertEquals(DummyFactory.class, lbf.getType("&x2")); - assertEquals(1, lbf.getAliases("x1").length); - assertEquals("x2", lbf.getAliases("x1")[0]); - assertEquals(1, lbf.getAliases("&x1").length); - assertEquals("&x2", lbf.getAliases("&x1")[0]); - assertEquals(1, lbf.getAliases("x2").length); - assertEquals("x1", lbf.getAliases("x2")[0]); - assertEquals(1, lbf.getAliases("&x2").length); - assertEquals("&x1", lbf.getAliases("&x2")[0]); + assertThat(lbf.containsBean("x2")).isTrue(); + assertThat(lbf.containsBean("&x2")).isTrue(); + assertThat(lbf.containsLocalBean("x2")).isTrue(); + assertThat(lbf.containsLocalBean("&x2")).isTrue(); + assertThat(lbf.isSingleton("x2")).isFalse(); + assertThat(lbf.isSingleton("&x2")).isTrue(); + assertThat(lbf.isPrototype("x2")).isTrue(); + assertThat(lbf.isPrototype("&x2")).isFalse(); + assertThat(lbf.isTypeMatch("x2", TestBean.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x2", TestBean.class)).isFalse(); + assertThat(lbf.isTypeMatch("&x2", DummyFactory.class)).isTrue(); + assertThat(lbf.isTypeMatch("x2", Object.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x2", Object.class)).isTrue(); + assertThat(lbf.getType("x2")).isEqualTo(TestBean.class); + assertThat(lbf.getType("&x2")).isEqualTo(DummyFactory.class); + assertThat(lbf.getAliases("x1").length).isEqualTo(1); + assertThat(lbf.getAliases("x1")[0]).isEqualTo("x2"); + assertThat(lbf.getAliases("&x1").length).isEqualTo(1); + assertThat(lbf.getAliases("&x1")[0]).isEqualTo("&x2"); + assertThat(lbf.getAliases("x2").length).isEqualTo(1); + assertThat(lbf.getAliases("x2")[0]).isEqualTo("x1"); + assertThat(lbf.getAliases("&x2").length).isEqualTo(1); + assertThat(lbf.getAliases("&x2")[0]).isEqualTo("&x1"); } @Test @@ -357,20 +349,20 @@ public class DefaultListableBeanFactoryTests { TestBeanFactory.initialized = false; String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertEquals(1, beanNames.length); - assertEquals("x1", beanNames[0]); - assertFalse(lbf.containsSingleton("x1")); - assertTrue(lbf.containsBean("x1")); - assertFalse(lbf.containsBean("&x1")); - assertTrue(lbf.isSingleton("x1")); - assertFalse(lbf.isSingleton("&x1")); - assertFalse(lbf.isPrototype("x1")); - assertFalse(lbf.isPrototype("&x1")); - assertTrue(lbf.isTypeMatch("x1", TestBean.class)); - assertFalse(lbf.isTypeMatch("&x1", TestBean.class)); - assertEquals(TestBean.class, lbf.getType("x1")); - assertEquals(null, lbf.getType("&x1")); - assertFalse(TestBeanFactory.initialized); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("x1"); + assertThat(lbf.containsSingleton("x1")).isFalse(); + assertThat(lbf.containsBean("x1")).isTrue(); + assertThat(lbf.containsBean("&x1")).isFalse(); + assertThat(lbf.isSingleton("x1")).isTrue(); + assertThat(lbf.isSingleton("&x1")).isFalse(); + assertThat(lbf.isPrototype("x1")).isFalse(); + assertThat(lbf.isPrototype("&x1")).isFalse(); + assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse(); + assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); + assertThat(lbf.getType("&x1")).isEqualTo(null); + assertThat(TestBeanFactory.initialized).isFalse(); } @Test @@ -383,20 +375,20 @@ public class DefaultListableBeanFactoryTests { TestBeanFactory.initialized = false; String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertEquals(1, beanNames.length); - assertEquals("x1", beanNames[0]); - assertFalse(lbf.containsSingleton("x1")); - assertTrue(lbf.containsBean("x1")); - assertFalse(lbf.containsBean("&x1")); - assertFalse(lbf.isSingleton("x1")); - assertFalse(lbf.isSingleton("&x1")); - assertTrue(lbf.isPrototype("x1")); - assertFalse(lbf.isPrototype("&x1")); - assertTrue(lbf.isTypeMatch("x1", TestBean.class)); - assertFalse(lbf.isTypeMatch("&x1", TestBean.class)); - assertEquals(TestBean.class, lbf.getType("x1")); - assertEquals(null, lbf.getType("&x1")); - assertFalse(TestBeanFactory.initialized); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("x1"); + assertThat(lbf.containsSingleton("x1")).isFalse(); + assertThat(lbf.containsBean("x1")).isTrue(); + assertThat(lbf.containsBean("&x1")).isFalse(); + assertThat(lbf.isSingleton("x1")).isFalse(); + assertThat(lbf.isSingleton("&x1")).isFalse(); + assertThat(lbf.isPrototype("x1")).isTrue(); + assertThat(lbf.isPrototype("&x1")).isFalse(); + assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse(); + assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); + assertThat(lbf.getType("&x1")).isEqualTo(null); + assertThat(TestBeanFactory.initialized).isFalse(); } @Test @@ -411,20 +403,20 @@ public class DefaultListableBeanFactoryTests { TestBeanFactory.initialized = false; String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertEquals(1, beanNames.length); - assertEquals("x1", beanNames[0]); - assertFalse(lbf.containsSingleton("x1")); - assertTrue(lbf.containsBean("x1")); - assertFalse(lbf.containsBean("&x1")); - assertTrue(lbf.isSingleton("x1")); - assertFalse(lbf.isSingleton("&x1")); - assertFalse(lbf.isPrototype("x1")); - assertFalse(lbf.isPrototype("&x1")); - assertTrue(lbf.isTypeMatch("x1", TestBean.class)); - assertFalse(lbf.isTypeMatch("&x1", TestBean.class)); - assertEquals(TestBean.class, lbf.getType("x1")); - assertEquals(null, lbf.getType("&x1")); - assertFalse(TestBeanFactory.initialized); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("x1"); + assertThat(lbf.containsSingleton("x1")).isFalse(); + assertThat(lbf.containsBean("x1")).isTrue(); + assertThat(lbf.containsBean("&x1")).isFalse(); + assertThat(lbf.isSingleton("x1")).isTrue(); + assertThat(lbf.isSingleton("&x1")).isFalse(); + assertThat(lbf.isPrototype("x1")).isFalse(); + assertThat(lbf.isPrototype("&x1")).isFalse(); + assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse(); + assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); + assertThat(lbf.getType("&x1")).isEqualTo(null); + assertThat(TestBeanFactory.initialized).isFalse(); } @Test @@ -440,56 +432,56 @@ public class DefaultListableBeanFactoryTests { TestBeanFactory.initialized = false; String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertEquals(1, beanNames.length); - assertEquals("x1", beanNames[0]); - assertFalse(lbf.containsSingleton("x1")); - assertTrue(lbf.containsBean("x1")); - assertFalse(lbf.containsBean("&x1")); - assertTrue(lbf.containsLocalBean("x1")); - assertFalse(lbf.containsLocalBean("&x1")); - assertFalse(lbf.isSingleton("x1")); - assertFalse(lbf.isSingleton("&x1")); - assertTrue(lbf.isPrototype("x1")); - assertFalse(lbf.isPrototype("&x1")); - assertTrue(lbf.isTypeMatch("x1", TestBean.class)); - assertFalse(lbf.isTypeMatch("&x1", TestBean.class)); - assertTrue(lbf.isTypeMatch("x1", Object.class)); - assertFalse(lbf.isTypeMatch("&x1", Object.class)); - assertEquals(TestBean.class, lbf.getType("x1")); - assertEquals(null, lbf.getType("&x1")); - assertFalse(TestBeanFactory.initialized); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("x1"); + assertThat(lbf.containsSingleton("x1")).isFalse(); + assertThat(lbf.containsBean("x1")).isTrue(); + assertThat(lbf.containsBean("&x1")).isFalse(); + assertThat(lbf.containsLocalBean("x1")).isTrue(); + assertThat(lbf.containsLocalBean("&x1")).isFalse(); + assertThat(lbf.isSingleton("x1")).isFalse(); + assertThat(lbf.isSingleton("&x1")).isFalse(); + assertThat(lbf.isPrototype("x1")).isTrue(); + assertThat(lbf.isPrototype("&x1")).isFalse(); + assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse(); + assertThat(lbf.isTypeMatch("x1", Object.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x1", Object.class)).isFalse(); + assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); + assertThat(lbf.getType("&x1")).isEqualTo(null); + assertThat(TestBeanFactory.initialized).isFalse(); lbf.registerAlias("x1", "x2"); - assertTrue(lbf.containsBean("x2")); - assertFalse(lbf.containsBean("&x2")); - assertTrue(lbf.containsLocalBean("x2")); - assertFalse(lbf.containsLocalBean("&x2")); - assertFalse(lbf.isSingleton("x2")); - assertFalse(lbf.isSingleton("&x2")); - assertTrue(lbf.isPrototype("x2")); - assertFalse(lbf.isPrototype("&x2")); - assertTrue(lbf.isTypeMatch("x2", TestBean.class)); - assertFalse(lbf.isTypeMatch("&x2", TestBean.class)); - assertTrue(lbf.isTypeMatch("x2", Object.class)); - assertFalse(lbf.isTypeMatch("&x2", Object.class)); - assertEquals(TestBean.class, lbf.getType("x2")); - assertEquals(null, lbf.getType("&x2")); - assertEquals(1, lbf.getAliases("x1").length); - assertEquals("x2", lbf.getAliases("x1")[0]); - assertEquals(1, lbf.getAliases("&x1").length); - assertEquals("&x2", lbf.getAliases("&x1")[0]); - assertEquals(1, lbf.getAliases("x2").length); - assertEquals("x1", lbf.getAliases("x2")[0]); - assertEquals(1, lbf.getAliases("&x2").length); - assertEquals("&x1", lbf.getAliases("&x2")[0]); + assertThat(lbf.containsBean("x2")).isTrue(); + assertThat(lbf.containsBean("&x2")).isFalse(); + assertThat(lbf.containsLocalBean("x2")).isTrue(); + assertThat(lbf.containsLocalBean("&x2")).isFalse(); + assertThat(lbf.isSingleton("x2")).isFalse(); + assertThat(lbf.isSingleton("&x2")).isFalse(); + assertThat(lbf.isPrototype("x2")).isTrue(); + assertThat(lbf.isPrototype("&x2")).isFalse(); + assertThat(lbf.isTypeMatch("x2", TestBean.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x2", TestBean.class)).isFalse(); + assertThat(lbf.isTypeMatch("x2", Object.class)).isTrue(); + assertThat(lbf.isTypeMatch("&x2", Object.class)).isFalse(); + assertThat(lbf.getType("x2")).isEqualTo(TestBean.class); + assertThat(lbf.getType("&x2")).isEqualTo(null); + assertThat(lbf.getAliases("x1").length).isEqualTo(1); + assertThat(lbf.getAliases("x1")[0]).isEqualTo("x2"); + assertThat(lbf.getAliases("&x1").length).isEqualTo(1); + assertThat(lbf.getAliases("&x1")[0]).isEqualTo("&x2"); + assertThat(lbf.getAliases("x2").length).isEqualTo(1); + assertThat(lbf.getAliases("x2")[0]).isEqualTo("x1"); + assertThat(lbf.getAliases("&x2").length).isEqualTo(1); + assertThat(lbf.getAliases("&x2")[0]).isEqualTo("&x1"); } @Test public void testEmpty() { ListableBeanFactory lbf = new DefaultListableBeanFactory(); - assertTrue("No beans defined --> array != null", lbf.getBeanDefinitionNames() != null); - assertTrue("No beans defined after no arg constructor", lbf.getBeanDefinitionNames().length == 0); - assertTrue("No beans defined after no arg constructor", lbf.getBeanDefinitionCount() == 0); + assertThat(lbf.getBeanDefinitionNames() != null).as("No beans defined --> array != null").isTrue(); + assertThat(lbf.getBeanDefinitionNames().length == 0).as("No beans defined after no arg constructor").isTrue(); + assertThat(lbf.getBeanDefinitionCount() == 0).as("No beans defined after no arg constructor").isTrue(); } @Test @@ -497,7 +489,7 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); Properties p = new Properties(); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); - assertTrue("No beans defined after ignorable invalid", lbf.getBeanDefinitionCount() == 0); + assertThat(lbf.getBeanDefinitionCount() == 0).as("No beans defined after ignorable invalid").isTrue(); } @Test @@ -507,7 +499,7 @@ public class DefaultListableBeanFactoryTests { p.setProperty("foo", "bar"); p.setProperty("qwert", "er"); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p, "test"); - assertTrue("No beans defined after harmless ignorable rubbish", lbf.getBeanDefinitionCount() == 0); + assertThat(lbf.getBeanDefinitionCount() == 0).as("No beans defined after harmless ignorable rubbish").isTrue(); } @Test @@ -518,7 +510,7 @@ public class DefaultListableBeanFactoryTests { p.setProperty("test.name", "Tony"); p.setProperty("test.age", "48"); int count = (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); - assertTrue("1 beans registered, not " + count, count == 1); + assertThat(count == 1).as("1 beans registered, not " + count).isTrue(); testSingleTestBean(lbf); } @@ -531,7 +523,7 @@ public class DefaultListableBeanFactoryTests { p.setProperty(PREFIX + "test.name", "Tony"); p.setProperty(PREFIX + "test.age", "0x30"); int count = (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p, PREFIX); - assertTrue("1 beans registered, not " + count, count == 1); + assertThat(count == 1).as("1 beans registered, not " + count).isTrue(); testSingleTestBean(lbf); } @@ -550,13 +542,13 @@ public class DefaultListableBeanFactoryTests { p.setProperty(PREFIX + "kerry.spouse(ref)", "rod"); int count = (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p, PREFIX); - assertTrue("2 beans registered, not " + count, count == 2); + assertThat(count == 2).as("2 beans registered, not " + count).isTrue(); TestBean kerry = lbf.getBean("kerry", TestBean.class); - assertTrue("Kerry name is Kerry", "Kerry".equals(kerry.getName())); + assertThat("Kerry".equals(kerry.getName())).as("Kerry name is Kerry").isTrue(); ITestBean spouse = kerry.getSpouse(); - assertTrue("Kerry spouse is non null", spouse != null); - assertTrue("Kerry spouse name is Rod", "Rod".equals(spouse.getName())); + assertThat(spouse != null).as("Kerry spouse is non null").isTrue(); + assertThat("Rod".equals(spouse.getName())).as("Kerry spouse name is Rod").isTrue(); } @Test @@ -568,11 +560,11 @@ public class DefaultListableBeanFactoryTests { p.setProperty("tb.someMap[my.key]", "my.value"); int count = (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); - assertTrue("1 beans registered, not " + count, count == 1); - assertEquals(1, lbf.getBeanDefinitionCount()); + assertThat(count == 1).as("1 beans registered, not " + count).isTrue(); + assertThat(lbf.getBeanDefinitionCount()).isEqualTo(1); TestBean tb = lbf.getBean("tb", TestBean.class); - assertEquals("my.value", tb.getSomeMap().get("my.key")); + assertThat(tb.getSomeMap().get("my.key")).isEqualTo("my.value"); } @Test @@ -600,7 +592,7 @@ public class DefaultListableBeanFactoryTests { bd.setPropertyValues(pvs); lbf.registerBeanDefinition("self", bd); TestBean self = (TestBean) lbf.getBean("self"); - assertEquals(self, self.getSpouse()); + assertThat(self.getSpouse()).isEqualTo(self); } @Test @@ -630,8 +622,8 @@ public class DefaultListableBeanFactoryTests { (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); TestBean kerry1 = (TestBean) lbf.getBean("kerry"); TestBean kerry2 = (TestBean) lbf.getBean("kerry"); - assertTrue("Non null", kerry1 != null); - assertTrue("Singletons equal", kerry1 == kerry2); + assertThat(kerry1 != null).as("Non null").isTrue(); + assertThat(kerry1 == kerry2).as("Singletons equal").isTrue(); lbf = new DefaultListableBeanFactory(); p = new Properties(); @@ -641,8 +633,8 @@ public class DefaultListableBeanFactoryTests { (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); kerry1 = (TestBean) lbf.getBean("kerry"); kerry2 = (TestBean) lbf.getBean("kerry"); - assertTrue("Non null", kerry1 != null); - assertTrue("Prototypes NOT equal", kerry1 != kerry2); + assertThat(kerry1 != null).as("Non null").isTrue(); + assertThat(kerry1 != kerry2).as("Prototypes NOT equal").isTrue(); lbf = new DefaultListableBeanFactory(); p = new Properties(); @@ -652,8 +644,8 @@ public class DefaultListableBeanFactoryTests { (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); kerry1 = (TestBean) lbf.getBean("kerry"); kerry2 = (TestBean) lbf.getBean("kerry"); - assertTrue("Non null", kerry1 != null); - assertTrue("Specified singletons equal", kerry1 == kerry2); + assertThat(kerry1 != null).as("Non null").isTrue(); + assertThat(kerry1 == kerry2).as("Specified singletons equal").isTrue(); } @Test @@ -687,9 +679,9 @@ public class DefaultListableBeanFactoryTests { (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); TestBean kerry1 = (TestBean) lbf.getBean("kerry"); TestBean kerry2 = (TestBean) lbf.getBean("kerry"); - assertEquals("kerry", kerry1.getName()); - assertNotNull("Non null", kerry1); - assertTrue("Singletons equal", kerry1 == kerry2); + assertThat(kerry1.getName()).isEqualTo("kerry"); + assertThat(kerry1).as("Non null").isNotNull(); + assertThat(kerry1 == kerry2).as("Singletons equal").isTrue(); lbf = new DefaultListableBeanFactory(); p = new Properties(); @@ -700,11 +692,11 @@ public class DefaultListableBeanFactoryTests { p.setProperty("kerry.(singleton)", "false"); p.setProperty("kerry.age", "35"); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); - assertFalse(lbf.isSingleton("kerry")); + assertThat(lbf.isSingleton("kerry")).isFalse(); kerry1 = (TestBean) lbf.getBean("kerry"); kerry2 = (TestBean) lbf.getBean("kerry"); - assertTrue("Non null", kerry1 != null); - assertTrue("Prototypes NOT equal", kerry1 != kerry2); + assertThat(kerry1 != null).as("Non null").isTrue(); + assertThat(kerry1 != kerry2).as("Prototypes NOT equal").isTrue(); lbf = new DefaultListableBeanFactory(); p = new Properties(); @@ -714,8 +706,8 @@ public class DefaultListableBeanFactoryTests { (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); kerry1 = (TestBean) lbf.getBean("kerry"); kerry2 = (TestBean) lbf.getBean("kerry"); - assertTrue("Non null", kerry1 != null); - assertTrue("Specified singletons equal", kerry1 == kerry2); + assertThat(kerry1 != null).as("Non null").isTrue(); + assertThat(kerry1 == kerry2).as("Specified singletons equal").isTrue(); } @Test @@ -736,11 +728,11 @@ public class DefaultListableBeanFactoryTests { factory.registerAlias("parent", "alias"); TestBean child = (TestBean) factory.getBean("child"); - assertEquals(EXPECTED_NAME, child.getName()); - assertEquals(EXPECTED_AGE, child.getAge()); + assertThat(child.getName()).isEqualTo(EXPECTED_NAME); + assertThat(child.getAge()).isEqualTo(EXPECTED_AGE); + Object mergedBeanDefinition2 = factory.getMergedBeanDefinition("child"); - assertEquals("Use cached merged bean definition", - factory.getMergedBeanDefinition("child"), factory.getMergedBeanDefinition("child")); + assertThat(mergedBeanDefinition2).as("Use cached merged bean definition").isEqualTo(mergedBeanDefinition2); } @Test @@ -753,8 +745,8 @@ public class DefaultListableBeanFactoryTests { factory.registerBeanDefinition("child", childDefinition); factory.freezeConfiguration(); - assertEquals(TestBean.class, factory.getType("parent")); - assertEquals(DerivedTestBean.class, factory.getType("child")); + assertThat(factory.getType("parent")).isEqualTo(TestBean.class); + assertThat(factory.getType("child")).isEqualTo(DerivedTestBean.class); } @Test @@ -768,21 +760,21 @@ public class DefaultListableBeanFactoryTests { (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); } catch (BeanDefinitionStoreException ex) { - assertEquals("kerry", ex.getBeanName()); + assertThat(ex.getBeanName()).isEqualTo("kerry"); // expected } } private void testSingleTestBean(ListableBeanFactory lbf) { - assertTrue("1 beans defined", lbf.getBeanDefinitionCount() == 1); + assertThat(lbf.getBeanDefinitionCount() == 1).as("1 beans defined").isTrue(); String[] names = lbf.getBeanDefinitionNames(); - assertTrue(names != lbf.getBeanDefinitionNames()); - assertTrue("Array length == 1", names.length == 1); - assertTrue("0th element == test", names[0].equals("test")); + assertThat(names != lbf.getBeanDefinitionNames()).isTrue(); + assertThat(names.length == 1).as("Array length == 1").isTrue(); + assertThat(names[0].equals("test")).as("0th element == test").isTrue(); TestBean tb = (TestBean) lbf.getBean("test"); - assertTrue("Test is non null", tb != null); - assertTrue("Test bean name is Tony", "Tony".equals(tb.getName())); - assertTrue("Test bean age is 48", tb.getAge() == 48); + assertThat(tb != null).as("Test is non null").isTrue(); + assertThat("Tony".equals(tb.getName())).as("Test bean name is Tony").isTrue(); + assertThat(tb.getAge() == 48).as("Test bean age is 48").isTrue(); } @Test @@ -804,8 +796,8 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("test", new RootBeanDefinition(NestedTestBean.class)); lbf.registerAlias("otherTest", "test2"); lbf.registerAlias("test", "test2"); - assertTrue(lbf.getBean("test") instanceof NestedTestBean); - assertTrue(lbf.getBean("test2") instanceof NestedTestBean); + assertThat(lbf.getBean("test") instanceof NestedTestBean).isTrue(); + assertThat(lbf.getBean("test2") instanceof NestedTestBean).isTrue(); } @Test @@ -819,8 +811,8 @@ public class DefaultListableBeanFactoryTests { lbf.removeAlias("test2"); lbf.registerBeanDefinition("test", new RootBeanDefinition(NestedTestBean.class)); lbf.registerAlias("test", "test2"); - assertTrue(lbf.getBean("test") instanceof NestedTestBean); - assertTrue(lbf.getBean("test2") instanceof NestedTestBean); + assertThat(lbf.getBean("test") instanceof NestedTestBean).isTrue(); + assertThat(lbf.getBean("test2") instanceof NestedTestBean).isTrue(); } @Test @@ -846,8 +838,8 @@ public class DefaultListableBeanFactoryTests { lbf.registerAlias("test", "testAlias"); lbf.registerBeanDefinition("test", new RootBeanDefinition(NestedTestBean.class)); lbf.registerAlias("test", "testAlias"); - assertTrue(lbf.getBean("test") instanceof NestedTestBean); - assertTrue(lbf.getBean("testAlias") instanceof NestedTestBean); + assertThat(lbf.getBean("test") instanceof NestedTestBean).isTrue(); + assertThat(lbf.getBean("testAlias") instanceof NestedTestBean).isTrue(); } @Test @@ -858,9 +850,9 @@ public class DefaultListableBeanFactoryTests { lbf.registerAlias("testAlias", "testAlias2"); lbf.registerAlias("testAlias2", "testAlias3"); Object bean = lbf.getBean("test"); - assertSame(bean, lbf.getBean("testAlias")); - assertSame(bean, lbf.getBean("testAlias2")); - assertSame(bean, lbf.getBean("testAlias3")); + assertThat(lbf.getBean("testAlias")).isSameAs(bean); + assertThat(lbf.getBean("testAlias2")).isSameAs(bean); + assertThat(lbf.getBean("testAlias3")).isSameAs(bean); } @Test @@ -875,7 +867,7 @@ public class DefaultListableBeanFactoryTests { (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); TestBean k = (TestBean) lbf.getBean("k"); TestBean r = (TestBean) lbf.getBean("r"); - assertTrue(k.getSpouse() == r); + assertThat(k.getSpouse() == r).isTrue(); } @Test @@ -887,7 +879,7 @@ public class DefaultListableBeanFactoryTests { p.setProperty("r.name", "*" + name); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); TestBean r = (TestBean) lbf.getBean("r"); - assertTrue(r.getName().equals(name)); + assertThat(r.getName().equals(name)).isTrue(); } @Test @@ -906,7 +898,7 @@ public class DefaultListableBeanFactoryTests { bd.setPropertyValues(pvs); lbf.registerBeanDefinition("testBean", bd); TestBean testBean = (TestBean) lbf.getBean("testBean"); - assertTrue(testBean.getMyFloat().floatValue() == 1.1f); + assertThat(testBean.getMyFloat().floatValue() == 1.1f).isTrue(); } @Test @@ -932,7 +924,7 @@ public class DefaultListableBeanFactoryTests { bd.setPropertyValues(pvs); lbf.registerBeanDefinition("testBean", bd); TestBean testBean = (TestBean) lbf.getBean("testBean"); - assertTrue(testBean.getMyFloat().floatValue() == 1.1f); + assertThat(testBean.getMyFloat().floatValue() == 1.1f).isTrue(); } @Test @@ -952,7 +944,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("testBean", bd); lbf.registerSingleton("myFloat", "1,1"); TestBean testBean = (TestBean) lbf.getBean("testBean"); - assertTrue(testBean.getMyFloat().floatValue() == 1.1f); + assertThat(testBean.getMyFloat().floatValue() == 1.1f).isTrue(); } @Test @@ -967,9 +959,9 @@ public class DefaultListableBeanFactoryTests { cav.addIndexedArgumentValue(1, "myAge"); lbf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class, cav, pvs)); TestBean testBean = (TestBean) lbf.getBean("testBean"); - assertEquals("myName", testBean.getName()); - assertEquals(5, testBean.getAge()); - assertTrue(testBean.getMyFloat().floatValue() == 1.1f); + assertThat(testBean.getName()).isEqualTo("myName"); + assertThat(testBean.getAge()).isEqualTo(5); + assertThat(testBean.getMyFloat().floatValue() == 1.1f).isTrue(); } @Test @@ -985,9 +977,9 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class, cav, pvs)); lbf.registerSingleton("myFloat", "1,1"); TestBean testBean = (TestBean) lbf.getBean("testBean"); - assertEquals("myName", testBean.getName()); - assertEquals(5, testBean.getAge()); - assertTrue(testBean.getMyFloat().floatValue() == 1.1f); + assertThat(testBean.getName()).isEqualTo("myName"); + assertThat(testBean.getAge()).isEqualTo(5); + assertThat(testBean.getMyFloat().floatValue() == 1.1f).isTrue(); } @Test @@ -1002,29 +994,29 @@ public class DefaultListableBeanFactoryTests { Object singletonObject = new TestBean(); lbf.registerSingleton("singletonObject", singletonObject); - assertTrue(lbf.isSingleton("singletonObject")); - assertEquals(TestBean.class, lbf.getType("singletonObject")); + assertThat(lbf.isSingleton("singletonObject")).isTrue(); + assertThat(lbf.getType("singletonObject")).isEqualTo(TestBean.class); TestBean test = (TestBean) lbf.getBean("test"); - assertEquals(singletonObject, lbf.getBean("singletonObject")); - assertEquals(singletonObject, test.getSpouse()); + assertThat(lbf.getBean("singletonObject")).isEqualTo(singletonObject); + assertThat(test.getSpouse()).isEqualTo(singletonObject); Map beansOfType = lbf.getBeansOfType(TestBean.class, false, true); - assertEquals(2, beansOfType.size()); - assertTrue(beansOfType.containsValue(test)); - assertTrue(beansOfType.containsValue(singletonObject)); + assertThat(beansOfType.size()).isEqualTo(2); + assertThat(beansOfType.containsValue(test)).isTrue(); + assertThat(beansOfType.containsValue(singletonObject)).isTrue(); beansOfType = lbf.getBeansOfType(null, false, true); - assertEquals(2, beansOfType.size()); + assertThat(beansOfType.size()).isEqualTo(2); Iterator beanNames = lbf.getBeanNamesIterator(); - assertEquals("test", beanNames.next()); - assertEquals("singletonObject", beanNames.next()); - assertFalse(beanNames.hasNext()); + assertThat(beanNames.next()).isEqualTo("test"); + assertThat(beanNames.next()).isEqualTo("singletonObject"); + assertThat(beanNames.hasNext()).isFalse(); - assertTrue(lbf.containsSingleton("test")); - assertTrue(lbf.containsSingleton("singletonObject")); - assertTrue(lbf.containsBeanDefinition("test")); - assertFalse(lbf.containsBeanDefinition("singletonObject")); + assertThat(lbf.containsSingleton("test")).isTrue(); + assertThat(lbf.containsSingleton("singletonObject")).isTrue(); + assertThat(lbf.containsBeanDefinition("test")).isTrue(); + assertThat(lbf.containsBeanDefinition("singletonObject")).isFalse(); } @Test @@ -1041,29 +1033,29 @@ public class DefaultListableBeanFactoryTests { lbf.registerSingleton("singletonObject", singletonObject); lbf.preInstantiateSingletons(); - assertTrue(lbf.isSingleton("singletonObject")); - assertEquals(TestBean.class, lbf.getType("singletonObject")); + assertThat(lbf.isSingleton("singletonObject")).isTrue(); + assertThat(lbf.getType("singletonObject")).isEqualTo(TestBean.class); TestBean test = (TestBean) lbf.getBean("test"); - assertEquals(singletonObject, lbf.getBean("singletonObject")); - assertEquals(singletonObject, test.getSpouse()); + assertThat(lbf.getBean("singletonObject")).isEqualTo(singletonObject); + assertThat(test.getSpouse()).isEqualTo(singletonObject); Map beansOfType = lbf.getBeansOfType(TestBean.class, false, true); - assertEquals(2, beansOfType.size()); - assertTrue(beansOfType.containsValue(test)); - assertTrue(beansOfType.containsValue(singletonObject)); + assertThat(beansOfType.size()).isEqualTo(2); + assertThat(beansOfType.containsValue(test)).isTrue(); + assertThat(beansOfType.containsValue(singletonObject)).isTrue(); beansOfType = lbf.getBeansOfType(null, false, true); Iterator beanNames = lbf.getBeanNamesIterator(); - assertEquals("test", beanNames.next()); - assertEquals("singletonObject", beanNames.next()); - assertFalse(beanNames.hasNext()); - assertEquals(2, beansOfType.size()); + assertThat(beanNames.next()).isEqualTo("test"); + assertThat(beanNames.next()).isEqualTo("singletonObject"); + assertThat(beanNames.hasNext()).isFalse(); + assertThat(beansOfType.size()).isEqualTo(2); - assertTrue(lbf.containsSingleton("test")); - assertTrue(lbf.containsSingleton("singletonObject")); - assertTrue(lbf.containsBeanDefinition("test")); - assertTrue(lbf.containsBeanDefinition("singletonObject")); + assertThat(lbf.containsSingleton("test")).isTrue(); + assertThat(lbf.containsSingleton("singletonObject")).isTrue(); + assertThat(lbf.containsBeanDefinition("test")).isTrue(); + assertThat(lbf.containsBeanDefinition("singletonObject")).isTrue(); } @Test @@ -1080,13 +1072,13 @@ public class DefaultListableBeanFactoryTests { Object singletonObject = new TestBean(); lbf.registerSingleton("singletonObject", singletonObject); - assertTrue(lbf.containsBean("singletonObject")); - assertTrue(lbf.isSingleton("singletonObject")); - assertEquals(TestBean.class, lbf.getType("singletonObject")); - assertEquals(0, lbf.getAliases("singletonObject").length); + assertThat(lbf.containsBean("singletonObject")).isTrue(); + assertThat(lbf.isSingleton("singletonObject")).isTrue(); + assertThat(lbf.getType("singletonObject")).isEqualTo(TestBean.class); + assertThat(lbf.getAliases("singletonObject").length).isEqualTo(0); DependenciesBean test = (DependenciesBean) lbf.getBean("test"); - assertEquals(singletonObject, lbf.getBean("singletonObject")); - assertEquals(singletonObject, test.getSpouse()); + assertThat(lbf.getBean("singletonObject")).isEqualTo(singletonObject); + assertThat(test.getSpouse()).isEqualTo(singletonObject); } @Test @@ -1104,11 +1096,11 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class); bd1.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); lbf.registerBeanDefinition("testBean", bd1); - assertTrue(lbf.getBean("testBean") instanceof TestBean); + assertThat(lbf.getBean("testBean") instanceof TestBean).isTrue(); RootBeanDefinition bd2 = new RootBeanDefinition(NestedTestBean.class); bd2.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); lbf.registerBeanDefinition("testBean", bd2); - assertTrue(lbf.getBean("testBean") instanceof NestedTestBean); + assertThat(lbf.getBean("testBean") instanceof NestedTestBean).isTrue(); } @Test @@ -1122,8 +1114,8 @@ public class DefaultListableBeanFactoryTests { bf.registerBeanDefinition("arrayBean", rbd); ArrayBean ab = (ArrayBean) bf.getBean("arrayBean"); - assertEquals(new UrlResource("http://localhost:8080"), ab.getResourceArray()[0]); - assertEquals(new UrlResource("http://localhost:9090"), ab.getResourceArray()[1]); + assertThat(ab.getResourceArray()[0]).isEqualTo(new UrlResource("http://localhost:8080")); + assertThat(ab.getResourceArray()[1]).isEqualTo(new UrlResource("http://localhost:9090")); } @Test @@ -1135,7 +1127,7 @@ public class DefaultListableBeanFactoryTests { bf.registerBeanDefinition("arrayBean", rbd); ArrayBean ab = (ArrayBean) bf.getBean("arrayBean"); - assertNull(ab.getResourceArray()); + assertThat(ab.getResourceArray()).isNull(); } @Test @@ -1149,8 +1141,8 @@ public class DefaultListableBeanFactoryTests { bf.registerBeanDefinition("arrayBean", rbd); ArrayBean ab = (ArrayBean) bf.getBean("arrayBean"); - assertEquals(new Integer(4), ab.getIntegerArray()[0]); - assertEquals(new Integer(5), ab.getIntegerArray()[1]); + assertThat(ab.getIntegerArray()[0]).isEqualTo(new Integer(4)); + assertThat(ab.getIntegerArray()[1]).isEqualTo(new Integer(5)); } @Test @@ -1162,7 +1154,7 @@ public class DefaultListableBeanFactoryTests { bf.registerBeanDefinition("arrayBean", rbd); ArrayBean ab = (ArrayBean) bf.getBean("arrayBean"); - assertNull(ab.getIntegerArray()); + assertThat(ab.getIntegerArray()).isNull(); } @Test @@ -1178,10 +1170,10 @@ public class DefaultListableBeanFactoryTests { bf.registerBeanDefinition("arrayBean", rbd); ArrayBean ab = (ArrayBean) bf.getBean("arrayBean"); - assertEquals(new Integer(4), ab.getIntegerArray()[0]); - assertEquals(new Integer(5), ab.getIntegerArray()[1]); - assertEquals(new UrlResource("http://localhost:8080"), ab.getResourceArray()[0]); - assertEquals(new UrlResource("http://localhost:9090"), ab.getResourceArray()[1]); + assertThat(ab.getIntegerArray()[0]).isEqualTo(new Integer(4)); + assertThat(ab.getIntegerArray()[1]).isEqualTo(new Integer(5)); + assertThat(ab.getResourceArray()[0]).isEqualTo(new UrlResource("http://localhost:8080")); + assertThat(ab.getResourceArray()[1]).isEqualTo(new UrlResource("http://localhost:9090")); } @Test @@ -1195,8 +1187,8 @@ public class DefaultListableBeanFactoryTests { bf.registerBeanDefinition("arrayBean", rbd); ArrayBean ab = (ArrayBean) bf.getBean("arrayBean"); - assertNull(ab.getIntegerArray()); - assertNull(ab.getResourceArray()); + assertThat(ab.getIntegerArray()).isNull(); + assertThat(ab.getResourceArray()).isNull(); } @Test @@ -1213,7 +1205,7 @@ public class DefaultListableBeanFactoryTests { rbd.setPropertyValues(pvs); bf.registerBeanDefinition("myProperties", rbd); Properties properties = (Properties) bf.getBean("myProperties"); - assertEquals("bar", properties.getProperty("foo")); + assertThat(properties.getProperty("foo")).isEqualTo("bar"); } @Test @@ -1221,10 +1213,10 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); lbf.registerBeanDefinition("rod", bd); - assertEquals(1, lbf.getBeanDefinitionCount()); + assertThat(lbf.getBeanDefinitionCount()).isEqualTo(1); Object registered = lbf.autowire(NoDependencies.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); - assertEquals(1, lbf.getBeanDefinitionCount()); - assertTrue(registered instanceof NoDependencies); + assertThat(lbf.getBeanDefinitionCount()).isEqualTo(1); + assertThat(registered instanceof NoDependencies).isTrue(); } @Test @@ -1235,13 +1227,13 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setPropertyValues(pvs); lbf.registerBeanDefinition("rod", bd); - assertEquals(1, lbf.getBeanDefinitionCount()); + assertThat(lbf.getBeanDefinitionCount()).isEqualTo(1); // Depends on age, name and spouse (TestBean) Object registered = lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); - assertEquals(1, lbf.getBeanDefinitionCount()); + assertThat(lbf.getBeanDefinitionCount()).isEqualTo(1); DependenciesBean kerry = (DependenciesBean) registered; TestBean rod = (TestBean) lbf.getBean("rod"); - assertSame(rod, kerry.getSpouse()); + assertThat(kerry.getSpouse()).isSameAs(rod); } @Test @@ -1252,12 +1244,12 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setPropertyValues(pvs); lbf.registerBeanDefinition("rod", bd); - assertEquals(1, lbf.getBeanDefinitionCount()); + assertThat(lbf.getBeanDefinitionCount()).isEqualTo(1); Object registered = lbf.autowire(ConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false); - assertEquals(1, lbf.getBeanDefinitionCount()); + assertThat(lbf.getBeanDefinitionCount()).isEqualTo(1); ConstructorDependency kerry = (ConstructorDependency) registered; TestBean rod = (TestBean) lbf.getBean("rod"); - assertSame(rod, kerry.spouse); + assertThat(kerry.spouse).isSameAs(rod); } @Test @@ -1281,7 +1273,7 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setPropertyValues(pvs); lbf.registerBeanDefinition("rod", bd); - assertEquals(1, lbf.getBeanDefinitionCount()); + assertThat(lbf.getBeanDefinitionCount()).isEqualTo(1); assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> lbf.autowire(UnsatisfiedConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true)); } @@ -1294,8 +1286,8 @@ public class DefaultListableBeanFactoryTests { ConstructorDependenciesBean bean = (ConstructorDependenciesBean) lbf.autowire(ConstructorDependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true); Object spouse = lbf.getBean("spouse"); - assertTrue(bean.getSpouse1() == spouse); - assertTrue(BeanFactoryUtils.beanOfType(lbf, TestBean.class) == spouse); + assertThat(bean.getSpouse1() == spouse).isTrue(); + assertThat(BeanFactoryUtils.beanOfType(lbf, TestBean.class) == spouse).isTrue(); } @Test @@ -1306,8 +1298,8 @@ public class DefaultListableBeanFactoryTests { DependenciesBean bean = (DependenciesBean) lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true); TestBean spouse = (TestBean) lbf.getBean("spouse"); - assertEquals(spouse, bean.getSpouse()); - assertTrue(BeanFactoryUtils.beanOfType(lbf, TestBean.class) == spouse); + assertThat(bean.getSpouse()).isEqualTo(spouse); + assertThat(BeanFactoryUtils.beanOfType(lbf, TestBean.class) == spouse).isTrue(); } @Test @@ -1326,7 +1318,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("spous", bd); DependenciesBean bean = (DependenciesBean) lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false); - assertNull(bean.getSpouse()); + assertThat(bean.getSpouse()).isNull(); } @Test @@ -1403,7 +1395,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("bd2", bd2); TestBean bean = lbf.getBean(TestBean.class); assertThat(bean.getBeanName()).isEqualTo("bd2"); - assertFalse(lbf.containsSingleton("bd1")); + assertThat(lbf.containsSingleton("bd1")).isFalse(); } @Test @@ -1418,11 +1410,11 @@ public class DefaultListableBeanFactoryTests { NullTestBeanFactoryBean factoryBeanByType = lbf.getBean(NullTestBeanFactoryBean.class); NullTestBeanFactoryBean bd1FactoryBean = (NullTestBeanFactoryBean)lbf.getBean("&bd1"); NullTestBeanFactoryBean bd2FactoryBean = (NullTestBeanFactoryBean)lbf.getBean("&bd2"); - assertNotNull(factoryBeanByType); - assertNotNull(bd1FactoryBean); - assertNotNull(bd2FactoryBean); - assertNotEquals(factoryBeanByType, bd1FactoryBean); - assertEquals(factoryBeanByType, bd2FactoryBean); + assertThat(factoryBeanByType).isNotNull(); + assertThat(bd1FactoryBean).isNotNull(); + assertThat(bd2FactoryBean).isNotNull(); + assertThat(bd1FactoryBean).isNotEqualTo(factoryBeanByType); + assertThat(bd2FactoryBean).isEqualTo(factoryBeanByType); } @Test @@ -1521,7 +1513,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("na1", na1); TestBean actual = lbf.getBean(TestBean.class); // na1 was filtered - assertSame(lbf.getBean("bd1", TestBean.class), actual); + assertThat(actual).isSameAs(lbf.getBean("bd1", TestBean.class)); lbf.registerBeanDefinition("bd2", bd2); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> @@ -1540,8 +1532,8 @@ public class DefaultListableBeanFactoryTests { provider::getObject); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> provider.getObject(42)); - assertNull(provider.getIfAvailable()); - assertNull(provider.getIfUnique()); + assertThat(provider.getIfAvailable()).isNull(); + assertThat(provider.getIfUnique()).isNull(); } @Test @@ -1593,26 +1585,26 @@ public class DefaultListableBeanFactoryTests { provider.getObject(42)); assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy( provider::getIfAvailable); - assertNull(provider.getIfUnique()); + assertThat(provider.getIfUnique()).isNull(); Set resolved = new HashSet<>(); for (ConstructorDependency instance : provider) { resolved.add(instance); } - assertEquals(2, resolved.size()); - assertTrue(resolved.contains(lbf.getBean("bd1"))); - assertTrue(resolved.contains(lbf.getBean("bd2"))); + assertThat(resolved.size()).isEqualTo(2); + assertThat(resolved.contains(lbf.getBean("bd1"))).isTrue(); + assertThat(resolved.contains(lbf.getBean("bd2"))).isTrue(); resolved = new HashSet<>(); provider.forEach(resolved::add); - assertEquals(2, resolved.size()); - assertTrue(resolved.contains(lbf.getBean("bd1"))); - assertTrue(resolved.contains(lbf.getBean("bd2"))); + assertThat(resolved.size()).isEqualTo(2); + assertThat(resolved.contains(lbf.getBean("bd1"))).isTrue(); + assertThat(resolved.contains(lbf.getBean("bd2"))).isTrue(); resolved = provider.stream().collect(Collectors.toSet()); - assertEquals(2, resolved.size()); - assertTrue(resolved.contains(lbf.getBean("bd1"))); - assertTrue(resolved.contains(lbf.getBean("bd2"))); + assertThat(resolved.size()).isEqualTo(2); + assertThat(resolved.contains(lbf.getBean("bd1"))).isTrue(); + assertThat(resolved.contains(lbf.getBean("bd2"))).isTrue(); } @Test @@ -1649,20 +1641,20 @@ public class DefaultListableBeanFactoryTests { for (ConstructorDependency instance : provider) { resolved.add(instance); } - assertEquals(2, resolved.size()); - assertTrue(resolved.contains(lbf.getBean("bd1"))); - assertTrue(resolved.contains(lbf.getBean("bd2"))); + assertThat(resolved.size()).isEqualTo(2); + assertThat(resolved.contains(lbf.getBean("bd1"))).isTrue(); + assertThat(resolved.contains(lbf.getBean("bd2"))).isTrue(); resolved = new HashSet<>(); provider.forEach(resolved::add); - assertEquals(2, resolved.size()); - assertTrue(resolved.contains(lbf.getBean("bd1"))); - assertTrue(resolved.contains(lbf.getBean("bd2"))); + assertThat(resolved.size()).isEqualTo(2); + assertThat(resolved.contains(lbf.getBean("bd1"))).isTrue(); + assertThat(resolved.contains(lbf.getBean("bd2"))).isTrue(); resolved = provider.stream().collect(Collectors.toSet()); - assertEquals(2, resolved.size()); - assertTrue(resolved.contains(lbf.getBean("bd1"))); - assertTrue(resolved.contains(lbf.getBean("bd2"))); + assertThat(resolved.size()).isEqualTo(2); + assertThat(resolved.contains(lbf.getBean("bd1"))).isTrue(); + assertThat(resolved.contains(lbf.getBean("bd2"))).isTrue(); } @Test @@ -1710,8 +1702,8 @@ public class DefaultListableBeanFactoryTests { deserialized::getObject); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> deserialized.getObject(42)); - assertNull(deserialized.getIfAvailable()); - assertNull(deserialized.getIfUnique()); + assertThat(deserialized.getIfAvailable()).isNull(); + assertThat(deserialized.getIfUnique()).isNull(); } @Test @@ -1728,10 +1720,10 @@ public class DefaultListableBeanFactoryTests { assertThat(bean.beanName).isEqualTo("bd1"); assertThat(bean.spouseAge).isEqualTo(42); - assertEquals(1, lbf.getBeanNamesForType(ConstructorDependency.class).length); - assertEquals(1, lbf.getBeanNamesForType(ConstructorDependencyFactoryBean.class).length); - assertEquals(1, lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class)).length); - assertEquals(0, lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, String.class)).length); + assertThat(lbf.getBeanNamesForType(ConstructorDependency.class).length).isEqualTo(1); + assertThat(lbf.getBeanNamesForType(ConstructorDependencyFactoryBean.class).length).isEqualTo(1); + assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class)).length).isEqualTo(1); + assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, String.class)).length).isEqualTo(0); } private RootBeanDefinition createConstructorDependencyBeanDefinition(int age) { @@ -1749,7 +1741,7 @@ public class DefaultListableBeanFactoryTests { DependenciesBean bean = (DependenciesBean) lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); TestBean test = (TestBean) lbf.getBean("test"); - assertEquals(test, bean.getSpouse()); + assertThat(bean.getSpouse()).isEqualTo(test); } /** @@ -1764,11 +1756,11 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(LazyInitFactory.class); lbf.registerBeanDefinition("factoryBean", bd); LazyInitFactory factoryBean = (LazyInitFactory) lbf.getBean("&factoryBean"); - assertNotNull("The FactoryBean should have been registered.", factoryBean); + assertThat(factoryBean).as("The FactoryBean should have been registered.").isNotNull(); FactoryBeanDependentBean bean = (FactoryBeanDependentBean) lbf.autowire(FactoryBeanDependentBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); - assertEquals("The FactoryBeanDependentBean should have been autowired 'by type' with the LazyInitFactory.", - factoryBean, bean.getFactoryBean()); + Object mergedBeanDefinition2 = bean.getFactoryBean(); + assertThat(mergedBeanDefinition2).as("The FactoryBeanDependentBean should have been autowired 'by type' with the LazyInitFactory.").isEqualTo(mergedBeanDefinition2); } @Test @@ -1781,12 +1773,12 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("bd2", bd2); LazyInitFactory bd1FactoryBean = (LazyInitFactory) lbf.getBean("&bd1"); LazyInitFactory bd2FactoryBean = (LazyInitFactory) lbf.getBean("&bd2"); - assertNotNull(bd1FactoryBean); - assertNotNull(bd2FactoryBean); + assertThat(bd1FactoryBean).isNotNull(); + assertThat(bd2FactoryBean).isNotNull(); FactoryBeanDependentBean bean = (FactoryBeanDependentBean) lbf.autowire(FactoryBeanDependentBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); - assertNotEquals(bd1FactoryBean, bean.getFactoryBean()); - assertEquals(bd2FactoryBean, bean.getFactoryBean()); + assertThat(bean.getFactoryBean()).isNotEqualTo(bd1FactoryBean); + assertThat(bean.getFactoryBean()).isEqualTo(bd2FactoryBean); } @Test @@ -1795,30 +1787,30 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(FactoryBeanThatShouldntBeCalled.class); bd.setAbstract(true); lbf.registerBeanDefinition("factoryBean", bd); - assertNull(lbf.getType("factoryBean")); + assertThat(lbf.getType("factoryBean")).isNull(); } @Test public void testGetBeanNamesForTypeBeforeFactoryBeanCreation() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); lbf.registerBeanDefinition("factoryBean", new RootBeanDefinition(FactoryBeanThatShouldntBeCalled.class)); - assertFalse(lbf.containsSingleton("factoryBean")); + assertThat(lbf.containsSingleton("factoryBean")).isFalse(); String[] beanNames = lbf.getBeanNamesForType(Runnable.class, false, false); - assertEquals(1, beanNames.length); - assertEquals("&factoryBean", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("&factoryBean"); beanNames = lbf.getBeanNamesForType(Callable.class, false, false); - assertEquals(1, beanNames.length); - assertEquals("&factoryBean", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("&factoryBean"); beanNames = lbf.getBeanNamesForType(RepositoryFactoryInformation.class, false, false); - assertEquals(1, beanNames.length); - assertEquals("&factoryBean", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("&factoryBean"); beanNames = lbf.getBeanNamesForType(FactoryBean.class, false, false); - assertEquals(1, beanNames.length); - assertEquals("&factoryBean", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("&factoryBean"); } @Test @@ -1828,20 +1820,20 @@ public class DefaultListableBeanFactoryTests { lbf.getBean("&factoryBean"); String[] beanNames = lbf.getBeanNamesForType(Runnable.class, false, false); - assertEquals(1, beanNames.length); - assertEquals("&factoryBean", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("&factoryBean"); beanNames = lbf.getBeanNamesForType(Callable.class, false, false); - assertEquals(1, beanNames.length); - assertEquals("&factoryBean", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("&factoryBean"); beanNames = lbf.getBeanNamesForType(RepositoryFactoryInformation.class, false, false); - assertEquals(1, beanNames.length); - assertEquals("&factoryBean", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("&factoryBean"); beanNames = lbf.getBeanNamesForType(FactoryBean.class, false, false); - assertEquals(1, beanNames.length); - assertEquals("&factoryBean", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("&factoryBean"); } /** @@ -1856,7 +1848,7 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(LazyInitFactory.class); lbf.registerBeanDefinition("factoryBean", bd); LazyInitFactory factoryBean = (LazyInitFactory) lbf.getBean("&factoryBean"); - assertNotNull("The FactoryBean should have been registered.", factoryBean); + assertThat(factoryBean).as("The FactoryBean should have been registered.").isNotNull(); assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() -> lbf.autowire(FactoryBeanDependentBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true)); } @@ -1886,7 +1878,7 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); DependenciesBean bean = (DependenciesBean) lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); - assertNull(bean.getSpouse()); + assertThat(bean.getSpouse()).isNull(); } @Test @@ -1968,8 +1960,8 @@ public class DefaultListableBeanFactoryTests { DependenciesBean existingBean = new DependenciesBean(); lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true); TestBean spouse = (TestBean) lbf.getBean("spouse"); - assertEquals(existingBean.getSpouse(), spouse); - assertSame(spouse, BeanFactoryUtils.beanOfType(lbf, TestBean.class)); + assertThat(spouse).isEqualTo(existingBean.getSpouse()); + assertThat(BeanFactoryUtils.beanOfType(lbf, TestBean.class)).isSameAs(spouse); } @Test @@ -1989,7 +1981,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("spous", bd); DependenciesBean existingBean = new DependenciesBean(); lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false); - assertNull(existingBean.getSpouse()); + assertThat(existingBean.getSpouse()).isNull(); } @Test @@ -2000,7 +1992,7 @@ public class DefaultListableBeanFactoryTests { DependenciesBean existingBean = new DependenciesBean(); lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); TestBean test = (TestBean) lbf.getBean("test"); - assertEquals(existingBean.getSpouse(), test); + assertThat(test).isEqualTo(existingBean.getSpouse()); } @Test @@ -2016,7 +2008,7 @@ public class DefaultListableBeanFactoryTests { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); DependenciesBean existingBean = new DependenciesBean(); lbf.autowireBeanProperties(existingBean, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); - assertNull(existingBean.getSpouse()); + assertThat(existingBean.getSpouse()).isNull(); } @Test @@ -2035,9 +2027,9 @@ public class DefaultListableBeanFactoryTests { bd.setPropertyValues(pvs); lbf.registerBeanDefinition("test", bd); TestBean tb = new TestBean(); - assertEquals(0, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(0); lbf.applyBeanPropertyValues(tb, "test"); - assertEquals(99, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(99); } @Test @@ -2049,18 +2041,18 @@ public class DefaultListableBeanFactoryTests { bd.setPropertyValues(pvs); lbf.registerBeanDefinition("test", bd); TestBean tb = new TestBean(); - assertEquals(0, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(0); lbf.applyBeanPropertyValues(tb, "test"); - assertEquals(99, tb.getAge()); - assertNull(tb.getBeanFactory()); - assertNull(tb.getSpouse()); + assertThat(tb.getAge()).isEqualTo(99); + assertThat(tb.getBeanFactory()).isNull(); + assertThat(tb.getSpouse()).isNull(); } @Test public void testCreateBean() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); TestBean tb = lbf.createBean(TestBean.class); - assertSame(lbf, tb.getBeanFactory()); + assertThat(tb.getBeanFactory()).isSameAs(lbf); lbf.destroyBean(tb); } @@ -2068,9 +2060,9 @@ public class DefaultListableBeanFactoryTests { public void testCreateBeanWithDisposableBean() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); DerivedTestBean tb = lbf.createBean(DerivedTestBean.class); - assertSame(lbf, tb.getBeanFactory()); + assertThat(tb.getBeanFactory()).isSameAs(lbf); lbf.destroyBean(tb); - assertTrue(tb.wasDestroyed()); + assertThat(tb.wasDestroyed()).isTrue(); } @Test @@ -2082,11 +2074,11 @@ public class DefaultListableBeanFactoryTests { bd.setPropertyValues(pvs); lbf.registerBeanDefinition("test", bd); TestBean tb = new TestBean(); - assertEquals(0, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(0); lbf.configureBean(tb, "test"); - assertEquals(99, tb.getAge()); - assertSame(lbf, tb.getBeanFactory()); - assertNull(tb.getSpouse()); + assertThat(tb.getAge()).isEqualTo(99); + assertThat(tb.getBeanFactory()).isSameAs(lbf); + assertThat(tb.getSpouse()).isNull(); } @Test @@ -2101,9 +2093,9 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("test", tbd); TestBean tb = new TestBean(); lbf.configureBean(tb, "test"); - assertSame(lbf, tb.getBeanFactory()); + assertThat(tb.getBeanFactory()).isSameAs(lbf); TestBean spouse = (TestBean) lbf.getBean("spouse"); - assertEquals(spouse, tb.getSpouse()); + assertThat(tb.getSpouse()).isEqualTo(spouse); } @Test @@ -2120,7 +2112,7 @@ public class DefaultListableBeanFactoryTests { for (int i = 0; i < 1000; i++) { TestBean bean = (TestBean) lbf.getBean("bean" + i); TestBean otherBean = (TestBean) lbf.getBean("bean" + (i < 99 ? i + 1 : 0)); - assertTrue(bean.getSpouse() == otherBean); + assertThat(bean.getSpouse() == otherBean).isTrue(); } } @@ -2223,14 +2215,14 @@ public class DefaultListableBeanFactoryTests { factory.registerBeanDefinition("tb2", bd2); factory.registerBeanDefinition("tb3", new RootBeanDefinition(TestBean.class)); - assertEquals(Boolean.TRUE, ((AbstractBeanDefinition) factory.getMergedBeanDefinition("tb1")).getLazyInit()); - assertEquals(Boolean.FALSE, ((AbstractBeanDefinition) factory.getMergedBeanDefinition("tb2")).getLazyInit()); - assertNull(((AbstractBeanDefinition) factory.getMergedBeanDefinition("tb3")).getLazyInit()); + assertThat(((AbstractBeanDefinition) factory.getMergedBeanDefinition("tb1")).getLazyInit()).isEqualTo(Boolean.TRUE); + assertThat(((AbstractBeanDefinition) factory.getMergedBeanDefinition("tb2")).getLazyInit()).isEqualTo(Boolean.FALSE); + assertThat(((AbstractBeanDefinition) factory.getMergedBeanDefinition("tb3")).getLazyInit()).isNull(); factory.preInstantiateSingletons(); - assertFalse(factory.containsSingleton("tb1")); - assertTrue(factory.containsSingleton("tb2")); - assertTrue(factory.containsSingleton("tb3")); + assertThat(factory.containsSingleton("tb1")).isFalse(); + assertThat(factory.containsSingleton("tb2")).isTrue(); + assertThat(factory.containsSingleton("tb3")).isTrue(); } @Test @@ -2239,7 +2231,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("test", new RootBeanDefinition(LazyInitFactory.class)); lbf.preInstantiateSingletons(); LazyInitFactory factory = (LazyInitFactory) lbf.getBean("&test"); - assertFalse(factory.initialized); + assertThat(factory.initialized).isFalse(); } @Test @@ -2248,7 +2240,7 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("test", new RootBeanDefinition(EagerInitFactory.class)); lbf.preInstantiateSingletons(); EagerInitFactory factory = (EagerInitFactory) lbf.getBean("&test"); - assertTrue(factory.initialized); + assertThat(factory.initialized).isTrue(); } @Test @@ -2268,9 +2260,9 @@ public class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("string", stringDef); String val1 = lbf.getBean("string", String.class); String val2 = lbf.getBean("string", String.class); - assertEquals("value", val1); - assertEquals("value", val2); - assertNotSame(val1, val2); + assertThat(val1).isEqualTo("value"); + assertThat(val2).isEqualTo("value"); + assertThat(val2).isNotSameAs(val1); } @Test @@ -2284,12 +2276,12 @@ public class DefaultListableBeanFactoryTests { bd.getConstructorArgumentValues().addGenericArgumentValue(list); lbf.registerBeanDefinition("test", bd); DerivedTestBean tb = (DerivedTestBean) lbf.getBean("test"); - assertEquals("myName", tb.getName()); - assertEquals("myBeanName", tb.getBeanName()); + assertThat(tb.getName()).isEqualTo("myName"); + assertThat(tb.getBeanName()).isEqualTo("myBeanName"); DerivedTestBean tb2 = (DerivedTestBean) lbf.getBean("test"); - assertTrue(tb != tb2); - assertEquals("myName", tb2.getName()); - assertEquals("myBeanName", tb2.getBeanName()); + assertThat(tb != tb2).isTrue(); + assertThat(tb2.getName()).isEqualTo("myName"); + assertThat(tb2.getBeanName()).isEqualTo("myBeanName"); } @Test @@ -2304,12 +2296,12 @@ public class DefaultListableBeanFactoryTests { bd.getConstructorArgumentValues().addGenericArgumentValue(list); lbf.registerBeanDefinition("test", bd); DerivedTestBean tb = (DerivedTestBean) lbf.getBean("test"); - assertEquals("myName", tb.getName()); - assertEquals("myBeanName", tb.getBeanName()); + assertThat(tb.getName()).isEqualTo("myName"); + assertThat(tb.getBeanName()).isEqualTo("myBeanName"); DerivedTestBean tb2 = (DerivedTestBean) lbf.getBean("test"); - assertTrue(tb != tb2); - assertEquals("myName", tb2.getName()); - assertEquals("myBeanName", tb2.getBeanName()); + assertThat(tb != tb2).isTrue(); + assertThat(tb2.getName()).isEqualTo("myName"); + assertThat(tb2.getBeanName()).isEqualTo("myBeanName"); } @Test @@ -2328,7 +2320,7 @@ public class DefaultListableBeanFactoryTests { } sw.stop(); // System.out.println(sw.getTotalTimeMillis()); - assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 3000); + assertThat(sw.getTotalTimeMillis() < 3000).as("Prototype creation took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -2349,7 +2341,7 @@ public class DefaultListableBeanFactoryTests { } sw.stop(); // System.out.println(sw.getTotalTimeMillis()); - assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 3000); + assertThat(sw.getTotalTimeMillis() < 3000).as("Prototype creation took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -2368,12 +2360,12 @@ public class DefaultListableBeanFactoryTests { sw.start("prototype"); for (int i = 0; i < 100000; i++) { TestBean tb = (TestBean) lbf.getBean("test"); - assertEquals("juergen", tb.getName()); - assertEquals(99, tb.getAge()); + assertThat(tb.getName()).isEqualTo("juergen"); + assertThat(tb.getAge()).isEqualTo(99); } sw.stop(); // System.out.println(sw.getTotalTimeMillis()); - assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 3000); + assertThat(sw.getTotalTimeMillis() < 3000).as("Prototype creation took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -2392,11 +2384,11 @@ public class DefaultListableBeanFactoryTests { sw.start("prototype"); for (int i = 0; i < 100000; i++) { TestBean tb = (TestBean) lbf.getBean("test"); - assertSame(spouse, tb.getSpouse()); + assertThat(tb.getSpouse()).isSameAs(spouse); } sw.stop(); // System.out.println(sw.getTotalTimeMillis()); - assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 4000); + assertThat(sw.getTotalTimeMillis() < 4000).as("Prototype creation took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -2414,12 +2406,12 @@ public class DefaultListableBeanFactoryTests { sw.start("prototype"); for (int i = 0; i < 100000; i++) { TestBean tb = (TestBean) lbf.getBean("test"); - assertEquals("juergen", tb.getName()); - assertEquals(99, tb.getAge()); + assertThat(tb.getName()).isEqualTo("juergen"); + assertThat(tb.getAge()).isEqualTo(99); } sw.stop(); // System.out.println(sw.getTotalTimeMillis()); - assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 4000); + assertThat(sw.getTotalTimeMillis() < 4000).as("Prototype creation took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -2438,11 +2430,11 @@ public class DefaultListableBeanFactoryTests { sw.start("prototype"); for (int i = 0; i < 100000; i++) { TestBean tb = (TestBean) lbf.getBean("test"); - assertSame(spouse, tb.getSpouse()); + assertThat(tb.getSpouse()).isSameAs(spouse); } sw.stop(); // System.out.println(sw.getTotalTimeMillis()); - assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 4000); + assertThat(sw.getTotalTimeMillis() < 4000).as("Prototype creation took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -2459,7 +2451,7 @@ public class DefaultListableBeanFactoryTests { } sw.stop(); // System.out.println(sw.getTotalTimeMillis()); - assertTrue("Singleton lookup took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 1000); + assertThat(sw.getTotalTimeMillis() < 1000).as("Singleton lookup took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -2476,7 +2468,7 @@ public class DefaultListableBeanFactoryTests { } sw.stop(); // System.out.println(sw.getTotalTimeMillis()); - assertTrue("Singleton lookup took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 1000); + assertThat(sw.getTotalTimeMillis() < 1000).as("Singleton lookup took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -2493,7 +2485,7 @@ public class DefaultListableBeanFactoryTests { BeanWithDisposableBean.closed = false; lbf.preInstantiateSingletons(); lbf.destroySingletons(); - assertTrue("Destroy method invoked", BeanWithDisposableBean.closed); + assertThat(BeanWithDisposableBean.closed).as("Destroy method invoked").isTrue(); } @Test @@ -2510,7 +2502,7 @@ public class DefaultListableBeanFactoryTests { BeanWithDisposableBean.closed = false; lbf.preInstantiateSingletons(); lbf.destroySingletons(); - assertTrue("Destroy method invoked", BeanWithCloseable.closed); + assertThat(BeanWithCloseable.closed).as("Destroy method invoked").isTrue(); } @Test @@ -2528,7 +2520,8 @@ public class DefaultListableBeanFactoryTests { BeanWithDestroyMethod.closeCount = 0; lbf.preInstantiateSingletons(); lbf.destroySingletons(); - assertEquals("Destroy methods invoked", 1, BeanWithDestroyMethod.closeCount); + Object mergedBeanDefinition2 = BeanWithDestroyMethod.closeCount; + assertThat(mergedBeanDefinition2).as("Destroy methods invoked").isEqualTo(mergedBeanDefinition2); } @Test @@ -2543,7 +2536,8 @@ public class DefaultListableBeanFactoryTests { BeanWithDestroyMethod.closeCount = 0; lbf.preInstantiateSingletons(); lbf.destroySingletons(); - assertEquals("Destroy methods invoked", 2, BeanWithDestroyMethod.closeCount); + Object mergedBeanDefinition2 = BeanWithDestroyMethod.closeCount; + assertThat(mergedBeanDefinition2).as("Destroy methods invoked").isEqualTo(mergedBeanDefinition2); } @Test @@ -2559,7 +2553,8 @@ public class DefaultListableBeanFactoryTests { BeanWithDestroyMethod.closeCount = 0; lbf.preInstantiateSingletons(); lbf.destroySingletons(); - assertEquals("Destroy methods invoked", 1, BeanWithDestroyMethod.closeCount); + Object mergedBeanDefinition2 = BeanWithDestroyMethod.closeCount; + assertThat(mergedBeanDefinition2).as("Destroy methods invoked").isEqualTo(mergedBeanDefinition2); } @Test @@ -2617,41 +2612,41 @@ public class DefaultListableBeanFactoryTests { } lbf.registerBeanDefinition("fmWithArgs", factoryMethodDefinitionWithArgs); - assertEquals(4, lbf.getBeanDefinitionCount()); + assertThat(lbf.getBeanDefinitionCount()).isEqualTo(4); List tbNames = Arrays.asList(lbf.getBeanNamesForType(TestBean.class)); - assertTrue(tbNames.contains("fmWithProperties")); - assertTrue(tbNames.contains("fmWithArgs")); - assertEquals(2, tbNames.size()); + assertThat(tbNames.contains("fmWithProperties")).isTrue(); + assertThat(tbNames.contains("fmWithArgs")).isTrue(); + assertThat(tbNames.size()).isEqualTo(2); TestBean tb = (TestBean) lbf.getBean("fmWithProperties"); TestBean second = (TestBean) lbf.getBean("fmWithProperties"); if (singleton) { - assertSame(tb, second); + assertThat(second).isSameAs(tb); } else { - assertNotSame(tb, second); + assertThat(second).isNotSameAs(tb); } - assertEquals(expectedNameFromProperties, tb.getName()); + assertThat(tb.getName()).isEqualTo(expectedNameFromProperties); tb = (TestBean) lbf.getBean("fmGeneric"); second = (TestBean) lbf.getBean("fmGeneric"); if (singleton) { - assertSame(tb, second); + assertThat(second).isSameAs(tb); } else { - assertNotSame(tb, second); + assertThat(second).isNotSameAs(tb); } - assertEquals(expectedNameFromProperties, tb.getName()); + assertThat(tb.getName()).isEqualTo(expectedNameFromProperties); TestBean tb2 = (TestBean) lbf.getBean("fmWithArgs"); second = (TestBean) lbf.getBean("fmWithArgs"); if (singleton) { - assertSame(tb2, second); + assertThat(second).isSameAs(tb2); } else { - assertNotSame(tb2, second); + assertThat(second).isNotSameAs(tb2); } - assertEquals(expectedNameFromArgs, tb2.getName()); + assertThat(tb2.getName()).isEqualTo(expectedNameFromArgs); } @Test @@ -2682,7 +2677,8 @@ public class DefaultListableBeanFactoryTests { factory.registerBeanDefinition("child", child); AbstractBeanDefinition def = (AbstractBeanDefinition) factory.getBeanDefinition("child"); - assertEquals("Child 'scope' not overriding parent scope (it must).", theChildScope, def.getScope()); + Object mergedBeanDefinition2 = def.getScope(); + assertThat(mergedBeanDefinition2).as("Child 'scope' not overriding parent scope (it must).").isEqualTo(mergedBeanDefinition2); } @Test @@ -2698,7 +2694,8 @@ public class DefaultListableBeanFactoryTests { factory.registerBeanDefinition("child", child); BeanDefinition def = factory.getMergedBeanDefinition("child"); - assertEquals("Child 'scope' not inherited", "bonanza!", def.getScope()); + Object mergedBeanDefinition2 = def.getScope(); + assertThat(mergedBeanDefinition2).as("Child 'scope' not inherited").isEqualTo(mergedBeanDefinition2); } @Test @@ -2735,12 +2732,15 @@ public class DefaultListableBeanFactoryTests { }); lbf.preInstantiateSingletons(); TestBean tb = (TestBean) lbf.getBean("test"); - assertEquals("Name was set on field by IAPP", nameSetOnField, tb.getName()); + Object mergedBeanDefinition2 = tb.getName(); + assertThat(mergedBeanDefinition2).as("Name was set on field by IAPP").isEqualTo(mergedBeanDefinition2); if (!skipPropertyPopulation) { - assertEquals("Property value still set", ageSetByPropertyValue, tb.getAge()); + Object mergedBeanDefinition21 = tb.getAge(); + assertThat(mergedBeanDefinition21).as("Property value still set").isEqualTo(mergedBeanDefinition21); } else { - assertEquals("Property value was NOT set and still has default value", 0, tb.getAge()); + Object mergedBeanDefinition21 = tb.getAge(); + assertThat(mergedBeanDefinition21).as("Property value was NOT set and still has default value").isEqualTo(mergedBeanDefinition21); } } @@ -2757,8 +2757,8 @@ public class DefaultListableBeanFactoryTests { TestSecuredBean bean = (TestSecuredBean) Subject.doAsPrivileged(subject, (PrivilegedAction) () -> lbf.getBean("test"), null); - assertNotNull(bean); - assertEquals("user1", bean.getUserName()); + assertThat(bean).isNotNull(); + assertThat(bean.getUserName()).isEqualTo("user1"); } @Test @@ -2797,7 +2797,7 @@ public class DefaultListableBeanFactoryTests { bd.setFactoryMethodName("of"); bd.getConstructorArgumentValues().addGenericArgumentValue("CONTENT"); bf.registerBeanDefinition("optionalBean", bd); - assertEquals(Optional.of("CONTENT"), bf.getBean(Optional.class)); + assertThat((Optional) bf.getBean(Optional.class)).isEqualTo(Optional.of("CONTENT")); } @Test @@ -2806,7 +2806,7 @@ public class DefaultListableBeanFactoryTests { RootBeanDefinition bd = new RootBeanDefinition(Optional.class); bd.setFactoryMethodName("empty"); bf.registerBeanDefinition("optionalBean", bd); - assertSame(Optional.empty(), bf.getBean(Optional.class)); + assertThat((Optional) bf.getBean(Optional.class)).isSameAs(Optional.empty()); } @Test @@ -2816,7 +2816,7 @@ public class DefaultListableBeanFactoryTests { bd.getConstructorArgumentValues().addGenericArgumentValue("VALUE_1"); bf.registerBeanDefinition("holderBean", bd); NonPublicEnumHolder holder = (NonPublicEnumHolder) bf.getBean("holderBean"); - assertEquals(NonPublicEnum.VALUE_1, holder.getNonPublicEnum()); + assertThat(holder.getNonPublicEnum()).isEqualTo(NonPublicEnum.VALUE_1); } /** diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanLookupTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanLookupTests.java index 4986d5c4c66..e7889ac4145 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanLookupTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanLookupTests.java @@ -26,7 +26,6 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; /** * Written with the intention of reproducing SPR-7318. @@ -52,13 +51,13 @@ public class FactoryBeanLookupTests { @Test public void factoryBeanLookupByType() { FooFactoryBean fooFactory = beanFactory.getBean(FooFactoryBean.class); - assertNotNull(fooFactory); + assertThat(fooFactory).isNotNull(); } @Test public void factoryBeanLookupByTypeAndNameDereference() { FooFactoryBean fooFactory = beanFactory.getBean("&fooFactory", FooFactoryBean.class); - assertNotNull(fooFactory); + assertThat(fooFactory).isNotNull(); } @Test @@ -70,7 +69,7 @@ public class FactoryBeanLookupTests { @Test public void factoryBeanObjectLookupByNameAndType() { Foo foo = beanFactory.getBean("fooFactory", Foo.class); - assertNotNull(foo); + assertThat(foo).isNotNull(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanTests.java index 32c0c968e4a..78ae71d453f 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanTests.java @@ -30,10 +30,7 @@ import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import org.springframework.util.Assert; -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.assertj.core.api.Assertions.assertThat; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -55,7 +52,7 @@ public class FactoryBeanTests { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(factory).loadBeanDefinitions(RETURNS_NULL_CONTEXT); - assertEquals("null", factory.getBean("factoryBean").toString()); + assertThat(factory.getBean("factoryBean").toString()).isEqualTo("null"); } @Test @@ -66,17 +63,17 @@ public class FactoryBeanTests { BeanFactoryPostProcessor ppc = (BeanFactoryPostProcessor) factory.getBean("propertyPlaceholderConfigurer"); ppc.postProcessBeanFactory(factory); - assertNull(factory.getType("betaFactory")); + assertThat(factory.getType("betaFactory")).isNull(); Alpha alpha = (Alpha) factory.getBean("alpha"); Beta beta = (Beta) factory.getBean("beta"); Gamma gamma = (Gamma) factory.getBean("gamma"); Gamma gamma2 = (Gamma) factory.getBean("gammaFactory"); - assertSame(beta, alpha.getBeta()); - assertSame(gamma, beta.getGamma()); - assertSame(gamma2, beta.getGamma()); - assertEquals("yourName", beta.getName()); + assertThat(alpha.getBeta()).isSameAs(beta); + assertThat(beta.getGamma()).isSameAs(gamma); + assertThat(beta.getGamma()).isSameAs(gamma2); + assertThat(beta.getName()).isEqualTo("yourName"); } @Test @@ -90,8 +87,8 @@ public class FactoryBeanTests { Beta beta = (Beta) factory.getBean("beta"); Alpha alpha = (Alpha) factory.getBean("alpha"); Gamma gamma = (Gamma) factory.getBean("gamma"); - assertSame(beta, alpha.getBeta()); - assertSame(gamma, beta.getGamma()); + assertThat(alpha.getBeta()).isSameAs(beta); + assertThat(beta.getGamma()).isSameAs(gamma); } @Test @@ -117,12 +114,12 @@ public class FactoryBeanTests { factory.addBeanPostProcessor(counter); BeanImpl1 impl1 = factory.getBean(BeanImpl1.class); - assertNotNull(impl1); - assertNotNull(impl1.getImpl2()); - assertNotNull(impl1.getImpl2()); - assertSame(impl1, impl1.getImpl2().getImpl1()); - assertEquals(1, counter.getCount("bean1")); - assertEquals(1, counter.getCount("bean2")); + assertThat(impl1).isNotNull(); + assertThat(impl1.getImpl2()).isNotNull(); + assertThat(impl1.getImpl2()).isNotNull(); + assertThat(impl1.getImpl2().getImpl1()).isSameAs(impl1); + assertThat(counter.getCount("bean1")).isEqualTo(1); + assertThat(counter.getCount("bean2")).isEqualTo(1); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolverTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolverTests.java index ff49dc6504c..3b7d0658b76 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolverTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolverTests.java @@ -20,11 +20,8 @@ import org.junit.Test; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; /** * @author Rick Evans @@ -42,32 +39,32 @@ public class AnnotationBeanWiringInfoResolverTests { public void testResolveWiringInfoWithAnInstanceOfANonAnnotatedClass() { AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver(); 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 public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClass() { AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver(); 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 public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClassWithAutowiringTurnedOffExplicitly() { AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver(); BeanWiringInfo info = resolver.resolveWiringInfo(new WirelessSoap()); - assertNotNull("Must *not* be returning null for an @Configurable class instance even when autowiring is NO", info); - assertFalse(info.indicatesAutowiring()); - assertEquals(WirelessSoap.class.getName(), info.getBeanName()); + assertThat(info).as("Must *not* be returning null for an @Configurable class instance even when autowiring is NO").isNotNull(); + assertThat(info.indicatesAutowiring()).isFalse(); + assertThat(info.getBeanName()).isEqualTo(WirelessSoap.class.getName()); } @Test public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClassWithAutowiringTurnedOffExplicitlyAndCustomBeanName() { AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver(); BeanWiringInfo info = resolver.resolveWiringInfo(new NamedWirelessSoap()); - assertNotNull("Must *not* be returning null for an @Configurable class instance even when autowiring is NO", info); - assertFalse(info.indicatesAutowiring()); - assertEquals("DerBigStick", info.getBeanName()); + assertThat(info).as("Must *not* be returning null for an @Configurable class instance even when autowiring is NO").isNotNull(); + assertThat(info.indicatesAutowiring()).isFalse(); + assertThat(info.getBeanName()).isEqualTo("DerBigStick"); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java index cf22c8a59a9..f1a4a7da23c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java @@ -77,14 +77,6 @@ import org.springframework.util.SerializationTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -134,12 +126,12 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean", tb); ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); bean = (ResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); } @Test @@ -153,25 +145,25 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean", ntb); TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); String[] depBeans = bf.getDependenciesForBean("annotatedBean"); - assertEquals(2, depBeans.length); - assertEquals("testBean", depBeans[0]); - assertEquals("nestedTestBean", depBeans[1]); + assertThat(depBeans.length).isEqualTo(2); + assertThat(depBeans[0]).isEqualTo("testBean"); + assertThat(depBeans[1]).isEqualTo("nestedTestBean"); } @Test @@ -183,19 +175,19 @@ public class AutowiredAnnotationBeanPostProcessorTests { TestBean tb = bf.getBean("testBean", TestBean.class); TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); - assertArrayEquals(new String[] {"testBean", "nestedTestBean"}, bf.getDependenciesForBean("annotatedBean")); + assertThat(bf.getDependenciesForBean("annotatedBean")).isEqualTo(new String[] {"testBean", "nestedTestBean"}); bf.destroySingleton("testBean"); - assertFalse(bf.containsSingleton("testBean")); - assertFalse(bf.containsSingleton("annotatedBean")); - assertTrue(bean.destroyed); - assertSame(0, bf.getDependenciesForBean("annotatedBean").length); + assertThat(bf.containsSingleton("testBean")).isFalse(); + assertThat(bf.containsSingleton("annotatedBean")).isFalse(); + assertThat(bean.destroyed).isTrue(); + assertThat(bf.getDependenciesForBean("annotatedBean").length).isSameAs(0); } @Test @@ -210,12 +202,12 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean", ntb); TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb2, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb2); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); } @Test @@ -228,14 +220,14 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean", ntb); OverriddenExtendedResourceInjectionBean bean = (OverriddenExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertNull(bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertNull(bean.getBeanFactory()); - assertTrue(bean.baseInjected); - assertTrue(bean.subInjected); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isNull(); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isNull(); + assertThat(bean.baseInjected).isTrue(); + assertThat(bean.subInjected).isTrue(); } @Test @@ -248,14 +240,14 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean", ntb); DefaultMethodResourceInjectionBean bean = (DefaultMethodResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertNull(bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertNull(bean.getBeanFactory()); - assertTrue(bean.baseInjected); - assertTrue(bean.subInjected); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isNull(); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isNull(); + assertThat(bean.baseInjected).isTrue(); + assertThat(bean.subInjected).isTrue(); } @Test @@ -271,12 +263,12 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean", ntb); TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); } @Test @@ -292,17 +284,17 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(itb, bean.getIndexedTestBean()); - assertEquals(2, bean.getNestedTestBeans().length); - assertSame(ntb1, bean.getNestedTestBeans()[0]); - assertSame(ntb2, bean.getNestedTestBeans()[1]); - assertEquals(2, bean.nestedTestBeansField.length); - assertSame(ntb1, bean.nestedTestBeansField[0]); - assertSame(ntb2, bean.nestedTestBeansField[1]); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getIndexedTestBean()).isSameAs(itb); + assertThat(bean.getNestedTestBeans().length).isEqualTo(2); + assertThat(bean.getNestedTestBeans()[0]).isSameAs(ntb1); + assertThat(bean.getNestedTestBeans()[1]).isSameAs(ntb2); + assertThat(bean.nestedTestBeansField.length).isEqualTo(2); + assertThat(bean.nestedTestBeansField[0]).isSameAs(ntb1); + assertThat(bean.nestedTestBeansField[1]).isSameAs(ntb2); } @Test @@ -322,20 +314,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { // Two calls to verify that caching doesn't break re-creation. OptionalCollectionResourceInjectionBean bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean"); bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(itb, bean.getIndexedTestBean()); - assertEquals(2, bean.getNestedTestBeans().size()); - assertSame(ntb1, bean.getNestedTestBeans().get(0)); - assertSame(ntb2, bean.getNestedTestBeans().get(1)); - assertEquals(2, bean.nestedTestBeansSetter.size()); - assertSame(ntb1, bean.nestedTestBeansSetter.get(0)); - assertSame(ntb2, bean.nestedTestBeansSetter.get(1)); - assertEquals(2, bean.nestedTestBeansField.size()); - assertSame(ntb1, bean.nestedTestBeansField.get(0)); - assertSame(ntb2, bean.nestedTestBeansField.get(1)); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getIndexedTestBean()).isSameAs(itb); + assertThat(bean.getNestedTestBeans().size()).isEqualTo(2); + assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb1); + assertThat(bean.getNestedTestBeans().get(1)).isSameAs(ntb2); + assertThat(bean.nestedTestBeansSetter.size()).isEqualTo(2); + assertThat(bean.nestedTestBeansSetter.get(0)).isSameAs(ntb1); + assertThat(bean.nestedTestBeansSetter.get(1)).isSameAs(ntb2); + assertThat(bean.nestedTestBeansField.size()).isEqualTo(2); + assertThat(bean.nestedTestBeansField.get(0)).isSameAs(ntb1); + assertThat(bean.nestedTestBeansField.get(1)).isSameAs(ntb2); } @Test @@ -353,17 +345,17 @@ public class AutowiredAnnotationBeanPostProcessorTests { // Two calls to verify that caching doesn't break re-creation. OptionalCollectionResourceInjectionBean bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean"); bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(itb, bean.getIndexedTestBean()); - assertEquals(1, bean.getNestedTestBeans().size()); - assertSame(ntb1, bean.getNestedTestBeans().get(0)); - assertEquals(1, bean.nestedTestBeansSetter.size()); - assertSame(ntb1, bean.nestedTestBeansSetter.get(0)); - assertEquals(1, bean.nestedTestBeansField.size()); - assertSame(ntb1, bean.nestedTestBeansField.get(0)); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getIndexedTestBean()).isSameAs(itb); + assertThat(bean.getNestedTestBeans().size()).isEqualTo(1); + assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb1); + assertThat(bean.nestedTestBeansSetter.size()).isEqualTo(1); + assertThat(bean.nestedTestBeansSetter.get(0)).isSameAs(ntb1); + assertThat(bean.nestedTestBeansField.size()).isEqualTo(1); + assertThat(bean.nestedTestBeansField.get(0)).isSameAs(ntb1); } @Test @@ -373,11 +365,11 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean", tb); OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertNull(bean.getTestBean4()); - assertNull(bean.getNestedTestBeans()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isNull(); + assertThat(bean.getNestedTestBeans()).isNull(); } @Test @@ -385,11 +377,11 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalResourceInjectionBean.class)); OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean()); - assertNull(bean.getTestBean2()); - assertNull(bean.getTestBean3()); - assertNull(bean.getTestBean4()); - assertNull(bean.getNestedTestBeans()); + assertThat(bean.getTestBean()).isNull(); + assertThat(bean.getTestBean2()).isNull(); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean4()).isNull(); + assertThat(bean.getNestedTestBeans()).isNull(); } @Test @@ -407,17 +399,17 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(itb, bean.getIndexedTestBean()); - assertEquals(2, bean.getNestedTestBeans().length); - assertSame(ntb2, bean.getNestedTestBeans()[0]); - assertSame(ntb1, bean.getNestedTestBeans()[1]); - assertEquals(2, bean.nestedTestBeansField.length); - assertSame(ntb2, bean.nestedTestBeansField[0]); - assertSame(ntb1, bean.nestedTestBeansField[1]); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getIndexedTestBean()).isSameAs(itb); + assertThat(bean.getNestedTestBeans().length).isEqualTo(2); + assertThat(bean.getNestedTestBeans()[0]).isSameAs(ntb2); + assertThat(bean.getNestedTestBeans()[1]).isSameAs(ntb1); + assertThat(bean.nestedTestBeansField.length).isEqualTo(2); + assertThat(bean.nestedTestBeansField[0]).isSameAs(ntb2); + assertThat(bean.nestedTestBeansField[1]).isSameAs(ntb1); } @Test @@ -433,17 +425,17 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); OptionalResourceInjectionBean bean = (OptionalResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(itb, bean.getIndexedTestBean()); - assertEquals(2, bean.getNestedTestBeans().length); - assertSame(ntb2, bean.getNestedTestBeans()[0]); - assertSame(ntb1, bean.getNestedTestBeans()[1]); - assertEquals(2, bean.nestedTestBeansField.length); - assertSame(ntb2, bean.nestedTestBeansField[0]); - assertSame(ntb1, bean.nestedTestBeansField[1]); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getIndexedTestBean()).isSameAs(itb); + assertThat(bean.getNestedTestBeans().length).isEqualTo(2); + assertThat(bean.getNestedTestBeans()[0]).isSameAs(ntb2); + assertThat(bean.getNestedTestBeans()[1]).isSameAs(ntb1); + assertThat(bean.nestedTestBeansField.length).isEqualTo(2); + assertThat(bean.nestedTestBeansField[0]).isSameAs(ntb2); + assertThat(bean.nestedTestBeansField[1]).isSameAs(ntb1); } @Test @@ -465,20 +457,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { // Two calls to verify that caching doesn't break re-creation. OptionalCollectionResourceInjectionBean bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean"); bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(itb, bean.getIndexedTestBean()); - assertEquals(2, bean.getNestedTestBeans().size()); - assertSame(ntb2, bean.getNestedTestBeans().get(0)); - assertSame(ntb1, bean.getNestedTestBeans().get(1)); - assertEquals(2, bean.nestedTestBeansSetter.size()); - assertSame(ntb2, bean.nestedTestBeansSetter.get(0)); - assertSame(ntb1, bean.nestedTestBeansSetter.get(1)); - assertEquals(2, bean.nestedTestBeansField.size()); - assertSame(ntb2, bean.nestedTestBeansField.get(0)); - assertSame(ntb1, bean.nestedTestBeansField.get(1)); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getIndexedTestBean()).isSameAs(itb); + assertThat(bean.getNestedTestBeans().size()).isEqualTo(2); + assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb2); + assertThat(bean.getNestedTestBeans().get(1)).isSameAs(ntb1); + assertThat(bean.nestedTestBeansSetter.size()).isEqualTo(2); + assertThat(bean.nestedTestBeansSetter.get(0)).isSameAs(ntb2); + assertThat(bean.nestedTestBeansSetter.get(1)).isSameAs(ntb1); + assertThat(bean.nestedTestBeansField.size()).isEqualTo(2); + assertThat(bean.nestedTestBeansField.get(0)).isSameAs(ntb2); + assertThat(bean.nestedTestBeansField.get(1)).isSameAs(ntb1); } @Test @@ -498,20 +490,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { // Two calls to verify that caching doesn't break re-creation. OptionalCollectionResourceInjectionBean bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean"); bean = (OptionalCollectionResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(itb, bean.getIndexedTestBean()); - assertEquals(2, bean.getNestedTestBeans().size()); - assertSame(ntb2, bean.getNestedTestBeans().get(0)); - assertSame(ntb1, bean.getNestedTestBeans().get(1)); - assertEquals(2, bean.nestedTestBeansSetter.size()); - assertSame(ntb2, bean.nestedTestBeansSetter.get(0)); - assertSame(ntb1, bean.nestedTestBeansSetter.get(1)); - assertEquals(2, bean.nestedTestBeansField.size()); - assertSame(ntb2, bean.nestedTestBeansField.get(0)); - assertSame(ntb1, bean.nestedTestBeansField.get(1)); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getIndexedTestBean()).isSameAs(itb); + assertThat(bean.getNestedTestBeans().size()).isEqualTo(2); + assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb2); + assertThat(bean.getNestedTestBeans().get(1)).isSameAs(ntb1); + assertThat(bean.nestedTestBeansSetter.size()).isEqualTo(2); + assertThat(bean.nestedTestBeansSetter.get(0)).isSameAs(ntb2); + assertThat(bean.nestedTestBeansSetter.get(1)).isSameAs(ntb1); + assertThat(bean.nestedTestBeansField.size()).isEqualTo(2); + assertThat(bean.nestedTestBeansField.get(0)).isSameAs(ntb2); + assertThat(bean.nestedTestBeansField.get(1)).isSameAs(ntb1); } @Test @@ -525,20 +517,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean", ntb); ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); } @Test @@ -552,20 +544,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", new NestedTestBean()); ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertNull(bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isNull(); + assertThat(bean.getBeanFactory()).isSameAs(bf); bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertNull(bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isNull(); + assertThat(bean.getBeanFactory()).isSameAs(bf); } @Test @@ -582,20 +574,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", new NestedTestBean()); ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean()); - assertNull(bean.getTestBean2()); - assertNull(bean.getTestBean3()); - assertNull(bean.getTestBean4()); - assertNull(bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isNull(); + assertThat(bean.getTestBean2()).isNull(); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean4()).isNull(); + assertThat(bean.getNestedTestBean()).isNull(); + assertThat(bean.getBeanFactory()).isSameAs(bf); bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean()); - assertNull(bean.getTestBean2()); - assertNull(bean.getTestBean3()); - assertNull(bean.getTestBean4()); - assertNull(bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isNull(); + assertThat(bean.getTestBean2()).isNull(); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean4()).isNull(); + assertThat(bean.getNestedTestBean()).isNull(); + assertThat(bean.getBeanFactory()).isSameAs(bf); } @Test @@ -609,11 +601,11 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertEquals(2, bean.getNestedTestBeans().length); - assertSame(ntb1, bean.getNestedTestBeans()[0]); - assertSame(ntb2, bean.getNestedTestBeans()[1]); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBeans().length).isEqualTo(2); + assertThat(bean.getNestedTestBeans()[0]).isSameAs(ntb1); + assertThat(bean.getNestedTestBeans()[1]).isSameAs(ntb2); } @Test @@ -635,14 +627,14 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertEquals(1, bean.getNestedTestBeans().size()); - assertSame(ntb2, bean.getNestedTestBeans().get(0)); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBeans().size()).isEqualTo(1); + assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb2); Map map = bf.getBeansOfType(NestedTestBean.class); - assertNull(map.get("nestedTestBean1")); - assertSame(ntb2, map.get("nestedTestBean2")); + assertThat(map.get("nestedTestBean1")).isNull(); + assertThat(map.get("nestedTestBean2")).isSameAs(ntb2); } @Test @@ -657,11 +649,11 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertEquals(2, bean.getNestedTestBeans().size()); - assertSame(ntb1, bean.getNestedTestBeans().get(0)); - assertSame(ntb2, bean.getNestedTestBeans().get(1)); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBeans().size()).isEqualTo(2); + assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb1); + assertThat(bean.getNestedTestBeans().get(1)).isSameAs(ntb2); } @Test @@ -675,11 +667,11 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertEquals(2, bean.getNestedTestBeans().length); - assertSame(ntb2, bean.getNestedTestBeans()[0]); - assertSame(ntb1, bean.getNestedTestBeans()[1]); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBeans().length).isEqualTo(2); + assertThat(bean.getNestedTestBeans()[0]).isSameAs(ntb2); + assertThat(bean.getNestedTestBeans()[1]).isSameAs(ntb1); } @Test @@ -693,11 +685,11 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertEquals(2, bean.getNestedTestBeans().size()); - assertSame(ntb2, bean.getNestedTestBeans().get(0)); - assertSame(ntb1, bean.getNestedTestBeans().get(1)); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBeans().size()).isEqualTo(2); + assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb2); + assertThat(bean.getNestedTestBeans().get(1)).isSameAs(ntb1); } @Test @@ -711,10 +703,10 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); SingleConstructorVarargBean bean = (SingleConstructorVarargBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertEquals(2, bean.getNestedTestBeans().size()); - assertSame(ntb2, bean.getNestedTestBeans().get(0)); - assertSame(ntb1, bean.getNestedTestBeans().get(1)); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getNestedTestBeans().size()).isEqualTo(2); + assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb2); + assertThat(bean.getNestedTestBeans().get(1)).isSameAs(ntb1); } @Test @@ -724,9 +716,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean", tb); SingleConstructorVarargBean bean = (SingleConstructorVarargBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertNotNull(bean.getNestedTestBeans()); - assertTrue(bean.getNestedTestBeans().isEmpty()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getNestedTestBeans()).isNotNull(); + assertThat(bean.getNestedTestBeans().isEmpty()).isTrue(); } @Test @@ -740,10 +732,10 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); SingleConstructorRequiredCollectionBean bean = (SingleConstructorRequiredCollectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertEquals(2, bean.getNestedTestBeans().size()); - assertSame(ntb2, bean.getNestedTestBeans().get(0)); - assertSame(ntb1, bean.getNestedTestBeans().get(1)); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getNestedTestBeans().size()).isEqualTo(2); + assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb2); + assertThat(bean.getNestedTestBeans().get(1)).isSameAs(ntb1); } @Test @@ -753,9 +745,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean", tb); SingleConstructorRequiredCollectionBean bean = (SingleConstructorRequiredCollectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertNotNull(bean.getNestedTestBeans()); - assertTrue(bean.getNestedTestBeans().isEmpty()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getNestedTestBeans()).isNotNull(); + assertThat(bean.getNestedTestBeans().isEmpty()).isTrue(); } @Test @@ -769,10 +761,10 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); SingleConstructorOptionalCollectionBean bean = (SingleConstructorOptionalCollectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertEquals(2, bean.getNestedTestBeans().size()); - assertSame(ntb2, bean.getNestedTestBeans().get(0)); - assertSame(ntb1, bean.getNestedTestBeans().get(1)); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getNestedTestBeans().size()).isEqualTo(2); + assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb2); + assertThat(bean.getNestedTestBeans().get(1)).isSameAs(ntb1); } @Test @@ -782,8 +774,8 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean", tb); SingleConstructorOptionalCollectionBean bean = (SingleConstructorOptionalCollectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertNull(bean.getNestedTestBeans()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getNestedTestBeans()).isNull(); } @Test @@ -810,8 +802,8 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean", tb); ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean3()); - assertNull(bean.getTestBean4()); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isNull(); } @Test @@ -819,8 +811,8 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ConstructorsResourceInjectionBean.class)); ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean3()); - assertNull(bean.getTestBean4()); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean4()).isNull(); } @Test @@ -835,14 +827,14 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean2", tb2); MapConstructorInjectionBean bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertEquals(1, bean.getTestBeanMap().size()); - assertSame(tb1, bean.getTestBeanMap().get("testBean1")); - assertNull(bean.getTestBeanMap().get("testBean2")); + assertThat(bean.getTestBeanMap().size()).isEqualTo(1); + assertThat(bean.getTestBeanMap().get("testBean1")).isSameAs(tb1); + assertThat(bean.getTestBeanMap().get("testBean2")).isNull(); bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertEquals(1, bean.getTestBeanMap().size()); - assertSame(tb1, bean.getTestBeanMap().get("testBean1")); - assertNull(bean.getTestBeanMap().get("testBean2")); + assertThat(bean.getTestBeanMap().size()).isEqualTo(1); + assertThat(bean.getTestBeanMap().get("testBean1")).isSameAs(tb1); + assertThat(bean.getTestBeanMap().get("testBean2")).isNull(); } @Test @@ -856,18 +848,18 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean2", tb2); MapFieldInjectionBean bean = (MapFieldInjectionBean) bf.getBean("annotatedBean"); - assertEquals(2, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean2")); - assertTrue(bean.getTestBeanMap().values().contains(tb1)); - assertTrue(bean.getTestBeanMap().values().contains(tb2)); + assertThat(bean.getTestBeanMap().size()).isEqualTo(2); + assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue(); + assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb1)).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb2)).isTrue(); bean = (MapFieldInjectionBean) bf.getBean("annotatedBean"); - assertEquals(2, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean2")); - assertTrue(bean.getTestBeanMap().values().contains(tb1)); - assertTrue(bean.getTestBeanMap().values().contains(tb2)); + assertThat(bean.getTestBeanMap().size()).isEqualTo(2); + assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue(); + assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb1)).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb2)).isTrue(); } @Test @@ -879,16 +871,16 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean", tb); MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean"); - assertEquals(1, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean")); - assertTrue(bean.getTestBeanMap().values().contains(tb)); - assertSame(tb, bean.getTestBean()); + assertThat(bean.getTestBeanMap().size()).isEqualTo(1); + assertThat(bean.getTestBeanMap().keySet().contains("testBean")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); bean = (MapMethodInjectionBean) bf.getBean("annotatedBean"); - assertEquals(1, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean")); - assertTrue(bean.getTestBeanMap().values().contains(tb)); - assertSame(tb, bean.getTestBean()); + assertThat(bean.getTestBeanMap().size()).isEqualTo(1); + assertThat(bean.getTestBeanMap().keySet().contains("testBean")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); } @Test @@ -911,10 +903,10 @@ public class AutowiredAnnotationBeanPostProcessorTests { MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean"); TestBean tb = (TestBean) bf.getBean("testBean1"); - assertEquals(1, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); - assertTrue(bean.getTestBeanMap().values().contains(tb)); - assertSame(tb, bean.getTestBean()); + assertThat(bean.getTestBeanMap().size()).isEqualTo(1); + assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); } @Test @@ -922,8 +914,8 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class)); MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBeanMap()); - assertNull(bean.getTestBean()); + assertThat(bean.getTestBeanMap()).isNull(); + assertThat(bean.getTestBean()).isNull(); } @Test @@ -938,9 +930,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("otherMap", new Properties()); MapConstructorInjectionBean bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(tbm, bean.getTestBeanMap()); + assertThat(bean.getTestBeanMap()).isSameAs(tbm); bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(tbm, bean.getTestBeanMap()); + assertThat(bean.getTestBeanMap()).isSameAs(tbm); } @Test @@ -954,9 +946,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("otherMap", new HashMap<>()); MapConstructorInjectionBean bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("myTestBeanMap"), bean.getTestBeanMap()); + assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap")); bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("myTestBeanMap"), bean.getTestBeanMap()); + assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap")); } @Test @@ -971,9 +963,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean2", new TestBean()); CustomMapConstructorInjectionBean bean = (CustomMapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("myTestBeanMap"), bean.getTestBeanMap()); + assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap")); bean = (CustomMapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("myTestBeanMap"), bean.getTestBeanMap()); + assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap")); } @Test @@ -984,9 +976,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("myTestBeanMap", new RootBeanDefinition(HashMap.class)); QualifiedMapConstructorInjectionBean bean = (QualifiedMapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("myTestBeanMap"), bean.getTestBeanMap()); + assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap")); bean = (QualifiedMapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("myTestBeanMap"), bean.getTestBeanMap()); + assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap")); } @Test @@ -1001,9 +993,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("otherSet", new HashSet<>()); SetConstructorInjectionBean bean = (SetConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(tbs, bean.getTestBeanSet()); + assertThat(bean.getTestBeanSet()).isSameAs(tbs); bean = (SetConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(tbs, bean.getTestBeanSet()); + assertThat(bean.getTestBeanSet()).isSameAs(tbs); } @Test @@ -1017,9 +1009,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("otherSet", new HashSet<>()); SetConstructorInjectionBean bean = (SetConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("myTestBeanSet"), bean.getTestBeanSet()); + assertThat(bean.getTestBeanSet()).isSameAs(bf.getBean("myTestBeanSet")); bean = (SetConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("myTestBeanSet"), bean.getTestBeanSet()); + assertThat(bean.getTestBeanSet()).isSameAs(bf.getBean("myTestBeanSet")); } @Test @@ -1032,9 +1024,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("myTestBeanSet", tbs); CustomSetConstructorInjectionBean bean = (CustomSetConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("myTestBeanSet"), bean.getTestBeanSet()); + assertThat(bean.getTestBeanSet()).isSameAs(bf.getBean("myTestBeanSet")); bean = (CustomSetConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("myTestBeanSet"), bean.getTestBeanSet()); + assertThat(bean.getTestBeanSet()).isSameAs(bf.getBean("myTestBeanSet")); } @Test @@ -1042,8 +1034,8 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SelfInjectionBean.class)); SelfInjectionBean bean = (SelfInjectionBean) bf.getBean("annotatedBean"); - assertSame(bean, bean.reference); - assertNull(bean.referenceCollection); + assertThat(bean.reference).isSameAs(bean); + assertThat(bean.referenceCollection).isNull(); } @Test @@ -1053,9 +1045,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { SelfInjectionBean bean = (SelfInjectionBean) bf.getBean("annotatedBean"); SelfInjectionBean bean2 = (SelfInjectionBean) bf.getBean("annotatedBean2"); - assertSame(bean2, bean.reference); - assertEquals(1, bean.referenceCollection.size()); - assertSame(bean2, bean.referenceCollection.get(0)); + assertThat(bean.reference).isSameAs(bean2); + assertThat(bean.referenceCollection.size()).isEqualTo(1); + assertThat(bean.referenceCollection.get(0)).isSameAs(bean2); } @Test @@ -1063,8 +1055,8 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SelfInjectionCollectionBean.class)); SelfInjectionCollectionBean bean = (SelfInjectionCollectionBean) bf.getBean("annotatedBean"); - assertSame(bean, bean.reference); - assertNull(bean.referenceCollection); + assertThat(bean.reference).isSameAs(bean); + assertThat(bean.referenceCollection).isNull(); } @Test @@ -1074,9 +1066,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { SelfInjectionCollectionBean bean = (SelfInjectionCollectionBean) bf.getBean("annotatedBean"); SelfInjectionCollectionBean bean2 = (SelfInjectionCollectionBean) bf.getBean("annotatedBean2"); - assertSame(bean2, bean.reference); - assertSame(1, bean2.referenceCollection.size()); - assertSame(bean2, bean.referenceCollection.get(0)); + assertThat(bean.reference).isSameAs(bean2); + assertThat(bean2.referenceCollection.size()).isSameAs(1); + assertThat(bean.referenceCollection.get(0)).isSameAs(bean2); } @Test @@ -1085,7 +1077,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); ObjectFactoryFieldInjectionBean bean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -1094,7 +1086,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); ObjectFactoryConstructorInjectionBean bean = (ObjectFactoryConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -1105,10 +1097,10 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); ObjectFactoryFieldInjectionBean bean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); ObjectFactoryFieldInjectionBean anotherBean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean"); - assertNotSame(anotherBean, bean); - assertSame(bf.getBean("testBean"), anotherBean.getTestBean()); + assertThat(bean).isNotSameAs(anotherBean); + assertThat(anotherBean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -1120,7 +1112,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("dependencyBean2", new RootBeanDefinition(TestBean.class)); ObjectFactoryQualifierInjectionBean bean = (ObjectFactoryQualifierInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("dependencyBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("dependencyBean")); } @Test @@ -1132,7 +1124,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("dependencyBean2", new RootBeanDefinition(TestBean.class)); ObjectFactoryQualifierInjectionBean bean = (ObjectFactoryQualifierInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("dependencyBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("dependencyBean")); } @Test @@ -1142,9 +1134,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.setSerializationId("test"); ObjectFactoryFieldInjectionBean bean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); bean = (ObjectFactoryFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -1155,27 +1147,27 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", tbd); ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean"); - assertEquals(bf.getBean("testBean"), bean.getTestBean()); - assertEquals(bf.getBean("testBean", "myName"), bean.getTestBean("myName")); - assertEquals(bf.getBean("testBean"), bean.getOptionalTestBean()); - assertEquals(bf.getBean("testBean"), bean.getOptionalTestBeanWithDefault()); - assertEquals(bf.getBean("testBean"), bean.consumeOptionalTestBean()); - assertEquals(bf.getBean("testBean"), bean.getUniqueTestBean()); - assertEquals(bf.getBean("testBean"), bean.getUniqueTestBeanWithDefault()); - assertEquals(bf.getBean("testBean"), bean.consumeUniqueTestBean()); + assertThat(bean.getTestBean()).isEqualTo(bf.getBean("testBean")); + assertThat(bean.getTestBean("myName")).isEqualTo(bf.getBean("testBean", "myName")); + assertThat(bean.getOptionalTestBean()).isEqualTo(bf.getBean("testBean")); + assertThat(bean.getOptionalTestBeanWithDefault()).isEqualTo(bf.getBean("testBean")); + assertThat(bean.consumeOptionalTestBean()).isEqualTo(bf.getBean("testBean")); + assertThat(bean.getUniqueTestBean()).isEqualTo(bf.getBean("testBean")); + assertThat(bean.getUniqueTestBeanWithDefault()).isEqualTo(bf.getBean("testBean")); + assertThat(bean.consumeUniqueTestBean()).isEqualTo(bf.getBean("testBean")); List testBeans = bean.iterateTestBeans(); - assertEquals(1, testBeans.size()); - assertTrue(testBeans.contains(bf.getBean("testBean"))); + assertThat(testBeans.size()).isEqualTo(1); + assertThat(testBeans.contains(bf.getBean("testBean"))).isTrue(); testBeans = bean.forEachTestBeans(); - assertEquals(1, testBeans.size()); - assertTrue(testBeans.contains(bf.getBean("testBean"))); + assertThat(testBeans.size()).isEqualTo(1); + assertThat(testBeans.contains(bf.getBean("testBean"))).isTrue(); testBeans = bean.streamTestBeans(); - assertEquals(1, testBeans.size()); - assertTrue(testBeans.contains(bf.getBean("testBean"))); + assertThat(testBeans.size()).isEqualTo(1); + assertThat(testBeans.contains(bf.getBean("testBean"))).isTrue(); testBeans = bean.sortedTestBeans(); - assertEquals(1, testBeans.size()); - assertTrue(testBeans.contains(bf.getBean("testBean"))); + assertThat(testBeans.size()).isEqualTo(1); + assertThat(testBeans.contains(bf.getBean("testBean"))).isTrue(); } @Test @@ -1184,26 +1176,26 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); - assertSame(bf.getBean("testBean"), bean.getOptionalTestBean()); - assertSame(bf.getBean("testBean"), bean.getOptionalTestBeanWithDefault()); - assertEquals(bf.getBean("testBean"), bean.consumeOptionalTestBean()); - assertSame(bf.getBean("testBean"), bean.getUniqueTestBean()); - assertSame(bf.getBean("testBean"), bean.getUniqueTestBeanWithDefault()); - assertEquals(bf.getBean("testBean"), bean.consumeUniqueTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); + assertThat(bean.getOptionalTestBean()).isSameAs(bf.getBean("testBean")); + assertThat(bean.getOptionalTestBeanWithDefault()).isSameAs(bf.getBean("testBean")); + assertThat(bean.consumeOptionalTestBean()).isEqualTo(bf.getBean("testBean")); + assertThat(bean.getUniqueTestBean()).isSameAs(bf.getBean("testBean")); + assertThat(bean.getUniqueTestBeanWithDefault()).isSameAs(bf.getBean("testBean")); + assertThat(bean.consumeUniqueTestBean()).isEqualTo(bf.getBean("testBean")); List testBeans = bean.iterateTestBeans(); - assertEquals(1, testBeans.size()); - assertTrue(testBeans.contains(bf.getBean("testBean"))); + assertThat(testBeans.size()).isEqualTo(1); + assertThat(testBeans.contains(bf.getBean("testBean"))).isTrue(); testBeans = bean.forEachTestBeans(); - assertEquals(1, testBeans.size()); - assertTrue(testBeans.contains(bf.getBean("testBean"))); + assertThat(testBeans.size()).isEqualTo(1); + assertThat(testBeans.contains(bf.getBean("testBean"))).isTrue(); testBeans = bean.streamTestBeans(); - assertEquals(1, testBeans.size()); - assertTrue(testBeans.contains(bf.getBean("testBean"))); + assertThat(testBeans.size()).isEqualTo(1); + assertThat(testBeans.contains(bf.getBean("testBean"))).isTrue(); testBeans = bean.sortedTestBeans(); - assertEquals(1, testBeans.size()); - assertTrue(testBeans.contains(bf.getBean("testBean"))); + assertThat(testBeans.size()).isEqualTo(1); + assertThat(testBeans.contains(bf.getBean("testBean"))).isTrue(); } @Test @@ -1213,21 +1205,21 @@ public class AutowiredAnnotationBeanPostProcessorTests { ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean"); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( bean::getTestBean); - assertNull(bean.getOptionalTestBean()); - assertNull(bean.consumeOptionalTestBean()); - assertEquals(new TestBean("default"), bean.getOptionalTestBeanWithDefault()); - assertEquals(new TestBean("default"), bean.getUniqueTestBeanWithDefault()); - assertNull(bean.getUniqueTestBean()); - assertNull(bean.consumeUniqueTestBean()); + assertThat(bean.getOptionalTestBean()).isNull(); + assertThat(bean.consumeOptionalTestBean()).isNull(); + assertThat(bean.getOptionalTestBeanWithDefault()).isEqualTo(new TestBean("default")); + assertThat(bean.getUniqueTestBeanWithDefault()).isEqualTo(new TestBean("default")); + assertThat(bean.getUniqueTestBean()).isNull(); + assertThat(bean.consumeUniqueTestBean()).isNull(); List testBeans = bean.iterateTestBeans(); - assertTrue(testBeans.isEmpty()); + assertThat(testBeans.isEmpty()).isTrue(); testBeans = bean.forEachTestBeans(); - assertTrue(testBeans.isEmpty()); + assertThat(testBeans.isEmpty()).isTrue(); testBeans = bean.streamTestBeans(); - assertTrue(testBeans.isEmpty()); + assertThat(testBeans.isEmpty()).isTrue(); testBeans = bean.sortedTestBeans(); - assertTrue(testBeans.isEmpty()); + assertThat(testBeans.isEmpty()).isTrue(); } @Test @@ -1240,25 +1232,25 @@ public class AutowiredAnnotationBeanPostProcessorTests { assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::getTestBean); assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::getOptionalTestBean); assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(bean::consumeOptionalTestBean); - assertNull(bean.getUniqueTestBean()); - assertNull(bean.consumeUniqueTestBean()); + assertThat(bean.getUniqueTestBean()).isNull(); + assertThat(bean.consumeUniqueTestBean()).isNull(); List testBeans = bean.iterateTestBeans(); - assertEquals(2, testBeans.size()); - assertSame(bf.getBean("testBean1"), testBeans.get(0)); - assertSame(bf.getBean("testBean2"), testBeans.get(1)); + assertThat(testBeans.size()).isEqualTo(2); + assertThat(testBeans.get(0)).isSameAs(bf.getBean("testBean1")); + assertThat(testBeans.get(1)).isSameAs(bf.getBean("testBean2")); testBeans = bean.forEachTestBeans(); - assertEquals(2, testBeans.size()); - assertSame(bf.getBean("testBean1"), testBeans.get(0)); - assertSame(bf.getBean("testBean2"), testBeans.get(1)); + assertThat(testBeans.size()).isEqualTo(2); + assertThat(testBeans.get(0)).isSameAs(bf.getBean("testBean1")); + assertThat(testBeans.get(1)).isSameAs(bf.getBean("testBean2")); testBeans = bean.streamTestBeans(); - assertEquals(2, testBeans.size()); - assertSame(bf.getBean("testBean1"), testBeans.get(0)); - assertSame(bf.getBean("testBean2"), testBeans.get(1)); + assertThat(testBeans.size()).isEqualTo(2); + assertThat(testBeans.get(0)).isSameAs(bf.getBean("testBean1")); + assertThat(testBeans.get(1)).isSameAs(bf.getBean("testBean2")); testBeans = bean.sortedTestBeans(); - assertEquals(2, testBeans.size()); - assertSame(bf.getBean("testBean1"), testBeans.get(0)); - assertSame(bf.getBean("testBean2"), testBeans.get(1)); + assertThat(testBeans.size()).isEqualTo(2); + assertThat(testBeans.get(0)).isSameAs(bf.getBean("testBean1")); + assertThat(testBeans.get(1)).isSameAs(bf.getBean("testBean2")); } @Test @@ -1274,29 +1266,29 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean2", tb2); ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean1"), bean.getTestBean()); - assertSame(bf.getBean("testBean1"), bean.getOptionalTestBean()); - assertSame(bf.getBean("testBean1"), bean.consumeOptionalTestBean()); - assertSame(bf.getBean("testBean1"), bean.getUniqueTestBean()); - assertSame(bf.getBean("testBean1"), bean.consumeUniqueTestBean()); - assertFalse(bf.containsSingleton("testBean2")); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean1")); + assertThat(bean.getOptionalTestBean()).isSameAs(bf.getBean("testBean1")); + assertThat(bean.consumeOptionalTestBean()).isSameAs(bf.getBean("testBean1")); + assertThat(bean.getUniqueTestBean()).isSameAs(bf.getBean("testBean1")); + assertThat(bean.consumeUniqueTestBean()).isSameAs(bf.getBean("testBean1")); + assertThat(bf.containsSingleton("testBean2")).isFalse(); List testBeans = bean.iterateTestBeans(); - assertEquals(2, testBeans.size()); - assertSame(bf.getBean("testBean1"), testBeans.get(0)); - assertSame(bf.getBean("testBean2"), testBeans.get(1)); + assertThat(testBeans.size()).isEqualTo(2); + assertThat(testBeans.get(0)).isSameAs(bf.getBean("testBean1")); + assertThat(testBeans.get(1)).isSameAs(bf.getBean("testBean2")); testBeans = bean.forEachTestBeans(); - assertEquals(2, testBeans.size()); - assertSame(bf.getBean("testBean1"), testBeans.get(0)); - assertSame(bf.getBean("testBean2"), testBeans.get(1)); + assertThat(testBeans.size()).isEqualTo(2); + assertThat(testBeans.get(0)).isSameAs(bf.getBean("testBean1")); + assertThat(testBeans.get(1)).isSameAs(bf.getBean("testBean2")); testBeans = bean.streamTestBeans(); - assertEquals(2, testBeans.size()); - assertSame(bf.getBean("testBean1"), testBeans.get(0)); - assertSame(bf.getBean("testBean2"), testBeans.get(1)); + assertThat(testBeans.size()).isEqualTo(2); + assertThat(testBeans.get(0)).isSameAs(bf.getBean("testBean1")); + assertThat(testBeans.get(1)).isSameAs(bf.getBean("testBean2")); testBeans = bean.sortedTestBeans(); - assertEquals(2, testBeans.size()); - assertSame(bf.getBean("testBean2"), testBeans.get(0)); - assertSame(bf.getBean("testBean1"), testBeans.get(1)); + assertThat(testBeans.size()).isEqualTo(2); + assertThat(testBeans.get(0)).isSameAs(bf.getBean("testBean2")); + assertThat(testBeans.get(1)).isSameAs(bf.getBean("testBean1")); } @Test @@ -1313,9 +1305,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { ObjectProviderInjectionBean bean = (ObjectProviderInjectionBean) bf.getBean("annotatedBean"); List testBeans = bean.sortedTestBeans(); - assertEquals(2, testBeans.size()); - assertSame(bf.getBean("testBean2"), testBeans.get(0)); - assertSame(bf.getBean("testBean1"), testBeans.get(1)); + assertThat(testBeans.size()).isEqualTo(2); + assertThat(testBeans.get(0)).isSameAs(bf.getBean("testBean2")); + assertThat(testBeans.get(1)).isSameAs(bf.getBean("testBean1")); } @Test @@ -1330,7 +1322,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { CustomAnnotationRequiredFieldResourceInjectionBean bean = (CustomAnnotationRequiredFieldResourceInjectionBean) bf.getBean("customBean"); - assertSame(tb, bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(tb); } @Test @@ -1373,7 +1365,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { CustomAnnotationRequiredMethodResourceInjectionBean bean = (CustomAnnotationRequiredMethodResourceInjectionBean) bf.getBean("customBean"); - assertSame(tb, bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(tb); } @Test @@ -1416,9 +1408,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { CustomAnnotationOptionalFieldResourceInjectionBean bean = (CustomAnnotationOptionalFieldResourceInjectionBean) bf.getBean("customBean"); - assertSame(tb, bean.getTestBean3()); - assertNull(bean.getTestBean()); - assertNull(bean.getTestBean2()); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean()).isNull(); + assertThat(bean.getTestBean2()).isNull(); } @Test @@ -1431,9 +1423,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { CustomAnnotationOptionalFieldResourceInjectionBean bean = (CustomAnnotationOptionalFieldResourceInjectionBean) bf.getBean("customBean"); - assertNull(bean.getTestBean3()); - assertNull(bean.getTestBean()); - assertNull(bean.getTestBean2()); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean()).isNull(); + assertThat(bean.getTestBean2()).isNull(); } @Test @@ -1464,9 +1456,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { CustomAnnotationOptionalMethodResourceInjectionBean bean = (CustomAnnotationOptionalMethodResourceInjectionBean) bf.getBean("customBean"); - assertSame(tb, bean.getTestBean3()); - assertNull(bean.getTestBean()); - assertNull(bean.getTestBean2()); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean()).isNull(); + assertThat(bean.getTestBean2()).isNull(); } @Test @@ -1479,9 +1471,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { CustomAnnotationOptionalMethodResourceInjectionBean bean = (CustomAnnotationOptionalMethodResourceInjectionBean) bf.getBean("customBean"); - assertNull(bean.getTestBean3()); - assertNull(bean.getTestBean()); - assertNull(bean.getTestBean2()); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean()).isNull(); + assertThat(bean.getTestBean2()).isNull(); } @Test @@ -1515,10 +1507,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { final StringFactoryBean factoryBean = (StringFactoryBean) bf.getBean("&stringFactoryBean"); final FactoryBeanDependentBean bean = (FactoryBeanDependentBean) bf.getBean("factoryBeanDependentBean"); - assertNotNull("The singleton StringFactoryBean should have been registered.", factoryBean); - assertNotNull("The factoryBeanDependentBean should have been registered.", bean); - assertEquals("The FactoryBeanDependentBean should have been autowired 'by type' with the StringFactoryBean.", - factoryBean, bean.getFactoryBean()); + assertThat(factoryBean).as("The singleton StringFactoryBean should have been registered.").isNotNull(); + assertThat(bean).as("The factoryBeanDependentBean should have been registered.").isNotNull(); + assertThat(bean.getFactoryBean()).as("The FactoryBeanDependentBean should have been autowired 'by type' with the StringFactoryBean.").isEqualTo(factoryBean); } @Test @@ -1536,34 +1527,34 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("integerRepo", ir); RepositoryFieldInjectionBean bean = (RepositoryFieldInjectionBean) bf.getBean("annotatedBean"); - assertSame(sv, bean.string); - assertSame(iv, bean.integer); - assertSame(1, bean.stringArray.length); - assertSame(1, bean.integerArray.length); - assertSame(sv, bean.stringArray[0]); - assertSame(iv, bean.integerArray[0]); - assertSame(1, bean.stringList.size()); - assertSame(1, bean.integerList.size()); - assertSame(sv, bean.stringList.get(0)); - assertSame(iv, bean.integerList.get(0)); - assertSame(1, bean.stringMap.size()); - assertSame(1, bean.integerMap.size()); - assertSame(sv, bean.stringMap.get("stringValue")); - assertSame(iv, bean.integerMap.get("integerValue")); - assertSame(sr, bean.stringRepository); - assertSame(ir, bean.integerRepository); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(1, bean.integerRepositoryArray.length); - assertSame(sr, bean.stringRepositoryArray[0]); - assertSame(ir, bean.integerRepositoryArray[0]); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(1, bean.integerRepositoryList.size()); - assertSame(sr, bean.stringRepositoryList.get(0)); - assertSame(ir, bean.integerRepositoryList.get(0)); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(1, bean.integerRepositoryMap.size()); - assertSame(sr, bean.stringRepositoryMap.get("stringRepo")); - assertSame(ir, bean.integerRepositoryMap.get("integerRepo")); + assertThat(bean.string).isSameAs(sv); + assertThat(bean.integer).isSameAs(iv); + assertThat(bean.stringArray.length).isSameAs(1); + assertThat(bean.integerArray.length).isSameAs(1); + assertThat(bean.stringArray[0]).isSameAs(sv); + assertThat(bean.integerArray[0]).isSameAs(iv); + assertThat(bean.stringList.size()).isSameAs(1); + assertThat(bean.integerList.size()).isSameAs(1); + assertThat(bean.stringList.get(0)).isSameAs(sv); + assertThat(bean.integerList.get(0)).isSameAs(iv); + assertThat(bean.stringMap.size()).isSameAs(1); + assertThat(bean.integerMap.size()).isSameAs(1); + assertThat(bean.stringMap.get("stringValue")).isSameAs(sv); + assertThat(bean.integerMap.get("integerValue")).isSameAs(iv); + assertThat(bean.stringRepository).isSameAs(sr); + assertThat(bean.integerRepository).isSameAs(ir); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.integerRepositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray[0]).isSameAs(sr); + assertThat(bean.integerRepositoryArray[0]).isSameAs(ir); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.integerRepositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(sr); + assertThat(bean.integerRepositoryList.get(0)).isSameAs(ir); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.integerRepositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.get("stringRepo")).isSameAs(sr); + assertThat(bean.integerRepositoryMap.get("integerRepo")).isSameAs(ir); } @Test @@ -1581,34 +1572,34 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("integerRepo", ir); RepositoryFieldInjectionBeanWithSubstitutedVariables bean = (RepositoryFieldInjectionBeanWithSubstitutedVariables) bf.getBean("annotatedBean"); - assertSame(sv, bean.string); - assertSame(iv, bean.integer); - assertSame(1, bean.stringArray.length); - assertSame(1, bean.integerArray.length); - assertSame(sv, bean.stringArray[0]); - assertSame(iv, bean.integerArray[0]); - assertSame(1, bean.stringList.size()); - assertSame(1, bean.integerList.size()); - assertSame(sv, bean.stringList.get(0)); - assertSame(iv, bean.integerList.get(0)); - assertSame(1, bean.stringMap.size()); - assertSame(1, bean.integerMap.size()); - assertSame(sv, bean.stringMap.get("stringValue")); - assertSame(iv, bean.integerMap.get("integerValue")); - assertSame(sr, bean.stringRepository); - assertSame(ir, bean.integerRepository); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(1, bean.integerRepositoryArray.length); - assertSame(sr, bean.stringRepositoryArray[0]); - assertSame(ir, bean.integerRepositoryArray[0]); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(1, bean.integerRepositoryList.size()); - assertSame(sr, bean.stringRepositoryList.get(0)); - assertSame(ir, bean.integerRepositoryList.get(0)); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(1, bean.integerRepositoryMap.size()); - assertSame(sr, bean.stringRepositoryMap.get("stringRepo")); - assertSame(ir, bean.integerRepositoryMap.get("integerRepo")); + assertThat(bean.string).isSameAs(sv); + assertThat(bean.integer).isSameAs(iv); + assertThat(bean.stringArray.length).isSameAs(1); + assertThat(bean.integerArray.length).isSameAs(1); + assertThat(bean.stringArray[0]).isSameAs(sv); + assertThat(bean.integerArray[0]).isSameAs(iv); + assertThat(bean.stringList.size()).isSameAs(1); + assertThat(bean.integerList.size()).isSameAs(1); + assertThat(bean.stringList.get(0)).isSameAs(sv); + assertThat(bean.integerList.get(0)).isSameAs(iv); + assertThat(bean.stringMap.size()).isSameAs(1); + assertThat(bean.integerMap.size()).isSameAs(1); + assertThat(bean.stringMap.get("stringValue")).isSameAs(sv); + assertThat(bean.integerMap.get("integerValue")).isSameAs(iv); + assertThat(bean.stringRepository).isSameAs(sr); + assertThat(bean.integerRepository).isSameAs(ir); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.integerRepositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray[0]).isSameAs(sr); + assertThat(bean.integerRepositoryArray[0]).isSameAs(ir); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.integerRepositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(sr); + assertThat(bean.integerRepositoryList.get(0)).isSameAs(ir); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.integerRepositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.get("stringRepo")).isSameAs(sr); + assertThat(bean.integerRepositoryMap.get("integerRepo")).isSameAs(ir); } @Test @@ -1622,20 +1613,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("integerRepo", ir); RepositoryFieldInjectionBeanWithQualifiers bean = (RepositoryFieldInjectionBeanWithQualifiers) bf.getBean("annotatedBean"); - assertSame(sr, bean.stringRepository); - assertSame(ir, bean.integerRepository); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(1, bean.integerRepositoryArray.length); - assertSame(sr, bean.stringRepositoryArray[0]); - assertSame(ir, bean.integerRepositoryArray[0]); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(1, bean.integerRepositoryList.size()); - assertSame(sr, bean.stringRepositoryList.get(0)); - assertSame(ir, bean.integerRepositoryList.get(0)); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(1, bean.integerRepositoryMap.size()); - assertSame(sr, bean.stringRepositoryMap.get("stringRepo")); - assertSame(ir, bean.integerRepositoryMap.get("integerRepo")); + assertThat(bean.stringRepository).isSameAs(sr); + assertThat(bean.integerRepository).isSameAs(ir); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.integerRepositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray[0]).isSameAs(sr); + assertThat(bean.integerRepositoryArray[0]).isSameAs(ir); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.integerRepositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(sr); + assertThat(bean.integerRepositoryList.get(0)).isSameAs(ir); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.integerRepositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.get("stringRepo")).isSameAs(sr); + assertThat(bean.integerRepositoryMap.get("integerRepo")).isSameAs(ir); } @Test @@ -1661,20 +1652,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { RepositoryFieldInjectionBeanWithQualifiers bean = (RepositoryFieldInjectionBeanWithQualifiers) bf.getBean("annotatedBean"); Repository sr = bf.getBean("stringRepo", Repository.class); Repository ir = bf.getBean("integerRepository", Repository.class); - assertSame(sr, bean.stringRepository); - assertSame(ir, bean.integerRepository); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(1, bean.integerRepositoryArray.length); - assertSame(sr, bean.stringRepositoryArray[0]); - assertSame(ir, bean.integerRepositoryArray[0]); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(1, bean.integerRepositoryList.size()); - assertSame(sr, bean.stringRepositoryList.get(0)); - assertSame(ir, bean.integerRepositoryList.get(0)); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(1, bean.integerRepositoryMap.size()); - assertSame(sr, bean.stringRepositoryMap.get("stringRepo")); - assertSame(ir, bean.integerRepositoryMap.get("integerRepository")); + assertThat(bean.stringRepository).isSameAs(sr); + assertThat(bean.integerRepository).isSameAs(ir); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.integerRepositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray[0]).isSameAs(sr); + assertThat(bean.integerRepositoryArray[0]).isSameAs(ir); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.integerRepositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(sr); + assertThat(bean.integerRepositoryList.get(0)).isSameAs(ir); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.integerRepositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.get("stringRepo")).isSameAs(sr); + assertThat(bean.integerRepositoryMap.get("integerRepository")).isSameAs(ir); } @Test @@ -1687,22 +1678,22 @@ public class AutowiredAnnotationBeanPostProcessorTests { RepositoryFieldInjectionBeanWithSimpleMatch bean = (RepositoryFieldInjectionBeanWithSimpleMatch) bf.getBean("annotatedBean"); Repository repo = bf.getBean("repo", Repository.class); - assertSame(repo, bean.repository); - assertSame(repo, bean.stringRepository); - assertSame(1, bean.repositoryArray.length); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(repo, bean.repositoryArray[0]); - assertSame(repo, bean.stringRepositoryArray[0]); - assertSame(1, bean.repositoryList.size()); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(repo, bean.repositoryList.get(0)); - assertSame(repo, bean.stringRepositoryList.get(0)); - assertSame(1, bean.repositoryMap.size()); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(repo, bean.repositoryMap.get("repo")); - assertSame(repo, bean.stringRepositoryMap.get("repo")); + assertThat(bean.repository).isSameAs(repo); + assertThat(bean.stringRepository).isSameAs(repo); + assertThat(bean.repositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.repositoryArray[0]).isSameAs(repo); + assertThat(bean.stringRepositoryArray[0]).isSameAs(repo); + assertThat(bean.repositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.repositoryList.get(0)).isSameAs(repo); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(repo); + assertThat(bean.repositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.repositoryMap.get("repo")).isSameAs(repo); + assertThat(bean.stringRepositoryMap.get("repo")).isSameAs(repo); - assertArrayEquals(new String[] {"repo"}, bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class))); + assertThat(bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class))).isEqualTo(new String[] {"repo"}); } @Test @@ -1714,7 +1705,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { RepositoryFactoryBeanInjectionBean bean = (RepositoryFactoryBeanInjectionBean) bf.getBean("annotatedBean"); RepositoryFactoryBean repoFactoryBean = bf.getBean("&repoFactoryBean", RepositoryFactoryBean.class); - assertSame(repoFactoryBean, bean.repositoryFactoryBean); + assertThat(bean.repositoryFactoryBean).isSameAs(repoFactoryBean); } @Test @@ -1726,7 +1717,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { RepositoryFactoryBeanInjectionBean bean = (RepositoryFactoryBeanInjectionBean) bf.getBean("annotatedBean"); RepositoryFactoryBean repoFactoryBean = bf.getBean("&repoFactoryBean", RepositoryFactoryBean.class); - assertSame(repoFactoryBean, bean.repositoryFactoryBean); + assertThat(bean.repositoryFactoryBean).isSameAs(repoFactoryBean); } @Test @@ -1745,20 +1736,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { RepositoryFieldInjectionBeanWithSimpleMatch bean = (RepositoryFieldInjectionBeanWithSimpleMatch) bf.getBean("annotatedBean"); Repository repo = bf.getBean("repo", Repository.class); - assertSame(repo, bean.repository); - assertSame(repo, bean.stringRepository); - assertSame(1, bean.repositoryArray.length); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(repo, bean.repositoryArray[0]); - assertSame(repo, bean.stringRepositoryArray[0]); - assertSame(1, bean.repositoryList.size()); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(repo, bean.repositoryList.get(0)); - assertSame(repo, bean.stringRepositoryList.get(0)); - assertSame(1, bean.repositoryMap.size()); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(repo, bean.repositoryMap.get("repo")); - assertSame(repo, bean.stringRepositoryMap.get("repo")); + assertThat(bean.repository).isSameAs(repo); + assertThat(bean.stringRepository).isSameAs(repo); + assertThat(bean.repositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.repositoryArray[0]).isSameAs(repo); + assertThat(bean.stringRepositoryArray[0]).isSameAs(repo); + assertThat(bean.repositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.repositoryList.get(0)).isSameAs(repo); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(repo); + assertThat(bean.repositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.repositoryMap.get("repo")).isSameAs(repo); + assertThat(bean.stringRepositoryMap.get("repo")).isSameAs(repo); } @Test @@ -1776,20 +1767,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { RepositoryFieldInjectionBeanWithSimpleMatch bean = (RepositoryFieldInjectionBeanWithSimpleMatch) bf.getBean("annotatedBean"); Repository repo = bf.getBean("repo", Repository.class); - assertSame(repo, bean.repository); - assertSame(repo, bean.stringRepository); - assertSame(1, bean.repositoryArray.length); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(repo, bean.repositoryArray[0]); - assertSame(repo, bean.stringRepositoryArray[0]); - assertSame(1, bean.repositoryList.size()); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(repo, bean.repositoryList.get(0)); - assertSame(repo, bean.stringRepositoryList.get(0)); - assertSame(1, bean.repositoryMap.size()); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(repo, bean.repositoryMap.get("repo")); - assertSame(repo, bean.stringRepositoryMap.get("repo")); + assertThat(bean.repository).isSameAs(repo); + assertThat(bean.stringRepository).isSameAs(repo); + assertThat(bean.repositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.repositoryArray[0]).isSameAs(repo); + assertThat(bean.stringRepositoryArray[0]).isSameAs(repo); + assertThat(bean.repositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.repositoryList.get(0)).isSameAs(repo); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(repo); + assertThat(bean.repositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.repositoryMap.get("repo")).isSameAs(repo); + assertThat(bean.stringRepositoryMap.get("repo")).isSameAs(repo); } @Test @@ -1807,34 +1798,34 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("integerRepo", ir); RepositoryMethodInjectionBean bean = (RepositoryMethodInjectionBean) bf.getBean("annotatedBean"); - assertSame(sv, bean.string); - assertSame(iv, bean.integer); - assertSame(1, bean.stringArray.length); - assertSame(1, bean.integerArray.length); - assertSame(sv, bean.stringArray[0]); - assertSame(iv, bean.integerArray[0]); - assertSame(1, bean.stringList.size()); - assertSame(1, bean.integerList.size()); - assertSame(sv, bean.stringList.get(0)); - assertSame(iv, bean.integerList.get(0)); - assertSame(1, bean.stringMap.size()); - assertSame(1, bean.integerMap.size()); - assertSame(sv, bean.stringMap.get("stringValue")); - assertSame(iv, bean.integerMap.get("integerValue")); - assertSame(sr, bean.stringRepository); - assertSame(ir, bean.integerRepository); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(1, bean.integerRepositoryArray.length); - assertSame(sr, bean.stringRepositoryArray[0]); - assertSame(ir, bean.integerRepositoryArray[0]); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(1, bean.integerRepositoryList.size()); - assertSame(sr, bean.stringRepositoryList.get(0)); - assertSame(ir, bean.integerRepositoryList.get(0)); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(1, bean.integerRepositoryMap.size()); - assertSame(sr, bean.stringRepositoryMap.get("stringRepo")); - assertSame(ir, bean.integerRepositoryMap.get("integerRepo")); + assertThat(bean.string).isSameAs(sv); + assertThat(bean.integer).isSameAs(iv); + assertThat(bean.stringArray.length).isSameAs(1); + assertThat(bean.integerArray.length).isSameAs(1); + assertThat(bean.stringArray[0]).isSameAs(sv); + assertThat(bean.integerArray[0]).isSameAs(iv); + assertThat(bean.stringList.size()).isSameAs(1); + assertThat(bean.integerList.size()).isSameAs(1); + assertThat(bean.stringList.get(0)).isSameAs(sv); + assertThat(bean.integerList.get(0)).isSameAs(iv); + assertThat(bean.stringMap.size()).isSameAs(1); + assertThat(bean.integerMap.size()).isSameAs(1); + assertThat(bean.stringMap.get("stringValue")).isSameAs(sv); + assertThat(bean.integerMap.get("integerValue")).isSameAs(iv); + assertThat(bean.stringRepository).isSameAs(sr); + assertThat(bean.integerRepository).isSameAs(ir); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.integerRepositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray[0]).isSameAs(sr); + assertThat(bean.integerRepositoryArray[0]).isSameAs(ir); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.integerRepositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(sr); + assertThat(bean.integerRepositoryList.get(0)).isSameAs(ir); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.integerRepositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.get("stringRepo")).isSameAs(sr); + assertThat(bean.integerRepositoryMap.get("integerRepo")).isSameAs(ir); } @Test @@ -1852,34 +1843,34 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("integerRepo", ir); RepositoryMethodInjectionBeanWithSubstitutedVariables bean = (RepositoryMethodInjectionBeanWithSubstitutedVariables) bf.getBean("annotatedBean"); - assertSame(sv, bean.string); - assertSame(iv, bean.integer); - assertSame(1, bean.stringArray.length); - assertSame(1, bean.integerArray.length); - assertSame(sv, bean.stringArray[0]); - assertSame(iv, bean.integerArray[0]); - assertSame(1, bean.stringList.size()); - assertSame(1, bean.integerList.size()); - assertSame(sv, bean.stringList.get(0)); - assertSame(iv, bean.integerList.get(0)); - assertSame(1, bean.stringMap.size()); - assertSame(1, bean.integerMap.size()); - assertSame(sv, bean.stringMap.get("stringValue")); - assertSame(iv, bean.integerMap.get("integerValue")); - assertSame(sr, bean.stringRepository); - assertSame(ir, bean.integerRepository); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(1, bean.integerRepositoryArray.length); - assertSame(sr, bean.stringRepositoryArray[0]); - assertSame(ir, bean.integerRepositoryArray[0]); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(1, bean.integerRepositoryList.size()); - assertSame(sr, bean.stringRepositoryList.get(0)); - assertSame(ir, bean.integerRepositoryList.get(0)); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(1, bean.integerRepositoryMap.size()); - assertSame(sr, bean.stringRepositoryMap.get("stringRepo")); - assertSame(ir, bean.integerRepositoryMap.get("integerRepo")); + assertThat(bean.string).isSameAs(sv); + assertThat(bean.integer).isSameAs(iv); + assertThat(bean.stringArray.length).isSameAs(1); + assertThat(bean.integerArray.length).isSameAs(1); + assertThat(bean.stringArray[0]).isSameAs(sv); + assertThat(bean.integerArray[0]).isSameAs(iv); + assertThat(bean.stringList.size()).isSameAs(1); + assertThat(bean.integerList.size()).isSameAs(1); + assertThat(bean.stringList.get(0)).isSameAs(sv); + assertThat(bean.integerList.get(0)).isSameAs(iv); + assertThat(bean.stringMap.size()).isSameAs(1); + assertThat(bean.integerMap.size()).isSameAs(1); + assertThat(bean.stringMap.get("stringValue")).isSameAs(sv); + assertThat(bean.integerMap.get("integerValue")).isSameAs(iv); + assertThat(bean.stringRepository).isSameAs(sr); + assertThat(bean.integerRepository).isSameAs(ir); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.integerRepositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray[0]).isSameAs(sr); + assertThat(bean.integerRepositoryArray[0]).isSameAs(ir); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.integerRepositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(sr); + assertThat(bean.integerRepositoryList.get(0)).isSameAs(ir); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.integerRepositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.get("stringRepo")).isSameAs(sr); + assertThat(bean.integerRepositoryMap.get("integerRepo")).isSameAs(ir); } @Test @@ -1893,20 +1884,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("integerRepo", ir); RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(sr, bean.stringRepository); - assertSame(ir, bean.integerRepository); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(1, bean.integerRepositoryArray.length); - assertSame(sr, bean.stringRepositoryArray[0]); - assertSame(ir, bean.integerRepositoryArray[0]); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(1, bean.integerRepositoryList.size()); - assertSame(sr, bean.stringRepositoryList.get(0)); - assertSame(ir, bean.integerRepositoryList.get(0)); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(1, bean.integerRepositoryMap.size()); - assertSame(sr, bean.stringRepositoryMap.get("stringRepo")); - assertSame(ir, bean.integerRepositoryMap.get("integerRepo")); + assertThat(bean.stringRepository).isSameAs(sr); + assertThat(bean.integerRepository).isSameAs(ir); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.integerRepositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray[0]).isSameAs(sr); + assertThat(bean.integerRepositoryArray[0]).isSameAs(ir); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.integerRepositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(sr); + assertThat(bean.integerRepositoryList.get(0)).isSameAs(ir); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.integerRepositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.get("stringRepo")).isSameAs(sr); + assertThat(bean.integerRepositoryMap.get("integerRepo")).isSameAs(ir); } @Test @@ -1919,20 +1910,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("genericRepo", gr); RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(gr, bean.stringRepository); - assertSame(gr, bean.integerRepository); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(1, bean.integerRepositoryArray.length); - assertSame(gr, bean.stringRepositoryArray[0]); - assertSame(gr, bean.integerRepositoryArray[0]); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(1, bean.integerRepositoryList.size()); - assertSame(gr, bean.stringRepositoryList.get(0)); - assertSame(gr, bean.integerRepositoryList.get(0)); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(1, bean.integerRepositoryMap.size()); - assertSame(gr, bean.stringRepositoryMap.get("genericRepo")); - assertSame(gr, bean.integerRepositoryMap.get("genericRepo")); + assertThat(bean.stringRepository).isSameAs(gr); + assertThat(bean.integerRepository).isSameAs(gr); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.integerRepositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray[0]).isSameAs(gr); + assertThat(bean.integerRepositoryArray[0]).isSameAs(gr); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.integerRepositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(gr); + assertThat(bean.integerRepositoryList.get(0)).isSameAs(gr); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.integerRepositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.get("genericRepo")).isSameAs(gr); + assertThat(bean.integerRepositoryMap.get("genericRepo")).isSameAs(gr); } @Test @@ -1944,20 +1935,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("simpleRepo", ngr); RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(ngr, bean.stringRepository); - assertSame(ngr, bean.integerRepository); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(1, bean.integerRepositoryArray.length); - assertSame(ngr, bean.stringRepositoryArray[0]); - assertSame(ngr, bean.integerRepositoryArray[0]); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(1, bean.integerRepositoryList.size()); - assertSame(ngr, bean.stringRepositoryList.get(0)); - assertSame(ngr, bean.integerRepositoryList.get(0)); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(1, bean.integerRepositoryMap.size()); - assertSame(ngr, bean.stringRepositoryMap.get("simpleRepo")); - assertSame(ngr, bean.integerRepositoryMap.get("simpleRepo")); + assertThat(bean.stringRepository).isSameAs(ngr); + assertThat(bean.integerRepository).isSameAs(ngr); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.integerRepositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray[0]).isSameAs(ngr); + assertThat(bean.integerRepositoryArray[0]).isSameAs(ngr); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.integerRepositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(ngr); + assertThat(bean.integerRepositoryList.get(0)).isSameAs(ngr); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.integerRepositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.get("simpleRepo")).isSameAs(ngr); + assertThat(bean.integerRepositoryMap.get("simpleRepo")).isSameAs(ngr); } @Test @@ -1972,20 +1963,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("genericRepo", gr); RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(sr, bean.stringRepository); - assertSame(gr, bean.integerRepository); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(1, bean.integerRepositoryArray.length); - assertSame(sr, bean.stringRepositoryArray[0]); - assertSame(gr, bean.integerRepositoryArray[0]); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(1, bean.integerRepositoryList.size()); - assertSame(sr, bean.stringRepositoryList.get(0)); - assertSame(gr, bean.integerRepositoryList.get(0)); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(1, bean.integerRepositoryMap.size()); - assertSame(sr, bean.stringRepositoryMap.get("stringRepo")); - assertSame(gr, bean.integerRepositoryMap.get("genericRepo")); + assertThat(bean.stringRepository).isSameAs(sr); + assertThat(bean.integerRepository).isSameAs(gr); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.integerRepositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray[0]).isSameAs(sr); + assertThat(bean.integerRepositoryArray[0]).isSameAs(gr); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.integerRepositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(sr); + assertThat(bean.integerRepositoryList.get(0)).isSameAs(gr); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.integerRepositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.get("stringRepo")).isSameAs(sr); + assertThat(bean.integerRepositoryMap.get("genericRepo")).isSameAs(gr); } @Test @@ -1999,20 +1990,20 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerSingleton("simpleRepo", ngr); RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean"); - assertSame(sr, bean.stringRepository); - assertSame(ngr, bean.integerRepository); - assertSame(1, bean.stringRepositoryArray.length); - assertSame(1, bean.integerRepositoryArray.length); - assertSame(sr, bean.stringRepositoryArray[0]); - assertSame(ngr, bean.integerRepositoryArray[0]); - assertSame(1, bean.stringRepositoryList.size()); - assertSame(1, bean.integerRepositoryList.size()); - assertSame(sr, bean.stringRepositoryList.get(0)); - assertSame(ngr, bean.integerRepositoryList.get(0)); - assertSame(1, bean.stringRepositoryMap.size()); - assertSame(1, bean.integerRepositoryMap.size()); - assertSame(sr, bean.stringRepositoryMap.get("stringRepo")); - assertSame(ngr, bean.integerRepositoryMap.get("simpleRepo")); + assertThat(bean.stringRepository).isSameAs(sr); + assertThat(bean.integerRepository).isSameAs(ngr); + assertThat(bean.stringRepositoryArray.length).isSameAs(1); + assertThat(bean.integerRepositoryArray.length).isSameAs(1); + assertThat(bean.stringRepositoryArray[0]).isSameAs(sr); + assertThat(bean.integerRepositoryArray[0]).isSameAs(ngr); + assertThat(bean.stringRepositoryList.size()).isSameAs(1); + assertThat(bean.integerRepositoryList.size()).isSameAs(1); + assertThat(bean.stringRepositoryList.get(0)).isSameAs(sr); + assertThat(bean.integerRepositoryList.get(0)).isSameAs(ngr); + assertThat(bean.stringRepositoryMap.size()).isSameAs(1); + assertThat(bean.integerRepositoryMap.size()).isSameAs(1); + assertThat(bean.stringRepositoryMap.get("stringRepo")).isSameAs(sr); + assertThat(bean.integerRepositoryMap.get("simpleRepo")).isSameAs(ngr); } @Test @@ -2025,8 +2016,8 @@ public class AutowiredAnnotationBeanPostProcessorTests { GenericInterface1Impl bean1 = (GenericInterface1Impl) bf.getBean("bean1"); GenericInterface2Impl bean2 = (GenericInterface2Impl) bf.getBean("bean2"); - assertSame(bean2, bean1.gi2); - assertEquals(ResolvableType.forClass(GenericInterface1Impl.class), bd.getResolvableType()); + assertThat(bean1.gi2).isSameAs(bean2); + assertThat(bd.getResolvableType()).isEqualTo(ResolvableType.forClass(GenericInterface1Impl.class)); } @Test @@ -2039,8 +2030,8 @@ public class AutowiredAnnotationBeanPostProcessorTests { GenericInterface1Impl bean1 = (GenericInterface1Impl) bf.getBean("bean1"); GenericInterface2Impl bean2 = (GenericInterface2Impl) bf.getBean("bean2"); - assertSame(bean2, bean1.gi2); - assertEquals(ResolvableType.forClass(GenericInterface1Impl.class), bd.getResolvableType()); + assertThat(bean1.gi2).isSameAs(bean2); + assertThat(bd.getResolvableType()).isEqualTo(ResolvableType.forClass(GenericInterface1Impl.class)); } @Test @@ -2055,9 +2046,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { GenericInterface1Impl bean1 = (GenericInterface1Impl) bf.getBean("bean1"); GenericInterface2Impl bean2 = (GenericInterface2Impl) bf.getBean("bean2"); - assertSame(bean2, bean1.gi2); - assertArrayEquals(new String[] {"bean1"}, bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(GenericInterface1.class, String.class))); - assertArrayEquals(new String[] {"bean2"}, bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(GenericInterface2.class, String.class))); + assertThat(bean1.gi2).isSameAs(bean2); + assertThat(bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(GenericInterface1.class, String.class))).isEqualTo(new String[] {"bean1"}); + assertThat(bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(GenericInterface2.class, String.class))).isEqualTo(new String[] {"bean2"}); } @Test @@ -2073,7 +2064,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { GenericInterface1Impl bean1 = (GenericInterface1Impl) bf.getBean("bean1"); GenericInterface2Impl bean2 = (GenericInterface2Impl) bf.getBean("bean2"); - assertSame(bean2, bean1.gi2); + assertThat(bean1.gi2).isSameAs(bean2); } @Test @@ -2086,9 +2077,9 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("bean2", bd2); bf.registerBeanDefinition("bean3", new RootBeanDefinition(MultiGenericFieldInjection.class)); - assertEquals("bean1 a bean2 123", bf.getBean("bean3").toString()); - assertEquals(ResolvableType.forClassWithGenerics(GenericInterface2Bean.class, String.class), bd1.getResolvableType()); - assertEquals(ResolvableType.forClassWithGenerics(GenericInterface2Bean.class, Integer.class), bd2.getResolvableType()); + assertThat(bf.getBean("bean3").toString()).isEqualTo("bean1 a bean2 123"); + assertThat(bd1.getResolvableType()).isEqualTo(ResolvableType.forClassWithGenerics(GenericInterface2Bean.class, String.class)); + assertThat(bd2.getResolvableType()).isEqualTo(ResolvableType.forClassWithGenerics(GenericInterface2Bean.class, Integer.class)); } @Test @@ -2099,7 +2090,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("bean4", new RootBeanDefinition(StockMovementInstructionImpl.class)); StockServiceImpl service = bf.getBean(StockServiceImpl.class); - assertSame(bf.getBean(StockMovementDaoImpl.class), service.stockMovementDao); + assertThat(service.stockMovementDao).isSameAs(bf.getBean(StockMovementDaoImpl.class)); } @Test @@ -2107,7 +2098,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("bean1", new RootBeanDefinition(MyCallable.class)); bf.registerBeanDefinition("bean2", new RootBeanDefinition(SecondCallable.class)); bf.registerBeanDefinition("bean3", new RootBeanDefinition(FooBar.class)); - assertNotNull(bf.getBean(FooBar.class)); + assertThat(bf.getBean(FooBar.class)).isNotNull(); } @Test @@ -2115,14 +2106,14 @@ public class AutowiredAnnotationBeanPostProcessorTests { RootBeanDefinition bd = new RootBeanDefinition(ProvidedArgumentBean.class); bd.getConstructorArgumentValues().addGenericArgumentValue(Collections.singletonList("value")); bf.registerBeanDefinition("beanWithArgs", bd); - assertNotNull(bf.getBean(ProvidedArgumentBean.class)); + assertThat(bf.getBean(ProvidedArgumentBean.class)).isNotNull(); } @Test public void testAnnotatedDefaultConstructor() { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(AnnotatedDefaultConstructorBean.class)); - assertNotNull(bf.getBean("annotatedBean")); + assertThat(bf.getBean("annotatedBean")).isNotNull(); } @Test // SPR-15125 @@ -2130,7 +2121,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SelfInjectingFactoryBean.class)); SelfInjectingFactoryBean bean = bf.getBean(SelfInjectingFactoryBean.class); - assertSame(bf.getBean("annotatedBean"), bean.testBean); + assertThat(bean.testBean).isSameAs(bf.getBean("annotatedBean")); } @Test // SPR-15125 @@ -2140,7 +2131,7 @@ public class AutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", bd); SelfInjectingFactoryBean bean = bf.getBean(SelfInjectingFactoryBean.class); - assertSame(bf.getBean("annotatedBean"), bean.testBean); + assertThat(bean.testBean).isSameAs(bf.getBean("annotatedBean")); } private Consumer methodParameterDeclaredOn( diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/CustomAutowireConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/CustomAutowireConfigurerTests.java index 7e01bbef213..69d0db5e1bb 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/CustomAutowireConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/CustomAutowireConfigurerTests.java @@ -24,7 +24,7 @@ import org.springframework.beans.factory.support.AutowireCandidateResolver; import org.springframework.beans.factory.support.DefaultListableBeanFactory; 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; /** @@ -47,7 +47,7 @@ public class CustomAutowireConfigurerTests { bf.setAutowireCandidateResolver(customResolver); cac.postProcessBeanFactory(bf); TestBean testBean = (TestBean) bf.getBean("testBean"); - assertEquals("#1!", testBean.getName()); + assertThat(testBean.getName()).isEqualTo("#1!"); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java index cdfb07cf18b..cd245c92d26 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java @@ -45,14 +45,8 @@ import org.springframework.tests.sample.beans.NestedTestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; 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} @@ -91,7 +85,8 @@ public class InjectAnnotationBeanPostProcessorTests { bf.getBean("testBean"); } 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); ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); bean = (ResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); } @Test @@ -123,20 +118,20 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean", ntb); TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); } @Test @@ -151,12 +146,12 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean", ntb); TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb2, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb2); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); } @Test @@ -172,12 +167,12 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean", ntb); TypedExtendedResourceInjectionBean bean = (TypedExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); } @Test @@ -191,20 +186,20 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean", ntb); ConstructorResourceInjectionBean bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); bean = (ConstructorResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean()); - assertSame(tb, bean.getTestBean2()); - assertSame(tb, bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertSame(ntb, bean.getNestedTestBean()); - assertSame(bf, bean.getBeanFactory()); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBean()).isSameAs(ntb); + assertThat(bean.getBeanFactory()).isSameAs(bf); } @Test @@ -219,11 +214,11 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerSingleton("nestedTestBean2", ntb2); ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean3()); - assertSame(tb, bean.getTestBean4()); - assertEquals(2, bean.getNestedTestBeans().size()); - assertSame(ntb1, bean.getNestedTestBeans().get(0)); - assertSame(ntb2, bean.getNestedTestBeans().get(1)); + assertThat(bean.getTestBean3()).isNull(); + assertThat(bean.getTestBean4()).isSameAs(tb); + assertThat(bean.getNestedTestBeans().size()).isEqualTo(2); + assertThat(bean.getNestedTestBeans().get(0)).isSameAs(ntb1); + assertThat(bean.getNestedTestBeans().get(1)).isSameAs(ntb2); } @Test @@ -233,8 +228,8 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean", tb); ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb, bean.getTestBean3()); - assertNull(bean.getTestBean4()); + assertThat(bean.getTestBean3()).isSameAs(tb); + assertThat(bean.getTestBean4()).isNull(); } @Test @@ -248,18 +243,18 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean2", tb1); MapConstructorInjectionBean bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertEquals(2, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean2")); - assertTrue(bean.getTestBeanMap().values().contains(tb1)); - assertTrue(bean.getTestBeanMap().values().contains(tb2)); + assertThat(bean.getTestBeanMap().size()).isEqualTo(2); + assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue(); + assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb1)).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb2)).isTrue(); bean = (MapConstructorInjectionBean) bf.getBean("annotatedBean"); - assertEquals(2, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean2")); - assertTrue(bean.getTestBeanMap().values().contains(tb1)); - assertTrue(bean.getTestBeanMap().values().contains(tb2)); + assertThat(bean.getTestBeanMap().size()).isEqualTo(2); + assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue(); + assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb1)).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb2)).isTrue(); } @Test @@ -273,18 +268,18 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean2", tb1); MapFieldInjectionBean bean = (MapFieldInjectionBean) bf.getBean("annotatedBean"); - assertEquals(2, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean2")); - assertTrue(bean.getTestBeanMap().values().contains(tb1)); - assertTrue(bean.getTestBeanMap().values().contains(tb2)); + assertThat(bean.getTestBeanMap().size()).isEqualTo(2); + assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue(); + assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb1)).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb2)).isTrue(); bean = (MapFieldInjectionBean) bf.getBean("annotatedBean"); - assertEquals(2, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean2")); - assertTrue(bean.getTestBeanMap().values().contains(tb1)); - assertTrue(bean.getTestBeanMap().values().contains(tb2)); + assertThat(bean.getTestBeanMap().size()).isEqualTo(2); + assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue(); + assertThat(bean.getTestBeanMap().keySet().contains("testBean2")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb1)).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb2)).isTrue(); } @Test @@ -296,16 +291,16 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean", tb); MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean"); - assertEquals(1, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean")); - assertTrue(bean.getTestBeanMap().values().contains(tb)); - assertSame(tb, bean.getTestBean()); + assertThat(bean.getTestBeanMap().size()).isEqualTo(1); + assertThat(bean.getTestBeanMap().keySet().contains("testBean")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); bean = (MapMethodInjectionBean) bf.getBean("annotatedBean"); - assertEquals(1, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean")); - assertTrue(bean.getTestBeanMap().values().contains(tb)); - assertSame(tb, bean.getTestBean()); + assertThat(bean.getTestBeanMap().size()).isEqualTo(1); + assertThat(bean.getTestBeanMap().keySet().contains("testBean")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); } @Test @@ -327,10 +322,10 @@ public class InjectAnnotationBeanPostProcessorTests { MapMethodInjectionBean bean = (MapMethodInjectionBean) bf.getBean("annotatedBean"); TestBean tb = (TestBean) bf.getBean("testBean1"); - assertEquals(1, bean.getTestBeanMap().size()); - assertTrue(bean.getTestBeanMap().keySet().contains("testBean1")); - assertTrue(bean.getTestBeanMap().values().contains(tb)); - assertSame(tb, bean.getTestBean()); + assertThat(bean.getTestBeanMap().size()).isEqualTo(1); + assertThat(bean.getTestBeanMap().keySet().contains("testBean1")).isTrue(); + assertThat(bean.getTestBeanMap().values().contains(tb)).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); } @Test @@ -342,7 +337,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class)); ObjectFactoryQualifierFieldInjectionBean bean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -353,7 +348,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", bd); ObjectFactoryQualifierFieldInjectionBean bean = (ObjectFactoryQualifierFieldInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -367,10 +362,10 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class)); 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"); - assertNotSame(anotherBean, bean); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean).isNotSameAs(anotherBean); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -384,10 +379,10 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class)); 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"); - assertNotSame(anotherBean, bean); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean).isNotSameAs(anotherBean); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -397,9 +392,9 @@ public class InjectAnnotationBeanPostProcessorTests { bf.setSerializationId("test"); ObjectFactoryFieldInjectionBean bean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); bean = (ObjectFactoryFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -409,9 +404,9 @@ public class InjectAnnotationBeanPostProcessorTests { bf.setSerializationId("test"); ObjectFactoryMethodInjectionBean bean = (ObjectFactoryMethodInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); bean = (ObjectFactoryMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -421,9 +416,9 @@ public class InjectAnnotationBeanPostProcessorTests { bf.setSerializationId("test"); ObjectFactoryListFieldInjectionBean bean = (ObjectFactoryListFieldInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); bean = (ObjectFactoryListFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -433,9 +428,9 @@ public class InjectAnnotationBeanPostProcessorTests { bf.setSerializationId("test"); ObjectFactoryListMethodInjectionBean bean = (ObjectFactoryListMethodInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); bean = (ObjectFactoryListMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -445,9 +440,9 @@ public class InjectAnnotationBeanPostProcessorTests { bf.setSerializationId("test"); ObjectFactoryMapFieldInjectionBean bean = (ObjectFactoryMapFieldInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); bean = (ObjectFactoryMapFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -457,9 +452,9 @@ public class InjectAnnotationBeanPostProcessorTests { bf.setSerializationId("test"); ObjectFactoryMapMethodInjectionBean bean = (ObjectFactoryMapMethodInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); 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 FactoryBeanDependentBean bean = (FactoryBeanDependentBean) bf.getBean("factoryBeanDependentBean"); - assertNotNull("The singleton StringFactoryBean should have been registered.", factoryBean); - assertNotNull("The factoryBeanDependentBean should have been registered.", bean); - assertEquals("The FactoryBeanDependentBean should have been autowired 'by type' with the StringFactoryBean.", - factoryBean, bean.getFactoryBean()); + assertThat(factoryBean).as("The singleton StringFactoryBean should have been registered.").isNotNull(); + assertThat(bean).as("The factoryBeanDependentBean should have been registered.").isNotNull(); + assertThat(bean.getFactoryBean()).as("The FactoryBeanDependentBean should have been autowired 'by type' with the StringFactoryBean.").isEqualTo(factoryBean); } @Test @@ -487,7 +481,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); NullableFieldInjectionBean bean = (NullableFieldInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -495,7 +489,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(NullableFieldInjectionBean.class)); NullableFieldInjectionBean bean = (NullableFieldInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean()); + assertThat(bean.getTestBean()).isNull(); } @Test @@ -504,7 +498,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); NullableMethodInjectionBean bean = (NullableMethodInjectionBean) bf.getBean("annotatedBean"); - assertSame(bf.getBean("testBean"), bean.getTestBean()); + assertThat(bean.getTestBean()).isSameAs(bf.getBean("testBean")); } @Test @@ -512,7 +506,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(NullableMethodInjectionBean.class)); NullableMethodInjectionBean bean = (NullableMethodInjectionBean) bf.getBean("annotatedBean"); - assertNull(bean.getTestBean()); + assertThat(bean.getTestBean()).isNull(); } @Test @@ -521,8 +515,8 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); OptionalFieldInjectionBean bean = (OptionalFieldInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.getTestBean().isPresent()); - assertSame(bf.getBean("testBean"), bean.getTestBean().get()); + assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean")); } @Test @@ -530,7 +524,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalFieldInjectionBean.class)); OptionalFieldInjectionBean bean = (OptionalFieldInjectionBean) bf.getBean("annotatedBean"); - assertFalse(bean.getTestBean().isPresent()); + assertThat(bean.getTestBean().isPresent()).isFalse(); } @Test @@ -539,8 +533,8 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); OptionalMethodInjectionBean bean = (OptionalMethodInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.getTestBean().isPresent()); - assertSame(bf.getBean("testBean"), bean.getTestBean().get()); + assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean")); } @Test @@ -548,7 +542,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalMethodInjectionBean.class)); OptionalMethodInjectionBean bean = (OptionalMethodInjectionBean) bf.getBean("annotatedBean"); - assertFalse(bean.getTestBean().isPresent()); + assertThat(bean.getTestBean().isPresent()).isFalse(); } @Test @@ -557,8 +551,8 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); OptionalListFieldInjectionBean bean = (OptionalListFieldInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.getTestBean().isPresent()); - assertSame(bf.getBean("testBean"), bean.getTestBean().get().get(0)); + assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean().get().get(0)).isSameAs(bf.getBean("testBean")); } @Test @@ -566,7 +560,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListFieldInjectionBean.class)); OptionalListFieldInjectionBean bean = (OptionalListFieldInjectionBean) bf.getBean("annotatedBean"); - assertFalse(bean.getTestBean().isPresent()); + assertThat(bean.getTestBean().isPresent()).isFalse(); } @Test @@ -575,8 +569,8 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); OptionalListMethodInjectionBean bean = (OptionalListMethodInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.getTestBean().isPresent()); - assertSame(bf.getBean("testBean"), bean.getTestBean().get().get(0)); + assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean().get().get(0)).isSameAs(bf.getBean("testBean")); } @Test @@ -584,7 +578,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListMethodInjectionBean.class)); OptionalListMethodInjectionBean bean = (OptionalListMethodInjectionBean) bf.getBean("annotatedBean"); - assertFalse(bean.getTestBean().isPresent()); + assertThat(bean.getTestBean().isPresent()).isFalse(); } @Test @@ -593,8 +587,8 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); ProviderOfOptionalFieldInjectionBean bean = (ProviderOfOptionalFieldInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.getTestBean().isPresent()); - assertSame(bf.getBean("testBean"), bean.getTestBean().get()); + assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean")); } @Test @@ -602,7 +596,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalFieldInjectionBean.class)); ProviderOfOptionalFieldInjectionBean bean = (ProviderOfOptionalFieldInjectionBean) bf.getBean("annotatedBean"); - assertFalse(bean.getTestBean().isPresent()); + assertThat(bean.getTestBean().isPresent()).isFalse(); } @Test @@ -611,8 +605,8 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); ProviderOfOptionalMethodInjectionBean bean = (ProviderOfOptionalMethodInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.getTestBean().isPresent()); - assertSame(bf.getBean("testBean"), bean.getTestBean().get()); + assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean")); } @Test @@ -620,14 +614,14 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalMethodInjectionBean.class)); ProviderOfOptionalMethodInjectionBean bean = (ProviderOfOptionalMethodInjectionBean) bf.getBean("annotatedBean"); - assertFalse(bean.getTestBean().isPresent()); + assertThat(bean.getTestBean().isPresent()).isFalse(); } @Test public void testAnnotatedDefaultConstructor() { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(AnnotatedDefaultConstructorBean.class)); - assertNotNull(bf.getBean("annotatedBean")); + assertThat(bf.getBean("annotatedBean")).isNotNull(); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/LookupAnnotationTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/LookupAnnotationTests.java index 470e8a33d34..29a81a355b0 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/LookupAnnotationTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/LookupAnnotationTests.java @@ -23,10 +23,8 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; /** * @author Karl Pietrzak @@ -54,59 +52,59 @@ public class LookupAnnotationTests { @Test public void testWithoutConstructorArg() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); Object expected = bean.get(); - assertEquals(TestBean.class, expected.getClass()); - assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); + assertThat(expected.getClass()).isEqualTo(TestBean.class); + assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean); } @Test public void testWithOverloadedArg() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); TestBean expected = bean.get("haha"); - assertEquals(TestBean.class, expected.getClass()); - assertEquals("haha", expected.getName()); - assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); + assertThat(expected.getClass()).isEqualTo(TestBean.class); + assertThat(expected.getName()).isEqualTo("haha"); + assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean); } @Test public void testWithOneConstructorArg() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); TestBean expected = bean.getOneArgument("haha"); - assertEquals(TestBean.class, expected.getClass()); - assertEquals("haha", expected.getName()); - assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); + assertThat(expected.getClass()).isEqualTo(TestBean.class); + assertThat(expected.getName()).isEqualTo("haha"); + assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean); } @Test public void testWithTwoConstructorArg() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); TestBean expected = bean.getTwoArguments("haha", 72); - assertEquals(TestBean.class, expected.getClass()); - assertEquals("haha", expected.getName()); - assertEquals(72, expected.getAge()); - assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); + assertThat(expected.getClass()).isEqualTo(TestBean.class); + assertThat(expected.getName()).isEqualTo("haha"); + assertThat(expected.getAge()).isEqualTo(72); + assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean); } @Test public void testWithThreeArgsShouldFail() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); assertThatExceptionOfType(AbstractMethodError.class).as("TestBean has no three arg constructor").isThrownBy(() -> bean.getThreeArguments("name", 1, 2)); - assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); + assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean); } @Test public void testWithEarlyInjection() { AbstractBean bean = beanFactory.getBean("beanConsumer", BeanConsumer.class).abstractBean; - assertNotNull(bean); + assertThat(bean).isNotNull(); Object expected = bean.get(); - assertEquals(TestBean.class, expected.getClass()); - assertSame(bean, beanFactory.getBean(BeanConsumer.class).abstractBean); + assertThat(expected.getClass()).isEqualTo(TestBean.class); + assertThat(beanFactory.getBean(BeanConsumer.class).abstractBean).isSameAs(bean); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/ParameterResolutionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/ParameterResolutionTests.java index ce46f7c9d0d..b9b3a7f4501 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/ParameterResolutionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/ParameterResolutionTests.java @@ -27,10 +27,8 @@ import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.DependencyDescriptor; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.isNull; import static org.mockito.BDDMockito.given; @@ -67,7 +65,7 @@ public class ParameterResolutionTests { @Test public void annotatedParametersInInnerClassConstructorAreCandidatesForAutowiring() throws Exception { Class innerClass = AutowirableClass.InnerAutowirableClass.class; - assertTrue(ClassUtils.isInnerClass(innerClass)); + assertThat(ClassUtils.isInnerClass(innerClass)).isTrue(); Constructor constructor = innerClass.getConstructor(AutowirableClass.class, String.class, String.class); assertAutowirableParameters(constructor); } @@ -78,8 +76,7 @@ public class ParameterResolutionTests { Parameter[] parameters = executable.getParameters(); for (int parameterIndex = startIndex; parameterIndex < parameters.length; parameterIndex++) { Parameter parameter = parameters[parameterIndex]; - assertTrue("Parameter " + parameter + " must be autowirable", - ParameterResolutionDelegate.isAutowirable(parameter, parameterIndex)); + assertThat(ParameterResolutionDelegate.isAutowirable(parameter, parameterIndex)).as("Parameter " + parameter + " must be autowirable").isTrue(); } } @@ -90,8 +87,7 @@ public class ParameterResolutionTests { Parameter[] parameters = notAutowirableConstructor.getParameters(); for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex++) { Parameter parameter = parameters[parameterIndex]; - assertFalse("Parameter " + parameter + " must not be autowirable", - ParameterResolutionDelegate.isAutowirable(parameter, parameterIndex)); + assertThat(ParameterResolutionDelegate.isAutowirable(parameter, parameterIndex)).as("Parameter " + parameter + " must not be autowirable").isFalse(); } } @@ -135,8 +131,8 @@ public class ParameterResolutionTests { Parameter parameter = parameters[parameterIndex]; DependencyDescriptor intermediateDependencyDescriptor = (DependencyDescriptor) ParameterResolutionDelegate.resolveDependency( parameter, parameterIndex, AutowirableClass.class, beanFactory); - assertEquals(constructor, intermediateDependencyDescriptor.getAnnotatedElement()); - assertEquals(parameter, intermediateDependencyDescriptor.getMethodParameter().getParameter()); + assertThat(intermediateDependencyDescriptor.getAnnotatedElement()).isEqualTo(constructor); + assertThat(intermediateDependencyDescriptor.getMethodParameter().getParameter()).isEqualTo(parameter); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessorTests.java index 530e9d51940..2cb831e4f39 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessorTests.java @@ -32,8 +32,8 @@ import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; 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.junit.Assert.assertEquals; /** * @author Rob Harrop @@ -92,8 +92,8 @@ public class RequiredAnnotationBeanPostProcessorTests { factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor()); factory.preInstantiateSingletons(); RequiredTestBean bean = (RequiredTestBean) factory.getBean("testBean"); - assertEquals(24, bean.getAge()); - assertEquals("Blue", bean.getFavouriteColour()); + assertThat(bean.getAge()).isEqualTo(24); + assertThat(bean.getFavouriteColour()).isEqualTo("Blue"); } @Test @@ -146,8 +146,8 @@ public class RequiredAnnotationBeanPostProcessorTests { factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor()); factory.preInstantiateSingletons(); RequiredTestBean bean = (RequiredTestBean) factory.getBean("testBean"); - assertEquals(24, bean.getAge()); - assertEquals("Blue", bean.getFavouriteColour()); + assertThat(bean.getAge()).isEqualTo(24); + assertThat(bean.getFavouriteColour()).isEqualTo("Blue"); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java index f6b56077f8a..5397ac4d7b1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java @@ -35,8 +35,7 @@ import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -71,9 +70,9 @@ public class CustomEditorConfigurerTests { bf.registerBeanDefinition("tb2", bd2); 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"); - assertEquals(df.parse("2.12.1975"), tb2.getSomeMap().get("myKey")); + assertThat(tb2.getSomeMap().get("myKey")).isEqualTo(df.parse("2.12.1975")); } @Test @@ -93,7 +92,7 @@ public class CustomEditorConfigurerTests { TestBean tb = (TestBean) bf.getBean("tb"); 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 @@ -112,8 +111,8 @@ public class CustomEditorConfigurerTests { bf.registerBeanDefinition("tb", bd); TestBean tb = (TestBean) bf.getBean("tb"); - assertTrue(tb.getStringArray() != null && tb.getStringArray().length == 1); - assertEquals("test", tb.getStringArray()[0]); + assertThat(tb.getStringArray() != null && tb.getStringArray().length == 1).isTrue(); + assertThat(tb.getStringArray()[0]).isEqualTo("test"); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java index e6432922424..7d4c4bbd999 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java @@ -23,9 +23,9 @@ import org.junit.Test; 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.assertThatIllegalArgumentException; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; /** @@ -66,7 +66,8 @@ public class CustomScopeConfigurerTests { CustomScopeConfigurer figurer = new CustomScopeConfigurer(); figurer.setScopes(scopes); figurer.postProcessBeanFactory(factory); - assertTrue(factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope); + boolean condition = factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope; + assertThat(condition).isTrue(); } @Test @@ -76,7 +77,8 @@ public class CustomScopeConfigurerTests { CustomScopeConfigurer figurer = new CustomScopeConfigurer(); figurer.setScopes(scopes); figurer.postProcessBeanFactory(factory); - assertTrue(factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope); + boolean condition = factory.getRegisteredScope(FOO_SCOPE) instanceof NoOpScope; + assertThat(condition).isTrue(); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/DeprecatedBeanWarnerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/DeprecatedBeanWarnerTests.java index c0181038d86..76319d16c87 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/DeprecatedBeanWarnerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/DeprecatedBeanWarnerTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -43,8 +43,8 @@ public class DeprecatedBeanWarnerTests { DeprecatedBeanWarner warner = new MyDeprecatedBeanWarner(); warner.postProcessBeanFactory(beanFactory); - assertEquals(beanName, this.beanName); - assertEquals(def, this.beanDefinition); + assertThat(this.beanName).isEqualTo(beanName); + assertThat(this.beanDefinition).isEqualTo(def); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests.java index e1507ba6f58..78e5b11b318 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests.java @@ -24,7 +24,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; 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; /** @@ -41,7 +41,7 @@ public class FieldRetrievingFactoryBeanTests { FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean(); fr.setStaticField("java.sql.Connection.TRANSACTION_SERIALIZABLE"); fr.afterPropertiesSet(); - assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject()); + assertThat(fr.getObject()).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE)); } @Test @@ -49,7 +49,7 @@ public class FieldRetrievingFactoryBeanTests { FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean(); fr.setStaticField(" java.sql.Connection.TRANSACTION_SERIALIZABLE "); fr.afterPropertiesSet(); - assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject()); + assertThat(fr.getObject()).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE)); } @Test @@ -58,7 +58,7 @@ public class FieldRetrievingFactoryBeanTests { fr.setTargetClass(Connection.class); fr.setTargetField("TRANSACTION_SERIALIZABLE"); fr.afterPropertiesSet(); - assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject()); + assertThat(fr.getObject()).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE)); } @Test @@ -68,7 +68,7 @@ public class FieldRetrievingFactoryBeanTests { fr.setTargetObject(target); fr.setTargetField("publicField"); fr.afterPropertiesSet(); - assertEquals(target.publicField, fr.getObject()); + assertThat(fr.getObject()).isEqualTo(target.publicField); } @Test @@ -76,7 +76,7 @@ public class FieldRetrievingFactoryBeanTests { FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean(); fr.setBeanName("java.sql.Connection.TRANSACTION_SERIALIZABLE"); fr.afterPropertiesSet(); - assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), fr.getObject()); + assertThat(fr.getObject()).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE)); } @Test @@ -117,7 +117,7 @@ public class FieldRetrievingFactoryBeanTests { FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean(); fr.setBeanName("org.springframework.tests.sample.beans.PackageLevelVisibleBean.CONSTANT"); fr.afterPropertiesSet(); - assertEquals("Wuby", fr.getObject()); + assertThat(fr.getObject()).isEqualTo("Wuby"); } @Test @@ -127,8 +127,8 @@ public class FieldRetrievingFactoryBeanTests { qualifiedResource(FieldRetrievingFactoryBeanTests.class, "context.xml")); TestBean testBean = (TestBean) bf.getBean("testBean"); - assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), testBean.getSomeIntegerArray()[0]); - assertEquals(new Integer(Connection.TRANSACTION_SERIALIZABLE), testBean.getSomeIntegerArray()[1]); + assertThat(testBean.getSomeIntegerArray()[0]).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE)); + assertThat(testBean.getSomeIntegerArray()[1]).isEqualTo(new Integer(Connection.TRANSACTION_SERIALIZABLE)); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/MethodInvokingFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/MethodInvokingFactoryBeanTests.java index 9e3012c49f4..9017b5d4bd5 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/MethodInvokingFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/MethodInvokingFactoryBeanTests.java @@ -26,12 +26,9 @@ import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.beans.support.ArgumentConvertingMethodInvoker; 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.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}. @@ -45,7 +42,6 @@ public class MethodInvokingFactoryBeanTests { @Test 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 MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean(); @@ -102,14 +98,14 @@ public class MethodInvokingFactoryBeanTests { mcfb.setTargetObject(tc1); mcfb.setTargetMethod("method1"); mcfb.afterPropertiesSet(); - assertTrue(int.class.equals(mcfb.getObjectType())); + assertThat(int.class.equals(mcfb.getObjectType())).isTrue(); mcfb = new MethodInvokingFactoryBean(); mcfb.setTargetClass(TestClass1.class); mcfb.setTargetMethod("voidRetvalMethod"); mcfb.afterPropertiesSet(); 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 // target method arg types @@ -139,9 +135,9 @@ public class MethodInvokingFactoryBeanTests { mcfb.setTargetMethod("method1"); mcfb.afterPropertiesSet(); Integer i = (Integer) mcfb.getObject(); - assertEquals(1, i.intValue()); + assertThat(i.intValue()).isEqualTo(1); i = (Integer) mcfb.getObject(); - assertEquals(1, i.intValue()); + assertThat(i.intValue()).isEqualTo(1); // non-singleton, non-static tc1 = new TestClass1(); @@ -151,9 +147,9 @@ public class MethodInvokingFactoryBeanTests { mcfb.setSingleton(false); mcfb.afterPropertiesSet(); i = (Integer) mcfb.getObject(); - assertEquals(1, i.intValue()); + assertThat(i.intValue()).isEqualTo(1); i = (Integer) mcfb.getObject(); - assertEquals(2, i.intValue()); + assertThat(i.intValue()).isEqualTo(2); // singleton, static TestClass1._staticField1 = 0; @@ -162,9 +158,9 @@ public class MethodInvokingFactoryBeanTests { mcfb.setTargetMethod("staticMethod1"); mcfb.afterPropertiesSet(); i = (Integer) mcfb.getObject(); - assertEquals(1, i.intValue()); + assertThat(i.intValue()).isEqualTo(1); i = (Integer) mcfb.getObject(); - assertEquals(1, i.intValue()); + assertThat(i.intValue()).isEqualTo(1); // non-singleton, static TestClass1._staticField1 = 0; @@ -173,16 +169,16 @@ public class MethodInvokingFactoryBeanTests { mcfb.setSingleton(false); mcfb.afterPropertiesSet(); i = (Integer) mcfb.getObject(); - assertEquals(1, i.intValue()); + assertThat(i.intValue()).isEqualTo(1); i = (Integer) mcfb.getObject(); - assertEquals(2, i.intValue()); + assertThat(i.intValue()).isEqualTo(2); // void return value mcfb = new MethodInvokingFactoryBean(); mcfb.setTargetClass(TestClass1.class); mcfb.setTargetMethod("voidRetvalMethod"); mcfb.afterPropertiesSet(); - assertNull(mcfb.getObject()); + assertThat(mcfb.getObject()).isNull(); // now see if we can match methods with arguments that have supertype arguments mcfb = new MethodInvokingFactoryBean(); @@ -216,7 +212,7 @@ public class MethodInvokingFactoryBeanTests { mcfb.setTargetMethod("supertypes2"); mcfb.setArguments(new ArrayList<>(), new ArrayList(), "hello", "bogus"); mcfb.afterPropertiesSet(); - assertEquals("hello", mcfb.getObject()); + assertThat(mcfb.getObject()).isEqualTo("hello"); mcfb = new MethodInvokingFactoryBean(); mcfb.setTargetClass(TestClass1.class); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java index 4b38fb7f108..8cb98f403ea 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java @@ -29,10 +29,8 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.Mockito.mock; import static org.springframework.tests.TestResourceUtils.qualifiedResource; @@ -69,7 +67,7 @@ public class ObjectFactoryCreatingFactoryBeanTests { Date date1 = (Date) objectFactory.getObject(); Date date2 = (Date) objectFactory.getObject(); - assertTrue(date1 != date2); + assertThat(date1 != date2).isTrue(); } @Test @@ -82,7 +80,7 @@ public class ObjectFactoryCreatingFactoryBeanTests { Date date1 = (Date) objectFactory.getObject(); Date date2 = (Date) objectFactory.getObject(); - assertTrue(date1 != date2); + assertThat(date1 != date2).isTrue(); } @Test @@ -92,7 +90,7 @@ public class ObjectFactoryCreatingFactoryBeanTests { Date date1 = (Date) provider.get(); Date date2 = (Date) provider.get(); - assertTrue(date1 != date2); + assertThat(date1 != date2).isTrue(); } @Test @@ -105,7 +103,7 @@ public class ObjectFactoryCreatingFactoryBeanTests { Date date1 = (Date) provider.get(); Date date2 = (Date) provider.get(); - assertTrue(date1 != date2); + assertThat(date1 != date2).isTrue(); } @Test @@ -122,7 +120,7 @@ public class ObjectFactoryCreatingFactoryBeanTests { factory.afterPropertiesSet(); ObjectFactory objectFactory = factory.getObject(); Object actualSingleton = objectFactory.getObject(); - assertSame(expectedSingleton, actualSingleton); + assertThat(actualSingleton).isSameAs(expectedSingleton); } @Test @@ -152,8 +150,7 @@ public class ObjectFactoryCreatingFactoryBeanTests { @Test public void testEnsureOFBFBReportsThatItActuallyCreatesObjectFactoryInstances() { - assertEquals("Must be reporting that it creates ObjectFactory instances (as per class contract).", - ObjectFactory.class, new ObjectFactoryCreatingFactoryBean().getObjectType()); + assertThat(new ObjectFactoryCreatingFactoryBean().getObjectType()).as("Must be reporting that it creates ObjectFactory instances (as per class contract).").isEqualTo(ObjectFactory.class); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertiesFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertiesFactoryBeanTests.java index 518869061fa..f29b48ff48e 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertiesFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertiesFactoryBeanTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.core.io.Resource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -45,7 +44,7 @@ public class PropertiesFactoryBeanTests { pfb.setLocation(TEST_PROPS); pfb.afterPropertiesSet(); Properties props = pfb.getObject(); - assertEquals("99", props.getProperty("tb.array[0].age")); + assertThat(props.getProperty("tb.array[0].age")).isEqualTo("99"); } @Test @@ -54,7 +53,7 @@ public class PropertiesFactoryBeanTests { pfb.setLocation(TEST_PROPS_XML); pfb.afterPropertiesSet(); Properties props = pfb.getObject(); - assertEquals("99", props.getProperty("tb.array[0].age")); + assertThat(props.getProperty("tb.array[0].age")).isEqualTo("99"); } @Test @@ -65,7 +64,7 @@ public class PropertiesFactoryBeanTests { pfb.setProperties(localProps); pfb.afterPropertiesSet(); Properties props = pfb.getObject(); - assertEquals("value2", props.getProperty("key2")); + assertThat(props.getProperty("key2")).isEqualTo("value2"); } @Test @@ -78,8 +77,8 @@ public class PropertiesFactoryBeanTests { pfb.setProperties(localProps); pfb.afterPropertiesSet(); Properties props = pfb.getObject(); - assertEquals("99", props.getProperty("tb.array[0].age")); - assertEquals("value2", props.getProperty("key2")); + assertThat(props.getProperty("tb.array[0].age")).isEqualTo("99"); + assertThat(props.getProperty("key2")).isEqualTo("value2"); } @Test @@ -103,12 +102,12 @@ public class PropertiesFactoryBeanTests { pfb.afterPropertiesSet(); Properties props = pfb.getObject(); - assertEquals("99", props.getProperty("tb.array[0].age")); - assertEquals("value2", props.getProperty("key2")); - assertEquals("framework", props.getProperty("spring")); - assertEquals("Mattingly", props.getProperty("Don")); - assertEquals("man", props.getProperty("spider")); - assertEquals("man", props.getProperty("bat")); + assertThat(props.getProperty("tb.array[0].age")).isEqualTo("99"); + assertThat(props.getProperty("key2")).isEqualTo("value2"); + assertThat(props.getProperty("spring")).isEqualTo("framework"); + assertThat(props.getProperty("Don")).isEqualTo("Mattingly"); + assertThat(props.getProperty("spider")).isEqualTo("man"); + assertThat(props.getProperty("bat")).isEqualTo("man"); } @Test @@ -122,8 +121,8 @@ public class PropertiesFactoryBeanTests { pfb.setLocalOverride(true); pfb.afterPropertiesSet(); Properties props = pfb.getObject(); - assertEquals("0", props.getProperty("tb.array[0].age")); - assertEquals("value2", props.getProperty("key2")); + assertThat(props.getProperty("tb.array[0].age")).isEqualTo("0"); + assertThat(props.getProperty("key2")).isEqualTo("value2"); } @Test @@ -136,12 +135,12 @@ public class PropertiesFactoryBeanTests { pfb.setProperties(localProps); pfb.afterPropertiesSet(); Properties props = pfb.getObject(); - assertEquals("99", props.getProperty("tb.array[0].age")); - assertEquals("value2", props.getProperty("key2")); + assertThat(props.getProperty("tb.array[0].age")).isEqualTo("99"); + assertThat(props.getProperty("key2")).isEqualTo("value2"); Properties newProps = pfb.getObject(); - assertTrue(props != newProps); - assertEquals("99", newProps.getProperty("tb.array[0].age")); - assertEquals("value2", newProps.getProperty("key2")); + assertThat(props != newProps).isTrue(); + assertThat(newProps.getProperty("tb.array[0].age")).isEqualTo("99"); + assertThat(newProps.getProperty("key2")).isEqualTo("value2"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests.java index f0947243f6d..2459ea6ea9b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests.java @@ -24,10 +24,7 @@ import org.springframework.core.io.Resource; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -46,43 +43,47 @@ public class PropertyPathFactoryBeanTests { public void testPropertyPathFactoryBeanWithSingletonResult() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); - assertEquals(new Integer(12), xbf.getBean("propertyPath1")); - assertEquals(new Integer(11), xbf.getBean("propertyPath2")); - assertEquals(new Integer(10), xbf.getBean("tb.age")); - assertEquals(ITestBean.class, xbf.getType("otb.spouse")); + assertThat(xbf.getBean("propertyPath1")).isEqualTo(new Integer(12)); + assertThat(xbf.getBean("propertyPath2")).isEqualTo(new Integer(11)); + assertThat(xbf.getBean("tb.age")).isEqualTo(new Integer(10)); + assertThat(xbf.getType("otb.spouse")).isEqualTo(ITestBean.class); Object result1 = xbf.getBean("otb.spouse"); Object result2 = xbf.getBean("otb.spouse"); - assertTrue(result1 instanceof TestBean); - assertTrue(result1 == result2); - assertEquals(99, ((TestBean) result1).getAge()); + boolean condition = result1 instanceof TestBean; + assertThat(condition).isTrue(); + assertThat(result1 == result2).isTrue(); + assertThat(((TestBean) result1).getAge()).isEqualTo(99); } @Test public void testPropertyPathFactoryBeanWithPrototypeResult() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); - assertNull(xbf.getType("tb.spouse")); - assertEquals(TestBean.class, xbf.getType("propertyPath3")); + assertThat(xbf.getType("tb.spouse")).isNull(); + assertThat(xbf.getType("propertyPath3")).isEqualTo(TestBean.class); Object result1 = xbf.getBean("tb.spouse"); Object result2 = xbf.getBean("propertyPath3"); Object result3 = xbf.getBean("propertyPath3"); - assertTrue(result1 instanceof TestBean); - assertTrue(result2 instanceof TestBean); - assertTrue(result3 instanceof TestBean); - assertEquals(11, ((TestBean) result1).getAge()); - assertEquals(11, ((TestBean) result2).getAge()); - assertEquals(11, ((TestBean) result3).getAge()); - assertTrue(result1 != result2); - assertTrue(result1 != result3); - assertTrue(result2 != result3); + boolean condition2 = result1 instanceof TestBean; + assertThat(condition2).isTrue(); + boolean condition1 = result2 instanceof TestBean; + assertThat(condition1).isTrue(); + boolean condition = result3 instanceof TestBean; + assertThat(condition).isTrue(); + assertThat(((TestBean) result1).getAge()).isEqualTo(11); + assertThat(((TestBean) result2).getAge()).isEqualTo(11); + assertThat(((TestBean) result3).getAge()).isEqualTo(11); + assertThat(result1 != result2).isTrue(); + assertThat(result1 != result3).isTrue(); + assertThat(result2 != result3).isTrue(); } @Test public void testPropertyPathFactoryBeanWithNullResult() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); - assertNull(xbf.getType("tb.spouse.spouse")); - assertEquals("null", xbf.getBean("tb.spouse.spouse").toString()); + assertThat(xbf.getType("tb.spouse.spouse")).isNull(); + assertThat(xbf.getBean("tb.spouse.spouse").toString()).isEqualTo("null"); } @Test @@ -91,23 +92,24 @@ public class PropertyPathFactoryBeanTests { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); TestBean spouse = (TestBean) xbf.getBean("otb.spouse"); TestBean tbWithInner = (TestBean) xbf.getBean("tbWithInner"); - assertSame(spouse, tbWithInner.getSpouse()); - assertTrue(!tbWithInner.getFriends().isEmpty()); - assertSame(spouse, tbWithInner.getFriends().iterator().next()); + assertThat(tbWithInner.getSpouse()).isSameAs(spouse); + boolean condition = !tbWithInner.getFriends().isEmpty(); + assertThat(condition).isTrue(); + assertThat(tbWithInner.getFriends().iterator().next()).isSameAs(spouse); } @Test public void testPropertyPathFactoryBeanAsNullReference() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); - assertNull(xbf.getBean("tbWithNullReference", TestBean.class).getSpouse()); + assertThat(xbf.getBean("tbWithNullReference", TestBean.class).getSpouse()).isNull(); } @Test public void testPropertyPathFactoryBeanAsInnerNull() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); - assertNull(xbf.getBean("tbWithInnerNull", TestBean.class).getSpouse()); + assertThat(xbf.getBean("tbWithInnerNull", TestBean.class).getSpouse()).isNull(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java index db55103f288..1c9e0ec3281 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java @@ -44,12 +44,8 @@ import org.springframework.tests.sample.beans.IndexedTestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.tests.TestResourceUtils.qualifiedResource; @@ -113,10 +109,10 @@ public class PropertyResourceConfigurerTests { TestBean tb1 = (TestBean) factory.getBean("tb1"); TestBean tb2 = (TestBean) factory.getBean("tb2"); - assertEquals(99, tb1.getAge()); - assertEquals(99, tb2.getAge()); - assertEquals(null, tb1.getName()); - assertEquals("test", tb2.getName()); + assertThat(tb1.getAge()).isEqualTo(99); + assertThat(tb2.getAge()).isEqualTo(99); + assertThat(tb1.getName()).isEqualTo(null); + assertThat(tb2.getName()).isEqualTo("test"); } @Test @@ -133,8 +129,8 @@ public class PropertyResourceConfigurerTests { poc.postProcessBeanFactory(factory); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); - assertEquals(99, tb.getArray()[0].getAge()); - assertEquals("test", ((TestBean) tb.getList().get(1)).getName()); + assertThat(tb.getArray()[0].getAge()).isEqualTo(99); + assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("test"); } @Test @@ -152,8 +148,8 @@ public class PropertyResourceConfigurerTests { poc.postProcessBeanFactory(factory); IndexedTestBean tb = (IndexedTestBean) factory.getBean("my.tb"); - assertEquals(99, tb.getArray()[0].getAge()); - assertEquals("test", ((TestBean) tb.getList().get(1)).getName()); + assertThat(tb.getArray()[0].getAge()).isEqualTo(99); + assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("test"); } @Test @@ -170,8 +166,8 @@ public class PropertyResourceConfigurerTests { poc.postProcessBeanFactory(factory); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); - assertEquals("99", tb.getMap().get("key1")); - assertEquals("test", tb.getMap().get("key2.ext")); + assertThat(tb.getMap().get("key1")).isEqualTo("99"); + assertThat(tb.getMap().get("key2.ext")).isEqualTo("test"); } @Test @@ -187,7 +183,7 @@ public class PropertyResourceConfigurerTests { poc.postProcessBeanFactory(factory); PropertiesHolder tb = (PropertiesHolder) factory.getBean("tb"); - assertEquals("true", tb.getHeldProperties().getProperty("mail.smtp.auth")); + assertThat(tb.getHeldProperties().getProperty("mail.smtp.auth")).isEqualTo("true"); } @Test @@ -200,8 +196,8 @@ public class PropertyResourceConfigurerTests { poc.postProcessBeanFactory(factory); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); - assertEquals(99, tb.getArray()[0].getAge()); - assertEquals("test", ((TestBean) tb.getList().get(1)).getName()); + assertThat(tb.getArray()[0].getAge()).isEqualTo(99); + assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("test"); } @Test @@ -215,8 +211,8 @@ public class PropertyResourceConfigurerTests { poc.postProcessBeanFactory(factory); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); - assertEquals(99, tb.getArray()[0].getAge()); - assertEquals("test", ((TestBean) tb.getList().get(1)).getName()); + assertThat(tb.getArray()[0].getAge()).isEqualTo(99); + assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("test"); } @Test @@ -229,8 +225,8 @@ public class PropertyResourceConfigurerTests { poc.postProcessBeanFactory(factory); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); - assertEquals(99, tb.getArray()[0].getAge()); - assertEquals("test", ((TestBean) tb.getList().get(1)).getName()); + assertThat(tb.getArray()[0].getAge()).isEqualTo(99); + assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("test"); } @Test @@ -246,8 +242,8 @@ public class PropertyResourceConfigurerTests { bfpp.postProcessBeanFactory(factory); IndexedTestBean tb = (IndexedTestBean) factory.getBean("tb"); - assertEquals("X99", tb.getArray()[0].getName()); - assertEquals("Xtest", ((TestBean) tb.getList().get(1)).getName()); + assertThat(tb.getArray()[0].getName()).isEqualTo("X99"); + assertThat(((TestBean) tb.getList().get(1)).getName()).isEqualTo("Xtest"); } @Test @@ -265,7 +261,7 @@ public class PropertyResourceConfigurerTests { props.setProperty("tb3.name", "test"); poc.setProperties(props); poc.postProcessBeanFactory(factory); - assertEquals("test", factory.getBean("tb2", TestBean.class).getName()); + assertThat(factory.getBean("tb2", TestBean.class).getName()).isEqualTo("test"); } { PropertyOverrideConfigurer poc = new PropertyOverrideConfigurer(); @@ -280,7 +276,7 @@ public class PropertyResourceConfigurerTests { } catch (BeanInitializationException ex) { // 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 tb2 = (TestBean) factory.getBean("tb2"); - assertEquals(99, tb1.getAge()); - assertEquals(99, tb2.getAge()); - assertEquals(null, tb1.getName()); - assertEquals("test", tb2.getName()); + assertThat(tb1.getAge()).isEqualTo(99); + assertThat(tb2.getAge()).isEqualTo(99); + assertThat(tb1.getName()).isEqualTo(null); + assertThat(tb2.getName()).isEqualTo("test"); } @Test @@ -402,36 +398,36 @@ public class PropertyResourceConfigurerTests { TestBean tb1 = (TestBean) factory.getBean("tb1"); TestBean tb2 = (TestBean) factory.getBean("tb2"); - assertEquals(98, tb1.getAge()); - assertEquals(98, tb2.getAge()); - assertEquals("namemyvarmyvar${", tb1.getName()); - assertEquals("myvarname98", tb2.getName()); - assertEquals(tb2, tb1.getSpouse()); - assertEquals(1, tb1.getSomeMap().size()); - assertEquals("myValue", tb1.getSomeMap().get("myKey")); - assertEquals(2, tb2.getStringArray().length); - assertEquals(System.getProperty("os.name"), tb2.getStringArray()[0]); - assertEquals("98", tb2.getStringArray()[1]); - assertEquals(2, tb2.getFriends().size()); - assertEquals("na98me", tb2.getFriends().iterator().next()); - assertEquals(tb2, tb2.getFriends().toArray()[1]); - assertEquals(3, tb2.getSomeSet().size()); - assertTrue(tb2.getSomeSet().contains("na98me")); - assertTrue(tb2.getSomeSet().contains(tb2)); - assertTrue(tb2.getSomeSet().contains(new Integer(98))); - assertEquals(6, tb2.getSomeMap().size()); - assertEquals("98", tb2.getSomeMap().get("key98")); - assertEquals(tb2, tb2.getSomeMap().get("key98ref")); - assertEquals(tb2, tb2.getSomeMap().get("key1")); - assertEquals("98name", tb2.getSomeMap().get("key2")); + assertThat(tb1.getAge()).isEqualTo(98); + assertThat(tb2.getAge()).isEqualTo(98); + assertThat(tb1.getName()).isEqualTo("namemyvarmyvar${"); + assertThat(tb2.getName()).isEqualTo("myvarname98"); + assertThat(tb1.getSpouse()).isEqualTo(tb2); + assertThat(tb1.getSomeMap().size()).isEqualTo(1); + assertThat(tb1.getSomeMap().get("myKey")).isEqualTo("myValue"); + assertThat(tb2.getStringArray().length).isEqualTo(2); + assertThat(tb2.getStringArray()[0]).isEqualTo(System.getProperty("os.name")); + assertThat(tb2.getStringArray()[1]).isEqualTo("98"); + assertThat(tb2.getFriends().size()).isEqualTo(2); + assertThat(tb2.getFriends().iterator().next()).isEqualTo("na98me"); + assertThat(tb2.getFriends().toArray()[1]).isEqualTo(tb2); + assertThat(tb2.getSomeSet().size()).isEqualTo(3); + assertThat(tb2.getSomeSet().contains("na98me")).isTrue(); + assertThat(tb2.getSomeSet().contains(tb2)).isTrue(); + assertThat(tb2.getSomeSet().contains(new Integer(98))).isTrue(); + assertThat(tb2.getSomeMap().size()).isEqualTo(6); + assertThat(tb2.getSomeMap().get("key98")).isEqualTo("98"); + assertThat(tb2.getSomeMap().get("key98ref")).isEqualTo(tb2); + assertThat(tb2.getSomeMap().get("key1")).isEqualTo(tb2); + assertThat(tb2.getSomeMap().get("key2")).isEqualTo("98name"); TestBean inner1 = (TestBean) tb2.getSomeMap().get("key3"); TestBean inner2 = (TestBean) tb2.getSomeMap().get("mykey4"); - assertEquals(0, inner1.getAge()); - assertEquals(null, inner1.getName()); - assertEquals(System.getProperty("os.name"), inner1.getCountry()); - assertEquals(98, inner2.getAge()); - assertEquals("namemyvarmyvar${", inner2.getName()); - assertEquals(System.getProperty("os.name"), inner2.getCountry()); + assertThat(inner1.getAge()).isEqualTo(0); + assertThat(inner1.getName()).isEqualTo(null); + assertThat(inner1.getCountry()).isEqualTo(System.getProperty("os.name")); + assertThat(inner2.getAge()).isEqualTo(98); + assertThat(inner2.getName()).isEqualTo("namemyvarmyvar${"); + assertThat(inner2.getCountry()).isEqualTo(System.getProperty("os.name")); } @Test @@ -443,7 +439,7 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertEquals(System.getProperty("os.name"), tb.getCountry()); + assertThat(tb.getCountry()).isEqualTo(System.getProperty("os.name")); } @Test @@ -458,7 +454,7 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertEquals("myos", tb.getCountry()); + assertThat(tb.getCountry()).isEqualTo("myos"); } @Test @@ -474,7 +470,7 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertEquals(System.getProperty("os.name"), tb.getCountry()); + assertThat(tb.getCountry()).isEqualTo(System.getProperty("os.name")); } @Test @@ -508,7 +504,7 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertEquals("${ref}", tb.getName()); + assertThat(tb.getName()).isEqualTo("${ref}"); } @Test @@ -521,7 +517,7 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertNull(tb.getName()); + assertThat(tb.getName()).isNull(); } @Test @@ -537,7 +533,7 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertNull(tb.getName()); + assertThat(tb.getName()).isNull(); } @Test @@ -553,7 +549,7 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertEquals("myname", tb.getName()); + assertThat(tb.getName()).isEqualTo("myname"); } @Test @@ -569,7 +565,7 @@ public class PropertyResourceConfigurerTests { TestBean tb = (TestBean) factory.getBean("tb"); TestBean tb2 = (TestBean) factory.getBean("tb2"); - assertSame(tb, tb2); + assertThat(tb2).isSameAs(tb); } @Test @@ -584,8 +580,8 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertNotNull(tb); - assertEquals(0, factory.getAliases("tb").length); + assertThat(tb).isNotNull(); + assertThat(factory.getAliases("tb").length).isEqualTo(0); } @Test @@ -617,7 +613,7 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertEquals("mytest", tb.getTouchy()); + assertThat(tb.getTouchy()).isEqualTo("mytest"); } @Test @@ -629,7 +625,7 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertEquals("mytest", tb.getTouchy()); + assertThat(tb.getTouchy()).isEqualTo("mytest"); } @Test @@ -649,11 +645,11 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertEquals("mytest", tb.getTouchy()); + assertThat(tb.getTouchy()).isEqualTo("mytest"); tb = (TestBean) factory.getBean("alias"); - assertEquals("mytest", tb.getTouchy()); + assertThat(tb.getTouchy()).isEqualTo("mytest"); tb = (TestBean) factory.getBean("alias2"); - assertEquals("mytest", tb.getTouchy()); + assertThat(tb.getTouchy()).isEqualTo("mytest"); } @Test @@ -675,9 +671,9 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertEquals("myNameValue", tb.getName()); - assertEquals(99, tb.getAge()); - assertEquals("myOtherTouchyValue", tb.getTouchy()); + assertThat(tb.getName()).isEqualTo("myNameValue"); + assertThat(tb.getAge()).isEqualTo(99); + assertThat(tb.getTouchy()).isEqualTo("myOtherTouchyValue"); Preferences.userRoot().remove("myTouchy"); Preferences.systemRoot().remove("myTouchy"); Preferences.systemRoot().remove("myName"); @@ -704,9 +700,9 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertEquals("myNameValue", tb.getName()); - assertEquals(99, tb.getAge()); - assertEquals("myOtherTouchyValue", tb.getTouchy()); + assertThat(tb.getName()).isEqualTo("myNameValue"); + assertThat(tb.getAge()).isEqualTo(99); + assertThat(tb.getTouchy()).isEqualTo("myOtherTouchyValue"); Preferences.userRoot().node("myUserPath").remove("myTouchy"); Preferences.systemRoot().node("mySystemPath").remove("myTouchy"); Preferences.systemRoot().node("mySystemPath").remove("myName"); @@ -733,9 +729,9 @@ public class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); - assertEquals("myNameValue", tb.getName()); - assertEquals(99, tb.getAge()); - assertEquals("myOtherTouchyValue", tb.getTouchy()); + assertThat(tb.getName()).isEqualTo("myNameValue"); + assertThat(tb.getAge()).isEqualTo(99); + assertThat(tb.getTouchy()).isEqualTo("myOtherTouchyValue"); Preferences.userRoot().node("myUserPath/myotherpath").remove("myTouchy"); Preferences.systemRoot().node("mySystemPath/myotherpath").remove("myTouchy"); Preferences.systemRoot().node("mySystemPath/mypath").remove("myName"); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java index 08795d599a1..a16f8fbc16f 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java @@ -27,12 +27,9 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.NestedCheckedException; 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.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.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; @@ -62,7 +59,7 @@ public class ServiceLocatorFactoryBeanTests { TestServiceLocator factory = (TestServiceLocator) bf.getBean("factory"); TestService testService = factory.getTestService(); - assertNotNull(testService); + assertThat(testService).isNotNull(); } @Test @@ -161,14 +158,14 @@ public class ServiceLocatorFactoryBeanTests { TestService testBean2 = factory.getTestService("testService"); TestService testBean3 = factory.getTestService(1); TestService testBean4 = factory.someFactoryMethod(); - assertNotSame(testBean1, testBean2); - assertNotSame(testBean1, testBean3); - assertNotSame(testBean1, testBean4); - assertNotSame(testBean2, testBean3); - assertNotSame(testBean2, testBean4); - assertNotSame(testBean3, testBean4); + assertThat(testBean2).isNotSameAs(testBean1); + assertThat(testBean3).isNotSameAs(testBean1); + assertThat(testBean4).isNotSameAs(testBean1); + assertThat(testBean3).isNotSameAs(testBean2); + assertThat(testBean4).isNotSameAs(testBean2); + 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 @@ -195,16 +192,20 @@ public class ServiceLocatorFactoryBeanTests { TestService testBean2 = factory.getTestService("testService1"); TestService testBean3 = factory.getTestService(1); TestService testBean4 = factory.getTestService(2); - assertNotSame(testBean1, testBean2); - assertNotSame(testBean1, testBean3); - assertNotSame(testBean1, testBean4); - assertNotSame(testBean2, testBean3); - assertNotSame(testBean2, testBean4); - assertNotSame(testBean3, testBean4); - assertFalse(testBean1 instanceof ExtendedTestService); - assertFalse(testBean2 instanceof ExtendedTestService); - assertFalse(testBean3 instanceof ExtendedTestService); - assertTrue(testBean4 instanceof ExtendedTestService); + assertThat(testBean2).isNotSameAs(testBean1); + assertThat(testBean3).isNotSameAs(testBean1); + assertThat(testBean4).isNotSameAs(testBean1); + assertThat(testBean3).isNotSameAs(testBean2); + assertThat(testBean4).isNotSameAs(testBean2); + assertThat(testBean4).isNotSameAs(testBean3); + boolean condition3 = testBean1 instanceof ExtendedTestService; + assertThat(condition3).isFalse(); + boolean condition2 = testBean2 instanceof ExtendedTestService; + assertThat(condition2).isFalse(); + boolean condition1 = testBean3 instanceof ExtendedTestService; + assertThat(condition1).isFalse(); + boolean condition = testBean4 instanceof ExtendedTestService; + assertThat(condition).isTrue(); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests.java index 10c8ff66d86..8c116ad7fb6 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests.java @@ -27,9 +27,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -65,9 +63,9 @@ public class SimpleScopeTests { beanFactory.registerScope("myScope", scope); String[] scopeNames = beanFactory.getRegisteredScopeNames(); - assertEquals(1, scopeNames.length); - assertEquals("myScope", scopeNames[0]); - assertSame(scope, beanFactory.getRegisteredScope("myScope")); + assertThat(scopeNames.length).isEqualTo(1); + assertThat(scopeNames[0]).isEqualTo("myScope"); + assertThat(beanFactory.getRegisteredScope("myScope")).isSameAs(scope); new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions( qualifiedResource(SimpleScopeTests.class, "context.xml")); @@ -78,9 +76,9 @@ public class SimpleScopeTests { public void testCanGetScopedObject() { TestBean tb1 = (TestBean) beanFactory.getBean("usesScope"); TestBean tb2 = (TestBean) beanFactory.getBean("usesScope"); - assertNotSame(tb1, tb2); + assertThat(tb2).isNotSameAs(tb1); TestBean tb3 = (TestBean) beanFactory.getBean("usesScope"); - assertSame(tb3, tb1); + assertThat(tb1).isSameAs(tb3); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlMapFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlMapFactoryBeanTests.java index 6646055f2a4..1a5ffc5438b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlMapFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlMapFactoryBeanTests.java @@ -28,10 +28,9 @@ import org.springframework.core.io.AbstractResource; import org.springframework.core.io.ByteArrayResource; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Tests for {@link YamlMapFactoryBean}. @@ -48,7 +47,7 @@ public class YamlMapFactoryBeanTests { public void testSetIgnoreResourceNotFound() { this.factory.setResolutionMethod(YamlMapFactoryBean.ResolutionMethod.OVERRIDE_AND_IGNORE); this.factory.setResources(new FileSystemResource("non-exsitent-file.yml")); - assertEquals(0, this.factory.getObject().size()); + assertThat(this.factory.getObject().size()).isEqualTo(0); } @Test @@ -62,7 +61,7 @@ public class YamlMapFactoryBeanTests { @Test public void testGetObject() { this.factory.setResources(new ByteArrayResource("foo: bar".getBytes())); - assertEquals(1, this.factory.getObject().size()); + assertThat(this.factory.getObject().size()).isEqualTo(1); } @SuppressWarnings("unchecked") @@ -71,8 +70,8 @@ public class YamlMapFactoryBeanTests { this.factory.setResources(new ByteArrayResource("foo:\n bar: spam".getBytes()), new ByteArrayResource("foo:\n spam: bar".getBytes())); - assertEquals(1, this.factory.getObject().size()); - assertEquals(2, ((Map) this.factory.getObject().get("foo")).size()); + assertThat(this.factory.getObject().size()).isEqualTo(1); + assertThat(((Map) this.factory.getObject().get("foo")).size()).isEqualTo(2); } @Test @@ -89,7 +88,7 @@ public class YamlMapFactoryBeanTests { } }, new ByteArrayResource("foo:\n spam: bar".getBytes())); - assertEquals(1, this.factory.getObject().size()); + assertThat(this.factory.getObject().size()).isEqualTo(1); } @Test @@ -97,14 +96,15 @@ public class YamlMapFactoryBeanTests { this.factory.setResources(new ByteArrayResource("foo:\n ? key1.key2\n : value".getBytes())); Map map = this.factory.getObject(); - assertEquals(1, map.size()); - assertTrue(map.containsKey("foo")); + assertThat(map.size()).isEqualTo(1); + assertThat(map.containsKey("foo")).isTrue(); Object object = map.get("foo"); - assertTrue(object instanceof LinkedHashMap); + boolean condition = object instanceof LinkedHashMap; + assertThat(condition).isTrue(); @SuppressWarnings("unchecked") Map sub = (Map) object; - assertTrue(sub.containsKey("key1.key2")); - assertEquals("value", sub.get("key1.key2")); + assertThat(sub.containsKey("key1.key2")).isTrue(); + assertThat(sub.get("key1.key2")).isEqualTo("value"); } @Test @@ -112,14 +112,15 @@ public class YamlMapFactoryBeanTests { this.factory.setResources(new ByteArrayResource("foo:\n ? key1.key2\n : 3".getBytes())); Map map = this.factory.getObject(); - assertEquals(1, map.size()); - assertTrue(map.containsKey("foo")); + assertThat(map.size()).isEqualTo(1); + assertThat(map.containsKey("foo")).isTrue(); Object object = map.get("foo"); - assertTrue(object instanceof LinkedHashMap); + boolean condition = object instanceof LinkedHashMap; + assertThat(condition).isTrue(); @SuppressWarnings("unchecked") Map sub = (Map) object; - assertEquals(1, sub.size()); - assertEquals(Integer.valueOf(3), sub.get("key1.key2")); + assertThat(sub.size()).isEqualTo(1); + assertThat(sub.get("key1.key2")).isEqualTo(Integer.valueOf(3)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlProcessorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlProcessorTests.java index 9fd853bdcce..67c16af1694 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlProcessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlProcessorTests.java @@ -25,9 +25,8 @@ import org.yaml.snakeyaml.scanner.ScannerException; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Tests for {@link YamlProcessor}. @@ -44,22 +43,22 @@ public class YamlProcessorTests { public void arrayConvertedToIndexedBeanReference() { this.processor.setResources(new ByteArrayResource("foo: bar\nbar: [1,2,3]".getBytes())); this.processor.process((properties, map) -> { - assertEquals(4, properties.size()); - assertEquals("bar", properties.get("foo")); - assertEquals("bar", properties.getProperty("foo")); - assertEquals(1, properties.get("bar[0]")); - assertEquals("1", properties.getProperty("bar[0]")); - assertEquals(2, properties.get("bar[1]")); - assertEquals("2", properties.getProperty("bar[1]")); - assertEquals(3, properties.get("bar[2]")); - assertEquals("3", properties.getProperty("bar[2]")); + assertThat(properties.size()).isEqualTo(4); + assertThat(properties.get("foo")).isEqualTo("bar"); + assertThat(properties.getProperty("foo")).isEqualTo("bar"); + assertThat(properties.get("bar[0]")).isEqualTo(1); + assertThat(properties.getProperty("bar[0]")).isEqualTo("1"); + assertThat(properties.get("bar[1]")).isEqualTo(2); + assertThat(properties.getProperty("bar[1]")).isEqualTo("2"); + assertThat(properties.get("bar[2]")).isEqualTo(3); + assertThat(properties.getProperty("bar[2]")).isEqualTo("3"); }); } @Test public void testStringResource() { 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 @@ -82,8 +81,8 @@ public class YamlProcessorTests { public void mapConvertedToIndexedBeanReference() { this.processor.setResources(new ByteArrayResource("foo: bar\nbar:\n spam: bucket".getBytes())); this.processor.process((properties, map) -> { - assertEquals("bucket", properties.get("bar.spam")); - assertEquals(2, properties.size()); + assertThat(properties.get("bar.spam")).isEqualTo("bucket"); + assertThat(properties.size()).isEqualTo(2); }); } @@ -91,8 +90,8 @@ public class YamlProcessorTests { public void integerKeyBehaves() { this.processor.setResources(new ByteArrayResource("foo: bar\n1: bar".getBytes())); this.processor.process((properties, map) -> { - assertEquals("bar", properties.get("[1]")); - assertEquals(2, properties.size()); + assertThat(properties.get("[1]")).isEqualTo("bar"); + assertThat(properties.size()).isEqualTo(2); }); } @@ -100,8 +99,8 @@ public class YamlProcessorTests { public void integerDeepKeyBehaves() { this.processor.setResources(new ByteArrayResource("foo:\n 1: bar".getBytes())); this.processor.process((properties, map) -> { - assertEquals("bar", properties.get("foo[1]")); - assertEquals(1, properties.size()); + assertThat(properties.get("foo[1]")).isEqualTo("bar"); + assertThat(properties.size()).isEqualTo(1); }); } @@ -110,14 +109,15 @@ public class YamlProcessorTests { public void flattenedMapIsSameAsPropertiesButOrdered() { this.processor.setResources(new ByteArrayResource("foo: bar\nbar:\n spam: bucket".getBytes())); this.processor.process((properties, map) -> { - assertEquals("bucket", properties.get("bar.spam")); - assertEquals(2, properties.size()); + assertThat(properties.get("bar.spam")).isEqualTo("bucket"); + assertThat(properties.size()).isEqualTo(2); Map flattenedMap = processor.getFlattenedMap(map); - assertEquals("bucket", flattenedMap.get("bar.spam")); - assertEquals(2, flattenedMap.size()); - assertTrue(flattenedMap instanceof LinkedHashMap); + assertThat(flattenedMap.get("bar.spam")).isEqualTo("bucket"); + assertThat(flattenedMap.size()).isEqualTo(2); + boolean condition = flattenedMap instanceof LinkedHashMap; + assertThat(condition).isTrue(); Map bar = (Map) map.get("bar"); - assertEquals("bucket", bar.get("spam")); + assertThat(bar.get("spam")).isEqualTo("bucket"); }); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java index c816bcf7eed..06c75b99090 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java @@ -26,8 +26,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** @@ -56,10 +55,10 @@ public class CustomProblemReporterTests { @Test public void testErrorsAreCollated() { 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"); - assertNotNull(bean); + assertThat(bean).isNotNull(); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/NullSourceExtractorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/NullSourceExtractorTests.java index 02b6bbaed18..b679643a861 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/NullSourceExtractorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/NullSourceExtractorTests.java @@ -18,7 +18,7 @@ package org.springframework.beans.factory.parsing; import org.junit.Test; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rick Evans @@ -30,13 +30,13 @@ public class NullSourceExtractorTests { public void testPassThroughContract() throws Exception { Object source = new Object(); 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 public void testPassThroughContractEvenWithNull() throws Exception { 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(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/ParseStateTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/ParseStateTests.java index b753b7226f2..2cee2488ec4 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/ParseStateTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/ParseStateTests.java @@ -18,8 +18,7 @@ package org.springframework.beans.factory.parsing; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -34,9 +33,9 @@ public class ParseStateTests { ParseState parseState = new ParseState(); parseState.push(entry); - assertEquals("Incorrect peek value.", entry, parseState.peek()); + assertThat(parseState.peek()).as("Incorrect peek value.").isEqualTo(entry); parseState.pop(); - assertNull("Should get null on peek()", parseState.peek()); + assertThat(parseState.peek()).as("Should get null on peek()").isNull(); } @Test @@ -47,16 +46,16 @@ public class ParseStateTests { ParseState parseState = new ParseState(); parseState.push(one); - assertEquals(one, parseState.peek()); + assertThat(parseState.peek()).isEqualTo(one); parseState.push(two); - assertEquals(two, parseState.peek()); + assertThat(parseState.peek()).isEqualTo(two); parseState.push(three); - assertEquals(three, parseState.peek()); + assertThat(parseState.peek()).isEqualTo(three); parseState.pop(); - assertEquals(two, parseState.peek()); + assertThat(parseState.peek()).isEqualTo(two); parseState.pop(); - assertEquals(one, parseState.peek()); + assertThat(parseState.peek()).isEqualTo(one); } @Test @@ -68,7 +67,7 @@ public class ParseStateTests { ParseState snapshot = original.snapshot(); 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); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/PassThroughSourceExtractorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/PassThroughSourceExtractorTests.java index a0d687c87d9..abc4e0dd5c9 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/PassThroughSourceExtractorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/PassThroughSourceExtractorTests.java @@ -18,8 +18,7 @@ package org.springframework.beans.factory.parsing; import org.junit.Test; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link PassThroughSourceExtractor}. @@ -33,15 +32,15 @@ public class PassThroughSourceExtractorTests { public void testPassThroughContract() throws Exception { Object source = new Object(); Object extractedSource = new PassThroughSourceExtractor().extractSource(source, null); - assertSame("The contract of PassThroughSourceExtractor states that the supplied " + - "source object *must* be returned as-is", source, extractedSource); + assertThat(extractedSource).as("The contract of PassThroughSourceExtractor states that the supplied " + + "source object *must* be returned as-is").isSameAs(source); } @Test public void testPassThroughContractEvenWithNull() throws Exception { Object extractedSource = new PassThroughSourceExtractor().extractSource(null, null); - assertNull("The contract of PassThroughSourceExtractor states that the supplied " + - "source object *must* be returned as-is (even if null)", extractedSource); + assertThat(extractedSource).as("The contract of PassThroughSourceExtractor states that the supplied " + + "source object *must* be returned as-is (even if null)").isNull(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/serviceloader/ServiceLoaderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/serviceloader/ServiceLoaderTests.java index 73fc2995f06..213d225e2eb 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/serviceloader/ServiceLoaderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/serviceloader/ServiceLoaderTests.java @@ -25,7 +25,7 @@ import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; 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; /** @@ -43,7 +43,8 @@ public class ServiceLoaderTests { bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName()); bf.registerBeanDefinition("service", bd); ServiceLoader serviceLoader = (ServiceLoader) bf.getBean("service"); - assertTrue(serviceLoader.iterator().next() instanceof DocumentBuilderFactory); + boolean condition = serviceLoader.iterator().next() instanceof DocumentBuilderFactory; + assertThat(condition).isTrue(); } @Test @@ -54,7 +55,8 @@ public class ServiceLoaderTests { RootBeanDefinition bd = new RootBeanDefinition(ServiceFactoryBean.class); bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName()); bf.registerBeanDefinition("service", bd); - assertTrue(bf.getBean("service") instanceof DocumentBuilderFactory); + boolean condition = bf.getBean("service") instanceof DocumentBuilderFactory; + assertThat(condition).isTrue(); } @Test @@ -66,7 +68,8 @@ public class ServiceLoaderTests { bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName()); bf.registerBeanDefinition("service", bd); List serviceList = (List) bf.getBean("service"); - assertTrue(serviceList.get(0) instanceof DocumentBuilderFactory); + boolean condition = serviceList.get(0) instanceof DocumentBuilderFactory; + assertThat(condition).isTrue(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/AutowireUtilsTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/AutowireUtilsTests.java index e7f5f6e42d2..9d8a67b71b1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/AutowireUtilsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/AutowireUtilsTests.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link AutowireUtils}. @@ -38,45 +38,36 @@ public class AutowireUtilsTests { @Test public void genericMethodReturnTypes() { Method notParameterized = ReflectionUtils.findMethod(MyTypeWithMethods.class, "notParameterized"); - assertEquals(String.class, - AutowireUtils.resolveReturnTypeForFactoryMethod(notParameterized, new Object[0], getClass().getClassLoader())); + Object actual = AutowireUtils.resolveReturnTypeForFactoryMethod(notParameterized, new Object[0], getClass().getClassLoader()); + assertThat(actual).isEqualTo(String.class); Method notParameterizedWithArguments = ReflectionUtils.findMethod(MyTypeWithMethods.class, "notParameterizedWithArguments", Integer.class, Boolean.class); - assertEquals(String.class, - AutowireUtils.resolveReturnTypeForFactoryMethod(notParameterizedWithArguments, new Object[] {99, true}, getClass().getClassLoader())); + assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(notParameterizedWithArguments, new Object[]{99, true}, getClass().getClassLoader())).isEqualTo(String.class); Method createProxy = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createProxy", Object.class); - assertEquals(String.class, - AutowireUtils.resolveReturnTypeForFactoryMethod(createProxy, new Object[] {"foo"}, getClass().getClassLoader())); + assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createProxy, new Object[]{"foo"}, getClass().getClassLoader())).isEqualTo(String.class); Method createNamedProxyWithDifferentTypes = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createNamedProxy", String.class, Object.class); - assertEquals(Long.class, - AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedProxyWithDifferentTypes, new Object[] {"enigma", 99L}, getClass().getClassLoader())); + assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedProxyWithDifferentTypes, new Object[]{"enigma", 99L}, getClass().getClassLoader())).isEqualTo(Long.class); Method createNamedProxyWithDuplicateTypes = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createNamedProxy", String.class, Object.class); - assertEquals(String.class, - AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedProxyWithDuplicateTypes, new Object[] {"enigma", "foo"}, getClass().getClassLoader())); + assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedProxyWithDuplicateTypes, new Object[]{"enigma", "foo"}, getClass().getClassLoader())).isEqualTo(String.class); Method createMock = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createMock", Class.class); - assertEquals(Runnable.class, - AutowireUtils.resolveReturnTypeForFactoryMethod(createMock, new Object[] {Runnable.class}, getClass().getClassLoader())); - assertEquals(Runnable.class, - AutowireUtils.resolveReturnTypeForFactoryMethod(createMock, new Object[] {Runnable.class.getName()}, getClass().getClassLoader())); + assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createMock, new Object[]{Runnable.class}, getClass().getClassLoader())).isEqualTo(Runnable.class); + assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createMock, new Object[]{Runnable.class.getName()}, getClass().getClassLoader())).isEqualTo(Runnable.class); Method createNamedMock = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createNamedMock", String.class, Class.class); - assertEquals(Runnable.class, - AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedMock, new Object[] {"foo", Runnable.class}, getClass().getClassLoader())); + assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createNamedMock, new Object[]{"foo", Runnable.class}, getClass().getClassLoader())).isEqualTo(Runnable.class); Method createVMock = ReflectionUtils.findMethod(MyTypeWithMethods.class, "createVMock", Object.class, Class.class); - assertEquals(Runnable.class, - AutowireUtils.resolveReturnTypeForFactoryMethod(createVMock, new Object[] {"foo", Runnable.class}, getClass().getClassLoader())); + assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(createVMock, new Object[]{"foo", Runnable.class}, getClass().getClassLoader())).isEqualTo(Runnable.class); // Ideally we would expect String.class instead of Object.class, but // resolveReturnTypeForFactoryMethod() does not currently support this form of // look-up. Method extractValueFrom = ReflectionUtils.findMethod(MyTypeWithMethods.class, "extractValueFrom", MyInterfaceType.class); - assertEquals(Object.class, - AutowireUtils.resolveReturnTypeForFactoryMethod(extractValueFrom, new Object[] {new MySimpleInterfaceType()}, getClass().getClassLoader())); + assertThat(AutowireUtils.resolveReturnTypeForFactoryMethod(extractValueFrom, new Object[]{new MySimpleInterfaceType()}, getClass().getClassLoader())).isEqualTo(Object.class); // Ideally we would expect Boolean.class instead of Object.class, but this // information is not available at run-time due to type erasure. @@ -84,7 +75,7 @@ public class AutowireUtilsTests { map.put(0, false); map.put(1, true); 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); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java index d3bb1206a8c..c0642fc1f6c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java @@ -23,9 +23,7 @@ import org.junit.Test; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -44,36 +42,36 @@ public class BeanDefinitionBuilderTests { } RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition(); - assertFalse(rbd.isSingleton()); - assertEquals(TestBean.class, rbd.getBeanClass()); - assertTrue("Depends on was added", Arrays.equals(dependsOn, rbd.getDependsOn())); - assertTrue(rbd.getPropertyValues().contains("age")); + assertThat(rbd.isSingleton()).isFalse(); + assertThat(rbd.getBeanClass()).isEqualTo(TestBean.class); + assertThat(Arrays.equals(dependsOn, rbd.getDependsOn())).as("Depends on was added").isTrue(); + assertThat(rbd.getPropertyValues().contains("age")).isTrue(); } @Test public void beanClassWithFactoryMethod() { BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class, "create"); RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition(); - assertTrue(rbd.hasBeanClass()); - assertEquals(TestBean.class, rbd.getBeanClass()); - assertEquals("create", rbd.getFactoryMethodName()); + assertThat(rbd.hasBeanClass()).isTrue(); + assertThat(rbd.getBeanClass()).isEqualTo(TestBean.class); + assertThat(rbd.getFactoryMethodName()).isEqualTo("create"); } @Test public void beanClassName() { BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class.getName()); RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition(); - assertFalse(rbd.hasBeanClass()); - assertEquals(TestBean.class.getName(), rbd.getBeanClassName()); + assertThat(rbd.hasBeanClass()).isFalse(); + assertThat(rbd.getBeanClassName()).isEqualTo(TestBean.class.getName()); } @Test public void beanClassNameWithFactoryMethod() { BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class.getName(), "create"); RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition(); - assertFalse(rbd.hasBeanClass()); - assertEquals(TestBean.class.getName(), rbd.getBeanClassName()); - assertEquals("create", rbd.getFactoryMethodName()); + assertThat(rbd.hasBeanClass()).isFalse(); + assertThat(rbd.getBeanClassName()).isEqualTo(TestBean.class.getName()); + assertThat(rbd.getFactoryMethodName()).isEqualTo("create"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java index 522e6808c56..d8bd862af76 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java @@ -21,8 +21,7 @@ import org.junit.Test; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -36,14 +35,16 @@ public class BeanDefinitionTests { bd.setLazyInit(true); bd.setScope("request"); RootBeanDefinition otherBd = new RootBeanDefinition(TestBean.class); - assertTrue(!bd.equals(otherBd)); - assertTrue(!otherBd.equals(bd)); + boolean condition1 = !bd.equals(otherBd); + assertThat(condition1).isTrue(); + boolean condition = !otherBd.equals(bd); + assertThat(condition).isTrue(); otherBd.setAbstract(true); otherBd.setLazyInit(true); otherBd.setScope("request"); - assertTrue(bd.equals(otherBd)); - assertTrue(otherBd.equals(bd)); - assertTrue(bd.hashCode() == otherBd.hashCode()); + assertThat(bd.equals(otherBd)).isTrue(); + assertThat(otherBd.equals(bd)).isTrue(); + assertThat(bd.hashCode() == otherBd.hashCode()).isTrue(); } @Test @@ -53,15 +54,19 @@ public class BeanDefinitionTests { bd.getPropertyValues().add("age", "99"); RootBeanDefinition otherBd = new RootBeanDefinition(TestBean.class); otherBd.getPropertyValues().add("name", "myName"); - assertTrue(!bd.equals(otherBd)); - assertTrue(!otherBd.equals(bd)); + boolean condition3 = !bd.equals(otherBd); + assertThat(condition3).isTrue(); + boolean condition2 = !otherBd.equals(bd); + assertThat(condition2).isTrue(); otherBd.getPropertyValues().add("age", "11"); - assertTrue(!bd.equals(otherBd)); - assertTrue(!otherBd.equals(bd)); + boolean condition1 = !bd.equals(otherBd); + assertThat(condition1).isTrue(); + boolean condition = !otherBd.equals(bd); + assertThat(condition).isTrue(); otherBd.getPropertyValues().add("age", "99"); - assertTrue(bd.equals(otherBd)); - assertTrue(otherBd.equals(bd)); - assertTrue(bd.hashCode() == otherBd.hashCode()); + assertThat(bd.equals(otherBd)).isTrue(); + assertThat(otherBd.equals(bd)).isTrue(); + assertThat(bd.hashCode() == otherBd.hashCode()).isTrue(); } @Test @@ -71,15 +76,19 @@ public class BeanDefinitionTests { bd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5)); RootBeanDefinition otherBd = new RootBeanDefinition(TestBean.class); otherBd.getConstructorArgumentValues().addGenericArgumentValue("test"); - assertTrue(!bd.equals(otherBd)); - assertTrue(!otherBd.equals(bd)); + boolean condition3 = !bd.equals(otherBd); + assertThat(condition3).isTrue(); + boolean condition2 = !otherBd.equals(bd); + assertThat(condition2).isTrue(); otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(9)); - assertTrue(!bd.equals(otherBd)); - assertTrue(!otherBd.equals(bd)); + boolean condition1 = !bd.equals(otherBd); + assertThat(condition1).isTrue(); + boolean condition = !otherBd.equals(bd); + assertThat(condition).isTrue(); otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5)); - assertTrue(bd.equals(otherBd)); - assertTrue(otherBd.equals(bd)); - assertTrue(bd.hashCode() == otherBd.hashCode()); + assertThat(bd.equals(otherBd)).isTrue(); + assertThat(otherBd.equals(bd)).isTrue(); + assertThat(bd.hashCode() == otherBd.hashCode()).isTrue(); } @Test @@ -90,15 +99,19 @@ public class BeanDefinitionTests { RootBeanDefinition otherBd = new RootBeanDefinition(TestBean.class); otherBd.getConstructorArgumentValues().addGenericArgumentValue("test", "int"); otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5)); - assertTrue(!bd.equals(otherBd)); - assertTrue(!otherBd.equals(bd)); + boolean condition3 = !bd.equals(otherBd); + assertThat(condition3).isTrue(); + boolean condition2 = !otherBd.equals(bd); + assertThat(condition2).isTrue(); otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5), "int"); - assertTrue(!bd.equals(otherBd)); - assertTrue(!otherBd.equals(bd)); + boolean condition1 = !bd.equals(otherBd); + assertThat(condition1).isTrue(); + boolean condition = !otherBd.equals(bd); + assertThat(condition).isTrue(); otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5), "long"); - assertTrue(bd.equals(otherBd)); - assertTrue(otherBd.equals(bd)); - assertTrue(bd.hashCode() == otherBd.hashCode()); + assertThat(bd.equals(otherBd)).isTrue(); + assertThat(otherBd.equals(bd)).isTrue(); + assertThat(bd.hashCode() == otherBd.hashCode()).isTrue(); } @Test @@ -109,15 +122,17 @@ public class BeanDefinitionTests { bd.setScope("request"); BeanDefinitionHolder holder = new BeanDefinitionHolder(bd, "bd"); RootBeanDefinition otherBd = new RootBeanDefinition(TestBean.class); - assertTrue(!bd.equals(otherBd)); - assertTrue(!otherBd.equals(bd)); + boolean condition1 = !bd.equals(otherBd); + assertThat(condition1).isTrue(); + boolean condition = !otherBd.equals(bd); + assertThat(condition).isTrue(); otherBd.setAbstract(true); otherBd.setLazyInit(true); otherBd.setScope("request"); BeanDefinitionHolder otherHolder = new BeanDefinitionHolder(bd, "bd"); - assertTrue(holder.equals(otherHolder)); - assertTrue(otherHolder.equals(holder)); - assertTrue(holder.hashCode() == otherHolder.hashCode()); + assertThat(holder.equals(otherHolder)).isTrue(); + assertThat(otherHolder.equals(holder)).isTrue(); + assertThat(holder.hashCode() == otherHolder.hashCode()).isTrue(); } @Test @@ -134,13 +149,13 @@ public class BeanDefinitionTests { RootBeanDefinition mergedBd = new RootBeanDefinition(bd); mergedBd.overrideFrom(childBd); - assertEquals(2, mergedBd.getConstructorArgumentValues().getArgumentCount()); - assertEquals(2, mergedBd.getPropertyValues().size()); - assertEquals(bd, mergedBd); + assertThat(mergedBd.getConstructorArgumentValues().getArgumentCount()).isEqualTo(2); + assertThat(mergedBd.getPropertyValues().size()).isEqualTo(2); + assertThat(mergedBd).isEqualTo(bd); mergedBd.getConstructorArgumentValues().getArgumentValue(1, null).setValue(new Integer(9)); - assertEquals(new Integer(5), bd.getConstructorArgumentValues().getArgumentValue(1, null).getValue()); - assertEquals(getClass(), bd.getQualifiedElement()); + assertThat(bd.getConstructorArgumentValues().getArgumentValue(1, null).getValue()).isEqualTo(new Integer(5)); + assertThat(bd.getQualifiedElement()).isEqualTo(getClass()); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java index dce9655da4b..ab16854a6ca 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java @@ -56,13 +56,8 @@ import org.springframework.tests.sample.beans.GenericIntegerBean; import org.springframework.tests.sample.beans.GenericSetOfIntegerBean; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -85,8 +80,8 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertTrue(gb.getIntegerSet().contains(new Integer(4))); - assertTrue(gb.getIntegerSet().contains(new Integer(5))); + assertThat(gb.getIntegerSet().contains(new Integer(4))).isTrue(); + assertThat(gb.getIntegerSet().contains(new Integer(5))).isTrue(); } @Test @@ -102,8 +97,8 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0)); - assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1)); + assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080")); + assertThat(gb.getResourceList().get(1)).isEqualTo(new UrlResource("http://localhost:9090")); } @Test @@ -117,8 +112,8 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericIntegerBean gb = (GenericIntegerBean) bf.getBean("genericBean"); - assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0)); - assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1)); + assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080")); + assertThat(gb.getResourceList().get(1)).isEqualTo(new UrlResource("http://localhost:9090")); } @Test @@ -148,7 +143,7 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertNull(gb.getResourceList()); + assertThat(gb.getResourceList()).isNull(); } @Test @@ -164,8 +159,8 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); - assertEquals(new Integer(7), gb.getShortMap().get(new Short("6"))); + assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5)); + assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(new Integer(7)); } @Test @@ -175,11 +170,11 @@ public class BeanFactoryGenericsTests { new ClassPathResource("genericBeanTests.xml", getClass())); GenericBean gb = (GenericBean) bf.getBean("listOfArrays"); - assertEquals(1, gb.getListOfArrays().size()); + assertThat(gb.getListOfArrays().size()).isEqualTo(1); String[] array = gb.getListOfArrays().get(0); - assertEquals(2, array.length); - assertEquals("value1", array[0]); - assertEquals("value2", array[1]); + assertThat(array.length).isEqualTo(2); + assertThat(array[0]).isEqualTo("value1"); + assertThat(array[1]).isEqualTo("value2"); } @@ -196,8 +191,8 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertTrue(gb.getIntegerSet().contains(new Integer(4))); - assertTrue(gb.getIntegerSet().contains(new Integer(5))); + assertThat(gb.getIntegerSet().contains(new Integer(4))).isTrue(); + assertThat(gb.getIntegerSet().contains(new Integer(5))).isTrue(); } @Test @@ -211,8 +206,8 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertTrue(gb.getIntegerSet().contains(new Integer(4))); - assertTrue(gb.getIntegerSet().contains(new Integer(5))); + assertThat(gb.getIntegerSet().contains(new Integer(4))).isTrue(); + assertThat(gb.getIntegerSet().contains(new Integer(5))).isTrue(); } @Test @@ -224,7 +219,7 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertNull(gb.getIntegerSet()); + assertThat(gb.getIntegerSet()).isNull(); } @Test @@ -244,10 +239,10 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertTrue(gb.getIntegerSet().contains(new Integer(4))); - assertTrue(gb.getIntegerSet().contains(new Integer(5))); - assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0)); - assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1)); + assertThat(gb.getIntegerSet().contains(new Integer(4))).isTrue(); + assertThat(gb.getIntegerSet().contains(new Integer(5))).isTrue(); + assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080")); + assertThat(gb.getResourceList().get(1)).isEqualTo(new UrlResource("http://localhost:9090")); } @Test @@ -263,10 +258,10 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertTrue(gb.getIntegerSet().contains(new Integer(4))); - assertTrue(gb.getIntegerSet().contains(new Integer(5))); - assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0)); - assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1)); + assertThat(gb.getIntegerSet().contains(new Integer(4))).isTrue(); + assertThat(gb.getIntegerSet().contains(new Integer(5))).isTrue(); + assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080")); + assertThat(gb.getResourceList().get(1)).isEqualTo(new UrlResource("http://localhost:9090")); } @Test @@ -280,8 +275,8 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertNull(gb.getIntegerSet()); - assertNull(gb.getResourceList()); + assertThat(gb.getIntegerSet()).isNull(); + assertThat(gb.getResourceList()).isNull(); } @Test @@ -301,10 +296,10 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertTrue(gb.getIntegerSet().contains(new Integer(4))); - assertTrue(gb.getIntegerSet().contains(new Integer(5))); - assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); - assertEquals(new Integer(7), gb.getShortMap().get(new Short("6"))); + assertThat(gb.getIntegerSet().contains(new Integer(4))).isTrue(); + assertThat(gb.getIntegerSet().contains(new Integer(5))).isTrue(); + assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5)); + assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(new Integer(7)); } @Test @@ -321,9 +316,9 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); - assertEquals(new Integer(7), gb.getShortMap().get(new Short("6"))); - assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0)); + assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5)); + assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(new Integer(7)); + assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080")); } @Test @@ -343,13 +338,13 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertNotSame(gb.getPlainMap(), gb.getShortMap()); - assertEquals(2, gb.getPlainMap().size()); - assertEquals("0", gb.getPlainMap().get("1")); - assertEquals("3", gb.getPlainMap().get("2")); - assertEquals(2, gb.getShortMap().size()); - assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); - assertEquals(new Integer(7), gb.getShortMap().get(new Short("6"))); + assertThat(gb.getShortMap()).isNotSameAs(gb.getPlainMap()); + assertThat(gb.getPlainMap().size()).isEqualTo(2); + assertThat(gb.getPlainMap().get("1")).isEqualTo("0"); + assertThat(gb.getPlainMap().get("2")).isEqualTo("3"); + assertThat(gb.getShortMap().size()).isEqualTo(2); + assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5)); + assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(new Integer(7)); } @Test @@ -366,13 +361,13 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertNotSame(gb.getPlainMap(), gb.getShortMap()); - assertEquals(2, gb.getPlainMap().size()); - assertEquals("0", gb.getPlainMap().get("1")); - assertEquals("3", gb.getPlainMap().get("2")); - assertEquals(2, gb.getShortMap().size()); - assertEquals(new Integer(0), gb.getShortMap().get(new Short("1"))); - assertEquals(new Integer(3), gb.getShortMap().get(new Short("2"))); + assertThat(gb.getShortMap()).isNotSameAs(gb.getPlainMap()); + assertThat(gb.getPlainMap().size()).isEqualTo(2); + assertThat(gb.getPlainMap().get("1")).isEqualTo("0"); + assertThat(gb.getPlainMap().get("2")).isEqualTo("3"); + assertThat(gb.getShortMap().size()).isEqualTo(2); + assertThat(gb.getShortMap().get(new Short("1"))).isEqualTo(new Integer(0)); + assertThat(gb.getShortMap().get(new Short("2"))).isEqualTo(new Integer(3)); } @Test @@ -389,10 +384,10 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertSame(gb.getPlainMap(), gb.getShortMap()); - assertEquals(2, gb.getShortMap().size()); - assertEquals(new Integer(0), gb.getShortMap().get(new Short("1"))); - assertEquals(new Integer(3), gb.getShortMap().get(new Short("2"))); + assertThat(gb.getShortMap()).isSameAs(gb.getPlainMap()); + assertThat(gb.getShortMap().size()).isEqualTo(2); + assertThat(gb.getShortMap().get(new Short("1"))).isEqualTo(new Integer(0)); + assertThat(gb.getShortMap().get(new Short("2"))).isEqualTo(new Integer(3)); } @Test @@ -408,8 +403,8 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertEquals("5", gb.getLongMap().get(new Long("4"))); - assertEquals("7", gb.getLongMap().get(new Long("6"))); + assertThat(gb.getLongMap().get(new Long("4"))).isEqualTo("5"); + assertThat(gb.getLongMap().get(new Long("6"))).isEqualTo("7"); } @Test @@ -436,8 +431,10 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet); - assertTrue(gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList); + boolean condition1 = gb.getCollectionMap().get(new Integer(1)) instanceof HashSet; + assertThat(condition1).isTrue(); + boolean condition = gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList; + assertThat(condition).isTrue(); } @@ -455,8 +452,8 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertTrue(gb.getIntegerSet().contains(new Integer(4))); - assertTrue(gb.getIntegerSet().contains(new Integer(5))); + assertThat(gb.getIntegerSet().contains(new Integer(4))).isTrue(); + assertThat(gb.getIntegerSet().contains(new Integer(5))).isTrue(); } @Test @@ -477,10 +474,10 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertTrue(gb.getIntegerSet().contains(new Integer(4))); - assertTrue(gb.getIntegerSet().contains(new Integer(5))); - assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0)); - assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1)); + assertThat(gb.getIntegerSet().contains(new Integer(4))).isTrue(); + assertThat(gb.getIntegerSet().contains(new Integer(5))).isTrue(); + assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080")); + assertThat(gb.getResourceList().get(1)).isEqualTo(new UrlResource("http://localhost:9090")); } @Test @@ -501,10 +498,10 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertTrue(gb.getIntegerSet().contains(new Integer(4))); - assertTrue(gb.getIntegerSet().contains(new Integer(5))); - assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); - assertEquals(new Integer(7), gb.getShortMap().get(new Short("6"))); + assertThat(gb.getIntegerSet().contains(new Integer(4))).isTrue(); + assertThat(gb.getIntegerSet().contains(new Integer(5))).isTrue(); + assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5)); + assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(new Integer(7)); } @Test @@ -522,9 +519,9 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); - assertEquals(new Integer(7), gb.getShortMap().get(new Short("6"))); - assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0)); + assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5)); + assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(new Integer(7)); + assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080")); } @Test @@ -545,10 +542,10 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertEquals("0", gb.getPlainMap().get("1")); - assertEquals("3", gb.getPlainMap().get("2")); - assertEquals(new Integer(5), gb.getShortMap().get(new Short("4"))); - assertEquals(new Integer(7), gb.getShortMap().get(new Short("6"))); + assertThat(gb.getPlainMap().get("1")).isEqualTo("0"); + assertThat(gb.getPlainMap().get("2")).isEqualTo("3"); + assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(new Integer(5)); + assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(new Integer(7)); } @Test @@ -565,8 +562,8 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertEquals("5", gb.getLongMap().get(new Long("4"))); - assertEquals("7", gb.getLongMap().get(new Long("6"))); + assertThat(gb.getLongMap().get(new Long("4"))).isEqualTo("5"); + assertThat(gb.getLongMap().get(new Long("6"))).isEqualTo("7"); } @Test @@ -594,8 +591,10 @@ public class BeanFactoryGenericsTests { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet); - assertTrue(gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList); + boolean condition1 = gb.getCollectionMap().get(new Integer(1)) instanceof HashSet; + assertThat(condition1).isTrue(); + boolean condition = gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList; + assertThat(condition).isTrue(); } @Test @@ -604,8 +603,8 @@ public class BeanFactoryGenericsTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); List list = (List) bf.getBean("list"); - assertEquals(1, list.size()); - assertEquals(new URL("http://localhost:8080"), list.get(0)); + assertThat(list.size()).isEqualTo(1); + assertThat(list.get(0)).isEqualTo(new URL("http://localhost:8080")); } @Test @@ -614,8 +613,8 @@ public class BeanFactoryGenericsTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); Set set = (Set) bf.getBean("set"); - assertEquals(1, set.size()); - assertEquals(new URL("http://localhost:8080"), set.iterator().next()); + assertThat(set.size()).isEqualTo(1); + assertThat(set.iterator().next()).isEqualTo(new URL("http://localhost:8080")); } @Test @@ -624,9 +623,9 @@ public class BeanFactoryGenericsTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); Map map = (Map) bf.getBean("map"); - assertEquals(1, map.size()); - assertEquals(new Integer(10), map.keySet().iterator().next()); - assertEquals(new URL("http://localhost:8080"), map.values().iterator().next()); + assertThat(map.size()).isEqualTo(1); + assertThat(map.keySet().iterator().next()).isEqualTo(new Integer(10)); + assertThat(map.values().iterator().next()).isEqualTo(new URL("http://localhost:8080")); } @Test @@ -635,9 +634,9 @@ public class BeanFactoryGenericsTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); GenericIntegerBean gb = (GenericIntegerBean) bf.getBean("integerBean"); - assertEquals(new Integer(10), gb.getGenericProperty()); - assertEquals(new Integer(20), gb.getGenericListProperty().get(0)); - assertEquals(new Integer(30), gb.getGenericListProperty().get(1)); + assertThat(gb.getGenericProperty()).isEqualTo(new Integer(10)); + assertThat(gb.getGenericListProperty().get(0)).isEqualTo(new Integer(20)); + assertThat(gb.getGenericListProperty().get(1)).isEqualTo(new Integer(30)); } @Test @@ -646,9 +645,9 @@ public class BeanFactoryGenericsTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); GenericSetOfIntegerBean gb = (GenericSetOfIntegerBean) bf.getBean("setOfIntegerBean"); - assertEquals(new Integer(10), gb.getGenericProperty().iterator().next()); - assertEquals(new Integer(20), gb.getGenericListProperty().get(0).iterator().next()); - assertEquals(new Integer(30), gb.getGenericListProperty().get(1).iterator().next()); + assertThat(gb.getGenericProperty().iterator().next()).isEqualTo(new Integer(10)); + assertThat(gb.getGenericListProperty().get(0).iterator().next()).isEqualTo(new Integer(20)); + assertThat(gb.getGenericListProperty().get(1).iterator().next()).isEqualTo(new Integer(30)); } @Test @@ -659,8 +658,8 @@ public class BeanFactoryGenericsTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); UrlSet us = (UrlSet) bf.getBean("setBean"); - assertEquals(1, us.size()); - assertEquals(new URL("https://www.springframework.org"), us.iterator().next()); + assertThat(us.size()).isEqualTo(1); + assertThat(us.iterator().next()).isEqualTo(new URL("https://www.springframework.org")); } /** @@ -682,10 +681,10 @@ public class BeanFactoryGenericsTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerBeanDefinition("mock", rbd); - assertEquals(Runnable.class, bf.getType("mock")); - assertEquals(Runnable.class, bf.getType("mock")); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertEquals(1, beans.size()); + assertThat(beans.size()).isEqualTo(1); } /** @@ -712,12 +711,12 @@ public class BeanFactoryGenericsTests { rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class); bf.registerBeanDefinition("mock", rbd); - assertTrue(bf.isTypeMatch("mock", Runnable.class)); - assertTrue(bf.isTypeMatch("mock", Runnable.class)); - assertEquals(Runnable.class, bf.getType("mock")); - assertEquals(Runnable.class, bf.getType("mock")); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isTrue(); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isTrue(); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertEquals(1, beans.size()); + assertThat(beans.size()).isEqualTo(1); } @Test @@ -733,12 +732,12 @@ public class BeanFactoryGenericsTests { rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class.getName()); bf.registerBeanDefinition("mock", rbd); - assertTrue(bf.isTypeMatch("mock", Runnable.class)); - assertTrue(bf.isTypeMatch("mock", Runnable.class)); - assertEquals(Runnable.class, bf.getType("mock")); - assertEquals(Runnable.class, bf.getType("mock")); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isTrue(); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isTrue(); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertEquals(1, beans.size()); + assertThat(beans.size()).isEqualTo(1); } @Test @@ -752,12 +751,12 @@ public class BeanFactoryGenericsTests { rbd.getConstructorArgumentValues().addGenericArgumentValue(new TypedStringValue(Runnable.class.getName())); bf.registerBeanDefinition("mock", rbd); - assertTrue(bf.isTypeMatch("mock", Runnable.class)); - assertTrue(bf.isTypeMatch("mock", Runnable.class)); - assertEquals(Runnable.class, bf.getType("mock")); - assertEquals(Runnable.class, bf.getType("mock")); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isTrue(); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isTrue(); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertEquals(1, beans.size()); + assertThat(beans.size()).isEqualTo(1); } @Test @@ -773,12 +772,12 @@ public class BeanFactoryGenericsTests { rbd.getConstructorArgumentValues().addGenericArgumentValue("x"); bf.registerBeanDefinition("mock", rbd); - assertFalse(bf.isTypeMatch("mock", Runnable.class)); - assertFalse(bf.isTypeMatch("mock", Runnable.class)); - assertNull(bf.getType("mock")); - assertNull(bf.getType("mock")); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isFalse(); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isFalse(); + assertThat(bf.getType("mock")).isNull(); + assertThat(bf.getType("mock")).isNull(); Map beans = bf.getBeansOfType(Runnable.class); - assertEquals(0, beans.size()); + assertThat(beans.size()).isEqualTo(0); } @Test @@ -794,12 +793,12 @@ public class BeanFactoryGenericsTests { rbd.getConstructorArgumentValues().addIndexedArgumentValue(0, Runnable.class); bf.registerBeanDefinition("mock", rbd); - assertTrue(bf.isTypeMatch("mock", Runnable.class)); - assertTrue(bf.isTypeMatch("mock", Runnable.class)); - assertEquals(Runnable.class, bf.getType("mock")); - assertEquals(Runnable.class, bf.getType("mock")); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isTrue(); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isTrue(); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertEquals(1, beans.size()); + assertThat(beans.size()).isEqualTo(1); } @Test // SPR-16720 @@ -816,12 +815,12 @@ public class BeanFactoryGenericsTests { rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class); bf.registerBeanDefinition("mock", rbd); - assertTrue(bf.isTypeMatch("mock", Runnable.class)); - assertTrue(bf.isTypeMatch("mock", Runnable.class)); - assertEquals(Runnable.class, bf.getType("mock")); - assertEquals(Runnable.class, bf.getType("mock")); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isTrue(); + assertThat(bf.isTypeMatch("mock", Runnable.class)).isTrue(); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); + assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertEquals(1, beans.size()); + assertThat(beans.size()).isEqualTo(1); } @Test @@ -835,17 +834,17 @@ public class BeanFactoryGenericsTests { new RootBeanDefinition(NumberBean.class, RootBeanDefinition.AUTOWIRE_CONSTRUCTOR, false)); NumberBean nb = bf.getBean(NumberBean.class); - assertSame(bf.getBean("doubleStore"), nb.getDoubleStore()); - assertSame(bf.getBean("floatStore"), nb.getFloatStore()); + assertThat(nb.getDoubleStore()).isSameAs(bf.getBean("doubleStore")); + assertThat(nb.getFloatStore()).isSameAs(bf.getBean("floatStore")); String[] numberStoreNames = bf.getBeanNamesForType(ResolvableType.forClass(NumberStore.class)); String[] doubleStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Double.class)); String[] floatStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Float.class)); - assertEquals(2, numberStoreNames.length); - assertEquals("doubleStore", numberStoreNames[0]); - assertEquals("floatStore", numberStoreNames[1]); - assertEquals(0, doubleStoreNames.length); - assertEquals(0, floatStoreNames.length); + assertThat(numberStoreNames.length).isEqualTo(2); + assertThat(numberStoreNames[0]).isEqualTo("doubleStore"); + assertThat(numberStoreNames[1]).isEqualTo("floatStore"); + assertThat(doubleStoreNames.length).isEqualTo(0); + assertThat(floatStoreNames.length).isEqualTo(0); } @Test @@ -864,80 +863,80 @@ public class BeanFactoryGenericsTests { new RootBeanDefinition(NumberBean.class, RootBeanDefinition.AUTOWIRE_CONSTRUCTOR, false)); NumberBean nb = bf.getBean(NumberBean.class); - assertSame(bf.getBean("store1"), nb.getDoubleStore()); - assertSame(bf.getBean("store2"), nb.getFloatStore()); + assertThat(nb.getDoubleStore()).isSameAs(bf.getBean("store1")); + assertThat(nb.getFloatStore()).isSameAs(bf.getBean("store2")); String[] numberStoreNames = bf.getBeanNamesForType(ResolvableType.forClass(NumberStore.class)); String[] doubleStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Double.class)); String[] floatStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Float.class)); - assertEquals(2, numberStoreNames.length); - assertEquals("store1", numberStoreNames[0]); - assertEquals("store2", numberStoreNames[1]); - assertEquals(1, doubleStoreNames.length); - assertEquals("store1", doubleStoreNames[0]); - assertEquals(1, floatStoreNames.length); - assertEquals("store2", floatStoreNames[0]); + assertThat(numberStoreNames.length).isEqualTo(2); + assertThat(numberStoreNames[0]).isEqualTo("store1"); + assertThat(numberStoreNames[1]).isEqualTo("store2"); + assertThat(doubleStoreNames.length).isEqualTo(1); + assertThat(doubleStoreNames[0]).isEqualTo("store1"); + assertThat(floatStoreNames.length).isEqualTo(1); + assertThat(floatStoreNames[0]).isEqualTo("store2"); ObjectProvider> numberStoreProvider = bf.getBeanProvider(ResolvableType.forClass(NumberStore.class)); ObjectProvider> doubleStoreProvider = bf.getBeanProvider(ResolvableType.forClassWithGenerics(NumberStore.class, Double.class)); ObjectProvider> floatStoreProvider = bf.getBeanProvider(ResolvableType.forClassWithGenerics(NumberStore.class, Float.class)); assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(numberStoreProvider::getObject); assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(numberStoreProvider::getIfAvailable); - assertNull(numberStoreProvider.getIfUnique()); - assertSame(bf.getBean("store1"), doubleStoreProvider.getObject()); - assertSame(bf.getBean("store1"), doubleStoreProvider.getIfAvailable()); - assertSame(bf.getBean("store1"), doubleStoreProvider.getIfUnique()); - assertSame(bf.getBean("store2"), floatStoreProvider.getObject()); - assertSame(bf.getBean("store2"), floatStoreProvider.getIfAvailable()); - assertSame(bf.getBean("store2"), floatStoreProvider.getIfUnique()); + assertThat(numberStoreProvider.getIfUnique()).isNull(); + assertThat(doubleStoreProvider.getObject()).isSameAs(bf.getBean("store1")); + assertThat(doubleStoreProvider.getIfAvailable()).isSameAs(bf.getBean("store1")); + assertThat(doubleStoreProvider.getIfUnique()).isSameAs(bf.getBean("store1")); + assertThat(floatStoreProvider.getObject()).isSameAs(bf.getBean("store2")); + assertThat(floatStoreProvider.getIfAvailable()).isSameAs(bf.getBean("store2")); + assertThat(floatStoreProvider.getIfUnique()).isSameAs(bf.getBean("store2")); List> resolved = new ArrayList<>(); for (NumberStore instance : numberStoreProvider) { resolved.add(instance); } - assertEquals(2, resolved.size()); - assertSame(bf.getBean("store1"), resolved.get(0)); - assertSame(bf.getBean("store2"), resolved.get(1)); + assertThat(resolved.size()).isEqualTo(2); + assertThat(resolved.get(0)).isSameAs(bf.getBean("store1")); + assertThat(resolved.get(1)).isSameAs(bf.getBean("store2")); resolved = numberStoreProvider.stream().collect(Collectors.toList()); - assertEquals(2, resolved.size()); - assertSame(bf.getBean("store1"), resolved.get(0)); - assertSame(bf.getBean("store2"), resolved.get(1)); + assertThat(resolved.size()).isEqualTo(2); + assertThat(resolved.get(0)).isSameAs(bf.getBean("store1")); + assertThat(resolved.get(1)).isSameAs(bf.getBean("store2")); resolved = numberStoreProvider.orderedStream().collect(Collectors.toList()); - assertEquals(2, resolved.size()); - assertSame(bf.getBean("store2"), resolved.get(0)); - assertSame(bf.getBean("store1"), resolved.get(1)); + assertThat(resolved.size()).isEqualTo(2); + assertThat(resolved.get(0)).isSameAs(bf.getBean("store2")); + assertThat(resolved.get(1)).isSameAs(bf.getBean("store1")); resolved = new ArrayList<>(); for (NumberStore instance : doubleStoreProvider) { resolved.add(instance); } - assertEquals(1, resolved.size()); - assertTrue(resolved.contains(bf.getBean("store1"))); + assertThat(resolved.size()).isEqualTo(1); + assertThat(resolved.contains(bf.getBean("store1"))).isTrue(); resolved = doubleStoreProvider.stream().collect(Collectors.toList()); - assertEquals(1, resolved.size()); - assertTrue(resolved.contains(bf.getBean("store1"))); + assertThat(resolved.size()).isEqualTo(1); + assertThat(resolved.contains(bf.getBean("store1"))).isTrue(); resolved = doubleStoreProvider.orderedStream().collect(Collectors.toList()); - assertEquals(1, resolved.size()); - assertTrue(resolved.contains(bf.getBean("store1"))); + assertThat(resolved.size()).isEqualTo(1); + assertThat(resolved.contains(bf.getBean("store1"))).isTrue(); resolved = new ArrayList<>(); for (NumberStore instance : floatStoreProvider) { resolved.add(instance); } - assertEquals(1, resolved.size()); - assertTrue(resolved.contains(bf.getBean("store2"))); + assertThat(resolved.size()).isEqualTo(1); + assertThat(resolved.contains(bf.getBean("store2"))).isTrue(); resolved = floatStoreProvider.stream().collect(Collectors.toList()); - assertEquals(1, resolved.size()); - assertTrue(resolved.contains(bf.getBean("store2"))); + assertThat(resolved.size()).isEqualTo(1); + assertThat(resolved.contains(bf.getBean("store2"))).isTrue(); resolved = floatStoreProvider.orderedStream().collect(Collectors.toList()); - assertEquals(1, resolved.size()); - assertTrue(resolved.contains(bf.getBean("store2"))); + assertThat(resolved.size()).isEqualTo(1); + assertThat(resolved.contains(bf.getBean("store2"))).isTrue(); } @Test @@ -955,9 +954,9 @@ public class BeanFactoryGenericsTests { ObjectProvider> numberStoreProvider = bf.getBeanProvider(ResolvableType.forClass(NumberStore.class)); List> resolved = numberStoreProvider.orderedStream().collect(Collectors.toList()); - assertEquals(2, resolved.size()); - assertSame(bf.getBean("store2"), resolved.get(0)); - assertSame(bf.getBean("store1"), resolved.get(1)); + assertThat(resolved.size()).isEqualTo(2); + assertThat(resolved.get(0)).isSameAs(bf.getBean("store2")); + assertThat(resolved.get(1)).isSameAs(bf.getBean("store1")); } @@ -979,9 +978,9 @@ public class BeanFactoryGenericsTests { public static class CollectionDependentBean { public CollectionDependentBean(NamedUrlList list, NamedUrlSet set, NamedUrlMap map) { - assertEquals(1, list.size()); - assertEquals(1, set.size()); - assertEquals(1, map.size()); + assertThat(list.size()).isEqualTo(1); + assertThat(set.size()).isEqualTo(1); + assertThat(map.size()).isEqualTo(1); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistryTests.java index 512541a9c8b..6d41520e40f 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistryTests.java @@ -23,10 +23,7 @@ import org.springframework.beans.factory.ObjectFactory; import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -41,7 +38,7 @@ public class DefaultSingletonBeanRegistryTests { TestBean tb = new TestBean(); beanRegistry.registerSingleton("tb", tb); - assertSame(tb, beanRegistry.getSingleton("tb")); + assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb); TestBean tb2 = (TestBean) beanRegistry.getSingleton("tb2", new ObjectFactory() { @Override @@ -49,19 +46,19 @@ public class DefaultSingletonBeanRegistryTests { return new TestBean(); } }); - assertSame(tb2, beanRegistry.getSingleton("tb2")); + assertThat(beanRegistry.getSingleton("tb2")).isSameAs(tb2); - assertSame(tb, beanRegistry.getSingleton("tb")); - assertSame(tb2, beanRegistry.getSingleton("tb2")); - assertEquals(2, beanRegistry.getSingletonCount()); + assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb); + assertThat(beanRegistry.getSingleton("tb2")).isSameAs(tb2); + assertThat(beanRegistry.getSingletonCount()).isEqualTo(2); String[] names = beanRegistry.getSingletonNames(); - assertEquals(2, names.length); - assertEquals("tb", names[0]); - assertEquals("tb2", names[1]); + assertThat(names.length).isEqualTo(2); + assertThat(names[0]).isEqualTo("tb"); + assertThat(names[1]).isEqualTo("tb2"); beanRegistry.destroySingletons(); - assertEquals(0, beanRegistry.getSingletonCount()); - assertEquals(0, beanRegistry.getSingletonNames().length); + assertThat(beanRegistry.getSingletonCount()).isEqualTo(0); + assertThat(beanRegistry.getSingletonNames().length).isEqualTo(0); } @Test @@ -71,19 +68,19 @@ public class DefaultSingletonBeanRegistryTests { DerivedTestBean tb = new DerivedTestBean(); beanRegistry.registerSingleton("tb", tb); beanRegistry.registerDisposableBean("tb", tb); - assertSame(tb, beanRegistry.getSingleton("tb")); + assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb); - assertSame(tb, beanRegistry.getSingleton("tb")); - assertEquals(1, beanRegistry.getSingletonCount()); + assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb); + assertThat(beanRegistry.getSingletonCount()).isEqualTo(1); String[] names = beanRegistry.getSingletonNames(); - assertEquals(1, names.length); - assertEquals("tb", names[0]); - assertFalse(tb.wasDestroyed()); + assertThat(names.length).isEqualTo(1); + assertThat(names[0]).isEqualTo("tb"); + assertThat(tb.wasDestroyed()).isFalse(); beanRegistry.destroySingletons(); - assertEquals(0, beanRegistry.getSingletonCount()); - assertEquals(0, beanRegistry.getSingletonNames().length); - assertTrue(tb.wasDestroyed()); + assertThat(beanRegistry.getSingletonCount()).isEqualTo(0); + assertThat(beanRegistry.getSingletonNames().length).isEqualTo(0); + assertThat(tb.wasDestroyed()).isTrue(); } @Test @@ -93,15 +90,15 @@ public class DefaultSingletonBeanRegistryTests { beanRegistry.registerDependentBean("a", "b"); beanRegistry.registerDependentBean("b", "c"); beanRegistry.registerDependentBean("c", "b"); - assertTrue(beanRegistry.isDependent("a", "b")); - assertTrue(beanRegistry.isDependent("b", "c")); - assertTrue(beanRegistry.isDependent("c", "b")); - assertTrue(beanRegistry.isDependent("a", "c")); - assertFalse(beanRegistry.isDependent("c", "a")); - assertFalse(beanRegistry.isDependent("b", "a")); - assertFalse(beanRegistry.isDependent("a", "a")); - assertTrue(beanRegistry.isDependent("b", "b")); - assertTrue(beanRegistry.isDependent("c", "c")); + assertThat(beanRegistry.isDependent("a", "b")).isTrue(); + assertThat(beanRegistry.isDependent("b", "c")).isTrue(); + assertThat(beanRegistry.isDependent("c", "b")).isTrue(); + assertThat(beanRegistry.isDependent("a", "c")).isTrue(); + assertThat(beanRegistry.isDependent("c", "a")).isFalse(); + assertThat(beanRegistry.isDependent("b", "a")).isFalse(); + assertThat(beanRegistry.isDependent("a", "a")).isFalse(); + assertThat(beanRegistry.isDependent("b", "b")).isTrue(); + assertThat(beanRegistry.isDependent("c", "c")).isTrue(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/DefinitionMetadataEqualsHashCodeTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/DefinitionMetadataEqualsHashCodeTests.java index 04bc8549a96..86ce2297cb6 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/DefinitionMetadataEqualsHashCodeTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/DefinitionMetadataEqualsHashCodeTests.java @@ -22,8 +22,7 @@ import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@code equals()} and {@code hashCode()} in bean definitions. @@ -69,8 +68,8 @@ public class DefinitionMetadataEqualsHashCodeTests { // override in 'master' will not. But... the bean definitions should still be // considered equal. - assertEquals("Should be equal", master, equal); - assertEquals("Hash code for equal instances must match", master.hashCode(), equal.hashCode()); + assertThat(equal).as("Should be equal").isEqualTo(master); + assertThat(equal.hashCode()).as("Hash code for equal instances must match").isEqualTo(master.hashCode()); } @Test @@ -123,14 +122,14 @@ public class DefinitionMetadataEqualsHashCodeTests { } private void assertEqualsAndHashCodeContracts(Object master, Object equal, Object notEqual, Object subclass) { - assertEquals("Should be equal", master, equal); - assertEquals("Hash code for equal instances should match", master.hashCode(), equal.hashCode()); + assertThat(equal).as("Should be equal").isEqualTo(master); + assertThat(equal.hashCode()).as("Hash code for equal instances should match").isEqualTo(master.hashCode()); - assertNotEquals("Should not be equal", master, notEqual); - assertNotEquals("Hash code for non-equal instances should not match", master.hashCode(), notEqual.hashCode()); + assertThat(notEqual).as("Should not be equal").isNotEqualTo(master); + assertThat(notEqual.hashCode()).as("Hash code for non-equal instances should not match").isNotEqualTo((long) master.hashCode()); - assertEquals("Subclass should be equal", master, subclass); - assertEquals("Hash code for subclass should match", master.hashCode(), subclass.hashCode()); + assertThat(subclass).as("Subclass should be equal").isEqualTo(master); + assertThat(subclass.hashCode()).as("Hash code for subclass should match").isEqualTo(master.hashCode()); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/LookupMethodTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/LookupMethodTests.java index ab6894f5179..63ec1155510 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/LookupMethodTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/LookupMethodTests.java @@ -23,10 +23,8 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * @author Karl Pietrzak @@ -48,43 +46,43 @@ public class LookupMethodTests { @Test public void testWithoutConstructorArg() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); Object expected = bean.get(); - assertEquals(TestBean.class, expected.getClass()); + assertThat(expected.getClass()).isEqualTo(TestBean.class); } @Test public void testWithOverloadedArg() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); TestBean expected = bean.get("haha"); - assertEquals(TestBean.class, expected.getClass()); - assertEquals("haha", expected.getName()); + assertThat(expected.getClass()).isEqualTo(TestBean.class); + assertThat(expected.getName()).isEqualTo("haha"); } @Test public void testWithOneConstructorArg() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); TestBean expected = bean.getOneArgument("haha"); - assertEquals(TestBean.class, expected.getClass()); - assertEquals("haha", expected.getName()); + assertThat(expected.getClass()).isEqualTo(TestBean.class); + assertThat(expected.getName()).isEqualTo("haha"); } @Test public void testWithTwoConstructorArg() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); TestBean expected = bean.getTwoArguments("haha", 72); - assertEquals(TestBean.class, expected.getClass()); - assertEquals("haha", expected.getName()); - assertEquals(72, expected.getAge()); + assertThat(expected.getClass()).isEqualTo(TestBean.class); + assertThat(expected.getName()).isEqualTo("haha"); + assertThat(expected.getAge()).isEqualTo(72); } @Test public void testWithThreeArgsShouldFail() { AbstractBean bean = (AbstractBean) beanFactory.getBean("abstractBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); assertThatExceptionOfType(AbstractMethodError.class).as("does not have a three arg constructor").isThrownBy(() -> bean.getThreeArguments("name", 1, 2)); } @@ -92,11 +90,11 @@ public class LookupMethodTests { @Test public void testWithOverriddenLookupMethod() { AbstractBean bean = (AbstractBean) beanFactory.getBean("extendedBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); TestBean expected = bean.getOneArgument("haha"); - assertEquals(TestBean.class, expected.getClass()); - assertEquals("haha", expected.getName()); - assertTrue(expected.isJedi()); + assertThat(expected.getClass()).isEqualTo(TestBean.class); + assertThat(expected.getName()).isEqualTo("haha"); + assertThat(expected.isJedi()).isTrue(); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java index 83f194df125..64afa3db0c6 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java @@ -20,10 +20,9 @@ import java.util.List; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; /** * @author Rick Evans @@ -42,7 +41,7 @@ public class ManagedListTests { child.add("three"); child.setMergeEnabled(true); List mergedList = child.merge(parent); - assertEquals("merge() obviously did not work.", 3, mergedList.size()); + assertThat(mergedList.size()).as("merge() obviously did not work.").isEqualTo(3); } @Test @@ -50,7 +49,7 @@ public class ManagedListTests { ManagedList child = new ManagedList(); child.add("one"); child.setMergeEnabled(true); - assertSame(child, child.merge(null)); + assertThat(child.merge(null)).isSameAs(child); } @Test @@ -77,7 +76,7 @@ public class ManagedListTests { ManagedList child = new ManagedList(); child.setMergeEnabled(true); List mergedList = child.merge(parent); - assertEquals("merge() obviously did not work.", 2, mergedList.size()); + assertThat(mergedList.size()).as("merge() obviously did not work.").isEqualTo(2); } @Test @@ -90,7 +89,7 @@ public class ManagedListTests { child.add("one"); child.setMergeEnabled(true); List mergedList = child.merge(parent); - assertEquals("merge() obviously did not work.", 3, mergedList.size()); + assertThat(mergedList.size()).as("merge() obviously did not work.").isEqualTo(3); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java index 5aa657504fb..1a3d6422d3d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java @@ -20,10 +20,9 @@ import java.util.Map; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; /** * @author Rick Evans @@ -42,14 +41,14 @@ public class ManagedMapTests { child.put("three", "three"); child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); - assertEquals("merge() obviously did not work.", 3, mergedMap.size()); + assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(3); } @Test public void mergeWithNullParent() { ManagedMap child = new ManagedMap(); child.setMergeEnabled(true); - assertSame(child, child.merge(null)); + assertThat(child.merge(null)).isSameAs(child); } @Test @@ -74,7 +73,7 @@ public class ManagedMapTests { ManagedMap child = new ManagedMap(); child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); - assertEquals("merge() obviously did not work.", 2, mergedMap.size()); + assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(2); } @Test @@ -87,8 +86,8 @@ public class ManagedMapTests { child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); // child value for 'one' must override parent value... - assertEquals("merge() obviously did not work.", 2, mergedMap.size()); - assertEquals("Parent value not being overridden during merge().", "fork", mergedMap.get("one")); + assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(2); + assertThat(mergedMap.get("one")).as("Parent value not being overridden during merge().").isEqualTo("fork"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java index fa792da09f0..9807fc179de 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java @@ -20,10 +20,9 @@ import java.util.Map; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; /** * @author Rick Evans @@ -42,14 +41,14 @@ public class ManagedPropertiesTests { child.setProperty("three", "three"); child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); - assertEquals("merge() obviously did not work.", 3, mergedMap.size()); + assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(3); } @Test public void mergeWithNullParent() { ManagedProperties child = new ManagedProperties(); child.setMergeEnabled(true); - assertSame(child, child.merge(null)); + assertThat(child.merge(null)).isSameAs(child); } @Test @@ -75,7 +74,7 @@ public class ManagedPropertiesTests { ManagedProperties child = new ManagedProperties(); child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); - assertEquals("merge() obviously did not work.", 2, mergedMap.size()); + assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(2); } @Test @@ -88,8 +87,8 @@ public class ManagedPropertiesTests { child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); // child value for 'one' must override parent value... - assertEquals("merge() obviously did not work.", 2, mergedMap.size()); - assertEquals("Parent value not being overridden during merge().", "fork", mergedMap.get("one")); + assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(2); + assertThat(mergedMap.get("one")).as("Parent value not being overridden during merge().").isEqualTo("fork"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java index 41d17b7c51c..a80bab7b6e3 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java @@ -20,10 +20,9 @@ import java.util.Set; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; /** * @author Rick Evans @@ -42,7 +41,7 @@ public class ManagedSetTests { child.add("three"); child.setMergeEnabled(true); Set mergedSet = child.merge(parent); - assertEquals("merge() obviously did not work.", 3, mergedSet.size()); + assertThat(mergedSet.size()).as("merge() obviously did not work.").isEqualTo(3); } @Test @@ -50,7 +49,7 @@ public class ManagedSetTests { ManagedSet child = new ManagedSet(); child.add("one"); child.setMergeEnabled(true); - assertSame(child, child.merge(null)); + assertThat(child.merge(null)).isSameAs(child); } @Test @@ -76,7 +75,7 @@ public class ManagedSetTests { ManagedSet child = new ManagedSet(); child.setMergeEnabled(true); Set mergedSet = child.merge(parent); - assertEquals("merge() obviously did not work.", 2, mergedSet.size()); + assertThat(mergedSet.size()).as("merge() obviously did not work.").isEqualTo(2); } @Test @@ -89,7 +88,7 @@ public class ManagedSetTests { child.add("one"); child.setMergeEnabled(true); Set mergedSet = child.merge(parent); - assertEquals("merge() obviously did not work.", 2, mergedSet.size()); + assertThat(mergedSet.size()).as("merge() obviously did not work.").isEqualTo(2); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java index d372ee5994b..a533534560c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -37,7 +37,7 @@ public class PropertiesBeanDefinitionReaderTests { public void withSimpleConstructorArg() { this.reader.loadBeanDefinitions(new ClassPathResource("simpleConstructorArg.properties", getClass())); TestBean bean = (TestBean) this.beanFactory.getBean("testBean"); - assertEquals("Rob Harrop", bean.getName()); + assertThat(bean.getName()).isEqualTo("Rob Harrop"); } @Test @@ -45,15 +45,15 @@ public class PropertiesBeanDefinitionReaderTests { this.reader.loadBeanDefinitions(new ClassPathResource("refConstructorArg.properties", getClass())); TestBean rob = (TestBean) this.beanFactory.getBean("rob"); TestBean sally = (TestBean) this.beanFactory.getBean("sally"); - assertEquals(sally, rob.getSpouse()); + assertThat(rob.getSpouse()).isEqualTo(sally); } @Test public void withMultipleConstructorsArgs() { this.reader.loadBeanDefinitions(new ClassPathResource("multiConstructorArgs.properties", getClass())); TestBean bean = (TestBean) this.beanFactory.getBean("testBean"); - assertEquals("Rob Harrop", bean.getName()); - assertEquals(23, bean.getAge()); + assertThat(bean.getName()).isEqualTo("Rob Harrop"); + assertThat(bean.getAge()).isEqualTo(23); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireBeanFactoryTests.java index 70bea17f9ad..9d31bc4b8c1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireBeanFactoryTests.java @@ -31,9 +31,7 @@ import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import org.springframework.core.MethodParameter; import org.springframework.util.ClassUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -53,11 +51,11 @@ public class QualifierAnnotationAutowireBeanFactoryTests { cavs.addGenericArgumentValue(JUERGEN); RootBeanDefinition rbd = new RootBeanDefinition(Person.class, cavs, null); lbf.registerBeanDefinition(JUERGEN, rbd); - assertTrue(lbf.isAutowireCandidate(JUERGEN, null)); - assertTrue(lbf.isAutowireCandidate(JUERGEN, - new DependencyDescriptor(Person.class.getDeclaredField("name"), false))); - assertTrue(lbf.isAutowireCandidate(JUERGEN, - new DependencyDescriptor(Person.class.getDeclaredField("name"), true))); + assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isTrue(); + assertThat(lbf.isAutowireCandidate(JUERGEN, + new DependencyDescriptor(Person.class.getDeclaredField("name"), false))).isTrue(); + assertThat(lbf.isAutowireCandidate(JUERGEN, + new DependencyDescriptor(Person.class.getDeclaredField("name"), true))).isTrue(); } @Test @@ -68,11 +66,11 @@ public class QualifierAnnotationAutowireBeanFactoryTests { RootBeanDefinition rbd = new RootBeanDefinition(Person.class, cavs, null); rbd.setAutowireCandidate(false); lbf.registerBeanDefinition(JUERGEN, rbd); - assertFalse(lbf.isAutowireCandidate(JUERGEN, null)); - assertFalse(lbf.isAutowireCandidate(JUERGEN, - new DependencyDescriptor(Person.class.getDeclaredField("name"), false))); - assertFalse(lbf.isAutowireCandidate(JUERGEN, - new DependencyDescriptor(Person.class.getDeclaredField("name"), true))); + assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isFalse(); + assertThat(lbf.isAutowireCandidate(JUERGEN, + new DependencyDescriptor(Person.class.getDeclaredField("name"), false))).isFalse(); + assertThat(lbf.isAutowireCandidate(JUERGEN, + new DependencyDescriptor(Person.class.getDeclaredField("name"), true))).isFalse(); } @Ignore @@ -92,12 +90,12 @@ public class QualifierAnnotationAutowireBeanFactoryTests { QualifiedTestBean.class.getDeclaredField("qualified"), false); DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor( QualifiedTestBean.class.getDeclaredField("nonqualified"), false); - assertTrue(lbf.isAutowireCandidate(JUERGEN, null)); - assertTrue(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)); - assertTrue(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)); - assertTrue(lbf.isAutowireCandidate(MARK, null)); - assertTrue(lbf.isAutowireCandidate(MARK, nonqualifiedDescriptor)); - assertFalse(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)); + assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isTrue(); + assertThat(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)).isTrue(); + assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isTrue(); + assertThat(lbf.isAutowireCandidate(MARK, null)).isTrue(); + assertThat(lbf.isAutowireCandidate(MARK, nonqualifiedDescriptor)).isTrue(); + assertThat(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)).isFalse(); } @Test @@ -113,9 +111,9 @@ public class QualifierAnnotationAutowireBeanFactoryTests { QualifiedTestBean.class.getDeclaredField("qualified"), false); DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor( QualifiedTestBean.class.getDeclaredField("nonqualified"), false); - assertFalse(lbf.isAutowireCandidate(JUERGEN, null)); - assertFalse(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)); - assertFalse(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)); + assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isFalse(); + assertThat(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)).isFalse(); + assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isFalse(); } @Test @@ -130,9 +128,9 @@ public class QualifierAnnotationAutowireBeanFactoryTests { QualifiedTestBean.class.getDeclaredField("qualified"), false); DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor( QualifiedTestBean.class.getDeclaredField("nonqualified"), false); - assertTrue(lbf.isAutowireCandidate(JUERGEN, null)); - assertTrue(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)); - assertTrue(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)); + assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isTrue(); + assertThat(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)).isTrue(); + assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isTrue(); } @Ignore @@ -151,10 +149,10 @@ public class QualifierAnnotationAutowireBeanFactoryTests { MethodParameter param = new MethodParameter(QualifiedTestBean.class.getDeclaredConstructor(Person.class), 0); DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(param, false); param.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer()); - assertEquals("tpb", param.getParameterName()); - assertTrue(lbf.isAutowireCandidate(JUERGEN, null)); - assertTrue(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)); - assertFalse(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)); + assertThat(param.getParameterName()).isEqualTo("tpb"); + assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isTrue(); + assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isTrue(); + assertThat(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)).isFalse(); } @Ignore @@ -177,15 +175,15 @@ public class QualifierAnnotationAutowireBeanFactoryTests { DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor(qualifiedParam, false); DependencyDescriptor nonqualifiedDescriptor = new DependencyDescriptor(nonqualifiedParam, false); qualifiedParam.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer()); - assertEquals("tpb", qualifiedParam.getParameterName()); + assertThat(qualifiedParam.getParameterName()).isEqualTo("tpb"); nonqualifiedParam.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer()); - assertEquals("tpb", nonqualifiedParam.getParameterName()); - assertTrue(lbf.isAutowireCandidate(JUERGEN, null)); - assertTrue(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)); - assertTrue(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)); - assertTrue(lbf.isAutowireCandidate(MARK, null)); - assertTrue(lbf.isAutowireCandidate(MARK, nonqualifiedDescriptor)); - assertFalse(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)); + assertThat(nonqualifiedParam.getParameterName()).isEqualTo("tpb"); + assertThat(lbf.isAutowireCandidate(JUERGEN, null)).isTrue(); + assertThat(lbf.isAutowireCandidate(JUERGEN, nonqualifiedDescriptor)).isTrue(); + assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isTrue(); + assertThat(lbf.isAutowireCandidate(MARK, null)).isTrue(); + assertThat(lbf.isAutowireCandidate(MARK, nonqualifiedDescriptor)).isTrue(); + assertThat(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)).isFalse(); } @Test @@ -204,8 +202,8 @@ public class QualifierAnnotationAutowireBeanFactoryTests { DependencyDescriptor qualifiedDescriptor = new DependencyDescriptor( new MethodParameter(QualifiedTestBean.class.getDeclaredConstructor(Person.class), 0), false); - assertTrue(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)); - assertTrue(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)); + assertThat(lbf.isAutowireCandidate(JUERGEN, qualifiedDescriptor)).isTrue(); + assertThat(lbf.isAutowireCandidate(MARK, qualifiedDescriptor)).isTrue(); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java index 16aa897d1e7..64bdca4fc69 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java @@ -57,9 +57,6 @@ import org.springframework.core.io.Resource; import static org.assertj.core.api.Assertions.assertThat; 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; /** * Security test case. Checks whether the container uses its privileges for its @@ -115,7 +112,7 @@ public class CallbacksSecurityTests { } private void checkCurrentContext() { - assertEquals(expectedName, getCurrentSubjectName()); + assertThat(getCurrentSubjectName()).isEqualTo(expectedName); } } @@ -160,7 +157,7 @@ public class CallbacksSecurityTests { } private void checkCurrentContext() { - assertEquals(expectedName, getCurrentSubjectName()); + assertThat(getCurrentSubjectName()).isEqualTo(expectedName); } } @@ -204,7 +201,7 @@ public class CallbacksSecurityTests { } private void checkCurrentContext() { - assertEquals(expectedName, getCurrentSubjectName()); + assertThat(getCurrentSubjectName()).isEqualTo(expectedName); } } @@ -215,16 +212,16 @@ public class CallbacksSecurityTests { public NonPrivilegedFactory(String expected) { this.expectedName = expected; - assertEquals(expectedName, getCurrentSubjectName()); + assertThat(getCurrentSubjectName()).isEqualTo(expectedName); } public static Object makeStaticInstance(String expectedName) { - assertEquals(expectedName, getCurrentSubjectName()); + assertThat(getCurrentSubjectName()).isEqualTo(expectedName); return new Object(); } public Object makeInstance() { - assertEquals(expectedName, getCurrentSubjectName()); + assertThat(getCurrentSubjectName()).isEqualTo(expectedName); return new Object(); } } @@ -365,14 +362,14 @@ public class CallbacksSecurityTests { public void testSpringDestroyBean() throws Exception { beanFactory.getBean("spring-destroy"); beanFactory.destroySingletons(); - assertNull(System.getProperty("security.destroy")); + assertThat(System.getProperty("security.destroy")).isNull(); } @Test public void testCustomDestroyBean() throws Exception { beanFactory.getBean("custom-destroy"); beanFactory.destroySingletons(); - assertNull(System.getProperty("security.destroy")); + assertThat(System.getProperty("security.destroy")).isNull(); } @Test @@ -384,8 +381,8 @@ public class CallbacksSecurityTests { @Test public void testCustomFactoryType() throws Exception { - assertNull(beanFactory.getType("spring-factory")); - assertNull(System.getProperty("factory.object.type")); + assertThat(beanFactory.getType("spring-factory")).isNull(); + assertThat(System.getProperty("factory.object.type")).isNull(); } @Test @@ -458,7 +455,7 @@ public class CallbacksSecurityTests { return lbf.getBean("test", NonPrivilegedBean.class); } }, null); - assertNotNull(bean); + assertThat(bean).isNotNull(); } @Test @@ -480,8 +477,8 @@ public class CallbacksSecurityTests { @Override public Object run() { // sanity check - assertEquals("user1", getCurrentSubjectName()); - assertEquals(false, NonPrivilegedBean.destroyed); + assertThat(getCurrentSubjectName()).isEqualTo("user1"); + assertThat(NonPrivilegedBean.destroyed).isEqualTo(false); beanFactory.getBean("trusted-spring-callbacks"); beanFactory.getBean("trusted-custom-init-destroy"); @@ -497,7 +494,7 @@ public class CallbacksSecurityTests { beanFactory.getBean("trusted-working-property-injection"); beanFactory.destroySingletons(); - assertEquals(true, NonPrivilegedBean.destroyed); + assertThat(NonPrivilegedBean.destroyed).isEqualTo(true); return null; } }, provider.getAccessControlContext()); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java index 56aa6fa9329..a7cb8a91a34 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java @@ -23,9 +23,8 @@ import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -54,7 +53,7 @@ public class BeanConfigurerSupportTests { configurer.setBeanFactory(new DefaultListableBeanFactory()); configurer.configureBean(beanInstance); verify(resolver).resolveWiringInfo(beanInstance); - assertNull(beanInstance.getName()); + assertThat(beanInstance.getName()).isNull(); } @Test @@ -62,7 +61,7 @@ public class BeanConfigurerSupportTests { TestBean beanInstance = new TestBean(); BeanConfigurerSupport configurer = new StubBeanConfigurerSupport(); configurer.configureBean(beanInstance); - assertNull(beanInstance.getName()); + assertThat(beanInstance.getName()).isNull(); } @Test @@ -78,7 +77,7 @@ public class BeanConfigurerSupportTests { configurer.setBeanFactory(factory); configurer.afterPropertiesSet(); configurer.configureBean(beanInstance); - assertEquals("Bean is evidently not being configured (for some reason)", "Harriet Wheeler", beanInstance.getName()); + assertThat(beanInstance.getName()).as("Bean is evidently not being configured (for some reason)").isEqualTo("Harriet Wheeler"); } @Test @@ -98,7 +97,7 @@ public class BeanConfigurerSupportTests { configurer.setBeanFactory(factory); configurer.setBeanWiringInfoResolver(resolver); configurer.configureBean(beanInstance); - assertEquals("Bean is evidently not being configured (for some reason)", "David Gavurin", beanInstance.getSpouse().getName()); + assertThat(beanInstance.getSpouse().getName()).as("Bean is evidently not being configured (for some reason)").isEqualTo("David Gavurin"); } @Test @@ -118,7 +117,7 @@ public class BeanConfigurerSupportTests { configurer.setBeanFactory(factory); configurer.setBeanWiringInfoResolver(resolver); configurer.configureBean(beanInstance); - assertEquals("Bean is evidently not being configured (for some reason)", "David Gavurin", beanInstance.getSpouse().getName()); + assertThat(beanInstance.getSpouse().getName()).as("Bean is evidently not being configured (for some reason)").isEqualTo("David Gavurin"); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java index ee1b842d907..05c5fec3f19 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java @@ -18,9 +18,8 @@ package org.springframework.beans.factory.wiring; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Unit tests for the BeanWiringInfo class. @@ -63,25 +62,25 @@ public class BeanWiringInfoTests { @Test public void usingAutowireCtorIndicatesAutowiring() throws Exception { BeanWiringInfo info = new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_NAME, true); - assertTrue(info.indicatesAutowiring()); + assertThat(info.indicatesAutowiring()).isTrue(); } @Test public void usingBeanNameCtorDoesNotIndicateAutowiring() throws Exception { BeanWiringInfo info = new BeanWiringInfo("fooService"); - assertFalse(info.indicatesAutowiring()); + assertThat(info.indicatesAutowiring()).isFalse(); } @Test public void noDependencyCheckValueIsPreserved() throws Exception { BeanWiringInfo info = new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_NAME, true); - assertTrue(info.getDependencyCheck()); + assertThat(info.getDependencyCheck()).isTrue(); } @Test public void dependencyCheckValueIsPreserved() throws Exception { BeanWiringInfo info = new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_TYPE, false); - assertFalse(info.getDependencyCheck()); + assertThat(info.getDependencyCheck()).isFalse(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java index 74b67760a3f..62837dc7259 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java @@ -18,9 +18,8 @@ package org.springframework.beans.factory.wiring; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Unit tests for the ClassNameBeanWiringInfoResolver class. @@ -40,9 +39,8 @@ public class ClassNameBeanWiringInfoResolverTests { ClassNameBeanWiringInfoResolver resolver = new ClassNameBeanWiringInfoResolver(); Long beanInstance = new Long(1); BeanWiringInfo info = resolver.resolveWiringInfo(beanInstance); - assertNotNull(info); - assertEquals("Not resolving bean name to the class name of the supplied bean instance as per class contract.", - beanInstance.getClass().getName(), info.getBeanName()); + assertThat(info).isNotNull(); + assertThat(info.getBeanName()).as("Not resolving bean name to the class name of the supplied bean instance as per class contract.").isEqualTo(beanInstance.getClass().getName()); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java index 05aaec20522..29ab847c863 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java @@ -37,10 +37,6 @@ import org.springframework.tests.sample.beans.factory.DummyFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertTrue; /** * Subclasses must initialize the bean factory and any other variables they need. @@ -58,15 +54,15 @@ public abstract class AbstractBeanFactoryTests { */ @Test public void inheritance() { - assertTrue(getBeanFactory().containsBean("rod")); - assertTrue(getBeanFactory().containsBean("roderick")); + assertThat(getBeanFactory().containsBean("rod")).isTrue(); + assertThat(getBeanFactory().containsBean("roderick")).isTrue(); TestBean rod = (TestBean) getBeanFactory().getBean("rod"); TestBean roderick = (TestBean) getBeanFactory().getBean("roderick"); - assertTrue("not == ", rod != roderick); - assertTrue("rod.name is Rod", rod.getName().equals("Rod")); - assertTrue("rod.age is 31", rod.getAge() == 31); - assertTrue("roderick.name is Roderick", roderick.getName().equals("Roderick")); - assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge()); + assertThat(rod != roderick).as("not == ").isTrue(); + assertThat(rod.getName().equals("Rod")).as("rod.name is Rod").isTrue(); + assertThat(rod.getAge() == 31).as("rod.age is 31").isTrue(); + assertThat(roderick.getName().equals("Roderick")).as("roderick.name is Roderick").isTrue(); + assertThat(roderick.getAge() == rod.getAge()).as("roderick.age was inherited").isTrue(); } @Test @@ -93,26 +89,29 @@ public abstract class AbstractBeanFactoryTests { @Test public void lifecycleCallbacks() { LifecycleBean lb = (LifecycleBean) getBeanFactory().getBean("lifecycle"); - assertEquals("lifecycle", lb.getBeanName()); + assertThat(lb.getBeanName()).isEqualTo("lifecycle"); // The dummy business method will throw an exception if the // necessary callbacks weren't invoked in the right order. lb.businessMethod(); - assertTrue("Not destroyed", !lb.isDestroyed()); + boolean condition = !lb.isDestroyed(); + assertThat(condition).as("Not destroyed").isTrue(); } @Test public void findsValidInstance() { Object o = getBeanFactory().getBean("rod"); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); + boolean condition = o instanceof TestBean; + assertThat(condition).as("Rod bean is a TestBean").isTrue(); TestBean rod = (TestBean) o; - assertTrue("rod.name is Rod", rod.getName().equals("Rod")); - assertTrue("rod.age is 31", rod.getAge() == 31); + assertThat(rod.getName().equals("Rod")).as("rod.name is Rod").isTrue(); + assertThat(rod.getAge() == 31).as("rod.age is 31").isTrue(); } @Test public void getInstanceByMatchingClass() { Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); + boolean condition = o instanceof TestBean; + assertThat(condition).as("Rod bean is a TestBean").isTrue(); } @Test @@ -129,13 +128,15 @@ public abstract class AbstractBeanFactoryTests { @Test public void getSharedInstanceByMatchingClass() { Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); + boolean condition = o instanceof TestBean; + assertThat(condition).as("Rod bean is a TestBean").isTrue(); } @Test public void getSharedInstanceByMatchingClassNoCatch() { Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); + boolean condition = o instanceof TestBean; + assertThat(condition).as("Rod bean is a TestBean").isTrue(); } @Test @@ -152,28 +153,31 @@ public abstract class AbstractBeanFactoryTests { @Test public void sharedInstancesAreEqual() { Object o = getBeanFactory().getBean("rod"); - assertTrue("Rod bean1 is a TestBean", o instanceof TestBean); + boolean condition1 = o instanceof TestBean; + assertThat(condition1).as("Rod bean1 is a TestBean").isTrue(); Object o1 = getBeanFactory().getBean("rod"); - assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean); - assertTrue("Object equals applies", o == o1); + boolean condition = o1 instanceof TestBean; + assertThat(condition).as("Rod bean2 is a TestBean").isTrue(); + assertThat(o == o1).as("Object equals applies").isTrue(); } @Test public void prototypeInstancesAreIndependent() { TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy"); TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy"); - assertTrue("ref equal DOES NOT apply", tb1 != tb2); - assertTrue("object equal true", tb1.equals(tb2)); + assertThat(tb1 != tb2).as("ref equal DOES NOT apply").isTrue(); + assertThat(tb1.equals(tb2)).as("object equal true").isTrue(); tb1.setAge(1); tb2.setAge(2); - assertTrue("1 age independent = 1", tb1.getAge() == 1); - assertTrue("2 age independent = 2", tb2.getAge() == 2); - assertTrue("object equal now false", !tb1.equals(tb2)); + assertThat(tb1.getAge() == 1).as("1 age independent = 1").isTrue(); + assertThat(tb2.getAge() == 2).as("2 age independent = 2").isTrue(); + boolean condition = !tb1.equals(tb2); + assertThat(condition).as("object equal now false").isTrue(); } @Test public void notThere() { - assertFalse(getBeanFactory().containsBean("Mr Squiggle")); + assertThat(getBeanFactory().containsBean("Mr Squiggle")).isFalse(); assertThatExceptionOfType(BeansException.class).isThrownBy(() -> getBeanFactory().getBean("Mr Squiggle")); } @@ -181,9 +185,10 @@ public abstract class AbstractBeanFactoryTests { @Test public void validEmpty() { Object o = getBeanFactory().getBean("validEmpty"); - assertTrue("validEmpty bean is a TestBean", o instanceof TestBean); + boolean condition = o instanceof TestBean; + assertThat(condition).as("validEmpty bean is a TestBean").isTrue(); TestBean ve = (TestBean) o; - assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null); + assertThat(ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null).as("Valid empty has defaults").isTrue(); } public void xtestTypeMismatch() { @@ -202,29 +207,30 @@ public abstract class AbstractBeanFactoryTests { @Test public void grandparentDefinitionFoundInBeanFactory() throws Exception { TestBean dad = (TestBean) getBeanFactory().getBean("father"); - assertTrue("Dad has correct name", dad.getName().equals("Albert")); + assertThat(dad.getName().equals("Albert")).as("Dad has correct name").isTrue(); } @Test public void factorySingleton() throws Exception { - assertTrue(getBeanFactory().isSingleton("&singletonFactory")); - assertTrue(getBeanFactory().isSingleton("singletonFactory")); + assertThat(getBeanFactory().isSingleton("&singletonFactory")).isTrue(); + assertThat(getBeanFactory().isSingleton("singletonFactory")).isTrue(); TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory"); - assertTrue("Singleton from factory has correct name, not " + tb.getName(), tb.getName().equals(DummyFactory.SINGLETON_NAME)); + assertThat(tb.getName().equals(DummyFactory.SINGLETON_NAME)).as("Singleton from factory has correct name, not " + tb.getName()).isTrue(); DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); TestBean tb2 = (TestBean) getBeanFactory().getBean("singletonFactory"); - assertTrue("Singleton references ==", tb == tb2); - assertTrue("FactoryBean is BeanFactoryAware", factory.getBeanFactory() != null); + assertThat(tb == tb2).as("Singleton references ==").isTrue(); + assertThat(factory.getBeanFactory() != null).as("FactoryBean is BeanFactoryAware").isTrue(); } @Test public void factoryPrototype() throws Exception { - assertTrue(getBeanFactory().isSingleton("&prototypeFactory")); - assertFalse(getBeanFactory().isSingleton("prototypeFactory")); + assertThat(getBeanFactory().isSingleton("&prototypeFactory")).isTrue(); + assertThat(getBeanFactory().isSingleton("prototypeFactory")).isFalse(); TestBean tb = (TestBean) getBeanFactory().getBean("prototypeFactory"); - assertTrue(!tb.getName().equals(DummyFactory.SINGLETON_NAME)); + boolean condition = !tb.getName().equals(DummyFactory.SINGLETON_NAME); + assertThat(condition).isTrue(); TestBean tb2 = (TestBean) getBeanFactory().getBean("prototypeFactory"); - assertTrue("Prototype references !=", tb != tb2); + assertThat(tb != tb2).as("Prototype references !=").isTrue(); } /** @@ -233,7 +239,7 @@ public abstract class AbstractBeanFactoryTests { */ @Test public void getFactoryItself() throws Exception { - assertNotNull(getBeanFactory().getBean("&singletonFactory")); + assertThat(getBeanFactory().getBean("&singletonFactory")).isNotNull(); } /** @@ -242,9 +248,9 @@ public abstract class AbstractBeanFactoryTests { @Test public void factoryIsInitialized() throws Exception { TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory"); - assertNotNull(tb); + assertThat(tb).isNotNull(); DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); - assertTrue("Factory was initialized because it implemented InitializingBean", factory.wasInitialized()); + assertThat(factory.wasInitialized()).as("Factory was initialized because it implemented InitializingBean").isTrue(); } /** @@ -276,7 +282,7 @@ public abstract class AbstractBeanFactoryTests { cbf.registerAlias("rod", alias); Object rod = getBeanFactory().getBean("rod"); Object aliasRod = getBeanFactory().getBean(alias); - assertTrue(rod == aliasRod); + assertThat(rod == aliasRod).isTrue(); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java index 7b8f5ee98b9..ad10d4a57f7 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java @@ -23,7 +23,7 @@ import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -50,25 +50,24 @@ public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFacto protected final void assertCount(int count) { String[] defnames = getListableBeanFactory().getBeanDefinitionNames(); - assertTrue("We should have " + count + " beans, not " + defnames.length, defnames.length == count); + assertThat(defnames.length == count).as("We should have " + count + " beans, not " + defnames.length).isTrue(); } protected void assertTestBeanCount(int count) { String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false); - assertTrue("We should have " + count + " beans for class org.springframework.tests.sample.beans.TestBean, not " + - defNames.length, defNames.length == count); + assertThat(defNames.length == count).as("We should have " + count + " beans for class org.springframework.tests.sample.beans.TestBean, not " + + defNames.length).isTrue(); int countIncludingFactoryBeans = count + 2; String[] names = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, true); - assertTrue("We should have " + countIncludingFactoryBeans + - " beans for class org.springframework.tests.sample.beans.TestBean, not " + names.length, - names.length == countIncludingFactoryBeans); + assertThat(names.length == countIncludingFactoryBeans).as("We should have " + countIncludingFactoryBeans + + " beans for class org.springframework.tests.sample.beans.TestBean, not " + names.length).isTrue(); } @Test public void getDefinitionsForNoSuchClass() { String[] defnames = getListableBeanFactory().getBeanNamesForType(String.class); - assertTrue("No string definitions", defnames.length == 0); + assertThat(defnames.length == 0).as("No string definitions").isTrue(); } /** @@ -77,19 +76,17 @@ public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFacto */ @Test public void getCountForFactoryClass() { - assertTrue("Should have 2 factories, not " + - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length, - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2); + assertThat(getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2).as("Should have 2 factories, not " + + getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length).isTrue(); - assertTrue("Should have 2 factories, not " + - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length, - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2); + assertThat(getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2).as("Should have 2 factories, not " + + getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length).isTrue(); } @Test public void containsBeanDefinition() { - assertTrue(getListableBeanFactory().containsBeanDefinition("rod")); - assertTrue(getListableBeanFactory().containsBeanDefinition("roderick")); + assertThat(getListableBeanFactory().containsBeanDefinition("rod")).isTrue(); + assertThat(getListableBeanFactory().containsBeanDefinition("roderick")).isTrue(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java index 00921f90b62..60ad0d6cd01 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java @@ -25,8 +25,7 @@ import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -41,8 +40,8 @@ public class AutowireWithExclusionTests { beanFactory.preInstantiateSingletons(); TestBean rob = (TestBean) beanFactory.getBean("rob"); TestBean sally = (TestBean) beanFactory.getBean("sally"); - assertEquals(sally, rob.getSpouse()); - assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); + assertThat(rob.getSpouse()).isEqualTo(sally); + assertThat(CountingFactory.getFactoryBeanInstanceCount()).isEqualTo(1); } @Test @@ -51,8 +50,8 @@ public class AutowireWithExclusionTests { DefaultListableBeanFactory beanFactory = getBeanFactory("autowire-with-exclusion.xml"); beanFactory.preInstantiateSingletons(); TestBean rob = (TestBean) beanFactory.getBean("rob"); - assertEquals("props1", rob.getSomeProperties().getProperty("name")); - assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); + assertThat(rob.getSomeProperties().getProperty("name")).isEqualTo("props1"); + assertThat(CountingFactory.getFactoryBeanInstanceCount()).isEqualTo(1); } @Test @@ -66,8 +65,8 @@ public class AutowireWithExclusionTests { robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally")); child.registerBeanDefinition("rob2", robDef); TestBean rob = (TestBean) child.getBean("rob2"); - assertEquals("props1", rob.getSomeProperties().getProperty("name")); - assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); + assertThat(rob.getSomeProperties().getProperty("name")).isEqualTo("props1"); + assertThat(CountingFactory.getFactoryBeanInstanceCount()).isEqualTo(1); } @Test @@ -85,8 +84,8 @@ public class AutowireWithExclusionTests { propsDef.getPropertyValues().add("properties", "name=props3"); child.registerBeanDefinition("props3", propsDef); TestBean rob = (TestBean) child.getBean("rob2"); - assertEquals("props1", rob.getSomeProperties().getProperty("name")); - assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); + assertThat(rob.getSomeProperties().getProperty("name")).isEqualTo("props1"); + assertThat(CountingFactory.getFactoryBeanInstanceCount()).isEqualTo(1); } @Test @@ -104,8 +103,8 @@ public class AutowireWithExclusionTests { propsDef.setPrimary(true); child.registerBeanDefinition("props3", propsDef); TestBean rob = (TestBean) child.getBean("rob2"); - assertEquals("props3", rob.getSomeProperties().getProperty("name")); - assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); + assertThat(rob.getSomeProperties().getProperty("name")).isEqualTo("props3"); + assertThat(CountingFactory.getFactoryBeanInstanceCount()).isEqualTo(1); } @Test @@ -124,8 +123,8 @@ public class AutowireWithExclusionTests { propsDef.setPrimary(true); child.registerBeanDefinition("props3", propsDef); TestBean rob = (TestBean) child.getBean("rob2"); - assertEquals("props3", rob.getSomeProperties().getProperty("name")); - assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); + assertThat(rob.getSomeProperties().getProperty("name")).isEqualTo("props3"); + assertThat(CountingFactory.getFactoryBeanInstanceCount()).isEqualTo(1); } @Test @@ -134,8 +133,8 @@ public class AutowireWithExclusionTests { DefaultListableBeanFactory beanFactory = getBeanFactory("autowire-with-inclusion.xml"); beanFactory.preInstantiateSingletons(); TestBean rob = (TestBean) beanFactory.getBean("rob"); - assertEquals("props1", rob.getSomeProperties().getProperty("name")); - assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); + assertThat(rob.getSomeProperties().getProperty("name")).isEqualTo("props1"); + assertThat(CountingFactory.getFactoryBeanInstanceCount()).isEqualTo(1); } @Test @@ -144,8 +143,8 @@ public class AutowireWithExclusionTests { DefaultListableBeanFactory beanFactory = getBeanFactory("autowire-with-selective-inclusion.xml"); beanFactory.preInstantiateSingletons(); TestBean rob = (TestBean) beanFactory.getBean("rob"); - assertEquals("props1", rob.getSomeProperties().getProperty("name")); - assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); + assertThat(rob.getSomeProperties().getProperty("name")).isEqualTo("props1"); + assertThat(CountingFactory.getFactoryBeanInstanceCount()).isEqualTo(1); } @Test @@ -153,19 +152,19 @@ public class AutowireWithExclusionTests { DefaultListableBeanFactory beanFactory = getBeanFactory("autowire-constructor-with-exclusion.xml"); TestBean rob = (TestBean) beanFactory.getBean("rob"); TestBean sally = (TestBean) beanFactory.getBean("sally"); - assertEquals(sally, rob.getSpouse()); + assertThat(rob.getSpouse()).isEqualTo(sally); TestBean rob2 = (TestBean) beanFactory.getBean("rob"); - assertEquals(rob, rob2); - assertNotSame(rob, rob2); - assertEquals(rob.getSpouse(), rob2.getSpouse()); - assertNotSame(rob.getSpouse(), rob2.getSpouse()); + assertThat(rob2).isEqualTo(rob); + assertThat(rob2).isNotSameAs(rob); + assertThat(rob2.getSpouse()).isEqualTo(rob.getSpouse()); + assertThat(rob2.getSpouse()).isNotSameAs(rob.getSpouse()); } @Test public void constructorAutowireWithExclusion() throws Exception { DefaultListableBeanFactory beanFactory = getBeanFactory("autowire-constructor-with-exclusion.xml"); TestBean rob = (TestBean) beanFactory.getBean("rob"); - assertEquals("props1", rob.getSomeProperties().getProperty("name")); + assertThat(rob.getSomeProperties().getProperty("name")).isEqualTo("props1"); } private DefaultListableBeanFactory getBeanFactory(String configPath) { diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/BeanNameGenerationTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/BeanNameGenerationTests.java index 27cbdc5bf29..619e72223c5 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/BeanNameGenerationTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/BeanNameGenerationTests.java @@ -23,9 +23,7 @@ import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -50,21 +48,21 @@ public class BeanNameGenerationTests { String targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "0"; GeneratedNameBean topLevel1 = (GeneratedNameBean) beanFactory.getBean(targetName); - assertNotNull(topLevel1); + assertThat(topLevel1).isNotNull(); targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "1"; GeneratedNameBean topLevel2 = (GeneratedNameBean) beanFactory.getBean(targetName); - assertNotNull(topLevel2); + assertThat(topLevel2).isNotNull(); GeneratedNameBean child1 = topLevel1.getChild(); - assertNotNull(child1.getBeanName()); - assertTrue(child1.getBeanName().startsWith(className)); + assertThat(child1.getBeanName()).isNotNull(); + assertThat(child1.getBeanName().startsWith(className)).isTrue(); GeneratedNameBean child2 = topLevel2.getChild(); - assertNotNull(child2.getBeanName()); - assertTrue(child2.getBeanName().startsWith(className)); + assertThat(child2.getBeanName()).isNotNull(); + assertThat(child2.getBeanName().startsWith(className)).isTrue(); - assertFalse(child1.getBeanName().equals(child2.getBeanName())); + assertThat(child1.getBeanName().equals(child2.getBeanName())).isFalse(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java index 9d0d0049337..56efb7db6e1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java @@ -30,9 +30,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit and integration tests for the collection merging support. @@ -56,148 +54,154 @@ public class CollectionMergingTests { public void mergeList() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithList"); List list = bean.getSomeList(); - assertEquals("Incorrect size", 3, list.size()); - assertEquals("Rob Harrop", list.get(0)); - assertEquals("Rod Johnson", list.get(1)); - assertEquals("Juergen Hoeller", list.get(2)); + assertThat(list.size()).as("Incorrect size").isEqualTo(3); + assertThat(list.get(0)).isEqualTo("Rob Harrop"); + assertThat(list.get(1)).isEqualTo("Rod Johnson"); + assertThat(list.get(2)).isEqualTo("Juergen Hoeller"); } @Test public void mergeListWithInnerBeanAsListElement() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithListOfRefs"); - List list = bean.getSomeList(); - assertNotNull(list); - assertEquals(3, list.size()); - assertNotNull(list.get(2)); - assertTrue(list.get(2) instanceof TestBean); + List list = bean.getSomeList(); + assertThat(list).isNotNull(); + assertThat(list.size()).isEqualTo(3); + assertThat(list.get(2)).isNotNull(); + boolean condition = list.get(2) instanceof TestBean; + assertThat(condition).isTrue(); } @Test public void mergeSet() { TestBean bean = (TestBean) this.beanFactory.getBean("childWithSet"); Set set = bean.getSomeSet(); - assertEquals("Incorrect size", 2, set.size()); - assertTrue(set.contains("Rob Harrop")); - assertTrue(set.contains("Sally Greenwood")); + assertThat(set.size()).as("Incorrect size").isEqualTo(2); + assertThat(set.contains("Rob Harrop")).isTrue(); + assertThat(set.contains("Sally Greenwood")).isTrue(); } @Test public void mergeSetWithInnerBeanAsSetElement() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithSetOfRefs"); - Set set = bean.getSomeSet(); - assertNotNull(set); - assertEquals(2, set.size()); + Set set = bean.getSomeSet(); + assertThat(set).isNotNull(); + assertThat(set.size()).isEqualTo(2); Iterator it = set.iterator(); it.next(); Object o = it.next(); - assertNotNull(o); - assertTrue(o instanceof TestBean); - assertEquals("Sally", ((TestBean) o).getName()); + assertThat(o).isNotNull(); + boolean condition = o instanceof TestBean; + assertThat(condition).isTrue(); + assertThat(((TestBean) o).getName()).isEqualTo("Sally"); } @Test public void mergeMap() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithMap"); Map map = bean.getSomeMap(); - assertEquals("Incorrect size", 3, map.size()); - assertEquals("Sally", map.get("Rob")); - assertEquals("Kerry", map.get("Rod")); - assertEquals("Eva", map.get("Juergen")); + assertThat(map.size()).as("Incorrect size").isEqualTo(3); + assertThat(map.get("Rob")).isEqualTo("Sally"); + assertThat(map.get("Rod")).isEqualTo("Kerry"); + assertThat(map.get("Juergen")).isEqualTo("Eva"); } @Test public void mergeMapWithInnerBeanAsMapEntryValue() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithMapOfRefs"); - Map map = bean.getSomeMap(); - assertNotNull(map); - assertEquals(2, map.size()); - assertNotNull(map.get("Rob")); - assertTrue(map.get("Rob") instanceof TestBean); - assertEquals("Sally", ((TestBean) map.get("Rob")).getName()); + Map map = bean.getSomeMap(); + assertThat(map).isNotNull(); + assertThat(map.size()).isEqualTo(2); + assertThat(map.get("Rob")).isNotNull(); + boolean condition = map.get("Rob") instanceof TestBean; + assertThat(condition).isTrue(); + assertThat(((TestBean) map.get("Rob")).getName()).isEqualTo("Sally"); } @Test public void mergeProperties() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithProps"); Properties props = bean.getSomeProperties(); - assertEquals("Incorrect size", 3, props.size()); - assertEquals("Sally", props.getProperty("Rob")); - assertEquals("Kerry",props.getProperty("Rod")); - assertEquals("Eva", props.getProperty("Juergen")); + assertThat(props.size()).as("Incorrect size").isEqualTo(3); + assertThat(props.getProperty("Rob")).isEqualTo("Sally"); + assertThat(props.getProperty("Rod")).isEqualTo("Kerry"); + assertThat(props.getProperty("Juergen")).isEqualTo("Eva"); } @Test public void mergeListInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithListInConstructor"); List list = bean.getSomeList(); - assertEquals("Incorrect size", 3, list.size()); - assertEquals("Rob Harrop", list.get(0)); - assertEquals("Rod Johnson", list.get(1)); - assertEquals("Juergen Hoeller", list.get(2)); + assertThat(list.size()).as("Incorrect size").isEqualTo(3); + assertThat(list.get(0)).isEqualTo("Rob Harrop"); + assertThat(list.get(1)).isEqualTo("Rod Johnson"); + assertThat(list.get(2)).isEqualTo("Juergen Hoeller"); } @Test public void mergeListWithInnerBeanAsListElementInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithListOfRefsInConstructor"); - List list = bean.getSomeList(); - assertNotNull(list); - assertEquals(3, list.size()); - assertNotNull(list.get(2)); - assertTrue(list.get(2) instanceof TestBean); + List list = bean.getSomeList(); + assertThat(list).isNotNull(); + assertThat(list.size()).isEqualTo(3); + assertThat(list.get(2)).isNotNull(); + boolean condition = list.get(2) instanceof TestBean; + assertThat(condition).isTrue(); } @Test public void mergeSetInConstructor() { TestBean bean = (TestBean) this.beanFactory.getBean("childWithSetInConstructor"); Set set = bean.getSomeSet(); - assertEquals("Incorrect size", 2, set.size()); - assertTrue(set.contains("Rob Harrop")); - assertTrue(set.contains("Sally Greenwood")); + assertThat(set.size()).as("Incorrect size").isEqualTo(2); + assertThat(set.contains("Rob Harrop")).isTrue(); + assertThat(set.contains("Sally Greenwood")).isTrue(); } @Test public void mergeSetWithInnerBeanAsSetElementInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithSetOfRefsInConstructor"); - Set set = bean.getSomeSet(); - assertNotNull(set); - assertEquals(2, set.size()); + Set set = bean.getSomeSet(); + assertThat(set).isNotNull(); + assertThat(set.size()).isEqualTo(2); Iterator it = set.iterator(); it.next(); Object o = it.next(); - assertNotNull(o); - assertTrue(o instanceof TestBean); - assertEquals("Sally", ((TestBean) o).getName()); + assertThat(o).isNotNull(); + boolean condition = o instanceof TestBean; + assertThat(condition).isTrue(); + assertThat(((TestBean) o).getName()).isEqualTo("Sally"); } @Test public void mergeMapInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithMapInConstructor"); Map map = bean.getSomeMap(); - assertEquals("Incorrect size", 3, map.size()); - assertEquals("Sally", map.get("Rob")); - assertEquals("Kerry", map.get("Rod")); - assertEquals("Eva", map.get("Juergen")); + assertThat(map.size()).as("Incorrect size").isEqualTo(3); + assertThat(map.get("Rob")).isEqualTo("Sally"); + assertThat(map.get("Rod")).isEqualTo("Kerry"); + assertThat(map.get("Juergen")).isEqualTo("Eva"); } @Test public void mergeMapWithInnerBeanAsMapEntryValueInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithMapOfRefsInConstructor"); - Map map = bean.getSomeMap(); - assertNotNull(map); - assertEquals(2, map.size()); - assertNotNull(map.get("Rob")); - assertTrue(map.get("Rob") instanceof TestBean); - assertEquals("Sally", ((TestBean) map.get("Rob")).getName()); + Map map = bean.getSomeMap(); + assertThat(map).isNotNull(); + assertThat(map.size()).isEqualTo(2); + assertThat(map.get("Rob")).isNotNull(); + boolean condition = map.get("Rob") instanceof TestBean; + assertThat(condition).isTrue(); + assertThat(((TestBean) map.get("Rob")).getName()).isEqualTo("Sally"); } @Test public void mergePropertiesInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithPropsInConstructor"); Properties props = bean.getSomeProperties(); - assertEquals("Incorrect size", 3, props.size()); - assertEquals("Sally", props.getProperty("Rob")); - assertEquals("Kerry", props.getProperty("Rod")); - assertEquals("Eva", props.getProperty("Juergen")); + assertThat(props.size()).as("Incorrect size").isEqualTo(3); + assertThat(props.getProperty("Rob")).isEqualTo("Sally"); + assertThat(props.getProperty("Rod")).isEqualTo("Kerry"); + assertThat(props.getProperty("Juergen")).isEqualTo("Eva"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionsWithDefaultTypesTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionsWithDefaultTypesTests.java index b2135bce507..acc18e9f1d1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionsWithDefaultTypesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionsWithDefaultTypesTests.java @@ -25,8 +25,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -46,7 +45,7 @@ public class CollectionsWithDefaultTypesTests { public void testListHasDefaultType() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("testBean"); for (Object o : bean.getSomeList()) { - assertEquals("Value type is incorrect", Integer.class, o.getClass()); + assertThat(o.getClass()).as("Value type is incorrect").isEqualTo(Integer.class); } } @@ -54,7 +53,7 @@ public class CollectionsWithDefaultTypesTests { public void testSetHasDefaultType() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("testBean"); for (Object o : bean.getSomeSet()) { - assertEquals("Value type is incorrect", Integer.class, o.getClass()); + assertThat(o.getClass()).as("Value type is incorrect").isEqualTo(Integer.class); } } @@ -73,8 +72,8 @@ public class CollectionsWithDefaultTypesTests { @SuppressWarnings("rawtypes") private void assertMap(Map map) { for (Map.Entry entry : map.entrySet()) { - assertEquals("Key type is incorrect", Integer.class, entry.getKey().getClass()); - assertEquals("Value type is incorrect", Boolean.class, entry.getValue().getClass()); + assertThat(entry.getKey().getClass()).as("Key type is incorrect").isEqualTo(Integer.class); + assertThat(entry.getValue().getClass()).as("Value type is incorrect").isEqualTo(Boolean.class); } } @@ -82,16 +81,15 @@ public class CollectionsWithDefaultTypesTests { @SuppressWarnings("rawtypes") public void testBuildCollectionFromMixtureOfReferencesAndValues() throws Exception { MixedCollectionBean jumble = (MixedCollectionBean) this.beanFactory.getBean("jumble"); - assertTrue("Expected 3 elements, not " + jumble.getJumble().size(), - jumble.getJumble().size() == 3); + assertThat(jumble.getJumble().size() == 3).as("Expected 3 elements, not " + jumble.getJumble().size()).isTrue(); List l = (List) jumble.getJumble(); - assertTrue(l.get(0).equals("literal")); + assertThat(l.get(0).equals("literal")).isTrue(); Integer[] array1 = (Integer[]) l.get(1); - assertTrue(array1[0].equals(new Integer(2))); - assertTrue(array1[1].equals(new Integer(4))); + assertThat(array1[0].equals(new Integer(2))).isTrue(); + assertThat(array1[1].equals(new Integer(4))).isTrue(); int[] array2 = (int[]) l.get(2); - assertTrue(array2[0] == 3); - assertTrue(array2[1] == 5); + assertThat(array2[0] == 3).isTrue(); + assertThat(array2[1] == 5).isTrue(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DefaultLifecycleMethodsTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DefaultLifecycleMethodsTests.java index 787b2610650..84bdca12445 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DefaultLifecycleMethodsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DefaultLifecycleMethodsTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -44,22 +43,22 @@ public class DefaultLifecycleMethodsTests { @Test public void lifecycleMethodsInvoked() { LifecycleAwareBean bean = (LifecycleAwareBean) this.beanFactory.getBean("lifecycleAware"); - assertTrue("Bean not initialized", bean.isInitCalled()); - assertFalse("Custom init method called incorrectly", bean.isCustomInitCalled()); - assertFalse("Bean destroyed too early", bean.isDestroyCalled()); + assertThat(bean.isInitCalled()).as("Bean not initialized").isTrue(); + assertThat(bean.isCustomInitCalled()).as("Custom init method called incorrectly").isFalse(); + assertThat(bean.isDestroyCalled()).as("Bean destroyed too early").isFalse(); this.beanFactory.destroySingletons(); - assertTrue("Bean not destroyed", bean.isDestroyCalled()); - assertFalse("Custom destroy method called incorrectly", bean.isCustomDestroyCalled()); + assertThat(bean.isDestroyCalled()).as("Bean not destroyed").isTrue(); + assertThat(bean.isCustomDestroyCalled()).as("Custom destroy method called incorrectly").isFalse(); } @Test public void lifecycleMethodsDisabled() throws Exception { LifecycleAwareBean bean = (LifecycleAwareBean) this.beanFactory.getBean("lifecycleMethodsDisabled"); - assertFalse("Bean init method called incorrectly", bean.isInitCalled()); - assertFalse("Custom init method called incorrectly", bean.isCustomInitCalled()); + assertThat(bean.isInitCalled()).as("Bean init method called incorrectly").isFalse(); + assertThat(bean.isCustomInitCalled()).as("Custom init method called incorrectly").isFalse(); this.beanFactory.destroySingletons(); - assertFalse("Bean destroy method called incorrectly", bean.isDestroyCalled()); - assertFalse("Custom destroy method called incorrectly", bean.isCustomDestroyCalled()); + assertThat(bean.isDestroyCalled()).as("Bean destroy method called incorrectly").isFalse(); + assertThat(bean.isCustomDestroyCalled()).as("Custom destroy method called incorrectly").isFalse(); } @Test @@ -74,32 +73,32 @@ public class DefaultLifecycleMethodsTests { @Test public void overrideDefaultLifecycleMethods() throws Exception { LifecycleAwareBean bean = (LifecycleAwareBean) this.beanFactory.getBean("overrideLifecycleMethods"); - assertFalse("Default init method called incorrectly", bean.isInitCalled()); - assertTrue("Custom init method not called", bean.isCustomInitCalled()); + assertThat(bean.isInitCalled()).as("Default init method called incorrectly").isFalse(); + assertThat(bean.isCustomInitCalled()).as("Custom init method not called").isTrue(); this.beanFactory.destroySingletons(); - assertFalse("Default destroy method called incorrectly", bean.isDestroyCalled()); - assertTrue("Custom destroy method not called", bean.isCustomDestroyCalled()); + assertThat(bean.isDestroyCalled()).as("Default destroy method called incorrectly").isFalse(); + assertThat(bean.isCustomDestroyCalled()).as("Custom destroy method not called").isTrue(); } @Test public void childWithDefaultLifecycleMethods() throws Exception { LifecycleAwareBean bean = (LifecycleAwareBean) this.beanFactory.getBean("childWithDefaultLifecycleMethods"); - assertTrue("Bean not initialized", bean.isInitCalled()); - assertFalse("Custom init method called incorrectly", bean.isCustomInitCalled()); - assertFalse("Bean destroyed too early", bean.isDestroyCalled()); + assertThat(bean.isInitCalled()).as("Bean not initialized").isTrue(); + assertThat(bean.isCustomInitCalled()).as("Custom init method called incorrectly").isFalse(); + assertThat(bean.isDestroyCalled()).as("Bean destroyed too early").isFalse(); this.beanFactory.destroySingletons(); - assertTrue("Bean not destroyed", bean.isDestroyCalled()); - assertFalse("Custom destroy method called incorrectly", bean.isCustomDestroyCalled()); + assertThat(bean.isDestroyCalled()).as("Bean not destroyed").isTrue(); + assertThat(bean.isCustomDestroyCalled()).as("Custom destroy method called incorrectly").isFalse(); } @Test public void childWithLifecycleMethodsDisabled() throws Exception { LifecycleAwareBean bean = (LifecycleAwareBean) this.beanFactory.getBean("childWithLifecycleMethodsDisabled"); - assertFalse("Bean init method called incorrectly", bean.isInitCalled()); - assertFalse("Custom init method called incorrectly", bean.isCustomInitCalled()); + assertThat(bean.isInitCalled()).as("Bean init method called incorrectly").isFalse(); + assertThat(bean.isCustomInitCalled()).as("Custom init method called incorrectly").isFalse(); this.beanFactory.destroySingletons(); - assertFalse("Bean destroy method called incorrectly", bean.isDestroyCalled()); - assertFalse("Custom destroy method called incorrectly", bean.isCustomDestroyCalled()); + assertThat(bean.isDestroyCalled()).as("Bean destroy method called incorrectly").isFalse(); + assertThat(bean.isCustomDestroyCalled()).as("Custom destroy method called incorrectly").isFalse(); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java index 52488e6ad2a..8a81d9ed95e 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java @@ -33,8 +33,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.beans.CollectingReaderEventListener; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -60,66 +59,72 @@ public class EventPublicationTests { @Test public void defaultsEventReceived() throws Exception { List defaultsList = this.eventListener.getDefaults(); - assertTrue(!defaultsList.isEmpty()); - assertTrue(defaultsList.get(0) instanceof DocumentDefaultsDefinition); + boolean condition2 = !defaultsList.isEmpty(); + assertThat(condition2).isTrue(); + boolean condition1 = defaultsList.get(0) instanceof DocumentDefaultsDefinition; + assertThat(condition1).isTrue(); DocumentDefaultsDefinition defaults = (DocumentDefaultsDefinition) defaultsList.get(0); - assertEquals("true", defaults.getLazyInit()); - assertEquals("constructor", defaults.getAutowire()); - assertEquals("myInit", defaults.getInitMethod()); - assertEquals("myDestroy", defaults.getDestroyMethod()); - assertEquals("true", defaults.getMerge()); - assertTrue(defaults.getSource() instanceof Element); + assertThat(defaults.getLazyInit()).isEqualTo("true"); + assertThat(defaults.getAutowire()).isEqualTo("constructor"); + assertThat(defaults.getInitMethod()).isEqualTo("myInit"); + assertThat(defaults.getDestroyMethod()).isEqualTo("myDestroy"); + assertThat(defaults.getMerge()).isEqualTo("true"); + boolean condition = defaults.getSource() instanceof Element; + assertThat(condition).isTrue(); } @Test public void beanEventReceived() throws Exception { ComponentDefinition componentDefinition1 = this.eventListener.getComponentDefinition("testBean"); - assertTrue(componentDefinition1 instanceof BeanComponentDefinition); - assertEquals(1, componentDefinition1.getBeanDefinitions().length); + boolean condition3 = componentDefinition1 instanceof BeanComponentDefinition; + assertThat(condition3).isTrue(); + assertThat(componentDefinition1.getBeanDefinitions().length).isEqualTo(1); BeanDefinition beanDefinition1 = componentDefinition1.getBeanDefinitions()[0]; - assertEquals(new TypedStringValue("Rob Harrop"), - beanDefinition1.getConstructorArgumentValues().getGenericArgumentValue(String.class).getValue()); - assertEquals(1, componentDefinition1.getBeanReferences().length); - assertEquals("testBean2", componentDefinition1.getBeanReferences()[0].getBeanName()); - assertEquals(1, componentDefinition1.getInnerBeanDefinitions().length); + assertThat(beanDefinition1.getConstructorArgumentValues().getGenericArgumentValue(String.class).getValue()).isEqualTo(new TypedStringValue("Rob Harrop")); + assertThat(componentDefinition1.getBeanReferences().length).isEqualTo(1); + assertThat(componentDefinition1.getBeanReferences()[0].getBeanName()).isEqualTo("testBean2"); + assertThat(componentDefinition1.getInnerBeanDefinitions().length).isEqualTo(1); BeanDefinition innerBd1 = componentDefinition1.getInnerBeanDefinitions()[0]; - assertEquals(new TypedStringValue("ACME"), - innerBd1.getConstructorArgumentValues().getGenericArgumentValue(String.class).getValue()); - assertTrue(componentDefinition1.getSource() instanceof Element); + assertThat(innerBd1.getConstructorArgumentValues().getGenericArgumentValue(String.class).getValue()).isEqualTo(new TypedStringValue("ACME")); + boolean condition2 = componentDefinition1.getSource() instanceof Element; + assertThat(condition2).isTrue(); ComponentDefinition componentDefinition2 = this.eventListener.getComponentDefinition("testBean2"); - assertTrue(componentDefinition2 instanceof BeanComponentDefinition); - assertEquals(1, componentDefinition1.getBeanDefinitions().length); + boolean condition1 = componentDefinition2 instanceof BeanComponentDefinition; + assertThat(condition1).isTrue(); + assertThat(componentDefinition1.getBeanDefinitions().length).isEqualTo(1); BeanDefinition beanDefinition2 = componentDefinition2.getBeanDefinitions()[0]; - assertEquals(new TypedStringValue("Juergen Hoeller"), - beanDefinition2.getPropertyValues().getPropertyValue("name").getValue()); - assertEquals(0, componentDefinition2.getBeanReferences().length); - assertEquals(1, componentDefinition2.getInnerBeanDefinitions().length); + assertThat(beanDefinition2.getPropertyValues().getPropertyValue("name").getValue()).isEqualTo(new TypedStringValue("Juergen Hoeller")); + assertThat(componentDefinition2.getBeanReferences().length).isEqualTo(0); + assertThat(componentDefinition2.getInnerBeanDefinitions().length).isEqualTo(1); BeanDefinition innerBd2 = componentDefinition2.getInnerBeanDefinitions()[0]; - assertEquals(new TypedStringValue("Eva Schallmeiner"), - innerBd2.getPropertyValues().getPropertyValue("name").getValue()); - assertTrue(componentDefinition2.getSource() instanceof Element); + assertThat(innerBd2.getPropertyValues().getPropertyValue("name").getValue()).isEqualTo(new TypedStringValue("Eva Schallmeiner")); + boolean condition = componentDefinition2.getSource() instanceof Element; + assertThat(condition).isTrue(); } @Test public void aliasEventReceived() throws Exception { List aliases = this.eventListener.getAliases("testBean"); - assertEquals(2, aliases.size()); + assertThat(aliases.size()).isEqualTo(2); AliasDefinition aliasDefinition1 = (AliasDefinition) aliases.get(0); - assertEquals("testBeanAlias1", aliasDefinition1.getAlias()); - assertTrue(aliasDefinition1.getSource() instanceof Element); + assertThat(aliasDefinition1.getAlias()).isEqualTo("testBeanAlias1"); + boolean condition1 = aliasDefinition1.getSource() instanceof Element; + assertThat(condition1).isTrue(); AliasDefinition aliasDefinition2 = (AliasDefinition) aliases.get(1); - assertEquals("testBeanAlias2", aliasDefinition2.getAlias()); - assertTrue(aliasDefinition2.getSource() instanceof Element); + assertThat(aliasDefinition2.getAlias()).isEqualTo("testBeanAlias2"); + boolean condition = aliasDefinition2.getSource() instanceof Element; + assertThat(condition).isTrue(); } @Test public void importEventReceived() throws Exception { List imports = this.eventListener.getImports(); - assertEquals(1, imports.size()); + assertThat(imports.size()).isEqualTo(1); ImportDefinition importDefinition = (ImportDefinition) imports.get(0); - assertEquals("beanEventsImported.xml", importDefinition.getImportedResource()); - assertTrue(importDefinition.getSource() instanceof Element); + assertThat(importDefinition.getImportedResource()).isEqualTo("beanEventsImported.xml"); + boolean condition = importDefinition.getSource() instanceof Element; + assertThat(condition).isTrue(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java index 4fa9cf86d3d..225fd27cff8 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java @@ -28,11 +28,8 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -47,31 +44,31 @@ public class FactoryMethodTests { reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); TestBean tb = (TestBean) xbf.getBean("defaultTestBean"); - assertEquals("defaultInstance", tb.getName()); - assertEquals(1, tb.getAge()); + assertThat(tb.getName()).isEqualTo("defaultInstance"); + assertThat(tb.getAge()).isEqualTo(1); FactoryMethods fm = (FactoryMethods) xbf.getBean("default"); - assertEquals(0, fm.getNum()); - assertEquals("default", fm.getName()); - assertEquals("defaultInstance", fm.getTestBean().getName()); - assertEquals("setterString", fm.getStringValue()); + assertThat(fm.getNum()).isEqualTo(0); + assertThat(fm.getName()).isEqualTo("default"); + assertThat(fm.getTestBean().getName()).isEqualTo("defaultInstance"); + assertThat(fm.getStringValue()).isEqualTo("setterString"); fm = (FactoryMethods) xbf.getBean("testBeanOnly"); - assertEquals(0, fm.getNum()); - assertEquals("default", fm.getName()); + assertThat(fm.getNum()).isEqualTo(0); + assertThat(fm.getName()).isEqualTo("default"); // This comes from the test bean - assertEquals("Juergen", fm.getTestBean().getName()); + assertThat(fm.getTestBean().getName()).isEqualTo("Juergen"); fm = (FactoryMethods) xbf.getBean("full"); - assertEquals(27, fm.getNum()); - assertEquals("gotcha", fm.getName()); - assertEquals("Juergen", fm.getTestBean().getName()); + assertThat(fm.getNum()).isEqualTo(27); + assertThat(fm.getName()).isEqualTo("gotcha"); + assertThat(fm.getTestBean().getName()).isEqualTo("Juergen"); FactoryMethods fm2 = (FactoryMethods) xbf.getBean("full"); - assertSame(fm, fm2); + assertThat(fm2).isSameAs(fm); xbf.destroySingletons(); - assertTrue(tb.wasDestroyed()); + assertThat(tb.wasDestroyed()).isTrue(); } @Test @@ -89,7 +86,7 @@ public class FactoryMethodTests { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); - assertEquals("null", xbf.getBean("null").toString()); + assertThat(xbf.getBean("null").toString()).isEqualTo("null"); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> xbf.getBean("nullWithProperty")); } @@ -101,19 +98,19 @@ public class FactoryMethodTests { reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); FactoryMethods fm = (FactoryMethods) xbf.getBean("fullWithNull"); - assertEquals(27, fm.getNum()); - assertEquals(null, fm.getName()); - assertEquals("Juergen", fm.getTestBean().getName()); + assertThat(fm.getNum()).isEqualTo(27); + assertThat(fm.getName()).isEqualTo(null); + assertThat(fm.getTestBean().getName()).isEqualTo("Juergen"); fm = (FactoryMethods) xbf.getBean("fullWithGenericNull"); - assertEquals(27, fm.getNum()); - assertEquals(null, fm.getName()); - assertEquals("Juergen", fm.getTestBean().getName()); + assertThat(fm.getNum()).isEqualTo(27); + assertThat(fm.getName()).isEqualTo(null); + assertThat(fm.getTestBean().getName()).isEqualTo("Juergen"); fm = (FactoryMethods) xbf.getBean("fullWithNamedNull"); - assertEquals(27, fm.getNum()); - assertEquals(null, fm.getName()); - assertEquals("Juergen", fm.getTestBean().getName()); + assertThat(fm.getNum()).isEqualTo(27); + assertThat(fm.getName()).isEqualTo(null); + assertThat(fm.getTestBean().getName()).isEqualTo("Juergen"); } @Test @@ -123,9 +120,9 @@ public class FactoryMethodTests { reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); FactoryMethods fm = (FactoryMethods) xbf.getBean("fullWithAutowire"); - assertEquals(27, fm.getNum()); - assertEquals("gotchaAutowired", fm.getName()); - assertEquals("Juergen", fm.getTestBean().getName()); + assertThat(fm.getNum()).isEqualTo(27); + assertThat(fm.getName()).isEqualTo("gotchaAutowired"); + assertThat(fm.getTestBean().getName()).isEqualTo("Juergen"); } @Test @@ -135,7 +132,7 @@ public class FactoryMethodTests { reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); TestBean tb = (TestBean) xbf.getBean("defaultTestBean.protected"); - assertEquals(1, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(1); } @Test @@ -145,7 +142,7 @@ public class FactoryMethodTests { reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); TestBean tb = (TestBean) xbf.getBean("defaultTestBean.private"); - assertEquals(1, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(1); } @Test @@ -155,38 +152,38 @@ public class FactoryMethodTests { reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); FactoryMethods fm = (FactoryMethods) xbf.getBean("defaultPrototype"); FactoryMethods fm2 = (FactoryMethods) xbf.getBean("defaultPrototype"); - assertEquals(0, fm.getNum()); - assertEquals("default", fm.getName()); - assertEquals("defaultInstance", fm.getTestBean().getName()); - assertEquals("setterString", fm.getStringValue()); - assertEquals(fm.getNum(), fm2.getNum()); - assertEquals(fm.getStringValue(), fm2.getStringValue()); + assertThat(fm.getNum()).isEqualTo(0); + assertThat(fm.getName()).isEqualTo("default"); + assertThat(fm.getTestBean().getName()).isEqualTo("defaultInstance"); + assertThat(fm.getStringValue()).isEqualTo("setterString"); + assertThat(fm2.getNum()).isEqualTo(fm.getNum()); + assertThat(fm2.getStringValue()).isEqualTo(fm.getStringValue()); // The TestBean is created separately for each bean - assertNotSame(fm.getTestBean(), fm2.getTestBean()); - assertNotSame(fm, fm2); + assertThat(fm2.getTestBean()).isNotSameAs(fm.getTestBean()); + assertThat(fm2).isNotSameAs(fm); fm = (FactoryMethods) xbf.getBean("testBeanOnlyPrototype"); fm2 = (FactoryMethods) xbf.getBean("testBeanOnlyPrototype"); - assertEquals(0, fm.getNum()); - assertEquals("default", fm.getName()); + assertThat(fm.getNum()).isEqualTo(0); + assertThat(fm.getName()).isEqualTo("default"); // This comes from the test bean - assertEquals("Juergen", fm.getTestBean().getName()); - assertEquals(fm.getNum(), fm2.getNum()); - assertEquals(fm.getStringValue(), fm2.getStringValue()); + assertThat(fm.getTestBean().getName()).isEqualTo("Juergen"); + assertThat(fm2.getNum()).isEqualTo(fm.getNum()); + assertThat(fm2.getStringValue()).isEqualTo(fm.getStringValue()); // The TestBean reference is resolved to a prototype in the factory - assertSame(fm.getTestBean(), fm2.getTestBean()); - assertNotSame(fm, fm2); + assertThat(fm2.getTestBean()).isSameAs(fm.getTestBean()); + assertThat(fm2).isNotSameAs(fm); fm = (FactoryMethods) xbf.getBean("fullPrototype"); fm2 = (FactoryMethods) xbf.getBean("fullPrototype"); - assertEquals(27, fm.getNum()); - assertEquals("gotcha", fm.getName()); - assertEquals("Juergen", fm.getTestBean().getName()); - assertEquals(fm.getNum(), fm2.getNum()); - assertEquals(fm.getStringValue(), fm2.getStringValue()); + assertThat(fm.getNum()).isEqualTo(27); + assertThat(fm.getName()).isEqualTo("gotcha"); + assertThat(fm.getTestBean().getName()).isEqualTo("Juergen"); + assertThat(fm2.getNum()).isEqualTo(fm.getNum()); + assertThat(fm2.getStringValue()).isEqualTo(fm.getStringValue()); // The TestBean reference is resolved to a prototype in the factory - assertSame(fm.getTestBean(), fm2.getTestBean()); - assertNotSame(fm, fm2); + assertThat(fm2.getTestBean()).isSameAs(fm.getTestBean()); + assertThat(fm2).isNotSameAs(fm); } /** @@ -198,24 +195,24 @@ public class FactoryMethodTests { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); - assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithoutArgs")); - assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithArgs")); + assertThat(xbf.getType("externalFactoryMethodWithoutArgs")).isEqualTo(TestBean.class); + assertThat(xbf.getType("externalFactoryMethodWithArgs")).isEqualTo(TestBean.class); String[] names = xbf.getBeanNamesForType(TestBean.class); - assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithoutArgs")); - assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithArgs")); + assertThat(Arrays.asList(names).contains("externalFactoryMethodWithoutArgs")).isTrue(); + assertThat(Arrays.asList(names).contains("externalFactoryMethodWithArgs")).isTrue(); TestBean tb = (TestBean) xbf.getBean("externalFactoryMethodWithoutArgs"); - assertEquals(2, tb.getAge()); - assertEquals("Tristan", tb.getName()); + assertThat(tb.getAge()).isEqualTo(2); + assertThat(tb.getName()).isEqualTo("Tristan"); tb = (TestBean) xbf.getBean("externalFactoryMethodWithArgs"); - assertEquals(33, tb.getAge()); - assertEquals("Rod", tb.getName()); + assertThat(tb.getAge()).isEqualTo(33); + assertThat(tb.getName()).isEqualTo("Rod"); - assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithoutArgs")); - assertEquals(TestBean.class, xbf.getType("externalFactoryMethodWithArgs")); + assertThat(xbf.getType("externalFactoryMethodWithoutArgs")).isEqualTo(TestBean.class); + assertThat(xbf.getType("externalFactoryMethodWithArgs")).isEqualTo(TestBean.class); names = xbf.getBeanNamesForType(TestBean.class); - assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithoutArgs")); - assertTrue(Arrays.asList(names).contains("externalFactoryMethodWithArgs")); + assertThat(Arrays.asList(names).contains("externalFactoryMethodWithoutArgs")).isTrue(); + assertThat(Arrays.asList(names).contains("externalFactoryMethodWithArgs")).isTrue(); } @Test @@ -226,14 +223,14 @@ public class FactoryMethodTests { InstanceFactory.count = 0; xbf.preInstantiateSingletons(); - assertEquals(1, InstanceFactory.count); + assertThat(InstanceFactory.count).isEqualTo(1); FactoryMethods fm = (FactoryMethods) xbf.getBean("instanceFactoryMethodWithoutArgs"); - assertEquals("instanceFactory", fm.getTestBean().getName()); - assertEquals(1, InstanceFactory.count); + assertThat(fm.getTestBean().getName()).isEqualTo("instanceFactory"); + assertThat(InstanceFactory.count).isEqualTo(1); FactoryMethods fm2 = (FactoryMethods) xbf.getBean("instanceFactoryMethodWithoutArgs"); - assertEquals("instanceFactory", fm2.getTestBean().getName()); - assertSame(fm2, fm); - assertEquals(1, InstanceFactory.count); + assertThat(fm2.getTestBean().getName()).isEqualTo("instanceFactory"); + assertThat(fm).isSameAs(fm2); + assertThat(InstanceFactory.count).isEqualTo(1); } @Test @@ -276,29 +273,29 @@ public class FactoryMethodTests { tbArg2.setName("arg2"); FactoryMethods fm1 = (FactoryMethods) xbf.getBean("testBeanOnlyPrototype", tbArg); - assertEquals(0, fm1.getNum()); - assertEquals("default", fm1.getName()); + assertThat(fm1.getNum()).isEqualTo(0); + assertThat(fm1.getName()).isEqualTo("default"); // This comes from the test bean - assertEquals("arg1", fm1.getTestBean().getName()); + assertThat(fm1.getTestBean().getName()).isEqualTo("arg1"); FactoryMethods fm2 = (FactoryMethods) xbf.getBean("testBeanOnlyPrototype", tbArg2); - assertEquals("arg2", fm2.getTestBean().getName()); - assertEquals(fm1.getNum(), fm2.getNum()); - assertEquals(fm2.getStringValue(), "testBeanOnlyPrototypeDISetterString"); - assertEquals(fm2.getStringValue(), fm2.getStringValue()); + assertThat(fm2.getTestBean().getName()).isEqualTo("arg2"); + assertThat(fm2.getNum()).isEqualTo(fm1.getNum()); + assertThat("testBeanOnlyPrototypeDISetterString").isEqualTo(fm2.getStringValue()); + assertThat(fm2.getStringValue()).isEqualTo(fm2.getStringValue()); // The TestBean reference is resolved to a prototype in the factory - assertSame(fm2.getTestBean(), fm2.getTestBean()); - assertNotSame(fm1, fm2); + assertThat(fm2.getTestBean()).isSameAs(fm2.getTestBean()); + assertThat(fm2).isNotSameAs(fm1); FactoryMethods fm3 = (FactoryMethods) xbf.getBean("testBeanOnlyPrototype", tbArg2, new Integer(1), "myName"); - assertEquals(1, fm3.getNum()); - assertEquals("myName", fm3.getName()); - assertEquals("arg2", fm3.getTestBean().getName()); + assertThat(fm3.getNum()).isEqualTo(1); + assertThat(fm3.getName()).isEqualTo("myName"); + assertThat(fm3.getTestBean().getName()).isEqualTo("arg2"); FactoryMethods fm4 = (FactoryMethods) xbf.getBean("testBeanOnlyPrototype", tbArg); - assertEquals(0, fm4.getNum()); - assertEquals("default", fm4.getName()); - assertEquals("arg1", fm4.getTestBean().getName()); + assertThat(fm4.getNum()).isEqualTo(0); + assertThat(fm4.getName()).isEqualTo("default"); + assertThat(fm4.getTestBean().getName()).isEqualTo("arg1"); } @Test @@ -310,10 +307,10 @@ public class FactoryMethodTests { // First getBean call triggers actual creation of the singleton bean TestBean tb = new TestBean(); FactoryMethods fm1 = (FactoryMethods) xbf.getBean("testBeanOnly", tb); - assertSame(tb, fm1.getTestBean()); + assertThat(fm1.getTestBean()).isSameAs(tb); FactoryMethods fm2 = (FactoryMethods) xbf.getBean("testBeanOnly", new TestBean()); - assertSame(fm1, fm2); - assertSame(tb, fm2.getTestBean()); + assertThat(fm2).isSameAs(fm1); + assertThat(fm2.getTestBean()).isSameAs(tb); } @Test @@ -326,8 +323,8 @@ public class FactoryMethodTests { FactoryMethods fm1 = (FactoryMethods) xbf.getBean("testBeanOnly"); TestBean tb = fm1.getTestBean(); FactoryMethods fm2 = (FactoryMethods) xbf.getBean("testBeanOnly", new TestBean()); - assertSame(fm1, fm2); - assertSame(tb, fm2.getTestBean()); + assertThat(fm2).isSameAs(fm1); + assertThat(fm2.getTestBean()).isSameAs(tb); } @Test @@ -337,20 +334,22 @@ public class FactoryMethodTests { reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); // Check that listInstance is not considered a bean of type FactoryMethods. - assertTrue(List.class.isAssignableFrom(xbf.getType("listInstance"))); + assertThat(List.class.isAssignableFrom(xbf.getType("listInstance"))).isTrue(); String[] names = xbf.getBeanNamesForType(FactoryMethods.class); - assertTrue(!Arrays.asList(names).contains("listInstance")); + boolean condition1 = !Arrays.asList(names).contains("listInstance"); + assertThat(condition1).isTrue(); names = xbf.getBeanNamesForType(List.class); - assertTrue(Arrays.asList(names).contains("listInstance")); + assertThat(Arrays.asList(names).contains("listInstance")).isTrue(); xbf.preInstantiateSingletons(); - assertTrue(List.class.isAssignableFrom(xbf.getType("listInstance"))); + assertThat(List.class.isAssignableFrom(xbf.getType("listInstance"))).isTrue(); names = xbf.getBeanNamesForType(FactoryMethods.class); - assertTrue(!Arrays.asList(names).contains("listInstance")); + boolean condition = !Arrays.asList(names).contains("listInstance"); + assertThat(condition).isTrue(); names = xbf.getBeanNamesForType(List.class); - assertTrue(Arrays.asList(names).contains("listInstance")); + assertThat(Arrays.asList(names).contains("listInstance")).isTrue(); List list = (List) xbf.getBean("listInstance"); - assertEquals(Collections.EMPTY_LIST, list); + assertThat(list).isEqualTo(Collections.EMPTY_LIST); } @Test @@ -360,8 +359,8 @@ public class FactoryMethodTests { reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass())); MailSession session = (MailSession) xbf.getBean("javaMailSession"); - assertEquals("someuser", session.getProperty("mail.smtp.user")); - assertEquals("somepw", session.getProperty("mail.smtp.password")); + assertThat(session.getProperty("mail.smtp.user")).isEqualTo("someuser"); + assertThat(session.getProperty("mail.smtp.password")).isEqualTo("somepw"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/MetadataAttachmentTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/MetadataAttachmentTests.java index 0d31a571bab..ec804238332 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/MetadataAttachmentTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/MetadataAttachmentTests.java @@ -24,7 +24,7 @@ import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -44,21 +44,21 @@ public class MetadataAttachmentTests { @Test public void metadataAttachment() throws Exception { BeanDefinition beanDefinition1 = this.beanFactory.getMergedBeanDefinition("testBean1"); - assertEquals("bar", beanDefinition1.getAttribute("foo")); + assertThat(beanDefinition1.getAttribute("foo")).isEqualTo("bar"); } @Test public void metadataIsInherited() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getMergedBeanDefinition("testBean2"); - assertEquals("Metadata not inherited", "bar", beanDefinition.getAttribute("foo")); - assertEquals("Child metdata not attached", "123", beanDefinition.getAttribute("abc")); + assertThat(beanDefinition.getAttribute("foo")).as("Metadata not inherited").isEqualTo("bar"); + assertThat(beanDefinition.getAttribute("abc")).as("Child metdata not attached").isEqualTo("123"); } @Test public void propertyMetadata() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getMergedBeanDefinition("testBean3"); PropertyValue pv = beanDefinition.getPropertyValues().getPropertyValue("name"); - assertEquals("Harrop", pv.getAttribute("surname")); + assertThat(pv.getAttribute("surname")).isEqualTo("Harrop"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java index 848ab75a8cc..9520203f5a0 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java @@ -24,9 +24,8 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * @author Rob Harrop @@ -60,8 +59,8 @@ public class SchemaValidationTests { reader.loadBeanDefinitions(new ClassPathResource("schemaValidated.xml", getClass())); TestBean foo = (TestBean) bf.getBean("fooBean"); - assertNotNull("Spouse is null", foo.getSpouse()); - assertEquals("Incorrect number of friends", 2, foo.getFriends().size()); + assertThat(foo.getSpouse()).as("Spouse is null").isNotNull(); + assertThat(foo.getFriends().size()).as("Incorrect number of friends").isEqualTo(2); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java index 8a6505345d4..085050cb283 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java @@ -24,8 +24,8 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.DummyBean; 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.junit.Assert.assertEquals; /** * @author Costin Leau @@ -38,7 +38,7 @@ public class SimpleConstructorNamespaceHandlerTests { String name = "simple"; // beanFactory.getBean("simple1", DummyBean.class); DummyBean nameValue = beanFactory.getBean(name, DummyBean.class); - assertEquals("simple", nameValue.getValue()); + assertThat(nameValue.getValue()).isEqualTo("simple"); } @Test @@ -47,7 +47,7 @@ public class SimpleConstructorNamespaceHandlerTests { String name = "simple-ref"; // beanFactory.getBean("name-value1", TestBean.class); DummyBean nameValue = beanFactory.getBean(name, DummyBean.class); - assertEquals(beanFactory.getBean("name"), nameValue.getValue()); + assertThat(nameValue.getValue()).isEqualTo(beanFactory.getBean("name")); } @Test @@ -56,8 +56,8 @@ public class SimpleConstructorNamespaceHandlerTests { String name = "name-value"; // beanFactory.getBean("name-value1", TestBean.class); TestBean nameValue = beanFactory.getBean(name, TestBean.class); - assertEquals(name, nameValue.getName()); - assertEquals(10, nameValue.getAge()); + assertThat(nameValue.getName()).isEqualTo(name); + assertThat(nameValue.getAge()).isEqualTo(10); } @Test @@ -66,8 +66,8 @@ public class SimpleConstructorNamespaceHandlerTests { TestBean nameValue = beanFactory.getBean("name-value", TestBean.class); DummyBean nameRef = beanFactory.getBean("name-ref", DummyBean.class); - assertEquals("some-name", nameRef.getName()); - assertEquals(nameValue, nameRef.getSpouse()); + assertThat(nameRef.getName()).isEqualTo("some-name"); + assertThat(nameRef.getSpouse()).isEqualTo(nameValue); } @Test @@ -75,9 +75,9 @@ public class SimpleConstructorNamespaceHandlerTests { DefaultListableBeanFactory beanFactory = createFactory("simpleConstructorNamespaceHandlerTests.xml"); DummyBean typeRef = beanFactory.getBean("indexed-value", DummyBean.class); - assertEquals("at", typeRef.getName()); - assertEquals("austria", typeRef.getValue()); - assertEquals(10, typeRef.getAge()); + assertThat(typeRef.getName()).isEqualTo("at"); + assertThat(typeRef.getValue()).isEqualTo("austria"); + assertThat(typeRef.getAge()).isEqualTo(10); } @Test @@ -85,8 +85,8 @@ public class SimpleConstructorNamespaceHandlerTests { DefaultListableBeanFactory beanFactory = createFactory("simpleConstructorNamespaceHandlerTests.xml"); DummyBean typeRef = beanFactory.getBean("indexed-ref", DummyBean.class); - assertEquals("some-name", typeRef.getName()); - assertEquals(beanFactory.getBean("name-value"), typeRef.getSpouse()); + assertThat(typeRef.getName()).isEqualTo("some-name"); + assertThat(typeRef.getSpouse()).isEqualTo(beanFactory.getBean("name-value")); } @Test @@ -101,8 +101,8 @@ public class SimpleConstructorNamespaceHandlerTests { public void constructorWithNameEndingInRef() throws Exception { DefaultListableBeanFactory beanFactory = createFactory("simpleConstructorNamespaceHandlerTests.xml"); DummyBean derivedBean = beanFactory.getBean("beanWithRefConstructorArg", DummyBean.class); - assertEquals(10, derivedBean.getAge()); - assertEquals("silly name", derivedBean.getName()); + assertThat(derivedBean.getAge()).isEqualTo(10); + assertThat(derivedBean.getName()).isEqualTo("silly name"); } private DefaultListableBeanFactory createFactory(String resourceName) { diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java index 09ae66a0f1d..0d4626569c1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java @@ -24,8 +24,8 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.ITestBean; 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.junit.Assert.assertEquals; /** * @author Rob Harrop @@ -41,9 +41,9 @@ public class SimplePropertyNamespaceHandlerTests { new ClassPathResource("simplePropertyNamespaceHandlerTests.xml", getClass())); ITestBean rob = (TestBean) beanFactory.getBean("rob"); ITestBean sally = (TestBean) beanFactory.getBean("sally"); - assertEquals("Rob Harrop", rob.getName()); - assertEquals(24, rob.getAge()); - assertEquals(rob.getSpouse(), sally); + assertThat(rob.getName()).isEqualTo("Rob Harrop"); + assertThat(rob.getAge()).isEqualTo(24); + assertThat(sally).isEqualTo(rob.getSpouse()); } @Test @@ -53,9 +53,9 @@ public class SimplePropertyNamespaceHandlerTests { new ClassPathResource("simplePropertyNamespaceHandlerTests.xml", getClass())); TestBean sally = (TestBean) beanFactory.getBean("sally2"); ITestBean rob = sally.getSpouse(); - assertEquals("Rob Harrop", rob.getName()); - assertEquals(24, rob.getAge()); - assertEquals(rob.getSpouse(), sally); + assertThat(rob.getName()).isEqualTo("Rob Harrop"); + assertThat(rob.getAge()).isEqualTo(24); + assertThat(sally).isEqualTo(rob.getSpouse()); } @Test @@ -72,7 +72,7 @@ public class SimplePropertyNamespaceHandlerTests { new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions( new ClassPathResource("simplePropertyNamespaceHandlerTests.xml", getClass())); ITestBean sally = (TestBean) beanFactory.getBean("derivedSally"); - assertEquals("r", sally.getSpouse().getName()); + assertThat(sally.getSpouse().getName()).isEqualTo("r"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/UtilNamespaceHandlerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/UtilNamespaceHandlerTests.java index 6791903d4b3..e95d46d7d67 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/UtilNamespaceHandlerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/UtilNamespaceHandlerTests.java @@ -38,10 +38,7 @@ import org.springframework.tests.sample.beans.CustomEnum; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.LinkedCaseInsensitiveMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -68,110 +65,112 @@ public class UtilNamespaceHandlerTests { @Test public void testConstant() { Integer min = (Integer) this.beanFactory.getBean("min"); - assertEquals(Integer.MIN_VALUE, min.intValue()); + assertThat(min.intValue()).isEqualTo(Integer.MIN_VALUE); } @Test public void testConstantWithDefaultName() { Integer max = (Integer) this.beanFactory.getBean("java.lang.Integer.MAX_VALUE"); - assertEquals(Integer.MAX_VALUE, max.intValue()); + assertThat(max.intValue()).isEqualTo(Integer.MAX_VALUE); } @Test public void testEvents() { ComponentDefinition propertiesComponent = this.listener.getComponentDefinition("myProperties"); - assertNotNull("Event for 'myProperties' not sent", propertiesComponent); + assertThat(propertiesComponent).as("Event for 'myProperties' not sent").isNotNull(); AbstractBeanDefinition propertiesBean = (AbstractBeanDefinition) propertiesComponent.getBeanDefinitions()[0]; - assertEquals("Incorrect BeanDefinition", PropertiesFactoryBean.class, propertiesBean.getBeanClass()); + assertThat(propertiesBean.getBeanClass()).as("Incorrect BeanDefinition").isEqualTo(PropertiesFactoryBean.class); ComponentDefinition constantComponent = this.listener.getComponentDefinition("min"); - assertNotNull("Event for 'min' not sent", propertiesComponent); + assertThat(propertiesComponent).as("Event for 'min' not sent").isNotNull(); AbstractBeanDefinition constantBean = (AbstractBeanDefinition) constantComponent.getBeanDefinitions()[0]; - assertEquals("Incorrect BeanDefinition", FieldRetrievingFactoryBean.class, constantBean.getBeanClass()); + assertThat(constantBean.getBeanClass()).as("Incorrect BeanDefinition").isEqualTo(FieldRetrievingFactoryBean.class); } @Test public void testNestedProperties() { TestBean bean = (TestBean) this.beanFactory.getBean("testBean"); Properties props = bean.getSomeProperties(); - assertEquals("Incorrect property value", "bar", props.get("foo")); + assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); } @Test public void testPropertyPath() { String name = (String) this.beanFactory.getBean("name"); - assertEquals("Rob Harrop", name); + assertThat(name).isEqualTo("Rob Harrop"); } @Test public void testNestedPropertyPath() { TestBean bean = (TestBean) this.beanFactory.getBean("testBean"); - assertEquals("Rob Harrop", bean.getName()); + assertThat(bean.getName()).isEqualTo("Rob Harrop"); } @Test public void testSimpleMap() { Map map = (Map) this.beanFactory.getBean("simpleMap"); - assertEquals("bar", map.get("foo")); + assertThat(map.get("foo")).isEqualTo("bar"); Map map2 = (Map) this.beanFactory.getBean("simpleMap"); - assertTrue(map == map2); + assertThat(map == map2).isTrue(); } @Test public void testScopedMap() { Map map = (Map) this.beanFactory.getBean("scopedMap"); - assertEquals("bar", map.get("foo")); + assertThat(map.get("foo")).isEqualTo("bar"); Map map2 = (Map) this.beanFactory.getBean("scopedMap"); - assertEquals("bar", map2.get("foo")); - assertTrue(map != map2); + assertThat(map2.get("foo")).isEqualTo("bar"); + assertThat(map != map2).isTrue(); } @Test public void testSimpleList() { List list = (List) this.beanFactory.getBean("simpleList"); - assertEquals("Rob Harrop", list.get(0)); + assertThat(list.get(0)).isEqualTo("Rob Harrop"); List list2 = (List) this.beanFactory.getBean("simpleList"); - assertTrue(list == list2); + assertThat(list == list2).isTrue(); } @Test public void testScopedList() { List list = (List) this.beanFactory.getBean("scopedList"); - assertEquals("Rob Harrop", list.get(0)); + assertThat(list.get(0)).isEqualTo("Rob Harrop"); List list2 = (List) this.beanFactory.getBean("scopedList"); - assertEquals("Rob Harrop", list2.get(0)); - assertTrue(list != list2); + assertThat(list2.get(0)).isEqualTo("Rob Harrop"); + assertThat(list != list2).isTrue(); } @Test public void testSimpleSet() { Set set = (Set) this.beanFactory.getBean("simpleSet"); - assertTrue(set.contains("Rob Harrop")); + assertThat(set.contains("Rob Harrop")).isTrue(); Set set2 = (Set) this.beanFactory.getBean("simpleSet"); - assertTrue(set == set2); + assertThat(set == set2).isTrue(); } @Test public void testScopedSet() { Set set = (Set) this.beanFactory.getBean("scopedSet"); - assertTrue(set.contains("Rob Harrop")); + assertThat(set.contains("Rob Harrop")).isTrue(); Set set2 = (Set) this.beanFactory.getBean("scopedSet"); - assertTrue(set2.contains("Rob Harrop")); - assertTrue(set != set2); + assertThat(set2.contains("Rob Harrop")).isTrue(); + assertThat(set != set2).isTrue(); } @Test public void testMapWithRef() { Map map = (Map) this.beanFactory.getBean("mapWithRef"); - assertTrue(map instanceof TreeMap); - assertEquals(this.beanFactory.getBean("testBean"), map.get("bean")); + boolean condition = map instanceof TreeMap; + assertThat(condition).isTrue(); + assertThat(map.get("bean")).isEqualTo(this.beanFactory.getBean("testBean")); } @Test public void testMapWithTypes() { Map map = (Map) this.beanFactory.getBean("mapWithTypes"); - assertTrue(map instanceof LinkedCaseInsensitiveMap); - assertEquals(this.beanFactory.getBean("testBean"), map.get("bean")); + boolean condition = map instanceof LinkedCaseInsensitiveMap; + assertThat(condition).isTrue(); + assertThat(map.get("bean")).isEqualTo(this.beanFactory.getBean("testBean")); } @Test @@ -179,51 +178,52 @@ public class UtilNamespaceHandlerTests { TestBean bean = (TestBean) this.beanFactory.getBean("nestedCollectionsBean"); List list = bean.getSomeList(); - assertEquals(1, list.size()); - assertEquals("foo", list.get(0)); + assertThat(list.size()).isEqualTo(1); + assertThat(list.get(0)).isEqualTo("foo"); Set set = bean.getSomeSet(); - assertEquals(1, set.size()); - assertTrue(set.contains("bar")); + assertThat(set.size()).isEqualTo(1); + assertThat(set.contains("bar")).isTrue(); Map map = bean.getSomeMap(); - assertEquals(1, map.size()); - assertTrue(map.get("foo") instanceof Set); + assertThat(map.size()).isEqualTo(1); + boolean condition = map.get("foo") instanceof Set; + assertThat(condition).isTrue(); Set innerSet = (Set) map.get("foo"); - assertEquals(1, innerSet.size()); - assertTrue(innerSet.contains("bar")); + assertThat(innerSet.size()).isEqualTo(1); + assertThat(innerSet.contains("bar")).isTrue(); TestBean bean2 = (TestBean) this.beanFactory.getBean("nestedCollectionsBean"); - assertEquals(list, bean2.getSomeList()); - assertEquals(set, bean2.getSomeSet()); - assertEquals(map, bean2.getSomeMap()); - assertFalse(list == bean2.getSomeList()); - assertFalse(set == bean2.getSomeSet()); - assertFalse(map == bean2.getSomeMap()); + assertThat(bean2.getSomeList()).isEqualTo(list); + assertThat(bean2.getSomeSet()).isEqualTo(set); + assertThat(bean2.getSomeMap()).isEqualTo(map); + assertThat(list == bean2.getSomeList()).isFalse(); + assertThat(set == bean2.getSomeSet()).isFalse(); + assertThat(map == bean2.getSomeMap()).isFalse(); } @Test public void testNestedShortcutCollections() { TestBean bean = (TestBean) this.beanFactory.getBean("nestedShortcutCollections"); - assertEquals(1, bean.getStringArray().length); - assertEquals("fooStr", bean.getStringArray()[0]); + assertThat(bean.getStringArray().length).isEqualTo(1); + assertThat(bean.getStringArray()[0]).isEqualTo("fooStr"); List list = bean.getSomeList(); - assertEquals(1, list.size()); - assertEquals("foo", list.get(0)); + assertThat(list.size()).isEqualTo(1); + assertThat(list.get(0)).isEqualTo("foo"); Set set = bean.getSomeSet(); - assertEquals(1, set.size()); - assertTrue(set.contains("bar")); + assertThat(set.size()).isEqualTo(1); + assertThat(set.contains("bar")).isTrue(); TestBean bean2 = (TestBean) this.beanFactory.getBean("nestedShortcutCollections"); - assertTrue(Arrays.equals(bean.getStringArray(), bean2.getStringArray())); - assertFalse(bean.getStringArray() == bean2.getStringArray()); - assertEquals(list, bean2.getSomeList()); - assertEquals(set, bean2.getSomeSet()); - assertFalse(list == bean2.getSomeList()); - assertFalse(set == bean2.getSomeSet()); + assertThat(Arrays.equals(bean.getStringArray(), bean2.getStringArray())).isTrue(); + assertThat(bean.getStringArray() == bean2.getStringArray()).isFalse(); + assertThat(bean2.getSomeList()).isEqualTo(list); + assertThat(bean2.getSomeSet()).isEqualTo(set); + assertThat(list == bean2.getSomeList()).isFalse(); + assertThat(set == bean2.getSomeSet()).isFalse(); } @Test @@ -231,25 +231,25 @@ public class UtilNamespaceHandlerTests { TestBean bean = (TestBean) this.beanFactory.getBean("nestedCustomTagBean"); List list = bean.getSomeList(); - assertEquals(1, list.size()); - assertEquals(Integer.MIN_VALUE, list.get(0)); + assertThat(list.size()).isEqualTo(1); + assertThat(list.get(0)).isEqualTo(Integer.MIN_VALUE); Set set = bean.getSomeSet(); - assertEquals(2, set.size()); - assertTrue(set.contains(Thread.State.NEW)); - assertTrue(set.contains(Thread.State.RUNNABLE)); + assertThat(set.size()).isEqualTo(2); + assertThat(set.contains(Thread.State.NEW)).isTrue(); + assertThat(set.contains(Thread.State.RUNNABLE)).isTrue(); Map map = bean.getSomeMap(); - assertEquals(1, map.size()); - assertEquals(CustomEnum.VALUE_1, map.get("min")); + assertThat(map.size()).isEqualTo(1); + assertThat(map.get("min")).isEqualTo(CustomEnum.VALUE_1); TestBean bean2 = (TestBean) this.beanFactory.getBean("nestedCustomTagBean"); - assertEquals(list, bean2.getSomeList()); - assertEquals(set, bean2.getSomeSet()); - assertEquals(map, bean2.getSomeMap()); - assertFalse(list == bean2.getSomeList()); - assertFalse(set == bean2.getSomeSet()); - assertFalse(map == bean2.getSomeMap()); + assertThat(bean2.getSomeList()).isEqualTo(list); + assertThat(bean2.getSomeSet()).isEqualTo(set); + assertThat(bean2.getSomeMap()).isEqualTo(map); + assertThat(list == bean2.getSomeList()).isFalse(); + assertThat(set == bean2.getSomeSet()).isFalse(); + assertThat(map == bean2.getSomeMap()).isFalse(); } @Test @@ -257,16 +257,16 @@ public class UtilNamespaceHandlerTests { TestBean bean = (TestBean) this.beanFactory.getBean("circularCollectionsBean"); List list = bean.getSomeList(); - assertEquals(1, list.size()); - assertEquals(bean, list.get(0)); + assertThat(list.size()).isEqualTo(1); + assertThat(list.get(0)).isEqualTo(bean); Set set = bean.getSomeSet(); - assertEquals(1, set.size()); - assertTrue(set.contains(bean)); + assertThat(set.size()).isEqualTo(1); + assertThat(set.contains(bean)).isTrue(); Map map = bean.getSomeMap(); - assertEquals(1, map.size()); - assertEquals(bean, map.get("foo")); + assertThat(map.size()).isEqualTo(1); + assertThat(map.get("foo")).isEqualTo(bean); } @Test @@ -275,19 +275,19 @@ public class UtilNamespaceHandlerTests { TestBean bean = (TestBean) this.beanFactory.getBean("circularCollectionBeansBean"); List list = bean.getSomeList(); - assertTrue(Proxy.isProxyClass(list.getClass())); - assertEquals(1, list.size()); - assertEquals(bean, list.get(0)); + assertThat(Proxy.isProxyClass(list.getClass())).isTrue(); + assertThat(list.size()).isEqualTo(1); + assertThat(list.get(0)).isEqualTo(bean); Set set = bean.getSomeSet(); - assertFalse(Proxy.isProxyClass(set.getClass())); - assertEquals(1, set.size()); - assertTrue(set.contains(bean)); + assertThat(Proxy.isProxyClass(set.getClass())).isFalse(); + assertThat(set.size()).isEqualTo(1); + assertThat(set.contains(bean)).isTrue(); Map map = bean.getSomeMap(); - assertFalse(Proxy.isProxyClass(map.getClass())); - assertEquals(1, map.size()); - assertEquals(bean, map.get("foo")); + assertThat(Proxy.isProxyClass(map.getClass())).isFalse(); + assertThat(map.size()).isEqualTo(1); + assertThat(map.get("foo")).isEqualTo(bean); } @Test @@ -296,19 +296,19 @@ public class UtilNamespaceHandlerTests { TestBean bean = (TestBean) this.beanFactory.getBean("circularCollectionBeansBean"); List list = bean.getSomeList(); - assertFalse(Proxy.isProxyClass(list.getClass())); - assertEquals(1, list.size()); - assertEquals(bean, list.get(0)); + assertThat(Proxy.isProxyClass(list.getClass())).isFalse(); + assertThat(list.size()).isEqualTo(1); + assertThat(list.get(0)).isEqualTo(bean); Set set = bean.getSomeSet(); - assertTrue(Proxy.isProxyClass(set.getClass())); - assertEquals(1, set.size()); - assertTrue(set.contains(bean)); + assertThat(Proxy.isProxyClass(set.getClass())).isTrue(); + assertThat(set.size()).isEqualTo(1); + assertThat(set.contains(bean)).isTrue(); Map map = bean.getSomeMap(); - assertFalse(Proxy.isProxyClass(map.getClass())); - assertEquals(1, map.size()); - assertEquals(bean, map.get("foo")); + assertThat(Proxy.isProxyClass(map.getClass())).isFalse(); + assertThat(map.size()).isEqualTo(1); + assertThat(map.get("foo")).isEqualTo(bean); } @Test @@ -317,80 +317,80 @@ public class UtilNamespaceHandlerTests { TestBean bean = (TestBean) this.beanFactory.getBean("circularCollectionBeansBean"); List list = bean.getSomeList(); - assertFalse(Proxy.isProxyClass(list.getClass())); - assertEquals(1, list.size()); - assertEquals(bean, list.get(0)); + assertThat(Proxy.isProxyClass(list.getClass())).isFalse(); + assertThat(list.size()).isEqualTo(1); + assertThat(list.get(0)).isEqualTo(bean); Set set = bean.getSomeSet(); - assertFalse(Proxy.isProxyClass(set.getClass())); - assertEquals(1, set.size()); - assertTrue(set.contains(bean)); + assertThat(Proxy.isProxyClass(set.getClass())).isFalse(); + assertThat(set.size()).isEqualTo(1); + assertThat(set.contains(bean)).isTrue(); Map map = bean.getSomeMap(); - assertTrue(Proxy.isProxyClass(map.getClass())); - assertEquals(1, map.size()); - assertEquals(bean, map.get("foo")); + assertThat(Proxy.isProxyClass(map.getClass())).isTrue(); + assertThat(map.size()).isEqualTo(1); + assertThat(map.get("foo")).isEqualTo(bean); } @Test public void testNestedInConstructor() { TestBean bean = (TestBean) this.beanFactory.getBean("constructedTestBean"); - assertEquals("Rob Harrop", bean.getName()); + assertThat(bean.getName()).isEqualTo("Rob Harrop"); } @Test public void testLoadProperties() { Properties props = (Properties) this.beanFactory.getBean("myProperties"); - assertEquals("Incorrect property value", "bar", props.get("foo")); - assertEquals("Incorrect property value", null, props.get("foo2")); + assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); + assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo(null); Properties props2 = (Properties) this.beanFactory.getBean("myProperties"); - assertTrue(props == props2); + assertThat(props == props2).isTrue(); } @Test public void testScopedProperties() { Properties props = (Properties) this.beanFactory.getBean("myScopedProperties"); - assertEquals("Incorrect property value", "bar", props.get("foo")); - assertEquals("Incorrect property value", null, props.get("foo2")); + assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); + assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo(null); Properties props2 = (Properties) this.beanFactory.getBean("myScopedProperties"); - assertEquals("Incorrect property value", "bar", props.get("foo")); - assertEquals("Incorrect property value", null, props.get("foo2")); - assertTrue(props != props2); + assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); + assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo(null); + assertThat(props != props2).isTrue(); } @Test public void testLocalProperties() { Properties props = (Properties) this.beanFactory.getBean("myLocalProperties"); - assertEquals("Incorrect property value", null, props.get("foo")); - assertEquals("Incorrect property value", "bar2", props.get("foo2")); + assertThat(props.get("foo")).as("Incorrect property value").isEqualTo(null); + assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo("bar2"); } @Test public void testMergedProperties() { Properties props = (Properties) this.beanFactory.getBean("myMergedProperties"); - assertEquals("Incorrect property value", "bar", props.get("foo")); - assertEquals("Incorrect property value", "bar2", props.get("foo2")); + assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); + assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo("bar2"); } @Test public void testLocalOverrideDefault() { Properties props = (Properties) this.beanFactory.getBean("defaultLocalOverrideProperties"); - assertEquals("Incorrect property value", "bar", props.get("foo")); - assertEquals("Incorrect property value", "local2", props.get("foo2")); + assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); + assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo("local2"); } @Test public void testLocalOverrideFalse() { Properties props = (Properties) this.beanFactory.getBean("falseLocalOverrideProperties"); - assertEquals("Incorrect property value", "bar", props.get("foo")); - assertEquals("Incorrect property value", "local2", props.get("foo2")); + assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); + assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo("local2"); } @Test public void testLocalOverrideTrue() { Properties props = (Properties) this.beanFactory.getBean("trueLocalOverrideProperties"); - assertEquals("Incorrect property value", "local", props.get("foo")); - assertEquals("Incorrect property value", "local2", props.get("foo2")); + assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("local"); + assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo("local2"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java index 7558679da3d..8b764bd8b6b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java @@ -42,10 +42,8 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.HasMap; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * Tests for collections in XML bean definitions. @@ -72,17 +70,20 @@ public class XmlBeanCollectionTests { ListFactoryBean listFactory = new ListFactoryBean(); listFactory.setSourceList(new LinkedList()); listFactory.afterPropertiesSet(); - assertTrue(listFactory.getObject() instanceof ArrayList); + boolean condition2 = listFactory.getObject() instanceof ArrayList; + assertThat(condition2).isTrue(); SetFactoryBean setFactory = new SetFactoryBean(); setFactory.setSourceSet(new TreeSet()); setFactory.afterPropertiesSet(); - assertTrue(setFactory.getObject() instanceof LinkedHashSet); + boolean condition1 = setFactory.getObject() instanceof LinkedHashSet; + assertThat(condition1).isTrue(); MapFactoryBean mapFactory = new MapFactoryBean(); mapFactory.setSourceMap(new TreeMap()); mapFactory.afterPropertiesSet(); - assertTrue(mapFactory.getObject() instanceof LinkedHashMap); + boolean condition = mapFactory.getObject() instanceof LinkedHashMap; + assertThat(condition).isTrue(); } @Test @@ -90,25 +91,25 @@ public class XmlBeanCollectionTests { //assertTrue("5 beans in reftypes, not " + this.beanFactory.getBeanDefinitionCount(), this.beanFactory.getBeanDefinitionCount() == 5); TestBean jen = (TestBean) this.beanFactory.getBean("jenny"); TestBean dave = (TestBean) this.beanFactory.getBean("david"); - assertTrue(jen.getSpouse() == dave); + assertThat(jen.getSpouse() == dave).isTrue(); } @Test public void testPropertyWithLiteralValueSubelement() throws Exception { TestBean verbose = (TestBean) this.beanFactory.getBean("verbose"); - assertTrue(verbose.getName().equals("verbose")); + assertThat(verbose.getName().equals("verbose")).isTrue(); } @Test public void testPropertyWithIdRefLocalAttrSubelement() throws Exception { TestBean verbose = (TestBean) this.beanFactory.getBean("verbose2"); - assertTrue(verbose.getName().equals("verbose")); + assertThat(verbose.getName().equals("verbose")).isTrue(); } @Test public void testPropertyWithIdRefBeanAttrSubelement() throws Exception { TestBean verbose = (TestBean) this.beanFactory.getBean("verbose3"); - assertTrue(verbose.getName().equals("verbose")); + assertThat(verbose.getName().equals("verbose")).isTrue(); } @Test @@ -121,10 +122,10 @@ public class XmlBeanCollectionTests { // Our bean doesn't modify the collection: // of course it could be a different copy in a real object. Object[] friends = rod.getFriends().toArray(); - assertTrue(friends.length == 2); + assertThat(friends.length == 2).isTrue(); - assertTrue("First friend must be jen, not " + friends[0], friends[0] == jen); - assertTrue(friends[1] == dave); + assertThat(friends[0] == jen).as("First friend must be jen, not " + friends[0]).isTrue(); + assertThat(friends[1] == dave).isTrue(); // Should be ordered } @@ -135,45 +136,42 @@ public class XmlBeanCollectionTests { TestBean rod = (TestBean) this.beanFactory.getBean("pRod"); Object[] friends = rod.getFriends().toArray(); - assertTrue(friends.length == 2); - assertTrue("First friend must be jen, not " + friends[0], - friends[0].toString().equals(jen.toString())); - assertTrue("Jen not same instance", friends[0] != jen); - assertTrue(friends[1].toString().equals(dave.toString())); - assertTrue("Dave not same instance", friends[1] != dave); - assertEquals("Jen", dave.getSpouse().getName()); + assertThat(friends.length == 2).isTrue(); + assertThat(friends[0].toString().equals(jen.toString())).as("First friend must be jen, not " + friends[0]).isTrue(); + assertThat(friends[0] != jen).as("Jen not same instance").isTrue(); + assertThat(friends[1].toString().equals(dave.toString())).isTrue(); + assertThat(friends[1] != dave).as("Dave not same instance").isTrue(); + assertThat(dave.getSpouse().getName()).isEqualTo("Jen"); TestBean rod2 = (TestBean) this.beanFactory.getBean("pRod"); Object[] friends2 = rod2.getFriends().toArray(); - assertTrue(friends2.length == 2); - assertTrue("First friend must be jen, not " + friends2[0], - friends2[0].toString().equals(jen.toString())); - assertTrue("Jen not same instance", friends2[0] != friends[0]); - assertTrue(friends2[1].toString().equals(dave.toString())); - assertTrue("Dave not same instance", friends2[1] != friends[1]); + assertThat(friends2.length == 2).isTrue(); + assertThat(friends2[0].toString().equals(jen.toString())).as("First friend must be jen, not " + friends2[0]).isTrue(); + assertThat(friends2[0] != friends[0]).as("Jen not same instance").isTrue(); + assertThat(friends2[1].toString().equals(dave.toString())).isTrue(); + assertThat(friends2[1] != friends[1]).as("Dave not same instance").isTrue(); } @Test public void testRefSubelementsBuildCollectionFromSingleElement() throws Exception { TestBean loner = (TestBean) this.beanFactory.getBean("loner"); TestBean dave = (TestBean) this.beanFactory.getBean("david"); - assertTrue(loner.getFriends().size() == 1); - assertTrue(loner.getFriends().contains(dave)); + assertThat(loner.getFriends().size() == 1).isTrue(); + assertThat(loner.getFriends().contains(dave)).isTrue(); } @Test public void testBuildCollectionFromMixtureOfReferencesAndValues() throws Exception { MixedCollectionBean jumble = (MixedCollectionBean) this.beanFactory.getBean("jumble"); - assertTrue("Expected 5 elements, not " + jumble.getJumble().size(), - jumble.getJumble().size() == 5); + assertThat(jumble.getJumble().size() == 5).as("Expected 5 elements, not " + jumble.getJumble().size()).isTrue(); List l = (List) jumble.getJumble(); - assertTrue(l.get(0).equals(this.beanFactory.getBean("david"))); - assertTrue(l.get(1).equals("literal")); - assertTrue(l.get(2).equals(this.beanFactory.getBean("jenny"))); - assertTrue(l.get(3).equals("rod")); + assertThat(l.get(0).equals(this.beanFactory.getBean("david"))).isTrue(); + assertThat(l.get(1).equals("literal")).isTrue(); + assertThat(l.get(2).equals(this.beanFactory.getBean("jenny"))).isTrue(); + assertThat(l.get(3).equals("rod")).isTrue(); Object[] array = (Object[]) l.get(4); - assertTrue(array[0].equals(this.beanFactory.getBean("david"))); - assertTrue(array[1].equals("literal2")); + assertThat(array[0].equals(this.beanFactory.getBean("david"))).isTrue(); + assertThat(array[1].equals("literal2")).isTrue(); } @Test @@ -187,258 +185,265 @@ public class XmlBeanCollectionTests { @Test public void testEmptyMap() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("emptyMap"); - assertTrue(hasMap.getMap().size() == 0); + assertThat(hasMap.getMap().size() == 0).isTrue(); } @Test public void testMapWithLiteralsOnly() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("literalMap"); - assertTrue(hasMap.getMap().size() == 3); - assertTrue(hasMap.getMap().get("foo").equals("bar")); - assertTrue(hasMap.getMap().get("fi").equals("fum")); - assertTrue(hasMap.getMap().get("fa") == null); + assertThat(hasMap.getMap().size() == 3).isTrue(); + assertThat(hasMap.getMap().get("foo").equals("bar")).isTrue(); + assertThat(hasMap.getMap().get("fi").equals("fum")).isTrue(); + assertThat(hasMap.getMap().get("fa") == null).isTrue(); } @Test public void testMapWithLiteralsAndReferences() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("mixedMap"); - assertTrue(hasMap.getMap().size() == 5); - assertTrue(hasMap.getMap().get("foo").equals(new Integer(10))); + assertThat(hasMap.getMap().size() == 5).isTrue(); + assertThat(hasMap.getMap().get("foo").equals(new Integer(10))).isTrue(); TestBean jenny = (TestBean) this.beanFactory.getBean("jenny"); - assertTrue(hasMap.getMap().get("jenny") == jenny); - assertTrue(hasMap.getMap().get(new Integer(5)).equals("david")); - assertTrue(hasMap.getMap().get("bar") instanceof Long); - assertTrue(hasMap.getMap().get("bar").equals(new Long(100))); - assertTrue(hasMap.getMap().get("baz") instanceof Integer); - assertTrue(hasMap.getMap().get("baz").equals(new Integer(200))); + assertThat(hasMap.getMap().get("jenny") == jenny).isTrue(); + assertThat(hasMap.getMap().get(new Integer(5)).equals("david")).isTrue(); + boolean condition1 = hasMap.getMap().get("bar") instanceof Long; + assertThat(condition1).isTrue(); + assertThat(hasMap.getMap().get("bar").equals(new Long(100))).isTrue(); + boolean condition = hasMap.getMap().get("baz") instanceof Integer; + assertThat(condition).isTrue(); + assertThat(hasMap.getMap().get("baz").equals(new Integer(200))).isTrue(); } @Test public void testMapWithLiteralsAndPrototypeReferences() throws Exception { TestBean jenny = (TestBean) this.beanFactory.getBean("pJenny"); HasMap hasMap = (HasMap) this.beanFactory.getBean("pMixedMap"); - assertTrue(hasMap.getMap().size() == 2); - assertTrue(hasMap.getMap().get("foo").equals("bar")); - assertTrue(hasMap.getMap().get("jenny").toString().equals(jenny.toString())); - assertTrue("Not same instance", hasMap.getMap().get("jenny") != jenny); + assertThat(hasMap.getMap().size() == 2).isTrue(); + assertThat(hasMap.getMap().get("foo").equals("bar")).isTrue(); + assertThat(hasMap.getMap().get("jenny").toString().equals(jenny.toString())).isTrue(); + assertThat(hasMap.getMap().get("jenny") != jenny).as("Not same instance").isTrue(); HasMap hasMap2 = (HasMap) this.beanFactory.getBean("pMixedMap"); - assertTrue(hasMap2.getMap().size() == 2); - assertTrue(hasMap2.getMap().get("foo").equals("bar")); - assertTrue(hasMap2.getMap().get("jenny").toString().equals(jenny.toString())); - assertTrue("Not same instance", hasMap2.getMap().get("jenny") != hasMap.getMap().get("jenny")); + assertThat(hasMap2.getMap().size() == 2).isTrue(); + assertThat(hasMap2.getMap().get("foo").equals("bar")).isTrue(); + assertThat(hasMap2.getMap().get("jenny").toString().equals(jenny.toString())).isTrue(); + assertThat(hasMap2.getMap().get("jenny") != hasMap.getMap().get("jenny")).as("Not same instance").isTrue(); } @Test public void testMapWithLiteralsReferencesAndList() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("mixedMapWithList"); - assertTrue(hasMap.getMap().size() == 4); - assertTrue(hasMap.getMap().get(null).equals("bar")); + assertThat(hasMap.getMap().size() == 4).isTrue(); + assertThat(hasMap.getMap().get(null).equals("bar")).isTrue(); TestBean jenny = (TestBean) this.beanFactory.getBean("jenny"); - assertTrue(hasMap.getMap().get("jenny").equals(jenny)); + assertThat(hasMap.getMap().get("jenny").equals(jenny)).isTrue(); // Check list List l = (List) hasMap.getMap().get("list"); - assertNotNull(l); - assertTrue(l.size() == 4); - assertTrue(l.get(0).equals("zero")); - assertTrue(l.get(3) == null); + assertThat(l).isNotNull(); + assertThat(l.size() == 4).isTrue(); + assertThat(l.get(0).equals("zero")).isTrue(); + assertThat(l.get(3) == null).isTrue(); // Check nested map in list Map m = (Map) l.get(1); - assertNotNull(m); - assertTrue(m.size() == 2); - assertTrue(m.get("fo").equals("bar")); - assertTrue("Map element 'jenny' should be equal to jenny bean, not " + m.get("jen"), - m.get("jen").equals(jenny)); + assertThat(m).isNotNull(); + assertThat(m.size() == 2).isTrue(); + assertThat(m.get("fo").equals("bar")).isTrue(); + assertThat(m.get("jen").equals(jenny)).as("Map element 'jenny' should be equal to jenny bean, not " + m.get("jen")).isTrue(); // Check nested list in list l = (List) l.get(2); - assertNotNull(l); - assertTrue(l.size() == 2); - assertTrue(l.get(0).equals(jenny)); - assertTrue(l.get(1).equals("ba")); + assertThat(l).isNotNull(); + assertThat(l.size() == 2).isTrue(); + assertThat(l.get(0).equals(jenny)).isTrue(); + assertThat(l.get(1).equals("ba")).isTrue(); // Check nested map m = (Map) hasMap.getMap().get("map"); - assertNotNull(m); - assertTrue(m.size() == 2); - assertTrue(m.get("foo").equals("bar")); - assertTrue("Map element 'jenny' should be equal to jenny bean, not " + m.get("jenny"), - m.get("jenny").equals(jenny)); + assertThat(m).isNotNull(); + assertThat(m.size() == 2).isTrue(); + assertThat(m.get("foo").equals("bar")).isTrue(); + assertThat(m.get("jenny").equals(jenny)).as("Map element 'jenny' should be equal to jenny bean, not " + m.get("jenny")).isTrue(); } @Test public void testEmptySet() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("emptySet"); - assertTrue(hasMap.getSet().size() == 0); + assertThat(hasMap.getSet().size() == 0).isTrue(); } @Test public void testPopulatedSet() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("set"); - assertTrue(hasMap.getSet().size() == 3); - assertTrue(hasMap.getSet().contains("bar")); + assertThat(hasMap.getSet().size() == 3).isTrue(); + assertThat(hasMap.getSet().contains("bar")).isTrue(); TestBean jenny = (TestBean) this.beanFactory.getBean("jenny"); - assertTrue(hasMap.getSet().contains(jenny)); - assertTrue(hasMap.getSet().contains(null)); + assertThat(hasMap.getSet().contains(jenny)).isTrue(); + assertThat(hasMap.getSet().contains(null)).isTrue(); Iterator it = hasMap.getSet().iterator(); - assertEquals("bar", it.next()); - assertEquals(jenny, it.next()); - assertEquals(null, it.next()); + assertThat(it.next()).isEqualTo("bar"); + assertThat(it.next()).isEqualTo(jenny); + assertThat(it.next()).isEqualTo(null); } @Test public void testPopulatedConcurrentSet() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("concurrentSet"); - assertTrue(hasMap.getConcurrentSet().size() == 3); - assertTrue(hasMap.getConcurrentSet().contains("bar")); + assertThat(hasMap.getConcurrentSet().size() == 3).isTrue(); + assertThat(hasMap.getConcurrentSet().contains("bar")).isTrue(); TestBean jenny = (TestBean) this.beanFactory.getBean("jenny"); - assertTrue(hasMap.getConcurrentSet().contains(jenny)); - assertTrue(hasMap.getConcurrentSet().contains(null)); + assertThat(hasMap.getConcurrentSet().contains(jenny)).isTrue(); + assertThat(hasMap.getConcurrentSet().contains(null)).isTrue(); } @Test public void testPopulatedIdentityMap() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("identityMap"); - assertTrue(hasMap.getIdentityMap().size() == 2); + assertThat(hasMap.getIdentityMap().size() == 2).isTrue(); HashSet set = new HashSet(hasMap.getIdentityMap().keySet()); - assertTrue(set.contains("foo")); - assertTrue(set.contains("jenny")); + assertThat(set.contains("foo")).isTrue(); + assertThat(set.contains("jenny")).isTrue(); } @Test public void testEmptyProps() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("emptyProps"); - assertTrue(hasMap.getProps().size() == 0); - assertEquals(hasMap.getProps().getClass(), Properties.class); + assertThat(hasMap.getProps().size() == 0).isTrue(); + assertThat(Properties.class).isEqualTo(hasMap.getProps().getClass()); } @Test public void testPopulatedProps() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("props"); - assertTrue(hasMap.getProps().size() == 2); - assertTrue(hasMap.getProps().get("foo").equals("bar")); - assertTrue(hasMap.getProps().get("2").equals("TWO")); + assertThat(hasMap.getProps().size() == 2).isTrue(); + assertThat(hasMap.getProps().get("foo").equals("bar")).isTrue(); + assertThat(hasMap.getProps().get("2").equals("TWO")).isTrue(); } @Test public void testObjectArray() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("objectArray"); - assertTrue(hasMap.getObjectArray().length == 2); - assertTrue(hasMap.getObjectArray()[0].equals("one")); - assertTrue(hasMap.getObjectArray()[1].equals(this.beanFactory.getBean("jenny"))); + assertThat(hasMap.getObjectArray().length == 2).isTrue(); + assertThat(hasMap.getObjectArray()[0].equals("one")).isTrue(); + assertThat(hasMap.getObjectArray()[1].equals(this.beanFactory.getBean("jenny"))).isTrue(); } @Test public void testIntegerArray() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("integerArray"); - assertTrue(hasMap.getIntegerArray().length == 3); - assertTrue(hasMap.getIntegerArray()[0].intValue() == 0); - assertTrue(hasMap.getIntegerArray()[1].intValue() == 1); - assertTrue(hasMap.getIntegerArray()[2].intValue() == 2); + assertThat(hasMap.getIntegerArray().length == 3).isTrue(); + assertThat(hasMap.getIntegerArray()[0].intValue() == 0).isTrue(); + assertThat(hasMap.getIntegerArray()[1].intValue() == 1).isTrue(); + assertThat(hasMap.getIntegerArray()[2].intValue() == 2).isTrue(); } @Test public void testClassArray() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("classArray"); - assertTrue(hasMap.getClassArray().length == 2); - assertTrue(hasMap.getClassArray()[0].equals(String.class)); - assertTrue(hasMap.getClassArray()[1].equals(Exception.class)); + assertThat(hasMap.getClassArray().length == 2).isTrue(); + assertThat(hasMap.getClassArray()[0].equals(String.class)).isTrue(); + assertThat(hasMap.getClassArray()[1].equals(Exception.class)).isTrue(); } @Test public void testClassList() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("classList"); - assertTrue(hasMap.getClassList().size()== 2); - assertTrue(hasMap.getClassList().get(0).equals(String.class)); - assertTrue(hasMap.getClassList().get(1).equals(Exception.class)); + assertThat(hasMap.getClassList().size()== 2).isTrue(); + assertThat(hasMap.getClassList().get(0).equals(String.class)).isTrue(); + assertThat(hasMap.getClassList().get(1).equals(Exception.class)).isTrue(); } @Test public void testProps() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("props"); - assertEquals(2, hasMap.getProps().size()); - assertEquals("bar", hasMap.getProps().getProperty("foo")); - assertEquals("TWO", hasMap.getProps().getProperty("2")); + assertThat(hasMap.getProps().size()).isEqualTo(2); + assertThat(hasMap.getProps().getProperty("foo")).isEqualTo("bar"); + assertThat(hasMap.getProps().getProperty("2")).isEqualTo("TWO"); HasMap hasMap2 = (HasMap) this.beanFactory.getBean("propsViaMap"); - assertEquals(2, hasMap2.getProps().size()); - assertEquals("bar", hasMap2.getProps().getProperty("foo")); - assertEquals("TWO", hasMap2.getProps().getProperty("2")); + assertThat(hasMap2.getProps().size()).isEqualTo(2); + assertThat(hasMap2.getProps().getProperty("foo")).isEqualTo("bar"); + assertThat(hasMap2.getProps().getProperty("2")).isEqualTo("TWO"); } @Test public void testListFactory() throws Exception { List list = (List) this.beanFactory.getBean("listFactory"); - assertTrue(list instanceof LinkedList); - assertTrue(list.size() == 2); - assertEquals("bar", list.get(0)); - assertEquals("jenny", list.get(1)); + boolean condition = list instanceof LinkedList; + assertThat(condition).isTrue(); + assertThat(list.size() == 2).isTrue(); + assertThat(list.get(0)).isEqualTo("bar"); + assertThat(list.get(1)).isEqualTo("jenny"); } @Test public void testPrototypeListFactory() throws Exception { List list = (List) this.beanFactory.getBean("pListFactory"); - assertTrue(list instanceof LinkedList); - assertTrue(list.size() == 2); - assertEquals("bar", list.get(0)); - assertEquals("jenny", list.get(1)); + boolean condition = list instanceof LinkedList; + assertThat(condition).isTrue(); + assertThat(list.size() == 2).isTrue(); + assertThat(list.get(0)).isEqualTo("bar"); + assertThat(list.get(1)).isEqualTo("jenny"); } @Test public void testSetFactory() throws Exception { Set set = (Set) this.beanFactory.getBean("setFactory"); - assertTrue(set instanceof TreeSet); - assertTrue(set.size() == 2); - assertTrue(set.contains("bar")); - assertTrue(set.contains("jenny")); + boolean condition = set instanceof TreeSet; + assertThat(condition).isTrue(); + assertThat(set.size() == 2).isTrue(); + assertThat(set.contains("bar")).isTrue(); + assertThat(set.contains("jenny")).isTrue(); } @Test public void testPrototypeSetFactory() throws Exception { Set set = (Set) this.beanFactory.getBean("pSetFactory"); - assertTrue(set instanceof TreeSet); - assertTrue(set.size() == 2); - assertTrue(set.contains("bar")); - assertTrue(set.contains("jenny")); + boolean condition = set instanceof TreeSet; + assertThat(condition).isTrue(); + assertThat(set.size() == 2).isTrue(); + assertThat(set.contains("bar")).isTrue(); + assertThat(set.contains("jenny")).isTrue(); } @Test public void testMapFactory() throws Exception { Map map = (Map) this.beanFactory.getBean("mapFactory"); - assertTrue(map instanceof TreeMap); - assertTrue(map.size() == 2); - assertEquals("bar", map.get("foo")); - assertEquals("jenny", map.get("jen")); + boolean condition = map instanceof TreeMap; + assertThat(condition).isTrue(); + assertThat(map.size() == 2).isTrue(); + assertThat(map.get("foo")).isEqualTo("bar"); + assertThat(map.get("jen")).isEqualTo("jenny"); } @Test public void testPrototypeMapFactory() throws Exception { Map map = (Map) this.beanFactory.getBean("pMapFactory"); - assertTrue(map instanceof TreeMap); - assertTrue(map.size() == 2); - assertEquals("bar", map.get("foo")); - assertEquals("jenny", map.get("jen")); + boolean condition = map instanceof TreeMap; + assertThat(condition).isTrue(); + assertThat(map.size() == 2).isTrue(); + assertThat(map.get("foo")).isEqualTo("bar"); + assertThat(map.get("jen")).isEqualTo("jenny"); } @Test public void testChoiceBetweenSetAndMap() { MapAndSet sam = (MapAndSet) this.beanFactory.getBean("setAndMap"); - assertTrue("Didn't choose constructor with Map argument", sam.getObject() instanceof Map); + boolean condition = sam.getObject() instanceof Map; + assertThat(condition).as("Didn't choose constructor with Map argument").isTrue(); Map map = (Map) sam.getObject(); - assertEquals(3, map.size()); - assertEquals("val1", map.get("key1")); - assertEquals("val2", map.get("key2")); - assertEquals("val3", map.get("key3")); + assertThat(map.size()).isEqualTo(3); + assertThat(map.get("key1")).isEqualTo("val1"); + assertThat(map.get("key2")).isEqualTo("val2"); + assertThat(map.get("key3")).isEqualTo("val3"); } @Test public void testEnumSetFactory() throws Exception { Set set = (Set) this.beanFactory.getBean("enumSetFactory"); - assertTrue(set.size() == 2); - assertTrue(set.contains("ONE")); - assertTrue(set.contains("TWO")); + assertThat(set.size() == 2).isTrue(); + assertThat(set.contains("ONE")).isTrue(); + assertThat(set.contains("TWO")).isTrue(); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java index e4d0e8eabfe..43fc2ba9cda 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java @@ -31,10 +31,8 @@ import org.springframework.core.io.Resource; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * @author Rick Evans @@ -110,19 +108,19 @@ public class XmlBeanDefinitionReaderTests { } private void testBeanDefinitions(BeanDefinitionRegistry registry) { - assertEquals(24, registry.getBeanDefinitionCount()); - assertEquals(24, registry.getBeanDefinitionNames().length); - assertTrue(Arrays.asList(registry.getBeanDefinitionNames()).contains("rod")); - assertTrue(Arrays.asList(registry.getBeanDefinitionNames()).contains("aliased")); - assertTrue(registry.containsBeanDefinition("rod")); - assertTrue(registry.containsBeanDefinition("aliased")); - assertEquals(TestBean.class.getName(), registry.getBeanDefinition("rod").getBeanClassName()); - assertEquals(TestBean.class.getName(), registry.getBeanDefinition("aliased").getBeanClassName()); - assertTrue(registry.isAlias("youralias")); + assertThat(registry.getBeanDefinitionCount()).isEqualTo(24); + assertThat(registry.getBeanDefinitionNames().length).isEqualTo(24); + assertThat(Arrays.asList(registry.getBeanDefinitionNames()).contains("rod")).isTrue(); + assertThat(Arrays.asList(registry.getBeanDefinitionNames()).contains("aliased")).isTrue(); + assertThat(registry.containsBeanDefinition("rod")).isTrue(); + assertThat(registry.containsBeanDefinition("aliased")).isTrue(); + assertThat(registry.getBeanDefinition("rod").getBeanClassName()).isEqualTo(TestBean.class.getName()); + assertThat(registry.getBeanDefinition("aliased").getBeanClassName()).isEqualTo(TestBean.class.getName()); + assertThat(registry.isAlias("youralias")).isTrue(); String[] aliases = registry.getAliases("aliased"); - assertEquals(2, aliases.length); - assertTrue(ObjectUtils.containsElement(aliases, "myalias")); - assertTrue(ObjectUtils.containsElement(aliases, "youralias")); + assertThat(aliases.length).isEqualTo(2); + assertThat(ObjectUtils.containsElement(aliases, "myalias")).isTrue(); + assertThat(ObjectUtils.containsElement(aliases, "youralias")).isTrue(); } @Test @@ -140,7 +138,7 @@ public class XmlBeanDefinitionReaderTests { Resource resource = new ClassPathResource(resourceName, getClass()); new XmlBeanDefinitionReader(factory).loadBeanDefinitions(resource); TestBean bean = (TestBean) factory.getBean("testBean"); - assertNotNull(bean); + assertThat(bean).isNotNull(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java index ab2c8c27d1b..82f6c5e9de4 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java @@ -36,9 +36,7 @@ import org.springframework.tests.sample.beans.LifecycleBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.factory.DummyFactory; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -125,7 +123,7 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest @Test public void descriptionButNoProperties() { TestBean validEmpty = (TestBean) getBeanFactory().getBean("validEmptyWithDescription"); - assertEquals(0, validEmpty.getAge()); + assertThat(validEmpty.getAge()).isEqualTo(0); } /** @@ -137,71 +135,71 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest TestBean tb1 = (TestBean) getBeanFactory().getBean("aliased"); TestBean alias1 = (TestBean) getBeanFactory().getBean("myalias"); - assertTrue(tb1 == alias1); + assertThat(tb1 == alias1).isTrue(); List tb1Aliases = Arrays.asList(getBeanFactory().getAliases("aliased")); - assertEquals(2, tb1Aliases.size()); - assertTrue(tb1Aliases.contains("myalias")); - assertTrue(tb1Aliases.contains("youralias")); - assertTrue(beanNames.contains("aliased")); - assertFalse(beanNames.contains("myalias")); - assertFalse(beanNames.contains("youralias")); + assertThat(tb1Aliases.size()).isEqualTo(2); + assertThat(tb1Aliases.contains("myalias")).isTrue(); + assertThat(tb1Aliases.contains("youralias")).isTrue(); + assertThat(beanNames.contains("aliased")).isTrue(); + assertThat(beanNames.contains("myalias")).isFalse(); + assertThat(beanNames.contains("youralias")).isFalse(); TestBean tb2 = (TestBean) getBeanFactory().getBean("multiAliased"); TestBean alias2 = (TestBean) getBeanFactory().getBean("alias1"); TestBean alias3 = (TestBean) getBeanFactory().getBean("alias2"); TestBean alias3a = (TestBean) getBeanFactory().getBean("alias3"); TestBean alias3b = (TestBean) getBeanFactory().getBean("alias4"); - assertTrue(tb2 == alias2); - assertTrue(tb2 == alias3); - assertTrue(tb2 == alias3a); - assertTrue(tb2 == alias3b); + assertThat(tb2 == alias2).isTrue(); + assertThat(tb2 == alias3).isTrue(); + assertThat(tb2 == alias3a).isTrue(); + assertThat(tb2 == alias3b).isTrue(); List tb2Aliases = Arrays.asList(getBeanFactory().getAliases("multiAliased")); - assertEquals(4, tb2Aliases.size()); - assertTrue(tb2Aliases.contains("alias1")); - assertTrue(tb2Aliases.contains("alias2")); - assertTrue(tb2Aliases.contains("alias3")); - assertTrue(tb2Aliases.contains("alias4")); - assertTrue(beanNames.contains("multiAliased")); - assertFalse(beanNames.contains("alias1")); - assertFalse(beanNames.contains("alias2")); - assertFalse(beanNames.contains("alias3")); - assertFalse(beanNames.contains("alias4")); + assertThat(tb2Aliases.size()).isEqualTo(4); + assertThat(tb2Aliases.contains("alias1")).isTrue(); + assertThat(tb2Aliases.contains("alias2")).isTrue(); + assertThat(tb2Aliases.contains("alias3")).isTrue(); + assertThat(tb2Aliases.contains("alias4")).isTrue(); + assertThat(beanNames.contains("multiAliased")).isTrue(); + assertThat(beanNames.contains("alias1")).isFalse(); + assertThat(beanNames.contains("alias2")).isFalse(); + assertThat(beanNames.contains("alias3")).isFalse(); + assertThat(beanNames.contains("alias4")).isFalse(); TestBean tb3 = (TestBean) getBeanFactory().getBean("aliasWithoutId1"); TestBean alias4 = (TestBean) getBeanFactory().getBean("aliasWithoutId2"); TestBean alias5 = (TestBean) getBeanFactory().getBean("aliasWithoutId3"); - assertTrue(tb3 == alias4); - assertTrue(tb3 == alias5); + assertThat(tb3 == alias4).isTrue(); + assertThat(tb3 == alias5).isTrue(); List tb3Aliases = Arrays.asList(getBeanFactory().getAliases("aliasWithoutId1")); - assertEquals(2, tb3Aliases.size()); - assertTrue(tb3Aliases.contains("aliasWithoutId2")); - assertTrue(tb3Aliases.contains("aliasWithoutId3")); - assertTrue(beanNames.contains("aliasWithoutId1")); - assertFalse(beanNames.contains("aliasWithoutId2")); - assertFalse(beanNames.contains("aliasWithoutId3")); + assertThat(tb3Aliases.size()).isEqualTo(2); + assertThat(tb3Aliases.contains("aliasWithoutId2")).isTrue(); + assertThat(tb3Aliases.contains("aliasWithoutId3")).isTrue(); + assertThat(beanNames.contains("aliasWithoutId1")).isTrue(); + assertThat(beanNames.contains("aliasWithoutId2")).isFalse(); + assertThat(beanNames.contains("aliasWithoutId3")).isFalse(); TestBean tb4 = (TestBean) getBeanFactory().getBean(TestBean.class.getName() + "#0"); - assertEquals(null, tb4.getName()); + assertThat(tb4.getName()).isEqualTo(null); Map drs = getListableBeanFactory().getBeansOfType(DummyReferencer.class, false, false); - assertEquals(5, drs.size()); - assertTrue(drs.containsKey(DummyReferencer.class.getName() + "#0")); - assertTrue(drs.containsKey(DummyReferencer.class.getName() + "#1")); - assertTrue(drs.containsKey(DummyReferencer.class.getName() + "#2")); + assertThat(drs.size()).isEqualTo(5); + assertThat(drs.containsKey(DummyReferencer.class.getName() + "#0")).isTrue(); + assertThat(drs.containsKey(DummyReferencer.class.getName() + "#1")).isTrue(); + assertThat(drs.containsKey(DummyReferencer.class.getName() + "#2")).isTrue(); } @Test public void factoryNesting() { ITestBean father = (ITestBean) getBeanFactory().getBean("father"); - assertTrue("Bean from root context", father != null); + assertThat(father != null).as("Bean from root context").isTrue(); TestBean rod = (TestBean) getBeanFactory().getBean("rod"); - assertTrue("Bean from child context", "Rod".equals(rod.getName())); - assertTrue("Bean has external reference", rod.getSpouse() == father); + assertThat("Rod".equals(rod.getName())).as("Bean from child context").isTrue(); + assertThat(rod.getSpouse() == father).as("Bean has external reference").isTrue(); rod = (TestBean) parent.getBean("rod"); - assertTrue("Bean from root context", "Roderick".equals(rod.getName())); + assertThat("Roderick".equals(rod.getName())).as("Bean from root context").isTrue(); } @Test @@ -209,25 +207,25 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); DummyReferencer ref = (DummyReferencer) getBeanFactory().getBean("factoryReferencer"); - assertTrue(ref.getTestBean1() == ref.getTestBean2()); - assertTrue(ref.getDummyFactory() == factory); + assertThat(ref.getTestBean1() == ref.getTestBean2()).isTrue(); + assertThat(ref.getDummyFactory() == factory).isTrue(); DummyReferencer ref2 = (DummyReferencer) getBeanFactory().getBean("factoryReferencerWithConstructor"); - assertTrue(ref2.getTestBean1() == ref2.getTestBean2()); - assertTrue(ref2.getDummyFactory() == factory); + assertThat(ref2.getTestBean1() == ref2.getTestBean2()).isTrue(); + assertThat(ref2.getDummyFactory() == factory).isTrue(); } @Test public void prototypeReferences() { // check that not broken by circular reference resolution mechanism DummyReferencer ref1 = (DummyReferencer) getBeanFactory().getBean("prototypeReferencer"); - assertTrue("Not referencing same bean twice", ref1.getTestBean1() != ref1.getTestBean2()); + assertThat(ref1.getTestBean1() != ref1.getTestBean2()).as("Not referencing same bean twice").isTrue(); DummyReferencer ref2 = (DummyReferencer) getBeanFactory().getBean("prototypeReferencer"); - assertTrue("Not the same referencer", ref1 != ref2); - assertTrue("Not referencing same bean twice", ref2.getTestBean1() != ref2.getTestBean2()); - assertTrue("Not referencing same bean twice", ref1.getTestBean1() != ref2.getTestBean1()); - assertTrue("Not referencing same bean twice", ref1.getTestBean2() != ref2.getTestBean2()); - assertTrue("Not referencing same bean twice", ref1.getTestBean1() != ref2.getTestBean2()); + assertThat(ref1 != ref2).as("Not the same referencer").isTrue(); + assertThat(ref2.getTestBean1() != ref2.getTestBean2()).as("Not referencing same bean twice").isTrue(); + assertThat(ref1.getTestBean1() != ref2.getTestBean1()).as("Not referencing same bean twice").isTrue(); + assertThat(ref1.getTestBean2() != ref2.getTestBean2()).as("Not referencing same bean twice").isTrue(); + assertThat(ref1.getTestBean1() != ref2.getTestBean2()).as("Not referencing same bean twice").isTrue(); } @Test @@ -236,24 +234,24 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest TestBean kathy = (TestBean) getBeanFactory().getBean("kathy"); DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); TestBean factoryCreated = (TestBean) getBeanFactory().getBean("singletonFactory"); - assertTrue(kerry.isPostProcessed()); - assertTrue(kathy.isPostProcessed()); - assertTrue(factory.isPostProcessed()); - assertTrue(factoryCreated.isPostProcessed()); + assertThat(kerry.isPostProcessed()).isTrue(); + assertThat(kathy.isPostProcessed()).isTrue(); + assertThat(factory.isPostProcessed()).isTrue(); + assertThat(factoryCreated.isPostProcessed()).isTrue(); } @Test public void emptyValues() { TestBean rod = (TestBean) getBeanFactory().getBean("rod"); TestBean kerry = (TestBean) getBeanFactory().getBean("kerry"); - assertTrue("Touchy is empty", "".equals(rod.getTouchy())); - assertTrue("Touchy is empty", "".equals(kerry.getTouchy())); + assertThat("".equals(rod.getTouchy())).as("Touchy is empty").isTrue(); + assertThat("".equals(kerry.getTouchy())).as("Touchy is empty").isTrue(); } @Test public void commentsAndCdataInValue() { TestBean bean = (TestBean) getBeanFactory().getBean("commentsInValue"); - assertEquals("Failed to handle comments and CDATA properly", "this is a ", bean.getName()); + assertThat(bean.getName()).as("Failed to handle comments and CDATA properly").isEqualTo("this is a "); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/support/DefaultNamespaceHandlerResolverTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/support/DefaultNamespaceHandlerResolverTests.java index 746e9c0da35..1d46bdcd561 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/support/DefaultNamespaceHandlerResolverTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/support/DefaultNamespaceHandlerResolverTests.java @@ -22,9 +22,8 @@ import org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver; import org.springframework.beans.factory.xml.NamespaceHandler; import org.springframework.beans.factory.xml.UtilNamespaceHandler; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Unit and integration tests for the {@link DefaultNamespaceHandlerResolver} class. @@ -38,16 +37,16 @@ public class DefaultNamespaceHandlerResolverTests { public void testResolvedMappedHandler() { DefaultNamespaceHandlerResolver resolver = new DefaultNamespaceHandlerResolver(getClass().getClassLoader()); NamespaceHandler handler = resolver.resolve("http://www.springframework.org/schema/util"); - assertNotNull("Handler should not be null.", handler); - assertEquals("Incorrect handler loaded", UtilNamespaceHandler.class, handler.getClass()); + assertThat(handler).as("Handler should not be null.").isNotNull(); + assertThat(handler.getClass()).as("Incorrect handler loaded").isEqualTo(UtilNamespaceHandler.class); } @Test public void testResolvedMappedHandlerWithNoArgCtor() { DefaultNamespaceHandlerResolver resolver = new DefaultNamespaceHandlerResolver(); NamespaceHandler handler = resolver.resolve("http://www.springframework.org/schema/util"); - assertNotNull("Handler should not be null.", handler); - assertEquals("Incorrect handler loaded", UtilNamespaceHandler.class, handler.getClass()); + assertThat(handler).as("Handler should not be null.").isNotNull(); + assertThat(handler.getClass()).as("Incorrect handler loaded").isEqualTo(UtilNamespaceHandler.class); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/BeanInfoTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/BeanInfoTests.java index 585a7525542..0e759436308 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/BeanInfoTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/BeanInfoTests.java @@ -27,8 +27,7 @@ import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.FatalBeanException; import org.springframework.util.Assert; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -43,17 +42,17 @@ public class BeanInfoTests { Integer value = new Integer(1); bw.setPropertyValue("value", value); - assertEquals("value not set correctly", bean.getValue(), value); + assertThat(value).as("value not set correctly").isEqualTo(bean.getValue()); value = new Integer(2); bw.setPropertyValue("value", value.toString()); - assertEquals("value not converted", bean.getValue(), value); + assertThat(value).as("value not converted").isEqualTo(bean.getValue()); bw.setPropertyValue("value", null); - assertNull("value not null", bean.getValue()); + assertThat(bean.getValue()).as("value not null").isNull(); bw.setPropertyValue("value", ""); - assertNull("value not converted to null", bean.getValue()); + assertThat(bean.getValue()).as("value not converted to null").isNull(); } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ByteArrayPropertyEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ByteArrayPropertyEditorTests.java index d7330bf5293..dbd9ffed444 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ByteArrayPropertyEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ByteArrayPropertyEditorTests.java @@ -20,9 +20,7 @@ import java.beans.PropertyEditor; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for the {@link ByteArrayPropertyEditor} class. @@ -39,21 +37,20 @@ public class ByteArrayPropertyEditorTests { byteEditor.setAsText(text); Object value = byteEditor.getValue(); - assertNotNull(value); - assertTrue(value instanceof byte[]); + assertThat(value).isNotNull().isInstanceOf(byte[].class); byte[] bytes = (byte[]) value; for (int i = 0; i < text.length(); ++i) { - assertEquals("cyte[] differs at index '" + i + "'", text.charAt(i), bytes[i]); + assertThat(bytes[i]).as("cyte[] differs at index '" + i + "'").isEqualTo((byte) text.charAt(i)); } - assertEquals(text, byteEditor.getAsText()); + assertThat(byteEditor.getAsText()).isEqualTo(text); } @Test public void getAsTextReturnsEmptyStringIfValueIsNull() throws Exception { - assertEquals("", byteEditor.getAsText()); + assertThat(byteEditor.getAsText()).isEqualTo(""); byteEditor.setAsText(null); - assertEquals("", byteEditor.getAsText()); + assertThat(byteEditor.getAsText()).isEqualTo(""); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CharArrayPropertyEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CharArrayPropertyEditorTests.java index 3451d7d6b89..0df5886fd99 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CharArrayPropertyEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CharArrayPropertyEditorTests.java @@ -20,9 +20,7 @@ import java.beans.PropertyEditor; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for the {@link CharArrayPropertyEditor} class. @@ -39,21 +37,20 @@ public class CharArrayPropertyEditorTests { charEditor.setAsText(text); Object value = charEditor.getValue(); - assertNotNull(value); - assertTrue(value instanceof char[]); + assertThat(value).isNotNull().isInstanceOf(char[].class); char[] chars = (char[]) value; for (int i = 0; i < text.length(); ++i) { - assertEquals("char[] differs at index '" + i + "'", text.charAt(i), chars[i]); + assertThat(chars[i]).as("char[] differs at index '" + i + "'").isEqualTo(text.charAt(i)); } - assertEquals(text, charEditor.getAsText()); + assertThat(charEditor.getAsText()).isEqualTo(text); } @Test public void getAsTextReturnsEmptyStringIfValueIsNull() throws Exception { - assertEquals("", charEditor.getAsText()); + assertThat(charEditor.getAsText()).isEqualTo(""); charEditor.setAsText(null); - assertEquals("", charEditor.getAsText()); + assertThat(charEditor.getAsText()).isEqualTo(""); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java index fb83b6af35f..d4e86341934 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java @@ -22,10 +22,8 @@ import java.util.List; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * Unit tests for the {@link CustomCollectionEditor} class. @@ -60,13 +58,14 @@ public class CustomCollectionEditorTests { CustomCollectionEditor editor = new CustomCollectionEditor(ArrayList.class); editor.setValue(new int[] {0, 1, 2}); Object value = editor.getValue(); - assertNotNull(value); - assertTrue(value instanceof ArrayList); + assertThat(value).isNotNull(); + boolean condition = value instanceof ArrayList; + assertThat(condition).isTrue(); List list = (List) value; - assertEquals("There must be 3 elements in the converted collection", 3, list.size()); - assertEquals(new Integer(0), list.get(0)); - assertEquals(new Integer(1), list.get(1)); - assertEquals(new Integer(2), list.get(2)); + assertThat(list.size()).as("There must be 3 elements in the converted collection").isEqualTo(3); + assertThat(list.get(0)).isEqualTo(new Integer(0)); + assertThat(list.get(1)).isEqualTo(new Integer(1)); + assertThat(list.get(2)).isEqualTo(new Integer(2)); } @Test @@ -74,9 +73,9 @@ public class CustomCollectionEditorTests { CustomCollectionEditor editor = new CustomCollectionEditor(Collection.class); editor.setValue("0, 1, 2"); Collection value = (Collection) editor.getValue(); - assertNotNull(value); - assertEquals("There must be 1 element in the converted collection", 1, value.size()); - assertEquals("0, 1, 2", value.iterator().next()); + assertThat(value).isNotNull(); + assertThat(value.size()).as("There must be 1 element in the converted collection").isEqualTo(1); + assertThat(value.iterator().next()).isEqualTo("0, 1, 2"); } @Test @@ -84,11 +83,12 @@ public class CustomCollectionEditorTests { CustomCollectionEditor editor = new CustomCollectionEditor(ArrayList.class); editor.setValue("0, 1, 2"); Object value = editor.getValue(); - assertNotNull(value); - assertTrue(value instanceof ArrayList); + assertThat(value).isNotNull(); + boolean condition = value instanceof ArrayList; + assertThat(condition).isTrue(); List list = (List) value; - assertEquals("There must be 1 element in the converted collection", 1, list.size()); - assertEquals("0, 1, 2", list.get(0)); + assertThat(list.size()).as("There must be 1 element in the converted collection").isEqualTo(1); + assertThat(list.get(0)).isEqualTo("0, 1, 2"); } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java index 1247bc9ea52..60527d248ab 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java @@ -52,11 +52,7 @@ 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.assertThatIllegalArgumentException; -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; +import static org.assertj.core.api.Assertions.within; /** * Unit tests for the various PropertyEditors in Spring. @@ -84,9 +80,8 @@ public class CustomEditorTests { pvs.addPropertyValue(new PropertyValue("touchy", "valid")); pvs.addPropertyValue(new PropertyValue("spouse", tbString)); bw.setPropertyValues(pvs); - assertTrue("spouse is non-null", tb.getSpouse() != null); - assertTrue("spouse name is Kerry and age is 34", - tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34); + assertThat(tb.getSpouse() != null).as("spouse is non-null").isTrue(); + assertThat(tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34).as("spouse name is Kerry and age is 34").isTrue(); } @Test @@ -105,13 +100,12 @@ public class CustomEditorTests { pvs.addPropertyValue(new PropertyValue("spouse", tbString)); bw.setPropertyValues(pvs); - assertTrue("spouse is non-null", tb.getSpouse() != null); - assertTrue("spouse name is Kerry and age is 34", - tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34); + assertThat(tb.getSpouse() != null).as("spouse is non-null").isTrue(); + assertThat(tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34).as("spouse name is Kerry and age is 34").isTrue(); ITestBean spouse = tb.getSpouse(); bw.setPropertyValues(pvs); - assertSame("Should have remained same object", spouse, tb.getSpouse()); + assertThat(tb.getSpouse()).as("Should have remained same object").isSameAs(spouse); } @Test @@ -126,10 +120,10 @@ public class CustomEditorTests { }); bw.setPropertyValue("name", "value"); bw.setPropertyValue("touchy", "value"); - assertEquals("prefixvalue", bw.getPropertyValue("name")); - assertEquals("prefixvalue", tb.getName()); - assertEquals("value", bw.getPropertyValue("touchy")); - assertEquals("value", tb.getTouchy()); + assertThat(bw.getPropertyValue("name")).isEqualTo("prefixvalue"); + assertThat(tb.getName()).isEqualTo("prefixvalue"); + assertThat(bw.getPropertyValue("touchy")).isEqualTo("value"); + assertThat(tb.getTouchy()).isEqualTo("value"); } @Test @@ -144,10 +138,10 @@ public class CustomEditorTests { }); bw.setPropertyValue("name", "value"); bw.setPropertyValue("touchy", "value"); - assertEquals("prefixvalue", bw.getPropertyValue("name")); - assertEquals("prefixvalue", tb.getName()); - assertEquals("prefixvalue", bw.getPropertyValue("touchy")); - assertEquals("prefixvalue", tb.getTouchy()); + assertThat(bw.getPropertyValue("name")).isEqualTo("prefixvalue"); + assertThat(tb.getName()).isEqualTo("prefixvalue"); + assertThat(bw.getPropertyValue("touchy")).isEqualTo("prefixvalue"); + assertThat(tb.getTouchy()).isEqualTo("prefixvalue"); } @Test @@ -163,10 +157,10 @@ public class CustomEditorTests { }); bw.setPropertyValue("spouse.name", "value"); bw.setPropertyValue("touchy", "value"); - assertEquals("prefixvalue", bw.getPropertyValue("spouse.name")); - assertEquals("prefixvalue", tb.getSpouse().getName()); - assertEquals("value", bw.getPropertyValue("touchy")); - assertEquals("value", tb.getTouchy()); + assertThat(bw.getPropertyValue("spouse.name")).isEqualTo("prefixvalue"); + assertThat(tb.getSpouse().getName()).isEqualTo("prefixvalue"); + assertThat(bw.getPropertyValue("touchy")).isEqualTo("value"); + assertThat(tb.getTouchy()).isEqualTo("value"); } @Test @@ -182,10 +176,10 @@ public class CustomEditorTests { }); bw.setPropertyValue("spouse.name", "value"); bw.setPropertyValue("touchy", "value"); - assertEquals("prefixvalue", bw.getPropertyValue("spouse.name")); - assertEquals("prefixvalue", tb.getSpouse().getName()); - assertEquals("prefixvalue", bw.getPropertyValue("touchy")); - assertEquals("prefixvalue", tb.getTouchy()); + assertThat(bw.getPropertyValue("spouse.name")).isEqualTo("prefixvalue"); + assertThat(tb.getSpouse().getName()).isEqualTo("prefixvalue"); + assertThat(bw.getPropertyValue("touchy")).isEqualTo("prefixvalue"); + assertThat(tb.getTouchy()).isEqualTo("prefixvalue"); } @Test @@ -194,36 +188,41 @@ public class CustomEditorTests { BeanWrapper bw = new BeanWrapperImpl(tb); bw.setPropertyValue("bool1", "true"); - assertTrue("Correct bool1 value", Boolean.TRUE.equals(bw.getPropertyValue("bool1"))); - assertTrue("Correct bool1 value", tb.isBool1()); + assertThat(Boolean.TRUE.equals(bw.getPropertyValue("bool1"))).as("Correct bool1 value").isTrue(); + assertThat(tb.isBool1()).as("Correct bool1 value").isTrue(); bw.setPropertyValue("bool1", "false"); - assertTrue("Correct bool1 value", Boolean.FALSE.equals(bw.getPropertyValue("bool1"))); - assertTrue("Correct bool1 value", !tb.isBool1()); + assertThat(Boolean.FALSE.equals(bw.getPropertyValue("bool1"))).as("Correct bool1 value").isTrue(); + boolean condition4 = !tb.isBool1(); + assertThat(condition4).as("Correct bool1 value").isTrue(); bw.setPropertyValue("bool1", " true "); - assertTrue("Correct bool1 value", tb.isBool1()); + assertThat(tb.isBool1()).as("Correct bool1 value").isTrue(); bw.setPropertyValue("bool1", " false "); - assertTrue("Correct bool1 value", !tb.isBool1()); + boolean condition3 = !tb.isBool1(); + assertThat(condition3).as("Correct bool1 value").isTrue(); bw.setPropertyValue("bool1", "on"); - assertTrue("Correct bool1 value", tb.isBool1()); + assertThat(tb.isBool1()).as("Correct bool1 value").isTrue(); bw.setPropertyValue("bool1", "off"); - assertTrue("Correct bool1 value", !tb.isBool1()); + boolean condition2 = !tb.isBool1(); + assertThat(condition2).as("Correct bool1 value").isTrue(); bw.setPropertyValue("bool1", "yes"); - assertTrue("Correct bool1 value", tb.isBool1()); + assertThat(tb.isBool1()).as("Correct bool1 value").isTrue(); bw.setPropertyValue("bool1", "no"); - assertTrue("Correct bool1 value", !tb.isBool1()); + boolean condition1 = !tb.isBool1(); + assertThat(condition1).as("Correct bool1 value").isTrue(); bw.setPropertyValue("bool1", "1"); - assertTrue("Correct bool1 value", tb.isBool1()); + assertThat(tb.isBool1()).as("Correct bool1 value").isTrue(); bw.setPropertyValue("bool1", "0"); - assertTrue("Correct bool1 value", !tb.isBool1()); + boolean condition = !tb.isBool1(); + assertThat(condition).as("Correct bool1 value").isTrue(); assertThatExceptionOfType(BeansException.class).isThrownBy(() -> bw.setPropertyValue("bool1", "argh")); @@ -235,33 +234,37 @@ public class CustomEditorTests { BeanWrapper bw = new BeanWrapperImpl(tb); bw.setPropertyValue("bool2", "true"); - assertTrue("Correct bool2 value", Boolean.TRUE.equals(bw.getPropertyValue("bool2"))); - assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); + assertThat(Boolean.TRUE.equals(bw.getPropertyValue("bool2"))).as("Correct bool2 value").isTrue(); + assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "false"); - assertTrue("Correct bool2 value", Boolean.FALSE.equals(bw.getPropertyValue("bool2"))); - assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); + assertThat(Boolean.FALSE.equals(bw.getPropertyValue("bool2"))).as("Correct bool2 value").isTrue(); + boolean condition3 = !tb.getBool2().booleanValue(); + assertThat(condition3).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "on"); - assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); + assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "off"); - assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); + boolean condition2 = !tb.getBool2().booleanValue(); + assertThat(condition2).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "yes"); - assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); + assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "no"); - assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); + boolean condition1 = !tb.getBool2().booleanValue(); + assertThat(condition1).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "1"); - assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); + assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "0"); - assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); + boolean condition = !tb.getBool2().booleanValue(); + assertThat(condition).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", ""); - assertNull("Correct bool2 value", tb.getBool2()); + assertThat(tb.getBool2()).as("Correct bool2 value").isNull(); } @Test @@ -271,34 +274,38 @@ public class CustomEditorTests { bw.registerCustomEditor(Boolean.class, new CustomBooleanEditor(true)); bw.setPropertyValue("bool2", "true"); - assertTrue("Correct bool2 value", Boolean.TRUE.equals(bw.getPropertyValue("bool2"))); - assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); + assertThat(Boolean.TRUE.equals(bw.getPropertyValue("bool2"))).as("Correct bool2 value").isTrue(); + assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "false"); - assertTrue("Correct bool2 value", Boolean.FALSE.equals(bw.getPropertyValue("bool2"))); - assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); + assertThat(Boolean.FALSE.equals(bw.getPropertyValue("bool2"))).as("Correct bool2 value").isTrue(); + boolean condition3 = !tb.getBool2().booleanValue(); + assertThat(condition3).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "on"); - assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); + assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "off"); - assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); + boolean condition2 = !tb.getBool2().booleanValue(); + assertThat(condition2).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "yes"); - assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); + assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "no"); - assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); + boolean condition1 = !tb.getBool2().booleanValue(); + assertThat(condition1).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "1"); - assertTrue("Correct bool2 value", tb.getBool2().booleanValue()); + assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "0"); - assertTrue("Correct bool2 value", !tb.getBool2().booleanValue()); + boolean condition = !tb.getBool2().booleanValue(); + assertThat(condition).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", ""); - assertTrue("Correct bool2 value", bw.getPropertyValue("bool2") == null); - assertTrue("Correct bool2 value", tb.getBool2() == null); + assertThat(bw.getPropertyValue("bool2") == null).as("Correct bool2 value").isTrue(); + assertThat(tb.getBool2() == null).as("Correct bool2 value").isTrue(); } @Test @@ -309,18 +316,18 @@ public class CustomEditorTests { CustomBooleanEditor editor = new CustomBooleanEditor(trueString, falseString, false); editor.setAsText(trueString); - assertTrue(((Boolean) editor.getValue()).booleanValue()); - assertEquals(trueString, editor.getAsText()); + assertThat(((Boolean) editor.getValue()).booleanValue()).isTrue(); + assertThat(editor.getAsText()).isEqualTo(trueString); editor.setAsText(falseString); - assertFalse(((Boolean) editor.getValue()).booleanValue()); - assertEquals(falseString, editor.getAsText()); + assertThat(((Boolean) editor.getValue()).booleanValue()).isFalse(); + assertThat(editor.getAsText()).isEqualTo(falseString); editor.setAsText(trueString.toUpperCase()); - assertTrue(((Boolean) editor.getValue()).booleanValue()); - assertEquals(trueString, editor.getAsText()); + assertThat(((Boolean) editor.getValue()).booleanValue()).isTrue(); + assertThat(editor.getAsText()).isEqualTo(trueString); editor.setAsText(falseString.toUpperCase()); - assertFalse(((Boolean) editor.getValue()).booleanValue()); - assertEquals(falseString, editor.getAsText()); + assertThat(((Boolean) editor.getValue()).booleanValue()).isFalse(); + assertThat(editor.getAsText()).isEqualTo(falseString); assertThatIllegalArgumentException().isThrownBy(() -> editor.setAsText(null)); } @@ -343,30 +350,30 @@ public class CustomEditorTests { bw.setPropertyValue("double2", "6.1"); bw.setPropertyValue("bigDecimal", "4.5"); - assertTrue("Correct short1 value", new Short("1").equals(bw.getPropertyValue("short1"))); - assertTrue("Correct short1 value", tb.getShort1() == 1); - assertTrue("Correct short2 value", new Short("2").equals(bw.getPropertyValue("short2"))); - assertTrue("Correct short2 value", new Short("2").equals(tb.getShort2())); - assertTrue("Correct int1 value", new Integer("7").equals(bw.getPropertyValue("int1"))); - assertTrue("Correct int1 value", tb.getInt1() == 7); - assertTrue("Correct int2 value", new Integer("8").equals(bw.getPropertyValue("int2"))); - assertTrue("Correct int2 value", new Integer("8").equals(tb.getInt2())); - assertTrue("Correct long1 value", new Long("5").equals(bw.getPropertyValue("long1"))); - assertTrue("Correct long1 value", tb.getLong1() == 5); - assertTrue("Correct long2 value", new Long("6").equals(bw.getPropertyValue("long2"))); - assertTrue("Correct long2 value", new Long("6").equals(tb.getLong2())); - assertTrue("Correct bigInteger value", new BigInteger("3").equals(bw.getPropertyValue("bigInteger"))); - assertTrue("Correct bigInteger value", new BigInteger("3").equals(tb.getBigInteger())); - assertTrue("Correct float1 value", new Float("7.1").equals(bw.getPropertyValue("float1"))); - assertTrue("Correct float1 value", new Float("7.1").equals(new Float(tb.getFloat1()))); - assertTrue("Correct float2 value", new Float("8.1").equals(bw.getPropertyValue("float2"))); - assertTrue("Correct float2 value", new Float("8.1").equals(tb.getFloat2())); - assertTrue("Correct double1 value", new Double("5.1").equals(bw.getPropertyValue("double1"))); - assertTrue("Correct double1 value", tb.getDouble1() == 5.1); - assertTrue("Correct double2 value", new Double("6.1").equals(bw.getPropertyValue("double2"))); - assertTrue("Correct double2 value", new Double("6.1").equals(tb.getDouble2())); - assertTrue("Correct bigDecimal value", new BigDecimal("4.5").equals(bw.getPropertyValue("bigDecimal"))); - assertTrue("Correct bigDecimal value", new BigDecimal("4.5").equals(tb.getBigDecimal())); + assertThat(new Short("1").equals(bw.getPropertyValue("short1"))).as("Correct short1 value").isTrue(); + assertThat(tb.getShort1() == 1).as("Correct short1 value").isTrue(); + assertThat(new Short("2").equals(bw.getPropertyValue("short2"))).as("Correct short2 value").isTrue(); + assertThat(new Short("2").equals(tb.getShort2())).as("Correct short2 value").isTrue(); + assertThat(new Integer("7").equals(bw.getPropertyValue("int1"))).as("Correct int1 value").isTrue(); + assertThat(tb.getInt1() == 7).as("Correct int1 value").isTrue(); + assertThat(new Integer("8").equals(bw.getPropertyValue("int2"))).as("Correct int2 value").isTrue(); + assertThat(new Integer("8").equals(tb.getInt2())).as("Correct int2 value").isTrue(); + assertThat(new Long("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue(); + assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue(); + assertThat(new Long("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); + assertThat(new Long("6").equals(tb.getLong2())).as("Correct long2 value").isTrue(); + assertThat(new BigInteger("3").equals(bw.getPropertyValue("bigInteger"))).as("Correct bigInteger value").isTrue(); + assertThat(new BigInteger("3").equals(tb.getBigInteger())).as("Correct bigInteger value").isTrue(); + assertThat(new Float("7.1").equals(bw.getPropertyValue("float1"))).as("Correct float1 value").isTrue(); + assertThat(new Float("7.1").equals(new Float(tb.getFloat1()))).as("Correct float1 value").isTrue(); + assertThat(new Float("8.1").equals(bw.getPropertyValue("float2"))).as("Correct float2 value").isTrue(); + assertThat(new Float("8.1").equals(tb.getFloat2())).as("Correct float2 value").isTrue(); + assertThat(new Double("5.1").equals(bw.getPropertyValue("double1"))).as("Correct double1 value").isTrue(); + assertThat(tb.getDouble1() == 5.1).as("Correct double1 value").isTrue(); + assertThat(new Double("6.1").equals(bw.getPropertyValue("double2"))).as("Correct double2 value").isTrue(); + assertThat(new Double("6.1").equals(tb.getDouble2())).as("Correct double2 value").isTrue(); + assertThat(new BigDecimal("4.5").equals(bw.getPropertyValue("bigDecimal"))).as("Correct bigDecimal value").isTrue(); + assertThat(new BigDecimal("4.5").equals(tb.getBigDecimal())).as("Correct bigDecimal value").isTrue(); } @Test @@ -400,30 +407,30 @@ public class CustomEditorTests { bw.setPropertyValue("double2", "6,1"); bw.setPropertyValue("bigDecimal", "4,5"); - assertTrue("Correct short1 value", new Short("1").equals(bw.getPropertyValue("short1"))); - assertTrue("Correct short1 value", tb.getShort1() == 1); - assertTrue("Correct short2 value", new Short("2").equals(bw.getPropertyValue("short2"))); - assertTrue("Correct short2 value", new Short("2").equals(tb.getShort2())); - assertTrue("Correct int1 value", new Integer("7").equals(bw.getPropertyValue("int1"))); - assertTrue("Correct int1 value", tb.getInt1() == 7); - assertTrue("Correct int2 value", new Integer("8").equals(bw.getPropertyValue("int2"))); - assertTrue("Correct int2 value", new Integer("8").equals(tb.getInt2())); - assertTrue("Correct long1 value", new Long("5").equals(bw.getPropertyValue("long1"))); - assertTrue("Correct long1 value", tb.getLong1() == 5); - assertTrue("Correct long2 value", new Long("6").equals(bw.getPropertyValue("long2"))); - assertTrue("Correct long2 value", new Long("6").equals(tb.getLong2())); - assertTrue("Correct bigInteger value", new BigInteger("3").equals(bw.getPropertyValue("bigInteger"))); - assertTrue("Correct bigInteger value", new BigInteger("3").equals(tb.getBigInteger())); - assertTrue("Correct float1 value", new Float("7.1").equals(bw.getPropertyValue("float1"))); - assertTrue("Correct float1 value", new Float("7.1").equals(new Float(tb.getFloat1()))); - assertTrue("Correct float2 value", new Float("8.1").equals(bw.getPropertyValue("float2"))); - assertTrue("Correct float2 value", new Float("8.1").equals(tb.getFloat2())); - assertTrue("Correct double1 value", new Double("5.1").equals(bw.getPropertyValue("double1"))); - assertTrue("Correct double1 value", tb.getDouble1() == 5.1); - assertTrue("Correct double2 value", new Double("6.1").equals(bw.getPropertyValue("double2"))); - assertTrue("Correct double2 value", new Double("6.1").equals(tb.getDouble2())); - assertTrue("Correct bigDecimal value", new BigDecimal("4.5").equals(bw.getPropertyValue("bigDecimal"))); - assertTrue("Correct bigDecimal value", new BigDecimal("4.5").equals(tb.getBigDecimal())); + assertThat(new Short("1").equals(bw.getPropertyValue("short1"))).as("Correct short1 value").isTrue(); + assertThat(tb.getShort1() == 1).as("Correct short1 value").isTrue(); + assertThat(new Short("2").equals(bw.getPropertyValue("short2"))).as("Correct short2 value").isTrue(); + assertThat(new Short("2").equals(tb.getShort2())).as("Correct short2 value").isTrue(); + assertThat(new Integer("7").equals(bw.getPropertyValue("int1"))).as("Correct int1 value").isTrue(); + assertThat(tb.getInt1() == 7).as("Correct int1 value").isTrue(); + assertThat(new Integer("8").equals(bw.getPropertyValue("int2"))).as("Correct int2 value").isTrue(); + assertThat(new Integer("8").equals(tb.getInt2())).as("Correct int2 value").isTrue(); + assertThat(new Long("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue(); + assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue(); + assertThat(new Long("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); + assertThat(new Long("6").equals(tb.getLong2())).as("Correct long2 value").isTrue(); + assertThat(new BigInteger("3").equals(bw.getPropertyValue("bigInteger"))).as("Correct bigInteger value").isTrue(); + assertThat(new BigInteger("3").equals(tb.getBigInteger())).as("Correct bigInteger value").isTrue(); + assertThat(new Float("7.1").equals(bw.getPropertyValue("float1"))).as("Correct float1 value").isTrue(); + assertThat(new Float("7.1").equals(new Float(tb.getFloat1()))).as("Correct float1 value").isTrue(); + assertThat(new Float("8.1").equals(bw.getPropertyValue("float2"))).as("Correct float2 value").isTrue(); + assertThat(new Float("8.1").equals(tb.getFloat2())).as("Correct float2 value").isTrue(); + assertThat(new Double("5.1").equals(bw.getPropertyValue("double1"))).as("Correct double1 value").isTrue(); + assertThat(tb.getDouble1() == 5.1).as("Correct double1 value").isTrue(); + assertThat(new Double("6.1").equals(bw.getPropertyValue("double2"))).as("Correct double2 value").isTrue(); + assertThat(new Double("6.1").equals(tb.getDouble2())).as("Correct double2 value").isTrue(); + assertThat(new BigDecimal("4.5").equals(bw.getPropertyValue("bigDecimal"))).as("Correct bigDecimal value").isTrue(); + assertThat(new BigDecimal("4.5").equals(tb.getBigDecimal())).as("Correct bigDecimal value").isTrue(); } @Test @@ -436,14 +443,14 @@ public class CustomEditorTests { bw.setPropertyValue("long1", "5"); bw.setPropertyValue("long2", "6"); - assertTrue("Correct long1 value", new Long("5").equals(bw.getPropertyValue("long1"))); - assertTrue("Correct long1 value", tb.getLong1() == 5); - assertTrue("Correct long2 value", new Long("6").equals(bw.getPropertyValue("long2"))); - assertTrue("Correct long2 value", new Long("6").equals(tb.getLong2())); + assertThat(new Long("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue(); + assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue(); + assertThat(new Long("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); + assertThat(new Long("6").equals(tb.getLong2())).as("Correct long2 value").isTrue(); bw.setPropertyValue("long2", ""); - assertTrue("Correct long2 value", bw.getPropertyValue("long2") == null); - assertTrue("Correct long2 value", tb.getLong2() == null); + assertThat(bw.getPropertyValue("long2") == null).as("Correct long2 value").isTrue(); + assertThat(tb.getLong2() == null).as("Correct long2 value").isTrue(); assertThatExceptionOfType(BeansException.class).isThrownBy(() -> bw.setPropertyValue("long1", "")); assertThat(bw.getPropertyValue("long1")).isEqualTo(5L); @@ -457,11 +464,14 @@ public class CustomEditorTests { BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, nf, true)); bw.setPropertyValue("bigDecimal", "1000"); - assertEquals(1000.0f, tb.getBigDecimal().floatValue(), 0f); + assertThat(tb.getBigDecimal().floatValue()).isCloseTo(1000.0f, within(0f)); + bw.setPropertyValue("bigDecimal", "1000,5"); - assertEquals(1000.5f, tb.getBigDecimal().floatValue(), 0f); + assertThat(tb.getBigDecimal().floatValue()).isCloseTo(1000.5f, within(0f)); + bw.setPropertyValue("bigDecimal", "1 000,5"); - assertEquals(1000.5f, tb.getBigDecimal().floatValue(), 0f); + assertThat(tb.getBigDecimal().floatValue()).isCloseTo(1000.5f, within(0f)); + } @Test @@ -476,7 +486,7 @@ public class CustomEditorTests { PrimitiveArrayBean bean = new PrimitiveArrayBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.setPropertyValue("byteArray", "myvalue"); - assertEquals("myvalue", new String(bean.getByteArray())); + assertThat(new String(bean.getByteArray())).isEqualTo("myvalue"); } @Test @@ -484,7 +494,7 @@ public class CustomEditorTests { PrimitiveArrayBean bean = new PrimitiveArrayBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.setPropertyValue("charArray", "myvalue"); - assertEquals("myvalue", new String(bean.getCharArray())); + assertThat(new String(bean.getCharArray())).isEqualTo("myvalue"); } @Test @@ -493,20 +503,20 @@ public class CustomEditorTests { BeanWrapper bw = new BeanWrapperImpl(cb); bw.setPropertyValue("myChar", new Character('c')); - assertEquals('c', cb.getMyChar()); + assertThat(cb.getMyChar()).isEqualTo('c'); bw.setPropertyValue("myChar", "c"); - assertEquals('c', cb.getMyChar()); + assertThat(cb.getMyChar()).isEqualTo('c'); bw.setPropertyValue("myChar", "\u0041"); - assertEquals('A', cb.getMyChar()); + assertThat(cb.getMyChar()).isEqualTo('A'); bw.setPropertyValue("myChar", "\\u0022"); - assertEquals('"', cb.getMyChar()); + assertThat(cb.getMyChar()).isEqualTo('"'); CharacterEditor editor = new CharacterEditor(false); editor.setAsText("M"); - assertEquals("M", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo("M"); } @Test @@ -516,19 +526,19 @@ public class CustomEditorTests { bw.registerCustomEditor(Character.class, new CharacterEditor(true)); bw.setPropertyValue("myCharacter", new Character('c')); - assertEquals(new Character('c'), cb.getMyCharacter()); + assertThat(cb.getMyCharacter()).isEqualTo(new Character('c')); bw.setPropertyValue("myCharacter", "c"); - assertEquals(new Character('c'), cb.getMyCharacter()); + assertThat(cb.getMyCharacter()).isEqualTo(new Character('c')); bw.setPropertyValue("myCharacter", "\u0041"); - assertEquals(new Character('A'), cb.getMyCharacter()); + assertThat(cb.getMyCharacter()).isEqualTo(new Character('A')); bw.setPropertyValue("myCharacter", " "); - assertEquals(new Character(' '), cb.getMyCharacter()); + assertThat(cb.getMyCharacter()).isEqualTo(new Character(' ')); bw.setPropertyValue("myCharacter", ""); - assertNull(cb.getMyCharacter()); + assertThat(cb.getMyCharacter()).isNull(); } @Test @@ -541,14 +551,14 @@ public class CustomEditorTests { @Test public void testCharacterEditorGetAsTextReturnsEmptyStringIfValueIsNull() throws Exception { PropertyEditor charEditor = new CharacterEditor(false); - assertEquals("", charEditor.getAsText()); + assertThat(charEditor.getAsText()).isEqualTo(""); charEditor = new CharacterEditor(true); charEditor.setAsText(null); - assertEquals("", charEditor.getAsText()); + assertThat(charEditor.getAsText()).isEqualTo(""); charEditor.setAsText(""); - assertEquals("", charEditor.getAsText()); + assertThat(charEditor.getAsText()).isEqualTo(""); charEditor.setAsText(" "); - assertEquals(" ", charEditor.getAsText()); + assertThat(charEditor.getAsText()).isEqualTo(" "); } @Test @@ -562,15 +572,15 @@ public class CustomEditorTests { public void testClassEditor() { PropertyEditor classEditor = new ClassEditor(); classEditor.setAsText(TestBean.class.getName()); - assertEquals(TestBean.class, classEditor.getValue()); - assertEquals(TestBean.class.getName(), classEditor.getAsText()); + assertThat(classEditor.getValue()).isEqualTo(TestBean.class); + assertThat(classEditor.getAsText()).isEqualTo(TestBean.class.getName()); classEditor.setAsText(null); - assertEquals("", classEditor.getAsText()); + assertThat(classEditor.getAsText()).isEqualTo(""); classEditor.setAsText(""); - assertEquals("", classEditor.getAsText()); + assertThat(classEditor.getAsText()).isEqualTo(""); classEditor.setAsText("\t "); - assertEquals("", classEditor.getAsText()); + assertThat(classEditor.getAsText()).isEqualTo(""); } @Test @@ -584,8 +594,8 @@ public class CustomEditorTests { public void testClassEditorWithArray() { PropertyEditor classEditor = new ClassEditor(); classEditor.setAsText("org.springframework.tests.sample.beans.TestBean[]"); - assertEquals(TestBean[].class, classEditor.getValue()); - assertEquals("org.springframework.tests.sample.beans.TestBean[]", classEditor.getAsText()); + assertThat(classEditor.getValue()).isEqualTo(TestBean[].class); + assertThat(classEditor.getAsText()).isEqualTo("org.springframework.tests.sample.beans.TestBean[]"); } /* @@ -596,7 +606,7 @@ public class CustomEditorTests { String[][] chessboard = new String[8][8]; ClassEditor editor = new ClassEditor(); editor.setValue(chessboard.getClass()); - assertEquals("java.lang.String[][]", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo("java.lang.String[][]"); } /* @@ -607,15 +617,15 @@ public class CustomEditorTests { String[][][][][] ridiculousChessboard = new String[8][4][0][1][3]; ClassEditor editor = new ClassEditor(); editor.setValue(ridiculousChessboard.getClass()); - assertEquals("java.lang.String[][][][][]", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo("java.lang.String[][][][][]"); } @Test public void testFileEditor() { PropertyEditor fileEditor = new FileEditor(); fileEditor.setAsText("file:myfile.txt"); - assertEquals(new File("myfile.txt"), fileEditor.getValue()); - assertEquals((new File("myfile.txt")).getPath(), fileEditor.getAsText()); + assertThat(fileEditor.getValue()).isEqualTo(new File("myfile.txt")); + assertThat(fileEditor.getAsText()).isEqualTo((new File("myfile.txt")).getPath()); } @Test @@ -636,12 +646,12 @@ public class CustomEditorTests { // testing on Windows if (new File("C:/myfile.txt").isAbsolute()) { fileEditor.setAsText("C:/myfile.txt"); - assertEquals(new File("C:/myfile.txt"), fileEditor.getValue()); + assertThat(fileEditor.getValue()).isEqualTo(new File("C:/myfile.txt")); } // testing on Unix if (new File("/myfile.txt").isAbsolute()) { fileEditor.setAsText("/myfile.txt"); - assertEquals(new File("/myfile.txt"), fileEditor.getValue()); + assertThat(fileEditor.getValue()).isEqualTo(new File("/myfile.txt")); } } @@ -649,11 +659,11 @@ public class CustomEditorTests { public void testLocaleEditor() { PropertyEditor localeEditor = new LocaleEditor(); localeEditor.setAsText("en_CA"); - assertEquals(Locale.CANADA, localeEditor.getValue()); - assertEquals("en_CA", localeEditor.getAsText()); + assertThat(localeEditor.getValue()).isEqualTo(Locale.CANADA); + assertThat(localeEditor.getAsText()).isEqualTo("en_CA"); localeEditor = new LocaleEditor(); - assertEquals("", localeEditor.getAsText()); + assertThat(localeEditor.getAsText()).isEqualTo(""); } @Test @@ -662,15 +672,15 @@ public class CustomEditorTests { PropertyEditor patternEditor = new PatternEditor(); patternEditor.setAsText(REGEX); - assertEquals(Pattern.compile(REGEX).pattern(), ((Pattern) patternEditor.getValue()).pattern()); - assertEquals(REGEX, patternEditor.getAsText()); + assertThat(((Pattern) patternEditor.getValue()).pattern()).isEqualTo(Pattern.compile(REGEX).pattern()); + assertThat(patternEditor.getAsText()).isEqualTo(REGEX); patternEditor = new PatternEditor(); - assertEquals("", patternEditor.getAsText()); + assertThat(patternEditor.getAsText()).isEqualTo(""); patternEditor = new PatternEditor(); patternEditor.setAsText(null); - assertEquals("", patternEditor.getAsText()); + assertThat(patternEditor.getAsText()).isEqualTo(""); } @Test @@ -678,16 +688,16 @@ public class CustomEditorTests { CustomBooleanEditor editor = new CustomBooleanEditor(false); editor.setAsText("true"); - assertEquals(Boolean.TRUE, editor.getValue()); - assertEquals("true", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(Boolean.TRUE); + assertThat(editor.getAsText()).isEqualTo("true"); editor.setAsText("false"); - assertEquals(Boolean.FALSE, editor.getValue()); - assertEquals("false", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(Boolean.FALSE); + assertThat(editor.getAsText()).isEqualTo("false"); editor.setValue(null); - assertEquals(null, editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(null); + assertThat(editor.getAsText()).isEqualTo(""); assertThatIllegalArgumentException().isThrownBy(() -> editor.setAsText(null)); @@ -698,32 +708,32 @@ public class CustomEditorTests { CustomBooleanEditor editor = new CustomBooleanEditor(true); editor.setAsText("true"); - assertEquals(Boolean.TRUE, editor.getValue()); - assertEquals("true", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(Boolean.TRUE); + assertThat(editor.getAsText()).isEqualTo("true"); editor.setAsText("false"); - assertEquals(Boolean.FALSE, editor.getValue()); - assertEquals("false", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(Boolean.FALSE); + assertThat(editor.getAsText()).isEqualTo("false"); editor.setValue(null); - assertEquals(null, editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(null); + assertThat(editor.getAsText()).isEqualTo(""); } @Test public void testCustomDateEditor() { CustomDateEditor editor = new CustomDateEditor(null, false); editor.setValue(null); - assertEquals(null, editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(null); + assertThat(editor.getAsText()).isEqualTo(""); } @Test public void testCustomDateEditorWithEmptyAsNull() { CustomDateEditor editor = new CustomDateEditor(null, true); editor.setValue(null); - assertEquals(null, editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(null); + assertThat(editor.getAsText()).isEqualTo(""); } @Test @@ -732,8 +742,8 @@ public class CustomEditorTests { String validDate = "01/01/2005"; String invalidDate = "01/01/05"; - assertTrue(validDate.length() == maxLength); - assertFalse(invalidDate.length() == maxLength); + assertThat(validDate.length() == maxLength).isTrue(); + assertThat(invalidDate.length() == maxLength).isFalse(); CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true, maxLength); editor.setAsText(validDate); @@ -746,98 +756,98 @@ public class CustomEditorTests { public void testCustomNumberEditor() { CustomNumberEditor editor = new CustomNumberEditor(Integer.class, false); editor.setAsText("5"); - assertEquals(new Integer(5), editor.getValue()); - assertEquals("5", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(new Integer(5)); + assertThat(editor.getAsText()).isEqualTo("5"); editor.setValue(null); - assertEquals(null, editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(null); + assertThat(editor.getAsText()).isEqualTo(""); } @Test public void testCustomNumberEditorWithHex() { CustomNumberEditor editor = new CustomNumberEditor(Integer.class, false); editor.setAsText("0x" + Integer.toHexString(64)); - assertEquals(new Integer(64), editor.getValue()); + assertThat(editor.getValue()).isEqualTo(new Integer(64)); } @Test public void testCustomNumberEditorWithEmptyAsNull() { CustomNumberEditor editor = new CustomNumberEditor(Integer.class, true); editor.setAsText("5"); - assertEquals(new Integer(5), editor.getValue()); - assertEquals("5", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(new Integer(5)); + assertThat(editor.getAsText()).isEqualTo("5"); editor.setAsText(""); - assertEquals(null, editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(null); + assertThat(editor.getAsText()).isEqualTo(""); editor.setValue(null); - assertEquals(null, editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(null); + assertThat(editor.getAsText()).isEqualTo(""); } @Test public void testStringTrimmerEditor() { StringTrimmerEditor editor = new StringTrimmerEditor(false); editor.setAsText("test"); - assertEquals("test", editor.getValue()); - assertEquals("test", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo("test"); + assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(" test "); - assertEquals("test", editor.getValue()); - assertEquals("test", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo("test"); + assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(""); - assertEquals("", editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(""); + assertThat(editor.getAsText()).isEqualTo(""); editor.setValue(null); - assertEquals("", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(""); editor.setAsText(null); - assertEquals("", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(""); } @Test public void testStringTrimmerEditorWithEmptyAsNull() { StringTrimmerEditor editor = new StringTrimmerEditor(true); editor.setAsText("test"); - assertEquals("test", editor.getValue()); - assertEquals("test", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo("test"); + assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(" test "); - assertEquals("test", editor.getValue()); - assertEquals("test", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo("test"); + assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(" "); - assertEquals(null, editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(null); + assertThat(editor.getAsText()).isEqualTo(""); editor.setValue(null); - assertEquals("", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(""); } @Test public void testStringTrimmerEditorWithCharsToDelete() { StringTrimmerEditor editor = new StringTrimmerEditor("\r\n\f", false); editor.setAsText("te\ns\ft"); - assertEquals("test", editor.getValue()); - assertEquals("test", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo("test"); + assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(" test "); - assertEquals("test", editor.getValue()); - assertEquals("test", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo("test"); + assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(""); - assertEquals("", editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(""); + assertThat(editor.getAsText()).isEqualTo(""); editor.setValue(null); - assertEquals("", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(""); } @Test public void testStringTrimmerEditorWithCharsToDeleteAndEmptyAsNull() { StringTrimmerEditor editor = new StringTrimmerEditor("\r\n\f", true); editor.setAsText("te\ns\ft"); - assertEquals("test", editor.getValue()); - assertEquals("test", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo("test"); + assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(" test "); - assertEquals("test", editor.getValue()); - assertEquals("test", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo("test"); + assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(" \n\f "); - assertEquals(null, editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isEqualTo(null); + assertThat(editor.getAsText()).isEqualTo(""); editor.setValue(null); - assertEquals("", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(""); } @Test @@ -856,20 +866,20 @@ public class CustomEditorTests { TestBean tb3 = ((TestBean) bean.getList().get(1)); TestBean tb4 = ((TestBean) bean.getMap().get("key1")); TestBean tb5 = ((TestBean) bean.getMap().get("key2")); - assertEquals("name0", tb0.getName()); - assertEquals("name1", tb1.getName()); - assertEquals("name2", tb2.getName()); - assertEquals("name3", tb3.getName()); - assertEquals("name4", tb4.getName()); - assertEquals("name5", tb5.getName()); - assertEquals("name0", bw.getPropertyValue("array[0].name")); - assertEquals("name1", bw.getPropertyValue("array[1].name")); - assertEquals("name2", bw.getPropertyValue("list[0].name")); - assertEquals("name3", bw.getPropertyValue("list[1].name")); - assertEquals("name4", bw.getPropertyValue("map[key1].name")); - assertEquals("name5", bw.getPropertyValue("map[key2].name")); - assertEquals("name4", bw.getPropertyValue("map['key1'].name")); - assertEquals("name5", bw.getPropertyValue("map[\"key2\"].name")); + assertThat(tb0.getName()).isEqualTo("name0"); + assertThat(tb1.getName()).isEqualTo("name1"); + assertThat(tb2.getName()).isEqualTo("name2"); + assertThat(tb3.getName()).isEqualTo("name3"); + assertThat(tb4.getName()).isEqualTo("name4"); + assertThat(tb5.getName()).isEqualTo("name5"); + assertThat(bw.getPropertyValue("array[0].name")).isEqualTo("name0"); + assertThat(bw.getPropertyValue("array[1].name")).isEqualTo("name1"); + assertThat(bw.getPropertyValue("list[0].name")).isEqualTo("name2"); + assertThat(bw.getPropertyValue("list[1].name")).isEqualTo("name3"); + assertThat(bw.getPropertyValue("map[key1].name")).isEqualTo("name4"); + assertThat(bw.getPropertyValue("map[key2].name")).isEqualTo("name5"); + assertThat(bw.getPropertyValue("map['key1'].name")).isEqualTo("name4"); + assertThat(bw.getPropertyValue("map[\"key2\"].name")).isEqualTo("name5"); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0].name", "name5"); @@ -879,18 +889,18 @@ public class CustomEditorTests { pvs.add("map[key1].name", "name1"); pvs.add("map['key2'].name", "name0"); bw.setPropertyValues(pvs); - assertEquals("prefixname5", tb0.getName()); - assertEquals("prefixname4", tb1.getName()); - assertEquals("prefixname3", tb2.getName()); - assertEquals("prefixname2", tb3.getName()); - assertEquals("prefixname1", tb4.getName()); - assertEquals("prefixname0", tb5.getName()); - assertEquals("prefixname5", bw.getPropertyValue("array[0].name")); - assertEquals("prefixname4", bw.getPropertyValue("array[1].name")); - assertEquals("prefixname3", bw.getPropertyValue("list[0].name")); - assertEquals("prefixname2", bw.getPropertyValue("list[1].name")); - assertEquals("prefixname1", bw.getPropertyValue("map[\"key1\"].name")); - assertEquals("prefixname0", bw.getPropertyValue("map['key2'].name")); + assertThat(tb0.getName()).isEqualTo("prefixname5"); + assertThat(tb1.getName()).isEqualTo("prefixname4"); + assertThat(tb2.getName()).isEqualTo("prefixname3"); + assertThat(tb3.getName()).isEqualTo("prefixname2"); + assertThat(tb4.getName()).isEqualTo("prefixname1"); + assertThat(tb5.getName()).isEqualTo("prefixname0"); + assertThat(bw.getPropertyValue("array[0].name")).isEqualTo("prefixname5"); + assertThat(bw.getPropertyValue("array[1].name")).isEqualTo("prefixname4"); + assertThat(bw.getPropertyValue("list[0].name")).isEqualTo("prefixname3"); + assertThat(bw.getPropertyValue("list[1].name")).isEqualTo("prefixname2"); + assertThat(bw.getPropertyValue("map[\"key1\"].name")).isEqualTo("prefixname1"); + assertThat(bw.getPropertyValue("map['key2'].name")).isEqualTo("prefixname0"); } @Test @@ -923,20 +933,20 @@ public class CustomEditorTests { TestBean tb3 = ((TestBean) bean.getList().get(1)); TestBean tb4 = ((TestBean) bean.getMap().get("key1")); TestBean tb5 = ((TestBean) bean.getMap().get("key2")); - assertEquals("name0", tb0.getName()); - assertEquals("name1", tb1.getName()); - assertEquals("name2", tb2.getName()); - assertEquals("name3", tb3.getName()); - assertEquals("name4", tb4.getName()); - assertEquals("name5", tb5.getName()); - assertEquals("name0", bw.getPropertyValue("array[0].name")); - assertEquals("name1", bw.getPropertyValue("array[1].name")); - assertEquals("name2", bw.getPropertyValue("list[0].name")); - assertEquals("name3", bw.getPropertyValue("list[1].name")); - assertEquals("name4", bw.getPropertyValue("map[key1].name")); - assertEquals("name5", bw.getPropertyValue("map[key2].name")); - assertEquals("name4", bw.getPropertyValue("map['key1'].name")); - assertEquals("name5", bw.getPropertyValue("map[\"key2\"].name")); + assertThat(tb0.getName()).isEqualTo("name0"); + assertThat(tb1.getName()).isEqualTo("name1"); + assertThat(tb2.getName()).isEqualTo("name2"); + assertThat(tb3.getName()).isEqualTo("name3"); + assertThat(tb4.getName()).isEqualTo("name4"); + assertThat(tb5.getName()).isEqualTo("name5"); + assertThat(bw.getPropertyValue("array[0].name")).isEqualTo("name0"); + assertThat(bw.getPropertyValue("array[1].name")).isEqualTo("name1"); + assertThat(bw.getPropertyValue("list[0].name")).isEqualTo("name2"); + assertThat(bw.getPropertyValue("list[1].name")).isEqualTo("name3"); + assertThat(bw.getPropertyValue("map[key1].name")).isEqualTo("name4"); + assertThat(bw.getPropertyValue("map[key2].name")).isEqualTo("name5"); + assertThat(bw.getPropertyValue("map['key1'].name")).isEqualTo("name4"); + assertThat(bw.getPropertyValue("map[\"key2\"].name")).isEqualTo("name5"); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0].name", "name5"); @@ -946,18 +956,18 @@ public class CustomEditorTests { pvs.add("map[key1].name", "name1"); pvs.add("map['key2'].name", "name0"); bw.setPropertyValues(pvs); - assertEquals("arrayname5", tb0.getName()); - assertEquals("arrayname4", tb1.getName()); - assertEquals("listname3", tb2.getName()); - assertEquals("listname2", tb3.getName()); - assertEquals("mapname1", tb4.getName()); - assertEquals("mapname0", tb5.getName()); - assertEquals("arrayname5", bw.getPropertyValue("array[0].name")); - assertEquals("arrayname4", bw.getPropertyValue("array[1].name")); - assertEquals("listname3", bw.getPropertyValue("list[0].name")); - assertEquals("listname2", bw.getPropertyValue("list[1].name")); - assertEquals("mapname1", bw.getPropertyValue("map[\"key1\"].name")); - assertEquals("mapname0", bw.getPropertyValue("map['key2'].name")); + assertThat(tb0.getName()).isEqualTo("arrayname5"); + assertThat(tb1.getName()).isEqualTo("arrayname4"); + assertThat(tb2.getName()).isEqualTo("listname3"); + assertThat(tb3.getName()).isEqualTo("listname2"); + assertThat(tb4.getName()).isEqualTo("mapname1"); + assertThat(tb5.getName()).isEqualTo("mapname0"); + assertThat(bw.getPropertyValue("array[0].name")).isEqualTo("arrayname5"); + assertThat(bw.getPropertyValue("array[1].name")).isEqualTo("arrayname4"); + assertThat(bw.getPropertyValue("list[0].name")).isEqualTo("listname3"); + assertThat(bw.getPropertyValue("list[1].name")).isEqualTo("listname2"); + assertThat(bw.getPropertyValue("map[\"key1\"].name")).isEqualTo("mapname1"); + assertThat(bw.getPropertyValue("map['key2'].name")).isEqualTo("mapname0"); } @Test @@ -1008,20 +1018,20 @@ public class CustomEditorTests { TestBean tb3 = ((TestBean) bean.getList().get(1)); TestBean tb4 = ((TestBean) bean.getMap().get("key1")); TestBean tb5 = ((TestBean) bean.getMap().get("key2")); - assertEquals("name0", tb0.getName()); - assertEquals("name1", tb1.getName()); - assertEquals("name2", tb2.getName()); - assertEquals("name3", tb3.getName()); - assertEquals("name4", tb4.getName()); - assertEquals("name5", tb5.getName()); - assertEquals("name0", bw.getPropertyValue("array[0].name")); - assertEquals("name1", bw.getPropertyValue("array[1].name")); - assertEquals("name2", bw.getPropertyValue("list[0].name")); - assertEquals("name3", bw.getPropertyValue("list[1].name")); - assertEquals("name4", bw.getPropertyValue("map[key1].name")); - assertEquals("name5", bw.getPropertyValue("map[key2].name")); - assertEquals("name4", bw.getPropertyValue("map['key1'].name")); - assertEquals("name5", bw.getPropertyValue("map[\"key2\"].name")); + assertThat(tb0.getName()).isEqualTo("name0"); + assertThat(tb1.getName()).isEqualTo("name1"); + assertThat(tb2.getName()).isEqualTo("name2"); + assertThat(tb3.getName()).isEqualTo("name3"); + assertThat(tb4.getName()).isEqualTo("name4"); + assertThat(tb5.getName()).isEqualTo("name5"); + assertThat(bw.getPropertyValue("array[0].name")).isEqualTo("name0"); + assertThat(bw.getPropertyValue("array[1].name")).isEqualTo("name1"); + assertThat(bw.getPropertyValue("list[0].name")).isEqualTo("name2"); + assertThat(bw.getPropertyValue("list[1].name")).isEqualTo("name3"); + assertThat(bw.getPropertyValue("map[key1].name")).isEqualTo("name4"); + assertThat(bw.getPropertyValue("map[key2].name")).isEqualTo("name5"); + assertThat(bw.getPropertyValue("map['key1'].name")).isEqualTo("name4"); + assertThat(bw.getPropertyValue("map[\"key2\"].name")).isEqualTo("name5"); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0].name", "name5"); @@ -1031,18 +1041,18 @@ public class CustomEditorTests { pvs.add("map[key1].name", "name1"); pvs.add("map['key2'].name", "name0"); bw.setPropertyValues(pvs); - assertEquals("array0name5", tb0.getName()); - assertEquals("array1name4", tb1.getName()); - assertEquals("list0name3", tb2.getName()); - assertEquals("list1name2", tb3.getName()); - assertEquals("mapkey1name1", tb4.getName()); - assertEquals("mapkey2name0", tb5.getName()); - assertEquals("array0name5", bw.getPropertyValue("array[0].name")); - assertEquals("array1name4", bw.getPropertyValue("array[1].name")); - assertEquals("list0name3", bw.getPropertyValue("list[0].name")); - assertEquals("list1name2", bw.getPropertyValue("list[1].name")); - assertEquals("mapkey1name1", bw.getPropertyValue("map[\"key1\"].name")); - assertEquals("mapkey2name0", bw.getPropertyValue("map['key2'].name")); + assertThat(tb0.getName()).isEqualTo("array0name5"); + assertThat(tb1.getName()).isEqualTo("array1name4"); + assertThat(tb2.getName()).isEqualTo("list0name3"); + assertThat(tb3.getName()).isEqualTo("list1name2"); + assertThat(tb4.getName()).isEqualTo("mapkey1name1"); + assertThat(tb5.getName()).isEqualTo("mapkey2name0"); + assertThat(bw.getPropertyValue("array[0].name")).isEqualTo("array0name5"); + assertThat(bw.getPropertyValue("array[1].name")).isEqualTo("array1name4"); + assertThat(bw.getPropertyValue("list[0].name")).isEqualTo("list0name3"); + assertThat(bw.getPropertyValue("list[1].name")).isEqualTo("list1name2"); + assertThat(bw.getPropertyValue("map[\"key1\"].name")).isEqualTo("mapkey1name1"); + assertThat(bw.getPropertyValue("map['key2'].name")).isEqualTo("mapkey2name0"); } @Test @@ -1094,18 +1104,18 @@ public class CustomEditorTests { return ((String) getValue()).substring(4); } }); - assertEquals("name0", tb0.getName()); - assertEquals("name1", tb1.getName()); - assertEquals("name2", tb2.getName()); - assertEquals("name3", tb3.getName()); - assertEquals("name4", tb4.getName()); - assertEquals("name5", tb5.getName()); - assertEquals("name0", bw.getPropertyValue("array[0].nestedIndexedBean.array[0].name")); - assertEquals("name1", bw.getPropertyValue("array[1].nestedIndexedBean.array[1].name")); - assertEquals("name2", bw.getPropertyValue("list[0].nestedIndexedBean.list[0].name")); - assertEquals("name3", bw.getPropertyValue("list[1].nestedIndexedBean.list[1].name")); - assertEquals("name4", bw.getPropertyValue("map[key1].nestedIndexedBean.map[key1].name")); - assertEquals("name5", bw.getPropertyValue("map['key2'].nestedIndexedBean.map[\"key2\"].name")); + assertThat(tb0.getName()).isEqualTo("name0"); + assertThat(tb1.getName()).isEqualTo("name1"); + assertThat(tb2.getName()).isEqualTo("name2"); + assertThat(tb3.getName()).isEqualTo("name3"); + assertThat(tb4.getName()).isEqualTo("name4"); + assertThat(tb5.getName()).isEqualTo("name5"); + assertThat(bw.getPropertyValue("array[0].nestedIndexedBean.array[0].name")).isEqualTo("name0"); + assertThat(bw.getPropertyValue("array[1].nestedIndexedBean.array[1].name")).isEqualTo("name1"); + assertThat(bw.getPropertyValue("list[0].nestedIndexedBean.list[0].name")).isEqualTo("name2"); + assertThat(bw.getPropertyValue("list[1].nestedIndexedBean.list[1].name")).isEqualTo("name3"); + assertThat(bw.getPropertyValue("map[key1].nestedIndexedBean.map[key1].name")).isEqualTo("name4"); + assertThat(bw.getPropertyValue("map['key2'].nestedIndexedBean.map[\"key2\"].name")).isEqualTo("name5"); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("array[0].nestedIndexedBean.array[0].name", "name5"); @@ -1115,18 +1125,18 @@ public class CustomEditorTests { pvs.add("map[key1].nestedIndexedBean.map[\"key1\"].name", "name1"); pvs.add("map['key2'].nestedIndexedBean.map[key2].name", "name0"); bw.setPropertyValues(pvs); - assertEquals("arrayname5", tb0.getNestedIndexedBean().getArray()[0].getName()); - assertEquals("arrayname4", tb1.getNestedIndexedBean().getArray()[1].getName()); - assertEquals("listname3", ((TestBean) tb2.getNestedIndexedBean().getList().get(0)).getName()); - assertEquals("listname2", ((TestBean) tb3.getNestedIndexedBean().getList().get(1)).getName()); - assertEquals("mapname1", ((TestBean) tb4.getNestedIndexedBean().getMap().get("key1")).getName()); - assertEquals("mapname0", ((TestBean) tb5.getNestedIndexedBean().getMap().get("key2")).getName()); - assertEquals("arrayname5", bw.getPropertyValue("array[0].nestedIndexedBean.array[0].name")); - assertEquals("arrayname4", bw.getPropertyValue("array[1].nestedIndexedBean.array[1].name")); - assertEquals("listname3", bw.getPropertyValue("list[0].nestedIndexedBean.list[0].name")); - assertEquals("listname2", bw.getPropertyValue("list[1].nestedIndexedBean.list[1].name")); - assertEquals("mapname1", bw.getPropertyValue("map['key1'].nestedIndexedBean.map[key1].name")); - assertEquals("mapname0", bw.getPropertyValue("map[key2].nestedIndexedBean.map[\"key2\"].name")); + assertThat(tb0.getNestedIndexedBean().getArray()[0].getName()).isEqualTo("arrayname5"); + assertThat(tb1.getNestedIndexedBean().getArray()[1].getName()).isEqualTo("arrayname4"); + assertThat(((TestBean) tb2.getNestedIndexedBean().getList().get(0)).getName()).isEqualTo("listname3"); + assertThat(((TestBean) tb3.getNestedIndexedBean().getList().get(1)).getName()).isEqualTo("listname2"); + assertThat(((TestBean) tb4.getNestedIndexedBean().getMap().get("key1")).getName()).isEqualTo("mapname1"); + assertThat(((TestBean) tb5.getNestedIndexedBean().getMap().get("key2")).getName()).isEqualTo("mapname0"); + assertThat(bw.getPropertyValue("array[0].nestedIndexedBean.array[0].name")).isEqualTo("arrayname5"); + assertThat(bw.getPropertyValue("array[1].nestedIndexedBean.array[1].name")).isEqualTo("arrayname4"); + assertThat(bw.getPropertyValue("list[0].nestedIndexedBean.list[0].name")).isEqualTo("listname3"); + assertThat(bw.getPropertyValue("list[1].nestedIndexedBean.list[1].name")).isEqualTo("listname2"); + assertThat(bw.getPropertyValue("map['key1'].nestedIndexedBean.map[key1].name")).isEqualTo("mapname1"); + assertThat(bw.getPropertyValue("map[key2].nestedIndexedBean.map[\"key2\"].name")).isEqualTo("mapname0"); } @Test @@ -1172,12 +1182,12 @@ public class CustomEditorTests { pvs.add("map[key1].nestedIndexedBean.map[\"key1\"].name", "name1"); pvs.add("map['key2'].nestedIndexedBean.map[key2].name", "name0"); bw.setPropertyValues(pvs); - assertEquals("arrayname5", tb0.getNestedIndexedBean().getArray()[0].getName()); - assertEquals("name4", tb1.getNestedIndexedBean().getArray()[1].getName()); - assertEquals("name3", ((TestBean) tb2.getNestedIndexedBean().getList().get(0)).getName()); - assertEquals("listname2", ((TestBean) tb3.getNestedIndexedBean().getList().get(1)).getName()); - assertEquals("mapname1", ((TestBean) tb4.getNestedIndexedBean().getMap().get("key1")).getName()); - assertEquals("name0", ((TestBean) tb5.getNestedIndexedBean().getMap().get("key2")).getName()); + assertThat(tb0.getNestedIndexedBean().getArray()[0].getName()).isEqualTo("arrayname5"); + assertThat(tb1.getNestedIndexedBean().getArray()[1].getName()).isEqualTo("name4"); + assertThat(((TestBean) tb2.getNestedIndexedBean().getList().get(0)).getName()).isEqualTo("name3"); + assertThat(((TestBean) tb3.getNestedIndexedBean().getList().get(1)).getName()).isEqualTo("listname2"); + assertThat(((TestBean) tb4.getNestedIndexedBean().getMap().get("key1")).getName()).isEqualTo("mapname1"); + assertThat(((TestBean) tb5.getNestedIndexedBean().getMap().get("key2")).getName()).isEqualTo("name0"); } @Test @@ -1226,12 +1236,12 @@ public class CustomEditorTests { pvs.add("map[key1]", "e"); pvs.add("map['key2']", "f"); bw.setPropertyValues(pvs); - assertEquals("arraya", bean.getArray()[0].getName()); - assertEquals("arrayb", bean.getArray()[1].getName()); - assertEquals("listc", ((TestBean) bean.getList().get(0)).getName()); - assertEquals("listd", ((TestBean) bean.getList().get(1)).getName()); - assertEquals("mape", ((TestBean) bean.getMap().get("key1")).getName()); - assertEquals("mapf", ((TestBean) bean.getMap().get("key2")).getName()); + assertThat(bean.getArray()[0].getName()).isEqualTo("arraya"); + assertThat(bean.getArray()[1].getName()).isEqualTo("arrayb"); + assertThat(((TestBean) bean.getList().get(0)).getName()).isEqualTo("listc"); + assertThat(((TestBean) bean.getList().get(1)).getName()).isEqualTo("listd"); + assertThat(((TestBean) bean.getMap().get("key1")).getName()).isEqualTo("mape"); + assertThat(((TestBean) bean.getMap().get("key2")).getName()).isEqualTo("mapf"); } @Test @@ -1313,12 +1323,12 @@ public class CustomEditorTests { pvs.add("map[key1]", "e"); pvs.add("map['key2']", "f"); bw.setPropertyValues(pvs); - assertEquals("array0a", bean.getArray()[0].getName()); - assertEquals("array1b", bean.getArray()[1].getName()); - assertEquals("list0c", ((TestBean) bean.getList().get(0)).getName()); - assertEquals("list1d", ((TestBean) bean.getList().get(1)).getName()); - assertEquals("mapkey1e", ((TestBean) bean.getMap().get("key1")).getName()); - assertEquals("mapkey2f", ((TestBean) bean.getMap().get("key2")).getName()); + assertThat(bean.getArray()[0].getName()).isEqualTo("array0a"); + assertThat(bean.getArray()[1].getName()).isEqualTo("array1b"); + assertThat(((TestBean) bean.getList().get(0)).getName()).isEqualTo("list0c"); + assertThat(((TestBean) bean.getList().get(1)).getName()).isEqualTo("list1d"); + assertThat(((TestBean) bean.getMap().get("key1")).getName()).isEqualTo("mapkey1e"); + assertThat(((TestBean) bean.getMap().get("key2")).getName()).isEqualTo("mapkey2f"); } @Test @@ -1334,9 +1344,9 @@ public class CustomEditorTests { } }); bw.setPropertyValue("list", "1"); - assertEquals("list1", ((TestBean) bean.getList().get(0)).getName()); + assertThat(((TestBean) bean.getList().get(0)).getName()).isEqualTo("list1"); bw.setPropertyValue("list[0]", "test"); - assertEquals("test", bean.getList().get(0)); + assertThat(bean.getList().get(0)).isEqualTo("test"); } @Test @@ -1347,13 +1357,13 @@ public class CustomEditorTests { bw.registerCustomEditor(Hashtable.class, new CustomMapEditor(Hashtable.class)); bw.setPropertyValue("vector", new String[] {"a", "b"}); - assertEquals(2, tb.getVector().size()); - assertEquals("a", tb.getVector().get(0)); - assertEquals("b", tb.getVector().get(1)); + assertThat(tb.getVector().size()).isEqualTo(2); + assertThat(tb.getVector().get(0)).isEqualTo("a"); + assertThat(tb.getVector().get(1)).isEqualTo("b"); bw.setPropertyValue("hashtable", Collections.singletonMap("foo", "bar")); - assertEquals(1, tb.getHashtable().size()); - assertEquals("bar", tb.getHashtable().get("foo")); + assertThat(tb.getHashtable().size()).isEqualTo(1); + assertThat(tb.getHashtable().get("foo")).isEqualTo("bar"); } @Test @@ -1365,11 +1375,11 @@ public class CustomEditorTests { TestBean tb = new TestBean(); bw.setPropertyValue("list", new ArrayList<>()); bw.setPropertyValue("list[0]", tb); - assertEquals(tb, bean.getList().get(0)); - assertEquals(pe, bw.findCustomEditor(int.class, "list.age")); - assertEquals(pe, bw.findCustomEditor(null, "list.age")); - assertEquals(pe, bw.findCustomEditor(int.class, "list[0].age")); - assertEquals(pe, bw.findCustomEditor(null, "list[0].age")); + assertThat(bean.getList().get(0)).isEqualTo(tb); + assertThat(bw.findCustomEditor(int.class, "list.age")).isEqualTo(pe); + assertThat(bw.findCustomEditor(null, "list.age")).isEqualTo(pe); + assertThat(bw.findCustomEditor(int.class, "list[0].age")).isEqualTo(pe); + assertThat(bw.findCustomEditor(null, "list[0].age")).isEqualTo(pe); } @Test @@ -1383,9 +1393,9 @@ public class CustomEditorTests { } }); bw.setPropertyValue("array", new String[] {"a", "b"}); - assertEquals(2, tb.getArray().length); - assertEquals("a", tb.getArray()[0].getName()); - assertEquals("b", tb.getArray()[1].getName()); + assertThat(tb.getArray().length).isEqualTo(2); + assertThat(tb.getArray()[0].getName()).isEqualTo("a"); + assertThat(tb.getArray()[1].getName()).isEqualTo("b"); } @Test @@ -1399,7 +1409,7 @@ public class CustomEditorTests { } }); bw.setPropertyValue("name", new String[] {"a", "b"}); - assertEquals("-a,b-", tb.getName()); + assertThat(tb.getName()).isEqualTo("-a,b-"); } @Test @@ -1407,10 +1417,10 @@ public class CustomEditorTests { ClassArrayEditor classArrayEditor = new ClassArrayEditor(); classArrayEditor.setAsText("java.lang.String,java.util.HashMap"); Class[] classes = (Class[]) classArrayEditor.getValue(); - assertEquals(2, classes.length); - assertEquals(String.class, classes[0]); - assertEquals(HashMap.class, classes[1]); - assertEquals("java.lang.String,java.util.HashMap", classArrayEditor.getAsText()); + assertThat(classes.length).isEqualTo(2); + assertThat(classes[0]).isEqualTo(String.class); + assertThat(classes[1]).isEqualTo(HashMap.class); + assertThat(classArrayEditor.getAsText()).isEqualTo("java.lang.String,java.util.HashMap"); // ensure setAsText can consume the return value of getAsText classArrayEditor.setAsText(classArrayEditor.getAsText()); } @@ -1420,12 +1430,12 @@ public class CustomEditorTests { ClassArrayEditor classArrayEditor = new ClassArrayEditor(); classArrayEditor.setAsText("java.lang.String[],java.util.Map[],int[],float[][][]"); Class[] classes = (Class[]) classArrayEditor.getValue(); - assertEquals(4, classes.length); - assertEquals(String[].class, classes[0]); - assertEquals(Map[].class, classes[1]); - assertEquals(int[].class, classes[2]); - assertEquals(float[][][].class, classes[3]); - assertEquals("java.lang.String[],java.util.Map[],int[],float[][][]", classArrayEditor.getAsText()); + assertThat(classes.length).isEqualTo(4); + assertThat(classes[0]).isEqualTo(String[].class); + assertThat(classes[1]).isEqualTo(Map[].class); + assertThat(classes[2]).isEqualTo(int[].class); + assertThat(classes[3]).isEqualTo(float[][][].class); + assertThat(classArrayEditor.getAsText()).isEqualTo("java.lang.String[],java.util.Map[],int[],float[][][]"); // ensure setAsText can consume the return value of getAsText classArrayEditor.setAsText(classArrayEditor.getAsText()); } @@ -1434,24 +1444,24 @@ public class CustomEditorTests { public void testClassArrayEditorSetAsTextWithNull() throws Exception { ClassArrayEditor editor = new ClassArrayEditor(); editor.setAsText(null); - assertNull(editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEqualTo(""); } @Test public void testClassArrayEditorSetAsTextWithEmptyString() throws Exception { ClassArrayEditor editor = new ClassArrayEditor(); editor.setAsText(""); - assertNull(editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEqualTo(""); } @Test public void testClassArrayEditorSetAsTextWithWhitespaceString() throws Exception { ClassArrayEditor editor = new ClassArrayEditor(); editor.setAsText("\n"); - assertNull(editor.getValue()); - assertEquals("", editor.getAsText()); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEqualTo(""); } @Test @@ -1460,9 +1470,9 @@ public class CustomEditorTests { String name = "UTF-8"; editor.setAsText(name); Charset charset = Charset.forName(name); - assertEquals("Invalid Charset conversion", charset, editor.getValue()); + assertThat(editor.getValue()).as("Invalid Charset conversion").isEqualTo(charset); editor.setValue(charset); - assertEquals("Invalid Charset conversion", name, editor.getAsText()); + assertThat(editor.getAsText()).as("Invalid Charset conversion").isEqualTo(name); } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/FileEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/FileEditorTests.java index bf1d16663db..1dbd7addc27 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/FileEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/FileEditorTests.java @@ -23,9 +23,8 @@ import org.junit.Test; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Thomas Risberg @@ -40,9 +39,10 @@ public class FileEditorTests { fileEditor.setAsText("classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class"); Object value = fileEditor.getValue(); - assertTrue(value instanceof File); + boolean condition = value instanceof File; + assertThat(condition).isTrue(); File file = (File) value; - assertTrue(file.exists()); + assertThat(file.exists()).isTrue(); } @Test @@ -57,9 +57,11 @@ public class FileEditorTests { PropertyEditor fileEditor = new FileEditor(); fileEditor.setAsText("file:no_way_this_file_is_found.doc"); Object value = fileEditor.getValue(); - assertTrue(value instanceof File); + boolean condition1 = value instanceof File; + assertThat(condition1).isTrue(); File file = (File) value; - assertTrue(!file.exists()); + boolean condition = !file.exists(); + assertThat(condition).isTrue(); } @Test @@ -67,9 +69,11 @@ public class FileEditorTests { PropertyEditor fileEditor = new FileEditor(); fileEditor.setAsText("/no_way_this_file_is_found.doc"); Object value = fileEditor.getValue(); - assertTrue(value instanceof File); + boolean condition1 = value instanceof File; + assertThat(condition1).isTrue(); File file = (File) value; - assertTrue(!file.exists()); + boolean condition = !file.exists(); + assertThat(condition).isTrue(); } @Test @@ -79,11 +83,12 @@ public class FileEditorTests { ClassUtils.getShortName(getClass()) + ".class"; fileEditor.setAsText(fileName); Object value = fileEditor.getValue(); - assertTrue(value instanceof File); + boolean condition = value instanceof File; + assertThat(condition).isTrue(); File file = (File) value; - assertTrue(file.exists()); + assertThat(file.exists()).isTrue(); String absolutePath = file.getAbsolutePath().replace('\\', '/'); - assertTrue(absolutePath.endsWith(fileName)); + assertThat(absolutePath.endsWith(fileName)).isTrue(); } @Test @@ -93,11 +98,12 @@ public class FileEditorTests { ClassUtils.getShortName(getClass()) + ".clazz"; fileEditor.setAsText(fileName); Object value = fileEditor.getValue(); - assertTrue(value instanceof File); + boolean condition = value instanceof File; + assertThat(condition).isTrue(); File file = (File) value; - assertFalse(file.exists()); + assertThat(file.exists()).isFalse(); String absolutePath = file.getAbsolutePath().replace('\\', '/'); - assertTrue(absolutePath.endsWith(fileName)); + assertThat(absolutePath.endsWith(fileName)).isTrue(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/InputStreamEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/InputStreamEditorTests.java index e75b586940c..c22ee1ade11 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/InputStreamEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/InputStreamEditorTests.java @@ -22,10 +22,8 @@ import org.junit.Test; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for the {@link InputStreamEditor} class. @@ -50,10 +48,11 @@ public class InputStreamEditorTests { InputStreamEditor editor = new InputStreamEditor(); editor.setAsText(resource); Object value = editor.getValue(); - assertNotNull(value); - assertTrue(value instanceof InputStream); + assertThat(value).isNotNull(); + boolean condition = value instanceof InputStream; + assertThat(condition).isTrue(); stream = (InputStream) value; - assertTrue(stream.available() > 0); + assertThat(stream.available() > 0).isTrue(); } finally { if (stream != null) { @@ -71,12 +70,12 @@ public class InputStreamEditorTests { @Test public void testGetAsTextReturnsNullByDefault() throws Exception { - assertNull(new InputStreamEditor().getAsText()); + assertThat(new InputStreamEditor().getAsText()).isNull(); String resource = "classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class"; InputStreamEditor editor = new InputStreamEditor(); editor.setAsText(resource); - assertNull(editor.getAsText()); + assertThat(editor.getAsText()).isNull(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java index 215f5a7e886..d7d30378763 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PathEditorTests.java @@ -24,9 +24,8 @@ import org.junit.Test; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -40,9 +39,10 @@ public class PathEditorTests { pathEditor.setAsText("classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class"); Object value = pathEditor.getValue(); - assertTrue(value instanceof Path); + boolean condition = value instanceof Path; + assertThat(condition).isTrue(); Path path = (Path) value; - assertTrue(path.toFile().exists()); + assertThat(path.toFile().exists()).isTrue(); } @Test @@ -57,9 +57,11 @@ public class PathEditorTests { PropertyEditor pathEditor = new PathEditor(); pathEditor.setAsText("file:/no_way_this_file_is_found.doc"); Object value = pathEditor.getValue(); - assertTrue(value instanceof Path); + boolean condition1 = value instanceof Path; + assertThat(condition1).isTrue(); Path path = (Path) value; - assertTrue(!path.toFile().exists()); + boolean condition = !path.toFile().exists(); + assertThat(condition).isTrue(); } @Test @@ -67,9 +69,11 @@ public class PathEditorTests { PropertyEditor pathEditor = new PathEditor(); pathEditor.setAsText("/no_way_this_file_is_found.doc"); Object value = pathEditor.getValue(); - assertTrue(value instanceof Path); + boolean condition1 = value instanceof Path; + assertThat(condition1).isTrue(); Path path = (Path) value; - assertTrue(!path.toFile().exists()); + boolean condition = !path.toFile().exists(); + assertThat(condition).isTrue(); } @Test @@ -79,15 +83,16 @@ public class PathEditorTests { ClassUtils.getShortName(getClass()) + ".class"; pathEditor.setAsText(fileName); Object value = pathEditor.getValue(); - assertTrue(value instanceof Path); + boolean condition = value instanceof Path; + assertThat(condition).isTrue(); Path path = (Path) value; File file = path.toFile(); - assertTrue(file.exists()); + assertThat(file.exists()).isTrue(); String absolutePath = file.getAbsolutePath(); if (File.separatorChar == '\\') { absolutePath = absolutePath.replace('\\', '/'); } - assertTrue(absolutePath.endsWith(fileName)); + assertThat(absolutePath.endsWith(fileName)).isTrue(); } @Test @@ -97,15 +102,16 @@ public class PathEditorTests { ClassUtils.getShortName(getClass()) + ".clazz"; pathEditor.setAsText(fileName); Object value = pathEditor.getValue(); - assertTrue(value instanceof Path); + boolean condition = value instanceof Path; + assertThat(condition).isTrue(); Path path = (Path) value; File file = path.toFile(); - assertFalse(file.exists()); + assertThat(file.exists()).isFalse(); String absolutePath = file.getAbsolutePath(); if (File.separatorChar == '\\') { absolutePath = absolutePath.replace('\\', '/'); } - assertTrue(absolutePath.endsWith(fileName)); + assertThat(absolutePath.endsWith(fileName)).isTrue(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java index 5a06df98192..d9166cf4341 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java @@ -22,9 +22,7 @@ import java.util.Properties; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test the conversion of Strings to {@link java.util.Properties} objects, @@ -42,8 +40,8 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertTrue("contains one entry", p.entrySet().size() == 1); - assertTrue("foo=bar", p.get("foo").equals("bar")); + assertThat(p.entrySet().size() == 1).as("contains one entry").isTrue(); + assertThat(p.get("foo").equals("bar")).as("foo=bar").isTrue(); } @Test @@ -53,9 +51,9 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertTrue("contains two entries", p.entrySet().size() == 2); - assertTrue("foo=bar with whitespace", p.get("foo").equals("bar with whitespace")); - assertTrue("me=mi", p.get("me").equals("mi")); + assertThat(p.entrySet().size() == 2).as("contains two entries").isTrue(); + assertThat(p.get("foo").equals("bar with whitespace")).as("foo=bar with whitespace").isTrue(); + assertThat(p.get("me").equals("mi")).as("me=mi").isTrue(); } @Test @@ -66,10 +64,10 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertTrue("contains two entries", p.entrySet().size() == 3); - assertTrue("foo=bar", p.get("foo").equals("bar")); - assertTrue("me=mi", p.get("me").equals("mi")); - assertTrue("x='y=z'", p.get("x").equals("y=z")); + assertThat(p.entrySet().size() == 3).as("contains two entries").isTrue(); + assertThat(p.get("foo").equals("bar")).as("foo=bar").isTrue(); + assertThat(p.get("me").equals("mi")).as("me=mi").isTrue(); + assertThat(p.get("x").equals("y=z")).as("x='y=z'").isTrue(); } @Test @@ -78,10 +76,10 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertTrue("contains two entries", p.entrySet().size() == 3); - assertTrue("foo=bar", p.get("foo").equals("bar")); - assertTrue("me=mi", p.get("me").equals("mi")); - assertTrue("x='y=z'", p.get("x").equals("")); + assertThat(p.entrySet().size() == 3).as("contains two entries").isTrue(); + assertThat(p.get("foo").equals("bar")).as("foo=bar").isTrue(); + assertThat(p.get("me").equals("mi")).as("me=mi").isTrue(); + assertThat(p.get("x").equals("")).as("x='y=z'").isTrue(); } @Test @@ -90,9 +88,9 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertTrue("contains three entries", p.entrySet().size() == 3); - assertTrue("foo is empty", p.get("foo").equals("")); - assertTrue("me=mi", p.get("me").equals("mi")); + assertThat(p.entrySet().size() == 3).as("contains three entries").isTrue(); + assertThat(p.get("foo").equals("")).as("foo is empty").isTrue(); + assertThat(p.get("me").equals("mi")).as("me=mi").isTrue(); } /** @@ -109,9 +107,9 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertTrue("contains three entries", p.entrySet().size() == 3); - assertTrue("foo is bar", p.get("foo").equals("bar")); - assertTrue("me=mi", p.get("me").equals("mi")); + assertThat(p.entrySet().size() == 3).as("contains three entries").isTrue(); + assertThat(p.get("foo").equals("bar")).as("foo is bar").isTrue(); + assertThat(p.get("me").equals("mi")).as("me=mi").isTrue(); } /** @@ -131,9 +129,9 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertTrue("contains 3 entries, not " + p.size(), p.size() == 3); - assertTrue("foo is bar", p.get("foo").equals("bar")); - assertTrue("me=mi", p.get("me").equals("mi")); + assertThat(p.size() == 3).as("contains 3 entries, not " + p.size()).isTrue(); + assertThat(p.get("foo").equals("bar")).as("foo is bar").isTrue(); + assertThat(p.get("me").equals("mi")).as("me=mi").isTrue(); } @Test @@ -141,7 +139,7 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(null); Properties p = (Properties) pe.getValue(); - assertEquals(0, p.size()); + assertThat(p.size()).isEqualTo(0); } @Test @@ -149,7 +147,7 @@ public class PropertiesEditorTests { PropertiesEditor pe = new PropertiesEditor(); pe.setAsText(""); Properties p = (Properties) pe.getValue(); - assertTrue("empty string means empty properties", p.isEmpty()); + assertThat(p.isEmpty()).as("empty string means empty properties").isTrue(); } @Test @@ -161,13 +159,14 @@ public class PropertiesEditorTests { PropertiesEditor pe = new PropertiesEditor(); pe.setValue(map); Object value = pe.getValue(); - assertNotNull(value); - assertTrue(value instanceof Properties); + assertThat(value).isNotNull(); + boolean condition = value instanceof Properties; + assertThat(condition).isTrue(); Properties props = (Properties) value; - assertEquals(3, props.size()); - assertEquals("1", props.getProperty("one")); - assertEquals("2", props.getProperty("two")); - assertEquals("3", props.getProperty("three")); + assertThat(props.size()).isEqualTo(3); + assertThat(props.getProperty("one")).isEqualTo("1"); + assertThat(props.getProperty("two")).isEqualTo("2"); + assertThat(props.getProperty("three")).isEqualTo("3"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ReaderEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ReaderEditorTests.java index 353045b54f1..dac76ab8c4c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ReaderEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ReaderEditorTests.java @@ -22,10 +22,8 @@ import org.junit.Test; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for the {@link ReaderEditor} class. @@ -50,10 +48,11 @@ public class ReaderEditorTests { ReaderEditor editor = new ReaderEditor(); editor.setAsText(resource); Object value = editor.getValue(); - assertNotNull(value); - assertTrue(value instanceof Reader); + assertThat(value).isNotNull(); + boolean condition = value instanceof Reader; + assertThat(condition).isTrue(); reader = (Reader) value; - assertTrue(reader.ready()); + assertThat(reader.ready()).isTrue(); } finally { if (reader != null) { @@ -72,12 +71,12 @@ public class ReaderEditorTests { @Test public void testGetAsTextReturnsNullByDefault() throws Exception { - assertNull(new ReaderEditor().getAsText()); + assertThat(new ReaderEditor().getAsText()).isNull(); String resource = "classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class"; ReaderEditor editor = new ReaderEditor(); editor.setAsText(resource); - assertNull(editor.getAsText()); + assertThat(editor.getAsText()).isNull(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ResourceBundleEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ResourceBundleEditorTests.java index 5a1d18cea8b..749422021f5 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ResourceBundleEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ResourceBundleEditorTests.java @@ -20,10 +20,8 @@ import java.util.ResourceBundle; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * Unit tests for the {@link ResourceBundleEditor} class. @@ -43,12 +41,12 @@ public class ResourceBundleEditorTests { ResourceBundleEditor editor = new ResourceBundleEditor(); editor.setAsText(BASE_NAME); Object value = editor.getValue(); - assertNotNull("Returned ResourceBundle was null (must not be for valid setAsText(..) call).", value); - assertTrue("Returned object was not a ResourceBundle (must be for valid setAsText(..) call).", - value instanceof ResourceBundle); + assertThat(value).as("Returned ResourceBundle was null (must not be for valid setAsText(..) call).").isNotNull(); + boolean condition = value instanceof ResourceBundle; + assertThat(condition).as("Returned object was not a ResourceBundle (must be for valid setAsText(..) call).").isTrue(); ResourceBundle bundle = (ResourceBundle) value; String string = bundle.getString(MESSAGE_KEY); - assertEquals(MESSAGE_KEY, string); + assertThat(string).isEqualTo(MESSAGE_KEY); } @Test @@ -56,12 +54,12 @@ public class ResourceBundleEditorTests { ResourceBundleEditor editor = new ResourceBundleEditor(); editor.setAsText(BASE_NAME + "_"); Object value = editor.getValue(); - assertNotNull("Returned ResourceBundle was null (must not be for valid setAsText(..) call).", value); - assertTrue("Returned object was not a ResourceBundle (must be for valid setAsText(..) call).", - value instanceof ResourceBundle); + assertThat(value).as("Returned ResourceBundle was null (must not be for valid setAsText(..) call).").isNotNull(); + boolean condition = value instanceof ResourceBundle; + assertThat(condition).as("Returned object was not a ResourceBundle (must be for valid setAsText(..) call).").isTrue(); ResourceBundle bundle = (ResourceBundle) value; String string = bundle.getString(MESSAGE_KEY); - assertEquals(MESSAGE_KEY, string); + assertThat(string).isEqualTo(MESSAGE_KEY); } @Test @@ -69,12 +67,12 @@ public class ResourceBundleEditorTests { ResourceBundleEditor editor = new ResourceBundleEditor(); editor.setAsText(BASE_NAME + "Lang" + "_en"); Object value = editor.getValue(); - assertNotNull("Returned ResourceBundle was null (must not be for valid setAsText(..) call).", value); - assertTrue("Returned object was not a ResourceBundle (must be for valid setAsText(..) call).", - value instanceof ResourceBundle); + assertThat(value).as("Returned ResourceBundle was null (must not be for valid setAsText(..) call).").isNotNull(); + boolean condition = value instanceof ResourceBundle; + assertThat(condition).as("Returned object was not a ResourceBundle (must be for valid setAsText(..) call).").isTrue(); ResourceBundle bundle = (ResourceBundle) value; String string = bundle.getString(MESSAGE_KEY); - assertEquals("yob", string); + assertThat(string).isEqualTo("yob"); } @Test @@ -82,12 +80,12 @@ public class ResourceBundleEditorTests { ResourceBundleEditor editor = new ResourceBundleEditor(); editor.setAsText(BASE_NAME + "LangCountry" + "_en_GB"); Object value = editor.getValue(); - assertNotNull("Returned ResourceBundle was null (must not be for valid setAsText(..) call).", value); - assertTrue("Returned object was not a ResourceBundle (must be for valid setAsText(..) call).", - value instanceof ResourceBundle); + assertThat(value).as("Returned ResourceBundle was null (must not be for valid setAsText(..) call).").isNotNull(); + boolean condition = value instanceof ResourceBundle; + assertThat(condition).as("Returned object was not a ResourceBundle (must be for valid setAsText(..) call).").isTrue(); ResourceBundle bundle = (ResourceBundle) value; String string = bundle.getString(MESSAGE_KEY); - assertEquals("chav", string); + assertThat(string).isEqualTo("chav"); } @Test @@ -95,12 +93,12 @@ public class ResourceBundleEditorTests { ResourceBundleEditor editor = new ResourceBundleEditor(); editor.setAsText(BASE_NAME + "LangCountryDialect" + "_en_GB_GLASGOW"); Object value = editor.getValue(); - assertNotNull("Returned ResourceBundle was null (must not be for valid setAsText(..) call).", value); - assertTrue("Returned object was not a ResourceBundle (must be for valid setAsText(..) call).", - value instanceof ResourceBundle); + assertThat(value).as("Returned ResourceBundle was null (must not be for valid setAsText(..) call).").isNotNull(); + boolean condition = value instanceof ResourceBundle; + assertThat(condition).as("Returned object was not a ResourceBundle (must be for valid setAsText(..) call).").isTrue(); ResourceBundle bundle = (ResourceBundle) value; String string = bundle.getString(MESSAGE_KEY); - assertEquals("ned", string); + assertThat(string).isEqualTo("ned"); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/StringArrayPropertyEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/StringArrayPropertyEditorTests.java index 9338282366c..e8b3570b185 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/StringArrayPropertyEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/StringArrayPropertyEditorTests.java @@ -18,10 +18,7 @@ package org.springframework.beans.propertyeditors; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rick Evans @@ -34,13 +31,14 @@ public class StringArrayPropertyEditorTests { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(); editor.setAsText("0,1,2"); Object value = editor.getValue(); - assertNotNull(value); - assertTrue(value instanceof String[]); + assertThat(value).isNotNull(); + boolean condition = value instanceof String[]; + assertThat(condition).isTrue(); String[] array = (String[]) value; for (int i = 0; i < array.length; ++i) { - assertEquals("" + i, array[i]); + assertThat(array[i]).isEqualTo(("" + i)); } - assertEquals("0,1,2", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo("0,1,2"); } @Test @@ -50,9 +48,9 @@ public class StringArrayPropertyEditorTests { Object value = editor.getValue(); String[] array = (String[]) value; for (int i = 0; i < array.length; ++i) { - assertEquals("" + i, array[i]); + assertThat(array[i]).isEqualTo(("" + i)); } - assertEquals("0,1,2", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo("0,1,2"); } @Test @@ -62,10 +60,10 @@ public class StringArrayPropertyEditorTests { Object value = editor.getValue(); String[] array = (String[]) value; for (int i = 0; i < array.length; ++i) { - assertEquals(3, array[i].length()); - assertEquals("" + i, array[i].trim()); + assertThat(array[i].length()).isEqualTo(3); + assertThat(array[i].trim()).isEqualTo(("" + i)); } - assertEquals(" 0,1 , 2 ", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(" 0,1 , 2 "); } @Test @@ -73,12 +71,13 @@ public class StringArrayPropertyEditorTests { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(":"); editor.setAsText("0:1:2"); Object value = editor.getValue(); - assertTrue(value instanceof String[]); + boolean condition = value instanceof String[]; + assertThat(condition).isTrue(); String[] array = (String[]) value; for (int i = 0; i < array.length; ++i) { - assertEquals("" + i, array[i]); + assertThat(array[i]).isEqualTo(("" + i)); } - assertEquals("0:1:2", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo("0:1:2"); } @Test @@ -86,12 +85,13 @@ public class StringArrayPropertyEditorTests { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(",", "\r\n", false); editor.setAsText("0\r,1,\n2"); Object value = editor.getValue(); - assertTrue(value instanceof String[]); + boolean condition = value instanceof String[]; + assertThat(condition).isTrue(); String[] array = (String[]) value; for (int i = 0; i < array.length; ++i) { - assertEquals("" + i, array[i]); + assertThat(array[i]).isEqualTo(("" + i)); } - assertEquals("0,1,2", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo("0,1,2"); } @Test @@ -99,15 +99,16 @@ public class StringArrayPropertyEditorTests { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(); editor.setAsText(""); Object value = editor.getValue(); - assertTrue(value instanceof String[]); - assertEquals(0, ((String[]) value).length); + boolean condition = value instanceof String[]; + assertThat(condition).isTrue(); + assertThat(((String[]) value).length).isEqualTo(0); } @Test public void withEmptyArrayAsNull() throws Exception { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(",", true); editor.setAsText(""); - assertNull(editor.getValue()); + assertThat(editor.getValue()).isNull(); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URIEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URIEditorTests.java index 1b6d21793c7..d352112cc7f 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URIEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URIEditorTests.java @@ -23,9 +23,7 @@ import org.junit.Test; import org.springframework.util.ClassUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -58,9 +56,10 @@ public class URIEditorTests { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText(" https://www.springframework.org "); Object value = uriEditor.getValue(); - assertTrue(value instanceof URI); + boolean condition = value instanceof URI; + assertThat(condition).isTrue(); URI uri = (URI) value; - assertEquals("https://www.springframework.org", uri.toString()); + assertThat(uri.toString()).isEqualTo("https://www.springframework.org"); } @Test @@ -69,10 +68,12 @@ public class URIEditorTests { uriEditor.setAsText("classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class"); Object value = uriEditor.getValue(); - assertTrue(value instanceof URI); + boolean condition1 = value instanceof URI; + assertThat(condition1).isTrue(); URI uri = (URI) value; - assertEquals(uri.toString(), uriEditor.getAsText()); - assertTrue(!uri.getScheme().startsWith("classpath")); + assertThat(uriEditor.getAsText()).isEqualTo(uri.toString()); + boolean condition = !uri.getScheme().startsWith("classpath"); + assertThat(condition).isTrue(); } @Test @@ -81,10 +82,12 @@ public class URIEditorTests { uriEditor.setAsText(" classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class "); Object value = uriEditor.getValue(); - assertTrue(value instanceof URI); + boolean condition1 = value instanceof URI; + assertThat(condition1).isTrue(); URI uri = (URI) value; - assertEquals(uri.toString(), uriEditor.getAsText()); - assertTrue(!uri.getScheme().startsWith("classpath")); + assertThat(uriEditor.getAsText()).isEqualTo(uri.toString()); + boolean condition = !uri.getScheme().startsWith("classpath"); + assertThat(condition).isTrue(); } @Test @@ -92,24 +95,25 @@ public class URIEditorTests { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText("classpath:test.txt"); Object value = uriEditor.getValue(); - assertTrue(value instanceof URI); + boolean condition = value instanceof URI; + assertThat(condition).isTrue(); URI uri = (URI) value; - assertEquals(uri.toString(), uriEditor.getAsText()); - assertTrue(uri.getScheme().startsWith("classpath")); + assertThat(uriEditor.getAsText()).isEqualTo(uri.toString()); + assertThat(uri.getScheme().startsWith("classpath")).isTrue(); } @Test public void setAsTextWithNull() throws Exception { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText(null); - assertNull(uriEditor.getValue()); - assertEquals("", uriEditor.getAsText()); + assertThat(uriEditor.getValue()).isNull(); + assertThat(uriEditor.getAsText()).isEqualTo(""); } @Test public void getAsTextReturnsEmptyStringIfValueNotSet() throws Exception { PropertyEditor uriEditor = new URIEditor(); - assertEquals("", uriEditor.getAsText()); + assertThat(uriEditor.getAsText()).isEqualTo(""); } @Test @@ -117,10 +121,11 @@ public class URIEditorTests { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText("https://example.com/spaces and \u20AC"); Object value = uriEditor.getValue(); - assertTrue(value instanceof URI); + boolean condition = value instanceof URI; + assertThat(condition).isTrue(); URI uri = (URI) value; - assertEquals(uri.toString(), uriEditor.getAsText()); - assertEquals("https://example.com/spaces%20and%20%E2%82%AC", uri.toASCIIString()); + assertThat(uriEditor.getAsText()).isEqualTo(uri.toString()); + assertThat(uri.toASCIIString()).isEqualTo("https://example.com/spaces%20and%20%E2%82%AC"); } @Test @@ -128,10 +133,11 @@ public class URIEditorTests { PropertyEditor uriEditor = new URIEditor(false); uriEditor.setAsText("https://example.com/spaces%20and%20%E2%82%AC"); Object value = uriEditor.getValue(); - assertTrue(value instanceof URI); + boolean condition = value instanceof URI; + assertThat(condition).isTrue(); URI uri = (URI) value; - assertEquals(uri.toString(), uriEditor.getAsText()); - assertEquals("https://example.com/spaces%20and%20%E2%82%AC", uri.toASCIIString()); + assertThat(uriEditor.getAsText()).isEqualTo(uri.toString()); + assertThat(uri.toASCIIString()).isEqualTo("https://example.com/spaces%20and%20%E2%82%AC"); } @@ -139,9 +145,10 @@ public class URIEditorTests { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText(uriSpec); Object value = uriEditor.getValue(); - assertTrue(value instanceof URI); + boolean condition = value instanceof URI; + assertThat(condition).isTrue(); URI uri = (URI) value; - assertEquals(uriSpec, uri.toString()); + assertThat(uri.toString()).isEqualTo(uriSpec); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URLEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URLEditorTests.java index e45cc287f2f..40b0afa2d32 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URLEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/URLEditorTests.java @@ -23,10 +23,8 @@ import org.junit.Test; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * @author Rick Evans @@ -45,9 +43,10 @@ public class URLEditorTests { PropertyEditor urlEditor = new URLEditor(); urlEditor.setAsText("mailto:juergen.hoeller@interface21.com"); Object value = urlEditor.getValue(); - assertTrue(value instanceof URL); + boolean condition = value instanceof URL; + assertThat(condition).isTrue(); URL url = (URL) value; - assertEquals(url.toExternalForm(), urlEditor.getAsText()); + assertThat(urlEditor.getAsText()).isEqualTo(url.toExternalForm()); } @Test @@ -55,9 +54,10 @@ public class URLEditorTests { PropertyEditor urlEditor = new URLEditor(); urlEditor.setAsText("https://www.springframework.org"); Object value = urlEditor.getValue(); - assertTrue(value instanceof URL); + boolean condition = value instanceof URL; + assertThat(condition).isTrue(); URL url = (URL) value; - assertEquals(url.toExternalForm(), urlEditor.getAsText()); + assertThat(urlEditor.getAsText()).isEqualTo(url.toExternalForm()); } @Test @@ -66,10 +66,12 @@ public class URLEditorTests { urlEditor.setAsText("classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class"); Object value = urlEditor.getValue(); - assertTrue(value instanceof URL); + boolean condition1 = value instanceof URL; + assertThat(condition1).isTrue(); URL url = (URL) value; - assertEquals(url.toExternalForm(), urlEditor.getAsText()); - assertTrue(!url.getProtocol().startsWith("classpath")); + assertThat(urlEditor.getAsText()).isEqualTo(url.toExternalForm()); + boolean condition = !url.getProtocol().startsWith("classpath"); + assertThat(condition).isTrue(); } @Test @@ -83,14 +85,14 @@ public class URLEditorTests { public void testSetAsTextWithNull() throws Exception { PropertyEditor urlEditor = new URLEditor(); urlEditor.setAsText(null); - assertNull(urlEditor.getValue()); - assertEquals("", urlEditor.getAsText()); + assertThat(urlEditor.getValue()).isNull(); + assertThat(urlEditor.getAsText()).isEqualTo(""); } @Test public void testGetAsTextReturnsEmptyStringIfValueNotSet() throws Exception { PropertyEditor urlEditor = new URLEditor(); - assertEquals("", urlEditor.getAsText()); + assertThat(urlEditor.getAsText()).isEqualTo(""); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ZoneIdEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ZoneIdEditorTests.java index 6aa18896c75..b2762e74895 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ZoneIdEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ZoneIdEditorTests.java @@ -20,8 +20,7 @@ import java.time.ZoneId; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Nicholas Williams @@ -35,10 +34,10 @@ public class ZoneIdEditorTests { editor.setAsText("America/Chicago"); ZoneId zoneId = (ZoneId) editor.getValue(); - assertNotNull("The zone ID should not be null.", zoneId); - assertEquals("The zone ID is not correct.", ZoneId.of("America/Chicago"), zoneId); + assertThat(zoneId).as("The zone ID should not be null.").isNotNull(); + assertThat(zoneId).as("The zone ID is not correct.").isEqualTo(ZoneId.of("America/Chicago")); - assertEquals("The text version is not correct.", "America/Chicago", editor.getAsText()); + assertThat(editor.getAsText()).as("The text version is not correct.").isEqualTo("America/Chicago"); } @Test @@ -46,21 +45,21 @@ public class ZoneIdEditorTests { editor.setAsText("America/Los_Angeles"); ZoneId zoneId = (ZoneId) editor.getValue(); - assertNotNull("The zone ID should not be null.", zoneId); - assertEquals("The zone ID is not correct.", ZoneId.of("America/Los_Angeles"), zoneId); + assertThat(zoneId).as("The zone ID should not be null.").isNotNull(); + assertThat(zoneId).as("The zone ID is not correct.").isEqualTo(ZoneId.of("America/Los_Angeles")); - assertEquals("The text version is not correct.", "America/Los_Angeles", editor.getAsText()); + assertThat(editor.getAsText()).as("The text version is not correct.").isEqualTo("America/Los_Angeles"); } @Test public void getNullAsText() { - assertEquals("The returned value is not correct.", "", editor.getAsText()); + assertThat(editor.getAsText()).as("The returned value is not correct.").isEqualTo(""); } @Test public void getValueAsText() { editor.setValue(ZoneId.of("America/New_York")); - assertEquals("The text version is not correct.", "America/New_York", editor.getAsText()); + assertThat(editor.getAsText()).as("The text version is not correct.").isEqualTo("America/New_York"); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java b/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java index 1d1ab0f818c..25b5d6b62ae 100644 --- a/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java @@ -25,9 +25,7 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -57,114 +55,114 @@ public class PagedListHolderTests { tbs.add(tb3); PagedListHolder holder = new PagedListHolder(tbs); - assertTrue("Correct source", holder.getSource() == tbs); - assertTrue("Correct number of elements", holder.getNrOfElements() == 3); - assertTrue("Correct number of pages", holder.getPageCount() == 1); - assertTrue("Correct page size", holder.getPageSize() == PagedListHolder.DEFAULT_PAGE_SIZE); - assertTrue("Correct page number", holder.getPage() == 0); - assertTrue("First page", holder.isFirstPage()); - assertTrue("Last page", holder.isLastPage()); - assertTrue("Correct first element", holder.getFirstElementOnPage() == 0); - assertTrue("Correct first element", holder.getLastElementOnPage() == 2); - assertTrue("Correct page list size", holder.getPageList().size() == 3); - assertTrue("Correct page list contents", holder.getPageList().get(0) == tb1); - assertTrue("Correct page list contents", holder.getPageList().get(1) == tb2); - assertTrue("Correct page list contents", holder.getPageList().get(2) == tb3); + assertThat(holder.getSource() == tbs).as("Correct source").isTrue(); + assertThat(holder.getNrOfElements() == 3).as("Correct number of elements").isTrue(); + assertThat(holder.getPageCount() == 1).as("Correct number of pages").isTrue(); + assertThat(holder.getPageSize() == PagedListHolder.DEFAULT_PAGE_SIZE).as("Correct page size").isTrue(); + assertThat(holder.getPage() == 0).as("Correct page number").isTrue(); + assertThat(holder.isFirstPage()).as("First page").isTrue(); + assertThat(holder.isLastPage()).as("Last page").isTrue(); + assertThat(holder.getFirstElementOnPage() == 0).as("Correct first element").isTrue(); + assertThat(holder.getLastElementOnPage() == 2).as("Correct first element").isTrue(); + assertThat(holder.getPageList().size() == 3).as("Correct page list size").isTrue(); + assertThat(holder.getPageList().get(0) == tb1).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(1) == tb2).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(2) == tb3).as("Correct page list contents").isTrue(); holder.setPageSize(2); - assertTrue("Correct number of pages", holder.getPageCount() == 2); - assertTrue("Correct page size", holder.getPageSize() == 2); - assertTrue("Correct page number", holder.getPage() == 0); - assertTrue("First page", holder.isFirstPage()); - assertFalse("Last page", holder.isLastPage()); - assertTrue("Correct first element", holder.getFirstElementOnPage() == 0); - assertTrue("Correct last element", holder.getLastElementOnPage() == 1); - assertTrue("Correct page list size", holder.getPageList().size() == 2); - assertTrue("Correct page list contents", holder.getPageList().get(0) == tb1); - assertTrue("Correct page list contents", holder.getPageList().get(1) == tb2); + assertThat(holder.getPageCount() == 2).as("Correct number of pages").isTrue(); + assertThat(holder.getPageSize() == 2).as("Correct page size").isTrue(); + assertThat(holder.getPage() == 0).as("Correct page number").isTrue(); + assertThat(holder.isFirstPage()).as("First page").isTrue(); + assertThat(holder.isLastPage()).as("Last page").isFalse(); + assertThat(holder.getFirstElementOnPage() == 0).as("Correct first element").isTrue(); + assertThat(holder.getLastElementOnPage() == 1).as("Correct last element").isTrue(); + assertThat(holder.getPageList().size() == 2).as("Correct page list size").isTrue(); + assertThat(holder.getPageList().get(0) == tb1).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(1) == tb2).as("Correct page list contents").isTrue(); holder.setPage(1); - assertTrue("Correct page number", holder.getPage() == 1); - assertFalse("First page", holder.isFirstPage()); - assertTrue("Last page", holder.isLastPage()); - assertTrue("Correct first element", holder.getFirstElementOnPage() == 2); - assertTrue("Correct last element", holder.getLastElementOnPage() == 2); - assertTrue("Correct page list size", holder.getPageList().size() == 1); - assertTrue("Correct page list contents", holder.getPageList().get(0) == tb3); + assertThat(holder.getPage() == 1).as("Correct page number").isTrue(); + assertThat(holder.isFirstPage()).as("First page").isFalse(); + assertThat(holder.isLastPage()).as("Last page").isTrue(); + assertThat(holder.getFirstElementOnPage() == 2).as("Correct first element").isTrue(); + assertThat(holder.getLastElementOnPage() == 2).as("Correct last element").isTrue(); + assertThat(holder.getPageList().size() == 1).as("Correct page list size").isTrue(); + assertThat(holder.getPageList().get(0) == tb3).as("Correct page list contents").isTrue(); holder.setPageSize(3); - assertTrue("Correct number of pages", holder.getPageCount() == 1); - assertTrue("Correct page size", holder.getPageSize() == 3); - assertTrue("Correct page number", holder.getPage() == 0); - assertTrue("First page", holder.isFirstPage()); - assertTrue("Last page", holder.isLastPage()); - assertTrue("Correct first element", holder.getFirstElementOnPage() == 0); - assertTrue("Correct last element", holder.getLastElementOnPage() == 2); + assertThat(holder.getPageCount() == 1).as("Correct number of pages").isTrue(); + assertThat(holder.getPageSize() == 3).as("Correct page size").isTrue(); + assertThat(holder.getPage() == 0).as("Correct page number").isTrue(); + assertThat(holder.isFirstPage()).as("First page").isTrue(); + assertThat(holder.isLastPage()).as("Last page").isTrue(); + assertThat(holder.getFirstElementOnPage() == 0).as("Correct first element").isTrue(); + assertThat(holder.getLastElementOnPage() == 2).as("Correct last element").isTrue(); holder.setPage(1); holder.setPageSize(2); - assertTrue("Correct number of pages", holder.getPageCount() == 2); - assertTrue("Correct page size", holder.getPageSize() == 2); - assertTrue("Correct page number", holder.getPage() == 1); - assertFalse("First page", holder.isFirstPage()); - assertTrue("Last page", holder.isLastPage()); - assertTrue("Correct first element", holder.getFirstElementOnPage() == 2); - assertTrue("Correct last element", holder.getLastElementOnPage() == 2); + assertThat(holder.getPageCount() == 2).as("Correct number of pages").isTrue(); + assertThat(holder.getPageSize() == 2).as("Correct page size").isTrue(); + assertThat(holder.getPage() == 1).as("Correct page number").isTrue(); + assertThat(holder.isFirstPage()).as("First page").isFalse(); + assertThat(holder.isLastPage()).as("Last page").isTrue(); + assertThat(holder.getFirstElementOnPage() == 2).as("Correct first element").isTrue(); + assertThat(holder.getLastElementOnPage() == 2).as("Correct last element").isTrue(); holder.setPageSize(2); holder.setPage(1); ((MutableSortDefinition) holder.getSort()).setProperty("name"); ((MutableSortDefinition) holder.getSort()).setIgnoreCase(false); holder.resort(); - assertTrue("Correct source", holder.getSource() == tbs); - assertTrue("Correct number of elements", holder.getNrOfElements() == 3); - assertTrue("Correct number of pages", holder.getPageCount() == 2); - assertTrue("Correct page size", holder.getPageSize() == 2); - assertTrue("Correct page number", holder.getPage() == 0); - assertTrue("First page", holder.isFirstPage()); - assertFalse("Last page", holder.isLastPage()); - assertTrue("Correct first element", holder.getFirstElementOnPage() == 0); - assertTrue("Correct last element", holder.getLastElementOnPage() == 1); - assertTrue("Correct page list size", holder.getPageList().size() == 2); - assertTrue("Correct page list contents", holder.getPageList().get(0) == tb3); - assertTrue("Correct page list contents", holder.getPageList().get(1) == tb1); + assertThat(holder.getSource() == tbs).as("Correct source").isTrue(); + assertThat(holder.getNrOfElements() == 3).as("Correct number of elements").isTrue(); + assertThat(holder.getPageCount() == 2).as("Correct number of pages").isTrue(); + assertThat(holder.getPageSize() == 2).as("Correct page size").isTrue(); + assertThat(holder.getPage() == 0).as("Correct page number").isTrue(); + assertThat(holder.isFirstPage()).as("First page").isTrue(); + assertThat(holder.isLastPage()).as("Last page").isFalse(); + assertThat(holder.getFirstElementOnPage() == 0).as("Correct first element").isTrue(); + assertThat(holder.getLastElementOnPage() == 1).as("Correct last element").isTrue(); + assertThat(holder.getPageList().size() == 2).as("Correct page list size").isTrue(); + assertThat(holder.getPageList().get(0) == tb3).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(1) == tb1).as("Correct page list contents").isTrue(); ((MutableSortDefinition) holder.getSort()).setProperty("name"); holder.resort(); - assertTrue("Correct page list contents", holder.getPageList().get(0) == tb2); - assertTrue("Correct page list contents", holder.getPageList().get(1) == tb1); + assertThat(holder.getPageList().get(0) == tb2).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(1) == tb1).as("Correct page list contents").isTrue(); ((MutableSortDefinition) holder.getSort()).setProperty("name"); holder.resort(); - assertTrue("Correct page list contents", holder.getPageList().get(0) == tb3); - assertTrue("Correct page list contents", holder.getPageList().get(1) == tb1); + assertThat(holder.getPageList().get(0) == tb3).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(1) == tb1).as("Correct page list contents").isTrue(); holder.setPage(1); - assertTrue("Correct page list size", holder.getPageList().size() == 1); - assertTrue("Correct page list contents", holder.getPageList().get(0) == tb2); + assertThat(holder.getPageList().size() == 1).as("Correct page list size").isTrue(); + assertThat(holder.getPageList().get(0) == tb2).as("Correct page list contents").isTrue(); ((MutableSortDefinition) holder.getSort()).setProperty("age"); holder.resort(); - assertTrue("Correct page list contents", holder.getPageList().get(0) == tb1); - assertTrue("Correct page list contents", holder.getPageList().get(1) == tb3); + assertThat(holder.getPageList().get(0) == tb1).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(1) == tb3).as("Correct page list contents").isTrue(); ((MutableSortDefinition) holder.getSort()).setIgnoreCase(true); holder.resort(); - assertTrue("Correct page list contents", holder.getPageList().get(0) == tb1); - assertTrue("Correct page list contents", holder.getPageList().get(1) == tb3); + assertThat(holder.getPageList().get(0) == tb1).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(1) == tb3).as("Correct page list contents").isTrue(); holder.nextPage(); - assertEquals(1, holder.getPage()); + assertThat(holder.getPage()).isEqualTo(1); holder.previousPage(); - assertEquals(0, holder.getPage()); + assertThat(holder.getPage()).isEqualTo(0); holder.nextPage(); - assertEquals(1, holder.getPage()); + assertThat(holder.getPage()).isEqualTo(1); holder.nextPage(); - assertEquals(1, holder.getPage()); + assertThat(holder.getPage()).isEqualTo(1); holder.previousPage(); - assertEquals(0, holder.getPage()); + assertThat(holder.getPage()).isEqualTo(0); holder.previousPage(); - assertEquals(0, holder.getPage()); + assertThat(holder.getPage()).isEqualTo(0); } diff --git a/spring-beans/src/test/java/org/springframework/beans/support/PropertyComparatorTests.java b/spring-beans/src/test/java/org/springframework/beans/support/PropertyComparatorTests.java index bb009ec1085..cf6ea346222 100644 --- a/spring-beans/src/test/java/org/springframework/beans/support/PropertyComparatorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/support/PropertyComparatorTests.java @@ -20,7 +20,7 @@ import java.util.Comparator; import org.junit.Test; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link PropertyComparator}. @@ -39,9 +39,9 @@ public class PropertyComparatorTests { dog2.setNickName("biscy"); PropertyComparator c = new PropertyComparator<>("nickName", false, true); - assertTrue(c.compare(dog, dog2) > 0); - assertTrue(c.compare(dog, dog) == 0); - assertTrue(c.compare(dog2, dog) < 0); + assertThat(c.compare(dog, dog2) > 0).isTrue(); + assertThat(c.compare(dog, dog) == 0).isTrue(); + assertThat(c.compare(dog2, dog) < 0).isTrue(); } @Test @@ -49,7 +49,7 @@ public class PropertyComparatorTests { Dog dog = new Dog(); Dog dog2 = new Dog(); PropertyComparator c = new PropertyComparator<>("nickName", false, true); - assertTrue(c.compare(dog, dog2) == 0); + assertThat(c.compare(dog, dog2) == 0).isTrue(); } @Test @@ -64,13 +64,13 @@ public class PropertyComparatorTests { dog2.setFirstName("biscuit"); dog2.setLastName("grayspots"); - assertTrue(c.compare(dog1, dog2) == 0); + assertThat(c.compare(dog1, dog2) == 0).isTrue(); c = c.thenComparing(new PropertyComparator<>("firstName", false, true)); - assertTrue(c.compare(dog1, dog2) > 0); + assertThat(c.compare(dog1, dog2) > 0).isTrue(); dog2.setLastName("konikk dog"); - assertTrue(c.compare(dog2, dog1) > 0); + assertThat(c.compare(dog2, dog1) > 0).isTrue(); } @Test @@ -86,9 +86,9 @@ public class PropertyComparatorTests { dog2.setFirstName("biscuit"); dog2.setLastName("grayspots"); - assertTrue(c.compare(dog1, dog2) > 0); + assertThat(c.compare(dog1, dog2) > 0).isTrue(); c = c.reversed(); - assertTrue(c.compare(dog1, dog2) < 0); + assertThat(c.compare(dog1, dog2) < 0).isTrue(); } diff --git a/spring-context-support/src/test/java/org/springframework/cache/caffeine/CaffeineCacheManagerTests.java b/spring-context-support/src/test/java/org/springframework/cache/caffeine/CaffeineCacheManagerTests.java index b207e22baf8..1ea2aca687d 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/caffeine/CaffeineCacheManagerTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/caffeine/CaffeineCacheManagerTests.java @@ -24,12 +24,8 @@ import org.junit.Test; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; +import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; /** @@ -43,73 +39,80 @@ public class CaffeineCacheManagerTests { public void testDynamicMode() { CacheManager cm = new CaffeineCacheManager(); Cache cache1 = cm.getCache("c1"); - assertTrue(cache1 instanceof CaffeineCache); + boolean condition2 = cache1 instanceof CaffeineCache; + assertThat(condition2).isTrue(); Cache cache1again = cm.getCache("c1"); - assertSame(cache1again, cache1); + assertThat(cache1).isSameAs(cache1again); Cache cache2 = cm.getCache("c2"); - assertTrue(cache2 instanceof CaffeineCache); + boolean condition1 = cache2 instanceof CaffeineCache; + assertThat(condition1).isTrue(); Cache cache2again = cm.getCache("c2"); - assertSame(cache2again, cache2); + assertThat(cache2).isSameAs(cache2again); Cache cache3 = cm.getCache("c3"); - assertTrue(cache3 instanceof CaffeineCache); + boolean condition = cache3 instanceof CaffeineCache; + assertThat(condition).isTrue(); Cache cache3again = cm.getCache("c3"); - assertSame(cache3again, cache3); + assertThat(cache3).isSameAs(cache3again); cache1.put("key1", "value1"); - assertEquals("value1", cache1.get("key1").get()); + assertThat(cache1.get("key1").get()).isEqualTo("value1"); cache1.put("key2", 2); - assertEquals(2, cache1.get("key2").get()); + assertThat(cache1.get("key2").get()).isEqualTo(2); cache1.put("key3", null); - assertNull(cache1.get("key3").get()); + assertThat(cache1.get("key3").get()).isNull(); cache1.evict("key3"); - assertNull(cache1.get("key3")); + assertThat(cache1.get("key3")).isNull(); } @Test public void testStaticMode() { CaffeineCacheManager cm = new CaffeineCacheManager("c1", "c2"); Cache cache1 = cm.getCache("c1"); - assertTrue(cache1 instanceof CaffeineCache); + boolean condition3 = cache1 instanceof CaffeineCache; + assertThat(condition3).isTrue(); Cache cache1again = cm.getCache("c1"); - assertSame(cache1again, cache1); + assertThat(cache1).isSameAs(cache1again); Cache cache2 = cm.getCache("c2"); - assertTrue(cache2 instanceof CaffeineCache); + boolean condition2 = cache2 instanceof CaffeineCache; + assertThat(condition2).isTrue(); Cache cache2again = cm.getCache("c2"); - assertSame(cache2again, cache2); + assertThat(cache2).isSameAs(cache2again); Cache cache3 = cm.getCache("c3"); - assertNull(cache3); + assertThat(cache3).isNull(); cache1.put("key1", "value1"); - assertEquals("value1", cache1.get("key1").get()); + assertThat(cache1.get("key1").get()).isEqualTo("value1"); cache1.put("key2", 2); - assertEquals(2, cache1.get("key2").get()); + assertThat(cache1.get("key2").get()).isEqualTo(2); cache1.put("key3", null); - assertNull(cache1.get("key3").get()); + assertThat(cache1.get("key3").get()).isNull(); cache1.evict("key3"); - assertNull(cache1.get("key3")); + assertThat(cache1.get("key3")).isNull(); cm.setAllowNullValues(false); Cache cache1x = cm.getCache("c1"); - assertTrue(cache1x instanceof CaffeineCache); - assertTrue(cache1x != cache1); + boolean condition1 = cache1x instanceof CaffeineCache; + assertThat(condition1).isTrue(); + assertThat(cache1x != cache1).isTrue(); Cache cache2x = cm.getCache("c2"); - assertTrue(cache2x instanceof CaffeineCache); - assertTrue(cache2x != cache2); + boolean condition = cache2x instanceof CaffeineCache; + assertThat(condition).isTrue(); + assertThat(cache2x != cache2).isTrue(); Cache cache3x = cm.getCache("c3"); - assertNull(cache3x); + assertThat(cache3x).isNull(); cache1x.put("key1", "value1"); - assertEquals("value1", cache1x.get("key1").get()); + assertThat(cache1x.get("key1").get()).isEqualTo("value1"); cache1x.put("key2", 2); - assertEquals(2, cache1x.get("key2").get()); + assertThat(cache1x.get("key2").get()).isEqualTo(2); cm.setAllowNullValues(true); Cache cache1y = cm.getCache("c1"); cache1y.put("key3", null); - assertNull(cache1y.get("key3").get()); + assertThat(cache1y.get("key3").get()).isNull(); cache1y.evict("key3"); - assertNull(cache1y.get("key3")); + assertThat(cache1y.get("key3")).isNull(); } @Test @@ -120,11 +123,11 @@ public class CaffeineCacheManagerTests { Caffeine caffeine = Caffeine.newBuilder().maximumSize(10); cm.setCaffeine(caffeine); Cache cache1x = cm.getCache("c1"); - assertTrue(cache1x != cache1); + assertThat(cache1x != cache1).isTrue(); cm.setCaffeine(caffeine); // Set same instance Cache cache1xx = cm.getCache("c1"); - assertSame(cache1x, cache1xx); + assertThat(cache1xx).isSameAs(cache1x); } @Test @@ -134,7 +137,7 @@ public class CaffeineCacheManagerTests { cm.setCaffeineSpec(CaffeineSpec.parse("maximumSize=10")); Cache cache1x = cm.getCache("c1"); - assertTrue(cache1x != cache1); + assertThat(cache1x != cache1).isTrue(); } @Test @@ -144,7 +147,7 @@ public class CaffeineCacheManagerTests { cm.setCacheSpecification("maximumSize=10"); Cache cache1x = cm.getCache("c1"); - assertTrue(cache1x != cache1); + assertThat(cache1x != cache1).isTrue(); } @Test @@ -155,19 +158,19 @@ public class CaffeineCacheManagerTests { CacheLoader loader = mockCacheLoader(); cm.setCacheLoader(loader); Cache cache1x = cm.getCache("c1"); - assertTrue(cache1x != cache1); + assertThat(cache1x != cache1).isTrue(); cm.setCacheLoader(loader); // Set same instance Cache cache1xx = cm.getCache("c1"); - assertSame(cache1x, cache1xx); + assertThat(cache1xx).isSameAs(cache1x); } @Test public void setCacheNameNullRestoreDynamicMode() { CaffeineCacheManager cm = new CaffeineCacheManager("c1"); - assertNull(cm.getCache("someCache")); + assertThat(cm.getCache("someCache")).isNull(); cm.setCacheNames(null); - assertNotNull(cm.getCache("someCache")); + assertThat(cm.getCache("someCache")).isNotNull(); } @Test @@ -184,11 +187,10 @@ public class CaffeineCacheManagerTests { }); Cache cache1 = cm.getCache("c1"); Cache.ValueWrapper value = cache1.get("ping"); - assertNotNull(value); - assertEquals("pong", value.get()); + assertThat(value).isNotNull(); + assertThat(value.get()).isEqualTo("pong"); - assertThatIllegalArgumentException().isThrownBy(() -> - assertNull(cache1.get("foo"))) + assertThatIllegalArgumentException().isThrownBy(() -> assertThat(cache1.get("foo")).isNull()) .withMessageContaining("I only know ping"); } diff --git a/spring-context-support/src/test/java/org/springframework/cache/caffeine/CaffeineCacheTests.java b/spring-context-support/src/test/java/org/springframework/cache/caffeine/CaffeineCacheTests.java index 1dfa4cd219e..3e4aad7859d 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/caffeine/CaffeineCacheTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/caffeine/CaffeineCacheTests.java @@ -23,9 +23,7 @@ import org.junit.Test; import org.springframework.cache.AbstractValueAdaptingCacheTests; import org.springframework.cache.Cache; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ben Manes @@ -70,13 +68,15 @@ public class CaffeineCacheTests extends AbstractValueAdaptingCacheTests { brancusi.setTimeToLive(3); nativeCache.put(brancusi); - assertEquals(value, cache.get(key).get()); + assertThat(cache.get(key).get()).isEqualTo(value); // wait for the entry to expire Thread.sleep(5 * 1000); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); } } diff --git a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java index 01784f37766..4e4cb57a94a 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java @@ -29,11 +29,8 @@ import org.junit.Test; import org.springframework.core.io.ClassPathResource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -46,14 +43,14 @@ public class EhCacheSupportTests { public void testBlankCacheManager() { EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean(); cacheManagerFb.setCacheManagerName("myCacheManager"); - assertEquals(CacheManager.class, cacheManagerFb.getObjectType()); - assertTrue("Singleton property", cacheManagerFb.isSingleton()); + assertThat(cacheManagerFb.getObjectType()).isEqualTo(CacheManager.class); + assertThat(cacheManagerFb.isSingleton()).as("Singleton property").isTrue(); cacheManagerFb.afterPropertiesSet(); try { CacheManager cm = cacheManagerFb.getObject(); - assertTrue("Loaded CacheManager with no caches", cm.getCacheNames().length == 0); + assertThat(cm.getCacheNames().length == 0).as("Loaded CacheManager with no caches").isTrue(); Cache myCache1 = cm.getCache("myCache1"); - assertTrue("No myCache1 defined", myCache1 == null); + assertThat(myCache1 == null).as("No myCache1 defined").isTrue(); } finally { cacheManagerFb.destroy(); @@ -65,13 +62,13 @@ public class EhCacheSupportTests { EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean(); try { cacheManagerFb.setCacheManagerName("myCacheManager"); - assertEquals(CacheManager.class, cacheManagerFb.getObjectType()); - assertTrue("Singleton property", cacheManagerFb.isSingleton()); + assertThat(cacheManagerFb.getObjectType()).isEqualTo(CacheManager.class); + assertThat(cacheManagerFb.isSingleton()).as("Singleton property").isTrue(); cacheManagerFb.afterPropertiesSet(); CacheManager cm = cacheManagerFb.getObject(); - assertTrue("Loaded CacheManager with no caches", cm.getCacheNames().length == 0); + assertThat(cm.getCacheNames().length == 0).as("Loaded CacheManager with no caches").isTrue(); Cache myCache1 = cm.getCache("myCache1"); - assertTrue("No myCache1 defined", myCache1 == null); + assertThat(myCache1 == null).as("No myCache1 defined").isTrue(); EhCacheManagerFactoryBean cacheManagerFb2 = new EhCacheManagerFactoryBean(); cacheManagerFb2.setCacheManagerName("myCacheManager"); @@ -87,21 +84,21 @@ public class EhCacheSupportTests { public void testAcceptExistingCacheManager() { EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean(); cacheManagerFb.setCacheManagerName("myCacheManager"); - assertEquals(CacheManager.class, cacheManagerFb.getObjectType()); - assertTrue("Singleton property", cacheManagerFb.isSingleton()); + assertThat(cacheManagerFb.getObjectType()).isEqualTo(CacheManager.class); + assertThat(cacheManagerFb.isSingleton()).as("Singleton property").isTrue(); cacheManagerFb.afterPropertiesSet(); try { CacheManager cm = cacheManagerFb.getObject(); - assertTrue("Loaded CacheManager with no caches", cm.getCacheNames().length == 0); + assertThat(cm.getCacheNames().length == 0).as("Loaded CacheManager with no caches").isTrue(); Cache myCache1 = cm.getCache("myCache1"); - assertTrue("No myCache1 defined", myCache1 == null); + assertThat(myCache1 == null).as("No myCache1 defined").isTrue(); EhCacheManagerFactoryBean cacheManagerFb2 = new EhCacheManagerFactoryBean(); cacheManagerFb2.setCacheManagerName("myCacheManager"); cacheManagerFb2.setAcceptExisting(true); cacheManagerFb2.afterPropertiesSet(); CacheManager cm2 = cacheManagerFb2.getObject(); - assertSame(cm, cm2); + assertThat(cm2).isSameAs(cm); cacheManagerFb2.destroy(); } finally { @@ -116,10 +113,10 @@ public class EhCacheSupportTests { cacheManagerFb.afterPropertiesSet(); try { CacheManager cm = cacheManagerFb.getObject(); - assertTrue("Correct number of caches loaded", cm.getCacheNames().length == 1); + assertThat(cm.getCacheNames().length == 1).as("Correct number of caches loaded").isTrue(); Cache myCache1 = cm.getCache("myCache1"); - assertFalse("myCache1 is not eternal", myCache1.getCacheConfiguration().isEternal()); - assertTrue("myCache1.maxElements == 300", myCache1.getCacheConfiguration().getMaxEntriesLocalHeap() == 300); + assertThat(myCache1.getCacheConfiguration().isEternal()).as("myCache1 is not eternal").isFalse(); + assertThat(myCache1.getCacheConfiguration().getMaxEntriesLocalHeap() == 300).as("myCache1.maxElements == 300").isTrue(); } finally { cacheManagerFb.destroy(); @@ -143,8 +140,8 @@ public class EhCacheSupportTests { try { EhCacheFactoryBean cacheFb = new EhCacheFactoryBean(); Class objectType = cacheFb.getObjectType(); - assertTrue(Ehcache.class.isAssignableFrom(objectType)); - assertTrue("Singleton property", cacheFb.isSingleton()); + assertThat(Ehcache.class.isAssignableFrom(objectType)).isTrue(); + assertThat(cacheFb.isSingleton()).as("Singleton property").isTrue(); if (useCacheManagerFb) { cacheManagerFb = new EhCacheManagerFactoryBean(); cacheManagerFb.setConfigLocation(new ClassPathResource("testEhcache.xml", getClass())); @@ -158,14 +155,14 @@ public class EhCacheSupportTests { cacheFb.afterPropertiesSet(); cache = (Cache) cacheFb.getObject(); Class objectType2 = cacheFb.getObjectType(); - assertSame(objectType, objectType2); + assertThat(objectType2).isSameAs(objectType); CacheConfiguration config = cache.getCacheConfiguration(); - assertEquals("myCache1", cache.getName()); + assertThat(cache.getName()).isEqualTo("myCache1"); if (useCacheManagerFb){ - assertEquals("myCache1.maxElements", 300, config.getMaxEntriesLocalHeap()); + assertThat(config.getMaxEntriesLocalHeap()).as("myCache1.maxElements").isEqualTo(300); } else { - assertEquals("myCache1.maxElements", 10000, config.getMaxEntriesLocalHeap()); + assertThat(config.getMaxEntriesLocalHeap()).as("myCache1.maxElements").isEqualTo(10000); } // Cache region is not defined. Should create one with default properties. @@ -177,12 +174,12 @@ public class EhCacheSupportTests { cacheFb.afterPropertiesSet(); cache = (Cache) cacheFb.getObject(); config = cache.getCacheConfiguration(); - assertEquals("undefinedCache", cache.getName()); - assertTrue("default maxElements is correct", config.getMaxEntriesLocalHeap() == 10000); - assertFalse("default eternal is correct", config.isEternal()); - assertTrue("default timeToLive is correct", config.getTimeToLiveSeconds() == 120); - assertTrue("default timeToIdle is correct", config.getTimeToIdleSeconds() == 120); - assertTrue("default diskExpiryThreadIntervalSeconds is correct", config.getDiskExpiryThreadIntervalSeconds() == 120); + assertThat(cache.getName()).isEqualTo("undefinedCache"); + assertThat(config.getMaxEntriesLocalHeap() == 10000).as("default maxElements is correct").isTrue(); + assertThat(config.isEternal()).as("default eternal is correct").isFalse(); + assertThat(config.getTimeToLiveSeconds() == 120).as("default timeToLive is correct").isTrue(); + assertThat(config.getTimeToIdleSeconds() == 120).as("default timeToIdle is correct").isTrue(); + assertThat(config.getDiskExpiryThreadIntervalSeconds() == 120).as("default diskExpiryThreadIntervalSeconds is correct").isTrue(); // overriding the default properties cacheFb = new EhCacheFactoryBean(); @@ -198,11 +195,11 @@ public class EhCacheSupportTests { cache = (Cache) cacheFb.getObject(); config = cache.getCacheConfiguration(); - assertEquals("undefinedCache2", cache.getName()); - assertTrue("overridden maxElements is correct", config.getMaxEntriesLocalHeap() == 5); - assertTrue("default timeToLive is correct", config.getTimeToLiveSeconds() == 8); - assertTrue("default timeToIdle is correct", config.getTimeToIdleSeconds() == 7); - assertTrue("overridden diskExpiryThreadIntervalSeconds is correct", config.getDiskExpiryThreadIntervalSeconds() == 10); + assertThat(cache.getName()).isEqualTo("undefinedCache2"); + assertThat(config.getMaxEntriesLocalHeap() == 5).as("overridden maxElements is correct").isTrue(); + assertThat(config.getTimeToLiveSeconds() == 8).as("default timeToLive is correct").isTrue(); + assertThat(config.getTimeToIdleSeconds() == 7).as("default timeToIdle is correct").isTrue(); + assertThat(config.getDiskExpiryThreadIntervalSeconds() == 10).as("overridden diskExpiryThreadIntervalSeconds is correct").isTrue(); } finally { if (cacheManagerFbInitialized) { @@ -224,10 +221,11 @@ public class EhCacheSupportTests { cacheFb.setCacheManager(cm); cacheFb.setCacheName("myCache1"); cacheFb.setBlocking(true); - assertEquals(cacheFb.getObjectType(), BlockingCache.class); + assertThat(BlockingCache.class).isEqualTo(cacheFb.getObjectType()); cacheFb.afterPropertiesSet(); Ehcache myCache1 = cm.getEhcache("myCache1"); - assertTrue(myCache1 instanceof BlockingCache); + boolean condition = myCache1 instanceof BlockingCache; + assertThat(condition).isTrue(); } finally { cacheManagerFb.destroy(); @@ -244,11 +242,12 @@ public class EhCacheSupportTests { cacheFb.setCacheManager(cm); cacheFb.setCacheName("myCache1"); cacheFb.setCacheEntryFactory(key -> key); - assertEquals(cacheFb.getObjectType(), SelfPopulatingCache.class); + assertThat(SelfPopulatingCache.class).isEqualTo(cacheFb.getObjectType()); cacheFb.afterPropertiesSet(); Ehcache myCache1 = cm.getEhcache("myCache1"); - assertTrue(myCache1 instanceof SelfPopulatingCache); - assertEquals("myKey1", myCache1.get("myKey1").getObjectValue()); + boolean condition = myCache1 instanceof SelfPopulatingCache; + assertThat(condition).isTrue(); + assertThat(myCache1.get("myKey1").getObjectValue()).isEqualTo("myKey1"); } finally { cacheManagerFb.destroy(); @@ -273,11 +272,12 @@ public class EhCacheSupportTests { public void updateEntryValue(Object key, Object value) { } }); - assertEquals(cacheFb.getObjectType(), UpdatingSelfPopulatingCache.class); + assertThat(UpdatingSelfPopulatingCache.class).isEqualTo(cacheFb.getObjectType()); cacheFb.afterPropertiesSet(); Ehcache myCache1 = cm.getEhcache("myCache1"); - assertTrue(myCache1 instanceof UpdatingSelfPopulatingCache); - assertEquals("myKey1", myCache1.get("myKey1").getObjectValue()); + boolean condition = myCache1 instanceof UpdatingSelfPopulatingCache; + assertThat(condition).isTrue(); + assertThat(myCache1.get("myKey1").getObjectValue()).isEqualTo("myKey1"); } finally { cacheManagerFb.destroy(); diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/AbstractJCacheAnnotationTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/AbstractJCacheAnnotationTests.java index ecae1e83c7c..46d7bf1ed7b 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/AbstractJCacheAnnotationTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/AbstractJCacheAnnotationTests.java @@ -33,12 +33,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIOException; import static org.assertj.core.api.Assertions.assertThatNullPointerException; -import static org.junit.Assert.assertEquals; -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; /** * @author Stephane Nicoll @@ -73,7 +67,7 @@ public abstract class AbstractJCacheAnnotationTests { Object first = service.cache(keyItem); Object second = service.cache(keyItem); - assertSame(first, second); + assertThat(second).isSameAs(first); } @Test @@ -81,16 +75,16 @@ public abstract class AbstractJCacheAnnotationTests { Cache cache = getCache(DEFAULT_CACHE); String keyItem = name.getMethodName(); - assertNull(cache.get(keyItem)); + assertThat(cache.get(keyItem)).isNull(); Object first = service.cacheNull(keyItem); Object second = service.cacheNull(keyItem); - assertSame(first, second); + assertThat(second).isSameAs(first); Cache.ValueWrapper wrapper = cache.get(keyItem); - assertNotNull(wrapper); - assertSame(first, wrapper.get()); - assertNull("Cached value should be null", wrapper.get()); + assertThat(wrapper).isNotNull(); + assertThat(wrapper.get()).isSameAs(first); + assertThat(wrapper.get()).as("Cached value should be null").isNull(); } @Test @@ -99,14 +93,14 @@ public abstract class AbstractJCacheAnnotationTests { Cache cache = getCache(EXCEPTION_CACHE); Object key = createKey(keyItem); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> service.cacheWithException(keyItem, true)); Cache.ValueWrapper result = cache.get(key); - assertNotNull(result); - assertEquals(UnsupportedOperationException.class, result.get().getClass()); + assertThat(result).isNotNull(); + assertThat(result.get().getClass()).isEqualTo(UnsupportedOperationException.class); } @Test @@ -115,11 +109,11 @@ public abstract class AbstractJCacheAnnotationTests { Cache cache = getCache(EXCEPTION_CACHE); Object key = createKey(keyItem); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); assertThatNullPointerException().isThrownBy(() -> service.cacheWithException(keyItem, false)); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); } @Test @@ -128,13 +122,13 @@ public abstract class AbstractJCacheAnnotationTests { Cache cache = getCache(EXCEPTION_CACHE); Object key = createKey(keyItem); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); assertThatIOException().isThrownBy(() -> service.cacheWithCheckedException(keyItem, true)); Cache.ValueWrapper result = cache.get(key); - assertNotNull(result); - assertEquals(IOException.class, result.get().getClass()); + assertThat(result).isNotNull(); + assertThat(result.get().getClass()).isEqualTo(IOException.class); } @@ -169,7 +163,7 @@ public abstract class AbstractJCacheAnnotationTests { Object first = service.cacheAlwaysInvoke(keyItem); Object second = service.cacheAlwaysInvoke(keyItem); - assertNotSame(first, second); + assertThat(second).isNotSameAs(first); } @Test @@ -178,7 +172,8 @@ public abstract class AbstractJCacheAnnotationTests { Object first = service.cacheWithPartialKey(keyItem, true); Object second = service.cacheWithPartialKey(keyItem, false); - assertSame(first, second); // second argument not used, see config + // second argument not used, see config + assertThat(second).isSameAs(first); } @Test @@ -189,7 +184,8 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); service.cacheWithCustomCacheResolver(keyItem); - assertNull(cache.get(key)); // Cache in mock cache + // Cache in mock cache + assertThat(cache.get(key)).isNull(); } @Test @@ -200,7 +196,7 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); service.cacheWithCustomKeyGenerator(keyItem, "ignored"); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); } @Test @@ -210,13 +206,13 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); Object value = new Object(); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); service.put(keyItem, value); Cache.ValueWrapper result = cache.get(key); - assertNotNull(result); - assertEquals(value, result.get()); + assertThat(result).isNotNull(); + assertThat(result.get()).isEqualTo(value); } @Test @@ -226,14 +222,14 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); Object value = new Object(); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> service.putWithException(keyItem, value, true)); Cache.ValueWrapper result = cache.get(key); - assertNotNull(result); - assertEquals(value, result.get()); + assertThat(result).isNotNull(); + assertThat(result.get()).isEqualTo(value); } @Test @@ -243,11 +239,11 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); Object value = new Object(); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); assertThatNullPointerException().isThrownBy(() -> service.putWithException(keyItem, value, false)); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); } @Test @@ -257,13 +253,13 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); Object value = new Object(); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); service.earlyPut(keyItem, value); Cache.ValueWrapper result = cache.get(key); - assertNotNull(result); - assertEquals(value, result.get()); + assertThat(result).isNotNull(); + assertThat(result.get()).isEqualTo(value); } @Test @@ -273,14 +269,14 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); Object value = new Object(); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> service.earlyPutWithException(keyItem, value, true)); Cache.ValueWrapper result = cache.get(key); - assertNotNull(result); - assertEquals(value, result.get()); + assertThat(result).isNotNull(); + assertThat(result.get()).isEqualTo(value); } @Test @@ -290,13 +286,13 @@ public abstract class AbstractJCacheAnnotationTests { Object key = createKey(keyItem); Object value = new Object(); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); assertThatNullPointerException().isThrownBy(() -> service.earlyPutWithException(keyItem, value, false)); // This will be cached anyway as the earlyPut has updated the cache before Cache.ValueWrapper result = cache.get(key); - assertNotNull(result); - assertEquals(value, result.get()); + assertThat(result).isNotNull(); + assertThat(result.get()).isEqualTo(value); } @Test @@ -310,7 +306,7 @@ public abstract class AbstractJCacheAnnotationTests { service.remove(keyItem); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); } @Test @@ -325,7 +321,7 @@ public abstract class AbstractJCacheAnnotationTests { assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> service.removeWithException(keyItem, true)); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); } @Test @@ -340,8 +336,8 @@ public abstract class AbstractJCacheAnnotationTests { assertThatNullPointerException().isThrownBy(() -> service.removeWithException(keyItem, false)); Cache.ValueWrapper wrapper = cache.get(key); - assertNotNull(wrapper); - assertEquals(value, wrapper.get()); + assertThat(wrapper).isNotNull(); + assertThat(wrapper.get()).isEqualTo(value); } @Test @@ -355,7 +351,7 @@ public abstract class AbstractJCacheAnnotationTests { service.earlyRemove(keyItem); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); } @Test @@ -369,7 +365,7 @@ public abstract class AbstractJCacheAnnotationTests { assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> service.earlyRemoveWithException(keyItem, true)); - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); } @Test @@ -384,7 +380,7 @@ public abstract class AbstractJCacheAnnotationTests { assertThatNullPointerException().isThrownBy(() -> service.earlyRemoveWithException(keyItem, false)); // This will be remove anyway as the earlyRemove has removed the cache before - assertNull(cache.get(key)); + assertThat(cache.get(key)).isNull(); } @Test @@ -396,7 +392,7 @@ public abstract class AbstractJCacheAnnotationTests { service.removeAll(); - assertTrue(isEmpty(cache)); + assertThat(isEmpty(cache)).isTrue(); } @Test @@ -409,7 +405,7 @@ public abstract class AbstractJCacheAnnotationTests { assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> service.removeAllWithException(true)); - assertTrue(isEmpty(cache)); + assertThat(isEmpty(cache)).isTrue(); } @Test @@ -421,7 +417,7 @@ public abstract class AbstractJCacheAnnotationTests { assertThatNullPointerException().isThrownBy(() -> service.removeAllWithException(false)); - assertNotNull(cache.get(key)); + assertThat(cache.get(key)).isNotNull(); } @Test @@ -433,7 +429,7 @@ public abstract class AbstractJCacheAnnotationTests { service.earlyRemoveAll(); - assertTrue(isEmpty(cache)); + assertThat(isEmpty(cache)).isTrue(); } @Test @@ -445,7 +441,7 @@ public abstract class AbstractJCacheAnnotationTests { assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> service.earlyRemoveAllWithException(true)); - assertTrue(isEmpty(cache)); + assertThat(isEmpty(cache)).isTrue(); } @Test @@ -458,7 +454,7 @@ public abstract class AbstractJCacheAnnotationTests { assertThatNullPointerException().isThrownBy(() -> service.earlyRemoveAllWithException(false)); // This will be remove anyway as the earlyRemove has removed the cache before - assertTrue(isEmpty(cache)); + assertThat(isEmpty(cache)).isTrue(); } protected boolean isEmpty(Cache cache) { @@ -473,7 +469,7 @@ public abstract class AbstractJCacheAnnotationTests { private Cache getCache(String name) { Cache cache = cacheManager.getCache(name); - assertNotNull("required cache " + name + " does not exist", cache); + assertThat(cache).as("required cache " + name + " does not exist").isNotNull(); return cache; } diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheCustomInterceptorTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheCustomInterceptorTests.java index 2853d1d227c..5bb7f10bcdf 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheCustomInterceptorTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheCustomInterceptorTests.java @@ -38,8 +38,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Stephane Nicoll @@ -71,15 +71,16 @@ public class JCacheCustomInterceptorTests { @Test public void onlyOneInterceptorIsAvailable() { Map interceptors = ctx.getBeansOfType(JCacheInterceptor.class); - assertEquals("Only one interceptor should be defined", 1, interceptors.size()); + assertThat(interceptors.size()).as("Only one interceptor should be defined").isEqualTo(1); JCacheInterceptor interceptor = interceptors.values().iterator().next(); - assertEquals("Custom interceptor not defined", TestCacheInterceptor.class, interceptor.getClass()); + assertThat(interceptor.getClass()).as("Custom interceptor not defined").isEqualTo(TestCacheInterceptor.class); } @Test public void customInterceptorAppliesWithRuntimeException() { Object o = cs.cacheWithException("id", true); - assertEquals(55L, o); // See TestCacheInterceptor + // See TestCacheInterceptor + assertThat(o).isEqualTo(55L); } @Test diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheJavaConfigTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheJavaConfigTests.java index 2368818695b..f536c96fae8 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheJavaConfigTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheJavaConfigTests.java @@ -44,11 +44,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; /** * @author Stephane Nicoll @@ -67,13 +64,11 @@ public class JCacheJavaConfigTests extends AbstractJCacheAnnotationTests { new AnnotationConfigApplicationContext(FullCachingConfig.class); DefaultJCacheOperationSource cos = context.getBean(DefaultJCacheOperationSource.class); - assertSame(context.getBean(KeyGenerator.class), cos.getKeyGenerator()); - assertSame(context.getBean("cacheResolver", CacheResolver.class), - cos.getCacheResolver()); - assertSame(context.getBean("exceptionCacheResolver", CacheResolver.class), - cos.getExceptionCacheResolver()); + assertThat(cos.getKeyGenerator()).isSameAs(context.getBean(KeyGenerator.class)); + assertThat(cos.getCacheResolver()).isSameAs(context.getBean("cacheResolver", CacheResolver.class)); + assertThat(cos.getExceptionCacheResolver()).isSameAs(context.getBean("exceptionCacheResolver", CacheResolver.class)); JCacheInterceptor interceptor = context.getBean(JCacheInterceptor.class); - assertSame(context.getBean("errorHandler", CacheErrorHandler.class), interceptor.getErrorHandler()); + assertThat(interceptor.getErrorHandler()).isSameAs(context.getBean("errorHandler", CacheErrorHandler.class)); context.close(); } @@ -83,11 +78,10 @@ public class JCacheJavaConfigTests extends AbstractJCacheAnnotationTests { new AnnotationConfigApplicationContext(EmptyConfigSupportConfig.class); DefaultJCacheOperationSource cos = context.getBean(DefaultJCacheOperationSource.class); - assertNotNull(cos.getCacheResolver()); - assertEquals(SimpleCacheResolver.class, cos.getCacheResolver().getClass()); - assertSame(context.getBean(CacheManager.class), - ((SimpleCacheResolver) cos.getCacheResolver()).getCacheManager()); - assertNull(cos.getExceptionCacheResolver()); + assertThat(cos.getCacheResolver()).isNotNull(); + assertThat(cos.getCacheResolver().getClass()).isEqualTo(SimpleCacheResolver.class); + assertThat(((SimpleCacheResolver) cos.getCacheResolver()).getCacheManager()).isSameAs(context.getBean(CacheManager.class)); + assertThat(cos.getExceptionCacheResolver()).isNull(); context.close(); } @@ -97,9 +91,9 @@ public class JCacheJavaConfigTests extends AbstractJCacheAnnotationTests { new AnnotationConfigApplicationContext(FullCachingConfigSupport.class); DefaultJCacheOperationSource cos = context.getBean(DefaultJCacheOperationSource.class); - assertSame(context.getBean("cacheResolver"), cos.getCacheResolver()); - assertSame(context.getBean("keyGenerator"), cos.getKeyGenerator()); - assertSame(context.getBean("exceptionCacheResolver"), cos.getExceptionCacheResolver()); + assertThat(cos.getCacheResolver()).isSameAs(context.getBean("cacheResolver")); + assertThat(cos.getKeyGenerator()).isSameAs(context.getBean("keyGenerator")); + assertThat(cos.getExceptionCacheResolver()).isSameAs(context.getBean("exceptionCacheResolver")); context.close(); } @@ -110,7 +104,7 @@ public class JCacheJavaConfigTests extends AbstractJCacheAnnotationTests { try { DefaultJCacheOperationSource cos = context.getBean(DefaultJCacheOperationSource.class); - assertSame(context.getBean("cacheResolver"), cos.getCacheResolver()); + assertThat(cos.getCacheResolver()).isSameAs(context.getBean("cacheResolver")); JCacheableService service = context.getBean(JCacheableService.class); service.cache("id"); diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheNamespaceDrivenTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheNamespaceDrivenTests.java index 00fb1a42882..c3dfa937313 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheNamespaceDrivenTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheNamespaceDrivenTests.java @@ -25,7 +25,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -44,14 +44,14 @@ public class JCacheNamespaceDrivenTests extends AbstractJCacheAnnotationTests { "/org/springframework/cache/jcache/config/jCacheNamespaceDriven-resolver.xml"); DefaultJCacheOperationSource ci = context.getBean(DefaultJCacheOperationSource.class); - assertSame(context.getBean("cacheResolver"), ci.getCacheResolver()); + assertThat(ci.getCacheResolver()).isSameAs(context.getBean("cacheResolver")); context.close(); } @Test public void testCacheErrorHandler() { JCacheInterceptor ci = ctx.getBean(JCacheInterceptor.class); - assertSame(ctx.getBean("errorHandler", CacheErrorHandler.class), ci.getErrorHandler()); + assertThat(ci.getErrorHandler()).isSameAs(ctx.getBean("errorHandler", CacheErrorHandler.class)); } } diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AbstractCacheOperationTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AbstractCacheOperationTests.java index 51dcd7adae0..a46b2b5b00a 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AbstractCacheOperationTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AbstractCacheOperationTests.java @@ -28,8 +28,7 @@ import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -44,20 +43,18 @@ public abstract class AbstractCacheOperationTests> @Test public void simple() { O operation = createSimpleOperation(); - assertEquals("Wrong cache name", "simpleCache", operation.getCacheName()); - assertEquals("Unexpected number of annotation on " + operation.getMethod(), - 1, operation.getAnnotations().size()); - assertEquals("Wrong method annotation", operation.getCacheAnnotation(), - operation.getAnnotations().iterator().next()); + assertThat(operation.getCacheName()).as("Wrong cache name").isEqualTo("simpleCache"); + assertThat(operation.getAnnotations().size()).as("Unexpected number of annotation on " + operation.getMethod()).isEqualTo(1); + assertThat(operation.getAnnotations().iterator().next()).as("Wrong method annotation").isEqualTo(operation.getCacheAnnotation()); - assertNotNull("cache resolver should be set", operation.getCacheResolver()); + assertThat(operation.getCacheResolver()).as("cache resolver should be set").isNotNull(); } protected void assertCacheInvocationParameter(CacheInvocationParameter actual, Class targetType, Object value, int position) { - assertEquals("wrong parameter type for " + actual, targetType, actual.getRawType()); - assertEquals("wrong parameter value for " + actual, value, actual.getValue()); - assertEquals("wrong parameter position for " + actual, position, actual.getParameterPosition()); + assertThat(actual.getRawType()).as("wrong parameter type for " + actual).isEqualTo(targetType); + assertThat(actual.getValue()).as("wrong parameter value for " + actual).isEqualTo(value); + assertThat(actual.getParameterPosition()).as("wrong parameter position for " + actual).isEqualTo(position); } protected CacheMethodDetails create(Class annotationType, diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AnnotationCacheOperationSourceTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AnnotationCacheOperationSourceTests.java index e739b89aaa1..b4c652ea17c 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AnnotationCacheOperationSourceTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/AnnotationCacheOperationSourceTests.java @@ -37,11 +37,8 @@ import org.springframework.cache.jcache.support.TestableCacheResolverFactory; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -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.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -68,15 +65,15 @@ public class AnnotationCacheOperationSourceTests extends AbstractJCacheTests { public void cache() { CacheResultOperation op = getDefaultCacheOperation(CacheResultOperation.class, String.class); assertDefaults(op); - assertNull("Exception caching not enabled so resolver should not be set", op.getExceptionCacheResolver()); + assertThat(op.getExceptionCacheResolver()).as("Exception caching not enabled so resolver should not be set").isNull(); } @Test public void cacheWithException() { CacheResultOperation op = getDefaultCacheOperation(CacheResultOperation.class, String.class, boolean.class); assertDefaults(op); - assertEquals(defaultExceptionCacheResolver, op.getExceptionCacheResolver()); - assertEquals("exception", op.getExceptionCacheName()); + assertThat(op.getExceptionCacheResolver()).isEqualTo(defaultExceptionCacheResolver); + assertThat(op.getExceptionCacheName()).isEqualTo("exception"); } @Test @@ -94,12 +91,12 @@ public class AnnotationCacheOperationSourceTests extends AbstractJCacheTests { @Test public void removeAll() { CacheRemoveAllOperation op = getDefaultCacheOperation(CacheRemoveAllOperation.class); - assertEquals(defaultCacheResolver, op.getCacheResolver()); + assertThat(op.getCacheResolver()).isEqualTo(defaultCacheResolver); } @Test public void noAnnotation() { - assertNull(getCacheOperation(AnnotatedJCacheableService.class, name.getMethodName())); + assertThat(getCacheOperation(AnnotatedJCacheableService.class, name.getMethodName())).isNull(); } @Test @@ -111,7 +108,7 @@ public class AnnotationCacheOperationSourceTests extends AbstractJCacheTests { @Test public void defaultCacheNameWithCandidate() { Method method = ReflectionUtils.findMethod(Object.class, "toString"); - assertEquals("foo", source.determineCacheName(method, null, "foo")); + assertThat(source.determineCacheName(method, null, "foo")).isEqualTo("foo"); } @Test @@ -119,20 +116,19 @@ public class AnnotationCacheOperationSourceTests extends AbstractJCacheTests { Method method = ReflectionUtils.findMethod(Object.class, "toString"); CacheDefaults mock = mock(CacheDefaults.class); given(mock.cacheName()).willReturn(""); - assertEquals("java.lang.Object.toString()", source.determineCacheName(method, mock, "")); + assertThat(source.determineCacheName(method, mock, "")).isEqualTo("java.lang.Object.toString()"); } @Test public void defaultCacheNameNoDefaults() { Method method = ReflectionUtils.findMethod(Object.class, "toString"); - assertEquals("java.lang.Object.toString()", source.determineCacheName(method, null, "")); + assertThat(source.determineCacheName(method, null, "")).isEqualTo("java.lang.Object.toString()"); } @Test public void defaultCacheNameWithParameters() { Method method = ReflectionUtils.findMethod(Comparator.class, "compare", Object.class, Object.class); - assertEquals("java.util.Comparator.compare(java.lang.Object,java.lang.Object)", - source.determineCacheName(method, null, "")); + assertThat(source.determineCacheName(method, null, "")).isEqualTo("java.util.Comparator.compare(java.lang.Object,java.lang.Object)"); } @Test @@ -141,16 +137,16 @@ public class AnnotationCacheOperationSourceTests extends AbstractJCacheTests { getCacheOperation(CacheResultOperation.class, CustomService.class, name.getMethodName(), Long.class); assertJCacheResolver(operation.getCacheResolver(), TestableCacheResolver.class); assertJCacheResolver(operation.getExceptionCacheResolver(), null); - assertEquals(KeyGeneratorAdapter.class, operation.getKeyGenerator().getClass()); - assertEquals(defaultKeyGenerator, ((KeyGeneratorAdapter) operation.getKeyGenerator()).getTarget()); + assertThat(operation.getKeyGenerator().getClass()).isEqualTo(KeyGeneratorAdapter.class); + assertThat(((KeyGeneratorAdapter) operation.getKeyGenerator()).getTarget()).isEqualTo(defaultKeyGenerator); } @Test public void customKeyGenerator() { CacheResultOperation operation = getCacheOperation(CacheResultOperation.class, CustomService.class, name.getMethodName(), Long.class); - assertEquals(defaultCacheResolver, operation.getCacheResolver()); - assertNull(operation.getExceptionCacheResolver()); + assertThat(operation.getCacheResolver()).isEqualTo(defaultCacheResolver); + assertThat(operation.getExceptionCacheResolver()).isNull(); assertCacheKeyGenerator(operation.getKeyGenerator(), TestableCacheKeyGenerator.class); } @@ -160,10 +156,11 @@ public class AnnotationCacheOperationSourceTests extends AbstractJCacheTests { beanFactory.registerSingleton("fooBar", bean); CacheResultOperation operation = getCacheOperation(CacheResultOperation.class, CustomService.class, name.getMethodName(), Long.class); - assertEquals(defaultCacheResolver, operation.getCacheResolver()); - assertNull(operation.getExceptionCacheResolver()); + assertThat(operation.getCacheResolver()).isEqualTo(defaultCacheResolver); + assertThat(operation.getExceptionCacheResolver()).isNull(); KeyGeneratorAdapter adapter = (KeyGeneratorAdapter) operation.getKeyGenerator(); - assertSame(bean, adapter.getTarget()); // take bean from context + // take bean from context + assertThat(adapter.getTarget()).isSameAs(bean); } @Test @@ -185,9 +182,9 @@ public class AnnotationCacheOperationSourceTests extends AbstractJCacheTests { } private void assertDefaults(AbstractJCacheKeyOperation operation) { - assertEquals(defaultCacheResolver, operation.getCacheResolver()); - assertEquals(KeyGeneratorAdapter.class, operation.getKeyGenerator().getClass()); - assertEquals(defaultKeyGenerator, ((KeyGeneratorAdapter) operation.getKeyGenerator()).getTarget()); + assertThat(operation.getCacheResolver()).isEqualTo(defaultCacheResolver); + assertThat(operation.getKeyGenerator().getClass()).isEqualTo(KeyGeneratorAdapter.class); + assertThat(((KeyGeneratorAdapter) operation.getKeyGenerator()).getTarget()).isEqualTo(defaultKeyGenerator); } protected > T getDefaultCacheOperation(Class operationType, Class... parameterTypes) { @@ -198,8 +195,8 @@ public class AnnotationCacheOperationSourceTests extends AbstractJCacheTests { Class operationType, Class targetType, String methodName, Class... parameterTypes) { JCacheOperation result = getCacheOperation(targetType, methodName, parameterTypes); - assertNotNull(result); - assertEquals(operationType, result.getClass()); + assertThat(result).isNotNull(); + assertThat(result.getClass()).isEqualTo(operationType); return operationType.cast(result); } @@ -213,20 +210,20 @@ public class AnnotationCacheOperationSourceTests extends AbstractJCacheTests { Class expectedTargetType) { if (expectedTargetType == null) { - assertNull(actual); + assertThat(actual).isNull(); } else { - assertEquals("Wrong cache resolver implementation", CacheResolverAdapter.class, actual.getClass()); + assertThat(actual.getClass()).as("Wrong cache resolver implementation").isEqualTo(CacheResolverAdapter.class); CacheResolverAdapter adapter = (CacheResolverAdapter) actual; - assertEquals("Wrong target JCache implementation", expectedTargetType, adapter.getTarget().getClass()); + assertThat(adapter.getTarget().getClass()).as("Wrong target JCache implementation").isEqualTo(expectedTargetType); } } private void assertCacheKeyGenerator(KeyGenerator actual, Class expectedTargetType) { - assertEquals("Wrong cache resolver implementation", KeyGeneratorAdapter.class, actual.getClass()); + assertThat(actual.getClass()).as("Wrong cache resolver implementation").isEqualTo(KeyGeneratorAdapter.class); KeyGeneratorAdapter adapter = (KeyGeneratorAdapter) actual; - assertEquals("Wrong target CacheKeyGenerator implementation", expectedTargetType, adapter.getTarget().getClass()); + assertThat(adapter.getTarget().getClass()).as("Wrong target CacheKeyGenerator implementation").isEqualTo(expectedTargetType); } diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CachePutOperationTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CachePutOperationTests.java index 0919c191c86..0c4f07a5c12 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CachePutOperationTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CachePutOperationTests.java @@ -23,12 +23,9 @@ import javax.cache.annotation.CachePut; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * @author Stephane Nicoll @@ -47,12 +44,12 @@ public class CachePutOperationTests extends AbstractCacheOperationTests methodDetails = create(CachePut.class, SampleObject.class, "fullPutConfig", Long.class, SampleObject.class); CachePutOperation operation = createDefaultOperation(methodDetails); - assertTrue(operation.isEarlyPut()); - assertNotNull(operation.getExceptionTypeFilter()); - assertTrue(operation.getExceptionTypeFilter().match(IOException.class)); - assertFalse(operation.getExceptionTypeFilter().match(NullPointerException.class)); + assertThat(operation.isEarlyPut()).isTrue(); + assertThat(operation.getExceptionTypeFilter()).isNotNull(); + assertThat(operation.getExceptionTypeFilter().match(IOException.class)).isTrue(); + assertThat(operation.getExceptionTypeFilter().match(NullPointerException.class)).isFalse(); } private CachePutOperation createDefaultOperation(CacheMethodDetails methodDetails) { diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheRemoveAllOperationTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheRemoveAllOperationTests.java index 2e164a68afc..e1c4aa15954 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheRemoveAllOperationTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheRemoveAllOperationTests.java @@ -22,7 +22,7 @@ import javax.cache.annotation.CacheRemoveAll; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -42,7 +42,7 @@ public class CacheRemoveAllOperationTests extends AbstractCacheOperationTests dummyContext = createDummyContext(); CacheResolverAdapter adapter = new CacheResolverAdapter(getCacheResolver(dummyContext, "testCache")); Collection caches = adapter.resolveCaches(dummyContext); - assertNotNull(caches); - assertEquals(1, caches.size()); - assertEquals("testCache", caches.iterator().next().getName()); + assertThat(caches).isNotNull(); + assertThat(caches.size()).isEqualTo(1); + assertThat(caches.iterator().next().getName()).isEqualTo("testCache"); } @Test diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheResultOperationTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheResultOperationTests.java index 67831a3dcc9..f70fe0ee604 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheResultOperationTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/CacheResultOperationTests.java @@ -28,12 +28,8 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.Value; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Stephane Nicoll @@ -53,18 +49,18 @@ public class CacheResultOperationTests extends AbstractCacheOperationTests firstParameterAnnotations = parameters[0].getAnnotations(); - assertEquals(1, firstParameterAnnotations.size()); - assertEquals(CacheKey.class, firstParameterAnnotations.iterator().next().annotationType()); + assertThat(firstParameterAnnotations.size()).isEqualTo(1); + assertThat(firstParameterAnnotations.iterator().next().annotationType()).isEqualTo(CacheKey.class); Set secondParameterAnnotations = parameters[1].getAnnotations(); - assertEquals(1, secondParameterAnnotations.size()); - assertEquals(Value.class, secondParameterAnnotations.iterator().next().annotationType()); + assertThat(secondParameterAnnotations.size()).isEqualTo(1); + assertThat(secondParameterAnnotations.iterator().next().annotationType()).isEqualTo(Value.class); } @Test @@ -123,10 +119,10 @@ public class CacheResultOperationTests extends AbstractCacheOperationTests methodDetails = create(CacheResult.class, SampleObject.class, "fullGetConfig", Long.class); CacheResultOperation operation = createDefaultOperation(methodDetails); - assertTrue(operation.isAlwaysInvoked()); - assertNotNull(operation.getExceptionTypeFilter()); - assertTrue(operation.getExceptionTypeFilter().match(IOException.class)); - assertFalse(operation.getExceptionTypeFilter().match(NullPointerException.class)); + assertThat(operation.isAlwaysInvoked()).isTrue(); + assertThat(operation.getExceptionTypeFilter()).isNotNull(); + assertThat(operation.getExceptionTypeFilter().match(IOException.class)).isTrue(); + assertThat(operation.getExceptionTypeFilter().match(NullPointerException.class)).isFalse(); } private CacheResultOperation createDefaultOperation(CacheMethodDetails methodDetails) { diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheErrorHandlerTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheErrorHandlerTests.java index 5d6373771cd..2dc6e3c3734 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheErrorHandlerTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheErrorHandlerTests.java @@ -39,7 +39,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -102,7 +102,7 @@ public class JCacheErrorHandlerTests { this.simpleService.getFail(0L); } catch (IllegalStateException ex) { - assertEquals("Test exception", ex.getMessage()); + assertThat(ex.getMessage()).isEqualTo("Test exception"); } verify(this.errorHandler).handleCachePutError( exceptionOnPut, this.errorCache, key, SimpleService.TEST_EXCEPTION); diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheInterceptorTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheInterceptorTests.java index 6e137494e49..7d1a668472f 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheInterceptorTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheInterceptorTests.java @@ -29,9 +29,8 @@ import org.springframework.cache.interceptor.NamedCacheResolver; import org.springframework.cache.jcache.AbstractJCacheTests; import org.springframework.util.ReflectionUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * @author Stephane Nicoll @@ -88,9 +87,9 @@ public class JCacheInterceptorTests extends AbstractJCacheTests { CacheOperationInvoker invoker = new DummyInvoker(0L); Object execute = interceptor.execute(invoker, service, method, new Object[] {"myId"}); - assertNotNull("result cannot be null.", execute); - assertEquals("Wrong result type", Long.class, execute.getClass()); - assertEquals("Wrong result", 0L, execute); + assertThat(execute).as("result cannot be null.").isNotNull(); + assertThat(execute.getClass()).as("Wrong result type").isEqualTo(Long.class); + assertThat(execute).as("Wrong result").isEqualTo(0L); } protected JCacheOperationSource createOperationSource(CacheManager cacheManager, diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheKeyGeneratorTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheKeyGeneratorTests.java index cf2e97b043f..0b9345d4fe5 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheKeyGeneratorTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheKeyGeneratorTests.java @@ -38,9 +38,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -67,10 +65,10 @@ public class JCacheKeyGeneratorTests { this.keyGenerator.expect(1L); Object first = this.simpleService.get(1L); Object second = this.simpleService.get(1L); - assertSame(first, second); + assertThat(second).isSameAs(first); Object key = new SimpleKey(1L); - assertEquals(first, cache.get(key).get()); + assertThat(cache.get(key).get()).isEqualTo(first); } @Test @@ -78,10 +76,10 @@ public class JCacheKeyGeneratorTests { this.keyGenerator.expect(1L, "foo", "bar"); Object first = this.simpleService.get(1L, "foo", "bar"); Object second = this.simpleService.get(1L, "foo", "bar"); - assertSame(first, second); + assertThat(second).isSameAs(first); Object key = new SimpleKey(1L, "foo", "bar"); - assertEquals(first, cache.get(key).get()); + assertThat(cache.get(key).get()).isEqualTo(first); } @Test @@ -89,10 +87,10 @@ public class JCacheKeyGeneratorTests { this.keyGenerator.expect(1L); Object first = this.simpleService.getFiltered(1L, "foo", "bar"); Object second = this.simpleService.getFiltered(1L, "foo", "bar"); - assertSame(first, second); + assertThat(second).isSameAs(first); Object key = new SimpleKey(1L); - assertEquals(first, cache.get(key).get()); + assertThat(cache.get(key).get()).isEqualTo(first); } @@ -151,9 +149,8 @@ public class JCacheKeyGeneratorTests { @Override public Object generate(Object target, Method method, Object... params) { - assertTrue("Unexpected parameters: expected: " - + Arrays.toString(this.expectedParams) + " but got: " + Arrays.toString(params), - Arrays.equals(expectedParams, params)); + assertThat(Arrays.equals(expectedParams, params)).as("Unexpected parameters: expected: " + + Arrays.toString(this.expectedParams) + " but got: " + Arrays.toString(params)).isTrue(); return new SimpleKey(params); } } diff --git a/spring-context-support/src/test/java/org/springframework/cache/transaction/AbstractTransactionSupportingCacheManagerTests.java b/spring-context-support/src/test/java/org/springframework/cache/transaction/AbstractTransactionSupportingCacheManagerTests.java index 9df193ec348..76db2329daa 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/transaction/AbstractTransactionSupportingCacheManagerTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/transaction/AbstractTransactionSupportingCacheManagerTests.java @@ -24,8 +24,6 @@ import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Shared tests for {@link CacheManager} that inherit from @@ -76,10 +74,10 @@ public abstract class AbstractTransactionSupportingCacheManagerTests ccs = Arrays.asList(message.getCc()); - assertTrue(ccs.contains("he@mail.org")); - assertTrue(ccs.contains("she@mail.org")); + assertThat(ccs.contains("he@mail.org")).isTrue(); + assertThat(ccs.contains("she@mail.org")).isTrue(); List bccs = Arrays.asList(message.getBcc()); - assertTrue(bccs.contains("us@mail.org")); - assertTrue(bccs.contains("them@mail.org")); - assertEquals(sentDate, message.getSentDate()); - assertEquals("my subject", message.getSubject()); - assertEquals("my text", message.getText()); + assertThat(bccs.contains("us@mail.org")).isTrue(); + assertThat(bccs.contains("them@mail.org")).isTrue(); + assertThat(message.getSentDate()).isEqualTo(sentDate); + assertThat(message.getSubject()).isEqualTo("my subject"); + assertThat(message.getText()).isEqualTo("my text"); messageCopy = new SimpleMailMessage(message); - assertEquals("me@mail.org", messageCopy.getFrom()); - assertEquals("reply@mail.org", messageCopy.getReplyTo()); - assertEquals("you@mail.org", messageCopy.getTo()[0]); + assertThat(messageCopy.getFrom()).isEqualTo("me@mail.org"); + assertThat(messageCopy.getReplyTo()).isEqualTo("reply@mail.org"); + assertThat(messageCopy.getTo()[0]).isEqualTo("you@mail.org"); ccs = Arrays.asList(messageCopy.getCc()); - assertTrue(ccs.contains("he@mail.org")); - assertTrue(ccs.contains("she@mail.org")); + assertThat(ccs.contains("he@mail.org")).isTrue(); + assertThat(ccs.contains("she@mail.org")).isTrue(); bccs = Arrays.asList(message.getBcc()); - assertTrue(bccs.contains("us@mail.org")); - assertTrue(bccs.contains("them@mail.org")); - assertEquals(sentDate, messageCopy.getSentDate()); - assertEquals("my subject", messageCopy.getSubject()); - assertEquals("my text", messageCopy.getText()); + assertThat(bccs.contains("us@mail.org")).isTrue(); + assertThat(bccs.contains("them@mail.org")).isTrue(); + assertThat(messageCopy.getSentDate()).isEqualTo(sentDate); + assertThat(messageCopy.getSubject()).isEqualTo("my subject"); + assertThat(messageCopy.getText()).isEqualTo("my text"); } @Test @@ -95,9 +94,9 @@ public class SimpleMailMessageTests { original.getCc()[0] = "mmm@mmm.org"; original.getBcc()[0] = "mmm@mmm.org"; - assertEquals("fiona@mail.org", copy.getTo()[0]); - assertEquals("he@mail.org", copy.getCc()[0]); - assertEquals("us@mail.org", copy.getBcc()[0]); + assertThat(copy.getTo()[0]).isEqualTo("fiona@mail.org"); + assertThat(copy.getCc()[0]).isEqualTo("he@mail.org"); + assertThat(copy.getBcc()[0]).isEqualTo("us@mail.org"); } /** @@ -118,8 +117,8 @@ public class SimpleMailMessageTests { // Copy the message SimpleMailMessage message2 = new SimpleMailMessage(message1); - assertEquals(message1, message2); - assertEquals(message1.hashCode(), message2.hashCode()); + assertThat(message2).isEqualTo(message1); + assertThat(message2.hashCode()).isEqualTo(message1.hashCode()); } public final void testEqualsObject() { @@ -129,20 +128,22 @@ public class SimpleMailMessageTests { // Same object is equal message1 = new SimpleMailMessage(); message2 = message1; - assertTrue(message1.equals(message2)); + assertThat(message1.equals(message2)).isTrue(); // Null object is not equal message1 = new SimpleMailMessage(); message2 = null; - assertTrue(!(message1.equals(message2))); + boolean condition1 = !(message1.equals(message2)); + assertThat(condition1).isTrue(); // Different class is not equal - assertTrue(!(message1.equals(new Object()))); + boolean condition = !(message1.equals(new Object())); + assertThat(condition).isTrue(); // Equal values are equal message1 = new SimpleMailMessage(); message2 = new SimpleMailMessage(); - assertTrue(message1.equals(message2)); + assertThat(message1.equals(message2)).isTrue(); message1 = new SimpleMailMessage(); message1.setFrom("from@somewhere"); @@ -154,7 +155,7 @@ public class SimpleMailMessageTests { message1.setSubject("subject"); message1.setText("text"); message2 = new SimpleMailMessage(message1); - assertTrue(message1.equals(message2)); + assertThat(message1.equals(message2)).isTrue(); } @Test diff --git a/spring-context-support/src/test/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMapTests.java b/spring-context-support/src/test/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMapTests.java index 6f756a5fa67..8771bf30c91 100644 --- a/spring-context-support/src/test/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMapTests.java +++ b/spring-context-support/src/test/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMapTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -36,18 +36,18 @@ public class ConfigurableMimeFileTypeMapTests { ConfigurableMimeFileTypeMap ftm = new ConfigurableMimeFileTypeMap(); ftm.afterPropertiesSet(); - assertEquals("Invalid content type for HTM", "text/html", ftm.getContentType("foobar.HTM")); - assertEquals("Invalid content type for html", "text/html", ftm.getContentType("foobar.html")); - assertEquals("Invalid content type for c++", "text/plain", ftm.getContentType("foobar.c++")); - assertEquals("Invalid content type for svf", "image/vnd.svf", ftm.getContentType("foobar.svf")); - assertEquals("Invalid content type for dsf", "image/x-mgx-dsf", ftm.getContentType("foobar.dsf")); - assertEquals("Invalid default content type", "application/octet-stream", ftm.getContentType("foobar.foo")); + assertThat(ftm.getContentType("foobar.HTM")).as("Invalid content type for HTM").isEqualTo("text/html"); + assertThat(ftm.getContentType("foobar.html")).as("Invalid content type for html").isEqualTo("text/html"); + assertThat(ftm.getContentType("foobar.c++")).as("Invalid content type for c++").isEqualTo("text/plain"); + assertThat(ftm.getContentType("foobar.svf")).as("Invalid content type for svf").isEqualTo("image/vnd.svf"); + assertThat(ftm.getContentType("foobar.dsf")).as("Invalid content type for dsf").isEqualTo("image/x-mgx-dsf"); + assertThat(ftm.getContentType("foobar.foo")).as("Invalid default content type").isEqualTo("application/octet-stream"); } @Test public void againstDefaultConfigurationWithFilePath() throws Exception { ConfigurableMimeFileTypeMap ftm = new ConfigurableMimeFileTypeMap(); - assertEquals("Invalid content type for HTM", "text/html", ftm.getContentType(new File("/tmp/foobar.HTM"))); + assertThat(ftm.getContentType(new File("/tmp/foobar.HTM"))).as("Invalid content type for HTM").isEqualTo("text/html"); } @Test @@ -56,9 +56,9 @@ public class ConfigurableMimeFileTypeMapTests { ftm.setMappings(new String[] {"foo/bar HTM foo", "foo/cpp c++"}); ftm.afterPropertiesSet(); - assertEquals("Invalid content type for HTM - override didn't work", "foo/bar", ftm.getContentType("foobar.HTM")); - assertEquals("Invalid content type for c++ - override didn't work", "foo/cpp", ftm.getContentType("foobar.c++")); - assertEquals("Invalid content type for foo - new mapping didn't work", "foo/bar", ftm.getContentType("bar.foo")); + assertThat(ftm.getContentType("foobar.HTM")).as("Invalid content type for HTM - override didn't work").isEqualTo("foo/bar"); + assertThat(ftm.getContentType("foobar.c++")).as("Invalid content type for c++ - override didn't work").isEqualTo("foo/cpp"); + assertThat(ftm.getContentType("bar.foo")).as("Invalid content type for foo - new mapping didn't work").isEqualTo("foo/bar"); } @Test @@ -69,10 +69,10 @@ public class ConfigurableMimeFileTypeMapTests { ftm.setMappingLocation(resource); ftm.afterPropertiesSet(); - assertEquals("Invalid content type for foo", "text/foo", ftm.getContentType("foobar.foo")); - assertEquals("Invalid content type for bar", "text/bar", ftm.getContentType("foobar.bar")); - assertEquals("Invalid content type for fimg", "image/foo", ftm.getContentType("foobar.fimg")); - assertEquals("Invalid content type for bimg", "image/bar", ftm.getContentType("foobar.bimg")); + assertThat(ftm.getContentType("foobar.foo")).as("Invalid content type for foo").isEqualTo("text/foo"); + assertThat(ftm.getContentType("foobar.bar")).as("Invalid content type for bar").isEqualTo("text/bar"); + assertThat(ftm.getContentType("foobar.fimg")).as("Invalid content type for fimg").isEqualTo("image/foo"); + assertThat(ftm.getContentType("foobar.bimg")).as("Invalid content type for bimg").isEqualTo("image/bar"); } } diff --git a/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java b/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java index 95dec56c26c..75b2c1b3967 100644 --- a/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java +++ b/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java @@ -18,8 +18,8 @@ package org.springframework.mail.javamail; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @author Brian Hanafee @@ -37,37 +37,37 @@ public class InternetAddressEditorTests { @Test public void uninitialized() { - assertEquals("Uninitialized editor did not return empty value string", EMPTY, editor.getAsText()); + assertThat(editor.getAsText()).as("Uninitialized editor did not return empty value string").isEqualTo(EMPTY); } @Test public void setNull() { editor.setAsText(null); - assertEquals("Setting null did not result in empty value string", EMPTY, editor.getAsText()); + assertThat(editor.getAsText()).as("Setting null did not result in empty value string").isEqualTo(EMPTY); } @Test public void setEmpty() { editor.setAsText(EMPTY); - assertEquals("Setting empty string did not result in empty value string", EMPTY, editor.getAsText()); + assertThat(editor.getAsText()).as("Setting empty string did not result in empty value string").isEqualTo(EMPTY); } @Test public void allWhitespace() { editor.setAsText(" "); - assertEquals("All whitespace was not recognized", EMPTY, editor.getAsText()); + assertThat(editor.getAsText()).as("All whitespace was not recognized").isEqualTo(EMPTY); } @Test public void simpleGoodAddress() { editor.setAsText(SIMPLE); - assertEquals("Simple email address failed", SIMPLE, editor.getAsText()); + assertThat(editor.getAsText()).as("Simple email address failed").isEqualTo(SIMPLE); } @Test public void excessWhitespace() { editor.setAsText(" " + SIMPLE + " "); - assertEquals("Whitespace was not stripped", SIMPLE, editor.getAsText()); + assertThat(editor.getAsText()).as("Whitespace was not stripped").isEqualTo(SIMPLE); } @Test diff --git a/spring-context-support/src/test/java/org/springframework/mail/javamail/JavaMailSenderTests.java b/spring-context-support/src/test/java/org/springframework/mail/javamail/JavaMailSenderTests.java index 16f43604f51..df1376ea4e6 100644 --- a/spring-context-support/src/test/java/org/springframework/mail/javamail/JavaMailSenderTests.java +++ b/spring-context-support/src/test/java/org/springframework/mail/javamail/JavaMailSenderTests.java @@ -45,9 +45,6 @@ import org.springframework.util.ObjectUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.entry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -76,33 +73,33 @@ public class JavaMailSenderTests { simpleMessage.setText("my text"); sender.send(simpleMessage); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals(30, sender.transport.getConnectedPort()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedPort()).isEqualTo(30); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); - assertEquals(1, sender.transport.getSentMessages().size()); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(1); MimeMessage sentMessage = sender.transport.getSentMessage(0); List
froms = Arrays.asList(sentMessage.getFrom()); - assertEquals(1, froms.size()); - assertEquals("me@mail.org", ((InternetAddress) froms.get(0)).getAddress()); + assertThat(froms.size()).isEqualTo(1); + assertThat(((InternetAddress) froms.get(0)).getAddress()).isEqualTo("me@mail.org"); List
replyTos = Arrays.asList(sentMessage.getReplyTo()); - assertEquals("reply@mail.org", ((InternetAddress) replyTos.get(0)).getAddress()); + assertThat(((InternetAddress) replyTos.get(0)).getAddress()).isEqualTo("reply@mail.org"); List
tos = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.TO)); - assertEquals(1, tos.size()); - assertEquals("you@mail.org", ((InternetAddress) tos.get(0)).getAddress()); + assertThat(tos.size()).isEqualTo(1); + assertThat(((InternetAddress) tos.get(0)).getAddress()).isEqualTo("you@mail.org"); List
ccs = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.CC)); - assertEquals(2, ccs.size()); - assertEquals("he@mail.org", ((InternetAddress) ccs.get(0)).getAddress()); - assertEquals("she@mail.org", ((InternetAddress) ccs.get(1)).getAddress()); + assertThat(ccs.size()).isEqualTo(2); + assertThat(((InternetAddress) ccs.get(0)).getAddress()).isEqualTo("he@mail.org"); + assertThat(((InternetAddress) ccs.get(1)).getAddress()).isEqualTo("she@mail.org"); List
bccs = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.BCC)); - assertEquals(2, bccs.size()); - assertEquals("us@mail.org", ((InternetAddress) bccs.get(0)).getAddress()); - assertEquals("them@mail.org", ((InternetAddress) bccs.get(1)).getAddress()); - assertEquals(sentDate.getTime(), sentMessage.getSentDate().getTime()); - assertEquals("my subject", sentMessage.getSubject()); - assertEquals("my text", sentMessage.getContent()); + assertThat(bccs.size()).isEqualTo(2); + assertThat(((InternetAddress) bccs.get(0)).getAddress()).isEqualTo("us@mail.org"); + assertThat(((InternetAddress) bccs.get(1)).getAddress()).isEqualTo("them@mail.org"); + assertThat(sentMessage.getSentDate().getTime()).isEqualTo(sentDate.getTime()); + assertThat(sentMessage.getSubject()).isEqualTo("my subject"); + assertThat(sentMessage.getContent()).isEqualTo("my text"); } @Test @@ -118,20 +115,20 @@ public class JavaMailSenderTests { simpleMessage2.setTo("she@mail.org"); sender.send(simpleMessage1, simpleMessage2); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); - assertEquals(2, sender.transport.getSentMessages().size()); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(2); MimeMessage sentMessage1 = sender.transport.getSentMessage(0); List
tos1 = Arrays.asList(sentMessage1.getRecipients(Message.RecipientType.TO)); - assertEquals(1, tos1.size()); - assertEquals("he@mail.org", ((InternetAddress) tos1.get(0)).getAddress()); + assertThat(tos1.size()).isEqualTo(1); + assertThat(((InternetAddress) tos1.get(0)).getAddress()).isEqualTo("he@mail.org"); MimeMessage sentMessage2 = sender.transport.getSentMessage(1); List
tos2 = Arrays.asList(sentMessage2.getRecipients(Message.RecipientType.TO)); - assertEquals(1, tos2.size()); - assertEquals("she@mail.org", ((InternetAddress) tos2.get(0)).getAddress()); + assertThat(tos2.size()).isEqualTo(1); + assertThat(((InternetAddress) tos2.get(0)).getAddress()).isEqualTo("she@mail.org"); } @Test @@ -145,12 +142,12 @@ public class JavaMailSenderTests { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("you@mail.org")); sender.send(mimeMessage); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); - assertEquals(1, sender.transport.getSentMessages().size()); - assertEquals(mimeMessage, sender.transport.getSentMessage(0)); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(1); + assertThat(sender.transport.getSentMessage(0)).isEqualTo(mimeMessage); } @Test @@ -166,13 +163,13 @@ public class JavaMailSenderTests { mimeMessage2.setRecipient(Message.RecipientType.TO, new InternetAddress("she@mail.org")); sender.send(mimeMessage1, mimeMessage2); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); - assertEquals(2, sender.transport.getSentMessages().size()); - assertEquals(mimeMessage1, sender.transport.getSentMessage(0)); - assertEquals(mimeMessage2, sender.transport.getSentMessage(1)); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(2); + assertThat(sender.transport.getSentMessage(0)).isEqualTo(mimeMessage1); + assertThat(sender.transport.getSentMessage(1)).isEqualTo(mimeMessage2); } @Test @@ -193,12 +190,12 @@ public class JavaMailSenderTests { }; sender.send(preparator); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); - assertEquals(1, sender.transport.getSentMessages().size()); - assertEquals(messages.get(0), sender.transport.getSentMessage(0)); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(1); + assertThat(sender.transport.getSentMessage(0)).isEqualTo(messages.get(0)); } @Test @@ -226,13 +223,13 @@ public class JavaMailSenderTests { }; sender.send(preparator1, preparator2); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); - assertEquals(2, sender.transport.getSentMessages().size()); - assertEquals(messages.get(0), sender.transport.getSentMessage(0)); - assertEquals(messages.get(1), sender.transport.getSentMessage(1)); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(2); + assertThat(sender.transport.getSentMessage(0)).isEqualTo(messages.get(0)); + assertThat(sender.transport.getSentMessage(1)).isEqualTo(messages.get(1)); } @Test @@ -243,18 +240,19 @@ public class JavaMailSenderTests { sender.setPassword("password"); MimeMessageHelper message = new MimeMessageHelper(sender.createMimeMessage()); - assertNull(message.getEncoding()); - assertTrue(message.getFileTypeMap() instanceof ConfigurableMimeFileTypeMap); + assertThat(message.getEncoding()).isNull(); + boolean condition = message.getFileTypeMap() instanceof ConfigurableMimeFileTypeMap; + assertThat(condition).isTrue(); message.setTo("you@mail.org"); sender.send(message.getMimeMessage()); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); - assertEquals(1, sender.transport.getSentMessages().size()); - assertEquals(message.getMimeMessage(), sender.transport.getSentMessage(0)); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(1); + assertThat(sender.transport.getSentMessage(0)).isEqualTo(message.getMimeMessage()); } @Test @@ -265,20 +263,20 @@ public class JavaMailSenderTests { sender.setPassword("password"); MimeMessageHelper message = new MimeMessageHelper(sender.createMimeMessage(), "UTF-8"); - assertEquals("UTF-8", message.getEncoding()); + assertThat(message.getEncoding()).isEqualTo("UTF-8"); FileTypeMap fileTypeMap = new ConfigurableMimeFileTypeMap(); message.setFileTypeMap(fileTypeMap); - assertEquals(fileTypeMap, message.getFileTypeMap()); + assertThat(message.getFileTypeMap()).isEqualTo(fileTypeMap); message.setTo("you@mail.org"); sender.send(message.getMimeMessage()); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); - assertEquals(1, sender.transport.getSentMessages().size()); - assertEquals(message.getMimeMessage(), sender.transport.getSentMessage(0)); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(1); + assertThat(sender.transport.getSentMessage(0)).isEqualTo(message.getMimeMessage()); } @Test @@ -292,18 +290,18 @@ public class JavaMailSenderTests { FileTypeMap fileTypeMap = new ConfigurableMimeFileTypeMap(); sender.setDefaultFileTypeMap(fileTypeMap); MimeMessageHelper message = new MimeMessageHelper(sender.createMimeMessage()); - assertEquals("UTF-8", message.getEncoding()); - assertEquals(fileTypeMap, message.getFileTypeMap()); + assertThat(message.getEncoding()).isEqualTo("UTF-8"); + assertThat(message.getFileTypeMap()).isEqualTo(fileTypeMap); message.setTo("you@mail.org"); sender.send(message.getMimeMessage()); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); - assertEquals(1, sender.transport.getSentMessages().size()); - assertEquals(message.getMimeMessage(), sender.transport.getSentMessage(0)); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(1); + assertThat(sender.transport.getSentMessage(0)).isEqualTo(message.getMimeMessage()); } @Test @@ -316,7 +314,8 @@ public class JavaMailSenderTests { } catch (MailParseException ex) { // expected - assertTrue(ex.getCause() instanceof AddressException); + boolean condition = ex.getCause() instanceof AddressException; + assertThat(condition).isTrue(); } } @@ -334,7 +333,8 @@ public class JavaMailSenderTests { } catch (MailParseException ex) { // expected - assertTrue(ex.getCause() instanceof AddressException); + boolean condition = ex.getCause() instanceof AddressException; + assertThat(condition).isTrue(); } } @@ -344,7 +344,7 @@ public class JavaMailSenderTests { MockJavaMailSender sender = new MockJavaMailSender() { @Override protected Transport getTransport(Session sess) throws NoSuchProviderException { - assertEquals(session, sess); + assertThat(sess).isEqualTo(session); return super.getTransport(sess); } }; @@ -359,12 +359,12 @@ public class JavaMailSenderTests { mimeMessage.setSentDate(new GregorianCalendar(2005, 3, 1).getTime()); sender.send(mimeMessage); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); - assertEquals(1, sender.transport.getSentMessages().size()); - assertEquals(mimeMessage, sender.transport.getSentMessage(0)); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(1); + assertThat(sender.transport.getSentMessage(0)).isEqualTo(mimeMessage); } @Test @@ -374,7 +374,7 @@ public class JavaMailSenderTests { MockJavaMailSender sender = new MockJavaMailSender() { @Override protected Transport getTransport(Session sess) throws NoSuchProviderException { - assertEquals("bogusValue", sess.getProperty("bogusKey")); + assertThat(sess.getProperty("bogusKey")).isEqualTo("bogusValue"); return super.getTransport(sess); } }; @@ -387,12 +387,12 @@ public class JavaMailSenderTests { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("you@mail.org")); sender.send(mimeMessage); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); - assertEquals(1, sender.transport.getSentMessages().size()); - assertEquals(mimeMessage, sender.transport.getSentMessage(0)); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(1); + assertThat(sender.transport.getSentMessage(0)).isEqualTo(mimeMessage); } @Test @@ -437,17 +437,18 @@ public class JavaMailSenderTests { } catch (MailSendException ex) { ex.printStackTrace(); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); - assertEquals(1, sender.transport.getSentMessages().size()); - assertEquals(new InternetAddress("she@mail.org"), sender.transport.getSentMessage(0).getAllRecipients()[0]); - assertEquals(1, ex.getFailedMessages().size()); - assertEquals(simpleMessage1, ex.getFailedMessages().keySet().iterator().next()); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(1); + assertThat(sender.transport.getSentMessage(0).getAllRecipients()[0]).isEqualTo(new InternetAddress("she@mail.org")); + assertThat(ex.getFailedMessages().size()).isEqualTo(1); + assertThat(ex.getFailedMessages().keySet().iterator().next()).isEqualTo(simpleMessage1); Object subEx = ex.getFailedMessages().values().iterator().next(); - assertTrue(subEx instanceof MessagingException); - assertEquals("failed", ((MessagingException) subEx).getMessage()); + boolean condition = subEx instanceof MessagingException; + assertThat(condition).isTrue(); + assertThat(((MessagingException) subEx).getMessage()).isEqualTo("failed"); } } @@ -469,17 +470,18 @@ public class JavaMailSenderTests { } catch (MailSendException ex) { ex.printStackTrace(); - assertEquals("host", sender.transport.getConnectedHost()); - assertEquals("username", sender.transport.getConnectedUsername()); - assertEquals("password", sender.transport.getConnectedPassword()); - assertTrue(sender.transport.isCloseCalled()); - assertEquals(1, sender.transport.getSentMessages().size()); - assertEquals(mimeMessage2, sender.transport.getSentMessage(0)); - assertEquals(1, ex.getFailedMessages().size()); - assertEquals(mimeMessage1, ex.getFailedMessages().keySet().iterator().next()); + assertThat(sender.transport.getConnectedHost()).isEqualTo("host"); + assertThat(sender.transport.getConnectedUsername()).isEqualTo("username"); + assertThat(sender.transport.getConnectedPassword()).isEqualTo("password"); + assertThat(sender.transport.isCloseCalled()).isTrue(); + assertThat(sender.transport.getSentMessages().size()).isEqualTo(1); + assertThat(sender.transport.getSentMessage(0)).isEqualTo(mimeMessage2); + assertThat(ex.getFailedMessages().size()).isEqualTo(1); + assertThat(ex.getFailedMessages().keySet().iterator().next()).isEqualTo(mimeMessage1); Object subEx = ex.getFailedMessages().values().iterator().next(); - assertTrue(subEx instanceof MessagingException); - assertEquals("failed", ((MessagingException) subEx).getMessage()); + boolean condition = subEx instanceof MessagingException; + assertThat(condition).isTrue(); + assertThat(((MessagingException) subEx).getMessage()).isEqualTo("failed"); } } @@ -585,7 +587,7 @@ public class JavaMailSenderTests { throw new MessagingException("No sentDate specified"); } if (message.getSubject() != null && message.getSubject().contains("custom")) { - assertEquals(new GregorianCalendar(2005, 3, 1).getTime(), message.getSentDate()); + assertThat(message.getSentDate()).isEqualTo(new GregorianCalendar(2005, 3, 1).getTime()); } this.sentMessages.add(message); } diff --git a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/CronTriggerFactoryBeanTests.java b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/CronTriggerFactoryBeanTests.java index ac22724770d..140fe75b4bf 100644 --- a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/CronTriggerFactoryBeanTests.java +++ b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/CronTriggerFactoryBeanTests.java @@ -21,7 +21,7 @@ import java.text.ParseException; import org.junit.Test; import org.quartz.CronTrigger; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -35,7 +35,7 @@ public class CronTriggerFactoryBeanTests { factory.setCronExpression("0 15 10 ? * *"); factory.afterPropertiesSet(); CronTrigger trigger = factory.getObject(); - assertEquals("0 15 10 ? * *", trigger.getCronExpression()); + assertThat(trigger.getCronExpression()).isEqualTo("0 15 10 ? * *"); } } diff --git a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSchedulerLifecycleTests.java b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSchedulerLifecycleTests.java index 306c9c9c68f..be87560ac3a 100644 --- a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSchedulerLifecycleTests.java +++ b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSchedulerLifecycleTests.java @@ -22,8 +22,7 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.util.StopWatch; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -35,26 +34,26 @@ public class QuartzSchedulerLifecycleTests { public void destroyLazyInitSchedulerWithDefaultShutdownOrderDoesNotHang() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("quartzSchedulerLifecycleTests.xml", getClass()); - assertNotNull(context.getBean("lazyInitSchedulerWithDefaultShutdownOrder")); + assertThat(context.getBean("lazyInitSchedulerWithDefaultShutdownOrder")).isNotNull(); StopWatch sw = new StopWatch(); sw.start("lazyScheduler"); context.close(); sw.stop(); - assertTrue("Quartz Scheduler with lazy-init is hanging on destruction: " + - sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 500); + assertThat(sw.getTotalTimeMillis() < 500).as("Quartz Scheduler with lazy-init is hanging on destruction: " + + sw.getTotalTimeMillis()).isTrue(); } @Test // SPR-6354 public void destroyLazyInitSchedulerWithCustomShutdownOrderDoesNotHang() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("quartzSchedulerLifecycleTests.xml", getClass()); - assertNotNull(context.getBean("lazyInitSchedulerWithCustomShutdownOrder")); + assertThat(context.getBean("lazyInitSchedulerWithCustomShutdownOrder")).isNotNull(); StopWatch sw = new StopWatch(); sw.start("lazyScheduler"); context.close(); sw.stop(); - assertTrue("Quartz Scheduler with lazy-init is hanging on destruction: " + - sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 500); + assertThat(sw.getTotalTimeMillis() < 500).as("Quartz Scheduler with lazy-init is hanging on destruction: " + + sw.getTotalTimeMillis()).isTrue(); } } diff --git a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java index 9284ab0b1f3..767c4fdde89 100644 --- a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java +++ b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java @@ -41,12 +41,8 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; 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.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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -87,8 +83,8 @@ public class QuartzSupportTests { schedulerFactoryBean.afterPropertiesSet(); schedulerFactoryBean.start(); Scheduler returnedScheduler = schedulerFactoryBean.getObject(); - assertEquals(tb, returnedScheduler.getContext().get("testBean")); - assertEquals(ac, returnedScheduler.getContext().get("appCtx")); + assertThat(returnedScheduler.getContext().get("testBean")).isEqualTo(tb); + assertThat(returnedScheduler.getContext().get("appCtx")).isEqualTo(ac); } finally { schedulerFactoryBean.destroy(); @@ -126,8 +122,8 @@ public class QuartzSupportTests { bean.start(); Thread.sleep(500); - assertTrue("DummyJob should have been executed at least once.", DummyJob.count > 0); - assertEquals(DummyJob.count, taskExecutor.count); + assertThat(DummyJob.count > 0).as("DummyJob should have been executed at least once.").isTrue(); + assertThat(taskExecutor.count).isEqualTo(DummyJob.count); bean.destroy(); } @@ -168,8 +164,8 @@ public class QuartzSupportTests { bean.start(); Thread.sleep(500); - assertEquals(10, DummyJobBean.param); - assertTrue(DummyJobBean.count > 0); + assertThat(DummyJobBean.param).isEqualTo(10); + assertThat(DummyJobBean.count > 0).isTrue(); bean.destroy(); } @@ -204,8 +200,8 @@ public class QuartzSupportTests { bean.start(); Thread.sleep(500); - assertEquals(10, DummyJob.param); - assertTrue("DummyJob should have been executed at least once.", DummyJob.count > 0); + assertThat(DummyJob.param).isEqualTo(10); + assertThat(DummyJob.count > 0).as("DummyJob should have been executed at least once.").isTrue(); bean.destroy(); } @@ -241,8 +237,8 @@ public class QuartzSupportTests { bean.afterPropertiesSet(); Thread.sleep(500); - assertEquals(0, DummyJob.param); - assertTrue(DummyJob.count == 0); + assertThat(DummyJob.param).isEqualTo(0); + assertThat(DummyJob.count == 0).isTrue(); bean.destroy(); } @@ -275,8 +271,8 @@ public class QuartzSupportTests { bean.start(); Thread.sleep(500); - assertEquals(10, DummyJobBean.param); - assertTrue(DummyJobBean.count > 0); + assertThat(DummyJobBean.param).isEqualTo(10); + assertThat(DummyJobBean.count > 0).isTrue(); bean.destroy(); } @@ -294,8 +290,8 @@ public class QuartzSupportTests { bean.start(); Thread.sleep(500); - assertEquals(10, DummyJob.param); - assertTrue("DummyJob should have been executed at least once.", DummyJob.count > 0); + assertThat(DummyJob.param).isEqualTo(10); + assertThat(DummyJob.count > 0).as("DummyJob should have been executed at least once.").isTrue(); bean.destroy(); } @@ -306,9 +302,9 @@ public class QuartzSupportTests { try { Scheduler scheduler1 = (Scheduler) ctx.getBean("scheduler1"); Scheduler scheduler2 = (Scheduler) ctx.getBean("scheduler2"); - assertNotSame(scheduler1, scheduler2); - assertEquals("quartz1", scheduler1.getSchedulerName()); - assertEquals("quartz2", scheduler2.getSchedulerName()); + assertThat(scheduler2).isNotSameAs(scheduler1); + assertThat(scheduler1.getSchedulerName()).isEqualTo("quartz1"); + assertThat(scheduler2.getSchedulerName()).isEqualTo("quartz2"); } finally { ctx.close(); @@ -321,9 +317,9 @@ public class QuartzSupportTests { try { Scheduler scheduler1 = (Scheduler) ctx.getBean("scheduler1"); Scheduler scheduler2 = (Scheduler) ctx.getBean("scheduler2"); - assertNotSame(scheduler1, scheduler2); - assertEquals("quartz1", scheduler1.getSchedulerName()); - assertEquals("quartz2", scheduler2.getSchedulerName()); + assertThat(scheduler2).isNotSameAs(scheduler1); + assertThat(scheduler1.getSchedulerName()).isEqualTo("quartz1"); + assertThat(scheduler2.getSchedulerName()).isEqualTo("quartz2"); } finally { ctx.close(); @@ -339,10 +335,10 @@ public class QuartzSupportTests { QuartzTestBean exportService = (QuartzTestBean) ctx.getBean("exportService"); QuartzTestBean importService = (QuartzTestBean) ctx.getBean("importService"); - assertEquals("doImport called exportService", 0, exportService.getImportCount()); - assertEquals("doExport not called on exportService", 2, exportService.getExportCount()); - assertEquals("doImport not called on importService", 2, importService.getImportCount()); - assertEquals("doExport called on importService", 0, importService.getExportCount()); + assertThat(exportService.getImportCount()).as("doImport called exportService").isEqualTo(0); + assertThat(exportService.getExportCount()).as("doExport not called on exportService").isEqualTo(2); + assertThat(importService.getImportCount()).as("doImport not called on importService").isEqualTo(2); + assertThat(importService.getExportCount()).as("doExport called on importService").isEqualTo(0); } finally { ctx.close(); @@ -358,10 +354,10 @@ public class QuartzSupportTests { QuartzTestBean exportService = (QuartzTestBean) ctx.getBean("exportService"); QuartzTestBean importService = (QuartzTestBean) ctx.getBean("importService"); - assertEquals("doImport called exportService", 0, exportService.getImportCount()); - assertEquals("doExport not called on exportService", 2, exportService.getExportCount()); - assertEquals("doImport not called on importService", 2, importService.getImportCount()); - assertEquals("doExport called on importService", 0, importService.getExportCount()); + assertThat(exportService.getImportCount()).as("doImport called exportService").isEqualTo(0); + assertThat(exportService.getExportCount()).as("doExport not called on exportService").isEqualTo(2); + assertThat(importService.getImportCount()).as("doImport not called on importService").isEqualTo(2); + assertThat(importService.getExportCount()).as("doExport called on importService").isEqualTo(0); } finally { ctx.close(); @@ -374,9 +370,9 @@ public class QuartzSupportTests { StaticApplicationContext context = new StaticApplicationContext(); context.registerBeanDefinition("scheduler", new RootBeanDefinition(SchedulerFactoryBean.class)); Scheduler bean = context.getBean("scheduler", Scheduler.class); - assertFalse(bean.isStarted()); + assertThat(bean.isStarted()).isFalse(); context.refresh(); - assertTrue(bean.isStarted()); + assertThat(bean.isStarted()).isTrue(); } @Test @@ -387,15 +383,15 @@ public class QuartzSupportTests { .addPropertyValue("autoStartup", false).getBeanDefinition(); context.registerBeanDefinition("scheduler", beanDefinition); Scheduler bean = context.getBean("scheduler", Scheduler.class); - assertFalse(bean.isStarted()); + assertThat(bean.isStarted()).isFalse(); context.refresh(); - assertFalse(bean.isStarted()); + assertThat(bean.isStarted()).isFalse(); } @Test public void schedulerRepositoryExposure() throws Exception { ClassPathXmlApplicationContext ctx = context("schedulerRepositoryExposure.xml"); - assertSame(SchedulerRepository.getInstance().lookup("myScheduler"), ctx.getBean("scheduler")); + assertThat(ctx.getBean("scheduler")).isSameAs(SchedulerRepository.getInstance().lookup("myScheduler")); ctx.close(); } @@ -412,7 +408,7 @@ public class QuartzSupportTests { ClassPathXmlApplicationContext ctx = context("databasePersistence.xml"); JdbcTemplate jdbcTemplate = new JdbcTemplate(ctx.getBean(DataSource.class)); - assertFalse("No triggers were persisted", jdbcTemplate.queryForList("SELECT * FROM qrtz_triggers").isEmpty()); + assertThat(jdbcTemplate.queryForList("SELECT * FROM qrtz_triggers").isEmpty()).as("No triggers were persisted").isFalse(); /* Thread.sleep(3000); diff --git a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/SimpleTriggerFactoryBeanTests.java b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/SimpleTriggerFactoryBeanTests.java index 7eca39565ad..24c9a294092 100644 --- a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/SimpleTriggerFactoryBeanTests.java +++ b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/SimpleTriggerFactoryBeanTests.java @@ -21,7 +21,7 @@ import java.text.ParseException; import org.junit.Test; import org.quartz.SimpleTrigger; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -36,8 +36,8 @@ public class SimpleTriggerFactoryBeanTests { factory.setRepeatInterval(1000L); factory.afterPropertiesSet(); SimpleTrigger trigger = factory.getObject(); - assertEquals(5, trigger.getRepeatCount()); - assertEquals(1000L, trigger.getRepeatInterval()); + assertThat(trigger.getRepeatCount()).isEqualTo(5); + assertThat(trigger.getRepeatInterval()).isEqualTo(1000L); } } diff --git a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/BeanValidationPostProcessorTests.java b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/BeanValidationPostProcessorTests.java index f39d102a3c1..8179851f557 100644 --- a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/BeanValidationPostProcessorTests.java +++ b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/BeanValidationPostProcessorTests.java @@ -31,7 +31,6 @@ import org.springframework.validation.beanvalidation.BeanValidationPostProcessor import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertNotNull; /** * @author Juergen Hoeller @@ -127,7 +126,7 @@ public class BeanValidationPostProcessorTests { @PostConstruct public void init() { - assertNotNull("Shouldn't be here after constraint checking", this.testBean); + assertThat(this.testBean).as("Shouldn't be here after constraint checking").isNotNull(); } } diff --git a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/MethodValidationTests.java b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/MethodValidationTests.java index 5e7bd3dd5a7..74de89b17ff 100644 --- a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/MethodValidationTests.java +++ b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/MethodValidationTests.java @@ -42,9 +42,8 @@ import org.springframework.validation.beanvalidation.CustomValidatorBean; import org.springframework.validation.beanvalidation.MethodValidationInterceptor; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * @author Juergen Hoeller @@ -76,7 +75,7 @@ public class MethodValidationTests { } private void doTestProxyValidation(MyValidInterface proxy) { - assertNotNull(proxy.myValidMethod("value", 5)); + assertThat(proxy.myValidMethod("value", 5)).isNotNull(); assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myValidMethod("value", 15)); assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> @@ -88,7 +87,7 @@ public class MethodValidationTests { proxy.myValidAsyncMethod("value", 15)); assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myValidAsyncMethod(null, 5)); - assertEquals("myValue", proxy.myGenericMethod("myValue")); + assertThat(proxy.myGenericMethod("myValue")).isEqualTo("myValue"); assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myGenericMethod(null)); } diff --git a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/SpringValidatorAdapterTests.java b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/SpringValidatorAdapterTests.java index 15535dc1f78..76aeff39e95 100644 --- a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/SpringValidatorAdapterTests.java +++ b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/SpringValidatorAdapterTests.java @@ -58,10 +58,6 @@ import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; 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.junit.Assert.assertTrue; /** * @author Kazuki Shimizu @@ -88,7 +84,7 @@ public class SpringValidatorAdapterTests { @Test public void testUnwrap() { Validator nativeValidator = validatorAdapter.unwrap(Validator.class); - assertSame(this.nativeValidator, nativeValidator); + assertThat(nativeValidator).isSameAs(this.nativeValidator); } @Test // SPR-13406 @@ -103,9 +99,9 @@ public class SpringValidatorAdapterTests { assertThat(errors.getFieldErrorCount("password")).isEqualTo(1); assertThat(errors.getFieldValue("password")).isEqualTo("pass"); FieldError error = errors.getFieldError("password"); - assertNotNull(error); + assertThat(error).isNotNull(); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Size of Password is must be between 8 and 128"); - assertTrue(error.contains(ConstraintViolation.class)); + assertThat(error.contains(ConstraintViolation.class)).isTrue(); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password"); } @@ -121,9 +117,9 @@ public class SpringValidatorAdapterTests { assertThat(errors.getFieldErrorCount("password")).isEqualTo(1); assertThat(errors.getFieldValue("password")).isEqualTo("password"); FieldError error = errors.getFieldError("password"); - assertNotNull(error); + assertThat(error).isNotNull(); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Password must be same value as Password(Confirm)"); - assertTrue(error.contains(ConstraintViolation.class)); + assertThat(error.contains(ConstraintViolation.class)).isTrue(); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password"); } @@ -141,13 +137,13 @@ public class SpringValidatorAdapterTests { assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1); FieldError error1 = errors.getFieldError("email"); FieldError error2 = errors.getFieldError("confirmEmail"); - assertNotNull(error1); - assertNotNull(error2); + assertThat(error1).isNotNull(); + assertThat(error2).isNotNull(); assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail"); assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required"); - assertTrue(error1.contains(ConstraintViolation.class)); + assertThat(error1.contains(ConstraintViolation.class)).isTrue(); assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); - assertTrue(error2.contains(ConstraintViolation.class)); + assertThat(error2.contains(ConstraintViolation.class)).isTrue(); assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail"); } @@ -167,13 +163,13 @@ public class SpringValidatorAdapterTests { assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1); FieldError error1 = errors.getFieldError("email"); FieldError error2 = errors.getFieldError("confirmEmail"); - assertNotNull(error1); - assertNotNull(error2); + assertThat(error1).isNotNull(); + assertThat(error2).isNotNull(); assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail"); assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required"); - assertTrue(error1.contains(ConstraintViolation.class)); + assertThat(error1.contains(ConstraintViolation.class)).isTrue(); assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); - assertTrue(error2.contains(ConstraintViolation.class)); + assertThat(error2.contains(ConstraintViolation.class)).isTrue(); assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail"); } @@ -189,9 +185,9 @@ public class SpringValidatorAdapterTests { assertThat(errors.getFieldErrorCount("email")).isEqualTo(1); assertThat(errors.getFieldValue("email")).isEqualTo("X"); FieldError error = errors.getFieldError("email"); - assertNotNull(error); + assertThat(error).isNotNull(); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).contains("[\\w.'-]{1,}@[\\w.'-]{1,}"); - assertTrue(error.contains(ConstraintViolation.class)); + assertThat(error.contains(ConstraintViolation.class)).isTrue(); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); } @@ -204,7 +200,7 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(parent, "parent"); validatorAdapter.validate(parent, errors); - assertTrue(errors.getErrorCount() > 0); + assertThat(errors.getErrorCount() > 0).isTrue(); } @Test // SPR-16177 @@ -216,7 +212,7 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(parent, "parent"); validatorAdapter.validate(parent, errors); - assertTrue(errors.getErrorCount() > 0); + assertThat(errors.getErrorCount() > 0).isTrue(); } private List createChildren(Parent parent) { @@ -242,7 +238,7 @@ public class SpringValidatorAdapterTests { validatorAdapter.validate(bean, errors); assertThat(errors.getFieldErrorCount("property[4]")).isEqualTo(1); - assertNull(errors.getFieldValue("property[4]")); + assertThat(errors.getFieldValue("property[4]")).isNull(); } @Test // SPR-15839 @@ -257,7 +253,7 @@ public class SpringValidatorAdapterTests { validatorAdapter.validate(bean, errors); assertThat(errors.getFieldErrorCount("property[no value can be]")).isEqualTo(1); - assertNull(errors.getFieldValue("property[no value can be]")); + assertThat(errors.getFieldValue("property[no value can be]")).isNull(); } @Test // SPR-15839 @@ -271,8 +267,8 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(bean, "bean"); validatorAdapter.validate(bean, errors); - assertTrue(errors.hasFieldErrors("property[]")); - assertNull(errors.getFieldValue("property[]")); + assertThat(errors.hasFieldErrors("property[]")).isTrue(); + assertThat(errors.getFieldValue("property[]")).isNull(); } diff --git a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/ValidatorFactoryTests.java b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/ValidatorFactoryTests.java index 5142ba5df20..ee21a7a1438 100644 --- a/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/ValidatorFactoryTests.java +++ b/spring-context-support/src/test/java/org/springframework/validation/beanvalidation2/ValidatorFactoryTests.java @@ -53,10 +53,6 @@ import org.springframework.validation.ObjectError; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -72,7 +68,7 @@ public class ValidatorFactoryTests { ValidPerson person = new ValidPerson(); Set> result = validator.validate(person); - assertEquals(2, result.size()); + assertThat(result.size()).isEqualTo(2); for (ConstraintViolation cv : result) { String path = cv.getPropertyPath().toString(); assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual)); @@ -80,9 +76,9 @@ public class ValidatorFactoryTests { } Validator nativeValidator = validator.unwrap(Validator.class); - assertTrue(nativeValidator.getClass().getName().startsWith("org.hibernate")); - assertTrue(validator.unwrap(ValidatorFactory.class) instanceof HibernateValidatorFactory); - assertTrue(validator.unwrap(HibernateValidatorFactory.class) instanceof HibernateValidatorFactory); + assertThat(nativeValidator.getClass().getName().startsWith("org.hibernate")).isTrue(); + assertThat(validator.unwrap(ValidatorFactory.class) instanceof HibernateValidatorFactory).isTrue(); + assertThat(validator.unwrap(HibernateValidatorFactory.class) instanceof HibernateValidatorFactory).isTrue(); validator.destroy(); } @@ -96,7 +92,7 @@ public class ValidatorFactoryTests { ValidPerson person = new ValidPerson(); Set> result = validator.validate(person); - assertEquals(2, result.size()); + assertThat(result.size()).isEqualTo(2); for (ConstraintViolation cv : result) { String path = cv.getPropertyPath().toString(); assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual)); @@ -104,9 +100,9 @@ public class ValidatorFactoryTests { } Validator nativeValidator = validator.unwrap(Validator.class); - assertTrue(nativeValidator.getClass().getName().startsWith("org.hibernate")); - assertTrue(validator.unwrap(ValidatorFactory.class) instanceof HibernateValidatorFactory); - assertTrue(validator.unwrap(HibernateValidatorFactory.class) instanceof HibernateValidatorFactory); + assertThat(nativeValidator.getClass().getName().startsWith("org.hibernate")).isTrue(); + assertThat(validator.unwrap(ValidatorFactory.class) instanceof HibernateValidatorFactory).isTrue(); + assertThat(validator.unwrap(HibernateValidatorFactory.class) instanceof HibernateValidatorFactory).isTrue(); validator.destroy(); } @@ -120,11 +116,11 @@ public class ValidatorFactoryTests { person.setName("Juergen"); person.getAddress().setStreet("Juergen's Street"); Set> result = validator.validate(person); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); Iterator> iterator = result.iterator(); ConstraintViolation cv = iterator.next(); - assertEquals("", cv.getPropertyPath().toString()); - assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NameAddressValid); + assertThat(cv.getPropertyPath().toString()).isEqualTo(""); + assertThat(cv.getConstraintDescriptor().getAnnotation() instanceof NameAddressValid).isTrue(); } @Test @@ -137,7 +133,7 @@ public class ValidatorFactoryTests { person.getAddress().setStreet("Phil's Street"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person"); validator.validate(person, errors); - assertEquals(1, errors.getErrorCount()); + assertThat(errors.getErrorCount()).isEqualTo(1); assertThat(errors.getFieldError("address").getRejectedValue()).isInstanceOf(ValidAddress.class); } @@ -149,24 +145,24 @@ public class ValidatorFactoryTests { ValidPerson person = new ValidPerson(); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); - assertEquals(2, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(2); FieldError fieldError = result.getFieldError("name"); - assertEquals("name", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("name"); List errorCodes = Arrays.asList(fieldError.getCodes()); - assertEquals(4, errorCodes.size()); - assertTrue(errorCodes.contains("NotNull.person.name")); - assertTrue(errorCodes.contains("NotNull.name")); - assertTrue(errorCodes.contains("NotNull.java.lang.String")); - assertTrue(errorCodes.contains("NotNull")); + assertThat(errorCodes.size()).isEqualTo(4); + assertThat(errorCodes.contains("NotNull.person.name")).isTrue(); + assertThat(errorCodes.contains("NotNull.name")).isTrue(); + assertThat(errorCodes.contains("NotNull.java.lang.String")).isTrue(); + assertThat(errorCodes.contains("NotNull")).isTrue(); fieldError = result.getFieldError("address.street"); - assertEquals("address.street", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("address.street"); errorCodes = Arrays.asList(fieldError.getCodes()); - assertEquals(5, errorCodes.size()); - assertTrue(errorCodes.contains("NotNull.person.address.street")); - assertTrue(errorCodes.contains("NotNull.address.street")); - assertTrue(errorCodes.contains("NotNull.street")); - assertTrue(errorCodes.contains("NotNull.java.lang.String")); - assertTrue(errorCodes.contains("NotNull")); + assertThat(errorCodes.size()).isEqualTo(5); + assertThat(errorCodes.contains("NotNull.person.address.street")).isTrue(); + assertThat(errorCodes.contains("NotNull.address.street")).isTrue(); + assertThat(errorCodes.contains("NotNull.street")).isTrue(); + assertThat(errorCodes.contains("NotNull.java.lang.String")).isTrue(); + assertThat(errorCodes.contains("NotNull")).isTrue(); } @Test @@ -179,12 +175,12 @@ public class ValidatorFactoryTests { person.getAddress().setStreet("Juergen's Street"); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); - assertEquals(1, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(1); ObjectError globalError = result.getGlobalError(); List errorCodes = Arrays.asList(globalError.getCodes()); - assertEquals(2, errorCodes.size()); - assertTrue(errorCodes.contains("NameAddressValid.person")); - assertTrue(errorCodes.contains("NameAddressValid")); + assertThat(errorCodes.size()).isEqualTo(2); + assertThat(errorCodes.contains("NameAddressValid.person")).isTrue(); + assertThat(errorCodes.contains("NameAddressValid")).isTrue(); } @Test @@ -199,12 +195,12 @@ public class ValidatorFactoryTests { person.getAddress().setStreet("Juergen's Street"); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); - assertEquals(1, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(1); ObjectError globalError = result.getGlobalError(); List errorCodes = Arrays.asList(globalError.getCodes()); - assertEquals(2, errorCodes.size()); - assertTrue(errorCodes.contains("NameAddressValid.person")); - assertTrue(errorCodes.contains("NameAddressValid")); + assertThat(errorCodes.size()).isEqualTo(2); + assertThat(errorCodes.contains("NameAddressValid.person")).isTrue(); + assertThat(errorCodes.contains("NameAddressValid")).isTrue(); ctx.close(); } @@ -217,13 +213,13 @@ public class ValidatorFactoryTests { person.getAddressList().add(new ValidAddress()); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); - assertEquals(3, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(3); FieldError fieldError = result.getFieldError("name"); - assertEquals("name", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("name"); fieldError = result.getFieldError("address.street"); - assertEquals("address.street", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("address.street"); fieldError = result.getFieldError("addressList[0].street"); - assertEquals("addressList[0].street", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("addressList[0].street"); } @Test @@ -235,13 +231,13 @@ public class ValidatorFactoryTests { person.getAddressSet().add(new ValidAddress()); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); - assertEquals(3, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(3); FieldError fieldError = result.getFieldError("name"); - assertEquals("name", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("name"); fieldError = result.getFieldError("address.street"); - assertEquals("address.street", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("address.street"); fieldError = result.getFieldError("addressSet[].street"); - assertEquals("addressSet[].street", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("addressSet[].street"); } @Test @@ -253,7 +249,7 @@ public class ValidatorFactoryTests { Errors errors = new BeanPropertyBindingResult(mainBean, "mainBean"); validator.validate(mainBean, errors); Object rejected = errors.getFieldValue("inner.value"); - assertNull(rejected); + assertThat(rejected).isNull(); } @Test @@ -265,7 +261,7 @@ public class ValidatorFactoryTests { Errors errors = new BeanPropertyBindingResult(mainBean, "mainBean"); validator.validate(mainBean, errors); Object rejected = errors.getFieldValue("inner.value"); - assertNull(rejected); + assertThat(rejected).isNull(); } @Test @@ -282,9 +278,9 @@ public class ValidatorFactoryTests { validator.validate(listContainer, errors); FieldError fieldError = errors.getFieldError("list[1]"); - assertNotNull(fieldError); - assertEquals("X", fieldError.getRejectedValue()); - assertEquals("X", errors.getFieldValue("list[1]")); + assertThat(fieldError).isNotNull(); + assertThat(fieldError.getRejectedValue()).isEqualTo("X"); + assertThat(errors.getFieldValue("list[1]")).isEqualTo("X"); } @@ -379,7 +375,7 @@ public class ValidatorFactoryTests { @Override public boolean isValid(ValidPerson value, ConstraintValidatorContext context) { if (value.expectsAutowiredValidator) { - assertNotNull(this.environment); + assertThat(this.environment).isNotNull(); } boolean valid = (value.name == null || !value.address.street.contains(value.name)); if (!valid && "Phil".equals(value.name)) { diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java index 4cb48075557..eff6372dc26 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java @@ -26,7 +26,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -53,7 +53,7 @@ public class AfterAdviceBindingTests { AdviceBindingTestAspect afterAdviceAspect = (AdviceBindingTestAspect) ctx.getBean("testAspect"); testBeanProxy = (ITestBean) ctx.getBean("testBean"); - assertTrue(AopUtils.isAopProxy(testBeanProxy)); + assertThat(AopUtils.isAopProxy(testBeanProxy)).isTrue(); // we need the real target too, not just the proxy... testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget(); diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java index fc02498d7e9..475c35cd560 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java @@ -26,7 +26,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -61,7 +61,7 @@ public class AfterReturningAdviceBindingTests { afterAdviceAspect.setCollaborator(mockCollaborator); testBeanProxy = (ITestBean) ctx.getBean("testBean"); - assertTrue(AopUtils.isAopProxy(testBeanProxy)); + assertThat(AopUtils.isAopProxy(testBeanProxy)).isTrue(); // we need the real target too, not just the proxy... this.testBeanTarget = (TestBean) ((Advised)testBeanProxy).getTargetSource().getTarget(); diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java index 861cc727abc..43dff6f85b5 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java @@ -28,7 +28,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -55,7 +55,7 @@ public class AroundAdviceBindingTests { AroundAdviceBindingTestAspect aroundAdviceAspect = ((AroundAdviceBindingTestAspect) ctx.getBean("testAspect")); ITestBean injectedTestBean = (ITestBean) ctx.getBean("testBean"); - assertTrue(AopUtils.isAopProxy(injectedTestBean)); + assertThat(AopUtils.isAopProxy(injectedTestBean)).isTrue(); this.testBeanProxy = injectedTestBean; // we need the real target too, not just the proxy... diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceCircularTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceCircularTests.java index f5cc0d8a1b5..e4cc4d9c7b1 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceCircularTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceCircularTests.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.springframework.aop.support.AopUtils; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -31,9 +31,9 @@ public class AroundAdviceCircularTests extends AroundAdviceBindingTests { @Test public void testBothBeansAreProxies() { Object tb = ctx.getBean("testBean"); - assertTrue(AopUtils.isAopProxy(tb)); + assertThat(AopUtils.isAopProxy(tb)).isTrue(); Object tb2 = ctx.getBean("testBean2"); - assertTrue(AopUtils.isAopProxy(tb2)); + assertThat(AopUtils.isAopProxy(tb2)).isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.java index 6bbaa359e8c..8cd955b4ee9 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -49,11 +49,11 @@ public class AspectJExpressionPointcutAdvisorTests { @Test public void testPointcutting() { - assertEquals("Count should be 0", 0, interceptor.getCount()); + assertThat(interceptor.getCount()).as("Count should be 0").isEqualTo(0); testBean.getSpouses(); - assertEquals("Count should be 1", 1, interceptor.getCount()); + assertThat(interceptor.getCount()).as("Count should be 1").isEqualTo(1); testBean.getSpouse(); - assertEquals("Count should be 1", 1, interceptor.getCount()); + assertThat(interceptor.getCount()).as("Count should be 1").isEqualTo(1); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.java index 94faae5b5d4..9bc152b1d63 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.java @@ -26,9 +26,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test for correct application of the bean() PCD for @AspectJ-based aspects. @@ -59,20 +57,22 @@ public class BeanNamePointcutAtAspectTests { @Test public void testMatchingBeanName() { - assertTrue("Expected a proxy", testBean1 instanceof Advised); + boolean condition = testBean1 instanceof Advised; + assertThat(condition).as("Expected a proxy").isTrue(); // Call two methods to test for SPR-3953-like condition testBean1.setAge(20); testBean1.setName(""); - assertEquals(2, counterAspect.count); + assertThat(counterAspect.count).isEqualTo(2); } @Test public void testNonMatchingBeanName() { - assertFalse("Didn't expect a proxy", testBean3 instanceof Advised); + boolean condition = testBean3 instanceof Advised; + assertThat(condition).as("Didn't expect a proxy").isFalse(); testBean3.setAge(20); - assertEquals(0, counterAspect.count); + assertThat(counterAspect.count).isEqualTo(0); } @Test @@ -87,9 +87,10 @@ public class BeanNamePointcutAtAspectTests { ITestBean proxyTestBean = factory.getProxy(); - assertTrue("Expected a proxy", proxyTestBean instanceof Advised); + boolean condition = proxyTestBean instanceof Advised; + assertThat(condition).as("Expected a proxy").isTrue(); proxyTestBean.setAge(20); - assertEquals("Programmatically created proxy shouldn't match bean()", 0, myCounterAspect.count); + assertThat(myCounterAspect.count).as("Programmatically created proxy shouldn't match bean()").isEqualTo(0); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.java index 4d11e6f69d4..b9a67a72b1a 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.java @@ -29,9 +29,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.lang.Nullable; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test for correct application of the bean() PCD for XML-based AspectJ aspects. @@ -77,53 +75,62 @@ public class BeanNamePointcutTests { @Test public void testMatchingBeanName() { - assertTrue("Matching bean must be advised (proxied)", this.testBean1 instanceof Advised); + boolean condition = this.testBean1 instanceof Advised; + assertThat(condition).as("Matching bean must be advised (proxied)").isTrue(); // Call two methods to test for SPR-3953-like condition this.testBean1.setAge(20); this.testBean1.setName(""); - assertEquals("Advice not executed: must have been", 2, this.counterAspect.getCount()); + assertThat(this.counterAspect.getCount()).as("Advice not executed: must have been").isEqualTo(2); } @Test public void testNonMatchingBeanName() { - assertFalse("Non-matching bean must *not* be advised (proxied)", this.testBean2 instanceof Advised); + boolean condition = this.testBean2 instanceof Advised; + assertThat(condition).as("Non-matching bean must *not* be advised (proxied)").isFalse(); this.testBean2.setAge(20); - assertEquals("Advice must *not* have been executed", 0, this.counterAspect.getCount()); + assertThat(this.counterAspect.getCount()).as("Advice must *not* have been executed").isEqualTo(0); } @Test public void testNonMatchingNestedBeanName() { - assertFalse("Non-matching bean must *not* be advised (proxied)", this.testBeanContainingNestedBean.getDoctor() instanceof Advised); + boolean condition = this.testBeanContainingNestedBean.getDoctor() instanceof Advised; + assertThat(condition).as("Non-matching bean must *not* be advised (proxied)").isFalse(); } @Test public void testMatchingFactoryBeanObject() { - assertTrue("Matching bean must be advised (proxied)", this.testFactoryBean1 instanceof Advised); - assertEquals("myValue", this.testFactoryBean1.get("myKey")); - assertEquals("myValue", this.testFactoryBean1.get("myKey")); - assertEquals("Advice not executed: must have been", 2, this.counterAspect.getCount()); + boolean condition1 = this.testFactoryBean1 instanceof Advised; + assertThat(condition1).as("Matching bean must be advised (proxied)").isTrue(); + assertThat(this.testFactoryBean1.get("myKey")).isEqualTo("myValue"); + assertThat(this.testFactoryBean1.get("myKey")).isEqualTo("myValue"); + assertThat(this.counterAspect.getCount()).as("Advice not executed: must have been").isEqualTo(2); FactoryBean fb = (FactoryBean) ctx.getBean("&testFactoryBean1"); - assertTrue("FactoryBean itself must *not* be advised", !(fb instanceof Advised)); + boolean condition = !(fb instanceof Advised); + assertThat(condition).as("FactoryBean itself must *not* be advised").isTrue(); } @Test public void testMatchingFactoryBeanItself() { - assertTrue("Matching bean must *not* be advised (proxied)", !(this.testFactoryBean2 instanceof Advised)); + boolean condition1 = !(this.testFactoryBean2 instanceof Advised); + assertThat(condition1).as("Matching bean must *not* be advised (proxied)").isTrue(); FactoryBean fb = (FactoryBean) ctx.getBean("&testFactoryBean2"); - assertTrue("FactoryBean itself must be advised", fb instanceof Advised); - assertTrue(Map.class.isAssignableFrom(fb.getObjectType())); - assertTrue(Map.class.isAssignableFrom(fb.getObjectType())); - assertEquals("Advice not executed: must have been", 2, this.counterAspect.getCount()); + boolean condition = fb instanceof Advised; + assertThat(condition).as("FactoryBean itself must be advised").isTrue(); + assertThat(Map.class.isAssignableFrom(fb.getObjectType())).isTrue(); + assertThat(Map.class.isAssignableFrom(fb.getObjectType())).isTrue(); + assertThat(this.counterAspect.getCount()).as("Advice not executed: must have been").isEqualTo(2); } @Test public void testPointcutAdvisorCombination() { - assertTrue("Matching bean must be advised (proxied)", this.interceptThis instanceof Advised); - assertFalse("Non-matching bean must *not* be advised (proxied)", this.dontInterceptThis instanceof Advised); + boolean condition = this.interceptThis instanceof Advised; + assertThat(condition).as("Matching bean must be advised (proxied)").isTrue(); + boolean condition1 = this.dontInterceptThis instanceof Advised; + assertThat(condition1).as("Non-matching bean must *not* be advised (proxied)").isFalse(); interceptThis.setAge(20); - assertEquals(1, testInterceptor.interceptionCount); + assertThat(testInterceptor.interceptionCount).isEqualTo(1); dontInterceptThis.setAge(20); - assertEquals(1, testInterceptor.interceptionCount); + assertThat(testInterceptor.interceptionCount).isEqualTo(1); } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java index ed747fed864..ed6bb422b16 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java @@ -26,7 +26,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -52,7 +52,7 @@ public class BeforeAdviceBindingTests { new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass()); testBeanProxy = (ITestBean) ctx.getBean("testBean"); - assertTrue(AopUtils.isAopProxy(testBeanProxy)); + assertThat(AopUtils.isAopProxy(testBeanProxy)).isTrue(); // we need the real target too, not just the proxy... testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget(); diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclarationOrderIndependenceTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclarationOrderIndependenceTests.java index 07bcc1ab5e6..59dbb3c6132 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclarationOrderIndependenceTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclarationOrderIndependenceTests.java @@ -25,7 +25,7 @@ import org.junit.Test; import org.springframework.beans.factory.BeanNameAware; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Adrian Colyer @@ -49,12 +49,14 @@ public class DeclarationOrderIndependenceTests { @Test public void testTargetIsSerializable() { - assertTrue("target bean is serializable",this.target instanceof Serializable); + boolean condition = this.target instanceof Serializable; + assertThat(condition).as("target bean is serializable").isTrue(); } @Test public void testTargetIsBeanNameAware() { - assertTrue("target bean is bean name aware",this.target instanceof BeanNameAware); + boolean condition = this.target instanceof BeanNameAware; + assertThat(condition).as("target bean is bean name aware").isTrue(); } @Test @@ -62,7 +64,7 @@ public class DeclarationOrderIndependenceTests { AspectCollaborator collab = new AspectCollaborator(); this.aspect.setCollaborator(collab); this.target.doSomething(); - assertTrue("before advice fired",collab.beforeFired); + assertThat(collab.beforeFired).as("before advice fired").isTrue(); } @Test @@ -70,7 +72,7 @@ public class DeclarationOrderIndependenceTests { AspectCollaborator collab = new AspectCollaborator(); this.aspect.setCollaborator(collab); this.target.getX(); - assertTrue("around advice fired",collab.aroundFired); + assertThat(collab.aroundFired).as("around advice fired").isTrue(); } @Test @@ -78,7 +80,7 @@ public class DeclarationOrderIndependenceTests { AspectCollaborator collab = new AspectCollaborator(); this.aspect.setCollaborator(collab); this.target.getX(); - assertTrue("after returning advice fired",collab.afterReturningFired); + assertThat(collab.afterReturningFired).as("after returning advice fired").isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsDelegateRefTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsDelegateRefTests.java index 2ae23276141..85ef11406f1 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsDelegateRefTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsDelegateRefTests.java @@ -21,8 +21,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ramnivas Laddad @@ -47,13 +46,14 @@ public class DeclareParentsDelegateRefTests { @Test public void testIntroductionWasMade() { - assertTrue("Introduction must have been made", noMethodsBean instanceof ICounter); + boolean condition = noMethodsBean instanceof ICounter; + assertThat(condition).as("Introduction must have been made").isTrue(); } @Test public void testIntroductionDelegation() { ((ICounter)noMethodsBean).increment(); - assertEquals("Delegate's counter should be updated", 1, counter.getCount()); + assertThat(counter.getCount()).as("Delegate's counter should be updated").isEqualTo(1); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java index 015a2a87c21..35f5007742b 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java @@ -24,9 +24,8 @@ import org.springframework.aop.support.AopUtils; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -50,9 +49,10 @@ public class DeclareParentsTests { @Test public void testIntroductionWasMade() { - assertTrue(AopUtils.isAopProxy(testBeanProxy)); - assertFalse("Introduction should not be proxied", AopUtils.isAopProxy(introductionObject)); - assertTrue("Introduction must have been made", testBeanProxy instanceof Lockable); + assertThat(AopUtils.isAopProxy(testBeanProxy)).isTrue(); + assertThat(AopUtils.isAopProxy(introductionObject)).as("Introduction should not be proxied").isFalse(); + boolean condition = testBeanProxy instanceof Lockable; + assertThat(condition).as("Introduction must have been made").isTrue(); } // TODO if you change type pattern from org.springframework.beans..* @@ -62,7 +62,7 @@ public class DeclareParentsTests { @Test public void testLockingWorks() { Lockable lockable = (Lockable) testBeanProxy; - assertFalse(lockable.locked()); + assertThat(lockable.locked()).isFalse(); // Invoke a non-advised method testBeanProxy.getAge(); diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests.java index d2f12424264..a59e5388765 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for overloaded advice. @@ -38,9 +38,9 @@ public class OverloadedAdviceTests { } catch (BeanCreationException ex) { Throwable cause = ex.getRootCause(); - assertTrue("Should be IllegalArgumentException", cause instanceof IllegalArgumentException); - assertTrue("invalidAbsoluteTypeName should be detected by AJ", - cause.getMessage().contains("invalidAbsoluteTypeName")); + boolean condition = cause instanceof IllegalArgumentException; + assertThat(condition).as("Should be IllegalArgumentException").isTrue(); + assertThat(cause.getMessage().contains("invalidAbsoluteTypeName")).as("invalidAbsoluteTypeName should be detected by AJ").isTrue(); } } @@ -51,9 +51,9 @@ public class OverloadedAdviceTests { } catch (BeanCreationException ex) { Throwable cause = ex.getRootCause(); - assertTrue("Should be IllegalArgumentException", cause instanceof IllegalArgumentException); - assertTrue("Cannot resolve method 'myBeforeAdvice' to a unique method", - cause.getMessage().contains("Cannot resolve method 'myBeforeAdvice' to a unique method")); + boolean condition = cause instanceof IllegalArgumentException; + assertThat(condition).as("Should be IllegalArgumentException").isTrue(); + assertThat(cause.getMessage().contains("Cannot resolve method 'myBeforeAdvice' to a unique method")).as("Cannot resolve method 'myBeforeAdvice' to a unique method").isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/ProceedTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/ProceedTests.java index bb26b567a90..db568cb0eb5 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/ProceedTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/ProceedTests.java @@ -24,8 +24,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.Ordered; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test for SPR-3522. Arguments changed on a call to proceed should be @@ -56,28 +55,28 @@ public class ProceedTests { @Test public void testSimpleProceedWithChangedArgs() { this.testBean.setName("abc"); - assertEquals("Name changed in around advice", "ABC", this.testBean.getName()); + assertThat(this.testBean.getName()).as("Name changed in around advice").isEqualTo("ABC"); } @Test public void testGetArgsIsDefensive() { this.testBean.setAge(5); - assertEquals("getArgs is defensive", 5, this.testBean.getAge()); + assertThat(this.testBean.getAge()).as("getArgs is defensive").isEqualTo(5); } @Test public void testProceedWithArgsInSameAspect() { this.testBean.setMyFloat(1.0F); - assertTrue("value changed in around advice", this.testBean.getMyFloat() > 1.9F); - assertTrue("changed value visible to next advice in chain", this.firstTestAspect.getLastBeforeFloatValue() > 1.9F); + assertThat(this.testBean.getMyFloat() > 1.9F).as("value changed in around advice").isTrue(); + assertThat(this.firstTestAspect.getLastBeforeFloatValue() > 1.9F).as("changed value visible to next advice in chain").isTrue(); } @Test public void testProceedWithArgsAcrossAspects() { this.testBean.setSex("male"); - assertEquals("value changed in around advice","MALE", this.testBean.getSex()); - assertEquals("changed value visible to next before advice in chain","MALE", this.secondTestAspect.getLastBeforeStringValue()); - assertEquals("changed value visible to next around advice in chain","MALE", this.secondTestAspect.getLastAroundStringValue()); + assertThat(this.testBean.getSex()).as("value changed in around advice").isEqualTo("MALE"); + assertThat(this.secondTestAspect.getLastBeforeStringValue()).as("changed value visible to next before advice in chain").isEqualTo("MALE"); + assertThat(this.secondTestAspect.getLastAroundStringValue()).as("changed value visible to next around advice in chain").isEqualTo("MALE"); } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/PropertyDependentAspectTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/PropertyDependentAspectTests.java index b114d67f851..5e7b639aaab 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/PropertyDependentAspectTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/PropertyDependentAspectTests.java @@ -26,8 +26,7 @@ import org.springframework.aop.framework.Advised; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Check that an aspect that depends on another bean, where the referenced bean @@ -66,23 +65,25 @@ public class PropertyDependentAspectTests { private void checkXmlAspect(String appContextFile) { ApplicationContext context = new ClassPathXmlApplicationContext(appContextFile, getClass()); ICounter counter = (ICounter) context.getBean("counter"); - assertTrue("Proxy didn't get created", counter instanceof Advised); + boolean condition = counter instanceof Advised; + assertThat(condition).as("Proxy didn't get created").isTrue(); counter.increment(); JoinPointMonitorAspect callCountingAspect = (JoinPointMonitorAspect)context.getBean("monitoringAspect"); - assertEquals("Advise didn't get executed", 1, callCountingAspect.beforeExecutions); - assertEquals("Advise didn't get executed", 1, callCountingAspect.aroundExecutions); + assertThat(callCountingAspect.beforeExecutions).as("Advise didn't get executed").isEqualTo(1); + assertThat(callCountingAspect.aroundExecutions).as("Advise didn't get executed").isEqualTo(1); } private void checkAtAspectJAspect(String appContextFile) { ApplicationContext context = new ClassPathXmlApplicationContext(appContextFile, getClass()); ICounter counter = (ICounter) context.getBean("counter"); - assertTrue("Proxy didn't get created", counter instanceof Advised); + boolean condition = counter instanceof Advised; + assertThat(condition).as("Proxy didn't get created").isTrue(); counter.increment(); JoinPointMonitorAtAspectJAspect callCountingAspect = (JoinPointMonitorAtAspectJAspect)context.getBean("monitoringAspect"); - assertEquals("Advise didn't get executed", 1, callCountingAspect.beforeExecutions); - assertEquals("Advise didn't get executed", 1, callCountingAspect.aroundExecutions); + assertThat(callCountingAspect.beforeExecutions).as("Advise didn't get executed").isEqualTo(1); + assertThat(callCountingAspect.aroundExecutions).as("Advise didn't get executed").isEqualTo(1); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/SubtypeSensitiveMatchingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/SubtypeSensitiveMatchingTests.java index 4b465b520c6..2adeb2db6f6 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/SubtypeSensitiveMatchingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/SubtypeSensitiveMatchingTests.java @@ -24,8 +24,7 @@ import org.junit.Test; import org.springframework.aop.framework.Advised; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Adrian Colyer @@ -52,20 +51,20 @@ public class SubtypeSensitiveMatchingTests { @Test public void testBeansAreProxiedOnStaticMatch() { - assertTrue("bean with serializable type should be proxied", - this.serializableBean instanceof Advised); + boolean condition = this.serializableBean instanceof Advised; + assertThat(condition).as("bean with serializable type should be proxied").isTrue(); } @Test public void testBeansThatDoNotMatchBasedSolelyOnRuntimeTypeAreNotProxied() { - assertFalse("bean with non-serializable type should not be proxied", - this.nonSerializableBean instanceof Advised); + boolean condition = this.nonSerializableBean instanceof Advised; + assertThat(condition).as("bean with non-serializable type should not be proxied").isFalse(); } @Test public void testBeansThatDoNotMatchBasedOnOtherTestAreProxied() { - assertTrue("bean with args check should be proxied", - this.bar instanceof Advised); + boolean condition = this.bar instanceof Advised; + assertThat(condition).as("bean with args check should be proxied").isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/TargetPointcutSelectionTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/TargetPointcutSelectionTests.java index 4ba38cce20d..059fa694cc0 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/TargetPointcutSelectionTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/TargetPointcutSelectionTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for target selection matching (see SPR-3783). @@ -64,17 +64,17 @@ public class TargetPointcutSelectionTests { @Test public void targetSelectionForMatchedType() { testImpl1.interfaceMethod(); - assertEquals("Should have been advised by POJO advice for impl", 1, testAspectForTestImpl1.count); - assertEquals("Should have been advised by POJO advice for base type", 1, testAspectForAbstractTestImpl.count); - assertEquals("Should have been advised by advisor", 1, testInterceptor.count); + assertThat(testAspectForTestImpl1.count).as("Should have been advised by POJO advice for impl").isEqualTo(1); + assertThat(testAspectForAbstractTestImpl.count).as("Should have been advised by POJO advice for base type").isEqualTo(1); + assertThat(testInterceptor.count).as("Should have been advised by advisor").isEqualTo(1); } @Test public void targetNonSelectionForMismatchedType() { testImpl2.interfaceMethod(); - assertEquals("Shouldn't have been advised by POJO advice for impl", 0, testAspectForTestImpl1.count); - assertEquals("Should have been advised by POJO advice for base type", 1, testAspectForAbstractTestImpl.count); - assertEquals("Shouldn't have been advised by advisor", 0, testInterceptor.count); + assertThat(testAspectForTestImpl1.count).as("Shouldn't have been advised by POJO advice for impl").isEqualTo(0); + assertThat(testAspectForAbstractTestImpl.count).as("Should have been advised by POJO advice for base type").isEqualTo(1); + assertThat(testInterceptor.count).as("Shouldn't have been advised by advisor").isEqualTo(0); } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.java index 4e7c4cb478a..00f0e0a7424 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.java @@ -25,7 +25,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ramnivas Laddad @@ -57,56 +57,56 @@ public class ThisAndTargetSelectionOnlyPointcutsAtAspectJTests { @Test public void thisAsClassDoesNotMatch() { testBean.doIt(); - assertEquals(0, counter.thisAsClassCounter); + assertThat(counter.thisAsClassCounter).isEqualTo(0); } @Test public void thisAsInterfaceMatch() { testBean.doIt(); - assertEquals(1, counter.thisAsInterfaceCounter); + assertThat(counter.thisAsInterfaceCounter).isEqualTo(1); } @Test public void targetAsClassDoesMatch() { testBean.doIt(); - assertEquals(1, counter.targetAsClassCounter); + assertThat(counter.targetAsClassCounter).isEqualTo(1); } @Test public void targetAsInterfaceMatch() { testBean.doIt(); - assertEquals(1, counter.targetAsInterfaceCounter); + assertThat(counter.targetAsInterfaceCounter).isEqualTo(1); } @Test public void thisAsClassAndTargetAsClassCounterNotMatch() { testBean.doIt(); - assertEquals(0, counter.thisAsClassAndTargetAsClassCounter); + assertThat(counter.thisAsClassAndTargetAsClassCounter).isEqualTo(0); } @Test public void thisAsInterfaceAndTargetAsInterfaceCounterMatch() { testBean.doIt(); - assertEquals(1, counter.thisAsInterfaceAndTargetAsInterfaceCounter); + assertThat(counter.thisAsInterfaceAndTargetAsInterfaceCounter).isEqualTo(1); } @Test public void thisAsInterfaceAndTargetAsClassCounterMatch() { testBean.doIt(); - assertEquals(1, counter.thisAsInterfaceAndTargetAsInterfaceCounter); + assertThat(counter.thisAsInterfaceAndTargetAsInterfaceCounter).isEqualTo(1); } @Test public void atTargetClassAnnotationMatch() { testAnnotatedClassBean.doIt(); - assertEquals(1, counter.atTargetClassAnnotationCounter); + assertThat(counter.atTargetClassAnnotationCounter).isEqualTo(1); } @Test public void atAnnotationMethodAnnotationMatch() { testAnnotatedMethodBean.doIt(); - assertEquals(1, counter.atAnnotationMethodAnnotationCounter); + assertThat(counter.atAnnotationMethodAnnotationCounter).isEqualTo(1); } public static interface TestInterface { diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsTests.java index 4d692cff9fb..bfb4484b127 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ramnivas Laddad @@ -66,43 +66,43 @@ public class ThisAndTargetSelectionOnlyPointcutsTests { @Test public void testThisAsClassDoesNotMatch() { testBean.doIt(); - assertEquals(0, thisAsClassCounter.getCount()); + assertThat(thisAsClassCounter.getCount()).isEqualTo(0); } @Test public void testThisAsInterfaceMatch() { testBean.doIt(); - assertEquals(1, thisAsInterfaceCounter.getCount()); + assertThat(thisAsInterfaceCounter.getCount()).isEqualTo(1); } @Test public void testTargetAsClassDoesMatch() { testBean.doIt(); - assertEquals(1, targetAsClassCounter.getCount()); + assertThat(targetAsClassCounter.getCount()).isEqualTo(1); } @Test public void testTargetAsInterfaceMatch() { testBean.doIt(); - assertEquals(1, targetAsInterfaceCounter.getCount()); + assertThat(targetAsInterfaceCounter.getCount()).isEqualTo(1); } @Test public void testThisAsClassAndTargetAsClassCounterNotMatch() { testBean.doIt(); - assertEquals(0, thisAsClassAndTargetAsClassCounter.getCount()); + assertThat(thisAsClassAndTargetAsClassCounter.getCount()).isEqualTo(0); } @Test public void testThisAsInterfaceAndTargetAsInterfaceCounterMatch() { testBean.doIt(); - assertEquals(1, thisAsInterfaceAndTargetAsInterfaceCounter.getCount()); + assertThat(thisAsInterfaceAndTargetAsInterfaceCounter.getCount()).isEqualTo(1); } @Test public void testThisAsInterfaceAndTargetAsClassCounterMatch() { testBean.doIt(); - assertEquals(1, thisAsInterfaceAndTargetAsInterfaceCounter.getCount()); + assertThat(thisAsInterfaceAndTargetAsInterfaceCounter.getCount()).isEqualTo(1); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AnnotationBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AnnotationBindingTests.java index b2cbc9af0b4..d2df89bea3d 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AnnotationBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AnnotationBindingTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Adrian Colyer @@ -42,13 +42,13 @@ public class AnnotationBindingTests { @Test public void testAnnotationBindingInAroundAdvice() { - assertEquals("this value", testBean.doThis()); - assertEquals("that value", testBean.doThat()); + assertThat(testBean.doThis()).isEqualTo("this value"); + assertThat(testBean.doThat()).isEqualTo("that value"); } @Test public void testNoMatchingWithoutAnnotationPresent() { - assertEquals("doTheOther", testBean.doTheOther()); + assertThat(testBean.doTheOther()).isEqualTo("doTheOther"); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AnnotationPointcutTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AnnotationPointcutTests.java index 6ff7be4a44d..914372c204a 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AnnotationPointcutTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AnnotationPointcutTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -45,12 +45,12 @@ public class AnnotationPointcutTests { @Test public void testAnnotationBindingInAroundAdvice() { - assertEquals("this value", testBean.doThis()); + assertThat(testBean.doThis()).isEqualTo("this value"); } @Test public void testNoMatchingWithoutAnnotationPresent() { - assertEquals("doTheOther", testBean.doTheOther()); + assertThat(testBean.doTheOther()).isEqualTo("doTheOther"); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests.java index 72e50bc2e2f..0a4764e6b7f 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests.java @@ -23,8 +23,7 @@ import org.springframework.aop.framework.Advised; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test for ensuring the aspects aren't advised. See SPR-3893 for more details. @@ -42,8 +41,10 @@ public class AspectImplementingInterfaceTests { ITestBean testBean = (ITestBean) ctx.getBean("testBean"); AnInterface interfaceExtendingAspect = (AnInterface) ctx.getBean("interfaceExtendingAspect"); - assertTrue(testBean instanceof Advised); - assertFalse(interfaceExtendingAspect instanceof Advised); + boolean condition = testBean instanceof Advised; + assertThat(condition).isTrue(); + boolean condition1 = interfaceExtendingAspect instanceof Advised; + assertThat(condition1).isFalse(); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorAndLazyInitTargetSourceTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorAndLazyInitTargetSourceTests.java index 6bfece657da..7a2dd74964d 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorAndLazyInitTargetSourceTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorAndLazyInitTargetSourceTests.java @@ -22,8 +22,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -38,11 +37,11 @@ public class AspectJAutoProxyCreatorAndLazyInitTargetSourceTests { new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass()); ITestBean adrian = (ITestBean) ctx.getBean("adrian"); - assertEquals(0, LazyTestBean.instantiations); - assertNotNull(adrian); + assertThat(LazyTestBean.instantiations).isEqualTo(0); + assertThat(adrian).isNotNull(); adrian.getAge(); - assertEquals(68, adrian.getAge()); - assertEquals(1, LazyTestBean.instantiations); + assertThat(adrian.getAge()).isEqualTo(68); + assertThat(LazyTestBean.instantiations).isEqualTo(1); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java index 8d68b2c71e1..d4c20360eea 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java @@ -59,10 +59,7 @@ import org.springframework.tests.sample.beans.NestedTestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.StopWatch; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for AspectJ auto-proxying. Includes mixing with Spring AOP Advisors @@ -83,10 +80,10 @@ public class AspectJAutoProxyCreatorTests { ClassPathXmlApplicationContext bf = newContext("aspects.xml"); ITestBean tb = (ITestBean) bf.getBean("adrian"); - assertEquals(68, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(68); MethodInvokingFactoryBean factoryBean = (MethodInvokingFactoryBean) bf.getBean("&factoryBean"); - assertTrue(AopUtils.isAopProxy(factoryBean.getTargetObject())); - assertEquals(68, ((ITestBean) factoryBean.getTargetObject()).getAge()); + assertThat(AopUtils.isAopProxy(factoryBean.getTargetObject())).isTrue(); + assertThat(((ITestBean) factoryBean.getTargetObject()).getAge()).isEqualTo(68); } @Test @@ -95,7 +92,7 @@ public class AspectJAutoProxyCreatorTests { ITestBean tb = (ITestBean) bf.getBean("adrian"); tb.setAge(10); - assertEquals(20, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(20); } @Test @@ -103,7 +100,7 @@ public class AspectJAutoProxyCreatorTests { ClassPathXmlApplicationContext bf = newContext("aspectsWithOrdering.xml"); ITestBean tb = (ITestBean) bf.getBean("adrian"); - assertEquals(71, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(71); } @Test @@ -148,7 +145,7 @@ public class AspectJAutoProxyCreatorTests { for (int i = 0; i < 100000; i++) { INestedTestBean shouldNotBeWeaved = (INestedTestBean) ac.getBean("i21"); if (i < 10) { - assertFalse(AopUtils.isAopProxy(shouldNotBeWeaved)); + assertThat(AopUtils.isAopProxy(shouldNotBeWeaved)).isFalse(); } } sw.stop(); @@ -204,17 +201,17 @@ public class AspectJAutoProxyCreatorTests { TestBeanAdvisor tba = (TestBeanAdvisor) ac.getBean("advisor"); MultiplyReturnValue mrv = (MultiplyReturnValue) ac.getBean("aspect"); - assertEquals(3, mrv.getMultiple()); + assertThat(mrv.getMultiple()).isEqualTo(3); tba.count = 0; mrv.invocations = 0; - assertTrue("Autoproxying must apply from @AspectJ aspect", AopUtils.isAopProxy(shouldBeWeaved)); - assertEquals("Adrian", shouldBeWeaved.getName()); - assertEquals(0, mrv.invocations); - assertEquals(34 * mrv.getMultiple(), shouldBeWeaved.getAge()); - assertEquals("Spring advisor must be invoked", 2, tba.count); - assertEquals("Must be able to hold state in aspect", 1, mrv.invocations); + assertThat(AopUtils.isAopProxy(shouldBeWeaved)).as("Autoproxying must apply from @AspectJ aspect").isTrue(); + assertThat(shouldBeWeaved.getName()).isEqualTo("Adrian"); + assertThat(mrv.invocations).isEqualTo(0); + assertThat(shouldBeWeaved.getAge()).isEqualTo((34 * mrv.getMultiple())); + assertThat(tba.count).as("Spring advisor must be invoked").isEqualTo(2); + assertThat(mrv.invocations).as("Must be able to hold state in aspect").isEqualTo(1); } @Test @@ -222,19 +219,19 @@ public class AspectJAutoProxyCreatorTests { ClassPathXmlApplicationContext bf = newContext("perthis.xml"); ITestBean adrian1 = (ITestBean) bf.getBean("adrian"); - assertTrue(AopUtils.isAopProxy(adrian1)); + assertThat(AopUtils.isAopProxy(adrian1)).isTrue(); - assertEquals(0, adrian1.getAge()); - assertEquals(1, adrian1.getAge()); + assertThat(adrian1.getAge()).isEqualTo(0); + assertThat(adrian1.getAge()).isEqualTo(1); ITestBean adrian2 = (ITestBean) bf.getBean("adrian"); - assertNotSame(adrian1, adrian2); - assertTrue(AopUtils.isAopProxy(adrian1)); - assertEquals(0, adrian2.getAge()); - assertEquals(1, adrian2.getAge()); - assertEquals(2, adrian2.getAge()); - assertEquals(3, adrian2.getAge()); - assertEquals(2, adrian1.getAge()); + assertThat(adrian2).isNotSameAs(adrian1); + assertThat(AopUtils.isAopProxy(adrian1)).isTrue(); + assertThat(adrian2.getAge()).isEqualTo(0); + assertThat(adrian2.getAge()).isEqualTo(1); + assertThat(adrian2.getAge()).isEqualTo(2); + assertThat(adrian2.getAge()).isEqualTo(3); + assertThat(adrian1.getAge()).isEqualTo(2); } @Test @@ -242,35 +239,35 @@ public class AspectJAutoProxyCreatorTests { ClassPathXmlApplicationContext bf = newContext("pertarget.xml"); ITestBean adrian1 = (ITestBean) bf.getBean("adrian"); - assertTrue(AopUtils.isAopProxy(adrian1)); + assertThat(AopUtils.isAopProxy(adrian1)).isTrue(); // Does not trigger advice or count int explicitlySetAge = 25; adrian1.setAge(explicitlySetAge); - assertEquals("Setter does not initiate advice", explicitlySetAge, adrian1.getAge()); + assertThat(adrian1.getAge()).as("Setter does not initiate advice").isEqualTo(explicitlySetAge); // Fire aspect AspectMetadata am = new AspectMetadata(PerTargetAspect.class, "someBean"); - assertTrue(am.getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)); + assertThat(am.getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null)).isTrue(); adrian1.getSpouse(); - assertEquals("Advice has now been instantiated", 0, adrian1.getAge()); + assertThat(adrian1.getAge()).as("Advice has now been instantiated").isEqualTo(0); adrian1.setAge(11); - assertEquals("Any int setter increments", 2, adrian1.getAge()); + assertThat(adrian1.getAge()).as("Any int setter increments").isEqualTo(2); adrian1.setName("Adrian"); //assertEquals("Any other setter does not increment", 2, adrian1.getAge()); ITestBean adrian2 = (ITestBean) bf.getBean("adrian"); - assertNotSame(adrian1, adrian2); - assertTrue(AopUtils.isAopProxy(adrian1)); - assertEquals(34, adrian2.getAge()); + assertThat(adrian2).isNotSameAs(adrian1); + assertThat(AopUtils.isAopProxy(adrian1)).isTrue(); + assertThat(adrian2.getAge()).isEqualTo(34); adrian2.getSpouse(); - assertEquals("Aspect now fired", 0, adrian2.getAge()); - assertEquals(1, adrian2.getAge()); - assertEquals(2, adrian2.getAge()); - assertEquals(3, adrian1.getAge()); + assertThat(adrian2.getAge()).as("Aspect now fired").isEqualTo(0); + assertThat(adrian2.getAge()).isEqualTo(1); + assertThat(adrian2.getAge()).isEqualTo(2); + assertThat(adrian1.getAge()).isEqualTo(3); } @Test @@ -288,7 +285,7 @@ public class AspectJAutoProxyCreatorTests { ITestBean adrian1 = (ITestBean) bf.getBean("adrian"); testAgeAspect(adrian1, 0, 1); ITestBean adrian2 = (ITestBean) bf.getBean("adrian"); - assertNotSame(adrian1, adrian2); + assertThat(adrian2).isNotSameAs(adrian1); testAgeAspect(adrian2, 2, 1); } @@ -299,19 +296,19 @@ public class AspectJAutoProxyCreatorTests { ITestBean adrian1 = (ITestBean) bf.getBean("adrian"); testAgeAspect(adrian1, 0, 1); ITestBean adrian2 = (ITestBean) bf.getBean("adrian"); - assertNotSame(adrian1, adrian2); + assertThat(adrian2).isNotSameAs(adrian1); testAgeAspect(adrian2, 0, 1); } private void testAgeAspect(ITestBean adrian, int start, int increment) { - assertTrue(AopUtils.isAopProxy(adrian)); + assertThat(AopUtils.isAopProxy(adrian)).isTrue(); adrian.setName(""); - assertEquals(start, adrian.age()); + assertThat(adrian.age()).isEqualTo(start); int newAge = 32; adrian.setAge(newAge); - assertEquals(start + increment, adrian.age()); + assertThat(adrian.age()).isEqualTo((start + increment)); adrian.setAge(0); - assertEquals(start + increment * 2, adrian.age()); + assertThat(adrian.age()).isEqualTo((start + increment * 2)); } @Test @@ -323,7 +320,7 @@ public class AspectJAutoProxyCreatorTests { AdviceUsingThisJoinPoint aspectInstance = (AdviceUsingThisJoinPoint) bf.getBean("aspect"); //(AdviceUsingThisJoinPoint) Aspects.aspectOf(AdviceUsingThisJoinPoint.class); //assertEquals("method-execution(int TestBean.getAge())",aspectInstance.getLastMethodEntered()); - assertTrue(aspectInstance.getLastMethodEntered().indexOf("TestBean.getAge())") != 0); + assertThat(aspectInstance.getLastMethodEntered().indexOf("TestBean.getAge())") != 0).isTrue(); } @Test @@ -331,8 +328,8 @@ public class AspectJAutoProxyCreatorTests { ClassPathXmlApplicationContext bf = newContext("usesInclude.xml"); ITestBean adrian = (ITestBean) bf.getBean("adrian"); - assertTrue(AopUtils.isAopProxy(adrian)); - assertEquals(68, adrian.getAge()); + assertThat(AopUtils.isAopProxy(adrian)).isTrue(); + assertThat(adrian.getAge()).isEqualTo(68); } @Test @@ -340,8 +337,8 @@ public class AspectJAutoProxyCreatorTests { ClassPathXmlApplicationContext bf = newContext("aspectsWithCGLIB.xml"); ProxyConfig pc = (ProxyConfig) bf.getBean(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME); - assertTrue("should be proxying classes", pc.isProxyTargetClass()); - assertTrue("should expose proxy", pc.isExposeProxy()); + assertThat(pc.isProxyTargetClass()).as("should be proxying classes").isTrue(); + assertThat(pc.isExposeProxy()).as("should expose proxy").isTrue(); } @Test @@ -349,8 +346,8 @@ public class AspectJAutoProxyCreatorTests { ClassPathXmlApplicationContext bf = newContext("aspectsWithAbstractBean.xml"); ITestBean adrian = (ITestBean) bf.getBean("adrian"); - assertTrue(AopUtils.isAopProxy(adrian)); - assertEquals(68, adrian.getAge()); + assertThat(AopUtils.isAopProxy(adrian)).isTrue(); + assertThat(adrian.getAge()).isEqualTo(68); } @Test @@ -360,10 +357,10 @@ public class AspectJAutoProxyCreatorTests { UnreliableBean bean = (UnreliableBean) bf.getBean("unreliableBean"); RetryAspect aspect = (RetryAspect) bf.getBean("retryAspect"); int attempts = bean.unreliable(); - assertEquals(2, attempts); - assertEquals(2, aspect.getBeginCalls()); - assertEquals(1, aspect.getRollbackCalls()); - assertEquals(1, aspect.getCommitCalls()); + assertThat(attempts).isEqualTo(2); + assertThat(aspect.getBeginCalls()).isEqualTo(2); + assertThat(aspect.getRollbackCalls()).isEqualTo(1); + assertThat(aspect.getCommitCalls()).isEqualTo(1); } @Test @@ -371,7 +368,7 @@ public class AspectJAutoProxyCreatorTests { ClassPathXmlApplicationContext bf = newContext("withBeanNameAutoProxyCreator.xml"); ITestBean tb = (ITestBean) bf.getBean("adrian"); - assertEquals(68, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(68); } @@ -393,8 +390,8 @@ public class AspectJAutoProxyCreatorTests { private void assertStopWatchTimeLimit(final StopWatch sw, final long maxTimeMillis) { long totalTimeMillis = sw.getTotalTimeMillis(); - assertTrue("'" + sw.getLastTaskName() + "' took too long: expected less than<" + maxTimeMillis + - "> ms, actual<" + totalTimeMillis + "> ms.", totalTimeMillis < maxTimeMillis); + assertThat(totalTimeMillis < maxTimeMillis).as("'" + sw.getLastTaskName() + "' took too long: expected less than<" + maxTimeMillis + + "> ms, actual<" + totalTimeMillis + "> ms.").isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests.java index 7c13aee78e1..532e91394c1 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests.java @@ -26,9 +26,7 @@ import org.springframework.aop.support.AopUtils; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -45,7 +43,7 @@ public class AtAspectJAfterThrowingTests { ITestBean bean = (ITestBean) ctx.getBean("testBean"); ExceptionHandlingAspect aspect = (ExceptionHandlingAspect) ctx.getBean("aspect"); - assertTrue(AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).isTrue(); try { bean.unreliableFileOperation(); } @@ -53,8 +51,8 @@ public class AtAspectJAfterThrowingTests { // } - assertEquals(1, aspect.handled); - assertNotNull(aspect.lastException); + assertThat(aspect.handled).isEqualTo(1); + assertThat(aspect.lastException).isNotNull(); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAnnotationBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAnnotationBindingTests.java index 185f12c1181..f059788a8cb 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAnnotationBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAnnotationBindingTests.java @@ -26,7 +26,7 @@ import org.springframework.beans.factory.FactoryBean; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.Resource; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Adrian Colyer @@ -48,14 +48,14 @@ public class AtAspectJAnnotationBindingTests { @Test public void testAnnotationBindingInAroundAdvice() { - assertEquals("this value doThis", testBean.doThis()); - assertEquals("that value doThat", testBean.doThat()); - assertEquals(2, testBean.doArray().length); + assertThat(testBean.doThis()).isEqualTo("this value doThis"); + assertThat(testBean.doThat()).isEqualTo("that value doThat"); + assertThat(testBean.doArray().length).isEqualTo(2); } @Test public void testNoMatchingWithoutAnnotationPresent() { - assertEquals("doTheOther", testBean.doTheOther()); + assertThat(testBean.doTheOther()).isEqualTo("doTheOther"); } @Test diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests.java index 5cb7661bce3..28feedca533 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests.java @@ -36,8 +36,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.util.StopWatch; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for AspectJ auto proxying. Includes mixing with Spring AOP @@ -108,8 +107,8 @@ public class BenchmarkTests { sw.start(howmany + " repeated around advice invocations with " + technology); ITestBean adrian = (ITestBean) bf.getBean("adrian"); - assertTrue(AopUtils.isAopProxy(adrian)); - assertEquals(68, adrian.getAge()); + assertThat(AopUtils.isAopProxy(adrian)).isTrue(); + assertThat(adrian.getAge()).isEqualTo(68); for (int i = 0; i < howmany; i++) { adrian.getAge(); @@ -127,10 +126,10 @@ public class BenchmarkTests { sw.start(howmany + " repeated before advice invocations with " + technology); ITestBean adrian = (ITestBean) bf.getBean("adrian"); - assertTrue(AopUtils.isAopProxy(adrian)); + assertThat(AopUtils.isAopProxy(adrian)).isTrue(); Advised a = (Advised) adrian; - assertTrue(a.getAdvisors().length >= 3); - assertEquals("adrian", adrian.getName()); + assertThat(a.getAdvisors().length >= 3).isTrue(); + assertThat(adrian.getName()).isEqualTo("adrian"); for (int i = 0; i < howmany; i++) { adrian.getName(); @@ -148,9 +147,9 @@ public class BenchmarkTests { sw.start(howmany + " repeated after returning advice invocations with " + technology); ITestBean adrian = (ITestBean) bf.getBean("adrian"); - assertTrue(AopUtils.isAopProxy(adrian)); + assertThat(AopUtils.isAopProxy(adrian)).isTrue(); Advised a = (Advised) adrian; - assertTrue(a.getAdvisors().length >= 3); + assertThat(a.getAdvisors().length >= 3).isTrue(); // Hits joinpoint adrian.setAge(25); @@ -170,9 +169,9 @@ public class BenchmarkTests { sw.start(howmany + " repeated mixed invocations with " + technology); ITestBean adrian = (ITestBean) bf.getBean("adrian"); - assertTrue(AopUtils.isAopProxy(adrian)); + assertThat(AopUtils.isAopProxy(adrian)).isTrue(); Advised a = (Advised) adrian; - assertTrue(a.getAdvisors().length >= 3); + assertThat(a.getAdvisors().length >= 3).isTrue(); for (int i = 0; i < howmany; i++) { // Hit all 3 joinpoints diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/generic/AfterReturningGenericTypeMatchingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/generic/AfterReturningGenericTypeMatchingTests.java index b6182848d7f..7b646047a7a 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/generic/AfterReturningGenericTypeMatchingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/generic/AfterReturningGenericTypeMatchingTests.java @@ -29,7 +29,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests ensuring that after-returning advice for generic parameters bound to @@ -62,42 +62,42 @@ public class AfterReturningGenericTypeMatchingTests { @Test public void testReturnTypeExactMatching() { testBean.getStrings(); - assertEquals(1, counterAspect.getStringsInvocationsCount); - assertEquals(0, counterAspect.getIntegersInvocationsCount); + assertThat(counterAspect.getStringsInvocationsCount).isEqualTo(1); + assertThat(counterAspect.getIntegersInvocationsCount).isEqualTo(0); counterAspect.reset(); testBean.getIntegers(); - assertEquals(0, counterAspect.getStringsInvocationsCount); - assertEquals(1, counterAspect.getIntegersInvocationsCount); + assertThat(counterAspect.getStringsInvocationsCount).isEqualTo(0); + assertThat(counterAspect.getIntegersInvocationsCount).isEqualTo(1); } @Test public void testReturnTypeRawMatching() { testBean.getStrings(); - assertEquals(1, counterAspect.getRawsInvocationsCount); + assertThat(counterAspect.getRawsInvocationsCount).isEqualTo(1); counterAspect.reset(); testBean.getIntegers(); - assertEquals(1, counterAspect.getRawsInvocationsCount); + assertThat(counterAspect.getRawsInvocationsCount).isEqualTo(1); } @Test public void testReturnTypeUpperBoundMatching() { testBean.getIntegers(); - assertEquals(1, counterAspect.getNumbersInvocationsCount); + assertThat(counterAspect.getNumbersInvocationsCount).isEqualTo(1); } @Test public void testReturnTypeLowerBoundMatching() { testBean.getTestBeans(); - assertEquals(1, counterAspect.getTestBeanInvocationsCount); + assertThat(counterAspect.getTestBeanInvocationsCount).isEqualTo(1); counterAspect.reset(); testBean.getEmployees(); - assertEquals(0, counterAspect.getTestBeanInvocationsCount); + assertThat(counterAspect.getTestBeanInvocationsCount).isEqualTo(0); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericBridgeMethodMatchingClassProxyTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericBridgeMethodMatchingClassProxyTests.java index 6a222896d9b..41efee549fd 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericBridgeMethodMatchingClassProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericBridgeMethodMatchingClassProxyTests.java @@ -18,7 +18,7 @@ package org.springframework.aop.aspectj.generic; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for AspectJ pointcut expression matching when working with bridge methods. @@ -35,13 +35,13 @@ public class GenericBridgeMethodMatchingClassProxyTests extends GenericBridgeMet @Test public void testGenericDerivedInterfaceMethodThroughClass() { ((DerivedStringParameterizedClass) testBean).genericDerivedInterfaceMethod(""); - assertEquals(1, counterAspect.count); + assertThat(counterAspect.count).isEqualTo(1); } @Test public void testGenericBaseInterfaceMethodThroughClass() { ((DerivedStringParameterizedClass) testBean).genericBaseInterfaceMethod(""); - assertEquals(1, counterAspect.count); + assertThat(counterAspect.count).isEqualTo(1); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericBridgeMethodMatchingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericBridgeMethodMatchingTests.java index 2f3a0f0d92d..ce8da547424 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericBridgeMethodMatchingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericBridgeMethodMatchingTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for AspectJ pointcut expression matching when working with bridge methods. @@ -62,13 +62,13 @@ public class GenericBridgeMethodMatchingTests { @Test public void testGenericDerivedInterfaceMethodThroughInterface() { testBean.genericDerivedInterfaceMethod(""); - assertEquals(1, counterAspect.count); + assertThat(counterAspect.count).isEqualTo(1); } @Test public void testGenericBaseInterfaceMethodThroughInterface() { testBean.genericBaseInterfaceMethod(""); - assertEquals(1, counterAspect.count); + assertThat(counterAspect.count).isEqualTo(1); } } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericParameterMatchingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericParameterMatchingTests.java index cf37987ebbf..88cc987d126 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericParameterMatchingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/generic/GenericParameterMatchingTests.java @@ -25,7 +25,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests that poitncut matching is correct with generic method parameter. @@ -57,19 +57,19 @@ public class GenericParameterMatchingTests { @Test public void testGenericInterfaceGenericArgExecution() { testBean.save(""); - assertEquals(1, counterAspect.genericInterfaceGenericArgExecutionCount); + assertThat(counterAspect.genericInterfaceGenericArgExecutionCount).isEqualTo(1); } @Test public void testGenericInterfaceGenericCollectionArgExecution() { testBean.saveAll(null); - assertEquals(1, counterAspect.genericInterfaceGenericCollectionArgExecutionCount); + assertThat(counterAspect.genericInterfaceGenericCollectionArgExecutionCount).isEqualTo(1); } @Test public void testGenericInterfaceSubtypeGenericCollectionArgExecution() { testBean.saveAll(null); - assertEquals(1, counterAspect.genericInterfaceSubtypeGenericCollectionArgExecutionCount); + assertThat(counterAspect.genericInterfaceSubtypeGenericCollectionArgExecutionCount).isEqualTo(1); } diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests.java b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests.java index 36825506c79..eadc5ec825a 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests.java +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests.java @@ -22,7 +22,7 @@ import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -33,8 +33,8 @@ public class AopNamespaceHandlerProxyTargetClassTests extends AopNamespaceHandle @Test public void testIsClassProxy() { ITestBean bean = getTestBean(); - assertTrue("Should be a CGLIB proxy", AopUtils.isCglibProxy(bean)); - assertTrue("Should expose proxy", ((Advised) bean).isExposeProxy()); + assertThat(AopUtils.isCglibProxy(bean)).as("Should be a CGLIB proxy").isTrue(); + assertThat(((Advised) bean).isExposeProxy()).as("Should expose proxy").isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests.java b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests.java index d2fe27d1902..79fd54eb684 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests.java +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests.java @@ -29,8 +29,7 @@ import org.springframework.tests.aop.advice.CountingBeforeAdvice; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for aop namespace. @@ -57,13 +56,13 @@ public class AopNamespaceHandlerTests { public void testIsProxy() throws Exception { ITestBean bean = getTestBean(); - assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).as("Bean is not a proxy").isTrue(); // check the advice details Advised advised = (Advised) bean; Advisor[] advisors = advised.getAdvisors(); - assertTrue("Advisors should not be empty", advisors.length > 0); + assertThat(advisors.length > 0).as("Advisors should not be empty").isTrue(); } @Test @@ -73,18 +72,18 @@ public class AopNamespaceHandlerTests { ITestBean bean = getTestBean(); - assertEquals("Incorrect initial getAge count", 0, getAgeCounter.getCalls("getAge")); - assertEquals("Incorrect initial getName count", 0, getNameCounter.getCalls("getName")); + assertThat(getAgeCounter.getCalls("getAge")).as("Incorrect initial getAge count").isEqualTo(0); + assertThat(getNameCounter.getCalls("getName")).as("Incorrect initial getName count").isEqualTo(0); bean.getAge(); - assertEquals("Incorrect getAge count on getAge counter", 1, getAgeCounter.getCalls("getAge")); - assertEquals("Incorrect getAge count on getName counter", 0, getNameCounter.getCalls("getAge")); + assertThat(getAgeCounter.getCalls("getAge")).as("Incorrect getAge count on getAge counter").isEqualTo(1); + assertThat(getNameCounter.getCalls("getAge")).as("Incorrect getAge count on getName counter").isEqualTo(0); bean.getName(); - assertEquals("Incorrect getName count on getName counter", 1, getNameCounter.getCalls("getName")); - assertEquals("Incorrect getName count on getAge counter", 0, getAgeCounter.getCalls("getName")); + assertThat(getNameCounter.getCalls("getName")).as("Incorrect getName count on getName counter").isEqualTo(1); + assertThat(getAgeCounter.getCalls("getName")).as("Incorrect getName count on getAge counter").isEqualTo(0); } @Test @@ -93,18 +92,18 @@ public class AopNamespaceHandlerTests { CountingAspectJAdvice advice = (CountingAspectJAdvice) this.context.getBean("countingAdvice"); - assertEquals("Incorrect before count", 0, advice.getBeforeCount()); - assertEquals("Incorrect after count", 0, advice.getAfterCount()); + assertThat(advice.getBeforeCount()).as("Incorrect before count").isEqualTo(0); + assertThat(advice.getAfterCount()).as("Incorrect after count").isEqualTo(0); bean.setName("Sally"); - assertEquals("Incorrect before count", 1, advice.getBeforeCount()); - assertEquals("Incorrect after count", 1, advice.getAfterCount()); + assertThat(advice.getBeforeCount()).as("Incorrect before count").isEqualTo(1); + assertThat(advice.getAfterCount()).as("Incorrect after count").isEqualTo(1); bean.getName(); - assertEquals("Incorrect before count", 1, advice.getBeforeCount()); - assertEquals("Incorrect after count", 1, advice.getAfterCount()); + assertThat(advice.getBeforeCount()).as("Incorrect before count").isEqualTo(1); + assertThat(advice.getAfterCount()).as("Incorrect after count").isEqualTo(1); } @Test @@ -113,18 +112,18 @@ public class AopNamespaceHandlerTests { CountingAspectJAdvice advice = (CountingAspectJAdvice) this.context.getBean("countingAdvice"); - assertEquals("Incorrect before count", 0, advice.getBeforeCount()); - assertEquals("Incorrect after count", 0, advice.getAfterCount()); + assertThat(advice.getBeforeCount()).as("Incorrect before count").isEqualTo(0); + assertThat(advice.getAfterCount()).as("Incorrect after count").isEqualTo(0); bean.setName("Sally"); - assertEquals("Incorrect before count", 1, advice.getBeforeCount()); - assertEquals("Incorrect after count", 1, advice.getAfterCount()); + assertThat(advice.getBeforeCount()).as("Incorrect before count").isEqualTo(1); + assertThat(advice.getAfterCount()).as("Incorrect after count").isEqualTo(1); bean.getName(); - assertEquals("Incorrect before count", 1, advice.getBeforeCount()); - assertEquals("Incorrect after count", 1, advice.getAfterCount()); + assertThat(advice.getBeforeCount()).as("Incorrect before count").isEqualTo(1); + assertThat(advice.getAfterCount()).as("Incorrect after count").isEqualTo(1); } @Test @@ -133,18 +132,18 @@ public class AopNamespaceHandlerTests { CountingAspectJAdvice advice = (CountingAspectJAdvice) this.context.getBean("countingAdvice"); - assertEquals("Incorrect before count", 0, advice.getBeforeCount()); - assertEquals("Incorrect after count", 0, advice.getAfterCount()); + assertThat(advice.getBeforeCount()).as("Incorrect before count").isEqualTo(0); + assertThat(advice.getAfterCount()).as("Incorrect after count").isEqualTo(0); bean.setName("Sally"); - assertEquals("Incorrect before count", 1, advice.getBeforeCount()); - assertEquals("Incorrect after count", 1, advice.getAfterCount()); + assertThat(advice.getBeforeCount()).as("Incorrect before count").isEqualTo(1); + assertThat(advice.getAfterCount()).as("Incorrect after count").isEqualTo(1); bean.getName(); - assertEquals("Incorrect before count", 1, advice.getBeforeCount()); - assertEquals("Incorrect after count", 1, advice.getAfterCount()); + assertThat(advice.getBeforeCount()).as("Incorrect before count").isEqualTo(1); + assertThat(advice.getAfterCount()).as("Incorrect after count").isEqualTo(1); } } diff --git a/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java index f8c0fc5ac02..8e969dd93cd 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java @@ -23,10 +23,8 @@ import org.junit.Test; import org.springframework.beans.factory.BeanFactory; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -49,12 +47,12 @@ public class MethodLocatingFactoryBeanTests { @Test public void testIsSingleton() { - assertTrue(factory.isSingleton()); + assertThat(factory.isSingleton()).isTrue(); } @Test public void testGetObjectType() { - assertEquals(Method.class, factory.getObjectType()); + assertThat(factory.getObjectType()).isEqualTo(Method.class); } @Test @@ -104,10 +102,11 @@ public class MethodLocatingFactoryBeanTests { factory.setMethodName("toString()"); factory.setBeanFactory(beanFactory); Object result = factory.getObject(); - assertNotNull(result); - assertTrue(result instanceof Method); + assertThat(result).isNotNull(); + boolean condition = result instanceof Method; + assertThat(condition).isTrue(); Method method = (Method) result; - assertEquals("Bingo", method.invoke("Bingo")); + assertThat(method.invoke("Bingo")).isEqualTo("Bingo"); } @Test diff --git a/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java index 1fb037c6986..7348d31d639 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java @@ -80,13 +80,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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.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; /** * @author Rod Johnson @@ -156,12 +149,12 @@ public abstract class AbstractAopProxyTests { pf1.addAdvisor(new DefaultPointcutAdvisor(new TimestampIntroductionInterceptor())); ITestBean tb = (ITestBean) pf1.getProxy(); - assertEquals(age1, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(age1); tb.setAge(age2); - assertEquals(age2, tb.getAge()); - assertNull(tb.getName()); + assertThat(tb.getAge()).isEqualTo(age2); + assertThat(tb.getName()).isNull(); tb.setName(name); - assertEquals(name, tb.getName()); + assertThat(tb.getName()).isEqualTo(name); } /** @@ -177,7 +170,7 @@ public abstract class AbstractAopProxyTests { sw.start("Create " + howMany + " proxies"); testManyProxies(howMany); sw.stop(); - assertTrue("Proxy creation was too slow", sw.getTotalTimeMillis() < 5000); + assertThat(sw.getTotalTimeMillis() < 5000).as("Proxy creation was too slow").isTrue(); } private void testManyProxies(int howMany) { @@ -190,37 +183,37 @@ public abstract class AbstractAopProxyTests { ITestBean[] proxies = new ITestBean[howMany]; for (int i = 0; i < howMany; i++) { proxies[i] = (ITestBean) createAopProxy(pf1).getProxy(); - assertEquals(age1, proxies[i].getAge()); + assertThat(proxies[i].getAge()).isEqualTo(age1); } } @Test public void testSerializationAdviceAndTargetNotSerializable() throws Exception { TestBean tb = new TestBean(); - assertFalse(SerializationTestUtils.isSerializable(tb)); + assertThat(SerializationTestUtils.isSerializable(tb)).isFalse(); ProxyFactory pf = new ProxyFactory(tb); pf.addAdvice(new NopInterceptor()); ITestBean proxy = (ITestBean) createAopProxy(pf).getProxy(); - assertFalse(SerializationTestUtils.isSerializable(proxy)); + assertThat(SerializationTestUtils.isSerializable(proxy)).isFalse(); } @Test public void testSerializationAdviceNotSerializable() throws Exception { SerializablePerson sp = new SerializablePerson(); - assertTrue(SerializationTestUtils.isSerializable(sp)); + assertThat(SerializationTestUtils.isSerializable(sp)).isTrue(); ProxyFactory pf = new ProxyFactory(sp); // This isn't serializable Advice i = new NopInterceptor(); pf.addAdvice(i); - assertFalse(SerializationTestUtils.isSerializable(i)); + assertThat(SerializationTestUtils.isSerializable(i)).isFalse(); Object proxy = createAopProxy(pf).getProxy(); - assertFalse(SerializationTestUtils.isSerializable(proxy)); + assertThat(SerializationTestUtils.isSerializable(proxy)).isFalse(); } @Test @@ -229,7 +222,7 @@ public abstract class AbstractAopProxyTests { personTarget.setName("jim"); personTarget.setAge(26); - assertTrue(SerializationTestUtils.isSerializable(personTarget)); + assertThat(SerializationTestUtils.isSerializable(personTarget)).isTrue(); ProxyFactory pf = new ProxyFactory(personTarget); @@ -243,49 +236,49 @@ public abstract class AbstractAopProxyTests { Person p = (Person) createAopProxy(pf).getProxy(); p.echo(null); - assertEquals(0, cta.getCalls()); + assertThat(cta.getCalls()).isEqualTo(0); try { p.echo(new IOException()); } catch (IOException ex) { /* expected */ } - assertEquals(1, cta.getCalls()); + assertThat(cta.getCalls()).isEqualTo(1); // Will throw exception if it fails Person p2 = (Person) SerializationTestUtils.serializeAndDeserialize(p); - assertNotSame(p, p2); - assertEquals(p.getName(), p2.getName()); - assertEquals(p.getAge(), p2.getAge()); - assertTrue("Deserialized object is an AOP proxy", AopUtils.isAopProxy(p2)); + assertThat(p2).isNotSameAs(p); + assertThat(p2.getName()).isEqualTo(p.getName()); + assertThat(p2.getAge()).isEqualTo(p.getAge()); + assertThat(AopUtils.isAopProxy(p2)).as("Deserialized object is an AOP proxy").isTrue(); Advised a1 = (Advised) p; Advised a2 = (Advised) p2; // Check we can manipulate state of p2 - assertEquals(a1.getAdvisors().length, a2.getAdvisors().length); + assertThat(a2.getAdvisors().length).isEqualTo(a1.getAdvisors().length); // This should work as SerializablePerson is equal - assertEquals("Proxies should be equal, even after one was serialized", p, p2); - assertEquals("Proxies should be equal, even after one was serialized", p2, p); + assertThat(p2).as("Proxies should be equal, even after one was serialized").isEqualTo(p); + assertThat(p).as("Proxies should be equal, even after one was serialized").isEqualTo(p2); // Check we can add a new advisor to the target NopInterceptor ni = new NopInterceptor(); p2.getAge(); - assertEquals(0, ni.getCount()); + assertThat(ni.getCount()).isEqualTo(0); a2.addAdvice(ni); p2.getAge(); - assertEquals(1, ni.getCount()); + assertThat(ni.getCount()).isEqualTo(1); cta = (CountingThrowsAdvice) a2.getAdvisors()[3].getAdvice(); p2.echo(null); - assertEquals(1, cta.getCalls()); + assertThat(cta.getCalls()).isEqualTo(1); try { p2.echo(new IOException()); } catch (IOException ex) { } - assertEquals(2, cta.getCalls()); + assertThat(cta.getCalls()).isEqualTo(2); } /** @@ -325,14 +318,16 @@ public abstract class AbstractAopProxyTests { advised2.setAge(age2); advised1.setSpouse(advised2); // = 2 invocations - assertEquals("Advised one has correct age", age1, advised1.getAge()); // = 3 invocations - assertEquals("Advised two has correct age", age2, advised2.getAge()); + // = 3 invocations + assertThat(advised1.getAge()).as("Advised one has correct age").isEqualTo(age1); + assertThat(advised2.getAge()).as("Advised two has correct age").isEqualTo(age2); // Means extra call on advised 2 - assertEquals("Advised one spouse has correct age", age2, advised1.getSpouse().getAge()); // = 4 invocations on 1 and another one on 2 + // = 4 invocations on 1 and another one on 2 + assertThat(advised1.getSpouse().getAge()).as("Advised one spouse has correct age").isEqualTo(age2); - assertEquals("one was invoked correct number of times", 4, di1.getCount()); + assertThat(di1.getCount()).as("one was invoked correct number of times").isEqualTo(4); // Got hit by call to advised1.getSpouse().getAge() - assertEquals("one was invoked correct number of times", 3, di2.getCount()); + assertThat(di2.getCount()).as("one was invoked correct number of times").isEqualTo(3); } @@ -348,15 +343,16 @@ public abstract class AbstractAopProxyTests { advised1.setAge(age1); // = 1 invocation advised1.setSpouse(advised1); // = 2 invocations - assertEquals("one was invoked correct number of times", 2, di1.getCount()); + assertThat(di1.getCount()).as("one was invoked correct number of times").isEqualTo(2); - assertEquals("Advised one has correct age", age1, advised1.getAge()); // = 3 invocations - assertEquals("one was invoked correct number of times", 3, di1.getCount()); + // = 3 invocations + assertThat(advised1.getAge()).as("Advised one has correct age").isEqualTo(age1); + assertThat(di1.getCount()).as("one was invoked correct number of times").isEqualTo(3); // = 5 invocations, as reentrant call to spouse is advised also - assertEquals("Advised spouse has correct age", age1, advised1.getSpouse().getAge()); + assertThat(advised1.getSpouse().getAge()).as("Advised spouse has correct age").isEqualTo(age1); - assertEquals("one was invoked correct number of times", 5, di1.getCount()); + assertThat(di1.getCount()).as("one was invoked correct number of times").isEqualTo(5); } @Test @@ -365,21 +361,21 @@ public abstract class AbstractAopProxyTests { INeedsToSeeProxy target = new TargetChecker(); ProxyFactory proxyFactory = new ProxyFactory(target); proxyFactory.setExposeProxy(true); - assertTrue(proxyFactory.isExposeProxy()); + assertThat(proxyFactory.isExposeProxy()).isTrue(); proxyFactory.addAdvice(0, di); INeedsToSeeProxy proxied = (INeedsToSeeProxy) createProxy(proxyFactory); - assertEquals(0, di.getCount()); - assertEquals(0, target.getCount()); + assertThat(di.getCount()).isEqualTo(0); + assertThat(target.getCount()).isEqualTo(0); proxied.incrementViaThis(); - assertEquals("Increment happened", 1, target.getCount()); + assertThat(target.getCount()).as("Increment happened").isEqualTo(1); - assertEquals("Only one invocation via AOP as use of this wasn't proxied", 1, di.getCount()); + assertThat(di.getCount()).as("Only one invocation via AOP as use of this wasn't proxied").isEqualTo(1); // 1 invocation - assertEquals("Increment happened", 1, proxied.getCount()); + assertThat(proxied.getCount()).as("Increment happened").isEqualTo(1); proxied.incrementViaProxy(); // 2 invocations - assertEquals("Increment happened", 2, target.getCount()); - assertEquals("3 more invocations via AOP as the first call was reentrant through the proxy", 4, di.getCount()); + assertThat(target.getCount()).as("Increment happened").isEqualTo(2); + assertThat(di.getCount()).as("3 more invocations via AOP as the first call was reentrant through the proxy").isEqualTo(4); } @Test @@ -387,7 +383,7 @@ public abstract class AbstractAopProxyTests { public void testTargetCantGetProxyByDefault() { NeedsToSeeProxy et = new NeedsToSeeProxy(); ProxyFactory pf1 = new ProxyFactory(et); - assertFalse(pf1.isExposeProxy()); + assertThat(pf1.isExposeProxy()).isFalse(); INeedsToSeeProxy proxied = (INeedsToSeeProxy) createProxy(pf1); assertThatIllegalStateException().isThrownBy(() -> proxied.incrementViaProxy()); @@ -416,7 +412,7 @@ public abstract class AbstractAopProxyTests { assertNoInvocationContext(); } else { - assertNotNull("have context", ExposeInvocationInterceptor.currentInvocation()); + assertThat(ExposeInvocationInterceptor.currentInvocation()).as("have context").isNotNull(); } return s; } @@ -435,7 +431,7 @@ public abstract class AbstractAopProxyTests { assertNoInvocationContext(); ITestBean tb = (ITestBean) aop.getProxy(); assertNoInvocationContext(); - assertSame("correct return value", s, tb.getName()); + assertThat(tb.getName()).as("correct return value").isSameAs(s); } /** @@ -452,7 +448,7 @@ public abstract class AbstractAopProxyTests { pc.setTarget(raw); ITestBean tb = (ITestBean) createProxy(pc); - assertSame("this return is wrapped in proxy", tb, tb.getSpouse()); + assertThat(tb.getSpouse()).as("this return is wrapped in proxy").isSameAs(tb); } @Test @@ -563,7 +559,7 @@ public abstract class AbstractAopProxyTests { @Override public Object invoke(MethodInvocation invocation) throws Throwable { // Assert that target matches BEFORE invocation returns - assertEquals("Target is correct", expectedTarget, invocation.getThis()); + assertThat(invocation.getThis()).as("Target is correct").isEqualTo(expectedTarget); return super.invoke(invocation); } }; @@ -613,22 +609,22 @@ public abstract class AbstractAopProxyTests { int newAge = 65; ITestBean itb = (ITestBean) createProxy(pc); itb.setAge(newAge); - assertEquals(newAge, itb.getAge()); + assertThat(itb.getAge()).isEqualTo(newAge); Lockable lockable = (Lockable) itb; - assertFalse(lockable.locked()); + assertThat(lockable.locked()).isFalse(); lockable.lock(); - assertEquals(newAge, itb.getAge()); + assertThat(itb.getAge()).isEqualTo(newAge); assertThatExceptionOfType(LockedException.class).isThrownBy(() -> itb.setAge(1)); - assertEquals(newAge, itb.getAge()); + assertThat(itb.getAge()).isEqualTo(newAge); // Unlock - assertTrue(lockable.locked()); + assertThat(lockable.locked()).isTrue(); lockable.unlock(); itb.setAge(1); - assertEquals(1, itb.getAge()); + assertThat(itb.getAge()).isEqualTo(1); } @Test @@ -642,14 +638,14 @@ public abstract class AbstractAopProxyTests { ITestBean t = (ITestBean) pc.getProxy(); int newAge = 5; t.setAge(newAge); - assertEquals(newAge, t.getAge()); + assertThat(t.getAge()).isEqualTo(newAge); String newName = "greg"; t.setName(newName); - assertEquals(newName, t.getName()); + assertThat(t.getName()).isEqualTo(newName); t.setName(null); // Null replacement magic should work - assertEquals("", t.getName()); + assertThat(t.getName()).isEqualTo(""); } @Test @@ -660,32 +656,32 @@ public abstract class AbstractAopProxyTests { pc.addAdvice(0, di); ITestBean t = (ITestBean) createProxy(pc); - assertEquals(0, di.getCount()); + assertThat(di.getCount()).isEqualTo(0); t.setAge(23); - assertEquals(23, t.getAge()); - assertEquals(2, di.getCount()); + assertThat(t.getAge()).isEqualTo(23); + assertThat(di.getCount()).isEqualTo(2); Advised advised = (Advised) t; - assertEquals("Have 1 advisor", 1, advised.getAdvisors().length); - assertEquals(di, advised.getAdvisors()[0].getAdvice()); + assertThat(advised.getAdvisors().length).as("Have 1 advisor").isEqualTo(1); + assertThat(advised.getAdvisors()[0].getAdvice()).isEqualTo(di); NopInterceptor di2 = new NopInterceptor(); advised.addAdvice(1, di2); t.getName(); - assertEquals(3, di.getCount()); - assertEquals(1, di2.getCount()); + assertThat(di.getCount()).isEqualTo(3); + assertThat(di2.getCount()).isEqualTo(1); // will remove di advised.removeAdvisor(0); t.getAge(); // Unchanged - assertEquals(3, di.getCount()); - assertEquals(2, di2.getCount()); + assertThat(di.getCount()).isEqualTo(3); + assertThat(di2.getCount()).isEqualTo(2); CountingBeforeAdvice cba = new CountingBeforeAdvice(); - assertEquals(0, cba.getCalls()); + assertThat(cba.getCalls()).isEqualTo(0); advised.addAdvice(cba); t.setAge(16); - assertEquals(16, t.getAge()); - assertEquals(2, cba.getCalls()); + assertThat(t.getAge()).isEqualTo(16); + assertThat(cba.getCalls()).isEqualTo(2); } @Test @@ -705,9 +701,9 @@ public abstract class AbstractAopProxyTests { })); ITestBean proxied = (ITestBean) createProxy(pc); - assertEquals(name, proxied.getName()); + assertThat(proxied.getName()).isEqualTo(name); TimeStamped intro = (TimeStamped) proxied; - assertEquals(ts, intro.getTimeStamp()); + assertThat(intro.getTimeStamp()).isEqualTo(ts); } @Test @@ -720,7 +716,7 @@ public abstract class AbstractAopProxyTests { .withMessageContaining("ntroduction"); // Check it still works: proxy factory state shouldn't have been corrupted ITestBean proxied = (ITestBean) createProxy(pc); - assertEquals(target.getAge(), proxied.getAge()); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); } @Test @@ -753,7 +749,7 @@ public abstract class AbstractAopProxyTests { pc.addAdvisor(0, new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor(), ITestBean.class))); // Check it still works: proxy factory state shouldn't have been corrupted ITestBean proxied = (ITestBean) createProxy(pc); - assertEquals(target.getAge(), proxied.getAge()); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); } /** @@ -796,7 +792,7 @@ public abstract class AbstractAopProxyTests { .withMessageContaining("interface"); // Check it still works: proxy factory state shouldn't have been corrupted ITestBean proxied = (ITestBean) createProxy(pc); - assertEquals(target.getAge(), proxied.getAge()); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); } @Test @@ -804,7 +800,7 @@ public abstract class AbstractAopProxyTests { TestBean target = new TestBean(); target.setAge(21); ProxyFactory pc = new ProxyFactory(target); - assertFalse(pc.isFrozen()); + assertThat(pc.isFrozen()).isFalse(); pc.addAdvice(new NopInterceptor()); ITestBean proxied = (ITestBean) createProxy(pc); pc.setFrozen(true); @@ -812,8 +808,8 @@ public abstract class AbstractAopProxyTests { pc.addAdvice(0, new NopInterceptor())) .withMessageContaining("frozen"); // Check it still works: proxy factory state shouldn't have been corrupted - assertEquals(target.getAge(), proxied.getAge()); - assertEquals(1, ((Advised) proxied).getAdvisors().length); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); + assertThat(((Advised) proxied).getAdvisors().length).isEqualTo(1); } /** @@ -824,19 +820,19 @@ public abstract class AbstractAopProxyTests { TestBean target = new TestBean(); target.setAge(21); ProxyFactory pc = new ProxyFactory(target); - assertFalse(pc.isFrozen()); + assertThat(pc.isFrozen()).isFalse(); pc.addAdvice(new NopInterceptor()); ITestBean proxied = (ITestBean) createProxy(pc); pc.setFrozen(true); Advised advised = (Advised) proxied; - assertTrue(pc.isFrozen()); + assertThat(pc.isFrozen()).isTrue(); assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to add Advisor when frozen").isThrownBy(() -> advised.addAdvisor(new DefaultPointcutAdvisor(new NopInterceptor()))) .withMessageContaining("frozen"); // Check it still works: proxy factory state shouldn't have been corrupted - assertEquals(target.getAge(), proxied.getAge()); - assertEquals(1, advised.getAdvisors().length); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); + assertThat(advised.getAdvisors().length).isEqualTo(1); } @Test @@ -844,24 +840,24 @@ public abstract class AbstractAopProxyTests { TestBean target = new TestBean(); target.setAge(21); ProxyFactory pc = new ProxyFactory(target); - assertFalse(pc.isFrozen()); + assertThat(pc.isFrozen()).isFalse(); pc.addAdvice(new NopInterceptor()); ITestBean proxied = (ITestBean) createProxy(pc); pc.setFrozen(true); Advised advised = (Advised) proxied; - assertTrue(pc.isFrozen()); + assertThat(pc.isFrozen()).isTrue(); assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to remove Advisor when frozen").isThrownBy(() -> advised.removeAdvisor(0)) .withMessageContaining("frozen"); // Didn't get removed - assertEquals(1, advised.getAdvisors().length); + assertThat(advised.getAdvisors().length).isEqualTo(1); pc.setFrozen(false); // Can now remove it advised.removeAdvisor(0); // Check it still works: proxy factory state shouldn't have been corrupted - assertEquals(target.getAge(), proxied.getAge()); - assertEquals(0, advised.getAdvisors().length); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); + assertThat(advised.getAdvisors().length).isEqualTo(0); } @Test @@ -879,11 +875,11 @@ public abstract class AbstractAopProxyTests { HashMap h = new HashMap<>(); Object value1 = "foo"; Object value2 = "bar"; - assertNull(h.get(proxy1)); + assertThat(h.get(proxy1)).isNull(); h.put(proxy1, value1); h.put(proxy2, value2); - assertEquals(h.get(proxy1), value1); - assertEquals(h.get(proxy2), value2); + assertThat(value1).isEqualTo(h.get(proxy1)); + assertThat(value2).isEqualTo(h.get(proxy2)); } /** @@ -901,8 +897,8 @@ public abstract class AbstractAopProxyTests { ITestBean proxied = (ITestBean) createProxy(pc); String proxyConfigString = ((Advised) proxied).toProxyConfigString(); - assertTrue(proxyConfigString.contains(advisor.toString())); - assertTrue(proxyConfigString.contains("1 interface")); + assertThat(proxyConfigString.contains(advisor.toString())).isTrue(); + assertThat(proxyConfigString.contains("1 interface")).isTrue(); } @Test @@ -914,15 +910,16 @@ public abstract class AbstractAopProxyTests { CountingBeforeAdvice mba = new CountingBeforeAdvice(); Advisor advisor = new DefaultPointcutAdvisor(new NameMatchMethodPointcut().addMethodName("setAge"), mba); pc.addAdvisor(advisor); - assertFalse("Opaque defaults to false", pc.isOpaque()); + assertThat(pc.isOpaque()).as("Opaque defaults to false").isFalse(); pc.setOpaque(true); - assertTrue("Opaque now true for this config", pc.isOpaque()); + assertThat(pc.isOpaque()).as("Opaque now true for this config").isTrue(); ITestBean proxied = (ITestBean) createProxy(pc); proxied.setAge(10); - assertEquals(10, proxied.getAge()); - assertEquals(1, mba.getCalls()); + assertThat(proxied.getAge()).isEqualTo(10); + assertThat(mba.getCalls()).isEqualTo(1); - assertFalse("Cannot be cast to Advised", proxied instanceof Advised); + boolean condition = proxied instanceof Advised; + assertThat(condition).as("Cannot be cast to Advised").isFalse(); } @Test @@ -936,32 +933,32 @@ public abstract class AbstractAopProxyTests { RefreshCountingAdvisorChainFactory acf = new RefreshCountingAdvisorChainFactory(); // Should be automatically added as a listener pc.addListener(acf); - assertFalse(pc.isActive()); - assertEquals(0, l.activates); - assertEquals(0, acf.refreshes); + assertThat(pc.isActive()).isFalse(); + assertThat(l.activates).isEqualTo(0); + assertThat(acf.refreshes).isEqualTo(0); ITestBean proxied = (ITestBean) createProxy(pc); - assertEquals(1, acf.refreshes); - assertEquals(1, l.activates); - assertTrue(pc.isActive()); - assertEquals(target.getAge(), proxied.getAge()); - assertEquals(0, l.adviceChanges); + assertThat(acf.refreshes).isEqualTo(1); + assertThat(l.activates).isEqualTo(1); + assertThat(pc.isActive()).isTrue(); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); + assertThat(l.adviceChanges).isEqualTo(0); NopInterceptor di = new NopInterceptor(); pc.addAdvice(0, di); - assertEquals(1, l.adviceChanges); - assertEquals(2, acf.refreshes); - assertEquals(target.getAge(), proxied.getAge()); + assertThat(l.adviceChanges).isEqualTo(1); + assertThat(acf.refreshes).isEqualTo(2); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); pc.removeAdvice(di); - assertEquals(2, l.adviceChanges); - assertEquals(3, acf.refreshes); - assertEquals(target.getAge(), proxied.getAge()); + assertThat(l.adviceChanges).isEqualTo(2); + assertThat(acf.refreshes).isEqualTo(3); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); pc.getProxy(); - assertEquals(1, l.activates); + assertThat(l.activates).isEqualTo(1); pc.removeListener(l); - assertEquals(2, l.adviceChanges); + assertThat(l.adviceChanges).isEqualTo(2); pc.addAdvisor(new DefaultPointcutAdvisor(new NopInterceptor())); // No longer counting - assertEquals(2, l.adviceChanges); + assertThat(l.adviceChanges).isEqualTo(2); } @Test @@ -978,33 +975,33 @@ public abstract class AbstractAopProxyTests { NopInterceptor nop = new NopInterceptor(); pc.addAdvice(nop); ITestBean proxy = (ITestBean) createProxy(pc); - assertEquals(nop.getCount(), 0); - assertEquals(tb1.getAge(), proxy.getAge()); - assertEquals(nop.getCount(), 1); + assertThat(0).isEqualTo(nop.getCount()); + assertThat(proxy.getAge()).isEqualTo(tb1.getAge()); + assertThat(1).isEqualTo(nop.getCount()); // Change to a new static target pc.setTarget(tb2); - assertEquals(tb2.getAge(), proxy.getAge()); - assertEquals(nop.getCount(), 2); + assertThat(proxy.getAge()).isEqualTo(tb2.getAge()); + assertThat(2).isEqualTo(nop.getCount()); // Change to a new dynamic target HotSwappableTargetSource hts = new HotSwappableTargetSource(tb3); pc.setTargetSource(hts); - assertEquals(tb3.getAge(), proxy.getAge()); - assertEquals(nop.getCount(), 3); + assertThat(proxy.getAge()).isEqualTo(tb3.getAge()); + assertThat(3).isEqualTo(nop.getCount()); hts.swap(tb1); - assertEquals(tb1.getAge(), proxy.getAge()); + assertThat(proxy.getAge()).isEqualTo(tb1.getAge()); tb1.setName("Colin"); - assertEquals(tb1.getName(), proxy.getName()); - assertEquals(nop.getCount(), 5); + assertThat(proxy.getName()).isEqualTo(tb1.getName()); + assertThat(5).isEqualTo(nop.getCount()); // Change back, relying on casting to Advised Advised advised = (Advised) proxy; - assertSame(hts, advised.getTargetSource()); + assertThat(advised.getTargetSource()).isSameAs(hts); SingletonTargetSource sts = new SingletonTargetSource(tb2); advised.setTargetSource(sts); - assertEquals(tb2.getName(), proxy.getName()); - assertSame(sts, advised.getTargetSource()); - assertEquals(tb2.getAge(), proxy.getAge()); + assertThat(proxy.getName()).isEqualTo(tb2.getName()); + assertThat(advised.getTargetSource()).isSameAs(sts); + assertThat(proxy.getAge()).isEqualTo(tb2.getAge()); } @Test @@ -1016,12 +1013,12 @@ public abstract class AbstractAopProxyTests { pc.addAdvisor(dp); pc.setTarget(tb); ITestBean it = (ITestBean) createProxy(pc); - assertEquals(0, dp.count); + assertThat(dp.count).isEqualTo(0); it.getAge(); - assertEquals(1, dp.count); + assertThat(dp.count).isEqualTo(1); it.setAge(11); - assertEquals(11, it.getAge()); - assertEquals(2, dp.count); + assertThat(it.getAge()).isEqualTo(11); + assertThat(dp.count).isEqualTo(2); } @Test @@ -1035,16 +1032,16 @@ public abstract class AbstractAopProxyTests { this.mockTargetSource.setTarget(tb); pc.setTargetSource(mockTargetSource); ITestBean it = (ITestBean) createProxy(pc); - assertEquals(0, dp.count); + assertThat(dp.count).isEqualTo(0); it.getAge(); // Statically vetoed - assertEquals(0, dp.count); + assertThat(dp.count).isEqualTo(0); it.setAge(11); - assertEquals(11, it.getAge()); - assertEquals(1, dp.count); + assertThat(it.getAge()).isEqualTo(11); + assertThat(dp.count).isEqualTo(1); // Applies statically but not dynamically it.setName("joe"); - assertEquals(1, dp.count); + assertThat(dp.count).isEqualTo(1); } @Test @@ -1057,12 +1054,12 @@ public abstract class AbstractAopProxyTests { pc.addAdvisor(sp); pc.setTarget(tb); ITestBean it = (ITestBean) createProxy(pc); - assertEquals(di.getCount(), 0); + assertThat(0).isEqualTo(di.getCount()); it.getAge(); - assertEquals(di.getCount(), 1); + assertThat(1).isEqualTo(di.getCount()); it.setAge(11); - assertEquals(it.getAge(), 11); - assertEquals(di.getCount(), 2); + assertThat(11).isEqualTo(it.getAge()); + assertThat(2).isEqualTo(di.getCount()); } /** @@ -1099,11 +1096,11 @@ public abstract class AbstractAopProxyTests { final int age = 20; it.setAge(age); - assertEquals(age, it.getAge()); + assertThat(it.getAge()).isEqualTo(age); // Should return the age before the third, AOP-induced birthday - assertEquals(age + 2, it.haveBirthday()); + assertThat(it.haveBirthday()).isEqualTo((age + 2)); // Return the final age produced by 3 birthdays - assertEquals(age + 3, it.getAge()); + assertThat(it.getAge()).isEqualTo((age + 3)); } /** @@ -1150,14 +1147,14 @@ public abstract class AbstractAopProxyTests { String name2 = "gordon"; tb.setName(name1); - assertEquals(name1, tb.getName()); + assertThat(tb.getName()).isEqualTo(name1); it.setName(name2); // NameReverter saved it back - assertEquals(name1, it.getName()); - assertEquals(2, saver.names.size()); - assertEquals(name2, saver.names.get(0)); - assertEquals(name1, saver.names.get(1)); + assertThat(it.getName()).isEqualTo(name1); + assertThat(saver.names.size()).isEqualTo(2); + assertThat(saver.names.get(0)).isEqualTo(name2); + assertThat(saver.names.get(1)).isEqualTo(name1); } @SuppressWarnings("serial") @@ -1184,17 +1181,17 @@ public abstract class AbstractAopProxyTests { }); IOverloads proxy = (IOverloads) createProxy(pc); - assertEquals(0, overLoadInts.getCount()); - assertEquals(0, overLoadVoids.getCount()); + assertThat(overLoadInts.getCount()).isEqualTo(0); + assertThat(overLoadVoids.getCount()).isEqualTo(0); proxy.overload(); - assertEquals(0, overLoadInts.getCount()); - assertEquals(1, overLoadVoids.getCount()); - assertEquals(25, proxy.overload(25)); - assertEquals(1, overLoadInts.getCount()); - assertEquals(1, overLoadVoids.getCount()); + assertThat(overLoadInts.getCount()).isEqualTo(0); + assertThat(overLoadVoids.getCount()).isEqualTo(1); + assertThat(proxy.overload(25)).isEqualTo(25); + assertThat(overLoadInts.getCount()).isEqualTo(1); + assertThat(overLoadVoids.getCount()).isEqualTo(1); proxy.noAdvice(); - assertEquals(1, overLoadInts.getCount()); - assertEquals(1, overLoadVoids.getCount()); + assertThat(overLoadInts.getCount()).isEqualTo(1); + assertThat(overLoadVoids.getCount()).isEqualTo(1); } @Test @@ -1218,7 +1215,7 @@ public abstract class AbstractAopProxyTests { } @Override public Object getTarget() throws Exception { - assertEquals(proxy, AopContext.currentProxy()); + assertThat(AopContext.currentProxy()).isEqualTo(proxy); return target; } @Override @@ -1227,7 +1224,7 @@ public abstract class AbstractAopProxyTests { }); // Just test anything: it will fail if context wasn't found - assertEquals(0, proxy.getAge()); + assertThat(proxy.getAge()).isEqualTo(0); } @Test @@ -1243,21 +1240,21 @@ public abstract class AbstractAopProxyTests { IOther proxyA = (IOther) createProxy(pfa); IOther proxyB = (IOther) createProxy(pfb); - assertEquals(pfa.getAdvisors().length, pfb.getAdvisors().length); - assertEquals(a, b); - assertEquals(i1, i2); - assertEquals(proxyA, proxyB); - assertEquals(proxyA.hashCode(), proxyB.hashCode()); - assertFalse(proxyA.equals(a)); + assertThat(pfb.getAdvisors().length).isEqualTo(pfa.getAdvisors().length); + assertThat(b).isEqualTo(a); + assertThat(i2).isEqualTo(i1); + assertThat(proxyB).isEqualTo(proxyA); + assertThat(proxyB.hashCode()).isEqualTo(proxyA.hashCode()); + assertThat(proxyA.equals(a)).isFalse(); // Equality checks were handled by the proxy - assertEquals(0, i1.getCount()); + assertThat(i1.getCount()).isEqualTo(0); // When we invoke A, it's NopInterceptor will have count == 1 // and won't think it's equal to B's NopInterceptor proxyA.absquatulate(); - assertEquals(1, i1.getCount()); - assertFalse(proxyA.equals(proxyB)); + assertThat(i1.getCount()).isEqualTo(1); + assertThat(proxyA.equals(proxyB)).isFalse(); } @Test @@ -1275,18 +1272,18 @@ public abstract class AbstractAopProxyTests { ProxyFactory pf = new ProxyFactory(target); pf.addAdvice(new NopInterceptor()); pf.addAdvisor(matchesNoArgs); - assertEquals("Advisor was added", matchesNoArgs, pf.getAdvisors()[1]); + assertThat(pf.getAdvisors()[1]).as("Advisor was added").isEqualTo(matchesNoArgs); ITestBean proxied = (ITestBean) createProxy(pf); - assertEquals(0, cba.getCalls()); - assertEquals(0, cba.getCalls("getAge")); - assertEquals(target.getAge(), proxied.getAge()); - assertEquals(1, cba.getCalls()); - assertEquals(1, cba.getCalls("getAge")); - assertEquals(0, cba.getCalls("setAge")); + assertThat(cba.getCalls()).isEqualTo(0); + assertThat(cba.getCalls("getAge")).isEqualTo(0); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); + assertThat(cba.getCalls()).isEqualTo(1); + assertThat(cba.getCalls("getAge")).isEqualTo(1); + assertThat(cba.getCalls("setAge")).isEqualTo(0); // Won't be advised proxied.setAge(26); - assertEquals(1, cba.getCalls()); - assertEquals(26, proxied.getAge()); + assertThat(cba.getCalls()).isEqualTo(1); + assertThat(proxied.getAge()).isEqualTo(26); } @Test @@ -1303,7 +1300,7 @@ public abstract class AbstractAopProxyTests { ReflectiveMethodInvocation rmi = (ReflectiveMethodInvocation) invocation; for (Iterator it = rmi.getUserAttributes().keySet().iterator(); it.hasNext(); ){ Object key = it.next(); - assertEquals(expectedValues.get(key), rmi.getUserAttributes().get(key)); + assertThat(rmi.getUserAttributes().get(key)).isEqualTo(expectedValues.get(key)); } rmi.getUserAttributes().putAll(valuesToAdd); return invocation.proceed(); @@ -1338,7 +1335,7 @@ public abstract class AbstractAopProxyTests { String newName = "foo"; tb.setName(newName); - assertEquals(newName, tb.getName()); + assertThat(tb.getName()).isEqualTo(newName); } @Test @@ -1356,23 +1353,23 @@ public abstract class AbstractAopProxyTests { ProxyFactory pf = new ProxyFactory(target); pf.addAdvice(new NopInterceptor()); pf.addAdvisor(matchesNoArgs); - assertEquals("Advisor was added", matchesNoArgs, pf.getAdvisors()[1]); + assertThat(pf.getAdvisors()[1]).as("Advisor was added").isEqualTo(matchesNoArgs); ITestBean proxied = (ITestBean) createProxy(pf); - assertEquals(0, cca.getCalls()); - assertEquals(0, cca.getCalls("getAge")); - assertEquals(target.getAge(), proxied.getAge()); - assertEquals(2, cca.getCalls()); - assertEquals(2, cca.getCalls("getAge")); - assertEquals(0, cca.getCalls("setAge")); + assertThat(cca.getCalls()).isEqualTo(0); + assertThat(cca.getCalls("getAge")).isEqualTo(0); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); + assertThat(cca.getCalls()).isEqualTo(2); + assertThat(cca.getCalls("getAge")).isEqualTo(2); + assertThat(cca.getCalls("setAge")).isEqualTo(0); // Won't be advised proxied.setAge(26); - assertEquals(2, cca.getCalls()); - assertEquals(26, proxied.getAge()); - assertEquals(4, cca.getCalls()); + assertThat(cca.getCalls()).isEqualTo(2); + assertThat(proxied.getAge()).isEqualTo(26); + assertThat(cca.getCalls()).isEqualTo(4); assertThatExceptionOfType(SpecializedUncheckedException.class).as("Should have thrown CannotGetJdbcConnectionException").isThrownBy(() -> proxied.exceptional(new SpecializedUncheckedException("foo", (SQLException)null))); - assertEquals(6, cca.getCalls()); + assertThat(cca.getCalls()).isEqualTo(6); } @Test @@ -1398,21 +1395,21 @@ public abstract class AbstractAopProxyTests { pf.addAdvice(nop2); ITestBean proxied = (ITestBean) createProxy(pf); // Won't throw an exception - assertEquals(target.getAge(), proxied.getAge()); - assertEquals(1, ba.getCalls()); - assertEquals(1, ba.getCalls("getAge")); - assertEquals(1, nop1.getCount()); - assertEquals(1, nop2.getCount()); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); + assertThat(ba.getCalls()).isEqualTo(1); + assertThat(ba.getCalls("getAge")).isEqualTo(1); + assertThat(nop1.getCount()).isEqualTo(1); + assertThat(nop2.getCount()).isEqualTo(1); // Will fail, after invoking Nop1 assertThatExceptionOfType(RuntimeException.class).as("before advice should have ended chain").isThrownBy(() -> proxied.setAge(26)) .matches(rex::equals); - assertEquals(2, ba.getCalls()); - assertEquals(2, nop1.getCount()); + assertThat(ba.getCalls()).isEqualTo(2); + assertThat(nop1.getCount()).isEqualTo(2); // Nop2 didn't get invoked when the exception was thrown - assertEquals(1, nop2.getCount()); + assertThat(nop2.getCount()).isEqualTo(1); // Shouldn't have changed value in joinpoint - assertEquals(target.getAge(), proxied.getAge()); + assertThat(proxied.getAge()).isEqualTo(target.getAge()); } @@ -1437,20 +1434,20 @@ public abstract class AbstractAopProxyTests { ProxyFactory pf = new ProxyFactory(target); pf.addAdvice(new NopInterceptor()); pf.addAdvisor(matchesInt); - assertEquals("Advisor was added", matchesInt, pf.getAdvisors()[1]); + assertThat(pf.getAdvisors()[1]).as("Advisor was added").isEqualTo(matchesInt); ITestBean proxied = (ITestBean) createProxy(pf); - assertEquals(0, aa.sum); + assertThat(aa.sum).isEqualTo(0); int i1 = 12; int i2 = 13; // Won't be advised proxied.setAge(i1); - assertEquals(i1, proxied.getAge()); - assertEquals(i1, aa.sum); + assertThat(proxied.getAge()).isEqualTo(i1); + assertThat(aa.sum).isEqualTo(i1); proxied.setAge(i2); - assertEquals(i2, proxied.getAge()); - assertEquals(i1 + i2, aa.sum); - assertEquals(i2, proxied.getAge()); + assertThat(proxied.getAge()).isEqualTo(i2); + assertThat(aa.sum).isEqualTo((i1 + i2)); + assertThat(proxied.getAge()).isEqualTo(i2); } @Test @@ -1460,19 +1457,19 @@ public abstract class AbstractAopProxyTests { ProxyFactory pf = new ProxyFactory(target); pf.addAdvice(new NopInterceptor()); pf.addAdvice(car); - assertEquals("Advice was wrapped in Advisor and added", car, pf.getAdvisors()[1].getAdvice()); + assertThat(pf.getAdvisors()[1].getAdvice()).as("Advice was wrapped in Advisor and added").isEqualTo(car); ITestBean proxied = (ITestBean) createProxy(pf); - assertEquals(0, car.getCalls()); + assertThat(car.getCalls()).isEqualTo(0); int age = 10; proxied.setAge(age); - assertEquals(age, proxied.getAge()); - assertEquals(2, car.getCalls()); + assertThat(proxied.getAge()).isEqualTo(age); + assertThat(car.getCalls()).isEqualTo(2); Exception exc = new Exception(); // On exception it won't be invoked assertThatExceptionOfType(Throwable.class).isThrownBy(() -> proxied.exceptional(exc)) .satisfies(ex -> assertThat(ex).isSameAs(exc)); - assertEquals(2, car.getCalls()); + assertThat(car.getCalls()).isEqualTo(2); } @@ -1493,11 +1490,11 @@ public abstract class AbstractAopProxyTests { ProxyFactory pf = new ProxyFactory(target); pf.addAdvice(new NopInterceptor()); pf.addAdvisor(matchesEchoInvocations); - assertEquals("Advisor was added", matchesEchoInvocations, pf.getAdvisors()[1]); + assertThat(pf.getAdvisors()[1]).as("Advisor was added").isEqualTo(matchesEchoInvocations); IEcho proxied = (IEcho) createProxy(pf); - assertEquals(0, th.getCalls()); - assertEquals(target.getA(), proxied.getA()); - assertEquals(0, th.getCalls()); + assertThat(th.getCalls()).isEqualTo(0); + assertThat(proxied.getA()).isEqualTo(target.getA()); + assertThat(th.getCalls()).isEqualTo(0); Exception ex = new Exception(); // Will be advised but doesn't match assertThatExceptionOfType(Exception.class).isThrownBy(() -> @@ -1507,7 +1504,7 @@ public abstract class AbstractAopProxyTests { assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() -> proxied.echoException(1, fex)) .matches(fex::equals); - assertEquals(1, th.getCalls("ioException")); + assertThat(th.getCalls("ioException")).isEqualTo(1); } @Test @@ -1521,9 +1518,9 @@ public abstract class AbstractAopProxyTests { pf.addAdvice(new NopInterceptor()); pf.addAdvice(th); IEcho proxied = (IEcho) createProxy(pf); - assertEquals(0, th.getCalls()); - assertEquals(target.getA(), proxied.getA()); - assertEquals(0, th.getCalls()); + assertThat(th.getCalls()).isEqualTo(0); + assertThat(proxied.getA()).isEqualTo(target.getA()); + assertThat(th.getCalls()).isEqualTo(0); Exception ex = new Exception(); // Will be advised but doesn't match assertThatExceptionOfType(Exception.class).isThrownBy(() -> @@ -1536,7 +1533,7 @@ public abstract class AbstractAopProxyTests { proxied.echoException(1, mex)) .matches(mex::equals); - assertEquals(1, th.getCalls("remoteException")); + assertThat(th.getCalls("remoteException")).isEqualTo(1); } private static class CheckMethodInvocationIsSameInAndOutInterceptor implements MethodInterceptor { @@ -1545,7 +1542,7 @@ public abstract class AbstractAopProxyTests { public Object invoke(MethodInvocation mi) throws Throwable { Method m = mi.getMethod(); Object retval = mi.proceed(); - assertEquals("Method invocation has same method on way back", m, mi.getMethod()); + assertThat(mi.getMethod()).as("Method invocation has same method on way back").isEqualTo(m); return retval; } } @@ -1561,10 +1558,10 @@ public abstract class AbstractAopProxyTests { String task = "get invocation on way IN"; try { MethodInvocation current = ExposeInvocationInterceptor.currentInvocation(); - assertEquals(mi.getMethod(), current.getMethod()); + assertThat(current.getMethod()).isEqualTo(mi.getMethod()); Object retval = mi.proceed(); task = "get invocation on way OUT"; - assertEquals(current, ExposeInvocationInterceptor.currentInvocation()); + assertThat(ExposeInvocationInterceptor.currentInvocation()).isEqualTo(current); return retval; } catch (IllegalStateException ex) { @@ -1587,7 +1584,7 @@ public abstract class AbstractAopProxyTests { public Object invoke(MethodInvocation mi) throws Throwable { Object proxy = AopContext.currentProxy(); Object ret = mi.proceed(); - assertEquals(proxy, AopContext.currentProxy()); + assertThat(AopContext.currentProxy()).isEqualTo(proxy); return ret; } } @@ -1804,13 +1801,13 @@ public abstract class AbstractAopProxyTests { @Override public void activated(AdvisedSupport advised) { - assertEquals(expectedSource, advised); + assertThat(advised).isEqualTo(expectedSource); ++activates; } @Override public void adviceChanged(AdvisedSupport advised) { - assertEquals(expectedSource, advised); + assertThat(advised).isEqualTo(expectedSource); ++adviceChanges; } } @@ -2008,9 +2005,8 @@ public abstract class AbstractAopProxyTests { static class InvocationCheckExposedInvocationTestBean extends ExposedInvocationTestBean { @Override protected void assertions(MethodInvocation invocation) { - assertSame(this, invocation.getThis()); - assertTrue("Invocation should be on ITestBean: " + invocation.getMethod(), - ITestBean.class.isAssignableFrom(invocation.getMethod().getDeclaringClass())); + assertThat(invocation.getThis()).isSameAs(this); + assertThat(ITestBean.class.isAssignableFrom(invocation.getMethod().getDeclaringClass())).as("Invocation should be on ITestBean: " + invocation.getMethod()).isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java index 25697b779e0..777e523844c 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java @@ -39,10 +39,6 @@ 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.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Additional and overridden tests for CGLIB proxies. @@ -64,7 +60,7 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab protected Object createProxy(ProxyCreatorSupport as) { as.setProxyTargetClass(true); Object proxy = as.createAopProxy().getProxy(); - assertTrue(AopUtils.isCglibProxy(proxy)); + assertThat(AopUtils.isCglibProxy(proxy)).isTrue(); return proxy; } @@ -107,9 +103,9 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab AopProxy aop = new CglibAopProxy(as); ProtectedMethodTestBean proxy = (ProtectedMethodTestBean) aop.getProxy(); - assertTrue(AopUtils.isCglibProxy(proxy)); - assertEquals(proxy.getClass().getClassLoader(), bean.getClass().getClassLoader()); - assertEquals("foo", proxy.getString()); + assertThat(AopUtils.isCglibProxy(proxy)).isTrue(); + assertThat(bean.getClass().getClassLoader()).isEqualTo(proxy.getClass().getClassLoader()); + assertThat(proxy.getString()).isEqualTo("foo"); } @Test @@ -124,9 +120,9 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab AopProxy aop = new CglibAopProxy(as); PackageMethodTestBean proxy = (PackageMethodTestBean) aop.getProxy(); - assertTrue(AopUtils.isCglibProxy(proxy)); - assertEquals(proxy.getClass().getClassLoader(), bean.getClass().getClassLoader()); - assertEquals("foo", proxy.getString()); + assertThat(AopUtils.isCglibProxy(proxy)).isTrue(); + assertThat(bean.getClass().getClassLoader()).isEqualTo(proxy.getClass().getClassLoader()); + assertThat(proxy.getString()).isEqualTo("foo"); } @Test @@ -139,12 +135,12 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab AopProxy aop = new CglibAopProxy(pc); Object proxy = aop.getProxy(); - assertTrue(AopUtils.isCglibProxy(proxy)); - assertTrue(proxy instanceof ITestBean); - assertTrue(proxy instanceof TestBean); + assertThat(AopUtils.isCglibProxy(proxy)).isTrue(); + assertThat(proxy instanceof ITestBean).isTrue(); + assertThat(proxy instanceof TestBean).isTrue(); TestBean tb = (TestBean) proxy; - assertEquals(32, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(32); } @Test @@ -158,7 +154,7 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab AopProxy aop = new CglibAopProxy(as); CglibTestBean proxy = (CglibTestBean) aop.getProxy(); - assertEquals("The name property has been overwritten by the constructor", "Rob Harrop", proxy.getName()); + assertThat(proxy.getName()).as("The name property has been overwritten by the constructor").isEqualTo("Rob Harrop"); } @Test @@ -172,7 +168,7 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab AopProxy aop = new CglibAopProxy(as); PrivateCglibTestBean proxy = (PrivateCglibTestBean) aop.getProxy(); - assertEquals("The name property has been overwritten by the constructor", "Rob Harrop", proxy.toString()); + assertThat(proxy.toString()).as("The name property has been overwritten by the constructor").isEqualTo("Rob Harrop"); } @Test @@ -186,8 +182,8 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab CglibAopProxy aop = new CglibAopProxy(pc); CglibTestBean proxy = (CglibTestBean) aop.getProxy(); - assertNotNull("Proxy should not be null", proxy); - assertEquals("Constructor overrode the value of name", "Rob Harrop", proxy.getName()); + assertThat(proxy).as("Proxy should not be null").isNotNull(); + assertThat(proxy.getName()).as("Constructor overrode the value of name").isEqualTo("Rob Harrop"); } @Test @@ -199,9 +195,9 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab ITestBean proxy1 = getAdvisedProxy(target); ITestBean proxy2 = getAdvisedProxy(target2); - assertSame(proxy1.getClass(), proxy2.getClass()); - assertEquals(target.getAge(), proxy1.getAge()); - assertEquals(target2.getAge(), proxy2.getAge()); + assertThat(proxy2.getClass()).isSameAs(proxy1.getClass()); + assertThat(proxy1.getAge()).isEqualTo(target.getAge()); + assertThat(proxy2.getAge()).isEqualTo(target2.getAge()); } private ITestBean getAdvisedProxy(TestBean target) { @@ -245,7 +241,7 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab ITestBean proxy1 = getIntroductionAdvisorProxy(target1); ITestBean proxy2 = getIntroductionAdvisorProxy(target2); - assertSame("Incorrect duplicate creation of proxy classes", proxy1.getClass(), proxy2.getClass()); + assertThat(proxy2.getClass()).as("Incorrect duplicate creation of proxy classes").isSameAs(proxy1.getClass()); } private ITestBean getIntroductionAdvisorProxy(TestBean target) { @@ -272,7 +268,7 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab aop.setConstructorArguments(new Object[] {"Rob Harrop", 22}, new Class[] {String.class, int.class}); NoArgCtorTestBean proxy = (NoArgCtorTestBean) aop.getProxy(); - assertNotNull(proxy); + assertThat(proxy).isNotNull(); } @Test @@ -316,7 +312,7 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab cglib = new CglibAopProxy(as); ITestBean proxy2 = (ITestBean) cglib.getProxy(); - assertTrue(proxy2 instanceof Serializable); + assertThat(proxy2 instanceof Serializable).isTrue(); } @Test @@ -335,11 +331,11 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab proxy.doTest(); } catch (Exception ex) { - assertTrue("Invalid exception class", ex instanceof ApplicationContextException); + assertThat(ex instanceof ApplicationContextException).as("Invalid exception class").isTrue(); } - assertTrue("Catch was not invoked", proxy.isCatchInvoked()); - assertTrue("Finally was not invoked", proxy.isFinallyInvoked()); + assertThat(proxy.isCatchInvoked()).as("Catch was not invoked").isTrue(); + assertThat(proxy.isFinallyInvoked()).as("Finally was not invoked").isTrue(); } @Test @@ -361,14 +357,14 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab pf.setProxyTargetClass(true); TestBean proxy = (TestBean) pf.getProxy(); - assertTrue(AopUtils.isCglibProxy(proxy)); + assertThat(AopUtils.isCglibProxy(proxy)).isTrue(); proxy.getAge(); - assertEquals(0, cba.getCalls()); + assertThat(cba.getCalls()).isEqualTo(0); ((Advised) proxy).addAdvice(cba); proxy.getAge(); - assertEquals(1, cba.getCalls()); + assertThat(cba.getCalls()).isEqualTo(1); } @Test @@ -379,22 +375,22 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab proxyFactory.setProxyTargetClass(true); MyBean proxy = (MyBean) proxyFactory.getProxy(); - assertEquals(4, proxy.add(1, 3)); - assertEquals(1, advice.getCalls("add")); + assertThat(proxy.add(1, 3)).isEqualTo(4); + assertThat(advice.getCalls("add")).isEqualTo(1); } @Test public void testProxyTargetClassInCaseOfNoInterfaces() { ProxyFactory proxyFactory = new ProxyFactory(new MyBean()); MyBean proxy = (MyBean) proxyFactory.getProxy(); - assertEquals(4, proxy.add(1, 3)); + assertThat(proxy.add(1, 3)).isEqualTo(4); } @Test // SPR-13328 public void testVarargsWithEnumArray() { ProxyFactory proxyFactory = new ProxyFactory(new MyBean()); MyBean proxy = (MyBean) proxyFactory.getProxy(); - assertTrue(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)); + assertThat(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java index 1d4a75f2f61..46613fdc88e 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java @@ -28,11 +28,8 @@ import org.springframework.tests.sample.beans.IOther; import org.springframework.tests.sample.beans.ITestBean; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -45,9 +42,9 @@ public class JdkDynamicProxyTests extends AbstractAopProxyTests implements Seria @Override protected Object createProxy(ProxyCreatorSupport as) { - assertFalse("Not forcible CGLIB", as.isProxyTargetClass()); + assertThat(as.isProxyTargetClass()).as("Not forcible CGLIB").isFalse(); Object proxy = as.createAopProxy().getProxy(); - assertTrue("Should be a JDK proxy: " + proxy.getClass(), AopUtils.isJdkDynamicProxy(proxy)); + assertThat(AopUtils.isJdkDynamicProxy(proxy)).as("Should be a JDK proxy: " + proxy.getClass()).isTrue(); return proxy; } @@ -72,8 +69,10 @@ public class JdkDynamicProxyTests extends AbstractAopProxyTests implements Seria JdkDynamicAopProxy aop = new JdkDynamicAopProxy(pc); Object proxy = aop.getProxy(); - assertTrue(proxy instanceof ITestBean); - assertFalse(proxy instanceof TestBean); + boolean condition = proxy instanceof ITestBean; + assertThat(condition).isTrue(); + boolean condition1 = proxy instanceof TestBean; + assertThat(condition1).isFalse(); } @Test @@ -87,7 +86,7 @@ public class JdkDynamicProxyTests extends AbstractAopProxyTests implements Seria AopProxy aop = createAopProxy(pc); ITestBean tb = (ITestBean) aop.getProxy(); - assertEquals("correct return value", age, tb.getAge()); + assertThat(tb.getAge()).as("correct return value").isEqualTo(age); } @Test @@ -95,9 +94,8 @@ public class JdkDynamicProxyTests extends AbstractAopProxyTests implements Seria final ExposedInvocationTestBean expectedTarget = new ExposedInvocationTestBean() { @Override protected void assertions(MethodInvocation invocation) { - assertEquals(this, invocation.getThis()); - assertEquals("Invocation should be on ITestBean: " + invocation.getMethod(), - ITestBean.class, invocation.getMethod().getDeclaringClass()); + assertThat(invocation.getThis()).isEqualTo(this); + assertThat(invocation.getMethod().getDeclaringClass()).as("Invocation should be on ITestBean: " + invocation.getMethod()).isEqualTo(ITestBean.class); } }; @@ -107,7 +105,7 @@ public class JdkDynamicProxyTests extends AbstractAopProxyTests implements Seria @Override public Object invoke(MethodInvocation invocation) throws Throwable { // Assert that target matches BEFORE invocation returns - assertEquals("Target is correct", expectedTarget, invocation.getThis()); + assertThat(invocation.getThis()).as("Target is correct").isEqualTo(expectedTarget); return super.invoke(invocation); } }; @@ -127,8 +125,8 @@ public class JdkDynamicProxyTests extends AbstractAopProxyTests implements Seria as.setTarget(bean); Foo proxy = (Foo) createProxy(as); - assertSame("Target should be returned when return types are incompatible", bean, proxy.getBarThis()); - assertSame("Proxy should be returned when return types are compatible", proxy, proxy.getFooThis()); + assertThat(proxy.getBarThis()).as("Target should be returned when return types are incompatible").isSameAs(bean); + assertThat(proxy.getFooThis()).as("Proxy should be returned when return types are compatible").isSameAs(proxy); } @Test @@ -138,15 +136,15 @@ public class JdkDynamicProxyTests extends AbstractAopProxyTests implements Seria JdkDynamicAopProxy aopProxy = new JdkDynamicAopProxy(as); Named proxy = (Named) aopProxy.getProxy(); Named named = new Person(); - assertEquals("equals()", proxy, named); - assertEquals("hashCode()", proxy.hashCode(), named.hashCode()); + assertThat(proxy).isEqualTo(named); + assertThat(named.hashCode()).isEqualTo(proxy.hashCode()); } @Test // SPR-13328 public void testVarargsWithEnumArray() { ProxyFactory proxyFactory = new ProxyFactory(new VarargTestBean()); VarargTestInterface proxy = (VarargTestInterface) proxyFactory.getProxy(); - assertTrue(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)); + assertThat(proxy.doWithVarargs(MyEnum.A, MyOtherEnum.C)).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java index bb42c61a85e..7ccc2f17b93 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java @@ -63,12 +63,6 @@ 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.assertThatIOException; -import static org.junit.Assert.assertArrayEquals; -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 13.03.2003 @@ -109,25 +103,25 @@ public class ProxyFactoryBeanTests { @Test public void testIsDynamicProxyWhenInterfaceSpecified() { ITestBean test1 = (ITestBean) factory.getBean("test1"); - assertTrue("test1 is a dynamic proxy", Proxy.isProxyClass(test1.getClass())); + assertThat(Proxy.isProxyClass(test1.getClass())).as("test1 is a dynamic proxy").isTrue(); } @Test public void testIsDynamicProxyWhenInterfaceSpecifiedForPrototype() { ITestBean test1 = (ITestBean) factory.getBean("test2"); - assertTrue("test2 is a dynamic proxy", Proxy.isProxyClass(test1.getClass())); + assertThat(Proxy.isProxyClass(test1.getClass())).as("test2 is a dynamic proxy").isTrue(); } @Test public void testIsDynamicProxyWhenAutodetectingInterfaces() { ITestBean test1 = (ITestBean) factory.getBean("test3"); - assertTrue("test3 is a dynamic proxy", Proxy.isProxyClass(test1.getClass())); + assertThat(Proxy.isProxyClass(test1.getClass())).as("test3 is a dynamic proxy").isTrue(); } @Test public void testIsDynamicProxyWhenAutodetectingInterfacesForPrototype() { ITestBean test1 = (ITestBean) factory.getBean("test4"); - assertTrue("test4 is a dynamic proxy", Proxy.isProxyClass(test1.getClass())); + assertThat(Proxy.isProxyClass(test1.getClass())).as("test4 is a dynamic proxy").isTrue(); } /** @@ -167,14 +161,14 @@ public class ProxyFactoryBeanTests { // We have a counting before advice here CountingBeforeAdvice cba = (CountingBeforeAdvice) bf.getBean("countingBeforeAdvice"); - assertEquals(0, cba.getCalls()); + assertThat(cba.getCalls()).isEqualTo(0); ITestBean tb = (ITestBean) bf.getBean("directTarget"); - assertTrue(tb.getName().equals("Adam")); - assertEquals(1, cba.getCalls()); + assertThat(tb.getName().equals("Adam")).isTrue(); + assertThat(cba.getCalls()).isEqualTo(1); ProxyFactoryBean pfb = (ProxyFactoryBean) bf.getBean("&directTarget"); - assertTrue("Has correct object type", TestBean.class.isAssignableFrom(pfb.getObjectType())); + assertThat(TestBean.class.isAssignableFrom(pfb.getObjectType())).as("Has correct object type").isTrue(); } @Test @@ -182,9 +176,9 @@ public class ProxyFactoryBeanTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(TARGETSOURCE_CONTEXT, CLASS)); ITestBean tb = (ITestBean) bf.getBean("viaTargetSource"); - assertTrue(tb.getName().equals("Adam")); + assertThat(tb.getName().equals("Adam")).isTrue(); ProxyFactoryBean pfb = (ProxyFactoryBean) bf.getBean("&viaTargetSource"); - assertTrue("Has correct object type", TestBean.class.isAssignableFrom(pfb.getObjectType())); + assertThat(TestBean.class.isAssignableFrom(pfb.getObjectType())).as("Has correct object type").isTrue(); } @Test @@ -197,7 +191,7 @@ public class ProxyFactoryBeanTests { tb.getName()) .withMessage("getName"); FactoryBean pfb = (ProxyFactoryBean) bf.getBean("&noTarget"); - assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(pfb.getObjectType())); + assertThat(ITestBean.class.isAssignableFrom(pfb.getObjectType())).as("Has correct object type").isTrue(); } /** @@ -209,33 +203,33 @@ public class ProxyFactoryBeanTests { ITestBean test1 = (ITestBean) factory.getBean("test1"); ITestBean test1_1 = (ITestBean) factory.getBean("test1"); //assertTrue("Singleton instances ==", test1 == test1_1); - assertEquals("Singleton instances ==", test1, test1_1); + assertThat(test1_1).as("Singleton instances ==").isEqualTo(test1); test1.setAge(25); - assertEquals(test1.getAge(), test1_1.getAge()); + assertThat(test1_1.getAge()).isEqualTo(test1.getAge()); test1.setAge(250); - assertEquals(test1.getAge(), test1_1.getAge()); + assertThat(test1_1.getAge()).isEqualTo(test1.getAge()); Advised pc1 = (Advised) test1; Advised pc2 = (Advised) test1_1; - assertArrayEquals(pc1.getAdvisors(), pc2.getAdvisors()); + assertThat(pc2.getAdvisors()).isEqualTo(pc1.getAdvisors()); int oldLength = pc1.getAdvisors().length; NopInterceptor di = new NopInterceptor(); pc1.addAdvice(1, di); - assertArrayEquals(pc1.getAdvisors(), pc2.getAdvisors()); - assertEquals("Now have one more advisor", oldLength + 1, pc2.getAdvisors().length); - assertEquals(di.getCount(), 0); + assertThat(pc2.getAdvisors()).isEqualTo(pc1.getAdvisors()); + assertThat(pc2.getAdvisors().length).as("Now have one more advisor").isEqualTo((oldLength + 1)); + assertThat(0).isEqualTo(di.getCount()); test1.setAge(5); - assertEquals(test1_1.getAge(), test1.getAge()); - assertEquals(di.getCount(), 3); + assertThat(test1.getAge()).isEqualTo(test1_1.getAge()); + assertThat(3).isEqualTo(di.getCount()); } @Test public void testPrototypeInstancesAreNotEqual() { - assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(factory.getType("prototype"))); + assertThat(ITestBean.class.isAssignableFrom(factory.getType("prototype"))).as("Has correct object type").isTrue(); ITestBean test2 = (ITestBean) factory.getBean("prototype"); ITestBean test2_1 = (ITestBean) factory.getBean("prototype"); - assertTrue("Prototype instances !=", test2 != test2_1); - assertTrue("Prototype instances equal", test2.equals(test2_1)); - assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(factory.getType("prototype"))); + assertThat(test2 != test2_1).as("Prototype instances !=").isTrue(); + assertThat(test2.equals(test2_1)).as("Prototype instances equal").isTrue(); + assertThat(ITestBean.class.isAssignableFrom(factory.getType("prototype"))).as("Has correct object type").isTrue(); } /** @@ -252,22 +246,22 @@ public class ProxyFactoryBeanTests { // Check it works without AOP SideEffectBean raw = (SideEffectBean) bf.getBean("prototypeTarget"); - assertEquals(INITIAL_COUNT, raw.getCount()); + assertThat(raw.getCount()).isEqualTo(INITIAL_COUNT); raw.doWork(); - assertEquals(INITIAL_COUNT+1, raw.getCount()); + assertThat(raw.getCount()).isEqualTo(INITIAL_COUNT+1); raw = (SideEffectBean) bf.getBean("prototypeTarget"); - assertEquals(INITIAL_COUNT, raw.getCount()); + assertThat(raw.getCount()).isEqualTo(INITIAL_COUNT); // Now try with advised instances SideEffectBean prototype2FirstInstance = (SideEffectBean) bf.getBean(beanName); - assertEquals(INITIAL_COUNT, prototype2FirstInstance.getCount()); + assertThat(prototype2FirstInstance.getCount()).isEqualTo(INITIAL_COUNT); prototype2FirstInstance.doWork(); - assertEquals(INITIAL_COUNT + 1, prototype2FirstInstance.getCount()); + assertThat(prototype2FirstInstance.getCount()).isEqualTo(INITIAL_COUNT + 1); SideEffectBean prototype2SecondInstance = (SideEffectBean) bf.getBean(beanName); - assertFalse("Prototypes are not ==", prototype2FirstInstance == prototype2SecondInstance); - assertEquals(INITIAL_COUNT, prototype2SecondInstance.getCount()); - assertEquals(INITIAL_COUNT + 1, prototype2FirstInstance.getCount()); + assertThat(prototype2FirstInstance == prototype2SecondInstance).as("Prototypes are not ==").isFalse(); + assertThat(prototype2SecondInstance.getCount()).isEqualTo(INITIAL_COUNT); + assertThat(prototype2FirstInstance.getCount()).isEqualTo(INITIAL_COUNT + 1); return prototype2FirstInstance; } @@ -275,8 +269,8 @@ public class ProxyFactoryBeanTests { @Test public void testCglibPrototypeInstance() { Object prototype = testPrototypeInstancesAreIndependent("cglibPrototype"); - assertTrue("It's a cglib proxy", AopUtils.isCglibProxy(prototype)); - assertFalse("It's not a dynamic proxy", AopUtils.isJdkDynamicProxy(prototype)); + assertThat(AopUtils.isCglibProxy(prototype)).as("It's a cglib proxy").isTrue(); + assertThat(AopUtils.isJdkDynamicProxy(prototype)).as("It's not a dynamic proxy").isFalse(); } /** @@ -288,19 +282,19 @@ public class ProxyFactoryBeanTests { TestBean target = (TestBean) factory.getBean("test"); target.setName(name); ITestBean autoInvoker = (ITestBean) factory.getBean("autoInvoker"); - assertTrue(autoInvoker.getName().equals(name)); + assertThat(autoInvoker.getName().equals(name)).isTrue(); } @Test public void testCanGetFactoryReferenceAndManipulate() { ProxyFactoryBean config = (ProxyFactoryBean) factory.getBean("&test1"); - assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(config.getObjectType())); - assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(factory.getType("test1"))); + assertThat(ITestBean.class.isAssignableFrom(config.getObjectType())).as("Has correct object type").isTrue(); + assertThat(ITestBean.class.isAssignableFrom(factory.getType("test1"))).as("Has correct object type").isTrue(); // Trigger lazy initialization. config.getObject(); - assertEquals("Have one advisors", 1, config.getAdvisors().length); - assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(config.getObjectType())); - assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(factory.getType("test1"))); + assertThat(config.getAdvisors().length).as("Have one advisors").isEqualTo(1); + assertThat(ITestBean.class.isAssignableFrom(config.getObjectType())).as("Has correct object type").isTrue(); + assertThat(ITestBean.class.isAssignableFrom(factory.getType("test1"))).as("Has correct object type").isTrue(); ITestBean tb = (ITestBean) factory.getBean("test1"); // no exception @@ -314,7 +308,7 @@ public class ProxyFactoryBeanTests { throw ex; } }); - assertEquals("Have correct advisor count", 2, config.getAdvisors().length); + assertThat(config.getAdvisors().length).as("Have correct advisor count").isEqualTo(2); ITestBean tb1 = (ITestBean) factory.getBean("test1"); assertThatExceptionOfType(Exception.class).isThrownBy( @@ -331,10 +325,10 @@ public class ProxyFactoryBeanTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(INNER_BEAN_TARGET_CONTEXT, CLASS)); ITestBean itb = (ITestBean) bf.getBean("testBean"); - assertEquals("innerBeanTarget", itb.getName()); - assertEquals("Only have proxy and interceptor: no target", 3, bf.getBeanDefinitionCount()); + assertThat(itb.getName()).isEqualTo("innerBeanTarget"); + assertThat(bf.getBeanDefinitionCount()).as("Only have proxy and interceptor: no target").isEqualTo(3); DependsOnITestBean doit = (DependsOnITestBean) bf.getBean("autowireCheck"); - assertSame(itb, doit.tb); + assertThat(doit.tb).isSameAs(itb); } /** @@ -354,47 +348,47 @@ public class ProxyFactoryBeanTests { // Add to head of interceptor chain int oldCount = config.getAdvisors().length; config.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class)); - assertTrue(config.getAdvisors().length == oldCount + 1); + assertThat(config.getAdvisors().length == oldCount + 1).isTrue(); TimeStamped ts = (TimeStamped) factory.getBean("test2"); - assertEquals(time, ts.getTimeStamp()); + assertThat(ts.getTimeStamp()).isEqualTo(time); // Can remove config.removeAdvice(ti); - assertTrue(config.getAdvisors().length == oldCount); + assertThat(config.getAdvisors().length == oldCount).isTrue(); // Check no change on existing object reference - assertTrue(ts.getTimeStamp() == time); + assertThat(ts.getTimeStamp() == time).isTrue(); assertThat(factory.getBean("test2")).as("Should no longer implement TimeStamped") .isNotInstanceOf(TimeStamped.class); // Now check non-effect of removing interceptor that isn't there config.removeAdvice(new DebugInterceptor()); - assertTrue(config.getAdvisors().length == oldCount); + assertThat(config.getAdvisors().length == oldCount).isTrue(); ITestBean it = (ITestBean) ts; DebugInterceptor debugInterceptor = new DebugInterceptor(); config.addAdvice(0, debugInterceptor); it.getSpouse(); // Won't affect existing reference - assertTrue(debugInterceptor.getCount() == 0); + assertThat(debugInterceptor.getCount() == 0).isTrue(); it = (ITestBean) factory.getBean("test2"); it.getSpouse(); - assertEquals(1, debugInterceptor.getCount()); + assertThat(debugInterceptor.getCount()).isEqualTo(1); config.removeAdvice(debugInterceptor); it.getSpouse(); // Still invoked with old reference - assertEquals(2, debugInterceptor.getCount()); + assertThat(debugInterceptor.getCount()).isEqualTo(2); // not invoked with new object it = (ITestBean) factory.getBean("test2"); it.getSpouse(); - assertEquals(2, debugInterceptor.getCount()); + assertThat(debugInterceptor.getCount()).isEqualTo(2); // Our own timestamped reference should still work - assertEquals(time, ts.getTimeStamp()); + assertThat(ts.getTimeStamp()).isEqualTo(time); } /** @@ -408,26 +402,26 @@ public class ProxyFactoryBeanTests { it.getAge(); NopInterceptor di = new NopInterceptor(); pc.addAdvice(0, di); - assertEquals(0, di.getCount()); + assertThat(di.getCount()).isEqualTo(0); it.setAge(25); - assertEquals(25, it.getAge()); - assertEquals(2, di.getCount()); + assertThat(it.getAge()).isEqualTo(25); + assertThat(di.getCount()).isEqualTo(2); } @Test public void testMethodPointcuts() { ITestBean tb = (ITestBean) factory.getBean("pointcuts"); PointcutForVoid.reset(); - assertTrue("No methods intercepted", PointcutForVoid.methodNames.isEmpty()); + assertThat(PointcutForVoid.methodNames.isEmpty()).as("No methods intercepted").isTrue(); tb.getAge(); - assertTrue("Not void: shouldn't have intercepted", PointcutForVoid.methodNames.isEmpty()); + assertThat(PointcutForVoid.methodNames.isEmpty()).as("Not void: shouldn't have intercepted").isTrue(); tb.setAge(1); tb.getAge(); tb.setName("Tristan"); tb.toString(); - assertEquals("Recorded wrong number of invocations", 2, PointcutForVoid.methodNames.size()); - assertTrue(PointcutForVoid.methodNames.get(0).equals("setAge")); - assertTrue(PointcutForVoid.methodNames.get(1).equals("setName")); + assertThat(PointcutForVoid.methodNames.size()).as("Recorded wrong number of invocations").isEqualTo(2); + assertThat(PointcutForVoid.methodNames.get(0).equals("setAge")).isTrue(); + assertThat(PointcutForVoid.methodNames.get(1).equals("setName")).isTrue(); } @Test @@ -436,20 +430,20 @@ public class ProxyFactoryBeanTests { new XmlBeanDefinitionReader(f).loadBeanDefinitions(new ClassPathResource(THROWS_ADVICE_CONTEXT, CLASS)); MyThrowsHandler th = (MyThrowsHandler) f.getBean("throwsAdvice"); CountingBeforeAdvice cba = (CountingBeforeAdvice) f.getBean("countingBeforeAdvice"); - assertEquals(0, cba.getCalls()); - assertEquals(0, th.getCalls()); + assertThat(cba.getCalls()).isEqualTo(0); + assertThat(th.getCalls()).isEqualTo(0); IEcho echo = (IEcho) f.getBean("throwsAdvised"); int i = 12; echo.setA(i); - assertEquals(i, echo.getA()); - assertEquals(2, cba.getCalls()); - assertEquals(0, th.getCalls()); + assertThat(echo.getA()).isEqualTo(i); + assertThat(cba.getCalls()).isEqualTo(2); + assertThat(th.getCalls()).isEqualTo(0); Exception expected = new Exception(); assertThatExceptionOfType(Exception.class).isThrownBy(() -> echo.echoException(1, expected)) .matches(expected::equals); // No throws handler method: count should still be 0 - assertEquals(0, th.getCalls()); + assertThat(th.getCalls()).isEqualTo(0); // Handler knows how to handle this exception FileNotFoundException expectedFileNotFound = new FileNotFoundException(); @@ -458,7 +452,7 @@ public class ProxyFactoryBeanTests { .matches(expectedFileNotFound::equals); // One match - assertEquals(1, th.getCalls("ioException")); + assertThat(th.getCalls("ioException")).isEqualTo(1); } // These two fail the whole bean factory @@ -505,17 +499,17 @@ public class ProxyFactoryBeanTests { @Test public void testGlobalsCanAddAspectInterfaces() { AddedGlobalInterface agi = (AddedGlobalInterface) factory.getBean("autoInvoker"); - assertTrue(agi.globalsAdded() == -1); + assertThat(agi.globalsAdded() == -1).isTrue(); ProxyFactoryBean pfb = (ProxyFactoryBean) factory.getBean("&validGlobals"); // Trigger lazy initialization. pfb.getObject(); // 2 globals + 2 explicit - assertEquals("Have 2 globals and 2 explicit advisors", 3, pfb.getAdvisors().length); + assertThat(pfb.getAdvisors().length).as("Have 2 globals and 2 explicit advisors").isEqualTo(3); ApplicationListener l = (ApplicationListener) factory.getBean("validGlobals"); agi = (AddedGlobalInterface) l; - assertTrue(agi.globalsAdded() == -1); + assertThat(agi.globalsAdded() == -1).isTrue(); assertThat(factory.getBean("test1")).as("Aspect interface should't be implemeneted without globals") .isNotInstanceOf(AddedGlobalInterface.class); @@ -526,22 +520,22 @@ public class ProxyFactoryBeanTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(SERIALIZATION_CONTEXT, CLASS)); Person p = (Person) bf.getBean("serializableSingleton"); - assertSame("Should be a Singleton", p, bf.getBean("serializableSingleton")); + assertThat(bf.getBean("serializableSingleton")).as("Should be a Singleton").isSameAs(p); Person p2 = (Person) SerializationTestUtils.serializeAndDeserialize(p); - assertEquals(p, p2); - assertNotSame(p, p2); - assertEquals("serializableSingleton", p2.getName()); + assertThat(p2).isEqualTo(p); + assertThat(p2).isNotSameAs(p); + assertThat(p2.getName()).isEqualTo("serializableSingleton"); // Add unserializable advice Advice nop = new NopInterceptor(); ((Advised) p).addAdvice(nop); // Check it still works - assertEquals(p2.getName(), p2.getName()); - assertFalse("Not serializable because an interceptor isn't serializable", SerializationTestUtils.isSerializable(p)); + assertThat(p2.getName()).isEqualTo(p2.getName()); + assertThat(SerializationTestUtils.isSerializable(p)).as("Not serializable because an interceptor isn't serializable").isFalse(); // Remove offending interceptor... - assertTrue(((Advised) p).removeAdvice(nop)); - assertTrue("Serializable again because offending interceptor was removed", SerializationTestUtils.isSerializable(p)); + assertThat(((Advised) p).removeAdvice(nop)).isTrue(); + assertThat(SerializationTestUtils.isSerializable(p)).as("Serializable again because offending interceptor was removed").isTrue(); } @Test @@ -549,11 +543,11 @@ public class ProxyFactoryBeanTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(SERIALIZATION_CONTEXT, CLASS)); Person p = (Person) bf.getBean("serializablePrototype"); - assertNotSame("Should not be a Singleton", p, bf.getBean("serializablePrototype")); + assertThat(bf.getBean("serializablePrototype")).as("Should not be a Singleton").isNotSameAs(p); Person p2 = (Person) SerializationTestUtils.serializeAndDeserialize(p); - assertEquals(p, p2); - assertNotSame(p, p2); - assertEquals("serializablePrototype", p2.getName()); + assertThat(p2).isEqualTo(p); + assertThat(p2).isNotSameAs(p); + assertThat(p2.getName()).isEqualTo("serializablePrototype"); } @Test @@ -564,9 +558,9 @@ public class ProxyFactoryBeanTests { ProxyFactoryBean pfb = (ProxyFactoryBean) bf.getBean("&serializableSingleton"); ProxyFactoryBean pfb2 = (ProxyFactoryBean) SerializationTestUtils.serializeAndDeserialize(pfb); Person p2 = (Person) pfb2.getObject(); - assertEquals(p, p2); - assertNotSame(p, p2); - assertEquals("serializableSingleton", p2.getName()); + assertThat(p2).isEqualTo(p); + assertThat(p2).isNotSameAs(p); + assertThat(p2.getName()).isEqualTo("serializableSingleton"); } @Test @@ -574,7 +568,7 @@ public class ProxyFactoryBeanTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(SERIALIZATION_CONTEXT, CLASS)); Person p = (Person) bf.getBean("interceptorNotSerializableSingleton"); - assertFalse("Not serializable because an interceptor isn't serializable", SerializationTestUtils.isSerializable(p)); + assertThat(SerializationTestUtils.isSerializable(p)).as("Not serializable because an interceptor isn't serializable").isFalse(); } @Test @@ -588,8 +582,8 @@ public class ProxyFactoryBeanTests { bean1.setAge(3); bean2.setAge(4); - assertEquals(3, bean1.getAge()); - assertEquals(4, bean2.getAge()); + assertThat(bean1.getAge()).isEqualTo(3); + assertThat(bean2.getAge()).isEqualTo(4); ((Lockable) bean1).lock(); @@ -610,7 +604,7 @@ public class ProxyFactoryBeanTests { bean1.setAge(1); bean2.setAge(2); - assertEquals(2, bean1.getAge()); + assertThat(bean1.getAge()).isEqualTo(2); ((Lockable) bean1).lock(); @@ -638,7 +632,7 @@ public class ProxyFactoryBeanTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(FROZEN_CONTEXT, CLASS)); Advised advised = (Advised)bf.getBean("frozen"); - assertTrue("The proxy should be frozen", advised.isFrozen()); + assertThat(advised.isFrozen()).as("The proxy should be frozen").isTrue(); } @Test @@ -648,7 +642,7 @@ public class ProxyFactoryBeanTests { fb.addAdvice(new DebugInterceptor()); fb.setBeanFactory(new DefaultListableBeanFactory()); ITestBean proxy = (ITestBean) fb.getObject(); - assertTrue(AopUtils.isJdkDynamicProxy(proxy)); + assertThat(AopUtils.isJdkDynamicProxy(proxy)).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests.java b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests.java index 1dc8e440c29..dd3375dd54e 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests.java @@ -37,9 +37,7 @@ import org.springframework.tests.aop.interceptor.NopInterceptor; import org.springframework.tests.sample.beans.CountingTestBean; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for auto proxy creation by advisor recognition. @@ -80,7 +78,7 @@ public class AdvisorAutoProxyCreatorTests { public void testCommonInterceptorAndAdvisor() throws Exception { BeanFactory bf = new ClassPathXmlApplicationContext(COMMON_INTERCEPTORS_CONTEXT, CLASS); ITestBean test1 = (ITestBean) bf.getBean("test1"); - assertTrue(AopUtils.isAopProxy(test1)); + assertThat(AopUtils.isAopProxy(test1)).isTrue(); Lockable lockable1 = (Lockable) test1; NopInterceptor nop1 = (NopInterceptor) bf.getBean("nopInterceptor"); @@ -90,30 +88,31 @@ public class AdvisorAutoProxyCreatorTests { Lockable lockable2 = (Lockable) test2; // Locking should be independent; nop is shared - assertFalse(lockable1.locked()); - assertFalse(lockable2.locked()); + assertThat(lockable1.locked()).isFalse(); + assertThat(lockable2.locked()).isFalse(); // equals 2 calls on shared nop, because it's first and sees calls // against the Lockable interface introduced by the specific advisor - assertEquals(2, nop1.getCount()); - assertEquals(0, nop2.getCount()); + assertThat(nop1.getCount()).isEqualTo(2); + assertThat(nop2.getCount()).isEqualTo(0); lockable1.lock(); - assertTrue(lockable1.locked()); - assertFalse(lockable2.locked()); - assertEquals(5, nop1.getCount()); - assertEquals(0, nop2.getCount()); + assertThat(lockable1.locked()).isTrue(); + assertThat(lockable2.locked()).isFalse(); + assertThat(nop1.getCount()).isEqualTo(5); + assertThat(nop2.getCount()).isEqualTo(0); PackageVisibleMethod packageVisibleMethod = (PackageVisibleMethod) bf.getBean("packageVisibleMethod"); - assertEquals(5, nop1.getCount()); - assertEquals(0, nop2.getCount()); + assertThat(nop1.getCount()).isEqualTo(5); + assertThat(nop2.getCount()).isEqualTo(0); packageVisibleMethod.doSomething(); - assertEquals(6, nop1.getCount()); - assertEquals(1, nop2.getCount()); - assertTrue(packageVisibleMethod instanceof Lockable); + assertThat(nop1.getCount()).isEqualTo(6); + assertThat(nop2.getCount()).isEqualTo(1); + boolean condition = packageVisibleMethod instanceof Lockable; + assertThat(condition).isTrue(); Lockable lockable3 = (Lockable) packageVisibleMethod; lockable3.lock(); - assertTrue(lockable3.locked()); + assertThat(lockable3.locked()).isTrue(); lockable3.unlock(); - assertFalse(lockable3.locked()); + assertThat(lockable3.locked()).isFalse(); } /** @@ -124,9 +123,9 @@ public class AdvisorAutoProxyCreatorTests { public void testCustomTargetSourceNoMatch() throws Exception { BeanFactory bf = new ClassPathXmlApplicationContext(CUSTOM_TARGETSOURCE_CONTEXT, CLASS); ITestBean test = (ITestBean) bf.getBean("test"); - assertFalse(AopUtils.isAopProxy(test)); - assertEquals("Rod", test.getName()); - assertEquals("Kerry", test.getSpouse().getName()); + assertThat(AopUtils.isAopProxy(test)).isFalse(); + assertThat(test.getName()).isEqualTo("Rod"); + assertThat(test.getSpouse().getName()).isEqualTo("Kerry"); } @Test @@ -134,13 +133,14 @@ public class AdvisorAutoProxyCreatorTests { CountingTestBean.count = 0; BeanFactory bf = new ClassPathXmlApplicationContext(CUSTOM_TARGETSOURCE_CONTEXT, CLASS); ITestBean test = (ITestBean) bf.getBean("prototypeTest"); - assertTrue(AopUtils.isAopProxy(test)); + assertThat(AopUtils.isAopProxy(test)).isTrue(); Advised advised = (Advised) test; - assertTrue(advised.getTargetSource() instanceof PrototypeTargetSource); - assertEquals("Rod", test.getName()); + boolean condition = advised.getTargetSource() instanceof PrototypeTargetSource; + assertThat(condition).isTrue(); + assertThat(test.getName()).isEqualTo("Rod"); // Check that references survived prototype creation - assertEquals("Kerry", test.getSpouse().getName()); - assertEquals("Only 2 CountingTestBeans instantiated", 2, CountingTestBean.count); + assertThat(test.getSpouse().getName()).isEqualTo("Kerry"); + assertThat(CountingTestBean.count).as("Only 2 CountingTestBeans instantiated").isEqualTo(2); CountingTestBean.count = 0; } @@ -149,13 +149,14 @@ public class AdvisorAutoProxyCreatorTests { CountingTestBean.count = 0; BeanFactory bf = new ClassPathXmlApplicationContext(CUSTOM_TARGETSOURCE_CONTEXT, CLASS); ITestBean test = (ITestBean) bf.getBean("lazyInitTest"); - assertTrue(AopUtils.isAopProxy(test)); + assertThat(AopUtils.isAopProxy(test)).isTrue(); Advised advised = (Advised) test; - assertTrue(advised.getTargetSource() instanceof LazyInitTargetSource); - assertEquals("No CountingTestBean instantiated yet", 0, CountingTestBean.count); - assertEquals("Rod", test.getName()); - assertEquals("Kerry", test.getSpouse().getName()); - assertEquals("Only 1 CountingTestBean instantiated", 1, CountingTestBean.count); + boolean condition = advised.getTargetSource() instanceof LazyInitTargetSource; + assertThat(condition).isTrue(); + assertThat(CountingTestBean.count).as("No CountingTestBean instantiated yet").isEqualTo(0); + assertThat(test.getName()).isEqualTo("Rod"); + assertThat(test.getSpouse().getName()).isEqualTo("Kerry"); + assertThat(CountingTestBean.count).as("Only 1 CountingTestBean instantiated").isEqualTo(1); CountingTestBean.count = 0; } @@ -164,43 +165,46 @@ public class AdvisorAutoProxyCreatorTests { ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(QUICK_TARGETSOURCE_CONTEXT, CLASS); ITestBean test = (ITestBean) bf.getBean("test"); - assertFalse(AopUtils.isAopProxy(test)); - assertEquals("Rod", test.getName()); + assertThat(AopUtils.isAopProxy(test)).isFalse(); + assertThat(test.getName()).isEqualTo("Rod"); // Check that references survived pooling - assertEquals("Kerry", test.getSpouse().getName()); + assertThat(test.getSpouse().getName()).isEqualTo("Kerry"); // Now test the pooled one test = (ITestBean) bf.getBean(":test"); - assertTrue(AopUtils.isAopProxy(test)); + assertThat(AopUtils.isAopProxy(test)).isTrue(); Advised advised = (Advised) test; - assertTrue(advised.getTargetSource() instanceof CommonsPool2TargetSource); - assertEquals("Rod", test.getName()); + boolean condition2 = advised.getTargetSource() instanceof CommonsPool2TargetSource; + assertThat(condition2).isTrue(); + assertThat(test.getName()).isEqualTo("Rod"); // Check that references survived pooling - assertEquals("Kerry", test.getSpouse().getName()); + assertThat(test.getSpouse().getName()).isEqualTo("Kerry"); // Now test the ThreadLocal one test = (ITestBean) bf.getBean("%test"); - assertTrue(AopUtils.isAopProxy(test)); + assertThat(AopUtils.isAopProxy(test)).isTrue(); advised = (Advised) test; - assertTrue(advised.getTargetSource() instanceof ThreadLocalTargetSource); - assertEquals("Rod", test.getName()); + boolean condition1 = advised.getTargetSource() instanceof ThreadLocalTargetSource; + assertThat(condition1).isTrue(); + assertThat(test.getName()).isEqualTo("Rod"); // Check that references survived pooling - assertEquals("Kerry", test.getSpouse().getName()); + assertThat(test.getSpouse().getName()).isEqualTo("Kerry"); // Now test the Prototype TargetSource test = (ITestBean) bf.getBean("!test"); - assertTrue(AopUtils.isAopProxy(test)); + assertThat(AopUtils.isAopProxy(test)).isTrue(); advised = (Advised) test; - assertTrue(advised.getTargetSource() instanceof PrototypeTargetSource); - assertEquals("Rod", test.getName()); + boolean condition = advised.getTargetSource() instanceof PrototypeTargetSource; + assertThat(condition).isTrue(); + assertThat(test.getName()).isEqualTo("Rod"); // Check that references survived pooling - assertEquals("Kerry", test.getSpouse().getName()); + assertThat(test.getSpouse().getName()).isEqualTo("Kerry"); ITestBean test2 = (ITestBean) bf.getBean("!test"); - assertFalse("Prototypes cannot be the same object", test == test2); - assertEquals("Rod", test2.getName()); - assertEquals("Kerry", test2.getSpouse().getName()); + assertThat(test == test2).as("Prototypes cannot be the same object").isFalse(); + assertThat(test2.getName()).isEqualTo("Rod"); + assertThat(test2.getSpouse().getName()).isEqualTo("Kerry"); bf.close(); } @@ -209,14 +213,14 @@ public class AdvisorAutoProxyCreatorTests { BeanFactory beanFactory = new ClassPathXmlApplicationContext(OPTIMIZED_CONTEXT, CLASS); ITestBean testBean = (ITestBean) beanFactory.getBean("optimizedTestBean"); - assertTrue(AopUtils.isAopProxy(testBean)); + assertThat(AopUtils.isAopProxy(testBean)).isTrue(); CountingBeforeAdvice beforeAdvice = (CountingBeforeAdvice) beanFactory.getBean("countingAdvice"); testBean.setAge(23); testBean.getAge(); - assertEquals("Incorrect number of calls to proxy", 2, beforeAdvice.getCalls()); + assertThat(beforeAdvice.getCalls()).as("Incorrect number of calls to proxy").isEqualTo(2); } } diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AutoProxyCreatorTests.java b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AutoProxyCreatorTests.java index 8a78d14c0a6..8aa6812ae76 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AutoProxyCreatorTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AutoProxyCreatorTests.java @@ -49,10 +49,7 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.factory.DummyFactory; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -85,31 +82,31 @@ public class AutoProxyCreatorTests { MessageSource messageSource = (MessageSource) sac.getBean("messageSource"); ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied"); - assertFalse(Proxy.isProxyClass(messageSource.getClass())); - assertTrue(Proxy.isProxyClass(singletonToBeProxied.getClass())); - assertTrue(Proxy.isProxyClass(singletonToBeProxied.getSpouse().getClass())); + assertThat(Proxy.isProxyClass(messageSource.getClass())).isFalse(); + assertThat(Proxy.isProxyClass(singletonToBeProxied.getClass())).isTrue(); + assertThat(Proxy.isProxyClass(singletonToBeProxied.getSpouse().getClass())).isTrue(); // test whether autowiring succeeded with auto proxy creation - assertEquals(sac.getBean("autowiredIndexedTestBean"), singletonToBeProxied.getNestedIndexedBean()); + assertThat(singletonToBeProxied.getNestedIndexedBean()).isEqualTo(sac.getBean("autowiredIndexedTestBean")); TestInterceptor ti = (TestInterceptor) sac.getBean("testInterceptor"); // already 2: getSpouse + getNestedIndexedBean calls above - assertEquals(2, ti.nrOfInvocations); + assertThat(ti.nrOfInvocations).isEqualTo(2); singletonToBeProxied.getName(); singletonToBeProxied.getSpouse().getName(); - assertEquals(5, ti.nrOfInvocations); + assertThat(ti.nrOfInvocations).isEqualTo(5); ITestBean tb = (ITestBean) sac.getBean("singletonFactoryToBeProxied"); - assertTrue(AopUtils.isJdkDynamicProxy(tb)); - assertEquals(5, ti.nrOfInvocations); + assertThat(AopUtils.isJdkDynamicProxy(tb)).isTrue(); + assertThat(ti.nrOfInvocations).isEqualTo(5); tb.getAge(); - assertEquals(6, ti.nrOfInvocations); + assertThat(ti.nrOfInvocations).isEqualTo(6); ITestBean tb2 = (ITestBean) sac.getBean("singletonFactoryToBeProxied"); - assertSame(tb, tb2); - assertEquals(6, ti.nrOfInvocations); + assertThat(tb2).isSameAs(tb); + assertThat(ti.nrOfInvocations).isEqualTo(6); tb2.getAge(); - assertEquals(7, ti.nrOfInvocations); + assertThat(ti.nrOfInvocations).isEqualTo(7); } @Test @@ -130,20 +127,20 @@ public class AutoProxyCreatorTests { sac.refresh(); ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied"); - assertTrue(Proxy.isProxyClass(singletonToBeProxied.getClass())); + assertThat(Proxy.isProxyClass(singletonToBeProxied.getClass())).isTrue(); TestInterceptor ti = (TestInterceptor) sac.getBean("testInterceptor"); int initialNr = ti.nrOfInvocations; singletonToBeProxied.getName(); - assertEquals(initialNr + 1, ti.nrOfInvocations); + assertThat(ti.nrOfInvocations).isEqualTo((initialNr + 1)); FactoryBean factory = (FactoryBean) sac.getBean("&singletonFactoryToBeProxied"); - assertTrue(Proxy.isProxyClass(factory.getClass())); + assertThat(Proxy.isProxyClass(factory.getClass())).isTrue(); TestBean tb = (TestBean) sac.getBean("singletonFactoryToBeProxied"); - assertFalse(AopUtils.isAopProxy(tb)); - assertEquals(initialNr + 3, ti.nrOfInvocations); + assertThat(AopUtils.isAopProxy(tb)).isFalse(); + assertThat(ti.nrOfInvocations).isEqualTo((initialNr + 3)); tb.getAge(); - assertEquals(initialNr + 3, ti.nrOfInvocations); + assertThat(ti.nrOfInvocations).isEqualTo((initialNr + 3)); } @Test @@ -164,21 +161,21 @@ public class AutoProxyCreatorTests { ITestBean singletonNoInterceptor = (ITestBean) sac.getBean("singletonNoInterceptor"); ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied"); ITestBean prototypeToBeProxied = (ITestBean) sac.getBean("prototypeToBeProxied"); - assertFalse(AopUtils.isCglibProxy(messageSource)); - assertTrue(AopUtils.isCglibProxy(noInterfaces)); - assertTrue(AopUtils.isCglibProxy(containerCallbackInterfacesOnly)); - assertTrue(AopUtils.isCglibProxy(singletonNoInterceptor)); - assertTrue(AopUtils.isCglibProxy(singletonToBeProxied)); - assertTrue(AopUtils.isCglibProxy(prototypeToBeProxied)); + assertThat(AopUtils.isCglibProxy(messageSource)).isFalse(); + assertThat(AopUtils.isCglibProxy(noInterfaces)).isTrue(); + assertThat(AopUtils.isCglibProxy(containerCallbackInterfacesOnly)).isTrue(); + assertThat(AopUtils.isCglibProxy(singletonNoInterceptor)).isTrue(); + assertThat(AopUtils.isCglibProxy(singletonToBeProxied)).isTrue(); + assertThat(AopUtils.isCglibProxy(prototypeToBeProxied)).isTrue(); TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator"); - assertEquals(0, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(0); singletonNoInterceptor.getName(); - assertEquals(0, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(0); singletonToBeProxied.getAge(); - assertEquals(1, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(1); prototypeToBeProxied.getSpouse(); - assertEquals(2, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(2); } @Test @@ -199,21 +196,21 @@ public class AutoProxyCreatorTests { ITestBean singletonNoInterceptor = (ITestBean) sac.getBean("singletonNoInterceptor"); ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied"); ITestBean prototypeToBeProxied = (ITestBean) sac.getBean("prototypeToBeProxied"); - assertFalse(AopUtils.isCglibProxy(messageSource)); - assertTrue(AopUtils.isCglibProxy(noInterfaces)); - assertTrue(AopUtils.isCglibProxy(containerCallbackInterfacesOnly)); - assertFalse(AopUtils.isCglibProxy(singletonNoInterceptor)); - assertFalse(AopUtils.isCglibProxy(singletonToBeProxied)); - assertFalse(AopUtils.isCglibProxy(prototypeToBeProxied)); + assertThat(AopUtils.isCglibProxy(messageSource)).isFalse(); + assertThat(AopUtils.isCglibProxy(noInterfaces)).isTrue(); + assertThat(AopUtils.isCglibProxy(containerCallbackInterfacesOnly)).isTrue(); + assertThat(AopUtils.isCglibProxy(singletonNoInterceptor)).isFalse(); + assertThat(AopUtils.isCglibProxy(singletonToBeProxied)).isFalse(); + assertThat(AopUtils.isCglibProxy(prototypeToBeProxied)).isFalse(); TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator"); - assertEquals(0, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(0); singletonNoInterceptor.getName(); - assertEquals(0, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(0); singletonToBeProxied.getAge(); - assertEquals(1, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(1); prototypeToBeProxied.getSpouse(); - assertEquals(2, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(2); } @Test @@ -239,21 +236,21 @@ public class AutoProxyCreatorTests { ITestBean singletonNoInterceptor = (ITestBean) sac.getBean("singletonNoInterceptor"); ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied"); ITestBean prototypeToBeProxied = (ITestBean) sac.getBean("prototypeToBeProxied"); - assertFalse(AopUtils.isCglibProxy(messageSource)); - assertTrue(AopUtils.isCglibProxy(noInterfaces)); - assertTrue(AopUtils.isCglibProxy(containerCallbackInterfacesOnly)); - assertFalse(AopUtils.isCglibProxy(singletonNoInterceptor)); - assertFalse(AopUtils.isCglibProxy(singletonToBeProxied)); - assertFalse(AopUtils.isCglibProxy(prototypeToBeProxied)); + assertThat(AopUtils.isCglibProxy(messageSource)).isFalse(); + assertThat(AopUtils.isCglibProxy(noInterfaces)).isTrue(); + assertThat(AopUtils.isCglibProxy(containerCallbackInterfacesOnly)).isTrue(); + assertThat(AopUtils.isCglibProxy(singletonNoInterceptor)).isFalse(); + assertThat(AopUtils.isCglibProxy(singletonToBeProxied)).isFalse(); + assertThat(AopUtils.isCglibProxy(prototypeToBeProxied)).isFalse(); TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator"); - assertEquals(0, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(0); singletonNoInterceptor.getName(); - assertEquals(0, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(0); singletonToBeProxied.getAge(); - assertEquals(1, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(1); prototypeToBeProxied.getSpouse(); - assertEquals(2, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(2); } @Test @@ -267,10 +264,10 @@ public class AutoProxyCreatorTests { tapc.testInterceptor.nrOfInvocations = 0; PackageVisibleMethod tb = (PackageVisibleMethod) sac.getBean("packageVisibleMethodToBeProxied"); - assertTrue(AopUtils.isCglibProxy(tb)); - assertEquals(0, tapc.testInterceptor.nrOfInvocations); + assertThat(AopUtils.isCglibProxy(tb)).isTrue(); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(0); tb.doSomething(); - assertEquals(1, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(1); } @Test @@ -284,13 +281,13 @@ public class AutoProxyCreatorTests { tapc.testInterceptor.nrOfInvocations = 0; FactoryBean factory = (FactoryBean) sac.getBean("&singletonFactoryToBeProxied"); - assertTrue(AopUtils.isCglibProxy(factory)); + assertThat(AopUtils.isCglibProxy(factory)).isTrue(); TestBean tb = (TestBean) sac.getBean("singletonFactoryToBeProxied"); - assertTrue(AopUtils.isCglibProxy(tb)); - assertEquals(2, tapc.testInterceptor.nrOfInvocations); + assertThat(AopUtils.isCglibProxy(tb)).isTrue(); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(2); tb.getAge(); - assertEquals(3, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(3); } @Test @@ -308,13 +305,13 @@ public class AutoProxyCreatorTests { tapc.testInterceptor.nrOfInvocations = 0; FactoryBean prototypeFactory = (FactoryBean) sac.getBean("&prototypeFactoryToBeProxied"); - assertTrue(AopUtils.isCglibProxy(prototypeFactory)); + assertThat(AopUtils.isCglibProxy(prototypeFactory)).isTrue(); TestBean tb = (TestBean) sac.getBean("prototypeFactoryToBeProxied"); - assertTrue(AopUtils.isCglibProxy(tb)); + assertThat(AopUtils.isCglibProxy(tb)).isTrue(); - assertEquals(2, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(2); tb.getAge(); - assertEquals(3, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(3); } @Test @@ -333,19 +330,19 @@ public class AutoProxyCreatorTests { tapc.testInterceptor.nrOfInvocations = 0; FactoryBean factory = (FactoryBean) sac.getBean("&singletonFactoryToBeProxied"); - assertFalse(AopUtils.isAopProxy(factory)); + assertThat(AopUtils.isAopProxy(factory)).isFalse(); TestBean tb = (TestBean) sac.getBean("singletonFactoryToBeProxied"); - assertTrue(AopUtils.isCglibProxy(tb)); - assertEquals(0, tapc.testInterceptor.nrOfInvocations); + assertThat(AopUtils.isCglibProxy(tb)).isTrue(); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(0); tb.getAge(); - assertEquals(1, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(1); TestBean tb2 = (TestBean) sac.getBean("singletonFactoryToBeProxied"); - assertSame(tb, tb2); - assertEquals(1, tapc.testInterceptor.nrOfInvocations); + assertThat(tb2).isSameAs(tb); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(1); tb2.getAge(); - assertEquals(2, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(2); } @Test @@ -366,13 +363,13 @@ public class AutoProxyCreatorTests { tapc.testInterceptor.nrOfInvocations = 0; FactoryBean prototypeFactory = (FactoryBean) sac.getBean("&prototypeFactoryToBeProxied"); - assertTrue(AopUtils.isCglibProxy(prototypeFactory)); + assertThat(AopUtils.isCglibProxy(prototypeFactory)).isTrue(); TestBean tb = (TestBean) sac.getBean("prototypeFactoryToBeProxied"); - assertFalse(AopUtils.isCglibProxy(tb)); + assertThat(AopUtils.isCglibProxy(tb)).isFalse(); - assertEquals(2, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(2); tb.getAge(); - assertEquals(2, tapc.testInterceptor.nrOfInvocations); + assertThat(tapc.testInterceptor.nrOfInvocations).isEqualTo(2); } diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java index 02d183b6e63..4ff78ac7a45 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java @@ -25,8 +25,8 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.lang.Nullable; 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.junit.Assert.assertEquals; /** * @author Juergen Hoeller @@ -41,7 +41,7 @@ public class BeanNameAutoProxyCreatorInitTests { new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass()); TestBean bean = (TestBean) ctx.getBean("bean"); bean.setName("foo"); - assertEquals("foo", bean.getName()); + assertThat(bean.getName()).isEqualTo("foo"); assertThatIllegalArgumentException().isThrownBy(() -> bean.setName(null)); } diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests.java b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests.java index e33279c4cf7..db09348847f 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests.java @@ -32,10 +32,8 @@ import org.springframework.tests.aop.interceptor.NopInterceptor; import org.springframework.tests.sample.beans.ITestBean; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -58,51 +56,52 @@ public class BeanNameAutoProxyCreatorTests { @Test public void testNoProxy() { TestBean tb = (TestBean) beanFactory.getBean("noproxy"); - assertFalse(AopUtils.isAopProxy(tb)); - assertEquals("noproxy", tb.getName()); + assertThat(AopUtils.isAopProxy(tb)).isFalse(); + assertThat(tb.getName()).isEqualTo("noproxy"); } @Test public void testJdkProxyWithExactNameMatch() { ITestBean tb = (ITestBean) beanFactory.getBean("onlyJdk"); jdkAssertions(tb, 1); - assertEquals("onlyJdk", tb.getName()); + assertThat(tb.getName()).isEqualTo("onlyJdk"); } @Test public void testJdkProxyWithDoubleProxying() { ITestBean tb = (ITestBean) beanFactory.getBean("doubleJdk"); jdkAssertions(tb, 2); - assertEquals("doubleJdk", tb.getName()); + assertThat(tb.getName()).isEqualTo("doubleJdk"); } @Test public void testJdkIntroduction() { ITestBean tb = (ITestBean) beanFactory.getBean("introductionUsingJdk"); NopInterceptor nop = (NopInterceptor) beanFactory.getBean("introductionNopInterceptor"); - assertEquals(0, nop.getCount()); - assertTrue(AopUtils.isJdkDynamicProxy(tb)); + assertThat(nop.getCount()).isEqualTo(0); + assertThat(AopUtils.isJdkDynamicProxy(tb)).isTrue(); int age = 5; tb.setAge(age); - assertEquals(age, tb.getAge()); - assertTrue("Introduction was made", tb instanceof TimeStamped); - assertEquals(0, ((TimeStamped) tb).getTimeStamp()); - assertEquals(3, nop.getCount()); - assertEquals("introductionUsingJdk", tb.getName()); + assertThat(tb.getAge()).isEqualTo(age); + boolean condition = tb instanceof TimeStamped; + assertThat(condition).as("Introduction was made").isTrue(); + assertThat(((TimeStamped) tb).getTimeStamp()).isEqualTo(0); + assertThat(nop.getCount()).isEqualTo(3); + assertThat(tb.getName()).isEqualTo("introductionUsingJdk"); ITestBean tb2 = (ITestBean) beanFactory.getBean("second-introductionUsingJdk"); // Check two per-instance mixins were distinct Lockable lockable1 = (Lockable) tb; Lockable lockable2 = (Lockable) tb2; - assertFalse(lockable1.locked()); - assertFalse(lockable2.locked()); + assertThat(lockable1.locked()).isFalse(); + assertThat(lockable2.locked()).isFalse(); tb.setAge(65); - assertEquals(65, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(65); lockable1.lock(); - assertTrue(lockable1.locked()); + assertThat(lockable1.locked()).isTrue(); // Shouldn't affect second - assertFalse(lockable2.locked()); + assertThat(lockable2.locked()).isFalse(); // Can still mod second object tb2.setAge(12); // But can't mod first @@ -114,28 +113,29 @@ public class BeanNameAutoProxyCreatorTests { public void testJdkIntroductionAppliesToCreatedObjectsNotFactoryBean() { ITestBean tb = (ITestBean) beanFactory.getBean("factory-introductionUsingJdk"); NopInterceptor nop = (NopInterceptor) beanFactory.getBean("introductionNopInterceptor"); - assertEquals("NOP should not have done any work yet", 0, nop.getCount()); - assertTrue(AopUtils.isJdkDynamicProxy(tb)); + assertThat(nop.getCount()).as("NOP should not have done any work yet").isEqualTo(0); + assertThat(AopUtils.isJdkDynamicProxy(tb)).isTrue(); int age = 5; tb.setAge(age); - assertEquals(age, tb.getAge()); - assertTrue("Introduction was made", tb instanceof TimeStamped); - assertEquals(0, ((TimeStamped) tb).getTimeStamp()); - assertEquals(3, nop.getCount()); + assertThat(tb.getAge()).isEqualTo(age); + boolean condition = tb instanceof TimeStamped; + assertThat(condition).as("Introduction was made").isTrue(); + assertThat(((TimeStamped) tb).getTimeStamp()).isEqualTo(0); + assertThat(nop.getCount()).isEqualTo(3); ITestBean tb2 = (ITestBean) beanFactory.getBean("second-introductionUsingJdk"); // Check two per-instance mixins were distinct Lockable lockable1 = (Lockable) tb; Lockable lockable2 = (Lockable) tb2; - assertFalse(lockable1.locked()); - assertFalse(lockable2.locked()); + assertThat(lockable1.locked()).isFalse(); + assertThat(lockable2.locked()).isFalse(); tb.setAge(65); - assertEquals(65, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(65); lockable1.lock(); - assertTrue(lockable1.locked()); + assertThat(lockable1.locked()).isTrue(); // Shouldn't affect second - assertFalse(lockable2.locked()); + assertThat(lockable2.locked()).isFalse(); // Can still mod second object tb2.setAge(12); // But can't mod first @@ -147,31 +147,31 @@ public class BeanNameAutoProxyCreatorTests { public void testJdkProxyWithWildcardMatch() { ITestBean tb = (ITestBean) beanFactory.getBean("jdk1"); jdkAssertions(tb, 1); - assertEquals("jdk1", tb.getName()); + assertThat(tb.getName()).isEqualTo("jdk1"); } @Test public void testCglibProxyWithWildcardMatch() { TestBean tb = (TestBean) beanFactory.getBean("cglib1"); cglibAssertions(tb); - assertEquals("cglib1", tb.getName()); + assertThat(tb.getName()).isEqualTo("cglib1"); } @Test public void testWithFrozenProxy() { ITestBean testBean = (ITestBean) beanFactory.getBean("frozenBean"); - assertTrue(((Advised)testBean).isFrozen()); + assertThat(((Advised)testBean).isFrozen()).isTrue(); } private void jdkAssertions(ITestBean tb, int nopInterceptorCount) { NopInterceptor nop = (NopInterceptor) beanFactory.getBean("nopInterceptor"); - assertEquals(0, nop.getCount()); - assertTrue(AopUtils.isJdkDynamicProxy(tb)); + assertThat(nop.getCount()).isEqualTo(0); + assertThat(AopUtils.isJdkDynamicProxy(tb)).isTrue(); int age = 5; tb.setAge(age); - assertEquals(age, tb.getAge()); - assertEquals(2 * nopInterceptorCount, nop.getCount()); + assertThat(tb.getAge()).isEqualTo(age); + assertThat(nop.getCount()).isEqualTo((2 * nopInterceptorCount)); } /** @@ -180,14 +180,14 @@ public class BeanNameAutoProxyCreatorTests { private void cglibAssertions(TestBean tb) { CountingBeforeAdvice cba = (CountingBeforeAdvice) beanFactory.getBean("countingBeforeAdvice"); NopInterceptor nop = (NopInterceptor) beanFactory.getBean("nopInterceptor"); - assertEquals(0, cba.getCalls()); - assertEquals(0, nop.getCount()); - assertTrue(AopUtils.isCglibProxy(tb)); + assertThat(cba.getCalls()).isEqualTo(0); + assertThat(nop.getCount()).isEqualTo(0); + assertThat(AopUtils.isCglibProxy(tb)).isTrue(); int age = 5; tb.setAge(age); - assertEquals(age, tb.getAge()); - assertEquals(2, nop.getCount()); - assertEquals(2, cba.getCalls()); + assertThat(tb.getAge()).isEqualTo(age); + assertThat(nop.getCount()).isEqualTo(2); + assertThat(cba.getCalls()).isEqualTo(2); } } diff --git a/spring-context/src/test/java/org/springframework/aop/scope/ScopedProxyTests.java b/spring-context/src/test/java/org/springframework/aop/scope/ScopedProxyTests.java index 8b00d703e15..9916cb6f7da 100644 --- a/spring-context/src/test/java/org/springframework/aop/scope/ScopedProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/scope/ScopedProxyTests.java @@ -32,9 +32,7 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -57,7 +55,8 @@ public class ScopedProxyTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(MAP_CONTEXT); Object baseMap = bf.getBean("singletonMap"); - assertTrue(baseMap instanceof Map); + boolean condition = baseMap instanceof Map; + assertThat(condition).isTrue(); } @Test @@ -65,8 +64,10 @@ public class ScopedProxyTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(MAP_CONTEXT); Object simpleMap = bf.getBean("simpleMap"); - assertTrue(simpleMap instanceof Map); - assertTrue(simpleMap instanceof HashMap); + boolean condition1 = simpleMap instanceof Map; + assertThat(condition1).isTrue(); + boolean condition = simpleMap instanceof HashMap; + assertThat(condition).isTrue(); } @Test @@ -78,11 +79,11 @@ public class ScopedProxyTests { ctx.refresh(); ITestBean bean = (ITestBean) ctx.getBean("testBean"); - assertEquals("male", bean.getName()); - assertEquals(99, bean.getAge()); + assertThat(bean.getName()).isEqualTo("male"); + assertThat(bean.getAge()).isEqualTo(99); - assertTrue(scope.getMap().containsKey("scopedTarget.testBean")); - assertEquals(TestBean.class, scope.getMap().get("scopedTarget.testBean").getClass()); + assertThat(scope.getMap().containsKey("scopedTarget.testBean")).isTrue(); + assertThat(scope.getMap().get("scopedTarget.testBean").getClass()).isEqualTo(TestBean.class); } @Test @@ -94,23 +95,25 @@ public class ScopedProxyTests { bf.registerScope("request", scope); ITestBean bean = (ITestBean) bf.getBean("testBean"); - assertNotNull(bean); - assertTrue(AopUtils.isJdkDynamicProxy(bean)); - assertTrue(bean instanceof ScopedObject); + assertThat(bean).isNotNull(); + assertThat(AopUtils.isJdkDynamicProxy(bean)).isTrue(); + boolean condition1 = bean instanceof ScopedObject; + assertThat(condition1).isTrue(); ScopedObject scoped = (ScopedObject) bean; - assertEquals(TestBean.class, scoped.getTargetObject().getClass()); + assertThat(scoped.getTargetObject().getClass()).isEqualTo(TestBean.class); bean.setAge(101); - assertTrue(scope.getMap().containsKey("testBeanTarget")); - assertEquals(TestBean.class, scope.getMap().get("testBeanTarget").getClass()); + assertThat(scope.getMap().containsKey("testBeanTarget")).isTrue(); + assertThat(scope.getMap().get("testBeanTarget").getClass()).isEqualTo(TestBean.class); ITestBean deserialized = (ITestBean) SerializationTestUtils.serializeAndDeserialize(bean); - assertNotNull(deserialized); - assertTrue(AopUtils.isJdkDynamicProxy(deserialized)); - assertEquals(101, bean.getAge()); - assertTrue(deserialized instanceof ScopedObject); + assertThat(deserialized).isNotNull(); + assertThat(AopUtils.isJdkDynamicProxy(deserialized)).isTrue(); + assertThat(bean.getAge()).isEqualTo(101); + boolean condition = deserialized instanceof ScopedObject; + assertThat(condition).isTrue(); ScopedObject scopedDeserialized = (ScopedObject) deserialized; - assertEquals(TestBean.class, scopedDeserialized.getTargetObject().getClass()); + assertThat(scopedDeserialized.getTargetObject().getClass()).isEqualTo(TestBean.class); bf.setSerializationId(null); } @@ -124,22 +127,24 @@ public class ScopedProxyTests { bf.registerScope("request", scope); TestBean tb = (TestBean) bf.getBean("testBean"); - assertTrue(AopUtils.isCglibProxy(tb.getFriends())); - assertTrue(tb.getFriends() instanceof ScopedObject); + assertThat(AopUtils.isCglibProxy(tb.getFriends())).isTrue(); + boolean condition1 = tb.getFriends() instanceof ScopedObject; + assertThat(condition1).isTrue(); ScopedObject scoped = (ScopedObject) tb.getFriends(); - assertEquals(ArrayList.class, scoped.getTargetObject().getClass()); + assertThat(scoped.getTargetObject().getClass()).isEqualTo(ArrayList.class); tb.getFriends().add("myFriend"); - assertTrue(scope.getMap().containsKey("scopedTarget.scopedList")); - assertEquals(ArrayList.class, scope.getMap().get("scopedTarget.scopedList").getClass()); + assertThat(scope.getMap().containsKey("scopedTarget.scopedList")).isTrue(); + assertThat(scope.getMap().get("scopedTarget.scopedList").getClass()).isEqualTo(ArrayList.class); ArrayList deserialized = (ArrayList) SerializationTestUtils.serializeAndDeserialize(tb.getFriends()); - assertNotNull(deserialized); - assertTrue(AopUtils.isCglibProxy(deserialized)); - assertTrue(deserialized.contains("myFriend")); - assertTrue(deserialized instanceof ScopedObject); + assertThat(deserialized).isNotNull(); + assertThat(AopUtils.isCglibProxy(deserialized)).isTrue(); + assertThat(deserialized.contains("myFriend")).isTrue(); + boolean condition = deserialized instanceof ScopedObject; + assertThat(condition).isTrue(); ScopedObject scopedDeserialized = (ScopedObject) deserialized; - assertEquals(ArrayList.class, scopedDeserialized.getTargetObject().getClass()); + assertThat(scopedDeserialized.getTargetObject().getClass()).isEqualTo(ArrayList.class); bf.setSerializationId(null); } diff --git a/spring-context/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceTests.java b/spring-context/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceTests.java index a8051de1018..f2117234a6b 100644 --- a/spring-context/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceTests.java +++ b/spring-context/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceTests.java @@ -32,10 +32,8 @@ import org.springframework.tests.sample.beans.SerializablePerson; import org.springframework.tests.sample.beans.SideEffectBean; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * Tests for pooling invoker interceptor. @@ -74,9 +72,9 @@ public class CommonsPool2TargetSourceTests { private void testFunctionality(String name) { SideEffectBean pooled = (SideEffectBean) beanFactory.getBean(name); - assertEquals(INITIAL_COUNT, pooled.getCount()); + assertThat(pooled.getCount()).isEqualTo(INITIAL_COUNT); pooled.doWork(); - assertEquals(INITIAL_COUNT + 1, pooled.getCount()); + assertThat(pooled.getCount()).isEqualTo((INITIAL_COUNT + 1)); pooled = (SideEffectBean) beanFactory.getBean(name); // Just check that it works--we can't make assumptions @@ -98,16 +96,16 @@ public class CommonsPool2TargetSourceTests { @Test public void testConfigMixin() { SideEffectBean pooled = (SideEffectBean) beanFactory.getBean("pooledWithMixin"); - assertEquals(INITIAL_COUNT, pooled.getCount()); + assertThat(pooled.getCount()).isEqualTo(INITIAL_COUNT); PoolingConfig conf = (PoolingConfig) beanFactory.getBean("pooledWithMixin"); // TODO one invocation from setup //assertEquals(1, conf.getInvocations()); pooled.doWork(); // assertEquals("No objects active", 0, conf.getActive()); - assertEquals("Correct target source", 25, conf.getMaxSize()); + assertThat(conf.getMaxSize()).as("Correct target source").isEqualTo(25); // assertTrue("Some free", conf.getFree() > 0); //assertEquals(2, conf.getInvocations()); - assertEquals(25, conf.getMaxSize()); + assertThat(conf.getMaxSize()).isEqualTo(25); } @Test @@ -115,7 +113,8 @@ public class CommonsPool2TargetSourceTests { CommonsPool2TargetSource cpts = (CommonsPool2TargetSource) beanFactory.getBean("personPoolTargetSource"); SingletonTargetSource serialized = (SingletonTargetSource) SerializationTestUtils.serializeAndDeserialize(cpts); - assertTrue(serialized.getTarget() instanceof Person); + boolean condition = serialized.getTarget() instanceof Person; + assertThat(condition).isTrue(); } @@ -124,13 +123,15 @@ public class CommonsPool2TargetSourceTests { Person pooled = (Person) beanFactory.getBean("pooledPerson"); //System.out.println(((Advised) pooled).toProxyConfigString()); - assertTrue(((Advised) pooled).getTargetSource() instanceof CommonsPool2TargetSource); + boolean condition1 = ((Advised) pooled).getTargetSource() instanceof CommonsPool2TargetSource; + assertThat(condition1).isTrue(); //((Advised) pooled).setTargetSource(new SingletonTargetSource(new SerializablePerson())); Person serialized = (Person) SerializationTestUtils.serializeAndDeserialize(pooled); - assertTrue(((Advised) serialized).getTargetSource() instanceof SingletonTargetSource); + boolean condition = ((Advised) serialized).getTargetSource() instanceof SingletonTargetSource; + assertThat(condition).isTrue(); serialized.setAge(25); - assertEquals(25, serialized.getAge()); + assertThat(serialized.getAge()).isEqualTo(25); } @Test @@ -146,7 +147,7 @@ public class CommonsPool2TargetSourceTests { for (int x = 0; x < maxSize; x++) { Object instance = targetSource.getTarget(); - assertNotNull(instance); + assertThat(instance).isNotNull(); pooledInstances[x] = instance; } @@ -174,7 +175,7 @@ public class CommonsPool2TargetSourceTests { for (int x = 0; x < maxSize; x++) { Object instance = targetSource.getTarget(); - assertNotNull(instance); + assertThat(instance).isNotNull(); pooledInstances[x] = instance; } @@ -197,7 +198,7 @@ public class CommonsPool2TargetSourceTests { public void testSetWhenExhaustedAction() { CommonsPool2TargetSource targetSource = new CommonsPool2TargetSource(); targetSource.setBlockWhenExhausted(true); - assertEquals(true, targetSource.isBlockWhenExhausted()); + assertThat(targetSource.isBlockWhenExhausted()).isEqualTo(true); } @Test @@ -208,9 +209,11 @@ public class CommonsPool2TargetSourceTests { Object first = targetSource.getTarget(); Object second = targetSource.getTarget(); - assertTrue(first instanceof SerializablePerson); - assertTrue(second instanceof SerializablePerson); - assertEquals(first, second); + boolean condition1 = first instanceof SerializablePerson; + assertThat(condition1).isTrue(); + boolean condition = second instanceof SerializablePerson; + assertThat(condition).isTrue(); + assertThat(second).isEqualTo(first); targetSource.releaseTarget(first); targetSource.releaseTarget(second); diff --git a/spring-context/src/test/java/org/springframework/beans/factory/annotation/BridgeMethodAutowiringTests.java b/spring-context/src/test/java/org/springframework/beans/factory/annotation/BridgeMethodAutowiringTests.java index b800ed4ea92..fcde824129a 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/annotation/BridgeMethodAutowiringTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/annotation/BridgeMethodAutowiringTests.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; public class BridgeMethodAutowiringTests { @@ -33,7 +33,7 @@ public class BridgeMethodAutowiringTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(UserServiceImpl.class, Foo.class); ctx.refresh(); - assertNotNull(ctx.getBean(UserServiceImpl.class).object); + assertThat(ctx.getBean(UserServiceImpl.class).object).isNotNull(); } diff --git a/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java b/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java index e43b67037f8..1470dbcbca1 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java @@ -37,7 +37,6 @@ import org.springframework.context.support.GenericApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * Integration tests for handling JSR-303 {@link javax.inject.Qualifier} annotations. @@ -115,7 +114,7 @@ public class InjectAnnotationAutowireContextTests { AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); QualifiedFieldTestBean bean = (QualifiedFieldTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -132,7 +131,7 @@ public class InjectAnnotationAutowireContextTests { context.refresh(); QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -149,7 +148,7 @@ public class InjectAnnotationAutowireContextTests { context.refresh(); QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -169,7 +168,7 @@ public class InjectAnnotationAutowireContextTests { context.refresh(); QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -186,7 +185,7 @@ public class InjectAnnotationAutowireContextTests { context.refresh(); QualifiedConstructorArgumentTestBean bean = (QualifiedConstructorArgumentTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -269,7 +268,7 @@ public class InjectAnnotationAutowireContextTests { AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); QualifiedFieldTestBean bean = (QualifiedFieldTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -290,7 +289,7 @@ public class InjectAnnotationAutowireContextTests { context.refresh(); QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -311,7 +310,7 @@ public class InjectAnnotationAutowireContextTests { context.refresh(); QualifiedConstructorArgumentTestBean bean = (QualifiedConstructorArgumentTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -333,7 +332,7 @@ public class InjectAnnotationAutowireContextTests { context.refresh(); QualifiedFieldWithDefaultValueTestBean bean = (QualifiedFieldWithDefaultValueTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -379,7 +378,7 @@ public class InjectAnnotationAutowireContextTests { context.refresh(); QualifiedFieldWithDefaultValueTestBean bean = (QualifiedFieldWithDefaultValueTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -405,7 +404,7 @@ public class InjectAnnotationAutowireContextTests { context.refresh(); QualifiedFieldWithMultipleAttributesTestBean bean = (QualifiedFieldWithMultipleAttributesTestBean) context.getBean("autowired"); - assertEquals(MARK, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(MARK); } @Test @@ -461,7 +460,7 @@ public class InjectAnnotationAutowireContextTests { context.refresh(); QualifiedFieldWithMultipleAttributesTestBean bean = (QualifiedFieldWithMultipleAttributesTestBean) context.getBean("autowired"); - assertEquals(MARK, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(MARK); } @Test diff --git a/spring-context/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireContextTests.java b/spring-context/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireContextTests.java index 3c3460f47b9..5473798ba97 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireContextTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireContextTests.java @@ -36,7 +36,6 @@ import org.springframework.context.support.GenericApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * Integration tests for handling {@link Qualifier} annotations. @@ -118,7 +117,7 @@ public class QualifierAnnotationAutowireContextTests { AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); QualifiedFieldTestBean bean = (QualifiedFieldTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -135,7 +134,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -152,7 +151,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -172,7 +171,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -189,7 +188,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedConstructorArgumentTestBean bean = (QualifiedConstructorArgumentTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -272,7 +271,7 @@ public class QualifierAnnotationAutowireContextTests { AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); QualifiedFieldTestBean bean = (QualifiedFieldTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -292,7 +291,7 @@ public class QualifierAnnotationAutowireContextTests { AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); MetaQualifiedFieldTestBean bean = (MetaQualifiedFieldTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -313,7 +312,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -334,7 +333,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedConstructorArgumentTestBean bean = (QualifiedConstructorArgumentTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -356,7 +355,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedFieldWithDefaultValueTestBean bean = (QualifiedFieldWithDefaultValueTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -402,7 +401,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedFieldWithDefaultValueTestBean bean = (QualifiedFieldWithDefaultValueTestBean) context.getBean("autowired"); - assertEquals(JUERGEN, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(JUERGEN); } @Test @@ -428,7 +427,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedFieldWithMultipleAttributesTestBean bean = (QualifiedFieldWithMultipleAttributesTestBean) context.getBean("autowired"); - assertEquals(MARK, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(MARK); } @Test @@ -484,7 +483,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedFieldWithMultipleAttributesTestBean bean = (QualifiedFieldWithMultipleAttributesTestBean) context.getBean("autowired"); - assertEquals(MARK, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(MARK); } @Test @@ -534,7 +533,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedFieldWithBaseQualifierDefaultValueTestBean bean = (QualifiedFieldWithBaseQualifierDefaultValueTestBean) context.getBean("autowired"); - assertEquals(MARK, bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo(MARK); } @Test @@ -556,7 +555,7 @@ public class QualifierAnnotationAutowireContextTests { context.refresh(); QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean bean = (QualifiedConstructorArgumentWithBaseQualifierNonDefaultValueTestBean) context.getBean("autowired"); - assertEquals("the real juergen", bean.getPerson().getName()); + assertThat(bean.getPerson().getName()).isEqualTo("the real juergen"); } @Test diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests.java index d9f31cd045f..4558e8e03ba 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests.java @@ -24,7 +24,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests lookup methods wrapped by a CGLIB proxy (see SPR-391). @@ -52,8 +52,8 @@ public class LookupMethodWrappedByCglibProxyTests { public void testAutoProxiedLookup() { OverloadLookup olup = (OverloadLookup) applicationContext.getBean("autoProxiedOverload"); ITestBean jenny = olup.newTestBean(); - assertEquals("Jenny", jenny.getName()); - assertEquals("foo", olup.testMethod()); + assertThat(jenny.getName()).isEqualTo("Jenny"); + assertThat(olup.testMethod()).isEqualTo("foo"); assertInterceptorCount(2); } @@ -61,14 +61,14 @@ public class LookupMethodWrappedByCglibProxyTests { public void testRegularlyProxiedLookup() { OverloadLookup olup = (OverloadLookup) applicationContext.getBean("regularlyProxiedOverload"); ITestBean jenny = olup.newTestBean(); - assertEquals("Jenny", jenny.getName()); - assertEquals("foo", olup.testMethod()); + assertThat(jenny.getName()).isEqualTo("Jenny"); + assertThat(olup.testMethod()).isEqualTo("foo"); assertInterceptorCount(2); } private void assertInterceptorCount(int count) { DebugInterceptor interceptor = getInterceptor(); - assertEquals("Interceptor count is incorrect", count, interceptor.getCount()); + assertThat(interceptor.getCount()).as("Interceptor count is incorrect").isEqualTo(count); } private void resetInterceptor() { diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java index ca32c8dee90..d434fff1ad1 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java @@ -35,10 +35,8 @@ import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.support.StaticApplicationContext; import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import static org.springframework.util.ClassUtils.convertClassNameToResourcePath; /** @@ -73,7 +71,7 @@ public class QualifierAnnotationTests { context.refresh(); QualifiedByValueTestBean testBean = (QualifiedByValueTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); - assertEquals("Larry", person.getName()); + assertThat(person.getName()).isEqualTo("Larry"); } @Test @@ -98,7 +96,7 @@ public class QualifierAnnotationTests { context.refresh(); QualifiedByParentValueTestBean testBean = (QualifiedByParentValueTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); - assertEquals("ParentLarry", person.getName()); + assertThat(person.getName()).isEqualTo("ParentLarry"); } @Test @@ -110,8 +108,8 @@ public class QualifierAnnotationTests { context.refresh(); QualifiedByBeanNameTestBean testBean = (QualifiedByBeanNameTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); - assertEquals("LarryBean", person.getName()); - assertTrue(testBean.myProps != null && testBean.myProps.isEmpty()); + assertThat(person.getName()).isEqualTo("LarryBean"); + assertThat(testBean.myProps != null && testBean.myProps.isEmpty()).isTrue(); } @Test @@ -123,7 +121,7 @@ public class QualifierAnnotationTests { context.refresh(); QualifiedByFieldNameTestBean testBean = (QualifiedByFieldNameTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); - assertEquals("LarryBean", person.getName()); + assertThat(person.getName()).isEqualTo("LarryBean"); } @Test @@ -135,7 +133,7 @@ public class QualifierAnnotationTests { context.refresh(); QualifiedByParameterNameTestBean testBean = (QualifiedByParameterNameTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); - assertEquals("LarryBean", person.getName()); + assertThat(person.getName()).isEqualTo("LarryBean"); } @Test @@ -147,7 +145,7 @@ public class QualifierAnnotationTests { context.refresh(); QualifiedByAliasTestBean testBean = (QualifiedByAliasTestBean) context.getBean("testBean"); Person person = testBean.getStooge(); - assertEquals("LarryBean", person.getName()); + assertThat(person.getName()).isEqualTo("LarryBean"); } @Test @@ -159,7 +157,7 @@ public class QualifierAnnotationTests { context.refresh(); QualifiedByAnnotationTestBean testBean = (QualifiedByAnnotationTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); - assertEquals("LarrySpecial", person.getName()); + assertThat(person.getName()).isEqualTo("LarrySpecial"); } @Test @@ -171,7 +169,7 @@ public class QualifierAnnotationTests { context.refresh(); QualifiedByCustomValueTestBean testBean = (QualifiedByCustomValueTestBean) context.getBean("testBean"); Person person = testBean.getCurly(); - assertEquals("Curly", person.getName()); + assertThat(person.getName()).isEqualTo("Curly"); } @Test @@ -183,7 +181,7 @@ public class QualifierAnnotationTests { context.refresh(); QualifiedByAnnotationValueTestBean testBean = (QualifiedByAnnotationValueTestBean) context.getBean("testBean"); Person person = testBean.getLarry(); - assertEquals("LarrySpecial", person.getName()); + assertThat(person.getName()).isEqualTo("LarrySpecial"); } @Test @@ -210,8 +208,8 @@ public class QualifierAnnotationTests { MultiQualifierClient testBean = (MultiQualifierClient) context.getBean("testBean"); - assertNotNull( testBean.factoryTheta); - assertNotNull( testBean.implTheta); + assertThat(testBean.factoryTheta).isNotNull(); + assertThat(testBean.implTheta).isNotNull(); } @Test diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerWithExpressionLanguageTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerWithExpressionLanguageTests.java index 7881a396a61..d516be6a7ce 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerWithExpressionLanguageTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerWithExpressionLanguageTests.java @@ -22,7 +22,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for combining the expression language and the p namespace. Due to the required EL dependency, this test is in @@ -39,8 +39,8 @@ public class SimplePropertyNamespaceHandlerWithExpressionLanguageTests { getClass()); ITestBean foo = applicationContext.getBean("foo", ITestBean.class); ITestBean bar = applicationContext.getBean("bar", ITestBean.class); - assertEquals("Invalid name", "Baz", foo.getName()); - assertEquals("Invalid name", "Baz", bar.getName()); + assertThat(foo.getName()).as("Invalid name").isEqualTo("Baz"); + assertThat(bar.getName()).as("Invalid name").isEqualTo("Baz"); } } diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java index 347a8ae605c..ea0f54f2605 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java @@ -69,13 +69,6 @@ import org.springframework.util.StopWatch; import static org.assertj.core.api.Assertions.assertThat; 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; /** * Miscellaneous tests for XML bean definitions. @@ -149,12 +142,12 @@ public class XmlBeanFactoryTests { TestBean georgia = (TestBean) xbf.getBean("georgia"); ITestBean emmasJenks = emma.getSpouse(); ITestBean georgiasJenks = georgia.getSpouse(); - assertTrue("Emma and georgia think they have a different boyfriend", emmasJenks != georgiasJenks); - assertTrue("Emmas jenks has right name", emmasJenks.getName().equals("Andrew")); - assertTrue("Emmas doesn't equal new ref", emmasJenks != xbf.getBean("jenks")); - assertTrue("Georgias jenks has right name", emmasJenks.getName().equals("Andrew")); - assertTrue("They are object equal", emmasJenks.equals(georgiasJenks)); - assertTrue("They object equal direct ref", emmasJenks.equals(xbf.getBean("jenks"))); + assertThat(emmasJenks != georgiasJenks).as("Emma and georgia think they have a different boyfriend").isTrue(); + assertThat(emmasJenks.getName().equals("Andrew")).as("Emmas jenks has right name").isTrue(); + assertThat(emmasJenks != xbf.getBean("jenks")).as("Emmas doesn't equal new ref").isTrue(); + assertThat(emmasJenks.getName().equals("Andrew")).as("Georgias jenks has right name").isTrue(); + assertThat(emmasJenks.equals(georgiasJenks)).as("They are object equal").isTrue(); + assertThat(emmasJenks.equals(xbf.getBean("jenks"))).as("They object equal direct ref").isTrue(); } @Test @@ -169,8 +162,8 @@ public class XmlBeanFactoryTests { TestBean jenks = (TestBean) xbf.getBean("jenks"); ITestBean davesJen = dave.getSpouse(); ITestBean jenksJen = jenks.getSpouse(); - assertTrue("1 jen instance", davesJen == jenksJen); - assertTrue("1 jen instance", davesJen == jen); + assertThat(davesJen == jenksJen).as("1 jen instance").isTrue(); + assertThat(davesJen == jen).as("1 jen instance").isTrue(); } @Test @@ -193,62 +186,62 @@ public class XmlBeanFactoryTests { xbf.getBean("innerBean"); TestBean hasInnerBeans = (TestBean) xbf.getBean("hasInnerBeans"); - assertEquals(5, hasInnerBeans.getAge()); + assertThat(hasInnerBeans.getAge()).isEqualTo(5); TestBean inner1 = (TestBean) hasInnerBeans.getSpouse(); - assertNotNull(inner1); - assertEquals("innerBean#1", inner1.getBeanName()); - assertEquals("inner1", inner1.getName()); - assertEquals(6, inner1.getAge()); + assertThat(inner1).isNotNull(); + assertThat(inner1.getBeanName()).isEqualTo("innerBean#1"); + assertThat(inner1.getName()).isEqualTo("inner1"); + assertThat(inner1.getAge()).isEqualTo(6); - assertNotNull(hasInnerBeans.getFriends()); + assertThat(hasInnerBeans.getFriends()).isNotNull(); Object[] friends = hasInnerBeans.getFriends().toArray(); - assertEquals(3, friends.length); + assertThat(friends.length).isEqualTo(3); DerivedTestBean inner2 = (DerivedTestBean) friends[0]; - assertEquals("inner2", inner2.getName()); - assertTrue(inner2.getBeanName().startsWith(DerivedTestBean.class.getName())); - assertFalse(xbf.containsBean("innerBean#1")); - assertNotNull(inner2); - assertEquals(7, inner2.getAge()); + assertThat(inner2.getName()).isEqualTo("inner2"); + assertThat(inner2.getBeanName().startsWith(DerivedTestBean.class.getName())).isTrue(); + assertThat(xbf.containsBean("innerBean#1")).isFalse(); + assertThat(inner2).isNotNull(); + assertThat(inner2.getAge()).isEqualTo(7); TestBean innerFactory = (TestBean) friends[1]; - assertEquals(DummyFactory.SINGLETON_NAME, innerFactory.getName()); + assertThat(innerFactory.getName()).isEqualTo(DummyFactory.SINGLETON_NAME); TestBean inner5 = (TestBean) friends[2]; - assertEquals("innerBean#2", inner5.getBeanName()); + assertThat(inner5.getBeanName()).isEqualTo("innerBean#2"); - assertNotNull(hasInnerBeans.getSomeMap()); - assertEquals(2, hasInnerBeans.getSomeMap().size()); + assertThat(hasInnerBeans.getSomeMap()).isNotNull(); + assertThat(hasInnerBeans.getSomeMap().size()).isEqualTo(2); TestBean inner3 = (TestBean) hasInnerBeans.getSomeMap().get("someKey"); - assertEquals("Jenny", inner3.getName()); - assertEquals(30, inner3.getAge()); + assertThat(inner3.getName()).isEqualTo("Jenny"); + assertThat(inner3.getAge()).isEqualTo(30); TestBean inner4 = (TestBean) hasInnerBeans.getSomeMap().get("someOtherKey"); - assertEquals("inner4", inner4.getName()); - assertEquals(9, inner4.getAge()); + assertThat(inner4.getName()).isEqualTo("inner4"); + assertThat(inner4.getAge()).isEqualTo(9); TestBean hasInnerBeansForConstructor = (TestBean) xbf.getBean("hasInnerBeansForConstructor"); TestBean innerForConstructor = (TestBean) hasInnerBeansForConstructor.getSpouse(); - assertNotNull(innerForConstructor); - assertEquals("innerBean#3", innerForConstructor.getBeanName()); - assertEquals("inner1", innerForConstructor.getName()); - assertEquals(6, innerForConstructor.getAge()); + assertThat(innerForConstructor).isNotNull(); + assertThat(innerForConstructor.getBeanName()).isEqualTo("innerBean#3"); + assertThat(innerForConstructor.getName()).isEqualTo("inner1"); + assertThat(innerForConstructor.getAge()).isEqualTo(6); hasInnerBeansForConstructor = (TestBean) xbf.getBean("hasInnerBeansAsPrototype"); innerForConstructor = (TestBean) hasInnerBeansForConstructor.getSpouse(); - assertNotNull(innerForConstructor); - assertEquals("innerBean", innerForConstructor.getBeanName()); - assertEquals("inner1", innerForConstructor.getName()); - assertEquals(6, innerForConstructor.getAge()); + assertThat(innerForConstructor).isNotNull(); + assertThat(innerForConstructor.getBeanName()).isEqualTo("innerBean"); + assertThat(innerForConstructor.getName()).isEqualTo("inner1"); + assertThat(innerForConstructor.getAge()).isEqualTo(6); hasInnerBeansForConstructor = (TestBean) xbf.getBean("hasInnerBeansAsPrototype"); innerForConstructor = (TestBean) hasInnerBeansForConstructor.getSpouse(); - assertNotNull(innerForConstructor); - assertEquals("innerBean", innerForConstructor.getBeanName()); - assertEquals("inner1", innerForConstructor.getName()); - assertEquals(6, innerForConstructor.getAge()); + assertThat(innerForConstructor).isNotNull(); + assertThat(innerForConstructor.getBeanName()).isEqualTo("innerBean"); + assertThat(innerForConstructor.getName()).isEqualTo("inner1"); + assertThat(innerForConstructor.getAge()).isEqualTo(6); xbf.destroySingletons(); - assertTrue(inner1.wasDestroyed()); - assertTrue(inner2.wasDestroyed()); - assertTrue(innerFactory.getName() == null); - assertTrue(inner5.wasDestroyed()); + assertThat(inner1.wasDestroyed()).isTrue(); + assertThat(inner2.wasDestroyed()).isTrue(); + assertThat(innerFactory.getName() == null).isTrue(); + assertThat(inner5.wasDestroyed()).isTrue(); } @Test @@ -264,25 +257,25 @@ public class XmlBeanFactoryTests { xbf.getBean("innerBean"); TestBean hasInnerBeans = (TestBean) xbf.getBean("hasInnerBeansWithoutDestroy"); - assertEquals(5, hasInnerBeans.getAge()); + assertThat(hasInnerBeans.getAge()).isEqualTo(5); TestBean inner1 = (TestBean) hasInnerBeans.getSpouse(); - assertNotNull(inner1); - assertTrue(inner1.getBeanName().startsWith("innerBean")); - assertEquals("inner1", inner1.getName()); - assertEquals(6, inner1.getAge()); + assertThat(inner1).isNotNull(); + assertThat(inner1.getBeanName().startsWith("innerBean")).isTrue(); + assertThat(inner1.getName()).isEqualTo("inner1"); + assertThat(inner1.getAge()).isEqualTo(6); - assertNotNull(hasInnerBeans.getFriends()); + assertThat(hasInnerBeans.getFriends()).isNotNull(); Object[] friends = hasInnerBeans.getFriends().toArray(); - assertEquals(3, friends.length); + assertThat(friends.length).isEqualTo(3); DerivedTestBean inner2 = (DerivedTestBean) friends[0]; - assertEquals("inner2", inner2.getName()); - assertTrue(inner2.getBeanName().startsWith(DerivedTestBean.class.getName())); - assertNotNull(inner2); - assertEquals(7, inner2.getAge()); + assertThat(inner2.getName()).isEqualTo("inner2"); + assertThat(inner2.getBeanName().startsWith(DerivedTestBean.class.getName())).isTrue(); + assertThat(inner2).isNotNull(); + assertThat(inner2.getAge()).isEqualTo(7); TestBean innerFactory = (TestBean) friends[1]; - assertEquals(DummyFactory.SINGLETON_NAME, innerFactory.getName()); + assertThat(innerFactory.getName()).isEqualTo(DummyFactory.SINGLETON_NAME); TestBean inner5 = (TestBean) friends[2]; - assertTrue(inner5.getBeanName().startsWith("innerBean")); + assertThat(inner5.getBeanName().startsWith("innerBean")).isTrue(); } @Test @@ -298,8 +291,8 @@ public class XmlBeanFactoryTests { catch (BeanCreationException ex) { // Check whether message contains outer bean name. ex.printStackTrace(); - assertTrue(ex.getMessage().contains("failsOnInnerBean")); - assertTrue(ex.getMessage().contains("someMap")); + assertThat(ex.getMessage().contains("failsOnInnerBean")).isTrue(); + assertThat(ex.getMessage().contains("someMap")).isTrue(); } try { @@ -308,8 +301,8 @@ public class XmlBeanFactoryTests { catch (BeanCreationException ex) { // Check whether message contains outer bean name. ex.printStackTrace(); - assertTrue(ex.getMessage().contains("failsOnInnerBeanForConstructor")); - assertTrue(ex.getMessage().contains("constructor argument")); + assertThat(ex.getMessage().contains("failsOnInnerBeanForConstructor")).isTrue(); + assertThat(ex.getMessage().contains("constructor argument")).isTrue(); } } @@ -319,14 +312,14 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); - assertEquals(TestBean.class, child.getType("inheritsFromParentFactory")); + assertThat(child.getType("inheritsFromParentFactory")).isEqualTo(TestBean.class); TestBean inherits = (TestBean) child.getBean("inheritsFromParentFactory"); // Name property value is overridden - assertTrue(inherits.getName().equals("override")); + assertThat(inherits.getName().equals("override")).isTrue(); // Age property is inherited from bean in parent factory - assertTrue(inherits.getAge() == 1); + assertThat(inherits.getAge() == 1).isTrue(); TestBean inherits2 = (TestBean) child.getBean("inheritsFromParentFactory"); - assertFalse(inherits2 == inherits); + assertThat(inherits2 == inherits).isFalse(); } @Test @@ -335,13 +328,13 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); - assertEquals(DerivedTestBean.class, child.getType("inheritsWithClass")); + assertThat(child.getType("inheritsWithClass")).isEqualTo(DerivedTestBean.class); DerivedTestBean inherits = (DerivedTestBean) child.getBean("inheritsWithDifferentClass"); // Name property value is overridden - assertTrue(inherits.getName().equals("override")); + assertThat(inherits.getName().equals("override")).isTrue(); // Age property is inherited from bean in parent factory - assertTrue(inherits.getAge() == 1); - assertTrue(inherits.wasInitialized()); + assertThat(inherits.getAge() == 1).isTrue(); + assertThat(inherits.wasInitialized()).isTrue(); } @Test @@ -350,13 +343,13 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); - assertEquals(DerivedTestBean.class, child.getType("inheritsWithClass")); + assertThat(child.getType("inheritsWithClass")).isEqualTo(DerivedTestBean.class); DerivedTestBean inherits = (DerivedTestBean) child.getBean("inheritsWithClass"); // Name property value is overridden - assertTrue(inherits.getName().equals("override")); + assertThat(inherits.getName().equals("override")).isTrue(); // Age property is inherited from bean in parent factory - assertTrue(inherits.getAge() == 1); - assertTrue(inherits.wasInitialized()); + assertThat(inherits.getAge() == 1).isTrue(); + assertThat(inherits.wasInitialized()).isTrue(); } @Test @@ -365,18 +358,18 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); - assertEquals(TestBean.class, child.getType("prototypeInheritsFromParentFactoryPrototype")); + assertThat(child.getType("prototypeInheritsFromParentFactoryPrototype")).isEqualTo(TestBean.class); TestBean inherits = (TestBean) child.getBean("prototypeInheritsFromParentFactoryPrototype"); // Name property value is overridden - assertTrue(inherits.getName().equals("prototype-override")); + assertThat(inherits.getName().equals("prototype-override")).isTrue(); // Age property is inherited from bean in parent factory - assertTrue(inherits.getAge() == 2); + assertThat(inherits.getAge() == 2).isTrue(); TestBean inherits2 = (TestBean) child.getBean("prototypeInheritsFromParentFactoryPrototype"); - assertFalse(inherits2 == inherits); + assertThat(inherits2 == inherits).isFalse(); inherits2.setAge(13); - assertTrue(inherits2.getAge() == 13); + assertThat(inherits2.getAge() == 13).isTrue(); // Shouldn't have changed first instance - assertTrue(inherits.getAge() == 2); + assertThat(inherits.getAge() == 2).isTrue(); } @Test @@ -387,15 +380,15 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); TestBean inherits = (TestBean) child.getBean("protoypeInheritsFromParentFactorySingleton"); // Name property value is overridden - assertTrue(inherits.getName().equals("prototypeOverridesInheritedSingleton")); + assertThat(inherits.getName().equals("prototypeOverridesInheritedSingleton")).isTrue(); // Age property is inherited from bean in parent factory - assertTrue(inherits.getAge() == 1); + assertThat(inherits.getAge() == 1).isTrue(); TestBean inherits2 = (TestBean) child.getBean("protoypeInheritsFromParentFactorySingleton"); - assertFalse(inherits2 == inherits); + assertThat(inherits2 == inherits).isFalse(); inherits2.setAge(13); - assertTrue(inherits2.getAge() == 13); + assertThat(inherits2.getAge() == 13).isTrue(); // Shouldn't have changed first instance - assertTrue(inherits.getAge() == 1); + assertThat(inherits.getAge() == 1).isTrue(); } @Test @@ -406,11 +399,11 @@ public class XmlBeanFactoryTests { TestBean david = (TestBean) xbf.getBean("magicDavid"); // the parent bean is autowiring - assertNotNull(david.getSpouse()); + assertThat(david.getSpouse()).isNotNull(); TestBean derivedDavid = (TestBean) xbf.getBean("magicDavidDerived"); // this fails while it inherits from the child bean - assertNull("autowiring not propagated along child relationships", derivedDavid.getSpouse()); + assertThat(derivedDavid.getSpouse()).as("autowiring not propagated along child relationships").isNull(); } @Test @@ -418,20 +411,20 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); parent.preInstantiateSingletons(); - assertTrue(parent.isSingleton("inheritedTestBeanWithoutClass")); + assertThat(parent.isSingleton("inheritedTestBeanWithoutClass")).isTrue(); // abstract beans should not match Map tbs = parent.getBeansOfType(TestBean.class); - assertEquals(2, tbs.size()); - assertTrue(tbs.containsKey("inheritedTestBeanPrototype")); - assertTrue(tbs.containsKey("inheritedTestBeanSingleton")); + assertThat(tbs.size()).isEqualTo(2); + assertThat(tbs.containsKey("inheritedTestBeanPrototype")).isTrue(); + assertThat(tbs.containsKey("inheritedTestBeanSingleton")).isTrue(); // abstract bean should throw exception on creation attempt assertThatExceptionOfType(BeanIsAbstractException.class).isThrownBy(() -> parent.getBean("inheritedTestBeanWithoutClass")); // non-abstract bean should work, even if it serves as parent - assertTrue(parent.getBean("inheritedTestBeanPrototype") instanceof TestBean); + assertThat(parent.getBean("inheritedTestBeanPrototype") instanceof TestBean).isTrue(); } @Test @@ -439,18 +432,18 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(DEP_MATERIALIZE_CONTEXT); - assertEquals(2, xbf.getBeansOfType(DummyBo.class, true, false).size()); - assertEquals(3, xbf.getBeansOfType(DummyBo.class, true, true).size()); - assertEquals(3, xbf.getBeansOfType(DummyBo.class, true, false).size()); - assertEquals(3, xbf.getBeansOfType(DummyBo.class).size()); - assertEquals(2, xbf.getBeansOfType(DummyBoImpl.class, true, true).size()); - assertEquals(1, xbf.getBeansOfType(DummyBoImpl.class, false, true).size()); - assertEquals(2, xbf.getBeansOfType(DummyBoImpl.class).size()); + assertThat(xbf.getBeansOfType(DummyBo.class, true, false).size()).isEqualTo(2); + assertThat(xbf.getBeansOfType(DummyBo.class, true, true).size()).isEqualTo(3); + assertThat(xbf.getBeansOfType(DummyBo.class, true, false).size()).isEqualTo(3); + assertThat(xbf.getBeansOfType(DummyBo.class).size()).isEqualTo(3); + assertThat(xbf.getBeansOfType(DummyBoImpl.class, true, true).size()).isEqualTo(2); + assertThat(xbf.getBeansOfType(DummyBoImpl.class, false, true).size()).isEqualTo(1); + assertThat(xbf.getBeansOfType(DummyBoImpl.class).size()).isEqualTo(2); DummyBoImpl bos = (DummyBoImpl) xbf.getBean("boSingleton"); DummyBoImpl bop = (DummyBoImpl) xbf.getBean("boPrototype"); - assertNotSame(bos, bop); - assertTrue(bos.dao == bop.dao); + assertThat(bop).isNotSameAs(bos); + assertThat(bos.dao == bop.dao).isTrue(); } @Test @@ -461,11 +454,11 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); TestBean inherits = (TestBean) child.getBean("inheritedTestBean"); // Name property value is overridden - assertTrue(inherits.getName().equals("overrideParentBean")); + assertThat(inherits.getName().equals("overrideParentBean")).isTrue(); // Age property is inherited from bean in parent factory - assertTrue(inherits.getAge() == 1); + assertThat(inherits.getAge() == 1).isTrue(); TestBean inherits2 = (TestBean) child.getBean("inheritedTestBean"); - assertTrue(inherits2 != inherits); + assertThat(inherits2 != inherits).isTrue(); } /** @@ -497,11 +490,11 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); TestBean inherits = (TestBean) child.getBean("singletonInheritsFromParentFactoryPrototype"); // Name property value is overridden - assertTrue(inherits.getName().equals("prototype-override")); + assertThat(inherits.getName().equals("prototype-override")).isTrue(); // Age property is inherited from bean in parent factory - assertTrue(inherits.getAge() == 2); + assertThat(inherits.getAge() == 2).isTrue(); TestBean inherits2 = (TestBean) child.getBean("singletonInheritsFromParentFactoryPrototype"); - assertTrue(inherits2 == inherits); + assertThat(inherits2 == inherits).isTrue(); } @Test @@ -512,7 +505,7 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); TestBean beanFromChild = (TestBean) child.getBean("inheritedTestBeanSingleton"); - assertTrue("singleton from parent and child is the same", beanFromParent == beanFromChild); + assertThat(beanFromParent == beanFromChild).as("singleton from parent and child is the same").isTrue(); } @Test @@ -522,7 +515,7 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); IndexedTestBean bean = (IndexedTestBean) child.getBean("indexedTestBean"); - assertEquals("name applied correctly", "myname", bean.getArray()[0].getName()); + assertThat(bean.getArray()[0].getName()).as("name applied correctly").isEqualTo("myname"); } @Test @@ -536,11 +529,11 @@ public class XmlBeanFactoryTests { TestBean ego = (TestBean) xbf.getBean("ego"); TestBean complexInnerEgo = (TestBean) xbf.getBean("complexInnerEgo"); TestBean complexEgo = (TestBean) xbf.getBean("complexEgo"); - assertTrue("Correct circular reference", jenny.getSpouse() == david); - assertTrue("Correct circular reference", david.getSpouse() == jenny); - assertTrue("Correct circular reference", ego.getSpouse() == ego); - assertTrue("Correct circular reference", complexInnerEgo.getSpouse().getSpouse() == complexInnerEgo); - assertTrue("Correct circular reference", complexEgo.getSpouse().getSpouse() == complexEgo); + assertThat(jenny.getSpouse() == david).as("Correct circular reference").isTrue(); + assertThat(david.getSpouse() == jenny).as("Correct circular reference").isTrue(); + assertThat(ego.getSpouse() == ego).as("Correct circular reference").isTrue(); + assertThat(complexInnerEgo.getSpouse().getSpouse() == complexInnerEgo).as("Correct circular reference").isTrue(); + assertThat(complexEgo.getSpouse().getSpouse() == complexEgo).as("Correct circular reference").isTrue(); } @Test @@ -551,7 +544,7 @@ public class XmlBeanFactoryTests { reader.loadBeanDefinitions(REFTYPES_CONTEXT); xbf.getBean("egoBridge"); TestBean complexEgo = (TestBean) xbf.getBean("complexEgo"); - assertTrue("Correct circular reference", complexEgo.getSpouse().getSpouse() == complexEgo); + assertThat(complexEgo.getSpouse().getSpouse() == complexEgo).as("Correct circular reference").isTrue(); } @Test @@ -561,9 +554,9 @@ public class XmlBeanFactoryTests { reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); reader.loadBeanDefinitions(REFTYPES_CONTEXT); TestBean ego1 = (TestBean) xbf.getBean("ego1"); - assertTrue("Correct circular reference", ego1.getSpouse().getSpouse() == ego1); + assertThat(ego1.getSpouse().getSpouse() == ego1).as("Correct circular reference").isTrue(); TestBean ego3 = (TestBean) xbf.getBean("ego3"); - assertTrue("Correct circular reference", ego3.getSpouse().getSpouse() == ego3); + assertThat(ego3.getSpouse().getSpouse() == ego3).as("Correct circular reference").isTrue(); } @Test @@ -601,14 +594,14 @@ public class XmlBeanFactoryTests { ITestBean jenny = (ITestBean) xbf.getBean("jenny"); ITestBean david = (ITestBean) xbf.getBean("david"); - assertTrue(AopUtils.isAopProxy(jenny)); - assertTrue(AopUtils.isAopProxy(david)); - assertSame(david, jenny.getSpouse()); - assertNotSame(jenny, david.getSpouse()); - assertEquals("Jenny", david.getSpouse().getName()); - assertSame(david, david.getSpouse().getSpouse()); - assertTrue(AopUtils.isAopProxy(jenny.getSpouse())); - assertTrue(!AopUtils.isAopProxy(david.getSpouse())); + assertThat(AopUtils.isAopProxy(jenny)).isTrue(); + assertThat(AopUtils.isAopProxy(david)).isTrue(); + assertThat(jenny.getSpouse()).isSameAs(david); + assertThat(david.getSpouse()).isNotSameAs(jenny); + assertThat(david.getSpouse().getName()).isEqualTo("Jenny"); + assertThat(david.getSpouse().getSpouse()).isSameAs(david); + assertThat(AopUtils.isAopProxy(jenny.getSpouse())).isTrue(); + assertThat(!AopUtils.isAopProxy(david.getSpouse())).isTrue(); } @Test @@ -617,7 +610,7 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(FACTORY_CIRCLE_CONTEXT); TestBean tb = (TestBean) xbf.getBean("singletonFactory"); DummyFactory db = (DummyFactory) xbf.getBean("&singletonFactory"); - assertTrue(tb == db.getOtherTestBean()); + assertThat(tb == db.getOtherTestBean()).isTrue(); } @Test @@ -633,10 +626,10 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(COMPLEX_FACTORY_CIRCLE_CONTEXT); xbf.getBean("proxy1"); // check that unused instances from autowiring got removed - assertEquals(4, xbf.getSingletonCount()); + assertThat(xbf.getSingletonCount()).isEqualTo(4); // properly create the remaining two instances xbf.getBean("proxy2"); - assertEquals(5, xbf.getSingletonCount()); + assertThat(xbf.getSingletonCount()).isEqualTo(5); } @Test @@ -653,7 +646,7 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT); DoubleInitializer in = (DoubleInitializer) xbf.getBean("init-method1"); // Initializer should have doubled value - assertEquals(14, in.getNum()); + assertThat(in.getNum()).isEqualTo(14); } /** @@ -691,17 +684,17 @@ public class XmlBeanFactoryTests { InitAndIB.constructed = false; DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT); - assertFalse(InitAndIB.constructed); + assertThat(InitAndIB.constructed).isFalse(); xbf.preInstantiateSingletons(); - assertFalse(InitAndIB.constructed); + assertThat(InitAndIB.constructed).isFalse(); InitAndIB iib = (InitAndIB) xbf.getBean("init-and-ib"); - assertTrue(InitAndIB.constructed); - assertTrue(iib.afterPropertiesSetInvoked && iib.initMethodInvoked); - assertTrue(!iib.destroyed && !iib.customDestroyed); + assertThat(InitAndIB.constructed).isTrue(); + assertThat(iib.afterPropertiesSetInvoked && iib.initMethodInvoked).isTrue(); + assertThat(!iib.destroyed && !iib.customDestroyed).isTrue(); xbf.destroySingletons(); - assertTrue(iib.destroyed && iib.customDestroyed); + assertThat(iib.destroyed && iib.customDestroyed).isTrue(); xbf.destroySingletons(); - assertTrue(iib.destroyed && iib.customDestroyed); + assertThat(iib.destroyed && iib.customDestroyed).isTrue(); } /** @@ -712,17 +705,17 @@ public class XmlBeanFactoryTests { InitAndIB.constructed = false; DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT); - assertFalse(InitAndIB.constructed); + assertThat(InitAndIB.constructed).isFalse(); xbf.preInstantiateSingletons(); - assertFalse(InitAndIB.constructed); + assertThat(InitAndIB.constructed).isFalse(); InitAndIB iib = (InitAndIB) xbf.getBean("ib-same-init"); - assertTrue(InitAndIB.constructed); - assertTrue(iib.afterPropertiesSetInvoked && !iib.initMethodInvoked); - assertTrue(!iib.destroyed && !iib.customDestroyed); + assertThat(InitAndIB.constructed).isTrue(); + assertThat(iib.afterPropertiesSetInvoked && !iib.initMethodInvoked).isTrue(); + assertThat(!iib.destroyed && !iib.customDestroyed).isTrue(); xbf.destroySingletons(); - assertTrue(iib.destroyed && !iib.customDestroyed); + assertThat(iib.destroyed && !iib.customDestroyed).isTrue(); xbf.destroySingletons(); - assertTrue(iib.destroyed && !iib.customDestroyed); + assertThat(iib.destroyed && !iib.customDestroyed).isTrue(); } @Test @@ -730,14 +723,14 @@ public class XmlBeanFactoryTests { InitAndIB.constructed = false; DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(DEFAULT_LAZY_CONTEXT); - assertFalse(InitAndIB.constructed); + assertThat(InitAndIB.constructed).isFalse(); xbf.preInstantiateSingletons(); - assertTrue(InitAndIB.constructed); + assertThat(InitAndIB.constructed).isTrue(); try { xbf.getBean("lazy-and-bad"); } catch (BeanCreationException ex) { - assertTrue(ex.getCause() instanceof IOException); + assertThat(ex.getCause() instanceof IOException).isTrue(); } } @@ -782,43 +775,43 @@ public class XmlBeanFactoryTests { DependenciesBean rod1 = (DependenciesBean) xbf.getBean("rod1"); TestBean kerry = (TestBean) xbf.getBean("spouse"); // should have been autowired - assertEquals(kerry, rod1.getSpouse()); + assertThat(rod1.getSpouse()).isEqualTo(kerry); DependenciesBean rod1a = (DependenciesBean) xbf.getBean("rod1a"); // should have been autowired - assertEquals(kerry, rod1a.getSpouse()); + assertThat(rod1a.getSpouse()).isEqualTo(kerry); DependenciesBean rod2 = (DependenciesBean) xbf.getBean("rod2"); // should have been autowired - assertEquals(kerry, rod2.getSpouse()); + assertThat(rod2.getSpouse()).isEqualTo(kerry); DependenciesBean rod2a = (DependenciesBean) xbf.getBean("rod2a"); // should have been set explicitly - assertEquals(kerry, rod2a.getSpouse()); + assertThat(rod2a.getSpouse()).isEqualTo(kerry); ConstructorDependenciesBean rod3 = (ConstructorDependenciesBean) xbf.getBean("rod3"); IndexedTestBean other = (IndexedTestBean) xbf.getBean("other"); // should have been autowired - assertEquals(kerry, rod3.getSpouse1()); - assertEquals(kerry, rod3.getSpouse2()); - assertEquals(other, rod3.getOther()); + assertThat(rod3.getSpouse1()).isEqualTo(kerry); + assertThat(rod3.getSpouse2()).isEqualTo(kerry); + assertThat(rod3.getOther()).isEqualTo(other); ConstructorDependenciesBean rod3a = (ConstructorDependenciesBean) xbf.getBean("rod3a"); // should have been autowired - assertEquals(kerry, rod3a.getSpouse1()); - assertEquals(kerry, rod3a.getSpouse2()); - assertEquals(other, rod3a.getOther()); + assertThat(rod3a.getSpouse1()).isEqualTo(kerry); + assertThat(rod3a.getSpouse2()).isEqualTo(kerry); + assertThat(rod3a.getOther()).isEqualTo(other); assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> xbf.getBean("rod4", ConstructorDependenciesBean.class)); DependenciesBean rod5 = (DependenciesBean) xbf.getBean("rod5"); // Should not have been autowired - assertNull(rod5.getSpouse()); + assertThat((Object) rod5.getSpouse()).isNull(); BeanFactory appCtx = (BeanFactory) xbf.getBean("childAppCtx"); - assertTrue(appCtx.containsBean("rod1")); - assertTrue(appCtx.containsBean("jenny")); + assertThat(appCtx.containsBean("rod1")).isTrue(); + assertThat(appCtx.containsBean("jenny")).isTrue(); } @Test @@ -828,13 +821,13 @@ public class XmlBeanFactoryTests { DependenciesBean rod1 = (DependenciesBean) xbf.getBean("rod1"); // should have been autowired - assertNotNull(rod1.getSpouse()); - assertTrue(rod1.getSpouse().getName().equals("Kerry")); + assertThat(rod1.getSpouse()).isNotNull(); + assertThat(rod1.getSpouse().getName().equals("Kerry")).isTrue(); DependenciesBean rod2 = (DependenciesBean) xbf.getBean("rod2"); // should have been autowired - assertNotNull(rod2.getSpouse()); - assertTrue(rod2.getSpouse().getName().equals("Kerry")); + assertThat(rod2.getSpouse()).isNotNull(); + assertThat(rod2.getSpouse().getName().equals("Kerry")).isTrue(); } @Test @@ -844,35 +837,35 @@ public class XmlBeanFactoryTests { ConstructorDependenciesBean rod1 = (ConstructorDependenciesBean) xbf.getBean("rod1"); TestBean kerry = (TestBean) xbf.getBean("kerry2"); // should have been autowired - assertEquals(kerry, rod1.getSpouse1()); - assertEquals(0, rod1.getAge()); - assertEquals(null, rod1.getName()); + assertThat(rod1.getSpouse1()).isEqualTo(kerry); + assertThat(rod1.getAge()).isEqualTo(0); + assertThat(rod1.getName()).isEqualTo(null); ConstructorDependenciesBean rod2 = (ConstructorDependenciesBean) xbf.getBean("rod2"); TestBean kerry1 = (TestBean) xbf.getBean("kerry1"); TestBean kerry2 = (TestBean) xbf.getBean("kerry2"); // should have been autowired - assertEquals(kerry2, rod2.getSpouse1()); - assertEquals(kerry1, rod2.getSpouse2()); - assertEquals(0, rod2.getAge()); - assertEquals(null, rod2.getName()); + assertThat(rod2.getSpouse1()).isEqualTo(kerry2); + assertThat(rod2.getSpouse2()).isEqualTo(kerry1); + assertThat(rod2.getAge()).isEqualTo(0); + assertThat(rod2.getName()).isEqualTo(null); ConstructorDependenciesBean rod = (ConstructorDependenciesBean) xbf.getBean("rod3"); IndexedTestBean other = (IndexedTestBean) xbf.getBean("other"); // should have been autowired - assertEquals(kerry, rod.getSpouse1()); - assertEquals(kerry, rod.getSpouse2()); - assertEquals(other, rod.getOther()); - assertEquals(0, rod.getAge()); - assertEquals(null, rod.getName()); + assertThat(rod.getSpouse1()).isEqualTo(kerry); + assertThat(rod.getSpouse2()).isEqualTo(kerry); + assertThat(rod.getOther()).isEqualTo(other); + assertThat(rod.getAge()).isEqualTo(0); + assertThat(rod.getName()).isEqualTo(null); xbf.getBean("rod4", ConstructorDependenciesBean.class); // should have been autowired - assertEquals(kerry, rod.getSpouse1()); - assertEquals(kerry, rod.getSpouse2()); - assertEquals(other, rod.getOther()); - assertEquals(0, rod.getAge()); - assertEquals(null, rod.getName()); + assertThat(rod.getSpouse1()).isEqualTo(kerry); + assertThat(rod.getSpouse2()).isEqualTo(kerry); + assertThat(rod.getOther()).isEqualTo(other); + assertThat(rod.getAge()).isEqualTo(0); + assertThat(rod.getName()).isEqualTo(null); } @Test @@ -885,24 +878,24 @@ public class XmlBeanFactoryTests { TestBean kerry2 = (TestBean) xbf.getBean("kerry2"); IndexedTestBean other = (IndexedTestBean) xbf.getBean("other"); // should have been autowired - assertEquals(kerry2, rod5.getSpouse1()); - assertEquals(kerry1, rod5.getSpouse2()); - assertEquals(other, rod5.getOther()); - assertEquals(99, rod5.getAge()); - assertEquals("myname", rod5.getName()); + assertThat(rod5.getSpouse1()).isEqualTo(kerry2); + assertThat(rod5.getSpouse2()).isEqualTo(kerry1); + assertThat(rod5.getOther()).isEqualTo(other); + assertThat(rod5.getAge()).isEqualTo(99); + assertThat(rod5.getName()).isEqualTo("myname"); DerivedConstructorDependenciesBean rod6 = (DerivedConstructorDependenciesBean) xbf.getBean("rod6"); // should have been autowired - assertTrue(rod6.initialized); - assertTrue(!rod6.destroyed); - assertEquals(kerry2, rod6.getSpouse1()); - assertEquals(kerry1, rod6.getSpouse2()); - assertEquals(other, rod6.getOther()); - assertEquals(0, rod6.getAge()); - assertEquals(null, rod6.getName()); + assertThat(rod6.initialized).isTrue(); + assertThat(!rod6.destroyed).isTrue(); + assertThat(rod6.getSpouse1()).isEqualTo(kerry2); + assertThat(rod6.getSpouse2()).isEqualTo(kerry1); + assertThat(rod6.getOther()).isEqualTo(other); + assertThat(rod6.getAge()).isEqualTo(0); + assertThat(rod6.getName()).isEqualTo(null); xbf.destroySingletons(); - assertTrue(rod6.destroyed); + assertThat(rod6.destroyed).isTrue(); } @Test @@ -914,9 +907,9 @@ public class XmlBeanFactoryTests { xbf.getBean("rod2Accessor"); } catch (BeanCreationException ex) { - assertTrue(ex.toString().contains("touchy")); + assertThat(ex.toString().contains("touchy")).isTrue(); ex.printStackTrace(); - assertNull(ex.getRelatedCauses()); + assertThat((Object) ex.getRelatedCauses()).isNull(); } } @@ -928,45 +921,45 @@ public class XmlBeanFactoryTests { TestBean kerry2 = (TestBean) xbf.getBean("kerry2"); ConstructorDependenciesBean rod9 = (ConstructorDependenciesBean) xbf.getBean("rod9"); - assertEquals(99, rod9.getAge()); + assertThat(rod9.getAge()).isEqualTo(99); ConstructorDependenciesBean rod9a = (ConstructorDependenciesBean) xbf.getBean("rod9", 98); - assertEquals(98, rod9a.getAge()); + assertThat(rod9a.getAge()).isEqualTo(98); ConstructorDependenciesBean rod9b = (ConstructorDependenciesBean) xbf.getBean("rod9", "myName"); - assertEquals("myName", rod9b.getName()); + assertThat(rod9b.getName()).isEqualTo("myName"); ConstructorDependenciesBean rod9c = (ConstructorDependenciesBean) xbf.getBean("rod9", 97); - assertEquals(97, rod9c.getAge()); + assertThat(rod9c.getAge()).isEqualTo(97); ConstructorDependenciesBean rod10 = (ConstructorDependenciesBean) xbf.getBean("rod10"); - assertEquals(null, rod10.getName()); + assertThat(rod10.getName()).isEqualTo(null); ConstructorDependenciesBean rod11 = (ConstructorDependenciesBean) xbf.getBean("rod11"); - assertEquals(kerry2, rod11.getSpouse1()); + assertThat(rod11.getSpouse1()).isEqualTo(kerry2); ConstructorDependenciesBean rod12 = (ConstructorDependenciesBean) xbf.getBean("rod12"); - assertEquals(kerry1, rod12.getSpouse1()); - assertNull(rod12.getSpouse2()); + assertThat(rod12.getSpouse1()).isEqualTo(kerry1); + assertThat(rod12.getSpouse2()).isNull(); ConstructorDependenciesBean rod13 = (ConstructorDependenciesBean) xbf.getBean("rod13"); - assertEquals(kerry1, rod13.getSpouse1()); - assertEquals(kerry2, rod13.getSpouse2()); + assertThat(rod13.getSpouse1()).isEqualTo(kerry1); + assertThat(rod13.getSpouse2()).isEqualTo(kerry2); ConstructorDependenciesBean rod14 = (ConstructorDependenciesBean) xbf.getBean("rod14"); - assertEquals(kerry1, rod14.getSpouse1()); - assertEquals(kerry2, rod14.getSpouse2()); + assertThat(rod14.getSpouse1()).isEqualTo(kerry1); + assertThat(rod14.getSpouse2()).isEqualTo(kerry2); ConstructorDependenciesBean rod15 = (ConstructorDependenciesBean) xbf.getBean("rod15"); - assertEquals(kerry2, rod15.getSpouse1()); - assertEquals(kerry1, rod15.getSpouse2()); + assertThat(rod15.getSpouse1()).isEqualTo(kerry2); + assertThat(rod15.getSpouse2()).isEqualTo(kerry1); ConstructorDependenciesBean rod16 = (ConstructorDependenciesBean) xbf.getBean("rod16"); - assertEquals(kerry2, rod16.getSpouse1()); - assertEquals(kerry1, rod16.getSpouse2()); - assertEquals(29, rod16.getAge()); + assertThat(rod16.getSpouse1()).isEqualTo(kerry2); + assertThat(rod16.getSpouse2()).isEqualTo(kerry1); + assertThat(rod16.getAge()).isEqualTo(29); ConstructorDependenciesBean rod17 = (ConstructorDependenciesBean) xbf.getBean("rod17"); - assertEquals(kerry1, rod17.getSpouse1()); - assertEquals(kerry2, rod17.getSpouse2()); - assertEquals(29, rod17.getAge()); + assertThat(rod17.getSpouse1()).isEqualTo(kerry1); + assertThat(rod17.getSpouse2()).isEqualTo(kerry2); + assertThat(rod17.getAge()).isEqualTo(29); } @Test @@ -974,15 +967,15 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); SimpleConstructorArgBean cd1 = (SimpleConstructorArgBean) xbf.getBean("rod18"); - assertEquals(0, cd1.getAge()); + assertThat(cd1.getAge()).isEqualTo(0); SimpleConstructorArgBean cd2 = (SimpleConstructorArgBean) xbf.getBean("rod18", 98); - assertEquals(98, cd2.getAge()); + assertThat(cd2.getAge()).isEqualTo(98); SimpleConstructorArgBean cd3 = (SimpleConstructorArgBean) xbf.getBean("rod18", "myName"); - assertEquals("myName", cd3.getName()); + assertThat(cd3.getName()).isEqualTo("myName"); SimpleConstructorArgBean cd4 = (SimpleConstructorArgBean) xbf.getBean("rod18"); - assertEquals(0, cd4.getAge()); + assertThat(cd4.getAge()).isEqualTo(0); SimpleConstructorArgBean cd5 = (SimpleConstructorArgBean) xbf.getBean("rod18", 97); - assertEquals(97, cd5.getAge()); + assertThat(cd5.getAge()).isEqualTo(97); } @Test @@ -990,7 +983,7 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); File file = (File) xbf.getBean("file"); - assertEquals(File.separator + "test", file.getPath()); + assertThat(file.getPath()).isEqualTo((File.separator + "test")); } @Test @@ -1070,13 +1063,13 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(resource); xbf.preInstantiateSingletons(); xbf.destroySingletons(); - assertTrue(PreparingBean1.prepared); - assertTrue(PreparingBean1.destroyed); - assertTrue(PreparingBean2.prepared); - assertTrue(PreparingBean2.destroyed); - assertEquals(nrOfHoldingBeans, DependingBean.destroyCount); + assertThat(PreparingBean1.prepared).isTrue(); + assertThat(PreparingBean1.destroyed).isTrue(); + assertThat(PreparingBean2.prepared).isTrue(); + assertThat(PreparingBean2.destroyed).isTrue(); + assertThat(DependingBean.destroyCount).isEqualTo(nrOfHoldingBeans); if (!xbf.getBeansOfType(HoldingBean.class, false, false).isEmpty()) { - assertEquals(nrOfHoldingBeans, HoldingBean.destroyCount); + assertThat(HoldingBean.destroyCount).isEqualTo(nrOfHoldingBeans); } } @@ -1104,7 +1097,7 @@ public class XmlBeanFactoryTests { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); reader.setBeanClassLoader(null); reader.loadBeanDefinitions(CLASS_NOT_FOUND_CONTEXT); - assertEquals("WhatALotOfRubbish", bf.getBeanDefinition("classNotFound").getBeanClassName()); + assertThat(bf.getBeanDefinition("classNotFound").getBeanClassName()).isEqualTo("WhatALotOfRubbish"); } @Test @@ -1116,19 +1109,19 @@ public class XmlBeanFactoryTests { // comes from "resource.xml" ResourceTestBean resource2 = (ResourceTestBean) xbf.getBean("resource2"); - assertTrue(resource1.getResource() instanceof ClassPathResource); + assertThat(resource1.getResource() instanceof ClassPathResource).isTrue(); StringWriter writer = new StringWriter(); FileCopyUtils.copy(new InputStreamReader(resource1.getResource().getInputStream()), writer); - assertEquals("test", writer.toString()); + assertThat(writer.toString()).isEqualTo("test"); writer = new StringWriter(); FileCopyUtils.copy(new InputStreamReader(resource1.getInputStream()), writer); - assertEquals("test", writer.toString()); + assertThat(writer.toString()).isEqualTo("test"); writer = new StringWriter(); FileCopyUtils.copy(new InputStreamReader(resource2.getResource().getInputStream()), writer); - assertEquals("test", writer.toString()); + assertThat(writer.toString()).isEqualTo("test"); writer = new StringWriter(); FileCopyUtils.copy(new InputStreamReader(resource2.getInputStream()), writer); - assertEquals("test", writer.toString()); + assertThat(writer.toString()).isEqualTo("test"); } @Test @@ -1171,9 +1164,9 @@ public class XmlBeanFactoryTests { } /** - * @since 3.2.8 and 4.0.2 - * @see SPR-10785 and SPR-10785 and SPR-11420 + * @since 3.2.8 and 4.0.2 */ @Test public void methodInjectedBeanMustBeOfSameEnhancedCglibSubclassTypeAcrossBeanFactories() { @@ -1184,14 +1177,13 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(bf).loadBeanDefinitions(OVERRIDES_CONTEXT); final Class currentClass = bf.getBean("overrideOneMethod").getClass(); - assertTrue("Method injected bean class [" + currentClass + "] must be a CGLIB enhanced subclass.", - ClassUtils.isCglibProxyClass(currentClass)); + assertThat(ClassUtils.isCglibProxyClass(currentClass)).as("Method injected bean class [" + currentClass + "] must be a CGLIB enhanced subclass.").isTrue(); if (firstClass == null) { firstClass = currentClass; } else { - assertEquals(firstClass, currentClass); + assertThat(currentClass).isEqualTo(firstClass); } } } @@ -1218,16 +1210,16 @@ public class XmlBeanFactoryTests { sw.stop(); // System.out.println(sw); if (!LogFactory.getLog(DefaultListableBeanFactory.class).isDebugEnabled()) { - assertTrue(sw.getTotalTimeMillis() < 2000); + assertThat(sw.getTotalTimeMillis() < 2000).isTrue(); } // Now test distinct bean with swapped value in factory, to ensure the two are independent OverrideOneMethod swappedOom = (OverrideOneMethod) xbf.getBean("overrideOneMethodSwappedReturnValues"); TestBean tb = swappedOom.getPrototypeDependency(); - assertEquals("David", tb.getName()); + assertThat(tb.getName()).isEqualTo("David"); tb = swappedOom.protectedOverrideSingleton(); - assertEquals("Jenny", tb.getName()); + assertThat(tb.getName()).isEqualTo("Jenny"); } private void lookupOverrideMethodsWithSetterInjection(BeanFactory xbf, @@ -1235,32 +1227,32 @@ public class XmlBeanFactoryTests { OverrideOneMethod oom = (OverrideOneMethod) xbf.getBean(beanName); if (singleton) { - assertSame(oom, xbf.getBean(beanName)); + assertThat(xbf.getBean(beanName)).isSameAs(oom); } else { - assertNotSame(oom, xbf.getBean(beanName)); + assertThat(xbf.getBean(beanName)).isNotSameAs(oom); } TestBean jenny1 = oom.getPrototypeDependency(); - assertEquals("Jenny", jenny1.getName()); + assertThat(jenny1.getName()).isEqualTo("Jenny"); TestBean jenny2 = oom.getPrototypeDependency(); - assertEquals("Jenny", jenny2.getName()); - assertNotSame(jenny1, jenny2); + assertThat(jenny2.getName()).isEqualTo("Jenny"); + assertThat(jenny2).isNotSameAs(jenny1); // Check that the bean can invoke the overridden method on itself // This differs from Spring's AOP support, which has a distinct notion // of a "target" object, meaning that the target needs explicit knowledge // of AOP proxying to invoke an advised method on itself. TestBean jenny3 = oom.invokesOverriddenMethodOnSelf(); - assertEquals("Jenny", jenny3.getName()); - assertNotSame(jenny1, jenny3); + assertThat(jenny3.getName()).isEqualTo("Jenny"); + assertThat(jenny3).isNotSameAs(jenny1); // Now try protected method, and singleton TestBean dave1 = oom.protectedOverrideSingleton(); - assertEquals("David", dave1.getName()); + assertThat(dave1.getName()).isEqualTo("David"); TestBean dave2 = oom.protectedOverrideSingleton(); - assertEquals("David", dave2.getName()); - assertSame(dave1, dave2); + assertThat(dave2.getName()).isEqualTo("David"); + assertThat(dave2).isSameAs(dave1); } @Test @@ -1273,42 +1265,41 @@ public class XmlBeanFactoryTests { // Same contract as for overrides.xml TestBean jenny1 = oom.getPrototypeDependency(); - assertEquals("Jenny", jenny1.getName()); + assertThat(jenny1.getName()).isEqualTo("Jenny"); TestBean jenny2 = oom.getPrototypeDependency(); - assertEquals("Jenny", jenny2.getName()); - assertNotSame(jenny1, jenny2); + assertThat(jenny2.getName()).isEqualTo("Jenny"); + assertThat(jenny2).isNotSameAs(jenny1); TestBean notJenny = oom.getPrototypeDependency("someParam"); - assertTrue(!"Jenny".equals(notJenny.getName())); + assertThat(!"Jenny".equals(notJenny.getName())).isTrue(); // Now try protected method, and singleton TestBean dave1 = oom.protectedOverrideSingleton(); - assertEquals("David", dave1.getName()); + assertThat(dave1.getName()).isEqualTo("David"); TestBean dave2 = oom.protectedOverrideSingleton(); - assertEquals("David", dave2.getName()); - assertSame(dave1, dave2); + assertThat(dave2.getName()).isEqualTo("David"); + assertThat(dave2).isSameAs(dave1); // Check unadvised behaviour String str = "woierowijeiowiej"; - assertEquals(str, oom.echo(str)); + assertThat(oom.echo(str)).isEqualTo(str); // Now test replace String s = "this is not a palindrome"; String reverse = new StringBuffer(s).reverse().toString(); - assertEquals("Should have overridden to reverse, not echo", reverse, oom.replaceMe(s)); + assertThat(oom.replaceMe(s)).as("Should have overridden to reverse, not echo").isEqualTo(reverse); - assertEquals("Should have overridden no-arg overloaded replaceMe method to return fixed value", - FixedMethodReplacer.VALUE, oom.replaceMe()); + assertThat(oom.replaceMe()).as("Should have overridden no-arg overloaded replaceMe method to return fixed value").isEqualTo(FixedMethodReplacer.VALUE); OverrideOneMethodSubclass ooms = (OverrideOneMethodSubclass) xbf.getBean("replaceVoidMethod"); DoSomethingReplacer dos = (DoSomethingReplacer) xbf.getBean("doSomethingReplacer"); - assertEquals(null, dos.lastArg); + assertThat(dos.lastArg).isEqualTo(null); String s1 = ""; String s2 = "foo bar black sheep"; ooms.doSomething(s1); - assertEquals(s1, dos.lastArg); + assertThat(dos.lastArg).isEqualTo(s1); ooms.doSomething(s2); - assertEquals(s2, dos.lastArg); + assertThat(dos.lastArg).isEqualTo(s2); } @Test @@ -1322,17 +1313,16 @@ public class XmlBeanFactoryTests { // Check that the setter was invoked... // We should be able to combine Constructor and // Setter Injection - assertEquals("Setter string was set", "from property element", cio.getSetterString()); + assertThat(cio.getSetterString()).as("Setter string was set").isEqualTo("from property element"); // Jenny is a singleton TestBean jenny = (TestBean) xbf.getBean("jenny"); - assertSame(jenny, cio.getTestBean()); - assertSame(jenny, cio.getTestBean()); + assertThat(cio.getTestBean()).isSameAs(jenny); + assertThat(cio.getTestBean()).isSameAs(jenny); FactoryMethods fm1 = cio.createFactoryMethods(); FactoryMethods fm2 = cio.createFactoryMethods(); - assertNotSame("FactoryMethods reference is to a prototype", fm1, fm2); - assertSame("The two prototypes hold the same singleton reference", - fm1.getTestBean(), fm2.getTestBean()); + assertThat(fm2).as("FactoryMethods reference is to a prototype").isNotSameAs(fm1); + assertThat(fm2.getTestBean()).as("The two prototypes hold the same singleton reference").isSameAs(fm1.getTestBean()); } @Test @@ -1353,11 +1343,9 @@ public class XmlBeanFactoryTests { SerializableMethodReplacerCandidate s = (SerializableMethodReplacerCandidate) xbf.getBean("serializableReplacer"); String forwards = "this is forwards"; String backwards = new StringBuffer(forwards).reverse().toString(); - assertEquals(backwards, s.replaceMe(forwards)); + assertThat(s.replaceMe(forwards)).isEqualTo(backwards); // SPR-356: lookup methods & method replacers are not serializable. - assertFalse( - "Lookup methods and method replacers are not meant to be serializable.", - SerializationTestUtils.isSerializable(s)); + assertThat(SerializationTestUtils.isSerializable(s)).as("Lookup methods and method replacers are not meant to be serializable.").isFalse(); } @Test @@ -1367,17 +1355,17 @@ public class XmlBeanFactoryTests { reader.loadBeanDefinitions(OVERRIDES_CONTEXT); TestBean jenny1 = (TestBean) xbf.getBean("jennyChild"); - assertEquals(1, jenny1.getFriends().size()); + assertThat(jenny1.getFriends().size()).isEqualTo(1); Object friend1 = jenny1.getFriends().iterator().next(); - assertTrue(friend1 instanceof TestBean); + assertThat(friend1 instanceof TestBean).isTrue(); TestBean jenny2 = (TestBean) xbf.getBean("jennyChild"); - assertEquals(1, jenny2.getFriends().size()); + assertThat(jenny2.getFriends().size()).isEqualTo(1); Object friend2 = jenny2.getFriends().iterator().next(); - assertTrue(friend2 instanceof TestBean); + assertThat(friend2 instanceof TestBean).isTrue(); - assertNotSame(jenny1, jenny2); - assertNotSame(friend1, friend2); + assertThat(jenny2).isNotSameAs(jenny1); + assertThat(friend2).isNotSameAs(friend1); } @Test @@ -1386,10 +1374,10 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); SingleSimpleTypeConstructorBean bean = (SingleSimpleTypeConstructorBean) xbf.getBean("beanWithBoolean"); - assertTrue(bean.isSingleBoolean()); + assertThat(bean.isSingleBoolean()).isTrue(); SingleSimpleTypeConstructorBean bean2 = (SingleSimpleTypeConstructorBean) xbf.getBean("beanWithBoolean2"); - assertTrue(bean2.isSingleBoolean()); + assertThat(bean2.isSingleBoolean()).isTrue(); } @Test @@ -1398,12 +1386,12 @@ public class XmlBeanFactoryTests { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); SingleSimpleTypeConstructorBean bean = (SingleSimpleTypeConstructorBean) xbf.getBean("beanWithBooleanAndString"); - assertTrue(bean.isSecondBoolean()); - assertEquals("A String", bean.getTestString()); + assertThat(bean.isSecondBoolean()).isTrue(); + assertThat(bean.getTestString()).isEqualTo("A String"); SingleSimpleTypeConstructorBean bean2 = (SingleSimpleTypeConstructorBean) xbf.getBean("beanWithBooleanAndString2"); - assertTrue(bean2.isSecondBoolean()); - assertEquals("A String", bean2.getTestString()); + assertThat(bean2.isSecondBoolean()).isTrue(); + assertThat(bean2.getTestString()).isEqualTo("A String"); } @Test @@ -1411,8 +1399,8 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); DoubleBooleanConstructorBean bean = (DoubleBooleanConstructorBean) xbf.getBean("beanWithDoubleBoolean"); - assertEquals(Boolean.TRUE, bean.boolean1); - assertEquals(Boolean.FALSE, bean.boolean2); + assertThat(bean.boolean1).isEqualTo(Boolean.TRUE); + assertThat(bean.boolean2).isEqualTo(Boolean.FALSE); } @Test @@ -1420,8 +1408,8 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); DoubleBooleanConstructorBean bean = (DoubleBooleanConstructorBean) xbf.getBean("beanWithDoubleBooleanAndIndex"); - assertEquals(Boolean.FALSE, bean.boolean1); - assertEquals(Boolean.TRUE, bean.boolean2); + assertThat(bean.boolean1).isEqualTo(Boolean.FALSE); + assertThat(bean.boolean2).isEqualTo(Boolean.TRUE); } @Test @@ -1429,7 +1417,7 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); LenientDependencyTestBean bean = (LenientDependencyTestBean) xbf.getBean("lenientDependencyTestBean"); - assertTrue(bean.tb instanceof DerivedTestBean); + assertThat(bean.tb instanceof DerivedTestBean).isTrue(); } @Test @@ -1437,7 +1425,7 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); LenientDependencyTestBean bean = (LenientDependencyTestBean) xbf.getBean("lenientDependencyTestBeanFactoryMethod"); - assertTrue(bean.tb instanceof DerivedTestBean); + assertThat(bean.tb instanceof DerivedTestBean).isTrue(); } @Test @@ -1469,7 +1457,7 @@ public class XmlBeanFactoryTests { AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("string"); bd.setLenientConstructorResolution(false); String str = (String) xbf.getBean("string"); - assertEquals("test", str); + assertThat(str).isEqualTo("test"); } @Test @@ -1479,7 +1467,7 @@ public class XmlBeanFactoryTests { AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("stringConstructor"); bd.setLenientConstructorResolution(false); StringConstructorTestBean tb = (StringConstructorTestBean) xbf.getBean("stringConstructor"); - assertEquals("test", tb.name); + assertThat(tb.name).isEqualTo("test"); } @Test @@ -1487,9 +1475,9 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); ConstructorArrayTestBean bean = (ConstructorArrayTestBean) xbf.getBean("constructorArray"); - assertTrue(bean.array instanceof int[]); - assertEquals(1, ((int[]) bean.array).length); - assertEquals(1, ((int[]) bean.array)[0]); + assertThat(bean.array instanceof int[]).isTrue(); + assertThat(((int[]) bean.array).length).isEqualTo(1); + assertThat(((int[]) bean.array)[0]).isEqualTo(1); } @Test @@ -1497,9 +1485,9 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); ConstructorArrayTestBean bean = (ConstructorArrayTestBean) xbf.getBean("indexedConstructorArray"); - assertTrue(bean.array instanceof int[]); - assertEquals(1, ((int[]) bean.array).length); - assertEquals(1, ((int[]) bean.array)[0]); + assertThat(bean.array instanceof int[]).isTrue(); + assertThat(((int[]) bean.array).length).isEqualTo(1); + assertThat(((int[]) bean.array)[0]).isEqualTo(1); } @Test @@ -1507,8 +1495,8 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); ConstructorArrayTestBean bean = (ConstructorArrayTestBean) xbf.getBean("constructorArrayNoType"); - assertTrue(bean.array instanceof String[]); - assertEquals(0, ((String[]) bean.array).length); + assertThat(bean.array instanceof String[]).isTrue(); + assertThat(((String[]) bean.array).length).isEqualTo(0); } @Test @@ -1518,8 +1506,8 @@ public class XmlBeanFactoryTests { AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("constructorArrayNoType"); bd.setLenientConstructorResolution(false); ConstructorArrayTestBean bean = (ConstructorArrayTestBean) xbf.getBean("constructorArrayNoType"); - assertTrue(bean.array instanceof String[]); - assertEquals(0, ((String[]) bean.array).length); + assertThat(bean.array instanceof String[]).isTrue(); + assertThat(((String[]) bean.array).length).isEqualTo(0); } @Test @@ -1527,9 +1515,9 @@ public class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); AtomicInteger bean = (AtomicInteger) xbf.getBean("constructorUnresolvableName"); - assertEquals(1, bean.get()); + assertThat(bean.get()).isEqualTo(1); bean = (AtomicInteger) xbf.getBean("constructorUnresolvableNameWithIndex"); - assertEquals(1, bean.get()); + assertThat(bean.get()).isEqualTo(1); } @Test @@ -1554,8 +1542,8 @@ public class XmlBeanFactoryTests { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(DELEGATION_OVERRIDES_CONTEXT); OverrideOneMethod oom = (OverrideOneMethod) xbf.getBean("overrideOneMethodByAttribute"); - assertEquals("should not replace", "replaceMe:1", oom.replaceMe(1)); - assertEquals("should replace", "cba", oom.replaceMe("abc")); + assertThat(oom.replaceMe(1)).as("should not replace").isEqualTo("replaceMe:1"); + assertThat(oom.replaceMe("abc")).as("should replace").isEqualTo("cba"); } @Test @@ -1564,8 +1552,8 @@ public class XmlBeanFactoryTests { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(DELEGATION_OVERRIDES_CONTEXT); OverrideOneMethod oom = (OverrideOneMethod) xbf.getBean("overrideOneMethodByElement"); - assertEquals("should not replace", "replaceMe:1", oom.replaceMe(1)); - assertEquals("should replace", "cba", oom.replaceMe("abc")); + assertThat(oom.replaceMe(1)).as("should not replace").isEqualTo("replaceMe:1"); + assertThat(oom.replaceMe("abc")).as("should replace").isEqualTo("cba"); } public static class DoSomethingReplacer implements MethodReplacer { @@ -1574,8 +1562,8 @@ public class XmlBeanFactoryTests { @Override public Object reimplement(Object obj, Method method, Object[] args) throws Throwable { - assertEquals(1, args.length); - assertEquals("doSomething", method.getName()); + assertThat(args.length).isEqualTo(1); + assertThat(method.getName()).isEqualTo("doSomething"); lastArg = args[0]; return null; } diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java index d2dc953c4c1..c336e5420ba 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java @@ -62,9 +62,6 @@ import org.springframework.tests.sample.beans.TestBean; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for custom XML namespace handler implementations. @@ -116,17 +113,17 @@ public class CustomNamespaceHandlerTests { public void testProxyingDecorator() throws Exception { ITestBean bean = (ITestBean) this.beanFactory.getBean("debuggingTestBean"); assertTestBean(bean); - assertTrue(AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).isTrue(); Advisor[] advisors = ((Advised) bean).getAdvisors(); - assertEquals("Incorrect number of advisors", 1, advisors.length); - assertEquals("Incorrect advice class", DebugInterceptor.class, advisors[0].getAdvice().getClass()); + assertThat(advisors.length).as("Incorrect number of advisors").isEqualTo(1); + assertThat(advisors[0].getAdvice().getClass()).as("Incorrect advice class").isEqualTo(DebugInterceptor.class); } @Test public void testProxyingDecoratorNoInstance() throws Exception { String[] beanNames = this.beanFactory.getBeanNamesForType(ApplicationListener.class); - assertTrue(Arrays.asList(beanNames).contains("debuggingTestBeanNoInstance")); - assertEquals(ApplicationListener.class, this.beanFactory.getType("debuggingTestBeanNoInstance")); + assertThat(Arrays.asList(beanNames).contains("debuggingTestBeanNoInstance")).isTrue(); + assertThat(this.beanFactory.getType("debuggingTestBeanNoInstance")).isEqualTo(ApplicationListener.class); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> this.beanFactory.getBean("debuggingTestBeanNoInstance")) .satisfies(ex -> assertThat(ex.getRootCause()).isInstanceOf(BeanInstantiationException.class)); @@ -136,44 +133,44 @@ public class CustomNamespaceHandlerTests { public void testChainedDecorators() throws Exception { ITestBean bean = (ITestBean) this.beanFactory.getBean("chainedTestBean"); assertTestBean(bean); - assertTrue(AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).isTrue(); Advisor[] advisors = ((Advised) bean).getAdvisors(); - assertEquals("Incorrect number of advisors", 2, advisors.length); - assertEquals("Incorrect advice class", DebugInterceptor.class, advisors[0].getAdvice().getClass()); - assertEquals("Incorrect advice class", NopInterceptor.class, advisors[1].getAdvice().getClass()); + assertThat(advisors.length).as("Incorrect number of advisors").isEqualTo(2); + assertThat(advisors[0].getAdvice().getClass()).as("Incorrect advice class").isEqualTo(DebugInterceptor.class); + assertThat(advisors[1].getAdvice().getClass()).as("Incorrect advice class").isEqualTo(NopInterceptor.class); } @Test public void testDecorationViaAttribute() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition("decorateWithAttribute"); - assertEquals("foo", beanDefinition.getAttribute("objectName")); + assertThat(beanDefinition.getAttribute("objectName")).isEqualTo("foo"); } @Test // SPR-2728 public void testCustomElementNestedWithinUtilList() throws Exception { List things = (List) this.beanFactory.getBean("list.of.things"); - assertNotNull(things); - assertEquals(2, things.size()); + assertThat(things).isNotNull(); + assertThat(things.size()).isEqualTo(2); } @Test // SPR-2728 public void testCustomElementNestedWithinUtilSet() throws Exception { Set things = (Set) this.beanFactory.getBean("set.of.things"); - assertNotNull(things); - assertEquals(2, things.size()); + assertThat(things).isNotNull(); + assertThat(things.size()).isEqualTo(2); } @Test // SPR-2728 public void testCustomElementNestedWithinUtilMap() throws Exception { Map things = (Map) this.beanFactory.getBean("map.of.things"); - assertNotNull(things); - assertEquals(2, things.size()); + assertThat(things).isNotNull(); + assertThat(things.size()).isEqualTo(2); } private void assertTestBean(ITestBean bean) { - assertEquals("Invalid name", "Rob Harrop", bean.getName()); - assertEquals("Invalid age", 23, bean.getAge()); + assertThat(bean.getName()).as("Invalid name").isEqualTo("Rob Harrop"); + assertThat(bean.getAge()).as("Invalid age").isEqualTo(23); } private Resource getResource() { diff --git a/spring-context/src/test/java/org/springframework/cache/AbstractCacheTests.java b/spring-context/src/test/java/org/springframework/cache/AbstractCacheTests.java index a73a13e26bf..2a15955a7cf 100644 --- a/spring-context/src/test/java/org/springframework/cache/AbstractCacheTests.java +++ b/spring-context/src/test/java/org/springframework/cache/AbstractCacheTests.java @@ -25,10 +25,6 @@ import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; /** * @author Stephane Nicoll @@ -44,12 +40,12 @@ public abstract class AbstractCacheTests { @Test public void testCacheName() throws Exception { - assertEquals(CACHE_NAME, getCache().getName()); + assertThat(getCache().getName()).isEqualTo(CACHE_NAME); } @Test public void testNativeCache() throws Exception { - assertSame(getNativeCache(), getCache().getNativeCache()); + assertThat(getCache().getNativeCache()).isSameAs(getNativeCache()); } @Test @@ -59,21 +55,21 @@ public abstract class AbstractCacheTests { String key = createRandomKey(); Object value = "george"; - assertNull(cache.get(key)); - assertNull(cache.get(key, String.class)); - assertNull(cache.get(key, Object.class)); + assertThat((Object) cache.get(key)).isNull(); + assertThat(cache.get(key, String.class)).isNull(); + assertThat(cache.get(key, Object.class)).isNull(); cache.put(key, value); - assertEquals(value, cache.get(key).get()); - assertEquals(value, cache.get(key, String.class)); - assertEquals(value, cache.get(key, Object.class)); - assertEquals(value, cache.get(key, (Class) null)); + assertThat(cache.get(key).get()).isEqualTo(value); + assertThat(cache.get(key, String.class)).isEqualTo(value); + assertThat(cache.get(key, Object.class)).isEqualTo(value); + assertThat(cache.get(key, (Class) null)).isEqualTo(value); cache.put(key, null); - assertNotNull(cache.get(key)); - assertNull(cache.get(key).get()); - assertNull(cache.get(key, String.class)); - assertNull(cache.get(key, Object.class)); + assertThat(cache.get(key)).isNotNull(); + assertThat(cache.get(key).get()).isNull(); + assertThat(cache.get(key, String.class)).isNull(); + assertThat(cache.get(key, Object.class)).isNull(); } @Test @@ -83,11 +79,12 @@ public abstract class AbstractCacheTests { String key = createRandomKey(); Object value = "initialValue"; - assertNull(cache.get(key)); - assertNull(cache.putIfAbsent(key, value)); - assertEquals(value, cache.get(key).get()); - assertEquals("initialValue", cache.putIfAbsent(key, "anotherValue").get()); - assertEquals(value, cache.get(key).get()); // not changed + assertThat(cache.get(key)).isNull(); + assertThat(cache.putIfAbsent(key, value)).isNull(); + assertThat(cache.get(key).get()).isEqualTo(value); + assertThat(cache.putIfAbsent(key, "anotherValue").get()).isEqualTo("initialValue"); + // not changed + assertThat(cache.get(key).get()).isEqualTo(value); } @Test @@ -97,7 +94,7 @@ public abstract class AbstractCacheTests { String key = createRandomKey(); Object value = "george"; - assertNull(cache.get(key)); + assertThat((Object) cache.get(key)).isNull(); cache.put(key, value); } @@ -105,13 +102,13 @@ public abstract class AbstractCacheTests { public void testCacheClear() throws Exception { T cache = getCache(); - assertNull(cache.get("enescu")); + assertThat((Object) cache.get("enescu")).isNull(); cache.put("enescu", "george"); - assertNull(cache.get("vlaicu")); + assertThat((Object) cache.get("vlaicu")).isNull(); cache.put("vlaicu", "aurel"); cache.clear(); - assertNull(cache.get("vlaicu")); - assertNull(cache.get("enescu")); + assertThat((Object) cache.get("vlaicu")).isNull(); + assertThat((Object) cache.get("enescu")).isNull(); } @Test @@ -129,10 +126,10 @@ public abstract class AbstractCacheTests { String key = createRandomKey(); - assertNull(cache.get(key)); + assertThat((Object) cache.get(key)).isNull(); Object value = cache.get(key, () -> returnValue); - assertEquals(returnValue, value); - assertEquals(value, cache.get(key).get()); + assertThat(value).isEqualTo(returnValue); + assertThat(cache.get(key).get()).isEqualTo(value); } @Test @@ -154,7 +151,7 @@ public abstract class AbstractCacheTests { Object value = cache.get(key, () -> { throw new IllegalStateException("Should not have been invoked"); }); - assertEquals(initialValue, value); + assertThat(value).isEqualTo(initialValue); } @Test @@ -162,7 +159,7 @@ public abstract class AbstractCacheTests { T cache = getCache(); String key = createRandomKey(); - assertNull(cache.get(key)); + assertThat((Object) cache.get(key)).isNull(); try { cache.get(key, () -> { @@ -170,8 +167,8 @@ public abstract class AbstractCacheTests { }); } catch (Cache.ValueRetrievalException ex) { - assertNotNull(ex.getCause()); - assertEquals(UnsupportedOperationException.class, ex.getCause().getClass()); + assertThat(ex.getCause()).isNotNull(); + assertThat(ex.getCause().getClass()).isEqualTo(UnsupportedOperationException.class); } } @@ -205,7 +202,7 @@ public abstract class AbstractCacheTests { } latch.await(); - assertEquals(10, results.size()); + assertThat(results.size()).isEqualTo(10); results.forEach(r -> assertThat(r).isEqualTo(1)); // Only one method got invoked } diff --git a/spring-context/src/test/java/org/springframework/cache/CacheReproTests.java b/spring-context/src/test/java/org/springframework/cache/CacheReproTests.java index 60c5e13c95f..648c453357e 100644 --- a/spring-context/src/test/java/org/springframework/cache/CacheReproTests.java +++ b/spring-context/src/test/java/org/springframework/cache/CacheReproTests.java @@ -41,11 +41,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.lang.Nullable; import org.springframework.tests.sample.beans.TestBean; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -74,7 +71,7 @@ public class CacheReproTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Spr11249Config.class); Spr11249Service bean = context.getBean(Spr11249Service.class); Object result = bean.doSomething("op", 2, 3); - assertSame(result, bean.doSomething("op", 2, 3)); + assertThat(bean.doSomething("op", 2, 3)).isSameAs(result); context.close(); } @@ -89,7 +86,7 @@ public class CacheReproTests { verify(cache, times(1)).get(key); // first call: cache miss Object cachedResult = bean.getSimple("1"); - assertSame(result, cachedResult); + assertThat(cachedResult).isSameAs(result); verify(cache, times(2)).get(key); // second call: cache hit context.close(); @@ -106,7 +103,7 @@ public class CacheReproTests { verify(cache, times(0)).get(key); // no cache hit at all, caching disabled Object cachedResult = bean.getNeverCache("1"); - assertNotSame(result, cachedResult); + assertThat(cachedResult).isNotSameAs(result); verify(cache, times(0)).get(key); // caching disabled context.close(); @@ -118,9 +115,9 @@ public class CacheReproTests { MyCacheResolver cacheResolver = context.getBean(MyCacheResolver.class); Spr13081Service bean = context.getBean(Spr13081Service.class); - assertNull(cacheResolver.getCache("foo").get("foo")); + assertThat(cacheResolver.getCache("foo").get("foo")).isNull(); Object result = bean.getSimple("foo"); // cache name = id - assertEquals(result, cacheResolver.getCache("foo").get("foo").get()); + assertThat(cacheResolver.getCache("foo").get("foo").get()).isEqualTo(result); } @Test @@ -141,13 +138,13 @@ public class CacheReproTests { TestBean tb = new TestBean("tb1"); bean.insertItem(tb); - assertSame(tb, bean.findById("tb1").get()); - assertSame(tb, cache.get("tb1").get()); + assertThat(bean.findById("tb1").get()).isSameAs(tb); + assertThat(cache.get("tb1").get()).isSameAs(tb); cache.clear(); TestBean tb2 = bean.findById("tb1").get(); - assertNotSame(tb, tb2); - assertSame(tb2, cache.get("tb1").get()); + assertThat(tb2).isNotSameAs(tb); + assertThat(cache.get("tb1").get()).isSameAs(tb2); } @Test @@ -158,13 +155,13 @@ public class CacheReproTests { TestBean tb = new TestBean("tb1"); bean.insertItem(tb); - assertSame(tb, bean.findById("tb1").get()); - assertSame(tb, cache.get("tb1").get()); + assertThat(bean.findById("tb1").get()).isSameAs(tb); + assertThat(cache.get("tb1").get()).isSameAs(tb); cache.clear(); TestBean tb2 = bean.findById("tb1").get(); - assertNotSame(tb, tb2); - assertSame(tb2, cache.get("tb1").get()); + assertThat(tb2).isNotSameAs(tb); + assertThat(cache.get("tb1").get()).isSameAs(tb2); } @Test @@ -175,8 +172,8 @@ public class CacheReproTests { TestBean tb = new TestBean("tb1"); bean.insertItem(tb); - assertSame(tb, bean.findById("tb1").get()); - assertSame(tb, cache.get("tb1").get()); + assertThat(bean.findById("tb1").get()).isSameAs(tb); + assertThat(cache.get("tb1").get()).isSameAs(tb); } @Test @@ -187,8 +184,8 @@ public class CacheReproTests { TestBean tb = new TestBean("tb1"); bean.insertItem(tb); - assertSame(tb, bean.findById("tb1").get()); - assertSame(tb, cache.get("tb1").get()); + assertThat(bean.findById("tb1").get()).isSameAs(tb); + assertThat(cache.get("tb1").get()).isSameAs(tb); } diff --git a/spring-context/src/test/java/org/springframework/cache/CacheTestUtils.java b/spring-context/src/test/java/org/springframework/cache/CacheTestUtils.java index 8e9d12aa7e0..c69f2aa9514 100644 --- a/spring-context/src/test/java/org/springframework/cache/CacheTestUtils.java +++ b/spring-context/src/test/java/org/springframework/cache/CacheTestUtils.java @@ -22,9 +22,7 @@ import java.util.List; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.cache.support.SimpleCacheManager; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * General cache-related test utilities. @@ -54,7 +52,7 @@ public class CacheTestUtils { */ public static void assertCacheMiss(Object key, Cache... caches) { for (Cache cache : caches) { - assertNull("No entry in " + cache + " should have been found with key " + key, cache.get(key)); + assertThat(cache.get(key)).as("No entry in " + cache + " should have been found with key " + key).isNull(); } } @@ -64,8 +62,8 @@ public class CacheTestUtils { public static void assertCacheHit(Object key, Object value, Cache... caches) { for (Cache cache : caches) { Cache.ValueWrapper wrapper = cache.get(key); - assertNotNull("An entry in " + cache + " should have been found with key " + key, wrapper); - assertEquals("Wrong value in " + cache + " for entry with key " + key, value, wrapper.get()); + assertThat(wrapper).as("An entry in " + cache + " should have been found with key " + key).isNotNull(); + assertThat(wrapper.get()).as("Wrong value in " + cache + " for entry with key " + key).isEqualTo(value); } } diff --git a/spring-context/src/test/java/org/springframework/cache/NoOpCacheManagerTests.java b/spring-context/src/test/java/org/springframework/cache/NoOpCacheManagerTests.java index ffb7b182c88..6eab60c4132 100644 --- a/spring-context/src/test/java/org/springframework/cache/NoOpCacheManagerTests.java +++ b/spring-context/src/test/java/org/springframework/cache/NoOpCacheManagerTests.java @@ -22,12 +22,7 @@ import org.junit.Test; import org.springframework.cache.support.NoOpCacheManager; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link NoOpCacheManager}. @@ -42,28 +37,28 @@ public class NoOpCacheManagerTests { @Test public void testGetCache() throws Exception { Cache cache = this.manager.getCache("bucket"); - assertNotNull(cache); - assertSame(cache, this.manager.getCache("bucket")); + assertThat(cache).isNotNull(); + assertThat(this.manager.getCache("bucket")).isSameAs(cache); } @Test public void testNoOpCache() throws Exception { String name = createRandomKey(); Cache cache = this.manager.getCache(name); - assertEquals(name, cache.getName()); + assertThat(cache.getName()).isEqualTo(name); Object key = new Object(); cache.put(key, new Object()); - assertNull(cache.get(key)); - assertNull(cache.get(key, Object.class)); - assertSame(cache, cache.getNativeCache()); + assertThat(cache.get(key)).isNull(); + assertThat(cache.get(key, Object.class)).isNull(); + assertThat(cache.getNativeCache()).isSameAs(cache); } @Test public void testCacheName() throws Exception { String name = "bucket"; - assertFalse(this.manager.getCacheNames().contains(name)); + assertThat(this.manager.getCacheNames().contains(name)).isFalse(); this.manager.getCache(name); - assertTrue(this.manager.getCacheNames().contains(name)); + assertThat(this.manager.getCacheNames().contains(name)).isTrue(); } @Test @@ -72,7 +67,7 @@ public class NoOpCacheManagerTests { Cache cache = this.manager.getCache(name); Object returnValue = new Object(); Object value = cache.get(new Object(), () -> returnValue); - assertEquals(returnValue, value); + assertThat(value).isEqualTo(returnValue); } @Test @@ -85,8 +80,8 @@ public class NoOpCacheManagerTests { }); } catch (Cache.ValueRetrievalException ex) { - assertNotNull(ex.getCause()); - assertEquals(UnsupportedOperationException.class, ex.getCause().getClass()); + assertThat(ex.getCause()).isNotNull(); + assertThat(ex.getCause().getClass()).isEqualTo(UnsupportedOperationException.class); } } diff --git a/spring-context/src/test/java/org/springframework/cache/annotation/AnnotationCacheOperationSourceTests.java b/spring-context/src/test/java/org/springframework/cache/annotation/AnnotationCacheOperationSourceTests.java index 12cc12bace4..3bdd24a4159 100644 --- a/spring-context/src/test/java/org/springframework/cache/annotation/AnnotationCacheOperationSourceTests.java +++ b/spring-context/src/test/java/org/springframework/cache/annotation/AnnotationCacheOperationSourceTests.java @@ -35,10 +35,6 @@ import org.springframework.core.annotation.AliasFor; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Costin Leau @@ -53,23 +49,23 @@ public class AnnotationCacheOperationSourceTests { @Test public void singularAnnotation() { Collection ops = getOps(AnnotatedClass.class, "singular", 1); - assertTrue(ops.iterator().next() instanceof CacheableOperation); + assertThat(ops.iterator().next() instanceof CacheableOperation).isTrue(); } @Test public void multipleAnnotation() { Collection ops = getOps(AnnotatedClass.class, "multiple", 2); Iterator it = ops.iterator(); - assertTrue(it.next() instanceof CacheableOperation); - assertTrue(it.next() instanceof CacheEvictOperation); + assertThat(it.next() instanceof CacheableOperation).isTrue(); + assertThat(it.next() instanceof CacheEvictOperation).isTrue(); } @Test public void caching() { Collection ops = getOps(AnnotatedClass.class, "caching", 2); Iterator it = ops.iterator(); - assertTrue(it.next() instanceof CacheableOperation); - assertTrue(it.next() instanceof CacheEvictOperation); + assertThat(it.next() instanceof CacheableOperation).isTrue(); + assertThat(it.next() instanceof CacheEvictOperation).isTrue(); } @Test @@ -80,20 +76,20 @@ public class AnnotationCacheOperationSourceTests { @Test public void singularStereotype() { Collection ops = getOps(AnnotatedClass.class, "singleStereotype", 1); - assertTrue(ops.iterator().next() instanceof CacheEvictOperation); + assertThat(ops.iterator().next() instanceof CacheEvictOperation).isTrue(); } @Test public void multipleStereotypes() { Collection ops = getOps(AnnotatedClass.class, "multipleStereotype", 3); Iterator it = ops.iterator(); - assertTrue(it.next() instanceof CacheableOperation); + assertThat(it.next() instanceof CacheableOperation).isTrue(); CacheOperation next = it.next(); - assertTrue(next instanceof CacheEvictOperation); - assertTrue(next.getCacheNames().contains("foo")); + assertThat(next instanceof CacheEvictOperation).isTrue(); + assertThat(next.getCacheNames().contains("foo")).isTrue(); next = it.next(); - assertTrue(next instanceof CacheEvictOperation); - assertTrue(next.getCacheNames().contains("bar")); + assertThat(next instanceof CacheEvictOperation).isTrue(); + assertThat(next.getCacheNames().contains("bar")).isTrue(); } @Test @@ -142,14 +138,14 @@ public class AnnotationCacheOperationSourceTests { public void customKeyGenerator() { Collection ops = getOps(AnnotatedClass.class, "customKeyGenerator", 1); CacheOperation cacheOperation = ops.iterator().next(); - assertEquals("Custom key generator not set", "custom", cacheOperation.getKeyGenerator()); + assertThat(cacheOperation.getKeyGenerator()).as("Custom key generator not set").isEqualTo("custom"); } @Test public void customKeyGeneratorInherited() { Collection ops = getOps(AnnotatedClass.class, "customKeyGeneratorInherited", 1); CacheOperation cacheOperation = ops.iterator().next(); - assertEquals("Custom key generator not set", "custom", cacheOperation.getKeyGenerator()); + assertThat(cacheOperation.getKeyGenerator()).as("Custom key generator not set").isEqualTo("custom"); } @Test @@ -162,28 +158,28 @@ public class AnnotationCacheOperationSourceTests { public void customCacheManager() { Collection ops = getOps(AnnotatedClass.class, "customCacheManager", 1); CacheOperation cacheOperation = ops.iterator().next(); - assertEquals("Custom cache manager not set", "custom", cacheOperation.getCacheManager()); + assertThat(cacheOperation.getCacheManager()).as("Custom cache manager not set").isEqualTo("custom"); } @Test public void customCacheManagerInherited() { Collection ops = getOps(AnnotatedClass.class, "customCacheManagerInherited", 1); CacheOperation cacheOperation = ops.iterator().next(); - assertEquals("Custom cache manager not set", "custom", cacheOperation.getCacheManager()); + assertThat(cacheOperation.getCacheManager()).as("Custom cache manager not set").isEqualTo("custom"); } @Test public void customCacheResolver() { Collection ops = getOps(AnnotatedClass.class, "customCacheResolver", 1); CacheOperation cacheOperation = ops.iterator().next(); - assertEquals("Custom cache resolver not set", "custom", cacheOperation.getCacheResolver()); + assertThat(cacheOperation.getCacheResolver()).as("Custom cache resolver not set").isEqualTo("custom"); } @Test public void customCacheResolverInherited() { Collection ops = getOps(AnnotatedClass.class, "customCacheResolverInherited", 1); CacheOperation cacheOperation = ops.iterator().next(); - assertEquals("Custom cache resolver not set", "custom", cacheOperation.getCacheResolver()); + assertThat(cacheOperation.getCacheResolver()).as("Custom cache resolver not set").isEqualTo("custom"); } @Test @@ -225,8 +221,8 @@ public class AnnotationCacheOperationSourceTests { // Valid as a CacheResolver might return the cache names to use with other info Collection ops = getOps(AnnotatedClass.class, "noCacheNameSpecified"); CacheOperation cacheOperation = ops.iterator().next(); - assertNotNull("cache names set must not be null", cacheOperation.getCacheNames()); - assertEquals("no cache names specified", 0, cacheOperation.getCacheNames().size()); + assertThat(cacheOperation.getCacheNames()).as("cache names set must not be null").isNotNull(); + assertThat(cacheOperation.getCacheNames().size()).as("no cache names specified").isEqualTo(0); } @Test @@ -253,9 +249,9 @@ public class AnnotationCacheOperationSourceTests { @Test public void cacheAnnotationOverride() { Collection ops = getOps(InterfaceCacheConfig.class, "interfaceCacheableOverride"); - assertSame(1, ops.size()); + assertThat(ops.size()).isSameAs(1); CacheOperation cacheOperation = ops.iterator().next(); - assertTrue(cacheOperation instanceof CacheableOperation); + assertThat(cacheOperation instanceof CacheableOperation).isTrue(); } @Test @@ -282,7 +278,7 @@ public class AnnotationCacheOperationSourceTests { private Collection getOps(Class target, String name, int expectedNumberOfOperations) { Collection result = getOps(target, name); - assertEquals("Wrong number of operation(s) for '" + name + "'", expectedNumberOfOperations, result.size()); + assertThat(result.size()).as("Wrong number of operation(s) for '" + name + "'").isEqualTo(expectedNumberOfOperations); return result; } @@ -299,13 +295,11 @@ public class AnnotationCacheOperationSourceTests { private void assertSharedConfig(CacheOperation actual, String keyGenerator, String cacheManager, String cacheResolver, String... cacheNames) { - assertEquals("Wrong key manager", keyGenerator, actual.getKeyGenerator()); - assertEquals("Wrong cache manager", cacheManager, actual.getCacheManager()); - assertEquals("Wrong cache resolver", cacheResolver, actual.getCacheResolver()); - assertEquals("Wrong number of cache names", cacheNames.length, actual.getCacheNames().size()); - Arrays.stream(cacheNames).forEach(cacheName -> - assertTrue("Cache '" + cacheName + "' not found in " + actual.getCacheNames(), - actual.getCacheNames().contains(cacheName))); + assertThat(actual.getKeyGenerator()).as("Wrong key manager").isEqualTo(keyGenerator); + assertThat(actual.getCacheManager()).as("Wrong cache manager").isEqualTo(cacheManager); + assertThat(actual.getCacheResolver()).as("Wrong cache resolver").isEqualTo(cacheResolver); + assertThat(actual.getCacheNames().size()).as("Wrong number of cache names").isEqualTo(cacheNames.length); + Arrays.stream(cacheNames).forEach(cacheName -> assertThat(actual.getCacheNames().contains(cacheName)).as("Cache '" + cacheName + "' not found in " + actual.getCacheNames()).isTrue()); } diff --git a/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentMapCacheManagerTests.java b/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentMapCacheManagerTests.java index dedfe8ecca8..4b0b620b916 100644 --- a/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentMapCacheManagerTests.java +++ b/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentMapCacheManagerTests.java @@ -21,11 +21,7 @@ import org.junit.Test; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; -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; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -37,102 +33,111 @@ public class ConcurrentMapCacheManagerTests { public void testDynamicMode() { CacheManager cm = new ConcurrentMapCacheManager(); Cache cache1 = cm.getCache("c1"); - assertTrue(cache1 instanceof ConcurrentMapCache); + boolean condition2 = cache1 instanceof ConcurrentMapCache; + assertThat(condition2).isTrue(); Cache cache1again = cm.getCache("c1"); - assertSame(cache1again, cache1); + assertThat(cache1).isSameAs(cache1again); Cache cache2 = cm.getCache("c2"); - assertTrue(cache2 instanceof ConcurrentMapCache); + boolean condition1 = cache2 instanceof ConcurrentMapCache; + assertThat(condition1).isTrue(); Cache cache2again = cm.getCache("c2"); - assertSame(cache2again, cache2); + assertThat(cache2).isSameAs(cache2again); Cache cache3 = cm.getCache("c3"); - assertTrue(cache3 instanceof ConcurrentMapCache); + boolean condition = cache3 instanceof ConcurrentMapCache; + assertThat(condition).isTrue(); Cache cache3again = cm.getCache("c3"); - assertSame(cache3again, cache3); + assertThat(cache3).isSameAs(cache3again); cache1.put("key1", "value1"); - assertEquals("value1", cache1.get("key1").get()); + assertThat(cache1.get("key1").get()).isEqualTo("value1"); cache1.put("key2", 2); - assertEquals(2, cache1.get("key2").get()); + assertThat(cache1.get("key2").get()).isEqualTo(2); cache1.put("key3", null); - assertNull(cache1.get("key3").get()); + assertThat(cache1.get("key3").get()).isNull(); cache1.put("key3", null); - assertNull(cache1.get("key3").get()); + assertThat(cache1.get("key3").get()).isNull(); cache1.evict("key3"); - assertNull(cache1.get("key3")); + assertThat(cache1.get("key3")).isNull(); - assertEquals("value1", cache1.putIfAbsent("key1", "value1x").get()); - assertEquals("value1", cache1.get("key1").get()); - assertEquals(2, cache1.putIfAbsent("key2", 2.1).get()); - assertNull(cache1.putIfAbsent("key3", null)); - assertNull(cache1.get("key3").get()); - assertNull(cache1.putIfAbsent("key3", null).get()); - assertNull(cache1.get("key3").get()); + assertThat(cache1.putIfAbsent("key1", "value1x").get()).isEqualTo("value1"); + assertThat(cache1.get("key1").get()).isEqualTo("value1"); + assertThat(cache1.putIfAbsent("key2", 2.1).get()).isEqualTo(2); + assertThat(cache1.putIfAbsent("key3", null)).isNull(); + assertThat(cache1.get("key3").get()).isNull(); + assertThat(cache1.putIfAbsent("key3", null).get()).isNull(); + assertThat(cache1.get("key3").get()).isNull(); cache1.evict("key3"); - assertNull(cache1.get("key3")); + assertThat(cache1.get("key3")).isNull(); } @Test public void testStaticMode() { ConcurrentMapCacheManager cm = new ConcurrentMapCacheManager("c1", "c2"); Cache cache1 = cm.getCache("c1"); - assertTrue(cache1 instanceof ConcurrentMapCache); + boolean condition3 = cache1 instanceof ConcurrentMapCache; + assertThat(condition3).isTrue(); Cache cache1again = cm.getCache("c1"); - assertSame(cache1again, cache1); + assertThat(cache1).isSameAs(cache1again); Cache cache2 = cm.getCache("c2"); - assertTrue(cache2 instanceof ConcurrentMapCache); + boolean condition2 = cache2 instanceof ConcurrentMapCache; + assertThat(condition2).isTrue(); Cache cache2again = cm.getCache("c2"); - assertSame(cache2again, cache2); + assertThat(cache2).isSameAs(cache2again); Cache cache3 = cm.getCache("c3"); - assertNull(cache3); + assertThat(cache3).isNull(); cache1.put("key1", "value1"); - assertEquals("value1", cache1.get("key1").get()); + assertThat(cache1.get("key1").get()).isEqualTo("value1"); cache1.put("key2", 2); - assertEquals(2, cache1.get("key2").get()); + assertThat(cache1.get("key2").get()).isEqualTo(2); cache1.put("key3", null); - assertNull(cache1.get("key3").get()); + assertThat(cache1.get("key3").get()).isNull(); cache1.evict("key3"); - assertNull(cache1.get("key3")); + assertThat(cache1.get("key3")).isNull(); cm.setAllowNullValues(false); Cache cache1x = cm.getCache("c1"); - assertTrue(cache1x instanceof ConcurrentMapCache); - assertTrue(cache1x != cache1); + boolean condition1 = cache1x instanceof ConcurrentMapCache; + assertThat(condition1).isTrue(); + assertThat(cache1x != cache1).isTrue(); Cache cache2x = cm.getCache("c2"); - assertTrue(cache2x instanceof ConcurrentMapCache); - assertTrue(cache2x != cache2); + boolean condition = cache2x instanceof ConcurrentMapCache; + assertThat(condition).isTrue(); + assertThat(cache2x != cache2).isTrue(); Cache cache3x = cm.getCache("c3"); - assertNull(cache3x); + assertThat(cache3x).isNull(); cache1x.put("key1", "value1"); - assertEquals("value1", cache1x.get("key1").get()); + assertThat(cache1x.get("key1").get()).isEqualTo("value1"); cache1x.put("key2", 2); - assertEquals(2, cache1x.get("key2").get()); + assertThat(cache1x.get("key2").get()).isEqualTo(2); cm.setAllowNullValues(true); Cache cache1y = cm.getCache("c1"); cache1y.put("key3", null); - assertNull(cache1y.get("key3").get()); + assertThat(cache1y.get("key3").get()).isNull(); cache1y.evict("key3"); - assertNull(cache1y.get("key3")); + assertThat(cache1y.get("key3")).isNull(); } @Test public void testChangeStoreByValue() { ConcurrentMapCacheManager cm = new ConcurrentMapCacheManager("c1", "c2"); - assertFalse(cm.isStoreByValue()); + assertThat(cm.isStoreByValue()).isFalse(); Cache cache1 = cm.getCache("c1"); - assertTrue(cache1 instanceof ConcurrentMapCache); - assertFalse(((ConcurrentMapCache)cache1).isStoreByValue()); + boolean condition1 = cache1 instanceof ConcurrentMapCache; + assertThat(condition1).isTrue(); + assertThat(((ConcurrentMapCache)cache1).isStoreByValue()).isFalse(); cache1.put("key", "value"); cm.setStoreByValue(true); - assertTrue(cm.isStoreByValue()); + assertThat(cm.isStoreByValue()).isTrue(); Cache cache1x = cm.getCache("c1"); - assertTrue(cache1x instanceof ConcurrentMapCache); - assertTrue(cache1x != cache1); - assertNull(cache1x.get("key")); + boolean condition = cache1x instanceof ConcurrentMapCache; + assertThat(condition).isTrue(); + assertThat(cache1x != cache1).isTrue(); + assertThat(cache1x.get("key")).isNull(); } } diff --git a/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentMapCacheTests.java b/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentMapCacheTests.java index 485b3eb4598..6030372d601 100644 --- a/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentMapCacheTests.java +++ b/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentMapCacheTests.java @@ -28,10 +28,8 @@ import org.junit.Test; import org.springframework.cache.AbstractValueAdaptingCacheTests; import org.springframework.core.serializer.support.SerializationDelegate; +import static org.assertj.core.api.Assertions.assertThat; 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 Costin Leau @@ -77,14 +75,14 @@ public class ConcurrentMapCacheTests @Test public void testIsStoreByReferenceByDefault() { - assertFalse(this.cache.isStoreByValue()); + assertThat(this.cache.isStoreByValue()).isFalse(); } @SuppressWarnings("unchecked") @Test public void testSerializer() { ConcurrentMapCache serializeCache = createCacheWithStoreByValue(); - assertTrue(serializeCache.isStoreByValue()); + assertThat(serializeCache.isStoreByValue()).isTrue(); Object key = createRandomKey(); List content = new ArrayList<>(); @@ -92,8 +90,8 @@ public class ConcurrentMapCacheTests serializeCache.put(key, content); content.remove(0); List entry = (List) serializeCache.get(key).get(); - assertEquals(3, entry.size()); - assertEquals("one", entry.get(0)); + assertThat(entry.size()).isEqualTo(3); + assertThat(entry.get(0)).isEqualTo("one"); } @Test diff --git a/spring-context/src/test/java/org/springframework/cache/config/AbstractCacheAnnotationTests.java b/spring-context/src/test/java/org/springframework/cache/config/AbstractCacheAnnotationTests.java index 7b6fb1723d7..f532b992449 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/AbstractCacheAnnotationTests.java +++ b/spring-context/src/test/java/org/springframework/cache/config/AbstractCacheAnnotationTests.java @@ -32,12 +32,6 @@ import org.springframework.context.ConfigurableApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIOException; -import static org.junit.Assert.assertEquals; -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; /** * Abstract cache annotation tests (containing several reusable methods). @@ -72,9 +66,9 @@ public abstract class AbstractCacheAnnotationTests { this.cm = ctx.getBean("cacheManager", CacheManager.class); Collection cn = this.cm.getCacheNames(); - assertTrue(cn.contains("testCache")); - assertTrue(cn.contains("secondary")); - assertTrue(cn.contains("primary")); + assertThat(cn.contains("testCache")).isTrue(); + assertThat(cn.contains("secondary")).isTrue(); + assertThat(cn.contains("primary")).isTrue(); } @After @@ -92,23 +86,23 @@ public abstract class AbstractCacheAnnotationTests { Object r2 = service.cache(o1); Object r3 = service.cache(o1); - assertSame(r1, r2); - assertSame(r1, r3); + assertThat(r2).isSameAs(r1); + assertThat(r3).isSameAs(r1); } public void testCacheableNull(CacheableService service) throws Exception { Object o1 = new Object(); - assertNull(this.cm.getCache("testCache").get(o1)); + assertThat((Object) this.cm.getCache("testCache").get(o1)).isNull(); Object r1 = service.cacheNull(o1); Object r2 = service.cacheNull(o1); Object r3 = service.cacheNull(o1); - assertSame(r1, r2); - assertSame(r1, r3); + assertThat(r2).isSameAs(r1); + assertThat(r3).isSameAs(r1); - assertEquals(r3, this.cm.getCache("testCache").get(o1).get()); - assertNull("Cached value should be null", r3); + assertThat(this.cm.getCache("testCache").get(o1).get()).isEqualTo(r3); + assertThat(r3).as("Cached value should be null").isNull(); } public void testCacheableSync(CacheableService service) throws Exception { @@ -118,23 +112,23 @@ public abstract class AbstractCacheAnnotationTests { Object r2 = service.cacheSync(o1); Object r3 = service.cacheSync(o1); - assertSame(r1, r2); - assertSame(r1, r3); + assertThat(r2).isSameAs(r1); + assertThat(r3).isSameAs(r1); } public void testCacheableSyncNull(CacheableService service) throws Exception { Object o1 = new Object(); - assertNull(this.cm.getCache("testCache").get(o1)); + assertThat((Object) this.cm.getCache("testCache").get(o1)).isNull(); Object r1 = service.cacheSyncNull(o1); Object r2 = service.cacheSyncNull(o1); Object r3 = service.cacheSyncNull(o1); - assertSame(r1, r2); - assertSame(r1, r3); + assertThat(r2).isSameAs(r1); + assertThat(r3).isSameAs(r1); - assertEquals(r3, this.cm.getCache("testCache").get(o1).get()); - assertNull("Cached value should be null", r3); + assertThat(this.cm.getCache("testCache").get(o1).get()).isEqualTo(r3); + assertThat(r3).as("Cached value should be null").isNull(); } public void testEvict(CacheableService service) throws Exception { @@ -143,12 +137,12 @@ public abstract class AbstractCacheAnnotationTests { Object r1 = service.cache(o1); Object r2 = service.cache(o1); - assertSame(r1, r2); + assertThat(r2).isSameAs(r1); service.invalidate(o1); Object r3 = service.cache(o1); Object r4 = service.cache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); + assertThat(r3).isNotSameAs(r1); + assertThat(r4).isSameAs(r3); } public void testEvictEarly(CacheableService service) throws Exception { @@ -157,7 +151,7 @@ public abstract class AbstractCacheAnnotationTests { Object r1 = service.cache(o1); Object r2 = service.cache(o1); - assertSame(r1, r2); + assertThat(r2).isSameAs(r1); try { service.evictEarly(o1); } @@ -167,8 +161,8 @@ public abstract class AbstractCacheAnnotationTests { Object r3 = service.cache(o1); Object r4 = service.cache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); + assertThat(r3).isNotSameAs(r1); + assertThat(r4).isSameAs(r3); } public void testEvictException(CacheableService service) throws Exception { @@ -177,7 +171,7 @@ public abstract class AbstractCacheAnnotationTests { Object r1 = service.cache(o1); Object r2 = service.cache(o1); - assertSame(r1, r2); + assertThat(r2).isSameAs(r1); try { service.evictWithException(o1); } @@ -186,7 +180,7 @@ public abstract class AbstractCacheAnnotationTests { } // exception occurred, eviction skipped, data should still be in the cache Object r3 = service.cache(o1); - assertSame(r1, r3); + assertThat(r3).isSameAs(r1); } public void testEvictWKey(CacheableService service) throws Exception { @@ -195,12 +189,12 @@ public abstract class AbstractCacheAnnotationTests { Object r1 = service.cache(o1); Object r2 = service.cache(o1); - assertSame(r1, r2); + assertThat(r2).isSameAs(r1); service.evict(o1, null); Object r3 = service.cache(o1); Object r4 = service.cache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); + assertThat(r3).isNotSameAs(r1); + assertThat(r4).isSameAs(r3); } public void testEvictWKeyEarly(CacheableService service) throws Exception { @@ -209,7 +203,7 @@ public abstract class AbstractCacheAnnotationTests { Object r1 = service.cache(o1); Object r2 = service.cache(o1); - assertSame(r1, r2); + assertThat(r2).isSameAs(r1); try { service.invalidateEarly(o1, null); @@ -219,8 +213,8 @@ public abstract class AbstractCacheAnnotationTests { } Object r3 = service.cache(o1); Object r4 = service.cache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); + assertThat(r3).isNotSameAs(r1); + assertThat(r4).isSameAs(r3); } public void testEvictAll(CacheableService service) throws Exception { @@ -232,41 +226,41 @@ public abstract class AbstractCacheAnnotationTests { Object o2 = new Object(); Object r10 = service.cache(o2); - assertSame(r1, r2); - assertNotSame(r1, r10); + assertThat(r2).isSameAs(r1); + assertThat(r10).isNotSameAs(r1); service.evictAll(new Object()); Cache cache = this.cm.getCache("testCache"); - assertNull(cache.get(o1)); - assertNull(cache.get(o2)); + assertThat((Object) cache.get(o1)).isNull(); + assertThat((Object) cache.get(o2)).isNull(); Object r3 = service.cache(o1); Object r4 = service.cache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); + assertThat(r3).isNotSameAs(r1); + assertThat(r4).isSameAs(r3); } public void testConditionalExpression(CacheableService service) throws Exception { Object r1 = service.conditional(4); Object r2 = service.conditional(4); - assertNotSame(r1, r2); + assertThat(r2).isNotSameAs(r1); Object r3 = service.conditional(3); Object r4 = service.conditional(3); - assertSame(r3, r4); + assertThat(r4).isSameAs(r3); } public void testConditionalExpressionSync(CacheableService service) throws Exception { Object r1 = service.conditionalSync(4); Object r2 = service.conditionalSync(4); - assertNotSame(r1, r2); + assertThat(r2).isNotSameAs(r1); Object r3 = service.conditionalSync(3); Object r4 = service.conditionalSync(3); - assertSame(r3, r4); + assertThat(r4).isSameAs(r3); } public void testUnlessExpression(CacheableService service) throws Exception { @@ -282,54 +276,54 @@ public abstract class AbstractCacheAnnotationTests { Object r1 = service.key(5, 1); Object r2 = service.key(5, 2); - assertSame(r1, r2); + assertThat(r2).isSameAs(r1); Object r3 = service.key(1, 5); Object r4 = service.key(2, 5); - assertNotSame(r3, r4); + assertThat(r4).isNotSameAs(r3); } public void testVarArgsKey(CacheableService service) throws Exception { Object r1 = service.varArgsKey(1, 2, 3); Object r2 = service.varArgsKey(1, 2, 3); - assertSame(r1, r2); + assertThat(r2).isSameAs(r1); Object r3 = service.varArgsKey(1, 2, 3); Object r4 = service.varArgsKey(1, 2); - assertNotSame(r3, r4); + assertThat(r4).isNotSameAs(r3); } public void testNullValue(CacheableService service) throws Exception { Object key = new Object(); - assertNull(service.nullValue(key)); + assertThat(service.nullValue(key)).isNull(); int nr = service.nullInvocations().intValue(); - assertNull(service.nullValue(key)); - assertEquals(nr, service.nullInvocations().intValue()); - assertNull(service.nullValue(new Object())); - assertEquals(nr + 1, service.nullInvocations().intValue()); + assertThat(service.nullValue(key)).isNull(); + assertThat(service.nullInvocations().intValue()).isEqualTo(nr); + assertThat(service.nullValue(new Object())).isNull(); + assertThat(service.nullInvocations().intValue()).isEqualTo(nr + 1); } public void testMethodName(CacheableService service, String keyName) throws Exception { Object key = new Object(); Object r1 = service.name(key); - assertSame(r1, service.name(key)); + assertThat(service.name(key)).isSameAs(r1); Cache cache = this.cm.getCache("testCache"); // assert the method name is used - assertNotNull(cache.get(keyName)); + assertThat(cache.get(keyName)).isNotNull(); } public void testRootVars(CacheableService service) { Object key = new Object(); Object r1 = service.rootVars(key); - assertSame(r1, service.rootVars(key)); + assertThat(service.rootVars(key)).isSameAs(r1); Cache cache = this.cm.getCache("testCache"); // assert the method name is used String expectedKey = "rootVarsrootVars" + AopProxyUtils.ultimateTargetClass(service) + service; - assertNotNull(cache.get(expectedKey)); + assertThat(cache.get(expectedKey)).isNotNull(); } public void testCheckedThrowable(CacheableService service) throws Exception { @@ -360,20 +354,20 @@ public abstract class AbstractCacheAnnotationTests { public void testNullArg(CacheableService service) { Object r1 = service.cache(null); - assertSame(r1, service.cache(null)); + assertThat(service.cache(null)).isSameAs(r1); } public void testCacheUpdate(CacheableService service) { Object o = new Object(); Cache cache = this.cm.getCache("testCache"); - assertNull(cache.get(o)); + assertThat((Object) cache.get(o)).isNull(); Object r1 = service.update(o); - assertSame(r1, cache.get(o).get()); + assertThat(cache.get(o).get()).isSameAs(r1); o = new Object(); - assertNull(cache.get(o)); + assertThat((Object) cache.get(o)).isNull(); Object r2 = service.update(o); - assertSame(r2, cache.get(o).get()); + assertThat(cache.get(o).get()).isSameAs(r2); } public void testConditionalCacheUpdate(CacheableService service) { @@ -381,11 +375,11 @@ public abstract class AbstractCacheAnnotationTests { Integer three = 3; Cache cache = this.cm.getCache("testCache"); - assertEquals(one, Integer.valueOf(service.conditionalUpdate(one).toString())); - assertNull(cache.get(one)); + assertThat((int) Integer.valueOf(service.conditionalUpdate(one).toString())).isEqualTo((int) one); + assertThat(cache.get(one)).isNull(); - assertEquals(three, Integer.valueOf(service.conditionalUpdate(three).toString())); - assertEquals(three, Integer.valueOf(cache.get(three).get().toString())); + assertThat((int) Integer.valueOf(service.conditionalUpdate(three).toString())).isEqualTo((int) three); + assertThat((int) Integer.valueOf(cache.get(three).get().toString())).isEqualTo((int) three); } public void testMultiCache(CacheableService service) { @@ -395,23 +389,23 @@ public abstract class AbstractCacheAnnotationTests { Cache primary = this.cm.getCache("primary"); Cache secondary = this.cm.getCache("secondary"); - assertNull(primary.get(o1)); - assertNull(secondary.get(o1)); + assertThat((Object) primary.get(o1)).isNull(); + assertThat((Object) secondary.get(o1)).isNull(); Object r1 = service.multiCache(o1); - assertSame(r1, primary.get(o1).get()); - assertSame(r1, secondary.get(o1).get()); + assertThat(primary.get(o1).get()).isSameAs(r1); + assertThat(secondary.get(o1).get()).isSameAs(r1); Object r2 = service.multiCache(o1); Object r3 = service.multiCache(o1); - assertSame(r1, r2); - assertSame(r1, r3); + assertThat(r2).isSameAs(r1); + assertThat(r3).isSameAs(r1); - assertNull(primary.get(o2)); - assertNull(secondary.get(o2)); + assertThat((Object) primary.get(o2)).isNull(); + assertThat((Object) secondary.get(o2)).isNull(); Object r4 = service.multiCache(o2); - assertSame(r4, primary.get(o2).get()); - assertSame(r4, secondary.get(o2).get()); + assertThat(primary.get(o2).get()).isSameAs(r4); + assertThat(secondary.get(o2).get()).isSameAs(r4); } public void testMultiEvict(CacheableService service) { @@ -426,22 +420,22 @@ public abstract class AbstractCacheAnnotationTests { Cache secondary = this.cm.getCache("secondary"); primary.put(o2, o2); - assertSame(r1, r2); - assertSame(r1, primary.get(o1).get()); - assertSame(r1, secondary.get(o1).get()); + assertThat(r2).isSameAs(r1); + assertThat(primary.get(o1).get()).isSameAs(r1); + assertThat(secondary.get(o1).get()).isSameAs(r1); service.multiEvict(o1); - assertNull(primary.get(o1)); - assertNull(secondary.get(o1)); - assertNull(primary.get(o2)); + assertThat((Object) primary.get(o1)).isNull(); + assertThat((Object) secondary.get(o1)).isNull(); + assertThat((Object) primary.get(o2)).isNull(); Object r3 = service.multiCache(o1); Object r4 = service.multiCache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); + assertThat(r3).isNotSameAs(r1); + assertThat(r4).isSameAs(r3); - assertSame(r3, primary.get(o1).get()); - assertSame(r4, secondary.get(o1).get()); + assertThat(primary.get(o1).get()).isSameAs(r3); + assertThat(secondary.get(o1).get()).isSameAs(r4); } public void testMultiPut(CacheableService service) { @@ -450,28 +444,28 @@ public abstract class AbstractCacheAnnotationTests { Cache primary = this.cm.getCache("primary"); Cache secondary = this.cm.getCache("secondary"); - assertNull(primary.get(o)); - assertNull(secondary.get(o)); + assertThat((Object) primary.get(o)).isNull(); + assertThat((Object) secondary.get(o)).isNull(); Object r1 = service.multiUpdate(o); - assertSame(r1, primary.get(o).get()); - assertSame(r1, secondary.get(o).get()); + assertThat(primary.get(o).get()).isSameAs(r1); + assertThat(secondary.get(o).get()).isSameAs(r1); o = 2; - assertNull(primary.get(o)); - assertNull(secondary.get(o)); + assertThat((Object) primary.get(o)).isNull(); + assertThat((Object) secondary.get(o)).isNull(); Object r2 = service.multiUpdate(o); - assertSame(r2, primary.get(o).get()); - assertSame(r2, secondary.get(o).get()); + assertThat(primary.get(o).get()).isSameAs(r2); + assertThat(secondary.get(o).get()).isSameAs(r2); } public void testPutRefersToResult(CacheableService service) throws Exception { Long id = Long.MIN_VALUE; TestEntity entity = new TestEntity(); Cache primary = this.cm.getCache("primary"); - assertNull(primary.get(id)); - assertNull(entity.getId()); + assertThat((Object) primary.get(id)).isNull(); + assertThat((Object) entity.getId()).isNull(); service.putRefersToResult(entity); - assertSame(entity, primary.get(id).get()); + assertThat(primary.get(id).get()).isSameAs(entity); } public void testMultiCacheAndEvict(CacheableService service) { @@ -483,16 +477,16 @@ public abstract class AbstractCacheAnnotationTests { secondary.put(key, key); - assertNull(secondary.get(methodName)); - assertSame(key, secondary.get(key).get()); + assertThat(secondary.get(methodName)).isNull(); + assertThat(secondary.get(key).get()).isSameAs(key); Object r1 = service.multiCacheAndEvict(key); - assertSame(r1, service.multiCacheAndEvict(key)); + assertThat(service.multiCacheAndEvict(key)).isSameAs(r1); // assert the method name is used - assertSame(r1, primary.get(methodName).get()); - assertNull(secondary.get(methodName)); - assertNull(secondary.get(key)); + assertThat(primary.get(methodName).get()).isSameAs(r1); + assertThat(secondary.get(methodName)).isNull(); + assertThat(secondary.get(key)).isNull(); } public void testMultiConditionalCacheAndEvict(CacheableService service) { @@ -502,22 +496,22 @@ public abstract class AbstractCacheAnnotationTests { secondary.put(key, key); - assertNull(primary.get(key)); - assertSame(key, secondary.get(key).get()); + assertThat(primary.get(key)).isNull(); + assertThat(secondary.get(key).get()).isSameAs(key); Object r1 = service.multiConditionalCacheAndEvict(key); Object r3 = service.multiConditionalCacheAndEvict(key); - assertTrue(!r1.equals(r3)); - assertNull(primary.get(key)); + assertThat(!r1.equals(r3)).isTrue(); + assertThat((Object) primary.get(key)).isNull(); Object key2 = 3; Object r2 = service.multiConditionalCacheAndEvict(key2); - assertSame(r2, service.multiConditionalCacheAndEvict(key2)); + assertThat(service.multiConditionalCacheAndEvict(key2)).isSameAs(r2); // assert the method name is used - assertSame(r2, primary.get(key2).get()); - assertNull(secondary.get(key2)); + assertThat(primary.get(key2).get()).isSameAs(r2); + assertThat(secondary.get(key2)).isNull(); } @Test @@ -643,14 +637,14 @@ public abstract class AbstractCacheAnnotationTests { @Test public void testClassNullValue() throws Exception { Object key = new Object(); - assertNull(this.ccs.nullValue(key)); + assertThat(this.ccs.nullValue(key)).isNull(); int nr = this.ccs.nullInvocations().intValue(); - assertNull(this.ccs.nullValue(key)); - assertEquals(nr, this.ccs.nullInvocations().intValue()); - assertNull(this.ccs.nullValue(new Object())); + assertThat(this.ccs.nullValue(key)).isNull(); + assertThat(this.ccs.nullInvocations().intValue()).isEqualTo(nr); + assertThat(this.ccs.nullValue(new Object())).isNull(); // the check method is also cached - assertEquals(nr, this.ccs.nullInvocations().intValue()); - assertEquals(nr + 1, AnnotatedClassCacheableService.nullInvocations.intValue()); + assertThat(this.ccs.nullInvocations().intValue()).isEqualTo(nr); + assertThat(AnnotatedClassCacheableService.nullInvocations.intValue()).isEqualTo(nr + 1); } @Test @@ -677,11 +671,11 @@ public abstract class AbstractCacheAnnotationTests { public void testCustomKeyGenerator() { Object param = new Object(); Object r1 = this.cs.customKeyGenerator(param); - assertSame(r1, this.cs.customKeyGenerator(param)); + assertThat(this.cs.customKeyGenerator(param)).isSameAs(r1); Cache cache = this.cm.getCache("testCache"); // Checks that the custom keyGenerator was used Object expectedKey = SomeCustomKeyGenerator.generateKey("customKeyGenerator", param); - assertNotNull(cache.get(expectedKey)); + assertThat(cache.get(expectedKey)).isNotNull(); } @Test @@ -696,10 +690,10 @@ public abstract class AbstractCacheAnnotationTests { CacheManager customCm = this.ctx.getBean("customCacheManager", CacheManager.class); Object key = new Object(); Object r1 = this.cs.customCacheManager(key); - assertSame(r1, this.cs.customCacheManager(key)); + assertThat(this.cs.customCacheManager(key)).isSameAs(r1); Cache cache = customCm.getCache("testCache"); - assertNotNull(cache.get(key)); + assertThat(cache.get(key)).isNotNull(); } @Test diff --git a/spring-context/src/test/java/org/springframework/cache/config/AnnotationNamespaceDrivenTests.java b/spring-context/src/test/java/org/springframework/cache/config/AnnotationNamespaceDrivenTests.java index 450328e8ab1..70dfcc9fa82 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/AnnotationNamespaceDrivenTests.java +++ b/spring-context/src/test/java/org/springframework/cache/config/AnnotationNamespaceDrivenTests.java @@ -23,7 +23,7 @@ import org.springframework.cache.interceptor.CacheInterceptor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Costin Leau @@ -42,7 +42,7 @@ public class AnnotationNamespaceDrivenTests extends AbstractCacheAnnotationTests public void testKeyStrategy() { CacheInterceptor ci = this.ctx.getBean( "org.springframework.cache.interceptor.CacheInterceptor#0", CacheInterceptor.class); - assertSame(this.ctx.getBean("keyGenerator"), ci.getKeyGenerator()); + assertThat(ci.getKeyGenerator()).isSameAs(this.ctx.getBean("keyGenerator")); } @Test @@ -51,7 +51,7 @@ public class AnnotationNamespaceDrivenTests extends AbstractCacheAnnotationTests "/org/springframework/cache/config/annotationDrivenCacheNamespace-resolver.xml"); CacheInterceptor ci = context.getBean(CacheInterceptor.class); - assertSame(context.getBean("cacheResolver"), ci.getCacheResolver()); + assertThat(ci.getCacheResolver()).isSameAs(context.getBean("cacheResolver")); context.close(); } @@ -61,7 +61,7 @@ public class AnnotationNamespaceDrivenTests extends AbstractCacheAnnotationTests "/org/springframework/cache/config/annotationDrivenCacheNamespace-manager-resolver.xml"); CacheInterceptor ci = context.getBean(CacheInterceptor.class); - assertSame(context.getBean("cacheResolver"), ci.getCacheResolver()); + assertThat(ci.getCacheResolver()).isSameAs(context.getBean("cacheResolver")); context.close(); } @@ -69,7 +69,7 @@ public class AnnotationNamespaceDrivenTests extends AbstractCacheAnnotationTests public void testCacheErrorHandler() { CacheInterceptor ci = this.ctx.getBean( "org.springframework.cache.interceptor.CacheInterceptor#0", CacheInterceptor.class); - assertSame(this.ctx.getBean("errorHandler", CacheErrorHandler.class), ci.getErrorHandler()); + assertThat(ci.getErrorHandler()).isSameAs(this.ctx.getBean("errorHandler", CacheErrorHandler.class)); } } diff --git a/spring-context/src/test/java/org/springframework/cache/config/CacheAdviceNamespaceTests.java b/spring-context/src/test/java/org/springframework/cache/config/CacheAdviceNamespaceTests.java index e1d88a8c080..eb9eed2c196 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/CacheAdviceNamespaceTests.java +++ b/spring-context/src/test/java/org/springframework/cache/config/CacheAdviceNamespaceTests.java @@ -22,7 +22,7 @@ import org.springframework.cache.interceptor.CacheInterceptor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Costin Leau @@ -39,7 +39,7 @@ public class CacheAdviceNamespaceTests extends AbstractCacheAnnotationTests { @Test public void testKeyStrategy() throws Exception { CacheInterceptor bean = this.ctx.getBean("cacheAdviceClass", CacheInterceptor.class); - assertSame(this.ctx.getBean("keyGenerator"), bean.getKeyGenerator()); + assertThat(bean.getKeyGenerator()).isSameAs(this.ctx.getBean("keyGenerator")); } } diff --git a/spring-context/src/test/java/org/springframework/cache/config/CustomInterceptorTests.java b/spring-context/src/test/java/org/springframework/cache/config/CustomInterceptorTests.java index a0d8fc43b36..8ca33fbce89 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/CustomInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/cache/config/CustomInterceptorTests.java @@ -34,8 +34,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Stephane Nicoll @@ -60,15 +60,16 @@ public class CustomInterceptorTests { @Test public void onlyOneInterceptorIsAvailable() { Map interceptors = this.ctx.getBeansOfType(CacheInterceptor.class); - assertEquals("Only one interceptor should be defined", 1, interceptors.size()); + assertThat(interceptors.size()).as("Only one interceptor should be defined").isEqualTo(1); CacheInterceptor interceptor = interceptors.values().iterator().next(); - assertEquals("Custom interceptor not defined", TestCacheInterceptor.class, interceptor.getClass()); + assertThat(interceptor.getClass()).as("Custom interceptor not defined").isEqualTo(TestCacheInterceptor.class); } @Test public void customInterceptorAppliesWithRuntimeException() { Object o = this.cs.throwUnchecked(0L); - assertEquals(55L, o); // See TestCacheInterceptor + // See TestCacheInterceptor + assertThat(o).isEqualTo(55L); } @Test diff --git a/spring-context/src/test/java/org/springframework/cache/config/EnableCachingIntegrationTests.java b/spring-context/src/test/java/org/springframework/cache/config/EnableCachingIntegrationTests.java index d38faf47ed0..11b01147f57 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/EnableCachingIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/cache/config/EnableCachingIntegrationTests.java @@ -37,7 +37,7 @@ import org.springframework.context.annotation.Import; import org.springframework.core.env.Environment; import org.springframework.mock.env.MockEnvironment; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.cache.CacheTestUtils.assertCacheHit; import static org.springframework.cache.CacheTestUtils.assertCacheMiss; @@ -95,7 +95,7 @@ public class EnableCachingIntegrationTests { service.getWithCondition(key); assertCacheMiss(key, cache); - assertEquals(2, this.context.getBean(BeanConditionConfig.Bar.class).count); + assertThat(this.context.getBean(BeanConditionConfig.Bar.class).count).isEqualTo(2); } @Test @@ -115,7 +115,7 @@ public class EnableCachingIntegrationTests { value = service.getWithCondition(key); assertCacheHit(key, value, cache); - assertEquals(2, this.context.getBean(BeanConditionConfig.Bar.class).count); + assertThat(this.context.getBean(BeanConditionConfig.Bar.class).count).isEqualTo(2); } private Cache getCache() { diff --git a/spring-context/src/test/java/org/springframework/cache/config/EnableCachingTests.java b/spring-context/src/test/java/org/springframework/cache/config/EnableCachingTests.java index 93e6e682cb0..fa1e9b28d2b 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/EnableCachingTests.java +++ b/spring-context/src/test/java/org/springframework/cache/config/EnableCachingTests.java @@ -36,10 +36,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@code @EnableCaching} and its related @@ -59,13 +56,13 @@ public class EnableCachingTests extends AbstractCacheAnnotationTests { @Test public void testKeyStrategy() { CacheInterceptor ci = this.ctx.getBean(CacheInterceptor.class); - assertSame(this.ctx.getBean("keyGenerator", KeyGenerator.class), ci.getKeyGenerator()); + assertThat(ci.getKeyGenerator()).isSameAs(this.ctx.getBean("keyGenerator", KeyGenerator.class)); } @Test public void testCacheErrorHandler() { CacheInterceptor ci = this.ctx.getBean(CacheInterceptor.class); - assertSame(this.ctx.getBean("errorHandler", CacheErrorHandler.class), ci.getErrorHandler()); + assertThat(ci.getErrorHandler()).isSameAs(this.ctx.getBean("errorHandler", CacheErrorHandler.class)); } @Test @@ -83,7 +80,7 @@ public class EnableCachingTests extends AbstractCacheAnnotationTests { ctx.refresh(); } catch (IllegalStateException ex) { - assertTrue(ex.getMessage().contains("no unique bean of type CacheManager")); + assertThat(ex.getMessage().contains("no unique bean of type CacheManager")).isTrue(); } } @@ -103,8 +100,9 @@ public class EnableCachingTests extends AbstractCacheAnnotationTests { } catch (BeanCreationException ex) { Throwable root = ex.getRootCause(); - assertTrue(root instanceof IllegalStateException); - assertTrue(root.getMessage().contains("implementations of CachingConfigurer")); + boolean condition = root instanceof IllegalStateException; + assertThat(condition).isTrue(); + assertThat(root.getMessage().contains("implementations of CachingConfigurer")).isTrue(); } } @@ -116,7 +114,7 @@ public class EnableCachingTests extends AbstractCacheAnnotationTests { ctx.refresh(); } catch (IllegalStateException ex) { - assertTrue(ex.getMessage().contains("no bean of type CacheManager")); + assertThat(ex.getMessage().contains("no bean of type CacheManager")).isTrue(); } } @@ -124,9 +122,9 @@ public class EnableCachingTests extends AbstractCacheAnnotationTests { public void emptyConfigSupport() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(EmptyConfigSupportConfig.class); CacheInterceptor ci = context.getBean(CacheInterceptor.class); - assertNotNull(ci.getCacheResolver()); - assertEquals(SimpleCacheResolver.class, ci.getCacheResolver().getClass()); - assertSame(context.getBean(CacheManager.class), ((SimpleCacheResolver)ci.getCacheResolver()).getCacheManager()); + assertThat(ci.getCacheResolver()).isNotNull(); + assertThat(ci.getCacheResolver().getClass()).isEqualTo(SimpleCacheResolver.class); + assertThat(((SimpleCacheResolver) ci.getCacheResolver()).getCacheManager()).isSameAs(context.getBean(CacheManager.class)); context.close(); } @@ -134,8 +132,8 @@ public class EnableCachingTests extends AbstractCacheAnnotationTests { public void bothSetOnlyResolverIsUsed() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(FullCachingConfig.class); CacheInterceptor ci = context.getBean(CacheInterceptor.class); - assertSame(context.getBean("cacheResolver"), ci.getCacheResolver()); - assertSame(context.getBean("keyGenerator"), ci.getKeyGenerator()); + assertThat(ci.getCacheResolver()).isSameAs(context.getBean("cacheResolver")); + assertThat(ci.getKeyGenerator()).isSameAs(context.getBean("keyGenerator")); context.close(); } diff --git a/spring-context/src/test/java/org/springframework/cache/interceptor/CacheErrorHandlerTests.java b/spring-context/src/test/java/org/springframework/cache/interceptor/CacheErrorHandlerTests.java index b373361e8dc..cf17ac5cca0 100644 --- a/spring-context/src/test/java/org/springframework/cache/interceptor/CacheErrorHandlerTests.java +++ b/spring-context/src/test/java/org/springframework/cache/interceptor/CacheErrorHandlerTests.java @@ -36,9 +36,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willReturn; import static org.mockito.BDDMockito.willThrow; @@ -89,8 +88,8 @@ public class CacheErrorHandlerTests { willReturn(new SimpleValueWrapper(2L)).given(this.cache).get(0L); Object counter2 = this.simpleService.get(0L); Object counter3 = this.simpleService.get(0L); - assertNotSame(counter, counter2); - assertEquals(counter2, counter3); + assertThat(counter2).isNotSameAs(counter); + assertThat(counter3).isEqualTo(counter2); } @Test diff --git a/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java index faf57d95a87..d62e7e3045c 100644 --- a/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/cache/interceptor/CacheProxyFactoryBeanTests.java @@ -27,10 +27,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link CacheProxyFactoryBean}. @@ -45,18 +42,18 @@ public class CacheProxyFactoryBeanTests { try (AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(CacheProxyFactoryBeanConfiguration.class)) { Greeter greeter = applicationContext.getBean("greeter", Greeter.class); - assertNotNull(greeter); - assertFalse(greeter.isCacheMiss()); - assertEquals("Hello John!", greeter.greet("John")); - assertTrue(greeter.isCacheMiss()); - assertEquals("Hello Jon!", greeter.greet("Jon")); - assertTrue(greeter.isCacheMiss()); - assertEquals("Hello John!", greeter.greet("John")); - assertFalse(greeter.isCacheMiss()); - assertEquals("Hello World!", greeter.greet()); - assertTrue(greeter.isCacheMiss()); - assertEquals("Hello World!", greeter.greet()); - assertFalse(greeter.isCacheMiss()); + assertThat(greeter).isNotNull(); + assertThat(greeter.isCacheMiss()).isFalse(); + assertThat(greeter.greet("John")).isEqualTo("Hello John!"); + assertThat(greeter.isCacheMiss()).isTrue(); + assertThat(greeter.greet("Jon")).isEqualTo("Hello Jon!"); + assertThat(greeter.isCacheMiss()).isTrue(); + assertThat(greeter.greet("John")).isEqualTo("Hello John!"); + assertThat(greeter.isCacheMiss()).isFalse(); + assertThat(greeter.greet()).isEqualTo("Hello World!"); + assertThat(greeter.isCacheMiss()).isTrue(); + assertThat(greeter.greet()).isEqualTo("Hello World!"); + assertThat(greeter.isCacheMiss()).isFalse(); } } diff --git a/spring-context/src/test/java/org/springframework/cache/interceptor/CachePutEvaluationTests.java b/spring-context/src/test/java/org/springframework/cache/interceptor/CachePutEvaluationTests.java index c0fbfd3f55c..700e3864588 100644 --- a/spring-context/src/test/java/org/springframework/cache/interceptor/CachePutEvaluationTests.java +++ b/spring-context/src/test/java/org/springframework/cache/interceptor/CachePutEvaluationTests.java @@ -35,9 +35,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests corner case of using {@link Cacheable} and {@link CachePut} on the @@ -73,15 +71,15 @@ public class CachePutEvaluationTests { Long first = this.service.getOrPut(key, true); Long second = this.service.getOrPut(key, true); - assertSame(first, second); + assertThat(second).isSameAs(first); // This forces the method to be executed again Long expected = first + 1; Long third = this.service.getOrPut(key, false); - assertEquals(expected, third); + assertThat(third).isEqualTo(expected); Long fourth = this.service.getOrPut(key, true); - assertSame(third, fourth); + assertThat(fourth).isSameAs(third); } @Test @@ -91,18 +89,19 @@ public class CachePutEvaluationTests { long key = 1; Long value = this.service.getAndPut(key); - assertEquals("Wrong value for @Cacheable key", value, this.cache.get(key).get()); - assertEquals("Wrong value for @CachePut key", value, this.cache.get(value + 100).get()); // See @CachePut + assertThat(this.cache.get(key).get()).as("Wrong value for @Cacheable key").isEqualTo(value); + // See @CachePut + assertThat(this.cache.get(value + 100).get()).as("Wrong value for @CachePut key").isEqualTo(value); // CachePut forced a method call Long anotherValue = this.service.getAndPut(key); - assertNotSame(value, anotherValue); + assertThat(anotherValue).isNotSameAs(value); // NOTE: while you might expect the main key to have been updated, it hasn't. @Cacheable operations // are only processed in case of a cache miss. This is why combining @Cacheable with @CachePut // is a very bad idea. We could refine the condition now that we can figure out if we are going // to invoke the method anyway but that brings a whole new set of potential regressions. //assertEquals("Wrong value for @Cacheable key", anotherValue, cache.get(key).get()); - assertEquals("Wrong value for @CachePut key", anotherValue, this.cache.get(anotherValue + 100).get()); + assertThat(this.cache.get(anotherValue + 100).get()).as("Wrong value for @CachePut key").isEqualTo(anotherValue); } @Configuration diff --git a/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvaluatorTests.java b/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvaluatorTests.java index e8365bdd29c..b321e2ceb7d 100644 --- a/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvaluatorTests.java +++ b/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvaluatorTests.java @@ -38,8 +38,6 @@ import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Costin Leau @@ -63,16 +61,16 @@ public class ExpressionEvaluatorTests { @Test public void testMultipleCachingSource() { Collection ops = getOps("multipleCaching"); - assertEquals(2, ops.size()); + assertThat(ops.size()).isEqualTo(2); Iterator it = ops.iterator(); CacheOperation next = it.next(); - assertTrue(next instanceof CacheableOperation); - assertTrue(next.getCacheNames().contains("test")); - assertEquals("#a", next.getKey()); + assertThat(next instanceof CacheableOperation).isTrue(); + assertThat(next.getCacheNames().contains("test")).isTrue(); + assertThat(next.getKey()).isEqualTo("#a"); next = it.next(); - assertTrue(next instanceof CacheableOperation); - assertTrue(next.getCacheNames().contains("test")); - assertEquals("#b", next.getKey()); + assertThat(next instanceof CacheableOperation).isTrue(); + assertThat(next.getCacheNames().contains("test")).isTrue(); + assertThat(next.getKey()).isEqualTo("#b"); } @Test @@ -93,8 +91,8 @@ public class ExpressionEvaluatorTests { Object keyA = this.eval.key(it.next().getKey(), key, evalCtx); Object keyB = this.eval.key(it.next().getKey(), key, evalCtx); - assertEquals(args[0], keyA); - assertEquals(args[1], keyB); + assertThat(keyA).isEqualTo(args[0]); + assertThat(keyB).isEqualTo(args[1]); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java index 2aafcbc0572..4be8c083d2f 100644 --- a/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java @@ -30,9 +30,8 @@ import org.springframework.beans.factory.xml.AbstractListableBeanFactoryTests; import org.springframework.tests.sample.beans.LifecycleBean; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -76,69 +75,71 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe @Test public void contextAwareSingletonWasCalledBack() throws Exception { ACATester aca = (ACATester) applicationContext.getBean("aca"); - assertTrue("has had context set", aca.getApplicationContext() == applicationContext); + assertThat(aca.getApplicationContext() == applicationContext).as("has had context set").isTrue(); Object aca2 = applicationContext.getBean("aca"); - assertTrue("Same instance", aca == aca2); - assertTrue("Says is singleton", applicationContext.isSingleton("aca")); + assertThat(aca == aca2).as("Same instance").isTrue(); + assertThat(applicationContext.isSingleton("aca")).as("Says is singleton").isTrue(); } @Test public void contextAwarePrototypeWasCalledBack() throws Exception { ACATester aca = (ACATester) applicationContext.getBean("aca-prototype"); - assertTrue("has had context set", aca.getApplicationContext() == applicationContext); + assertThat(aca.getApplicationContext() == applicationContext).as("has had context set").isTrue(); Object aca2 = applicationContext.getBean("aca-prototype"); - assertTrue("NOT Same instance", aca != aca2); - assertTrue("Says is prototype", !applicationContext.isSingleton("aca-prototype")); + assertThat(aca != aca2).as("NOT Same instance").isTrue(); + boolean condition = !applicationContext.isSingleton("aca-prototype"); + assertThat(condition).as("Says is prototype").isTrue(); } @Test public void parentNonNull() { - assertTrue("parent isn't null", applicationContext.getParent() != null); + assertThat(applicationContext.getParent() != null).as("parent isn't null").isTrue(); } @Test public void grandparentNull() { - assertTrue("grandparent is null", applicationContext.getParent().getParent() == null); + assertThat(applicationContext.getParent().getParent() == null).as("grandparent is null").isTrue(); } @Test public void overrideWorked() throws Exception { TestBean rod = (TestBean) applicationContext.getParent().getBean("rod"); - assertTrue("Parent's name differs", rod.getName().equals("Roderick")); + assertThat(rod.getName().equals("Roderick")).as("Parent's name differs").isTrue(); } @Test public void grandparentDefinitionFound() throws Exception { TestBean dad = (TestBean) applicationContext.getBean("father"); - assertTrue("Dad has correct name", dad.getName().equals("Albert")); + assertThat(dad.getName().equals("Albert")).as("Dad has correct name").isTrue(); } @Test public void grandparentTypedDefinitionFound() throws Exception { TestBean dad = applicationContext.getBean("father", TestBean.class); - assertTrue("Dad has correct name", dad.getName().equals("Albert")); + assertThat(dad.getName().equals("Albert")).as("Dad has correct name").isTrue(); } @Test public void closeTriggersDestroy() { LifecycleBean lb = (LifecycleBean) applicationContext.getBean("lifecycle"); - assertTrue("Not destroyed", !lb.isDestroyed()); + boolean condition = !lb.isDestroyed(); + assertThat(condition).as("Not destroyed").isTrue(); applicationContext.close(); if (applicationContext.getParent() != null) { ((ConfigurableApplicationContext) applicationContext.getParent()).close(); } - assertTrue("Destroyed", lb.isDestroyed()); + assertThat(lb.isDestroyed()).as("Destroyed").isTrue(); applicationContext.close(); if (applicationContext.getParent() != null) { ((ConfigurableApplicationContext) applicationContext.getParent()).close(); } - assertTrue("Destroyed", lb.isDestroyed()); + assertThat(lb.isDestroyed()).as("Destroyed").isTrue(); } @Test public void messageSource() throws NoSuchMessageException { - assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault())); - assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault())); + assertThat(applicationContext.getMessage("code1", null, Locale.getDefault())).isEqualTo("message1"); + assertThat(applicationContext.getMessage("code2", null, Locale.getDefault())).isEqualTo("message2"); assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> applicationContext.getMessage("code0", null, Locale.getDefault())); } @@ -165,11 +166,11 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe MyEvent event) { listener.zeroCounter(); parentListener.zeroCounter(); - assertTrue("0 events before publication", listener.getEventCount() == 0); - assertTrue("0 parent events before publication", parentListener.getEventCount() == 0); + assertThat(listener.getEventCount() == 0).as("0 events before publication").isTrue(); + assertThat(parentListener.getEventCount() == 0).as("0 parent events before publication").isTrue(); this.applicationContext.publishEvent(event); - assertTrue("1 events after publication, not " + listener.getEventCount(), listener.getEventCount() == 1); - assertTrue("1 parent events after publication", parentListener.getEventCount() == 1); + assertThat(listener.getEventCount() == 1).as("1 events after publication, not " + listener.getEventCount()).isTrue(); + assertThat(parentListener.getEventCount() == 1).as("1 parent events after publication").isTrue(); } @Test @@ -178,9 +179,9 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe //assertTrue("listeners include beanThatListens", Arrays.asList(listenerNames).contains("beanThatListens")); BeanThatListens b = (BeanThatListens) applicationContext.getBean("beanThatListens"); b.zero(); - assertTrue("0 events before publication", b.getEventCount() == 0); + assertThat(b.getEventCount() == 0).as("0 events before publication").isTrue(); this.applicationContext.publishEvent(new MyEvent(this)); - assertTrue("1 events after publication, not " + b.getEventCount(), b.getEventCount() == 1); + assertThat(b.getEventCount() == 1).as("1 events after publication, not " + b.getEventCount()).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AbstractCircularImportDetectionTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AbstractCircularImportDetectionTests.java index 7e4f09ba687..d637dd693f9 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AbstractCircularImportDetectionTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AbstractCircularImportDetectionTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * TCK-style unit tests for handling circular use of the {@link Import} annotation. @@ -43,13 +43,12 @@ public abstract class AbstractCircularImportDetectionTests { newParser().parse(loadAsConfigurationSource(A.class), "A"); } catch (BeanDefinitionParsingException ex) { - assertTrue("Wrong message. Got: " + ex.getMessage(), - ex.getMessage().contains( - "Illegal attempt by @Configuration class 'AbstractCircularImportDetectionTests.B' " + - "to import class 'AbstractCircularImportDetectionTests.A'")); + assertThat(ex.getMessage().contains( + "Illegal attempt by @Configuration class 'AbstractCircularImportDetectionTests.B' " + + "to import class 'AbstractCircularImportDetectionTests.A'")).as("Wrong message. Got: " + ex.getMessage()).isTrue(); threw = true; } - assertTrue(threw); + assertThat(threw).isTrue(); } @Test @@ -59,13 +58,12 @@ public abstract class AbstractCircularImportDetectionTests { newParser().parse(loadAsConfigurationSource(X.class), "X"); } catch (BeanDefinitionParsingException ex) { - assertTrue("Wrong message. Got: " + ex.getMessage(), - ex.getMessage().contains( - "Illegal attempt by @Configuration class 'AbstractCircularImportDetectionTests.Z2' " + - "to import class 'AbstractCircularImportDetectionTests.Z'")); + assertThat(ex.getMessage().contains( + "Illegal attempt by @Configuration class 'AbstractCircularImportDetectionTests.Z2' " + + "to import class 'AbstractCircularImportDetectionTests.Z'")).as("Wrong message. Got: " + ex.getMessage()).isTrue(); threw = true; } - assertTrue(threw); + assertThat(threw).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationBeanNameGeneratorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationBeanNameGeneratorTests.java index 90c0cc7192a..78305981ea4 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationBeanNameGeneratorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationBeanNameGeneratorTests.java @@ -33,9 +33,7 @@ import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link AnnotationBeanNameGenerator}. @@ -56,9 +54,9 @@ public class AnnotationBeanNameGeneratorTests { BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComponentWithName.class); String beanName = this.beanNameGenerator.generateBeanName(bd, registry); - assertNotNull("The generated beanName must *never* be null.", beanName); - assertTrue("The generated beanName must *never* be blank.", StringUtils.hasText(beanName)); - assertEquals("walden", beanName); + assertThat(beanName).as("The generated beanName must *never* be null.").isNotNull(); + assertThat(StringUtils.hasText(beanName)).as("The generated beanName must *never* be blank.").isTrue(); + assertThat(beanName).isEqualTo("walden"); } @Test @@ -66,9 +64,9 @@ public class AnnotationBeanNameGeneratorTests { BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(DefaultNamedComponent.class); String beanName = this.beanNameGenerator.generateBeanName(bd, registry); - assertNotNull("The generated beanName must *never* be null.", beanName); - assertTrue("The generated beanName must *never* be blank.", StringUtils.hasText(beanName)); - assertEquals("thoreau", beanName); + assertThat(beanName).as("The generated beanName must *never* be null.").isNotNull(); + assertThat(StringUtils.hasText(beanName)).as("The generated beanName must *never* be blank.").isTrue(); + assertThat(beanName).isEqualTo("thoreau"); } @Test @@ -76,10 +74,10 @@ public class AnnotationBeanNameGeneratorTests { BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComponentWithBlankName.class); String beanName = this.beanNameGenerator.generateBeanName(bd, registry); - assertNotNull("The generated beanName must *never* be null.", beanName); - assertTrue("The generated beanName must *never* be blank.", StringUtils.hasText(beanName)); + assertThat(beanName).as("The generated beanName must *never* be null.").isNotNull(); + assertThat(StringUtils.hasText(beanName)).as("The generated beanName must *never* be blank.").isTrue(); String expectedGeneratedBeanName = this.beanNameGenerator.buildDefaultBeanName(bd); - assertEquals(expectedGeneratedBeanName, beanName); + assertThat(beanName).isEqualTo(expectedGeneratedBeanName); } @Test @@ -87,10 +85,10 @@ public class AnnotationBeanNameGeneratorTests { BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnonymousComponent.class); String beanName = this.beanNameGenerator.generateBeanName(bd, registry); - assertNotNull("The generated beanName must *never* be null.", beanName); - assertTrue("The generated beanName must *never* be blank.", StringUtils.hasText(beanName)); + assertThat(beanName).as("The generated beanName must *never* be null.").isNotNull(); + assertThat(StringUtils.hasText(beanName)).as("The generated beanName must *never* be blank.").isTrue(); String expectedGeneratedBeanName = this.beanNameGenerator.buildDefaultBeanName(bd); - assertEquals(expectedGeneratedBeanName, beanName); + assertThat(beanName).isEqualTo(expectedGeneratedBeanName); } @Test @@ -98,7 +96,7 @@ public class AnnotationBeanNameGeneratorTests { BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComponentFromStringMeta.class); String beanName = this.beanNameGenerator.generateBeanName(bd, registry); - assertEquals("henry", beanName); + assertThat(beanName).isEqualTo("henry"); } @Test @@ -106,7 +104,7 @@ public class AnnotationBeanNameGeneratorTests { BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComponentFromNonStringMeta.class); String beanName = this.beanNameGenerator.generateBeanName(bd, registry); - assertEquals("annotationBeanNameGeneratorTests.ComponentFromNonStringMeta", beanName); + assertThat(beanName).isEqualTo("annotationBeanNameGeneratorTests.ComponentFromNonStringMeta"); } @Test @@ -116,7 +114,7 @@ public class AnnotationBeanNameGeneratorTests { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComposedControllerAnnotationWithoutName.class); String beanName = this.beanNameGenerator.generateBeanName(bd, registry); String expectedGeneratedBeanName = this.beanNameGenerator.buildDefaultBeanName(bd); - assertEquals(expectedGeneratedBeanName, beanName); + assertThat(beanName).isEqualTo(expectedGeneratedBeanName); } @Test @@ -126,7 +124,7 @@ public class AnnotationBeanNameGeneratorTests { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(ComposedControllerAnnotationWithBlankName.class); String beanName = this.beanNameGenerator.generateBeanName(bd, registry); String expectedGeneratedBeanName = this.beanNameGenerator.buildDefaultBeanName(bd); - assertEquals(expectedGeneratedBeanName, beanName); + assertThat(beanName).isEqualTo(expectedGeneratedBeanName); } @Test @@ -136,7 +134,7 @@ public class AnnotationBeanNameGeneratorTests { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition( ComposedControllerAnnotationWithStringValue.class); String beanName = this.beanNameGenerator.generateBeanName(bd, registry); - assertEquals("restController", beanName); + assertThat(beanName).isEqualTo("restController"); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java index 93868d62365..5dcd74b7a83 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java @@ -36,13 +36,6 @@ import org.springframework.util.ObjectUtils; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.springframework.util.StringUtils.uncapitalize; /** @@ -62,7 +55,7 @@ public class AnnotationConfigApplicationContextTests { context.getBean(uncapitalize(ComponentForScanning.class.getSimpleName())); context.getBean(uncapitalize(Jsr330NamedForScanning.class.getSimpleName())); Map beans = context.getBeansWithAnnotation(Configuration.class); - assertEquals(1, beans.size()); + assertThat(beans.size()).isEqualTo(1); } @Test @@ -74,7 +67,7 @@ public class AnnotationConfigApplicationContextTests { context.getBean("testBean"); context.getBean("name"); Map beans = context.getBeansWithAnnotation(Configuration.class); - assertEquals(2, beans.size()); + assertThat(beans.size()).isEqualTo(2); } @Test @@ -86,14 +79,14 @@ public class AnnotationConfigApplicationContextTests { context.getBean("testBean"); context.getBean("name"); Map beans = context.getBeansWithAnnotation(Configuration.class); - assertEquals(2, beans.size()); + assertThat(beans.size()).isEqualTo(2); } @Test public void getBeanByType() { ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); TestBean testBean = context.getBean(TestBean.class); - assertNotNull(testBean); + assertThat(testBean).isNotNull(); assertThat(testBean.name).isEqualTo("foo"); } @@ -128,7 +121,7 @@ public class AnnotationConfigApplicationContextTests { // attempt to retrieve the instance by its generated bean name Config configObject = (Config) context.getBean("annotationConfigApplicationContextTests.Config"); - assertNotNull(configObject); + assertThat(configObject).isNotNull(); } /** @@ -141,7 +134,7 @@ public class AnnotationConfigApplicationContextTests { // attempt to retrieve the instance by its specified name ConfigWithCustomName configObject = (ConfigWithCustomName) context.getBean("customConfigBeanName"); - assertNotNull(configObject); + assertThat(configObject).isNotNull(); } @Test @@ -185,9 +178,9 @@ public class AnnotationConfigApplicationContextTests { context.register(BeanA.class, BeanB.class, BeanC.class); context.refresh(); - assertSame(context.getBean(BeanB.class), context.getBean(BeanA.class).b); - assertSame(context.getBean(BeanC.class), context.getBean(BeanA.class).c); - assertSame(context, context.getBean(BeanB.class).applicationContext); + assertThat(context.getBean(BeanA.class).b).isSameAs(context.getBean(BeanB.class)); + assertThat(context.getBean(BeanA.class).c).isSameAs(context.getBean(BeanC.class)); + assertThat(context.getBean(BeanB.class).applicationContext).isSameAs(context); } @Test @@ -198,9 +191,9 @@ public class AnnotationConfigApplicationContextTests { context.registerBean("c", BeanC.class); context.refresh(); - assertSame(context.getBean("b"), context.getBean("a", BeanA.class).b); - assertSame(context.getBean("c"), context.getBean("a", BeanA.class).c); - assertSame(context, context.getBean("b", BeanB.class).applicationContext); + assertThat(context.getBean("a", BeanA.class).b).isSameAs(context.getBean("b")); + assertThat(context.getBean("a", BeanA.class).c).isSameAs(context.getBean("c")); + assertThat(context.getBean("b", BeanB.class).applicationContext).isSameAs(context); } @Test @@ -212,15 +205,13 @@ public class AnnotationConfigApplicationContextTests { context.registerBean(BeanC.class, BeanC::new); context.refresh(); - assertTrue(context.getBeanFactory().containsSingleton("annotationConfigApplicationContextTests.BeanA")); - assertSame(context.getBean(BeanB.class), context.getBean(BeanA.class).b); - assertSame(context.getBean(BeanC.class), context.getBean(BeanA.class).c); - assertSame(context, context.getBean(BeanB.class).applicationContext); + assertThat(context.getBeanFactory().containsSingleton("annotationConfigApplicationContextTests.BeanA")).isTrue(); + assertThat(context.getBean(BeanA.class).b).isSameAs(context.getBean(BeanB.class)); + assertThat(context.getBean(BeanA.class).c).isSameAs(context.getBean(BeanC.class)); + assertThat(context.getBean(BeanB.class).applicationContext).isSameAs(context); - assertArrayEquals(new String[] {"annotationConfigApplicationContextTests.BeanA"}, - context.getDefaultListableBeanFactory().getDependentBeans("annotationConfigApplicationContextTests.BeanB")); - assertArrayEquals(new String[] {"annotationConfigApplicationContextTests.BeanA"}, - context.getDefaultListableBeanFactory().getDependentBeans("annotationConfigApplicationContextTests.BeanC")); + assertThat(context.getDefaultListableBeanFactory().getDependentBeans("annotationConfigApplicationContextTests.BeanB")).isEqualTo(new String[] {"annotationConfigApplicationContextTests.BeanA"}); + assertThat(context.getDefaultListableBeanFactory().getDependentBeans("annotationConfigApplicationContextTests.BeanC")).isEqualTo(new String[] {"annotationConfigApplicationContextTests.BeanA"}); } @Test @@ -233,10 +224,10 @@ public class AnnotationConfigApplicationContextTests { context.registerBean(BeanC.class, BeanC::new); context.refresh(); - assertFalse(context.getBeanFactory().containsSingleton("annotationConfigApplicationContextTests.BeanA")); - assertSame(context.getBean(BeanB.class), context.getBean(BeanA.class).b); - assertSame(context.getBean(BeanC.class), context.getBean(BeanA.class).c); - assertSame(context, context.getBean(BeanB.class).applicationContext); + assertThat(context.getBeanFactory().containsSingleton("annotationConfigApplicationContextTests.BeanA")).isFalse(); + assertThat(context.getBean(BeanA.class).b).isSameAs(context.getBean(BeanB.class)); + assertThat(context.getBean(BeanA.class).c).isSameAs(context.getBean(BeanC.class)); + assertThat(context.getBean(BeanB.class).applicationContext).isSameAs(context); } @Test @@ -248,10 +239,10 @@ public class AnnotationConfigApplicationContextTests { context.registerBean("c", BeanC.class, BeanC::new); context.refresh(); - assertTrue(context.getBeanFactory().containsSingleton("a")); - assertSame(context.getBean("b", BeanB.class), context.getBean(BeanA.class).b); - assertSame(context.getBean("c"), context.getBean("a", BeanA.class).c); - assertSame(context, context.getBean("b", BeanB.class).applicationContext); + assertThat(context.getBeanFactory().containsSingleton("a")).isTrue(); + assertThat(context.getBean(BeanA.class).b).isSameAs(context.getBean("b", BeanB.class)); + assertThat(context.getBean("a", BeanA.class).c).isSameAs(context.getBean("c")); + assertThat(context.getBean("b", BeanB.class).applicationContext).isSameAs(context); } @Test @@ -264,10 +255,10 @@ public class AnnotationConfigApplicationContextTests { context.registerBean("c", BeanC.class, BeanC::new); context.refresh(); - assertFalse(context.getBeanFactory().containsSingleton("a")); - assertSame(context.getBean("b", BeanB.class), context.getBean(BeanA.class).b); - assertSame(context.getBean("c"), context.getBean("a", BeanA.class).c); - assertSame(context, context.getBean("b", BeanB.class).applicationContext); + assertThat(context.getBeanFactory().containsSingleton("a")).isFalse(); + assertThat(context.getBean(BeanA.class).b).isSameAs(context.getBean("b", BeanB.class)); + assertThat(context.getBean("a", BeanA.class).c).isSameAs(context.getBean("c")); + assertThat(context.getBean("b", BeanB.class).applicationContext).isSameAs(context); } @Test @@ -278,12 +269,12 @@ public class AnnotationConfigApplicationContextTests { context.registerBean("c", BeanC.class, BeanC::new); context.refresh(); - assertTrue(ObjectUtils.containsElement(context.getBeanNamesForType(BeanA.class), "a")); - assertTrue(ObjectUtils.containsElement(context.getBeanNamesForType(BeanB.class), "b")); - assertTrue(ObjectUtils.containsElement(context.getBeanNamesForType(BeanC.class), "c")); - assertTrue(context.getBeansOfType(BeanA.class).isEmpty()); - assertSame(context.getBean(BeanB.class), context.getBeansOfType(BeanB.class).values().iterator().next()); - assertSame(context.getBean(BeanC.class), context.getBeansOfType(BeanC.class).values().iterator().next()); + assertThat(ObjectUtils.containsElement(context.getBeanNamesForType(BeanA.class), "a")).isTrue(); + assertThat(ObjectUtils.containsElement(context.getBeanNamesForType(BeanB.class), "b")).isTrue(); + assertThat(ObjectUtils.containsElement(context.getBeanNamesForType(BeanC.class), "c")).isTrue(); + assertThat(context.getBeansOfType(BeanA.class).isEmpty()).isTrue(); + assertThat(context.getBeansOfType(BeanB.class).values().iterator().next()).isSameAs(context.getBean(BeanB.class)); + assertThat(context.getBeansOfType(BeanC.class).values().iterator().next()).isSameAs(context.getBean(BeanC.class)); } @Test @@ -294,9 +285,9 @@ public class AnnotationConfigApplicationContextTests { context.registerBean(BeanA.class, b, c); context.refresh(); - assertSame(b, context.getBean(BeanA.class).b); - assertSame(c, context.getBean(BeanA.class).c); - assertNull(b.applicationContext); + assertThat(context.getBean(BeanA.class).b).isSameAs(b); + assertThat(context.getBean(BeanA.class).c).isSameAs(c); + assertThat((Object) b.applicationContext).isNull(); } @Test @@ -307,9 +298,9 @@ public class AnnotationConfigApplicationContextTests { context.registerBean("a", BeanA.class, b, c); context.refresh(); - assertSame(b, context.getBean("a", BeanA.class).b); - assertSame(c, context.getBean("a", BeanA.class).c); - assertNull(b.applicationContext); + assertThat(context.getBean("a", BeanA.class).b).isSameAs(b); + assertThat(context.getBean("a", BeanA.class).c).isSameAs(c); + assertThat((Object) b.applicationContext).isNull(); } @Test @@ -320,9 +311,9 @@ public class AnnotationConfigApplicationContextTests { context.registerBean(BeanB.class); context.refresh(); - assertSame(context.getBean(BeanB.class), context.getBean(BeanA.class).b); - assertSame(c, context.getBean(BeanA.class).c); - assertSame(context, context.getBean(BeanB.class).applicationContext); + assertThat(context.getBean(BeanA.class).b).isSameAs(context.getBean(BeanB.class)); + assertThat(context.getBean(BeanA.class).c).isSameAs(c); + assertThat(context.getBean(BeanB.class).applicationContext).isSameAs(context); } @Test @@ -333,9 +324,9 @@ public class AnnotationConfigApplicationContextTests { context.registerBean("b", BeanB.class); context.refresh(); - assertSame(context.getBean("b", BeanB.class), context.getBean("a", BeanA.class).b); - assertSame(c, context.getBean("a", BeanA.class).c); - assertSame(context, context.getBean("b", BeanB.class).applicationContext); + assertThat(context.getBean("a", BeanA.class).b).isSameAs(context.getBean("b", BeanB.class)); + assertThat(context.getBean("a", BeanA.class).c).isSameAs(c); + assertThat(context.getBean("b", BeanB.class).applicationContext).isSameAs(context); } @Test @@ -344,8 +335,8 @@ public class AnnotationConfigApplicationContextTests { context.registerBean("fb", TypedFactoryBean.class, TypedFactoryBean::new, bd -> bd.setLazyInit(true)); context.refresh(); - assertEquals(String.class, context.getType("fb")); - assertEquals(TypedFactoryBean.class, context.getType("&fb")); + assertThat(context.getType("fb")).isEqualTo(String.class); + assertThat(context.getType("&fb")).isEqualTo(TypedFactoryBean.class); } @Test @@ -358,8 +349,8 @@ public class AnnotationConfigApplicationContextTests { context.registerBeanDefinition("fb", bd); context.refresh(); - assertEquals(String.class, context.getType("fb")); - assertEquals(FactoryBean.class, context.getType("&fb")); + assertThat(context.getType("fb")).isEqualTo(String.class); + assertThat(context.getType("&fb")).isEqualTo(FactoryBean.class); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java index fe0251a27d0..4d25a56a95e 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java @@ -34,8 +34,7 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.StopWatch; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -67,10 +66,10 @@ public class AnnotationProcessorPerformanceTests { sw.start("prototype"); for (int i = 0; i < 100000; i++) { TestBean tb = (TestBean) ctx.getBean("test"); - assertSame(spouse, tb.getSpouse()); + assertThat(tb.getSpouse()).isSameAs(spouse); } sw.stop(); - assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 4000); + assertThat(sw.getTotalTimeMillis() < 4000).as("Prototype creation took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -89,10 +88,10 @@ public class AnnotationProcessorPerformanceTests { sw.start("prototype"); for (int i = 0; i < 100000; i++) { TestBean tb = (TestBean) ctx.getBean("test"); - assertSame(spouse, tb.getSpouse()); + assertThat(tb.getSpouse()).isSameAs(spouse); } sw.stop(); - assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 4000); + assertThat(sw.getTotalTimeMillis() < 4000).as("Prototype creation took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -110,10 +109,10 @@ public class AnnotationProcessorPerformanceTests { sw.start("prototype"); for (int i = 0; i < 100000; i++) { TestBean tb = (TestBean) ctx.getBean("test"); - assertSame(spouse, tb.getSpouse()); + assertThat(tb.getSpouse()).isSameAs(spouse); } sw.stop(); - assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 4000); + assertThat(sw.getTotalTimeMillis() < 4000).as("Prototype creation took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -132,10 +131,10 @@ public class AnnotationProcessorPerformanceTests { sw.start("prototype"); for (int i = 0; i < 100000; i++) { TestBean tb = (TestBean) ctx.getBean("test"); - assertSame(spouse, tb.getSpouse()); + assertThat(tb.getSpouse()).isSameAs(spouse); } sw.stop(); - assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 6000); + assertThat(sw.getTotalTimeMillis() < 6000).as("Prototype creation took too long: " + sw.getTotalTimeMillis()).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationScopeMetadataResolverTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationScopeMetadataResolverTests.java index 147a7d19941..7ae0d5842be 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationScopeMetadataResolverTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationScopeMetadataResolverTests.java @@ -29,9 +29,8 @@ import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.springframework.context.annotation.ScopedProxyMode.INTERFACES; import static org.springframework.context.annotation.ScopedProxyMode.NO; import static org.springframework.context.annotation.ScopedProxyMode.TARGET_CLASS; @@ -53,9 +52,9 @@ public class AnnotationScopeMetadataResolverTests { public void resolveScopeMetadataShouldNotApplyScopedProxyModeToSingleton() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithSingletonScope.class); ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); - assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); - assertEquals(BeanDefinition.SCOPE_SINGLETON, scopeMetadata.getScopeName()); - assertEquals(NO, scopeMetadata.getScopedProxyMode()); + assertThat(scopeMetadata).as("resolveScopeMetadata(..) must *never* return null.").isNotNull(); + assertThat(scopeMetadata.getScopeName()).isEqualTo(BeanDefinition.SCOPE_SINGLETON); + assertThat(scopeMetadata.getScopedProxyMode()).isEqualTo(NO); } @Test @@ -63,27 +62,27 @@ public class AnnotationScopeMetadataResolverTests { this.scopeMetadataResolver = new AnnotationScopeMetadataResolver(INTERFACES); AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithPrototypeScope.class); ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); - assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); - assertEquals(BeanDefinition.SCOPE_PROTOTYPE, scopeMetadata.getScopeName()); - assertEquals(INTERFACES, scopeMetadata.getScopedProxyMode()); + assertThat(scopeMetadata).as("resolveScopeMetadata(..) must *never* return null.").isNotNull(); + assertThat(scopeMetadata.getScopeName()).isEqualTo(BeanDefinition.SCOPE_PROTOTYPE); + assertThat(scopeMetadata.getScopedProxyMode()).isEqualTo(INTERFACES); } @Test public void resolveScopeMetadataShouldReadScopedProxyModeFromAnnotation() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithScopedProxy.class); ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); - assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); - assertEquals("request", scopeMetadata.getScopeName()); - assertEquals(TARGET_CLASS, scopeMetadata.getScopedProxyMode()); + assertThat(scopeMetadata).as("resolveScopeMetadata(..) must *never* return null.").isNotNull(); + assertThat(scopeMetadata.getScopeName()).isEqualTo("request"); + assertThat(scopeMetadata.getScopedProxyMode()).isEqualTo(TARGET_CLASS); } @Test public void customRequestScope() { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(AnnotatedWithCustomRequestScope.class); ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); - assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); - assertEquals("request", scopeMetadata.getScopeName()); - assertEquals(NO, scopeMetadata.getScopedProxyMode()); + assertThat(scopeMetadata).as("resolveScopeMetadata(..) must *never* return null.").isNotNull(); + assertThat(scopeMetadata.getScopeName()).isEqualTo("request"); + assertThat(scopeMetadata.getScopedProxyMode()).isEqualTo(NO); } @Test @@ -92,9 +91,9 @@ public class AnnotationScopeMetadataResolverTests { MetadataReader reader = readerFactory.getMetadataReader(AnnotatedWithCustomRequestScope.class.getName()); AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(reader.getAnnotationMetadata()); ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); - assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); - assertEquals("request", scopeMetadata.getScopeName()); - assertEquals(NO, scopeMetadata.getScopedProxyMode()); + assertThat(scopeMetadata).as("resolveScopeMetadata(..) must *never* return null.").isNotNull(); + assertThat(scopeMetadata.getScopeName()).isEqualTo("request"); + assertThat(scopeMetadata.getScopedProxyMode()).isEqualTo(NO); } @Test @@ -102,9 +101,9 @@ public class AnnotationScopeMetadataResolverTests { AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition( AnnotatedWithCustomRequestScopeWithAttributeOverride.class); ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); - assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); - assertEquals("request", scopeMetadata.getScopeName()); - assertEquals(TARGET_CLASS, scopeMetadata.getScopedProxyMode()); + assertThat(scopeMetadata).as("resolveScopeMetadata(..) must *never* return null.").isNotNull(); + assertThat(scopeMetadata.getScopeName()).isEqualTo("request"); + assertThat(scopeMetadata.getScopedProxyMode()).isEqualTo(TARGET_CLASS); } @Test @@ -113,9 +112,9 @@ public class AnnotationScopeMetadataResolverTests { MetadataReader reader = readerFactory.getMetadataReader(AnnotatedWithCustomRequestScopeWithAttributeOverride.class.getName()); AnnotatedBeanDefinition bd = new AnnotatedGenericBeanDefinition(reader.getAnnotationMetadata()); ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(bd); - assertNotNull("resolveScopeMetadata(..) must *never* return null.", scopeMetadata); - assertEquals("request", scopeMetadata.getScopeName()); - assertEquals(TARGET_CLASS, scopeMetadata.getScopedProxyMode()); + assertThat(scopeMetadata).as("resolveScopeMetadata(..) must *never* return null.").isNotNull(); + assertThat(scopeMetadata.getScopeName()).isEqualTo("request"); + assertThat(scopeMetadata.getScopedProxyMode()).isEqualTo(TARGET_CLASS); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AutoProxyLazyInitTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AutoProxyLazyInitTests.java index 5ec8a3573ca..7421d014cdc 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AutoProxyLazyInitTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AutoProxyLazyInitTests.java @@ -27,9 +27,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ApplicationContextEvent; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -44,9 +42,9 @@ public class AutoProxyLazyInitTests { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithStatic.class); MyBean bean = ctx.getBean("myBean", MyBean.class); - assertFalse(MyBeanImpl.initialized); + assertThat(MyBeanImpl.initialized).isFalse(); bean.doIt(); - assertTrue(MyBeanImpl.initialized); + assertThat(MyBeanImpl.initialized).isTrue(); } @Test @@ -56,9 +54,9 @@ public class AutoProxyLazyInitTests { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithStaticAndInterface.class); MyBean bean = ctx.getBean("myBean", MyBean.class); - assertFalse(MyBeanImpl.initialized); + assertThat(MyBeanImpl.initialized).isFalse(); bean.doIt(); - assertTrue(MyBeanImpl.initialized); + assertThat(MyBeanImpl.initialized).isTrue(); } @Test @@ -68,9 +66,9 @@ public class AutoProxyLazyInitTests { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithNonStatic.class); MyBean bean = ctx.getBean("myBean", MyBean.class); - assertFalse(MyBeanImpl.initialized); + assertThat(MyBeanImpl.initialized).isFalse(); bean.doIt(); - assertTrue(MyBeanImpl.initialized); + assertThat(MyBeanImpl.initialized).isTrue(); } @Test @@ -80,9 +78,9 @@ public class AutoProxyLazyInitTests { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithNonStaticAndInterface.class); MyBean bean = ctx.getBean("myBean", MyBean.class); - assertFalse(MyBeanImpl.initialized); + assertThat(MyBeanImpl.initialized).isFalse(); bean.doIt(); - assertTrue(MyBeanImpl.initialized); + assertThat(MyBeanImpl.initialized).isTrue(); } @@ -216,7 +214,7 @@ public class AutoProxyLazyInitTests { @Override protected AbstractBeanFactoryBasedTargetSource createBeanFactoryBasedTargetSource(Class beanClass, String beanName) { if ("myBean".equals(beanName)) { - assertEquals(MyBean.class, beanClass); + assertThat(beanClass).isEqualTo(MyBean.class); } return super.createBeanFactoryBasedTargetSource(beanClass, beanName); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java b/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java index f863860a6bb..e1971befa56 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java @@ -26,9 +26,6 @@ import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.beans.factory.support.RootBeanDefinition; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Tests regarding overloading and overriding of bean methods. @@ -53,9 +50,9 @@ public class BeanMethodPolymorphismTests { ctx.register(OverridingConfig.class); ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); - assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")); - assertEquals("overridden", ctx.getBean("testBean", TestBean.class).toString()); - assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")).isFalse(); + assertThat(ctx.getBean("testBean", TestBean.class).toString()).isEqualTo("overridden"); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")).isTrue(); } @Test @@ -64,9 +61,9 @@ public class BeanMethodPolymorphismTests { ctx.registerBeanDefinition("config", new RootBeanDefinition(OverridingConfig.class.getName())); ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); - assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")); - assertEquals("overridden", ctx.getBean("testBean", TestBean.class).toString()); - assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")).isFalse(); + assertThat(ctx.getBean("testBean", TestBean.class).toString()).isEqualTo("overridden"); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")).isTrue(); } @Test @@ -75,9 +72,9 @@ public class BeanMethodPolymorphismTests { ctx.register(NarrowedOverridingConfig.class); ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); - assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")); - assertEquals("overridden", ctx.getBean("testBean", TestBean.class).toString()); - assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")).isFalse(); + assertThat(ctx.getBean("testBean", TestBean.class).toString()).isEqualTo("overridden"); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")).isTrue(); } @Test @@ -86,9 +83,9 @@ public class BeanMethodPolymorphismTests { ctx.registerBeanDefinition("config", new RootBeanDefinition(NarrowedOverridingConfig.class.getName())); ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); - assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")); - assertEquals("overridden", ctx.getBean("testBean", TestBean.class).toString()); - assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")).isFalse(); + assertThat(ctx.getBean("testBean", TestBean.class).toString()).isEqualTo("overridden"); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("testBean")).isTrue(); } @Test @@ -116,9 +113,9 @@ public class BeanMethodPolymorphismTests { ctx.register(ConfigWithOverloadingAndAdditionalMetadata.class); ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); - assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("aString")).isFalse(); assertThat(ctx.getBean(String.class)).isEqualTo("regular"); - assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("aString")).isTrue(); } @Test @@ -128,9 +125,9 @@ public class BeanMethodPolymorphismTests { ctx.getDefaultListableBeanFactory().registerSingleton("anInt", 5); ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); - assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("aString")).isFalse(); assertThat(ctx.getBean(String.class)).isEqualTo("overloaded5"); - assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("aString")).isTrue(); } @Test @@ -139,9 +136,9 @@ public class BeanMethodPolymorphismTests { ctx.register(SubConfig.class); ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); - assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("aString")).isFalse(); assertThat(ctx.getBean(String.class)).isEqualTo("overloaded5"); - assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("aString")).isTrue(); } // SPR-11025 @@ -151,9 +148,9 @@ public class BeanMethodPolymorphismTests { ctx.register(SubConfigWithList.class); ctx.setAllowBeanDefinitionOverriding(false); ctx.refresh(); - assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("aString")).isFalse(); assertThat(ctx.getBean(String.class)).isEqualTo("overloaded5"); - assertTrue(ctx.getDefaultListableBeanFactory().containsSingleton("aString")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("aString")).isTrue(); } /** diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java index 02cac0bc3e4..529ce25f8ff 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java @@ -42,10 +42,6 @@ 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Mark Fisher @@ -62,25 +58,25 @@ public class ClassPathBeanDefinitionScannerTests { GenericApplicationContext context = new GenericApplicationContext(); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(12, beanCount); - assertTrue(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); - assertTrue(context.containsBean("thoreau")); - assertTrue(context.containsBean(AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)); + assertThat(beanCount).isEqualTo(12); + assertThat(context.containsBean("serviceInvocationCounter")).isTrue(); + assertThat(context.containsBean("fooServiceImpl")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); + assertThat(context.containsBean("thoreau")).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)).isTrue(); context.refresh(); FooServiceImpl fooService = context.getBean("fooServiceImpl", FooServiceImpl.class); - assertTrue(context.getDefaultListableBeanFactory().containsSingleton("myNamedComponent")); - assertEquals("bar", fooService.foo(123)); - assertEquals("bar", fooService.lookupFoo(123)); - assertTrue(context.isPrototype("thoreau")); + assertThat(context.getDefaultListableBeanFactory().containsSingleton("myNamedComponent")).isTrue(); + assertThat(fooService.foo(123)).isEqualTo("bar"); + assertThat(fooService.lookupFoo(123)).isEqualTo("bar"); + assertThat(context.isPrototype("thoreau")).isTrue(); } @Test @@ -89,20 +85,20 @@ public class ClassPathBeanDefinitionScannerTests { ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context); scanner.scan(BASE_PACKAGE); scanner.scan("org.springframework.context.annotation5"); - assertTrue(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); - assertTrue(context.containsBean("otherFooDao")); + assertThat(context.containsBean("serviceInvocationCounter")).isTrue(); + assertThat(context.containsBean("fooServiceImpl")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); + assertThat(context.containsBean("otherFooDao")).isTrue(); context.refresh(); - assertFalse(context.getBeanFactory().containsSingleton("otherFooDao")); - assertFalse(context.getBeanFactory().containsSingleton("fooServiceImpl")); + assertThat(context.getBeanFactory().containsSingleton("otherFooDao")).isFalse(); + assertThat(context.getBeanFactory().containsSingleton("fooServiceImpl")).isFalse(); FooServiceImpl fooService = context.getBean("fooServiceImpl", FooServiceImpl.class); - assertTrue(context.getBeanFactory().containsSingleton("otherFooDao")); - assertEquals("other", fooService.foo(123)); - assertEquals("other", fooService.lookupFoo(123)); + assertThat(context.getBeanFactory().containsSingleton("otherFooDao")).isTrue(); + assertThat(fooService.foo(123)).isEqualTo("other"); + assertThat(fooService.lookupFoo(123)).isEqualTo("other"); } @Test @@ -110,15 +106,15 @@ public class ClassPathBeanDefinitionScannerTests { GenericApplicationContext context = new GenericApplicationContext(); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(12, beanCount); + assertThat(beanCount).isEqualTo(12); scanner.scan(BASE_PACKAGE); - assertTrue(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); - assertTrue(context.containsBean("thoreau")); + assertThat(context.containsBean("serviceInvocationCounter")).isTrue(); + assertThat(context.containsBean("fooServiceImpl")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); + assertThat(context.containsBean("thoreau")).isTrue(); } @Test @@ -127,13 +123,13 @@ public class ClassPathBeanDefinitionScannerTests { ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context); scanner.setIncludeAnnotationConfig(false); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(7, beanCount); + assertThat(beanCount).isEqualTo(7); - assertTrue(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); + assertThat(context.containsBean("serviceInvocationCounter")).isTrue(); + assertThat(context.containsBean("fooServiceImpl")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); } @Test @@ -167,13 +163,13 @@ public class ClassPathBeanDefinitionScannerTests { scanner.setIncludeAnnotationConfig(false); int scannedBeanCount = scanner.scan(BASE_PACKAGE); - assertEquals(6, scannedBeanCount); - assertEquals(initialBeanCount + scannedBeanCount, context.getBeanDefinitionCount()); - assertTrue(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); + assertThat(scannedBeanCount).isEqualTo(6); + assertThat(context.getBeanDefinitionCount()).isEqualTo((initialBeanCount + scannedBeanCount)); + assertThat(context.containsBean("serviceInvocationCounter")).isTrue(); + assertThat(context.containsBean("fooServiceImpl")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); } @Test @@ -187,13 +183,13 @@ public class ClassPathBeanDefinitionScannerTests { scanner.setIncludeAnnotationConfig(false); int scannedBeanCount = scanner.scan(BASE_PACKAGE); - assertEquals(6, scannedBeanCount); - assertEquals(initialBeanCount + scannedBeanCount, context.getBeanDefinitionCount()); - assertTrue(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); + assertThat(scannedBeanCount).isEqualTo(6); + assertThat(context.getBeanDefinitionCount()).isEqualTo((initialBeanCount + scannedBeanCount)); + assertThat(context.containsBean("serviceInvocationCounter")).isTrue(); + assertThat(context.containsBean("fooServiceImpl")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); } @Test @@ -226,12 +222,12 @@ public class ClassPathBeanDefinitionScannerTests { scanner.addIncludeFilter(new AnnotationTypeFilter(CustomComponent.class)); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(6, beanCount); - assertTrue(context.containsBean("messageBean")); - assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)); + assertThat(beanCount).isEqualTo(6); + assertThat(context.containsBean("messageBean")).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)).isTrue(); } @Test @@ -241,17 +237,17 @@ public class ClassPathBeanDefinitionScannerTests { scanner.addIncludeFilter(new AnnotationTypeFilter(CustomComponent.class)); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(6, beanCount); - assertTrue(context.containsBean("messageBean")); - assertFalse(context.containsBean("serviceInvocationCounter")); - assertFalse(context.containsBean("fooServiceImpl")); - assertFalse(context.containsBean("stubFooDao")); - assertFalse(context.containsBean("myNamedComponent")); - assertFalse(context.containsBean("myNamedDao")); - assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)); + assertThat(beanCount).isEqualTo(6); + assertThat(context.containsBean("messageBean")).isTrue(); + assertThat(context.containsBean("serviceInvocationCounter")).isFalse(); + assertThat(context.containsBean("fooServiceImpl")).isFalse(); + assertThat(context.containsBean("stubFooDao")).isFalse(); + assertThat(context.containsBean("myNamedComponent")).isFalse(); + assertThat(context.containsBean("myNamedDao")).isFalse(); + assertThat(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)).isTrue(); } @Test @@ -261,17 +257,17 @@ public class ClassPathBeanDefinitionScannerTests { scanner.addIncludeFilter(new AnnotationTypeFilter(CustomComponent.class)); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(13, beanCount); - assertTrue(context.containsBean("messageBean")); - assertTrue(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); - assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)); + assertThat(beanCount).isEqualTo(13); + assertThat(context.containsBean("messageBean")).isTrue(); + assertThat(context.containsBean("serviceInvocationCounter")).isTrue(); + assertThat(context.containsBean("fooServiceImpl")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)).isTrue(); } @Test @@ -281,15 +277,15 @@ public class ClassPathBeanDefinitionScannerTests { scanner.addExcludeFilter(new AnnotationTypeFilter(Aspect.class)); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(11, beanCount); - assertFalse(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); - assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)); + assertThat(beanCount).isEqualTo(11); + assertThat(context.containsBean("serviceInvocationCounter")).isFalse(); + assertThat(context.containsBean("fooServiceImpl")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)).isTrue(); } @Test @@ -299,16 +295,16 @@ public class ClassPathBeanDefinitionScannerTests { scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class)); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(11, beanCount); - assertFalse(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); - assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)); + assertThat(beanCount).isEqualTo(11); + assertThat(context.containsBean("fooServiceImpl")).isFalse(); + assertThat(context.containsBean("serviceInvocationCounter")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)).isTrue(); } @Test @@ -319,14 +315,14 @@ public class ClassPathBeanDefinitionScannerTests { scanner.addExcludeFilter(new AssignableTypeFilter(FooService.class)); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(6, beanCount); - assertFalse(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); - assertFalse(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertFalse(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); + assertThat(beanCount).isEqualTo(6); + assertThat(context.containsBean("fooServiceImpl")).isFalse(); + assertThat(context.containsBean("serviceInvocationCounter")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)).isFalse(); + assertThat(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)).isFalse(); } @Test @@ -337,16 +333,16 @@ public class ClassPathBeanDefinitionScannerTests { scanner.addExcludeFilter(new AnnotationTypeFilter(Aspect.class)); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(10, beanCount); - assertFalse(context.containsBean("fooServiceImpl")); - assertFalse(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); - assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)); + assertThat(beanCount).isEqualTo(10); + assertThat(context.containsBean("fooServiceImpl")).isFalse(); + assertThat(context.containsBean("serviceInvocationCounter")).isFalse(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)).isTrue(); } @Test @@ -356,17 +352,17 @@ public class ClassPathBeanDefinitionScannerTests { scanner.setBeanNameGenerator(new TestBeanNameGenerator()); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(12, beanCount); - assertFalse(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("fooService")); - assertTrue(context.containsBean("serviceInvocationCounter")); - assertTrue(context.containsBean("stubFooDao")); - assertTrue(context.containsBean("myNamedComponent")); - assertTrue(context.containsBean("myNamedDao")); - assertTrue(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)); - assertTrue(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)); + assertThat(beanCount).isEqualTo(12); + assertThat(context.containsBean("fooServiceImpl")).isFalse(); + assertThat(context.containsBean("fooService")).isTrue(); + assertThat(context.containsBean("serviceInvocationCounter")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("myNamedComponent")).isTrue(); + assertThat(context.containsBean("myNamedDao")).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_PROCESSOR_BEAN_NAME)).isTrue(); + assertThat(context.containsBean(AnnotationConfigUtils.EVENT_LISTENER_FACTORY_BEAN_NAME)).isTrue(); } @Test @@ -376,7 +372,7 @@ public class ClassPathBeanDefinitionScannerTests { GenericApplicationContext multiPackageContext = new GenericApplicationContext(); ClassPathBeanDefinitionScanner multiPackageScanner = new ClassPathBeanDefinitionScanner(multiPackageContext); int singlePackageBeanCount = singlePackageScanner.scan(BASE_PACKAGE); - assertEquals(12, singlePackageBeanCount); + assertThat(singlePackageBeanCount).isEqualTo(12); multiPackageScanner.scan(BASE_PACKAGE, "org.springframework.dao.annotation"); // assertTrue(multiPackageBeanCount > singlePackageBeanCount); } @@ -387,10 +383,10 @@ public class ClassPathBeanDefinitionScannerTests { ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context); int initialBeanCount = context.getBeanDefinitionCount(); int scannedBeanCount = scanner.scan(BASE_PACKAGE); - assertEquals(12, scannedBeanCount); - assertEquals(scannedBeanCount, context.getBeanDefinitionCount() - initialBeanCount); + assertThat(scannedBeanCount).isEqualTo(12); + assertThat((context.getBeanDefinitionCount() - initialBeanCount)).isEqualTo(scannedBeanCount); int addedBeanCount = scanner.scan("org.springframework.aop.aspectj.annotation"); - assertEquals(initialBeanCount + scannedBeanCount + addedBeanCount, context.getBeanDefinitionCount()); + assertThat(context.getBeanDefinitionCount()).isEqualTo((initialBeanCount + scannedBeanCount + addedBeanCount)); } @Test @@ -400,27 +396,27 @@ public class ClassPathBeanDefinitionScannerTests { ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context); scanner.setBeanNameGenerator(new TestBeanNameGenerator()); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(12, beanCount); + assertThat(beanCount).isEqualTo(12); context.refresh(); FooServiceImpl fooService = context.getBean("fooService", FooServiceImpl.class); StaticListableBeanFactory myBf = (StaticListableBeanFactory) context.getBean("myBf"); MessageSource ms = (MessageSource) context.getBean("messageSource"); - assertTrue(fooService.isInitCalled()); - assertEquals("bar", fooService.foo(123)); - assertEquals("bar", fooService.lookupFoo(123)); - assertSame(context.getDefaultListableBeanFactory(), fooService.beanFactory); - assertEquals(2, fooService.listableBeanFactory.size()); - assertSame(context.getDefaultListableBeanFactory(), fooService.listableBeanFactory.get(0)); - assertSame(myBf, fooService.listableBeanFactory.get(1)); - assertSame(context, fooService.resourceLoader); - assertSame(context, fooService.resourcePatternResolver); - assertSame(context, fooService.eventPublisher); - assertSame(ms, fooService.messageSource); - assertSame(context, fooService.context); - assertEquals(1, fooService.configurableContext.length); - assertSame(context, fooService.configurableContext[0]); - assertSame(context, fooService.genericContext); + assertThat(fooService.isInitCalled()).isTrue(); + assertThat(fooService.foo(123)).isEqualTo("bar"); + assertThat(fooService.lookupFoo(123)).isEqualTo("bar"); + assertThat(fooService.beanFactory).isSameAs(context.getDefaultListableBeanFactory()); + assertThat(fooService.listableBeanFactory.size()).isEqualTo(2); + assertThat(fooService.listableBeanFactory.get(0)).isSameAs(context.getDefaultListableBeanFactory()); + assertThat(fooService.listableBeanFactory.get(1)).isSameAs(myBf); + assertThat(fooService.resourceLoader).isSameAs(context); + assertThat(fooService.resourcePatternResolver).isSameAs(context); + assertThat(fooService.eventPublisher).isSameAs(context); + assertThat(fooService.messageSource).isSameAs(ms); + assertThat(fooService.context).isSameAs(context); + assertThat(fooService.configurableContext.length).isEqualTo(1); + assertThat(fooService.configurableContext[0]).isSameAs(context); + assertThat(fooService.genericContext).isSameAs(context); } @Test @@ -430,14 +426,14 @@ public class ClassPathBeanDefinitionScannerTests { scanner.setIncludeAnnotationConfig(false); scanner.setBeanNameGenerator(new TestBeanNameGenerator()); int beanCount = scanner.scan(BASE_PACKAGE); - assertEquals(7, beanCount); + assertThat(beanCount).isEqualTo(7); context.refresh(); try { context.getBean("fooService"); } catch (BeanCreationException expected) { - assertTrue(expected.contains(BeanInstantiationException.class)); + assertThat(expected.contains(BeanInstantiationException.class)).isTrue(); // @Lookup method not substituted } } @@ -453,8 +449,8 @@ public class ClassPathBeanDefinitionScannerTests { context.refresh(); FooServiceImpl fooService = (FooServiceImpl) context.getBean("fooService"); - assertEquals("bar", fooService.foo(123)); - assertEquals("bar", fooService.lookupFoo(123)); + assertThat(fooService.foo(123)).isEqualTo("bar"); + assertThat(fooService.lookupFoo(123)).isEqualTo("bar"); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathFactoryBeanDefinitionScannerTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathFactoryBeanDefinitionScannerTests.java index 98fd8c7e48f..c474b500be9 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathFactoryBeanDefinitionScannerTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathFactoryBeanDefinitionScannerTests.java @@ -31,11 +31,7 @@ import org.springframework.tests.context.SimpleMapScope; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ClassUtils; -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; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Pollack @@ -58,37 +54,38 @@ public class ClassPathFactoryBeanDefinitionScannerTests { context.refresh(); FactoryMethodComponent fmc = context.getBean("factoryMethodComponent", FactoryMethodComponent.class); - assertFalse(fmc.getClass().getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)); + assertThat(fmc.getClass().getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)).isFalse(); TestBean tb = (TestBean) context.getBean("publicInstance"); //2 - assertEquals("publicInstance", tb.getName()); + assertThat(tb.getName()).isEqualTo("publicInstance"); TestBean tb2 = (TestBean) context.getBean("publicInstance"); //2 - assertEquals("publicInstance", tb2.getName()); - assertSame(tb2, tb); + assertThat(tb2.getName()).isEqualTo("publicInstance"); + assertThat(tb).isSameAs(tb2); tb = (TestBean) context.getBean("protectedInstance"); //3 - assertEquals("protectedInstance", tb.getName()); - assertSame(tb, context.getBean("protectedInstance")); - assertEquals("0", tb.getCountry()); + assertThat(tb.getName()).isEqualTo("protectedInstance"); + assertThat(context.getBean("protectedInstance")).isSameAs(tb); + assertThat(tb.getCountry()).isEqualTo("0"); tb2 = context.getBean("protectedInstance", TestBean.class); //3 - assertEquals("protectedInstance", tb2.getName()); - assertSame(tb2, tb); + assertThat(tb2.getName()).isEqualTo("protectedInstance"); + assertThat(tb).isSameAs(tb2); tb = context.getBean("privateInstance", TestBean.class); //4 - assertEquals("privateInstance", tb.getName()); - assertEquals(1, tb.getAge()); + assertThat(tb.getName()).isEqualTo("privateInstance"); + assertThat(tb.getAge()).isEqualTo(1); tb2 = context.getBean("privateInstance", TestBean.class); //4 - assertEquals(2, tb2.getAge()); - assertNotSame(tb2, tb); + assertThat(tb2.getAge()).isEqualTo(2); + assertThat(tb).isNotSameAs(tb2); Object bean = context.getBean("requestScopedInstance"); //5 - assertTrue(AopUtils.isCglibProxy(bean)); - assertTrue(bean instanceof ScopedObject); + assertThat(AopUtils.isCglibProxy(bean)).isTrue(); + boolean condition = bean instanceof ScopedObject; + assertThat(condition).isTrue(); QualifiedClientBean clientBean = context.getBean("clientBean", QualifiedClientBean.class); - assertSame(context.getBean("publicInstance"), clientBean.testBean); - assertSame(context.getBean("dependencyBean"), clientBean.dependencyBean); - assertSame(context, clientBean.applicationContext); + assertThat(clientBean.testBean).isSameAs(context.getBean("publicInstance")); + assertThat(clientBean.dependencyBean).isSameAs(context.getBean("dependencyBean")); + assertThat(clientBean.applicationContext).isSameAs(context); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProviderTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProviderTests.java index e23f392da31..a9d7eab18c3 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProviderTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProviderTests.java @@ -56,9 +56,6 @@ import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Mark Fisher @@ -95,14 +92,14 @@ public class ClassPathScanningCandidateComponentProviderTests { private void testDefault(ClassPathScanningCandidateComponentProvider provider, Class expectedBeanDefinitionType) { Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertTrue(containsBeanClass(candidates, DefaultNamedComponent.class)); - assertTrue(containsBeanClass(candidates, NamedComponent.class)); - assertTrue(containsBeanClass(candidates, FooServiceImpl.class)); - assertTrue(containsBeanClass(candidates, StubFooDao.class)); - assertTrue(containsBeanClass(candidates, NamedStubDao.class)); - assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class)); - assertTrue(containsBeanClass(candidates, BarComponent.class)); - assertEquals(7, candidates.size()); + assertThat(containsBeanClass(candidates, DefaultNamedComponent.class)).isTrue(); + assertThat(containsBeanClass(candidates, NamedComponent.class)).isTrue(); + assertThat(containsBeanClass(candidates, FooServiceImpl.class)).isTrue(); + assertThat(containsBeanClass(candidates, StubFooDao.class)).isTrue(); + assertThat(containsBeanClass(candidates, NamedStubDao.class)).isTrue(); + assertThat(containsBeanClass(candidates, ServiceInvocationCounter.class)).isTrue(); + assertThat(containsBeanClass(candidates, BarComponent.class)).isTrue(); + assertThat(candidates.size()).isEqualTo(7); assertBeanDefinitionType(candidates, expectedBeanDefinitionType); } @@ -124,8 +121,8 @@ public class ClassPathScanningCandidateComponentProviderTests { private void testAntStyle(ClassPathScanningCandidateComponentProvider provider, Class expectedBeanDefinitionType) { Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE + ".**.sub"); - assertTrue(containsBeanClass(candidates, BarComponent.class)); - assertEquals(1, candidates.size()); + assertThat(containsBeanClass(candidates, BarComponent.class)).isTrue(); + assertThat(candidates.size()).isEqualTo(1); assertBeanDefinitionType(candidates, expectedBeanDefinitionType); } @@ -135,7 +132,7 @@ public class ClassPathScanningCandidateComponentProviderTests { provider.setResourceLoader(new DefaultResourceLoader( CandidateComponentsTestClassLoader.disableIndex(getClass().getClassLoader()))); Set candidates = provider.findCandidateComponents("bogus"); - assertEquals(0, candidates.size()); + assertThat(candidates.size()).isEqualTo(0); } @Test @@ -143,7 +140,7 @@ public class ClassPathScanningCandidateComponentProviderTests { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true); provider.setResourceLoader(new DefaultResourceLoader(TEST_BASE_CLASSLOADER)); Set candidates = provider.findCandidateComponents("bogus"); - assertEquals(0, candidates.size()); + assertThat(candidates.size()).isEqualTo(0); } @Test @@ -197,10 +194,10 @@ public class ClassPathScanningCandidateComponentProviderTests { provider.addIncludeFilter(new AssignableTypeFilter(FooService.class)); Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); // Interfaces/Abstract class are filtered out automatically. - assertTrue(containsBeanClass(candidates, AutowiredQualifierFooService.class)); - assertTrue(containsBeanClass(candidates, FooServiceImpl.class)); - assertTrue(containsBeanClass(candidates, ScopedProxyTestBean.class)); - assertEquals(3, candidates.size()); + assertThat(containsBeanClass(candidates, AutowiredQualifierFooService.class)).isTrue(); + assertThat(containsBeanClass(candidates, FooServiceImpl.class)).isTrue(); + assertThat(containsBeanClass(candidates, ScopedProxyTestBean.class)).isTrue(); + assertThat(candidates.size()).isEqualTo(3); assertBeanDefinitionType(candidates, expectedBeanDefinitionType); } @@ -225,10 +222,10 @@ public class ClassPathScanningCandidateComponentProviderTests { provider.addExcludeFilter(new AnnotationTypeFilter(Service.class)); provider.addExcludeFilter(new AnnotationTypeFilter(Repository.class)); Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertTrue(containsBeanClass(candidates, NamedComponent.class)); - assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class)); - assertTrue(containsBeanClass(candidates, BarComponent.class)); - assertEquals(3, candidates.size()); + assertThat(containsBeanClass(candidates, NamedComponent.class)).isTrue(); + assertThat(containsBeanClass(candidates, ServiceInvocationCounter.class)).isTrue(); + assertThat(containsBeanClass(candidates, BarComponent.class)).isTrue(); + assertThat(candidates.size()).isEqualTo(3); assertBeanDefinitionType(candidates, expectedBeanDefinitionType); } @@ -240,8 +237,8 @@ public class ClassPathScanningCandidateComponentProviderTests { // the index to find candidates provider.addIncludeFilter(new AnnotationTypeFilter(CustomStereotype.class)); Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertTrue(containsBeanClass(candidates, DefaultNamedComponent.class)); - assertEquals(1, candidates.size()); + assertThat(containsBeanClass(candidates, DefaultNamedComponent.class)).isTrue(); + assertThat(candidates.size()).isEqualTo(1); assertBeanDefinitionType(candidates, ScannedGenericBeanDefinition.class); } @@ -251,8 +248,8 @@ public class ClassPathScanningCandidateComponentProviderTests { provider.setResourceLoader(new DefaultResourceLoader(TEST_BASE_CLASSLOADER)); provider.addIncludeFilter(new AssignableTypeFilter(FooDao.class)); Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertTrue(containsBeanClass(candidates, StubFooDao.class)); - assertEquals(1, candidates.size()); + assertThat(containsBeanClass(candidates, StubFooDao.class)).isTrue(); + assertThat(candidates.size()).isEqualTo(1); assertBeanDefinitionType(candidates, ScannedGenericBeanDefinition.class); } @@ -276,11 +273,11 @@ public class ClassPathScanningCandidateComponentProviderTests { private void testExclude(ClassPathScanningCandidateComponentProvider provider, Class expectedBeanDefinitionType) { Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertTrue(containsBeanClass(candidates, FooServiceImpl.class)); - assertTrue(containsBeanClass(candidates, StubFooDao.class)); - assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class)); - assertTrue(containsBeanClass(candidates, BarComponent.class)); - assertEquals(4, candidates.size()); + assertThat(containsBeanClass(candidates, FooServiceImpl.class)).isTrue(); + assertThat(containsBeanClass(candidates, StubFooDao.class)).isTrue(); + assertThat(containsBeanClass(candidates, ServiceInvocationCounter.class)).isTrue(); + assertThat(containsBeanClass(candidates, BarComponent.class)).isTrue(); + assertThat(candidates.size()).isEqualTo(4); assertBeanDefinitionType(candidates, expectedBeanDefinitionType); } @@ -288,7 +285,7 @@ public class ClassPathScanningCandidateComponentProviderTests { public void testWithNoFilters() { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertEquals(0, candidates.size()); + assertThat(candidates.size()).isEqualTo(0); } @Test @@ -299,13 +296,13 @@ public class ClassPathScanningCandidateComponentProviderTests { provider.addExcludeFilter(new AnnotationTypeFilter(Service.class)); provider.addExcludeFilter(new AnnotationTypeFilter(Controller.class)); Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertEquals(3, candidates.size()); - assertTrue(containsBeanClass(candidates, NamedComponent.class)); - assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class)); - assertTrue(containsBeanClass(candidates, BarComponent.class)); - assertFalse(containsBeanClass(candidates, FooServiceImpl.class)); - assertFalse(containsBeanClass(candidates, StubFooDao.class)); - assertFalse(containsBeanClass(candidates, NamedStubDao.class)); + assertThat(candidates.size()).isEqualTo(3); + assertThat(containsBeanClass(candidates, NamedComponent.class)).isTrue(); + assertThat(containsBeanClass(candidates, ServiceInvocationCounter.class)).isTrue(); + assertThat(containsBeanClass(candidates, BarComponent.class)).isTrue(); + assertThat(containsBeanClass(candidates, FooServiceImpl.class)).isFalse(); + assertThat(containsBeanClass(candidates, StubFooDao.class)).isFalse(); + assertThat(containsBeanClass(candidates, NamedStubDao.class)).isFalse(); } @Test @@ -313,8 +310,8 @@ public class ClassPathScanningCandidateComponentProviderTests { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AnnotationTypeFilter(Aspect.class)); Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertEquals(1, candidates.size()); - assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class)); + assertThat(candidates.size()).isEqualTo(1); + assertThat(containsBeanClass(candidates, ServiceInvocationCounter.class)).isTrue(); } @Test @@ -322,8 +319,8 @@ public class ClassPathScanningCandidateComponentProviderTests { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AssignableTypeFilter(FooDao.class)); Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertEquals(1, candidates.size()); - assertTrue(containsBeanClass(candidates, StubFooDao.class)); + assertThat(candidates.size()).isEqualTo(1); + assertThat(containsBeanClass(candidates, StubFooDao.class)).isTrue(); } @Test @@ -331,8 +328,8 @@ public class ClassPathScanningCandidateComponentProviderTests { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AssignableTypeFilter(MessageBean.class)); Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertEquals(1, candidates.size()); - assertTrue(containsBeanClass(candidates, MessageBean.class)); + assertThat(candidates.size()).isEqualTo(1); + assertThat(containsBeanClass(candidates, MessageBean.class)).isTrue(); } @Test @@ -341,11 +338,11 @@ public class ClassPathScanningCandidateComponentProviderTests { provider.addIncludeFilter(new AnnotationTypeFilter(Component.class)); provider.addIncludeFilter(new AssignableTypeFilter(FooServiceImpl.class)); Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertEquals(7, candidates.size()); - assertTrue(containsBeanClass(candidates, NamedComponent.class)); - assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class)); - assertTrue(containsBeanClass(candidates, FooServiceImpl.class)); - assertTrue(containsBeanClass(candidates, BarComponent.class)); + assertThat(candidates.size()).isEqualTo(7); + assertThat(containsBeanClass(candidates, NamedComponent.class)).isTrue(); + assertThat(containsBeanClass(candidates, ServiceInvocationCounter.class)).isTrue(); + assertThat(containsBeanClass(candidates, FooServiceImpl.class)).isTrue(); + assertThat(containsBeanClass(candidates, BarComponent.class)).isTrue(); } @Test @@ -355,11 +352,11 @@ public class ClassPathScanningCandidateComponentProviderTests { provider.addIncludeFilter(new AssignableTypeFilter(FooServiceImpl.class)); provider.addExcludeFilter(new AssignableTypeFilter(FooService.class)); Set candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE); - assertEquals(6, candidates.size()); - assertTrue(containsBeanClass(candidates, NamedComponent.class)); - assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class)); - assertTrue(containsBeanClass(candidates, BarComponent.class)); - assertFalse(containsBeanClass(candidates, FooServiceImpl.class)); + assertThat(candidates.size()).isEqualTo(6); + assertThat(containsBeanClass(candidates, NamedComponent.class)).isTrue(); + assertThat(containsBeanClass(candidates, ServiceInvocationCounter.class)).isTrue(); + assertThat(containsBeanClass(candidates, BarComponent.class)).isTrue(); + assertThat(containsBeanClass(candidates, FooServiceImpl.class)).isFalse(); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java index 841437e34ae..3e44555d288 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java @@ -44,12 +44,7 @@ import org.springframework.tests.sample.beans.NestedTestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; -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.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -64,9 +59,9 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(AnnotatedInitDestroyBean.class)); AnnotatedInitDestroyBean bean = (AnnotatedInitDestroyBean) bf.getBean("annotatedBean"); - assertTrue(bean.initCalled); + assertThat(bean.initCalled).isTrue(); bf.destroySingletons(); - assertTrue(bean.destroyCalled); + assertThat(bean.destroyCalled).isTrue(); } @Test @@ -77,9 +72,9 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(AnnotatedInitDestroyBean.class)); AnnotatedInitDestroyBean bean = (AnnotatedInitDestroyBean) bf.getBean("annotatedBean"); - assertTrue(bean.initCalled); + assertThat(bean.initCalled).isTrue(); bf.destroySingletons(); - assertTrue(bean.destroyCalled); + assertThat(bean.destroyCalled).isTrue(); } @Test @@ -91,9 +86,9 @@ public class CommonAnnotationBeanPostProcessorTests { ctx.refresh(); AnnotatedInitDestroyBean bean = (AnnotatedInitDestroyBean) ctx.getBean("annotatedBean"); - assertTrue(bean.initCalled); + assertThat(bean.initCalled).isTrue(); ctx.close(); - assertTrue(bean.destroyCalled); + assertThat(bean.destroyCalled).isTrue(); } @Test @@ -106,9 +101,9 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(AnnotatedInitDestroyBean.class)); AnnotatedInitDestroyBean bean = (AnnotatedInitDestroyBean) bf.getBean("annotatedBean"); - assertTrue(bean.initCalled); + assertThat(bean.initCalled).isTrue(); bf.destroySingletons(); - assertTrue(bean.destroyCalled); + assertThat(bean.destroyCalled).isTrue(); } @Test @@ -119,7 +114,7 @@ public class CommonAnnotationBeanPostProcessorTests { rbd.setFactoryMethodName("create"); bf.registerBeanDefinition("bean", rbd); - assertEquals("null", bf.getBean("bean").toString()); + assertThat(bf.getBean("bean").toString()).isEqualTo("null"); bf.destroySingletons(); } @@ -131,7 +126,7 @@ public class CommonAnnotationBeanPostProcessorTests { AnnotatedInitDestroyBean bean = new AnnotatedInitDestroyBean(); bpp2.postProcessBeforeDestruction(bean, "annotatedBean"); - assertTrue(bean.destroyCalled); + assertThat(bean.destroyCalled).isTrue(); } @Test @@ -144,7 +139,7 @@ public class CommonAnnotationBeanPostProcessorTests { AnnotatedInitDestroyBean bean = new AnnotatedInitDestroyBean(); bpp2.postProcessBeforeDestruction(bean, "annotatedBean"); - assertTrue(bean.destroyCalled); + assertThat(bean.destroyCalled).isTrue(); } @Test @@ -160,15 +155,15 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean2", tb2); ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.initCalled); - assertTrue(bean.init2Called); - assertTrue(bean.init3Called); - assertSame(tb, bean.getTestBean()); - assertSame(tb2, bean.getTestBean2()); + assertThat(bean.initCalled).isTrue(); + assertThat(bean.init2Called).isTrue(); + assertThat(bean.init3Called).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb2); bf.destroySingletons(); - assertTrue(bean.destroyCalled); - assertTrue(bean.destroy2Called); - assertTrue(bean.destroy3Called); + assertThat(bean.destroyCalled).isTrue(); + assertThat(bean.destroy2Called).isTrue(); + assertThat(bean.destroy3Called).isTrue(); } @Test @@ -188,24 +183,24 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean2", tbd2); ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.initCalled); - assertTrue(bean.init2Called); - assertTrue(bean.init3Called); + assertThat(bean.initCalled).isTrue(); + assertThat(bean.init2Called).isTrue(); + assertThat(bean.init3Called).isTrue(); TestBean tb = bean.getTestBean(); TestBean tb2 = bean.getTestBean2(); - assertNotNull(tb); - assertNotNull(tb2); + assertThat(tb).isNotNull(); + assertThat(tb2).isNotNull(); ResourceInjectionBean anotherBean = (ResourceInjectionBean) bf.getBean("annotatedBean"); - assertNotSame(anotherBean, bean); - assertNotSame(anotherBean.getTestBean(), tb); - assertNotSame(anotherBean.getTestBean2(), tb2); + assertThat(bean).isNotSameAs(anotherBean); + assertThat(tb).isNotSameAs(anotherBean.getTestBean()); + assertThat(tb2).isNotSameAs(anotherBean.getTestBean2()); bf.destroyBean("annotatedBean", bean); - assertTrue(bean.destroyCalled); - assertTrue(bean.destroy2Called); - assertTrue(bean.destroy3Called); + assertThat(bean.destroyCalled).isTrue(); + assertThat(bean.destroy2Called).isTrue(); + assertThat(bean.destroy3Called).isTrue(); } @Test @@ -237,15 +232,15 @@ public class CommonAnnotationBeanPostProcessorTests { ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean"); INestedTestBean tb = bean.getTestBean6(); - assertNotNull(tb); + assertThat(tb).isNotNull(); ExtendedResourceInjectionBean anotherBean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertNotSame(anotherBean, bean); - assertNotSame(anotherBean.getTestBean6(), tb); + assertThat(bean).isNotSameAs(anotherBean); + assertThat(tb).isNotSameAs(anotherBean.getTestBean6()); String[] depBeans = bf.getDependenciesForBean("annotatedBean"); - assertEquals(1, depBeans.length); - assertEquals("testBean4", depBeans[0]); + assertThat(depBeans.length).isEqualTo(1); + assertThat(depBeans[0]).isEqualTo("testBean4"); } @Test @@ -261,11 +256,11 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean7", tb7); DefaultMethodResourceInjectionBean bean = (DefaultMethodResourceInjectionBean) bf.getBean("annotatedBean"); - assertSame(tb2, bean.getTestBean2()); - assertSame(2, bean.counter); + assertThat(bean.getTestBean2()).isSameAs(tb2); + assertThat(bean.counter).isSameAs(2); bf.destroySingletons(); - assertSame(3, bean.counter); + assertThat(bean.counter).isSameAs(3); } @Test @@ -284,13 +279,13 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerSingleton("testBean2", tb2); ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.initCalled); - assertTrue(bean.init2Called); - assertSame(tb, bean.getTestBean()); - assertSame(tb2, bean.getTestBean2()); + assertThat(bean.initCalled).isTrue(); + assertThat(bean.init2Called).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb2); bf.destroySingletons(); - assertTrue(bean.destroyCalled); - assertTrue(bean.destroy2Called); + assertThat(bean.destroyCalled).isTrue(); + assertThat(bean.destroy2Called).isTrue(); } @Test @@ -309,13 +304,13 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ResourceInjectionBean.class)); ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.initCalled); - assertTrue(bean.init2Called); - assertSame(tb, bean.getTestBean()); - assertSame(tb2, bean.getTestBean2()); + assertThat(bean.initCalled).isTrue(); + assertThat(bean.init2Called).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb2); bf.destroySingletons(); - assertTrue(bean.destroyCalled); - assertTrue(bean.destroy2Called); + assertThat(bean.destroyCalled).isTrue(); + assertThat(bean.destroy2Called).isTrue(); } @Test @@ -349,25 +344,25 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerAlias("xy", "testBean9"); ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.initCalled); - assertTrue(bean.init2Called); - assertSame(tb, bean.getTestBean()); - assertSame(tb2, bean.getTestBean2()); - assertSame(tb4, bean.getTestBean3()); - assertSame(tb3, bean.getTestBean4()); - assertSame(tb6, bean.testBean5); - assertSame(tb6, bean.testBean6); - assertSame(bf, bean.beanFactory); + assertThat(bean.initCalled).isTrue(); + assertThat(bean.init2Called).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb2); + assertThat(bean.getTestBean3()).isSameAs(tb4); + assertThat(bean.getTestBean4()).isSameAs(tb3); + assertThat(bean.testBean5).isSameAs(tb6); + assertThat(bean.testBean6).isSameAs(tb6); + assertThat(bean.beanFactory).isSameAs(bf); NamedResourceInjectionBean bean2 = (NamedResourceInjectionBean) bf.getBean("annotatedBean2"); - assertSame(tb6, bean2.testBean); + assertThat(bean2.testBean).isSameAs(tb6); ConvertedResourceInjectionBean bean3 = (ConvertedResourceInjectionBean) bf.getBean("annotatedBean3"); - assertSame(5, bean3.value); + assertThat(bean3.value).isSameAs(5); bf.destroySingletons(); - assertTrue(bean.destroyCalled); - assertTrue(bean.destroy2Called); + assertThat(bean.destroyCalled).isTrue(); + assertThat(bean.destroy2Called).isTrue(); } @Test @@ -401,28 +396,29 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerSingleton("xy", tb6); ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.initCalled); - assertTrue(bean.init2Called); - assertSame(tb, bean.getTestBean()); - assertSame(tb5, bean.getTestBean2()); - assertSame(tb4, bean.getTestBean3()); - assertSame(tb3, bean.getTestBean4()); - assertSame(tb6, bean.testBean5); - assertSame(tb6, bean.testBean6); - assertSame(bf, bean.beanFactory); + assertThat(bean.initCalled).isTrue(); + assertThat(bean.init2Called).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb5); + assertThat(bean.getTestBean3()).isSameAs(tb4); + assertThat(bean.getTestBean4()).isSameAs(tb3); + assertThat(bean.testBean5).isSameAs(tb6); + assertThat(bean.testBean6).isSameAs(tb6); + assertThat(bean.beanFactory).isSameAs(bf); try { bf.getBean("annotatedBean2"); } catch (BeanCreationException ex) { - assertTrue(ex.getRootCause() instanceof NoSuchBeanDefinitionException); + boolean condition = ex.getRootCause() instanceof NoSuchBeanDefinitionException; + assertThat(condition).isTrue(); NoSuchBeanDefinitionException innerEx = (NoSuchBeanDefinitionException) ex.getRootCause(); - assertEquals("testBean9", innerEx.getBeanName()); + assertThat(innerEx.getBeanName()).isEqualTo("testBean9"); } bf.destroySingletons(); - assertTrue(bean.destroyCalled); - assertTrue(bean.destroy2Called); + assertThat(bean.destroyCalled).isTrue(); + assertThat(bean.destroy2Called).isTrue(); } @Test @@ -447,19 +443,19 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerAlias("xy", "testBean9"); ExtendedEjbInjectionBean bean = (ExtendedEjbInjectionBean) bf.getBean("annotatedBean"); - assertTrue(bean.initCalled); - assertTrue(bean.init2Called); - assertSame(tb, bean.getTestBean()); - assertSame(tb2, bean.getTestBean2()); - assertSame(tb4, bean.getTestBean3()); - assertSame(tb3, bean.getTestBean4()); - assertSame(tb6, bean.testBean5); - assertSame(tb6, bean.testBean6); - assertSame(bf, bean.beanFactory); + assertThat(bean.initCalled).isTrue(); + assertThat(bean.init2Called).isTrue(); + assertThat(bean.getTestBean()).isSameAs(tb); + assertThat(bean.getTestBean2()).isSameAs(tb2); + assertThat(bean.getTestBean3()).isSameAs(tb4); + assertThat(bean.getTestBean4()).isSameAs(tb3); + assertThat(bean.testBean5).isSameAs(tb6); + assertThat(bean.testBean6).isSameAs(tb6); + assertThat(bean.beanFactory).isSameAs(bf); bf.destroySingletons(); - assertTrue(bean.destroyCalled); - assertTrue(bean.destroy2Called); + assertThat(bean.destroyCalled).isTrue(); + assertThat(bean.destroy2Called).isTrue(); } @Test @@ -473,11 +469,11 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); LazyResourceFieldInjectionBean bean = (LazyResourceFieldInjectionBean) bf.getBean("annotatedBean"); - assertFalse(bf.containsSingleton("testBean")); + assertThat(bf.containsSingleton("testBean")).isFalse(); bean.testBean.setName("notLazyAnymore"); - assertTrue(bf.containsSingleton("testBean")); + assertThat(bf.containsSingleton("testBean")).isTrue(); TestBean tb = (TestBean) bf.getBean("testBean"); - assertEquals("notLazyAnymore", tb.getName()); + assertThat(tb.getName()).isEqualTo("notLazyAnymore"); } @Test @@ -491,11 +487,11 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); LazyResourceMethodInjectionBean bean = (LazyResourceMethodInjectionBean) bf.getBean("annotatedBean"); - assertFalse(bf.containsSingleton("testBean")); + assertThat(bf.containsSingleton("testBean")).isFalse(); bean.testBean.setName("notLazyAnymore"); - assertTrue(bf.containsSingleton("testBean")); + assertThat(bf.containsSingleton("testBean")).isTrue(); TestBean tb = (TestBean) bf.getBean("testBean"); - assertEquals("notLazyAnymore", tb.getName()); + assertThat(tb.getName()).isEqualTo("notLazyAnymore"); } @Test @@ -509,11 +505,11 @@ public class CommonAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); LazyResourceCglibInjectionBean bean = (LazyResourceCglibInjectionBean) bf.getBean("annotatedBean"); - assertFalse(bf.containsSingleton("testBean")); + assertThat(bf.containsSingleton("testBean")).isFalse(); bean.testBean.setName("notLazyAnymore"); - assertTrue(bf.containsSingleton("testBean")); + assertThat(bf.containsSingleton("testBean")).isTrue(); TestBean tb = (TestBean) bf.getBean("testBean"); - assertEquals("notLazyAnymore", tb.getName()); + assertThat(tb.getName()).isEqualTo("notLazyAnymore"); } @@ -546,7 +542,7 @@ public class CommonAnnotationBeanPostProcessorTests { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AnnotatedInitDestroyBean) { - assertFalse(((AnnotatedInitDestroyBean) bean).initCalled); + assertThat(((AnnotatedInitDestroyBean) bean).initCalled).isFalse(); } return bean; } @@ -554,7 +550,7 @@ public class CommonAnnotationBeanPostProcessorTests { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AnnotatedInitDestroyBean) { - assertTrue(((AnnotatedInitDestroyBean) bean).initCalled); + assertThat(((AnnotatedInitDestroyBean) bean).initCalled).isTrue(); } return bean; } @@ -562,7 +558,7 @@ public class CommonAnnotationBeanPostProcessorTests { @Override public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { if (bean instanceof AnnotatedInitDestroyBean) { - assertFalse(((AnnotatedInitDestroyBean) bean).destroyCalled); + assertThat(((AnnotatedInitDestroyBean) bean).destroyCalled).isFalse(); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java index b1488544ed9..d359dfae79e 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java @@ -62,9 +62,6 @@ import org.springframework.tests.context.SimpleMapScope; import org.springframework.util.SerializationTestUtils; 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.assertTrue; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; /** @@ -192,7 +189,7 @@ public class ComponentScanAnnotationIntegrationTests { @Test public void withCustomTypeFilter() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ComponentScanWithCustomTypeFilter.class); - assertFalse(ctx.getDefaultListableBeanFactory().containsSingleton("componentScanParserTests.KustomAnnotationAutowiredBean")); + assertThat(ctx.getDefaultListableBeanFactory().containsSingleton("componentScanParserTests.KustomAnnotationAutowiredBean")).isFalse(); KustomAnnotationAutowiredBean testBean = ctx.getBean("componentScanParserTests.KustomAnnotationAutowiredBean", KustomAnnotationAutowiredBean.class); assertThat(testBean.getDependency()).isNotNull(); } @@ -200,7 +197,7 @@ public class ComponentScanAnnotationIntegrationTests { @Test public void withAwareTypeFilter() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ComponentScanWithAwareTypeFilter.class); - assertTrue(ctx.getEnvironment().acceptsProfiles(Profiles.of("the-filter-ran"))); + assertThat(ctx.getEnvironment().acceptsProfiles(Profiles.of("the-filter-ran"))).isTrue(); } @Test @@ -315,10 +312,10 @@ public class ComponentScanAnnotationIntegrationTests { @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) { ((ConfigurableEnvironment) this.environment).addActiveProfile("the-filter-ran"); - assertNotNull(this.beanFactory); - assertNotNull(this.classLoader); - assertNotNull(this.resourceLoader); - assertNotNull(this.environment); + assertThat(this.beanFactory).isNotNull(); + assertThat(this.classLoader).isNotNull(); + assertThat(this.resourceLoader).isNotNull(); + assertThat(this.environment).isNotNull(); return false; } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java index c5b52c1a1f4..b30b8021e5d 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java @@ -23,12 +23,8 @@ import org.springframework.beans.factory.UnsatisfiedDependencyException; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.support.GenericApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Mark Fisher @@ -51,10 +47,10 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { GenericApplicationContext context = new GenericApplicationContext(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultWithNoOverridesTests.xml"); - assertFalse("lazy-init should be false", context.getBeanDefinition(TEST_BEAN_NAME).isLazyInit()); - assertEquals("initCount should be 0", 0, DefaultsTestBean.INIT_COUNT); + assertThat(context.getBeanDefinition(TEST_BEAN_NAME).isLazyInit()).as("lazy-init should be false").isFalse(); + assertThat(DefaultsTestBean.INIT_COUNT).as("initCount should be 0").isEqualTo(0); context.refresh(); - assertEquals("bean should have been instantiated", 1, DefaultsTestBean.INIT_COUNT); + assertThat(DefaultsTestBean.INIT_COUNT).as("bean should have been instantiated").isEqualTo(1); } @Test @@ -62,12 +58,12 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { GenericApplicationContext context = new GenericApplicationContext(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultLazyInitTrueTests.xml"); - assertTrue("lazy-init should be true", context.getBeanDefinition(TEST_BEAN_NAME).isLazyInit()); - assertEquals("initCount should be 0", 0, DefaultsTestBean.INIT_COUNT); + assertThat(context.getBeanDefinition(TEST_BEAN_NAME).isLazyInit()).as("lazy-init should be true").isTrue(); + assertThat(DefaultsTestBean.INIT_COUNT).as("initCount should be 0").isEqualTo(0); context.refresh(); - assertEquals("bean should not have been instantiated yet", 0, DefaultsTestBean.INIT_COUNT); + assertThat(DefaultsTestBean.INIT_COUNT).as("bean should not have been instantiated yet").isEqualTo(0); context.getBean(TEST_BEAN_NAME); - assertEquals("bean should have been instantiated", 1, DefaultsTestBean.INIT_COUNT); + assertThat(DefaultsTestBean.INIT_COUNT).as("bean should have been instantiated").isEqualTo(1); } @Test @@ -75,10 +71,10 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { GenericApplicationContext context = new GenericApplicationContext(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultLazyInitFalseTests.xml"); - assertFalse("lazy-init should be false", context.getBeanDefinition(TEST_BEAN_NAME).isLazyInit()); - assertEquals("initCount should be 0", 0, DefaultsTestBean.INIT_COUNT); + assertThat(context.getBeanDefinition(TEST_BEAN_NAME).isLazyInit()).as("lazy-init should be false").isFalse(); + assertThat(DefaultsTestBean.INIT_COUNT).as("initCount should be 0").isEqualTo(0); context.refresh(); - assertEquals("bean should have been instantiated", 1, DefaultsTestBean.INIT_COUNT); + assertThat(DefaultsTestBean.INIT_COUNT).as("bean should have been instantiated").isEqualTo(1); } @Test @@ -88,9 +84,9 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultWithNoOverridesTests.xml"); context.refresh(); DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME); - assertNull("no dependencies should have been autowired", bean.getConstructorDependency()); - assertNull("no dependencies should have been autowired", bean.getPropertyDependency1()); - assertNull("no dependencies should have been autowired", bean.getPropertyDependency2()); + assertThat(bean.getConstructorDependency()).as("no dependencies should have been autowired").isNull(); + assertThat(bean.getPropertyDependency1()).as("no dependencies should have been autowired").isNull(); + assertThat(bean.getPropertyDependency2()).as("no dependencies should have been autowired").isNull(); } @Test @@ -100,9 +96,9 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultAutowireNoTests.xml"); context.refresh(); DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME); - assertNull("no dependencies should have been autowired", bean.getConstructorDependency()); - assertNull("no dependencies should have been autowired", bean.getPropertyDependency1()); - assertNull("no dependencies should have been autowired", bean.getPropertyDependency2()); + assertThat(bean.getConstructorDependency()).as("no dependencies should have been autowired").isNull(); + assertThat(bean.getPropertyDependency1()).as("no dependencies should have been autowired").isNull(); + assertThat(bean.getPropertyDependency2()).as("no dependencies should have been autowired").isNull(); } @Test @@ -112,10 +108,10 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultAutowireConstructorTests.xml"); context.refresh(); DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME); - assertNotNull("constructor dependency should have been autowired", bean.getConstructorDependency()); - assertEquals("cd", bean.getConstructorDependency().getName()); - assertNull("property dependencies should not have been autowired", bean.getPropertyDependency1()); - assertNull("property dependencies should not have been autowired", bean.getPropertyDependency2()); + assertThat(bean.getConstructorDependency()).as("constructor dependency should have been autowired").isNotNull(); + assertThat(bean.getConstructorDependency().getName()).isEqualTo("cd"); + assertThat(bean.getPropertyDependency1()).as("property dependencies should not have been autowired").isNull(); + assertThat(bean.getPropertyDependency2()).as("property dependencies should not have been autowired").isNull(); } @Test @@ -134,10 +130,10 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultAutowireByNameTests.xml"); context.refresh(); DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME); - assertNull("constructor dependency should not have been autowired", bean.getConstructorDependency()); - assertNull("propertyDependency1 should not have been autowired", bean.getPropertyDependency1()); - assertNotNull("propertyDependency2 should have been autowired", bean.getPropertyDependency2()); - assertEquals("pd2", bean.getPropertyDependency2().getName()); + assertThat(bean.getConstructorDependency()).as("constructor dependency should not have been autowired").isNull(); + assertThat(bean.getPropertyDependency1()).as("propertyDependency1 should not have been autowired").isNull(); + assertThat(bean.getPropertyDependency2()).as("propertyDependency2 should have been autowired").isNotNull(); + assertThat(bean.getPropertyDependency2().getName()).isEqualTo("pd2"); } @Test @@ -147,9 +143,9 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultWithNoOverridesTests.xml"); context.refresh(); DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME); - assertNull("constructor dependency should not have been autowired", bean.getConstructorDependency()); - assertNull("property dependencies should not have been autowired", bean.getPropertyDependency1()); - assertNull("property dependencies should not have been autowired", bean.getPropertyDependency2()); + assertThat(bean.getConstructorDependency()).as("constructor dependency should not have been autowired").isNull(); + assertThat(bean.getPropertyDependency1()).as("property dependencies should not have been autowired").isNull(); + assertThat(bean.getPropertyDependency2()).as("property dependencies should not have been autowired").isNull(); } @Test @@ -159,9 +155,9 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultWithNoOverridesTests.xml"); context.refresh(); DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME); - assertFalse("bean should not have been initialized", bean.isInitialized()); + assertThat(bean.isInitialized()).as("bean should not have been initialized").isFalse(); context.close(); - assertFalse("bean should not have been destroyed", bean.isDestroyed()); + assertThat(bean.isDestroyed()).as("bean should not have been destroyed").isFalse(); } @Test @@ -171,9 +167,9 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultInitAndDestroyMethodsTests.xml"); context.refresh(); DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME); - assertTrue("bean should have been initialized", bean.isInitialized()); + assertThat(bean.isInitialized()).as("bean should have been initialized").isTrue(); context.close(); - assertTrue("bean should have been destroyed", bean.isDestroyed()); + assertThat(bean.isDestroyed()).as("bean should have been destroyed").isTrue(); } @Test @@ -183,9 +179,9 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultNonExistingInitAndDestroyMethodsTests.xml"); context.refresh(); DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME); - assertFalse("bean should not have been initialized", bean.isInitialized()); + assertThat(bean.isInitialized()).as("bean should not have been initialized").isFalse(); context.close(); - assertFalse("bean should not have been destroyed", bean.isDestroyed()); + assertThat(bean.isDestroyed()).as("bean should not have been destroyed").isFalse(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserScopedProxyTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserScopedProxyTests.java index 01608cc39e0..a19fc249f5c 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserScopedProxyTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserScopedProxyTests.java @@ -26,11 +26,8 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.context.SimpleMapScope; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * @author Mark Fisher @@ -47,7 +44,7 @@ public class ComponentScanParserScopedProxyTests { ScopedProxyTestBean bean = (ScopedProxyTestBean) context.getBean("scopedProxyTestBean"); // should not be a proxy - assertFalse(AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).isFalse(); context.close(); } @@ -59,7 +56,7 @@ public class ComponentScanParserScopedProxyTests { ScopedProxyTestBean bean = (ScopedProxyTestBean) context.getBean("scopedProxyTestBean"); // should not be a proxy - assertFalse(AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).isFalse(); context.close(); } @@ -72,12 +69,12 @@ public class ComponentScanParserScopedProxyTests { // should cast to the interface FooService bean = (FooService) context.getBean("scopedProxyTestBean"); // should be dynamic proxy - assertTrue(AopUtils.isJdkDynamicProxy(bean)); + assertThat(AopUtils.isJdkDynamicProxy(bean)).isTrue(); // test serializability - assertEquals("bar", bean.foo(1)); + assertThat(bean.foo(1)).isEqualTo("bar"); FooService deserialized = (FooService) SerializationTestUtils.serializeAndDeserialize(bean); - assertNotNull(deserialized); - assertEquals("bar", deserialized.foo(1)); + assertThat(deserialized).isNotNull(); + assertThat(deserialized.foo(1)).isEqualTo("bar"); context.close(); } @@ -89,12 +86,12 @@ public class ComponentScanParserScopedProxyTests { ScopedProxyTestBean bean = (ScopedProxyTestBean) context.getBean("scopedProxyTestBean"); // should be a class-based proxy - assertTrue(AopUtils.isCglibProxy(bean)); + assertThat(AopUtils.isCglibProxy(bean)).isTrue(); // test serializability - assertEquals("bar", bean.foo(1)); + assertThat(bean.foo(1)).isEqualTo("bar"); ScopedProxyTestBean deserialized = (ScopedProxyTestBean) SerializationTestUtils.serializeAndDeserialize(bean); - assertNotNull(deserialized); - assertEquals("bar", deserialized.foo(1)); + assertThat(deserialized).isNotNull(); + assertThat(deserialized.foo(1)).isEqualTo("bar"); context.close(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserTests.java index 6c7305d1be1..7e4360465cf 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserTests.java @@ -34,10 +34,6 @@ import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.TypeFilter; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * @author Mark Fisher @@ -55,9 +51,9 @@ public class ComponentScanParserTests { @Test public void aspectjTypeFilter() { ClassPathXmlApplicationContext context = loadContext("aspectjTypeFilterTests.xml"); - assertTrue(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("stubFooDao")); - assertFalse(context.containsBean("scopedProxyTestBean")); + assertThat(context.containsBean("fooServiceImpl")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("scopedProxyTestBean")).isFalse(); context.close(); } @@ -68,9 +64,9 @@ public class ComponentScanParserTests { System.setProperty("scanExclude", "example..Scoped*Test*"); try { ClassPathXmlApplicationContext context = loadContext("aspectjTypeFilterTestsWithPlaceholders.xml"); - assertTrue(context.containsBean("fooServiceImpl")); - assertTrue(context.containsBean("stubFooDao")); - assertFalse(context.containsBean("scopedProxyTestBean")); + assertThat(context.containsBean("fooServiceImpl")).isTrue(); + assertThat(context.containsBean("stubFooDao")).isTrue(); + assertThat(context.containsBean("scopedProxyTestBean")).isFalse(); context.close(); } finally { @@ -83,14 +79,14 @@ public class ComponentScanParserTests { @Test public void nonMatchingResourcePattern() { ClassPathXmlApplicationContext context = loadContext("nonMatchingResourcePatternTests.xml"); - assertFalse(context.containsBean("fooServiceImpl")); + assertThat(context.containsBean("fooServiceImpl")).isFalse(); context.close(); } @Test public void matchingResourcePattern() { ClassPathXmlApplicationContext context = loadContext("matchingResourcePatternTests.xml"); - assertTrue(context.containsBean("fooServiceImpl")); + assertThat(context.containsBean("fooServiceImpl")).isTrue(); context.close(); } @@ -98,8 +94,8 @@ public class ComponentScanParserTests { public void componentScanWithAutowiredQualifier() { ClassPathXmlApplicationContext context = loadContext("componentScanWithAutowiredQualifierTests.xml"); AutowiredQualifierFooService fooService = (AutowiredQualifierFooService) context.getBean("fooService"); - assertTrue(fooService.isInitCalled()); - assertEquals("bar", fooService.foo(123)); + assertThat(fooService.isInitCalled()).isTrue(); + assertThat(fooService.foo(123)).isEqualTo("bar"); context.close(); } @@ -107,7 +103,7 @@ public class ComponentScanParserTests { public void customAnnotationUsedForBothComponentScanAndQualifier() { ClassPathXmlApplicationContext context = loadContext("customAnnotationUsedForBothComponentScanAndQualifierTests.xml"); KustomAnnotationAutowiredBean testBean = (KustomAnnotationAutowiredBean) context.getBean("testBean"); - assertNotNull(testBean.getDependency()); + assertThat(testBean.getDependency()).isNotNull(); context.close(); } @@ -115,7 +111,7 @@ public class ComponentScanParserTests { public void customTypeFilter() { ClassPathXmlApplicationContext context = loadContext("customTypeFilterTests.xml"); KustomAnnotationAutowiredBean testBean = (KustomAnnotationAutowiredBean) context.getBean("testBean"); - assertNotNull(testBean.getDependency()); + assertThat(testBean.getDependency()).isNotNull(); context.close(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserWithUserDefinedStrategiesTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserWithUserDefinedStrategiesTests.java index 4b488f9ad8b..4d9ac3e8e87 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserWithUserDefinedStrategiesTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserWithUserDefinedStrategiesTests.java @@ -23,10 +23,8 @@ import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * @author Mark Fisher @@ -37,7 +35,7 @@ public class ComponentScanParserWithUserDefinedStrategiesTests { public void testCustomBeanNameGenerator() { ApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/context/annotation/customNameGeneratorTests.xml"); - assertTrue(context.containsBean("testing.fooServiceImpl")); + assertThat(context.containsBean("testing.fooServiceImpl")).isTrue(); } @Test @@ -45,8 +43,8 @@ public class ComponentScanParserWithUserDefinedStrategiesTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/context/annotation/customScopeResolverTests.xml"); BeanDefinition bd = context.getBeanFactory().getBeanDefinition("fooServiceImpl"); - assertEquals("myCustomScope", bd.getScope()); - assertFalse(bd.isSingleton()); + assertThat(bd.getScope()).isEqualTo("myCustomScope"); + assertThat(bd.isSingleton()).isFalse(); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java index 69750f37873..076da9bef37 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java @@ -64,13 +64,9 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Chris Beams @@ -103,11 +99,11 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerBeanDefinition("config", new RootBeanDefinition(SingletonBeanConfig.class)); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); - assertTrue(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()); + assertThat(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()).isTrue(); Foo foo = beanFactory.getBean("foo", Foo.class); Bar bar = beanFactory.getBean("bar", Bar.class); - assertSame(foo, bar.foo); - assertTrue(Arrays.asList(beanFactory.getDependentBeans("foo")).contains("bar")); + assertThat(bar.foo).isSameAs(foo); + assertThat(Arrays.asList(beanFactory.getDependentBeans("foo")).contains("bar")).isTrue(); } @Test @@ -115,11 +111,11 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerBeanDefinition("config", new RootBeanDefinition(SingletonBeanConfig.class.getName())); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); - assertTrue(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()); + assertThat(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()).isTrue(); Foo foo = beanFactory.getBean("foo", Foo.class); Bar bar = beanFactory.getBean("bar", Bar.class); - assertSame(foo, bar.foo); - assertTrue(Arrays.asList(beanFactory.getDependentBeans("foo")).contains("bar")); + assertThat(bar.foo).isSameAs(foo); + assertThat(Arrays.asList(beanFactory.getDependentBeans("foo")).contains("bar")).isTrue(); } @Test @@ -127,10 +123,10 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerBeanDefinition("config", new RootBeanDefinition(NonEnhancedSingletonBeanConfig.class)); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); - assertTrue(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()); + assertThat(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()).isTrue(); Foo foo = beanFactory.getBean("foo", Foo.class); Bar bar = beanFactory.getBean("bar", Bar.class); - assertNotSame(foo, bar.foo); + assertThat(bar.foo).isNotSameAs(foo); } @Test @@ -138,10 +134,10 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerBeanDefinition("config", new RootBeanDefinition(NonEnhancedSingletonBeanConfig.class.getName())); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); - assertTrue(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()); + assertThat(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()).isTrue(); Foo foo = beanFactory.getBean("foo", Foo.class); Bar bar = beanFactory.getBean("bar", Bar.class); - assertNotSame(foo, bar.foo); + assertThat(bar.foo).isNotSameAs(foo); } @Test @@ -149,12 +145,12 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerBeanDefinition("config", new RootBeanDefinition(StaticSingletonBeanConfig.class)); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); - assertTrue(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()); - assertTrue(((RootBeanDefinition) beanFactory.getBeanDefinition("foo")).hasBeanClass()); - assertTrue(((RootBeanDefinition) beanFactory.getBeanDefinition("bar")).hasBeanClass()); + assertThat(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()).isTrue(); + assertThat(((RootBeanDefinition) beanFactory.getBeanDefinition("foo")).hasBeanClass()).isTrue(); + assertThat(((RootBeanDefinition) beanFactory.getBeanDefinition("bar")).hasBeanClass()).isTrue(); Foo foo = beanFactory.getBean("foo", Foo.class); Bar bar = beanFactory.getBean("bar", Bar.class); - assertNotSame(foo, bar.foo); + assertThat(bar.foo).isNotSameAs(foo); } @Test @@ -162,12 +158,12 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerBeanDefinition("config", new RootBeanDefinition(StaticSingletonBeanConfig.class.getName())); ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); - assertTrue(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()); - assertTrue(((RootBeanDefinition) beanFactory.getBeanDefinition("foo")).hasBeanClass()); - assertTrue(((RootBeanDefinition) beanFactory.getBeanDefinition("bar")).hasBeanClass()); + assertThat(((RootBeanDefinition) beanFactory.getBeanDefinition("config")).hasBeanClass()).isTrue(); + assertThat(((RootBeanDefinition) beanFactory.getBeanDefinition("foo")).hasBeanClass()).isTrue(); + assertThat(((RootBeanDefinition) beanFactory.getBeanDefinition("bar")).hasBeanClass()).isTrue(); Foo foo = beanFactory.getBean("foo", Foo.class); Bar bar = beanFactory.getBean("bar", Bar.class); - assertNotSame(foo, bar.foo); + assertThat(bar.foo).isNotSameAs(foo); } @Test @@ -177,7 +173,7 @@ public class ConfigurationClassPostProcessorTests { pp.postProcessBeanFactory(beanFactory); Foo foo = beanFactory.getBean("foo", Foo.class); Bar bar = beanFactory.getBean("bar", Bar.class); - assertSame(foo, bar.foo); + assertThat(bar.foo).isSameAs(foo); } /** @@ -206,7 +202,7 @@ public class ConfigurationClassPostProcessorTests { pp.postProcessBeanFactory(beanFactory); Foo foo = beanFactory.getBean("foo", Foo.class); Bar bar = beanFactory.getBean("bar", Bar.class); - assertSame(foo, bar.foo); + assertThat(bar.foo).isSameAs(foo); } @Test @@ -311,7 +307,7 @@ public class ConfigurationClassPostProcessorTests { pp.setEnvironment(new StandardEnvironment()); pp.postProcessBeanFactory(beanFactory); SimpleComponent simpleComponent = beanFactory.getBean(SimpleComponent.class); - assertNotNull(simpleComponent); + assertThat(simpleComponent).isNotNull(); } private void assertSupportForComposedAnnotationWithExclude(RootBeanDefinition beanDefinition) { @@ -333,7 +329,7 @@ public class ConfigurationClassPostProcessorTests { pp.postProcessBeanFactory(beanFactory); Foo foo = beanFactory.getBean("foo", Foo.class); Bar bar = beanFactory.getBean("bar", Bar.class); - assertSame(foo, bar.foo); + assertThat(bar.foo).isSameAs(foo); } @Test @@ -385,9 +381,10 @@ public class ConfigurationClassPostProcessorTests { pp.postProcessBeanFactory(beanFactory); Foo foo = beanFactory.getBean(Foo.class); - assertTrue(foo instanceof ExtendedFoo); + boolean condition = foo instanceof ExtendedFoo; + assertThat(condition).isTrue(); Bar bar = beanFactory.getBean(Bar.class); - assertSame(foo, bar.foo); + assertThat(bar.foo).isSameAs(foo); } @Test @@ -399,9 +396,10 @@ public class ConfigurationClassPostProcessorTests { pp.postProcessBeanFactory(beanFactory); Foo foo = beanFactory.getBean(Foo.class); - assertTrue(foo instanceof ExtendedAgainFoo); + boolean condition = foo instanceof ExtendedAgainFoo; + assertThat(condition).isTrue(); Bar bar = beanFactory.getBean(Bar.class); - assertSame(foo, bar.foo); + assertThat(bar.foo).isSameAs(foo); } @Test @@ -427,9 +425,10 @@ public class ConfigurationClassPostProcessorTests { pp.postProcessBeanFactory(beanFactory); Foo foo = beanFactory.getBean(Foo.class); - assertTrue(foo instanceof ExtendedFoo); + boolean condition = foo instanceof ExtendedFoo; + assertThat(condition).isTrue(); Bar bar = beanFactory.getBean(Bar.class); - assertSame(foo, bar.foo); + assertThat(bar.foo).isSameAs(foo); } @Test // SPR-16734 @@ -440,9 +439,10 @@ public class ConfigurationClassPostProcessorTests { beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor()); Foo foo = beanFactory.getBean(Foo.class); - assertTrue(foo instanceof ExtendedFoo); + boolean condition = foo instanceof ExtendedFoo; + assertThat(condition).isTrue(); Bar bar = beanFactory.getBean(Bar.class); - assertSame(foo, bar.foo); + assertThat(bar.foo).isSameAs(foo); } @Test @@ -456,9 +456,10 @@ public class ConfigurationClassPostProcessorTests { pp.postProcessBeanFactory(beanFactory); ITestBean injected = beanFactory.getBean("consumer", ScopedProxyConsumer.class).testBean; - assertTrue(injected instanceof ScopedObject); - assertSame(beanFactory.getBean("scopedClass"), injected); - assertSame(beanFactory.getBean(ITestBean.class), injected); + boolean condition = injected instanceof ScopedObject; + assertThat(condition).isTrue(); + assertThat(injected).isSameAs(beanFactory.getBean("scopedClass")); + assertThat(injected).isSameAs(beanFactory.getBean(ITestBean.class)); } @Test @@ -487,8 +488,8 @@ public class ConfigurationClassPostProcessorTests { pp.postProcessBeanFactory(beanFactory); RepositoryInjectionBean bean = (RepositoryInjectionBean) beanFactory.getBean("annotatedBean"); - assertEquals("Repository", bean.stringRepository.toString()); - assertEquals("Repository", bean.integerRepository.toString()); + assertThat(bean.stringRepository.toString()).isEqualTo("Repository"); + assertThat(bean.integerRepository.toString()).isEqualTo("Repository"); } @Test @@ -504,8 +505,8 @@ public class ConfigurationClassPostProcessorTests { pp.postProcessBeanFactory(beanFactory); RepositoryInjectionBean bean = (RepositoryInjectionBean) beanFactory.getBean("annotatedBean"); - assertEquals("Repository", bean.stringRepository.toString()); - assertEquals("Repository", bean.integerRepository.toString()); + assertThat(bean.stringRepository.toString()).isEqualTo("Repository"); + assertThat(bean.integerRepository.toString()).isEqualTo("Repository"); } @Test @@ -522,10 +523,10 @@ public class ConfigurationClassPostProcessorTests { beanFactory.freezeConfiguration(); RepositoryInjectionBean bean = (RepositoryInjectionBean) beanFactory.getBean("annotatedBean"); - assertEquals("Repository", bean.stringRepository.toString()); - assertEquals("Repository", bean.integerRepository.toString()); - assertTrue(AopUtils.isCglibProxy(bean.stringRepository)); - assertTrue(AopUtils.isCglibProxy(bean.integerRepository)); + assertThat(bean.stringRepository.toString()).isEqualTo("Repository"); + assertThat(bean.integerRepository.toString()).isEqualTo("Repository"); + assertThat(AopUtils.isCglibProxy(bean.stringRepository)).isTrue(); + assertThat(AopUtils.isCglibProxy(bean.integerRepository)).isTrue(); } @Test @@ -542,10 +543,10 @@ public class ConfigurationClassPostProcessorTests { beanFactory.freezeConfiguration(); RepositoryInjectionBean bean = (RepositoryInjectionBean) beanFactory.getBean("annotatedBean"); - assertEquals("Repository", bean.stringRepository.toString()); - assertEquals("Repository", bean.integerRepository.toString()); - assertTrue(AopUtils.isCglibProxy(bean.stringRepository)); - assertTrue(AopUtils.isCglibProxy(bean.integerRepository)); + assertThat(bean.stringRepository.toString()).isEqualTo("Repository"); + assertThat(bean.integerRepository.toString()).isEqualTo("Repository"); + assertThat(AopUtils.isCglibProxy(bean.stringRepository)).isTrue(); + assertThat(AopUtils.isCglibProxy(bean.integerRepository)).isTrue(); } @Test @@ -562,7 +563,7 @@ public class ConfigurationClassPostProcessorTests { beanFactory.preInstantiateSingletons(); SpecificRepositoryInjectionBean bean = (SpecificRepositoryInjectionBean) beanFactory.getBean("annotatedBean"); - assertSame(beanFactory.getBean("genericRepo"), bean.genericRepository); + assertThat(bean.genericRepository).isSameAs(beanFactory.getBean("genericRepo")); } @Test @@ -579,9 +580,9 @@ public class ConfigurationClassPostProcessorTests { beanFactory.preInstantiateSingletons(); RepositoryFactoryBeanInjectionBean bean = (RepositoryFactoryBeanInjectionBean) beanFactory.getBean("annotatedBean"); - assertSame(beanFactory.getBean("&repoFactoryBean"), bean.repositoryFactoryBean); - assertSame(beanFactory.getBean("&repoFactoryBean"), bean.qualifiedRepositoryFactoryBean); - assertSame(beanFactory.getBean("&repoFactoryBean"), bean.prefixQualifiedRepositoryFactoryBean); + assertThat(bean.repositoryFactoryBean).isSameAs(beanFactory.getBean("&repoFactoryBean")); + assertThat(bean.qualifiedRepositoryFactoryBean).isSameAs(beanFactory.getBean("&repoFactoryBean")); + assertThat(bean.prefixQualifiedRepositoryFactoryBean).isSameAs(beanFactory.getBean("&repoFactoryBean")); } @Test @@ -590,7 +591,7 @@ public class ConfigurationClassPostProcessorTests { ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); - assertSame(beanFactory.getBean("rawRepo"), beanFactory.getBean("repoConsumer")); + assertThat(beanFactory.getBean("repoConsumer")).isSameAs(beanFactory.getBean("rawRepo")); } @Test @@ -599,7 +600,7 @@ public class ConfigurationClassPostProcessorTests { ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor(); pp.postProcessBeanFactory(beanFactory); - assertSame(beanFactory.getBean("genericRepo"), beanFactory.getBean("repoConsumer")); + assertThat(beanFactory.getBean("repoConsumer")).isSameAs(beanFactory.getBean("genericRepo")); } @Test @@ -607,7 +608,7 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(WildcardWithExtendsConfiguration.class)); new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory); - assertSame(beanFactory.getBean("stringRepo"), beanFactory.getBean("repoConsumer")); + assertThat(beanFactory.getBean("repoConsumer")).isSameAs(beanFactory.getBean("stringRepo")); } @Test @@ -615,7 +616,7 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(WildcardWithGenericExtendsConfiguration.class)); new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory); - assertSame(beanFactory.getBean("genericRepo"), beanFactory.getBean("repoConsumer")); + assertThat(beanFactory.getBean("repoConsumer")).isSameAs(beanFactory.getBean("genericRepo")); } @Test @@ -624,15 +625,15 @@ public class ConfigurationClassPostProcessorTests { new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory); String[] beanNames = beanFactory.getBeanNamesForType(Repository.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); } @Test @@ -642,15 +643,15 @@ public class ConfigurationClassPostProcessorTests { beanFactory.preInstantiateSingletons(); String[] beanNames = beanFactory.getBeanNamesForType(Repository.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); } @Test @@ -659,13 +660,13 @@ public class ConfigurationClassPostProcessorTests { new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory); String[] beanNames = beanFactory.getBeanNamesForType(Repository.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(0, beanNames.length); + assertThat(beanNames.length).isEqualTo(0); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(0, beanNames.length); + assertThat(beanNames.length).isEqualTo(0); } @Test @@ -675,15 +676,15 @@ public class ConfigurationClassPostProcessorTests { beanFactory.preInstantiateSingletons(); String[] beanNames = beanFactory.getBeanNamesForType(Repository.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); } @Test @@ -692,15 +693,15 @@ public class ConfigurationClassPostProcessorTests { new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory); String[] beanNames = beanFactory.getBeanNamesForType(Repository.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); } @Test @@ -710,15 +711,15 @@ public class ConfigurationClassPostProcessorTests { beanFactory.preInstantiateSingletons(); String[] beanNames = beanFactory.getBeanNamesForType(Repository.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); } @Test @@ -732,17 +733,17 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerSingleton("traceInterceptor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor())); String[] beanNames = beanFactory.getBeanNamesForType(Repository.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); - assertTrue(AopUtils.isCglibProxy(beanFactory.getBean("stringRepo"))); + assertThat(AopUtils.isCglibProxy(beanFactory.getBean("stringRepo"))).isTrue(); } @Test @@ -757,17 +758,17 @@ public class ConfigurationClassPostProcessorTests { beanFactory.preInstantiateSingletons(); String[] beanNames = beanFactory.getBeanNamesForType(Repository.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); - assertTrue(AopUtils.isCglibProxy(beanFactory.getBean("stringRepo"))); + assertThat(AopUtils.isCglibProxy(beanFactory.getBean("stringRepo"))).isTrue(); } @Test @@ -782,17 +783,17 @@ public class ConfigurationClassPostProcessorTests { beanFactory.preInstantiateSingletons(); String[] beanNames = beanFactory.getBeanNamesForType(Repository.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); - assertTrue(AopUtils.isCglibProxy(beanFactory.getBean("stringRepo"))); + assertThat(AopUtils.isCglibProxy(beanFactory.getBean("stringRepo"))).isTrue(); } @Test @@ -807,17 +808,17 @@ public class ConfigurationClassPostProcessorTests { beanFactory.preInstantiateSingletons(); String[] beanNames = beanFactory.getBeanNamesForType(Repository.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); - assertTrue(AopUtils.isCglibProxy(beanFactory.getBean("stringRepo"))); + assertThat(AopUtils.isCglibProxy(beanFactory.getBean("stringRepo"))).isTrue(); } @Test @@ -830,17 +831,17 @@ public class ConfigurationClassPostProcessorTests { beanFactory.registerSingleton("traceInterceptor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor())); String[] beanNames = beanFactory.getBeanNamesForType(RepositoryInterface.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); - assertTrue(AopUtils.isJdkDynamicProxy(beanFactory.getBean("stringRepo"))); + assertThat(AopUtils.isJdkDynamicProxy(beanFactory.getBean("stringRepo"))).isTrue(); } @Test @@ -854,17 +855,17 @@ public class ConfigurationClassPostProcessorTests { beanFactory.preInstantiateSingletons(); String[] beanNames = beanFactory.getBeanNamesForType(RepositoryInterface.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); - assertTrue(AopUtils.isJdkDynamicProxy(beanFactory.getBean("stringRepo"))); + assertThat(AopUtils.isJdkDynamicProxy(beanFactory.getBean("stringRepo"))).isTrue(); } @Test @@ -878,17 +879,17 @@ public class ConfigurationClassPostProcessorTests { beanFactory.preInstantiateSingletons(); String[] beanNames = beanFactory.getBeanNamesForType(RepositoryInterface.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); - assertTrue(AopUtils.isJdkDynamicProxy(beanFactory.getBean("stringRepo"))); + assertThat(AopUtils.isJdkDynamicProxy(beanFactory.getBean("stringRepo"))).isTrue(); } @Test @@ -902,17 +903,17 @@ public class ConfigurationClassPostProcessorTests { beanFactory.preInstantiateSingletons(); String[] beanNames = beanFactory.getBeanNamesForType(RepositoryInterface.class); - assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo")); + assertThat(ObjectUtils.containsElement(beanNames, "stringRepo")).isTrue(); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class)); - assertEquals(1, beanNames.length); - assertEquals("stringRepo", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("stringRepo"); - assertTrue(AopUtils.isJdkDynamicProxy(beanFactory.getBean("stringRepo"))); + assertThat(AopUtils.isJdkDynamicProxy(beanFactory.getBean("stringRepo"))).isTrue(); } @Test @@ -998,84 +999,84 @@ public class ConfigurationClassPostProcessorTests { @Test public void testInjectionPointMatchForNarrowTargetReturnType() { ApplicationContext ctx = new AnnotationConfigApplicationContext(FooBarConfiguration.class); - assertSame(ctx.getBean(BarImpl.class), ctx.getBean(FooImpl.class).bar); + assertThat(ctx.getBean(FooImpl.class).bar).isSameAs(ctx.getBean(BarImpl.class)); } @Test public void testVarargOnBeanMethod() { ApplicationContext ctx = new AnnotationConfigApplicationContext(VarargConfiguration.class, TestBean.class); VarargConfiguration bean = ctx.getBean(VarargConfiguration.class); - assertNotNull(bean.testBeans); - assertEquals(1, bean.testBeans.length); - assertSame(ctx.getBean(TestBean.class), bean.testBeans[0]); + assertThat(bean.testBeans).isNotNull(); + assertThat(bean.testBeans.length).isEqualTo(1); + assertThat(bean.testBeans[0]).isSameAs(ctx.getBean(TestBean.class)); } @Test public void testEmptyVarargOnBeanMethod() { ApplicationContext ctx = new AnnotationConfigApplicationContext(VarargConfiguration.class); VarargConfiguration bean = ctx.getBean(VarargConfiguration.class); - assertNotNull(bean.testBeans); - assertEquals(0, bean.testBeans.length); + assertThat(bean.testBeans).isNotNull(); + assertThat(bean.testBeans.length).isEqualTo(0); } @Test public void testCollectionArgumentOnBeanMethod() { ApplicationContext ctx = new AnnotationConfigApplicationContext(CollectionArgumentConfiguration.class, TestBean.class); CollectionArgumentConfiguration bean = ctx.getBean(CollectionArgumentConfiguration.class); - assertNotNull(bean.testBeans); - assertEquals(1, bean.testBeans.size()); - assertSame(ctx.getBean(TestBean.class), bean.testBeans.get(0)); + assertThat(bean.testBeans).isNotNull(); + assertThat(bean.testBeans.size()).isEqualTo(1); + assertThat(bean.testBeans.get(0)).isSameAs(ctx.getBean(TestBean.class)); } @Test public void testEmptyCollectionArgumentOnBeanMethod() { ApplicationContext ctx = new AnnotationConfigApplicationContext(CollectionArgumentConfiguration.class); CollectionArgumentConfiguration bean = ctx.getBean(CollectionArgumentConfiguration.class); - assertNotNull(bean.testBeans); - assertTrue(bean.testBeans.isEmpty()); + assertThat(bean.testBeans).isNotNull(); + assertThat(bean.testBeans.isEmpty()).isTrue(); } @Test public void testMapArgumentOnBeanMethod() { ApplicationContext ctx = new AnnotationConfigApplicationContext(MapArgumentConfiguration.class, DummyRunnable.class); MapArgumentConfiguration bean = ctx.getBean(MapArgumentConfiguration.class); - assertNotNull(bean.testBeans); - assertEquals(1, bean.testBeans.size()); - assertSame(ctx.getBean(Runnable.class), bean.testBeans.values().iterator().next()); + assertThat(bean.testBeans).isNotNull(); + assertThat(bean.testBeans.size()).isEqualTo(1); + assertThat(bean.testBeans.values().iterator().next()).isSameAs(ctx.getBean(Runnable.class)); } @Test public void testEmptyMapArgumentOnBeanMethod() { ApplicationContext ctx = new AnnotationConfigApplicationContext(MapArgumentConfiguration.class); MapArgumentConfiguration bean = ctx.getBean(MapArgumentConfiguration.class); - assertNotNull(bean.testBeans); - assertTrue(bean.testBeans.isEmpty()); + assertThat(bean.testBeans).isNotNull(); + assertThat(bean.testBeans.isEmpty()).isTrue(); } @Test public void testCollectionInjectionFromSameConfigurationClass() { ApplicationContext ctx = new AnnotationConfigApplicationContext(CollectionInjectionConfiguration.class); CollectionInjectionConfiguration bean = ctx.getBean(CollectionInjectionConfiguration.class); - assertNotNull(bean.testBeans); - assertEquals(1, bean.testBeans.size()); - assertSame(ctx.getBean(TestBean.class), bean.testBeans.get(0)); + assertThat(bean.testBeans).isNotNull(); + assertThat(bean.testBeans.size()).isEqualTo(1); + assertThat(bean.testBeans.get(0)).isSameAs(ctx.getBean(TestBean.class)); } @Test public void testMapInjectionFromSameConfigurationClass() { ApplicationContext ctx = new AnnotationConfigApplicationContext(MapInjectionConfiguration.class); MapInjectionConfiguration bean = ctx.getBean(MapInjectionConfiguration.class); - assertNotNull(bean.testBeans); - assertEquals(1, bean.testBeans.size()); - assertSame(ctx.getBean(Runnable.class), bean.testBeans.get("testBean")); + assertThat(bean.testBeans).isNotNull(); + assertThat(bean.testBeans.size()).isEqualTo(1); + assertThat(bean.testBeans.get("testBean")).isSameAs(ctx.getBean(Runnable.class)); } @Test public void testBeanLookupFromSameConfigurationClass() { ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanLookupConfiguration.class); BeanLookupConfiguration bean = ctx.getBean(BeanLookupConfiguration.class); - assertNotNull(bean.getTestBean()); - assertSame(ctx.getBean(TestBean.class), bean.getTestBean()); + assertThat(bean.getTestBean()).isNotNull(); + assertThat(bean.getTestBean()).isSameAs(ctx.getBean(TestBean.class)); } @Test @@ -1089,7 +1090,8 @@ public class ConfigurationClassPostProcessorTests { @Test public void testBeanDefinitionRegistryPostProcessorConfig() { ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanDefinitionRegistryPostProcessorConfig.class); - assertTrue(ctx.getBean("myTestBean") instanceof TestBean); + boolean condition = ctx.getBean("myTestBean") instanceof TestBean; + assertThat(condition).isTrue(); } @@ -1910,8 +1912,8 @@ public class ConfigurationClassPostProcessorTests { @Qualifier("systemProperties") Map sysprops, @Qualifier("systemEnvironment") Map sysenv) { this.testBeans = testBeans; - assertSame(env.getSystemProperties(), sysprops); - assertSame(env.getSystemEnvironment(), sysenv); + assertThat(sysprops).isSameAs(env.getSystemProperties()); + assertThat(sysenv).isSameAs(env.getSystemEnvironment()); return () -> {}; } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassWithConditionTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassWithConditionTests.java index 255d72ab3fd..c9b84903916 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassWithConditionTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassWithConditionTests.java @@ -32,9 +32,6 @@ import org.springframework.core.type.AnnotationMetadata; import org.springframework.stereotype.Component; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Test for {@link Conditional} beans. @@ -50,9 +47,9 @@ public class ConfigurationClassWithConditionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(BeanOneConfiguration.class, BeanTwoConfiguration.class); ctx.refresh(); - assertTrue(ctx.containsBean("bean1")); - assertFalse(ctx.containsBean("bean2")); - assertFalse(ctx.containsBean("configurationClassWithConditionTests.BeanTwoConfiguration")); + assertThat(ctx.containsBean("bean1")).isTrue(); + assertThat(ctx.containsBean("bean2")).isFalse(); + assertThat(ctx.containsBean("configurationClassWithConditionTests.BeanTwoConfiguration")).isFalse(); } @Test @@ -60,9 +57,9 @@ public class ConfigurationClassWithConditionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(BeanTwoConfiguration.class); ctx.refresh(); - assertFalse(ctx.containsBean("bean1")); - assertTrue(ctx.containsBean("bean2")); - assertTrue(ctx.containsBean("configurationClassWithConditionTests.BeanTwoConfiguration")); + assertThat(ctx.containsBean("bean1")).isFalse(); + assertThat(ctx.containsBean("bean2")).isTrue(); + assertThat(ctx.containsBean("configurationClassWithConditionTests.BeanTwoConfiguration")).isTrue(); } @Test @@ -70,8 +67,8 @@ public class ConfigurationClassWithConditionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(BeanOneConfiguration.class, BeanThreeConfiguration.class); ctx.refresh(); - assertTrue(ctx.containsBean("bean1")); - assertTrue(ctx.containsBean("bean3")); + assertThat(ctx.containsBean("bean1")).isTrue(); + assertThat(ctx.containsBean("bean3")).isTrue(); } @Test @@ -79,8 +76,8 @@ public class ConfigurationClassWithConditionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(BeanThreeConfiguration.class); ctx.refresh(); - assertFalse(ctx.containsBean("bean1")); - assertFalse(ctx.containsBean("bean3")); + assertThat(ctx.containsBean("bean1")).isFalse(); + assertThat(ctx.containsBean("bean3")).isFalse(); } @Test @@ -88,7 +85,7 @@ public class ConfigurationClassWithConditionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConfigurationWithMetaCondition.class); ctx.refresh(); - assertTrue(ctx.containsBean("bean")); + assertThat(ctx.containsBean("bean")).isTrue(); } @Test @@ -96,7 +93,7 @@ public class ConfigurationClassWithConditionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.registerBeanDefinition("config", new RootBeanDefinition(ConfigurationWithMetaCondition.class.getName())); ctx.refresh(); - assertTrue(ctx.containsBean("bean")); + assertThat(ctx.containsBean("bean")).isTrue(); } @Test @@ -104,7 +101,7 @@ public class ConfigurationClassWithConditionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(NonConfigurationClass.class); ctx.refresh(); - assertFalse(ctx.containsBean("bean1")); + assertThat(ctx.containsBean("bean1")).isFalse(); } @Test @@ -112,7 +109,7 @@ public class ConfigurationClassWithConditionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.registerBeanDefinition("config", new RootBeanDefinition(NonConfigurationClass.class.getName())); ctx.refresh(); - assertFalse(ctx.containsBean("bean1")); + assertThat(ctx.containsBean("bean1")).isFalse(); } @Test @@ -120,7 +117,7 @@ public class ConfigurationClassWithConditionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConditionOnMethodConfiguration.class); ctx.refresh(); - assertFalse(ctx.containsBean("bean1")); + assertThat(ctx.containsBean("bean1")).isFalse(); } @Test @@ -128,7 +125,7 @@ public class ConfigurationClassWithConditionTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.registerBeanDefinition("config", new RootBeanDefinition(ConditionOnMethodConfiguration.class.getName())); ctx.refresh(); - assertFalse(ctx.containsBean("bean1")); + assertThat(ctx.containsBean("bean1")).isFalse(); } @Test @@ -141,23 +138,23 @@ public class ConfigurationClassWithConditionTests { @Test public void conditionOnOverriddenMethodHonored() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithBeanSkipped.class); - assertEquals(0, context.getBeansOfType(ExampleBean.class).size()); + assertThat(context.getBeansOfType(ExampleBean.class).size()).isEqualTo(0); } @Test public void noConditionOnOverriddenMethodHonored() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithBeanReactivated.class); Map beans = context.getBeansOfType(ExampleBean.class); - assertEquals(1, beans.size()); - assertEquals("baz", beans.keySet().iterator().next()); + assertThat(beans.size()).isEqualTo(1); + assertThat(beans.keySet().iterator().next()).isEqualTo("baz"); } @Test public void configWithAlternativeBeans() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithAlternativeBeans.class); Map beans = context.getBeansOfType(ExampleBean.class); - assertEquals(1, beans.size()); - assertEquals("baz", beans.keySet().iterator().next()); + assertThat(beans.size()).isEqualTo(1); + assertThat(beans.keySet().iterator().next()).isEqualTo("baz"); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationWithFactoryBeanAndAutowiringTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationWithFactoryBeanAndAutowiringTests.java index 162a6f80278..815665dd05a 100755 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationWithFactoryBeanAndAutowiringTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationWithFactoryBeanAndAutowiringTests.java @@ -23,7 +23,7 @@ import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests cornering bug SPR-8514. @@ -88,7 +88,7 @@ public class ConfigurationWithFactoryBeanAndAutowiringTests { ctx.register(AppConfig.class); ctx.register(FactoryBeanCallingConfig.class); ctx.refresh(); - assertEquals("true", ctx.getBean("myString")); + assertThat(ctx.getBean("myString")).isEqualTo("true"); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationWithFactoryBeanAndParametersTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationWithFactoryBeanAndParametersTests.java index 6b81e0519b9..ce6034466bc 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationWithFactoryBeanAndParametersTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationWithFactoryBeanAndParametersTests.java @@ -23,7 +23,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Test case cornering the bug initially raised with SPR-8762, in which a @@ -38,7 +38,7 @@ public class ConfigurationWithFactoryBeanAndParametersTests { @Test public void test() { ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class, Bar.class); - assertNotNull(ctx.getBean(Bar.class).foo); + assertThat(ctx.getBean(Bar.class).foo).isNotNull(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/DeferredImportSelectorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/DeferredImportSelectorTests.java index f7a39111205..0b87fe4c26e 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/DeferredImportSelectorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/DeferredImportSelectorTests.java @@ -21,8 +21,7 @@ import org.junit.Test; import org.springframework.context.annotation.DeferredImportSelector.Group; import org.springframework.core.type.AnnotationMetadata; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -36,27 +35,23 @@ public class DeferredImportSelectorTests { public void entryEqualsSameInstance() { AnnotationMetadata metadata = mock(AnnotationMetadata.class); Group.Entry entry = new Group.Entry(metadata, "com.example.Test"); - assertEquals(entry, entry); + assertThat(entry).isEqualTo(entry); } @Test public void entryEqualsSameMetadataAndClassName() { AnnotationMetadata metadata = mock(AnnotationMetadata.class); - assertEquals(new Group.Entry(metadata, "com.example.Test"), - new Group.Entry(metadata, "com.example.Test")); + assertThat(new Group.Entry(metadata, "com.example.Test")).isEqualTo(new Group.Entry(metadata, "com.example.Test")); } @Test public void entryEqualDifferentMetadataAndSameClassName() { - assertNotEquals( - new Group.Entry(mock(AnnotationMetadata.class), "com.example.Test"), - new Group.Entry(mock(AnnotationMetadata.class), "com.example.Test")); + assertThat(new Group.Entry(mock(AnnotationMetadata.class), "com.example.Test")).isNotEqualTo(new Group.Entry(mock(AnnotationMetadata.class), "com.example.Test")); } @Test public void entryEqualSameMetadataAnDifferentClassName() { AnnotationMetadata metadata = mock(AnnotationMetadata.class); - assertNotEquals(new Group.Entry(metadata, "com.example.Test"), - new Group.Entry(metadata, "com.example.AnotherTest")); + assertThat(new Group.Entry(metadata, "com.example.AnotherTest")).isNotEqualTo(new Group.Entry(metadata, "com.example.Test")); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/EnableAspectJAutoProxyTests.java b/spring-context/src/test/java/org/springframework/context/annotation/EnableAspectJAutoProxyTests.java index 1a3d66fdecc..a7a90b5ceb2 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/EnableAspectJAutoProxyTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/EnableAspectJAutoProxyTests.java @@ -33,9 +33,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -71,17 +68,17 @@ public class EnableAspectJAutoProxyTests { FooService fooService = ctx.getBean(FooService.class); ServiceInvocationCounter counter = ctx.getBean(ServiceInvocationCounter.class); - assertEquals(0, counter.getCount()); + assertThat(counter.getCount()).isEqualTo(0); - assertTrue(fooService.isInitCalled()); - assertEquals(1, counter.getCount()); + assertThat(fooService.isInitCalled()).isTrue(); + assertThat(counter.getCount()).isEqualTo(1); String value = fooService.foo(1); - assertEquals("bar", value); - assertEquals(2, counter.getCount()); + assertThat(value).isEqualTo("bar"); + assertThat(counter.getCount()).isEqualTo(2); fooService.foo(1); - assertEquals(3, counter.getCount()); + assertThat(counter.getCount()).isEqualTo(3); } @Test @@ -130,7 +127,7 @@ public class EnableAspectJAutoProxyTests { return new FooServiceImpl() { @Override public String foo(int id) { - assertNotNull(AopContext.currentProxy()); + assertThat(AopContext.currentProxy()).isNotNull(); return super.foo(id); } @Override diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java index 85ddbdae012..5d75e5782ed 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java @@ -37,8 +37,6 @@ import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcesso import org.springframework.util.Assert; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Tests that an ImportAware @Configuration classes gets injected with the @@ -55,7 +53,7 @@ public class ImportAwareTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ImportingConfig.class); ctx.refresh(); - assertNotNull(ctx.getBean("importedConfigBean")); + assertThat(ctx.getBean("importedConfigBean")).isNotNull(); ImportedConfig importAwareConfig = ctx.getBean(ImportedConfig.class); AnnotationMetadata importMetadata = importAwareConfig.importMetadata; @@ -71,7 +69,7 @@ public class ImportAwareTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(IndirectlyImportingConfig.class); ctx.refresh(); - assertNotNull(ctx.getBean("importedConfigBean")); + assertThat(ctx.getBean("importedConfigBean")).isNotNull(); ImportedConfig importAwareConfig = ctx.getBean(ImportedConfig.class); AnnotationMetadata importMetadata = importAwareConfig.importMetadata; @@ -87,7 +85,7 @@ public class ImportAwareTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ImportingConfigLite.class); ctx.refresh(); - assertNotNull(ctx.getBean("importedConfigBean")); + assertThat(ctx.getBean("importedConfigBean")).isNotNull(); ImportedConfigLite importAwareConfig = ctx.getBean(ImportedConfigLite.class); AnnotationMetadata importMetadata = importAwareConfig.importMetadata; @@ -104,8 +102,8 @@ public class ImportAwareTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ImportingRegistrarConfig.class); ctx.refresh(); - assertNotNull(ctx.getBean("registrarImportedBean")); - assertNotNull(ctx.getBean("otherImportedConfigBean")); + assertThat(ctx.getBean("registrarImportedBean")).isNotNull(); + assertThat(ctx.getBean("otherImportedConfigBean")).isNotNull(); } @Test @@ -114,10 +112,10 @@ public class ImportAwareTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ImportingRegistrarConfigWithImport.class); ctx.refresh(); - assertNotNull(ctx.getBean("registrarImportedBean")); - assertNotNull(ctx.getBean("otherImportedConfigBean")); - assertNotNull(ctx.getBean("importedConfigBean")); - assertNotNull(ctx.getBean(ImportedConfig.class)); + assertThat(ctx.getBean("registrarImportedBean")).isNotNull(); + assertThat(ctx.getBean("otherImportedConfigBean")).isNotNull(); + assertThat(ctx.getBean("importedConfigBean")).isNotNull(); + assertThat(ctx.getBean(ImportedConfig.class)).isNotNull(); } @Test @@ -125,8 +123,7 @@ public class ImportAwareTests { AnnotationMetadata importMetadata = new AnnotationConfigApplicationContext( ConfigurationOne.class, ConfigurationTwo.class) .getBean(MetadataHolder.class).importMetadata; - assertEquals(ConfigurationOne.class, - ((StandardAnnotationMetadata) importMetadata).getIntrospectedClass()); + assertThat(((StandardAnnotationMetadata) importMetadata).getIntrospectedClass()).isEqualTo(ConfigurationOne.class); } @Test @@ -134,8 +131,7 @@ public class ImportAwareTests { AnnotationMetadata importMetadata = new AnnotationConfigApplicationContext( ConfigurationTwo.class, ConfigurationOne.class) .getBean(MetadataHolder.class).importMetadata; - assertEquals(ConfigurationOne.class, - ((StandardAnnotationMetadata) importMetadata).getIntrospectedClass()); + assertThat(((StandardAnnotationMetadata) importMetadata).getIntrospectedClass()).isEqualTo(ConfigurationOne.class); } @Test @@ -398,9 +394,8 @@ public class ImportAwareTests { public void setImportMetadata(AnnotationMetadata annotationMetadata) { AnnotationAttributes enableFeatureAttributes = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(EnableFeature.class.getName())); - assertEquals(EnableFeature.class, enableFeatureAttributes.annotationType()); - Arrays.stream(enableFeatureAttributes.getAnnotationArray("policies")).forEach(featurePolicyAttributes -> - assertEquals(EnableFeature.FeaturePolicy.class, featurePolicyAttributes.annotationType())); + assertThat(enableFeatureAttributes.annotationType()).isEqualTo(EnableFeature.class); + Arrays.stream(enableFeatureAttributes.getAnnotationArray("policies")).forEach(featurePolicyAttributes -> assertThat(featurePolicyAttributes.annotationType()).isEqualTo(EnableFeature.FeaturePolicy.class)); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/LazyAutowiredAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/LazyAutowiredAnnotationBeanPostProcessorTests.java index 887f8278fb2..95aa50b6e20 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/LazyAutowiredAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/LazyAutowiredAnnotationBeanPostProcessorTests.java @@ -29,12 +29,8 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; 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.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -53,13 +49,13 @@ public class LazyAutowiredAnnotationBeanPostProcessorTests { ac.refresh(); TestBeanHolder bean = ac.getBean("annotatedBean", TestBeanHolder.class); - assertFalse(ac.getBeanFactory().containsSingleton("testBean")); - assertNotNull(bean.getTestBean()); - assertNull(bean.getTestBean().getName()); - assertTrue(ac.getBeanFactory().containsSingleton("testBean")); + assertThat(ac.getBeanFactory().containsSingleton("testBean")).isFalse(); + assertThat(bean.getTestBean()).isNotNull(); + assertThat(bean.getTestBean().getName()).isNull(); + assertThat(ac.getBeanFactory().containsSingleton("testBean")).isTrue(); TestBean tb = (TestBean) ac.getBean("testBean"); tb.setName("tb"); - assertSame("tb", bean.getTestBean().getName()); + assertThat(bean.getTestBean().getName()).isSameAs("tb"); } @Test @@ -76,13 +72,13 @@ public class LazyAutowiredAnnotationBeanPostProcessorTests { ac.refresh(); FieldResourceInjectionBean bean = ac.getBean("annotatedBean", FieldResourceInjectionBean.class); - assertFalse(ac.getBeanFactory().containsSingleton("testBean")); - assertFalse(bean.getTestBeans().isEmpty()); - assertNull(bean.getTestBeans().get(0).getName()); - assertTrue(ac.getBeanFactory().containsSingleton("testBean")); + assertThat(ac.getBeanFactory().containsSingleton("testBean")).isFalse(); + assertThat(bean.getTestBeans().isEmpty()).isFalse(); + assertThat(bean.getTestBeans().get(0).getName()).isNull(); + assertThat(ac.getBeanFactory().containsSingleton("testBean")).isTrue(); TestBean tb = (TestBean) ac.getBean("testBean"); tb.setName("tb"); - assertSame("tb", bean.getTestBean().getName()); + assertThat(bean.getTestBean().getName()).isSameAs("tb"); } @Test @@ -132,7 +128,7 @@ public class LazyAutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", bd); FieldResourceInjectionBean bean = (FieldResourceInjectionBean) bf.getBean("annotatedBean"); - assertNotNull(bean.getTestBean()); + assertThat(bean.getTestBean()).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> bean.getTestBean().getName()); } @@ -149,9 +145,9 @@ public class LazyAutowiredAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", bd); OptionalFieldResourceInjectionBean bean = (OptionalFieldResourceInjectionBean) bf.getBean("annotatedBean"); - assertNotNull(bean.getTestBean()); - assertNotNull(bean.getTestBeans()); - assertTrue(bean.getTestBeans().isEmpty()); + assertThat(bean.getTestBean()).isNotNull(); + assertThat(bean.getTestBeans()).isNotNull(); + assertThat(bean.getTestBeans().isEmpty()).isTrue(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> bean.getTestBean().getName()); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/NestedConfigurationClassTests.java b/spring-context/src/test/java/org/springframework/context/annotation/NestedConfigurationClassTests.java index 105227a5570..54cf8bcd8f0 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/NestedConfigurationClassTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/NestedConfigurationClassTests.java @@ -22,9 +22,6 @@ import org.springframework.stereotype.Component; import org.springframework.tests.sample.beans.TestBean; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; /** * Tests ensuring that nested static @Configuration classes are automatically detected @@ -42,7 +39,7 @@ public class NestedConfigurationClassTests { ctx.register(L0Config.L1Config.class); ctx.refresh(); - assertFalse(ctx.containsBean("l0Bean")); + assertThat(ctx.containsBean("l0Bean")).isFalse(); ctx.getBean(L0Config.L1Config.class); ctx.getBean("l1Bean"); @@ -60,15 +57,15 @@ public class NestedConfigurationClassTests { ctx.register(L0Config.class); ctx.refresh(); - assertFalse(ctx.getBeanFactory().containsSingleton("nestedConfigurationClassTests.L0Config")); + assertThat(ctx.getBeanFactory().containsSingleton("nestedConfigurationClassTests.L0Config")).isFalse(); ctx.getBean(L0Config.class); ctx.getBean("l0Bean"); - assertTrue(ctx.getBeanFactory().containsSingleton(L0Config.L1Config.class.getName())); + assertThat(ctx.getBeanFactory().containsSingleton(L0Config.L1Config.class.getName())).isTrue(); ctx.getBean(L0Config.L1Config.class); ctx.getBean("l1Bean"); - assertFalse(ctx.getBeanFactory().containsSingleton(L0Config.L1Config.L2Config.class.getName())); + assertThat(ctx.getBeanFactory().containsSingleton(L0Config.L1Config.L2Config.class.getName())).isFalse(); ctx.getBean(L0Config.L1Config.L2Config.class); ctx.getBean("l2Bean"); @@ -82,15 +79,15 @@ public class NestedConfigurationClassTests { ctx.register(L0ConfigLight.class); ctx.refresh(); - assertFalse(ctx.getBeanFactory().containsSingleton("nestedConfigurationClassTests.L0ConfigLight")); + assertThat(ctx.getBeanFactory().containsSingleton("nestedConfigurationClassTests.L0ConfigLight")).isFalse(); ctx.getBean(L0ConfigLight.class); ctx.getBean("l0Bean"); - assertTrue(ctx.getBeanFactory().containsSingleton(L0ConfigLight.L1ConfigLight.class.getName())); + assertThat(ctx.getBeanFactory().containsSingleton(L0ConfigLight.L1ConfigLight.class.getName())).isTrue(); ctx.getBean(L0ConfigLight.L1ConfigLight.class); ctx.getBean("l1Bean"); - assertFalse(ctx.getBeanFactory().containsSingleton(L0ConfigLight.L1ConfigLight.L2ConfigLight.class.getName())); + assertThat(ctx.getBeanFactory().containsSingleton(L0ConfigLight.L1ConfigLight.L2ConfigLight.class.getName())).isFalse(); ctx.getBean(L0ConfigLight.L1ConfigLight.L2ConfigLight.class); ctx.getBean("l2Bean"); @@ -105,9 +102,9 @@ public class NestedConfigurationClassTests { ctx.refresh(); S1Config config = ctx.getBean(S1Config.class); - assertTrue(config != ctx.getBean(S1Config.class)); + assertThat(config != ctx.getBean(S1Config.class)).isTrue(); TestBean tb = ctx.getBean("l0Bean", TestBean.class); - assertTrue(tb == ctx.getBean("l0Bean", TestBean.class)); + assertThat(tb == ctx.getBean("l0Bean", TestBean.class)).isTrue(); ctx.getBean(L0Config.L1Config.class); ctx.getBean("l1Bean"); @@ -118,12 +115,12 @@ public class NestedConfigurationClassTests { // ensure that override order is correct and that it is a singleton TestBean ob = ctx.getBean("overrideBean", TestBean.class); assertThat(ob.getName()).isEqualTo("override-s1"); - assertTrue(ob == ctx.getBean("overrideBean", TestBean.class)); + assertThat(ob == ctx.getBean("overrideBean", TestBean.class)).isTrue(); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); TestBean pb2 = ctx.getBean("prototypeBean", TestBean.class); - assertTrue(pb1 != pb2); - assertTrue(pb1.getFriends().iterator().next() != pb2.getFriends().iterator().next()); + assertThat(pb1 != pb2).isTrue(); + assertThat(pb1.getFriends().iterator().next() != pb2.getFriends().iterator().next()).isTrue(); } @Test @@ -133,9 +130,9 @@ public class NestedConfigurationClassTests { ctx.refresh(); S1Config config = ctx.getBean(S1Config.class); - assertTrue(config != ctx.getBean(S1Config.class)); + assertThat(config != ctx.getBean(S1Config.class)).isTrue(); TestBean tb = ctx.getBean("l0Bean", TestBean.class); - assertTrue(tb == ctx.getBean("l0Bean", TestBean.class)); + assertThat(tb == ctx.getBean("l0Bean", TestBean.class)).isTrue(); ctx.getBean(L0Config.L1Config.class); ctx.getBean("l1Bean"); @@ -146,12 +143,12 @@ public class NestedConfigurationClassTests { // ensure that override order is correct and that it is a singleton TestBean ob = ctx.getBean("overrideBean", TestBean.class); assertThat(ob.getName()).isEqualTo("override-s1"); - assertTrue(ob == ctx.getBean("overrideBean", TestBean.class)); + assertThat(ob == ctx.getBean("overrideBean", TestBean.class)).isTrue(); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); TestBean pb2 = ctx.getBean("prototypeBean", TestBean.class); - assertTrue(pb1 != pb2); - assertTrue(pb1.getFriends().iterator().next() != pb2.getFriends().iterator().next()); + assertThat(pb1 != pb2).isTrue(); + assertThat(pb1.getFriends().iterator().next() != pb2.getFriends().iterator().next()).isTrue(); } @Test @@ -161,9 +158,9 @@ public class NestedConfigurationClassTests { ctx.refresh(); S1ConfigWithProxy config = ctx.getBean(S1ConfigWithProxy.class); - assertTrue(config == ctx.getBean(S1ConfigWithProxy.class)); + assertThat(config == ctx.getBean(S1ConfigWithProxy.class)).isTrue(); TestBean tb = ctx.getBean("l0Bean", TestBean.class); - assertTrue(tb == ctx.getBean("l0Bean", TestBean.class)); + assertThat(tb == ctx.getBean("l0Bean", TestBean.class)).isTrue(); ctx.getBean(L0Config.L1Config.class); ctx.getBean("l1Bean"); @@ -174,12 +171,12 @@ public class NestedConfigurationClassTests { // ensure that override order is correct and that it is a singleton TestBean ob = ctx.getBean("overrideBean", TestBean.class); assertThat(ob.getName()).isEqualTo("override-s1"); - assertTrue(ob == ctx.getBean("overrideBean", TestBean.class)); + assertThat(ob == ctx.getBean("overrideBean", TestBean.class)).isTrue(); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); TestBean pb2 = ctx.getBean("prototypeBean", TestBean.class); - assertTrue(pb1 != pb2); - assertTrue(pb1.getFriends().iterator().next() != pb2.getFriends().iterator().next()); + assertThat(pb1 != pb2).isTrue(); + assertThat(pb1.getFriends().iterator().next() != pb2.getFriends().iterator().next()).isTrue(); } @Test @@ -188,19 +185,19 @@ public class NestedConfigurationClassTests { ctx.register(L0ConfigEmpty.class); ctx.refresh(); - assertFalse(ctx.getBeanFactory().containsSingleton("l0ConfigEmpty")); + assertThat(ctx.getBeanFactory().containsSingleton("l0ConfigEmpty")).isFalse(); Object l0i1 = ctx.getBean(L0ConfigEmpty.class); Object l0i2 = ctx.getBean(L0ConfigEmpty.class); - assertTrue(l0i1 == l0i2); + assertThat(l0i1 == l0i2).isTrue(); Object l1i1 = ctx.getBean(L0ConfigEmpty.L1ConfigEmpty.class); Object l1i2 = ctx.getBean(L0ConfigEmpty.L1ConfigEmpty.class); - assertTrue(l1i1 != l1i2); + assertThat(l1i1 != l1i2).isTrue(); Object l2i1 = ctx.getBean(L0ConfigEmpty.L1ConfigEmpty.L2ConfigEmpty.class); Object l2i2 = ctx.getBean(L0ConfigEmpty.L1ConfigEmpty.L2ConfigEmpty.class); - assertTrue(l2i1 == l2i2); - assertNotEquals(l2i1.toString(), l2i2.toString()); + assertThat(l2i1 == l2i2).isTrue(); + assertThat(l2i2.toString()).isNotEqualTo(l2i1.toString()); } @Test @@ -209,19 +206,19 @@ public class NestedConfigurationClassTests { ctx.register(L0ConfigConcrete.class); ctx.refresh(); - assertFalse(ctx.getBeanFactory().containsSingleton("l0ConfigConcrete")); + assertThat(ctx.getBeanFactory().containsSingleton("l0ConfigConcrete")).isFalse(); Object l0i1 = ctx.getBean(L0ConfigConcrete.class); Object l0i2 = ctx.getBean(L0ConfigConcrete.class); - assertTrue(l0i1 == l0i2); + assertThat(l0i1 == l0i2).isTrue(); Object l1i1 = ctx.getBean(L0ConfigConcrete.L1ConfigEmpty.class); Object l1i2 = ctx.getBean(L0ConfigConcrete.L1ConfigEmpty.class); - assertTrue(l1i1 != l1i2); + assertThat(l1i1 != l1i2).isTrue(); Object l2i1 = ctx.getBean(L0ConfigConcrete.L1ConfigEmpty.L2ConfigEmpty.class); Object l2i2 = ctx.getBean(L0ConfigConcrete.L1ConfigEmpty.L2ConfigEmpty.class); - assertTrue(l2i1 == l2i2); - assertNotEquals(l2i1.toString(), l2i2.toString()); + assertThat(l2i1 == l2i2).isTrue(); + assertThat(l2i2.toString()).isNotEqualTo(l2i1.toString()); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java index d5c44db657c..650497ae9a9 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java @@ -40,7 +40,6 @@ 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.junit.Assert.assertTrue; /** * Tests the processing of @PropertySource annotations on @Configuration classes. @@ -57,8 +56,7 @@ public class PropertySourceAnnotationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConfigWithExplicitName.class); ctx.refresh(); - assertTrue("property source p1 was not added", - ctx.getEnvironment().getPropertySources().contains("p1")); + assertThat(ctx.getEnvironment().getPropertySources().contains("p1")).as("property source p1 was not added").isTrue(); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean"); // assert that the property source was added last to the set of sources @@ -78,8 +76,7 @@ public class PropertySourceAnnotationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConfigWithImplicitName.class); ctx.refresh(); - assertTrue("property source p1 was not added", - ctx.getEnvironment().getPropertySources().contains("class path resource [org/springframework/context/annotation/p1.properties]")); + assertThat(ctx.getEnvironment().getPropertySources().contains("class path resource [org/springframework/context/annotation/p1.properties]")).as("property source p1 was not added").isTrue(); assertThat(ctx.getBean(TestBean.class).getName()).isEqualTo("p1TestBean"); } @@ -88,8 +85,8 @@ public class PropertySourceAnnotationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(ConfigWithTestProfileBeans.class); ctx.refresh(); - assertTrue(ctx.containsBean("testBean")); - assertTrue(ctx.containsBean("testProfileBean")); + assertThat(ctx.containsBean("testBean")).isTrue(); + assertThat(ctx.containsBean("testProfileBean")).isTrue(); } /** @@ -139,7 +136,7 @@ public class PropertySourceAnnotationTests { ctx.refresh(); } catch (BeanDefinitionStoreException ex) { - assertTrue(ex.getCause() instanceof IllegalArgumentException); + assertThat(ex.getCause() instanceof IllegalArgumentException).isTrue(); } } @@ -179,7 +176,7 @@ public class PropertySourceAnnotationTests { ctx.refresh(); } catch (BeanDefinitionStoreException ex) { - assertTrue(ex.getCause() instanceof IllegalArgumentException); + assertThat(ex.getCause() instanceof IllegalArgumentException).isTrue(); } } @@ -398,7 +395,7 @@ public class PropertySourceAnnotationTests { public static class MyCustomFactory implements PropertySourceFactory { @Override - public org.springframework.core.env.PropertySource createPropertySource(String name, EncodedResource resource) throws IOException { + public org.springframework.core.env.PropertySource createPropertySource(String name, EncodedResource resource) throws IOException { Properties props = PropertiesLoaderUtils.loadProperties(resource); return new org.springframework.core.env.PropertySource("my" + name, props) { @Override diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ReflectionUtilsIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ReflectionUtilsIntegrationTests.java index 20d4538233b..9f06cc1db6e 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ReflectionUtilsIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ReflectionUtilsIntegrationTests.java @@ -23,7 +23,6 @@ import org.junit.Test; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Tests ReflectionUtils methods as used against CGLIB-generated classes created @@ -48,7 +47,7 @@ public class ReflectionUtilsIntegrationTests { assertThat(m1MethodCount).isEqualTo(1); for (Method method : methods) { if (method.getName().contains("m1")) { - assertEquals(method.getReturnType(), Integer.class); + assertThat(Integer.class).isEqualTo(method.getReturnType()); } } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/SimpleConfigTests.java b/spring-context/src/test/java/org/springframework/context/annotation/SimpleConfigTests.java index 548d9357ae3..d90d1262f4b 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/SimpleConfigTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/SimpleConfigTests.java @@ -25,8 +25,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -42,16 +41,17 @@ public class SimpleConfigTests { ServiceInvocationCounter serviceInvocationCounter = ctx.getBean("serviceInvocationCounter", ServiceInvocationCounter.class); String value = fooService.foo(1); - assertEquals("bar", value); + assertThat(value).isEqualTo("bar"); Future future = fooService.asyncFoo(1); - assertTrue(future instanceof FutureTask); - assertEquals("bar", future.get()); + boolean condition = future instanceof FutureTask; + assertThat(condition).isTrue(); + assertThat(future.get()).isEqualTo("bar"); - assertEquals(2, serviceInvocationCounter.getCount()); + assertThat(serviceInvocationCounter.getCount()).isEqualTo(2); fooService.foo(1); - assertEquals(3, serviceInvocationCounter.getCount()); + assertThat(serviceInvocationCounter.getCount()).isEqualTo(3); } public String[] getConfigLocations() { diff --git a/spring-context/src/test/java/org/springframework/context/annotation/SimpleScanTests.java b/spring-context/src/test/java/org/springframework/context/annotation/SimpleScanTests.java index 55289fdb60c..df26c5731fa 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/SimpleScanTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/SimpleScanTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -43,17 +42,17 @@ public class SimpleScanTests { FooService fooService = (FooService) ctx.getBean("fooServiceImpl"); ServiceInvocationCounter serviceInvocationCounter = (ServiceInvocationCounter) ctx.getBean("serviceInvocationCounter"); - assertEquals(0, serviceInvocationCounter.getCount()); + assertThat(serviceInvocationCounter.getCount()).isEqualTo(0); - assertTrue(fooService.isInitCalled()); - assertEquals(1, serviceInvocationCounter.getCount()); + assertThat(fooService.isInitCalled()).isTrue(); + assertThat(serviceInvocationCounter.getCount()).isEqualTo(1); String value = fooService.foo(1); - assertEquals("bar", value); - assertEquals(2, serviceInvocationCounter.getCount()); + assertThat(value).isEqualTo("bar"); + assertThat(serviceInvocationCounter.getCount()).isEqualTo(2); fooService.foo(1); - assertEquals(3, serviceInvocationCounter.getCount()); + assertThat(serviceInvocationCounter.getCount()).isEqualTo(3); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/Spr11202Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/Spr11202Tests.java index 9aa57c024d3..45df0cc571b 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/Spr11202Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/Spr11202Tests.java @@ -31,7 +31,7 @@ import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -41,13 +41,13 @@ public class Spr11202Tests { @Test public void testWithImporter() { ApplicationContext context = new AnnotationConfigApplicationContext(Wrapper.class); - assertEquals("foo", context.getBean("value")); + assertThat(context.getBean("value")).isEqualTo("foo"); } @Test public void testWithoutImporter() { ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); - assertEquals("foo", context.getBean("value")); + assertThat(context.getBean("value")).isEqualTo("foo"); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/Spr11310Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/Spr11310Tests.java index 7fcf59d9b81..0d2288bc2e0 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/Spr11310Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/Spr11310Tests.java @@ -24,7 +24,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.annotation.Order; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -35,18 +35,18 @@ public class Spr11310Tests { public void orderedList() { ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); StringHolder holder = context.getBean(StringHolder.class); - assertEquals("second", holder.itemsList.get(0)); - assertEquals("first", holder.itemsList.get(1)); - assertEquals("unknownOrder", holder.itemsList.get(2)); + assertThat(holder.itemsList.get(0)).isEqualTo("second"); + assertThat(holder.itemsList.get(1)).isEqualTo("first"); + assertThat(holder.itemsList.get(2)).isEqualTo("unknownOrder"); } @Test public void orderedArray() { ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); StringHolder holder = context.getBean(StringHolder.class); - assertEquals("second", holder.itemsArray[0]); - assertEquals("first", holder.itemsArray[1]); - assertEquals("unknownOrder", holder.itemsArray[2]); + assertThat(holder.itemsArray[0]).isEqualTo("second"); + assertThat(holder.itemsArray[1]).isEqualTo("first"); + assertThat(holder.itemsArray[2]).isEqualTo("unknownOrder"); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/Spr12636Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/Spr12636Tests.java index db4523f4652..13466fb8369 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/Spr12636Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/Spr12636Tests.java @@ -29,8 +29,7 @@ import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Component; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -51,8 +50,8 @@ public class Spr12636Tests { this.context = new AnnotationConfigApplicationContext( UserServiceTwo.class, UserServiceOne.class, UserServiceCollector.class); UserServiceCollector bean = this.context.getBean(UserServiceCollector.class); - assertSame(context.getBean("serviceOne", UserService.class), bean.userServices.get(0)); - assertSame(context.getBean("serviceTwo", UserService.class), bean.userServices.get(1)); + assertThat(bean.userServices.get(0)).isSameAs(context.getBean("serviceOne", UserService.class)); + assertThat(bean.userServices.get(1)).isSameAs(context.getBean("serviceTwo", UserService.class)); } @@ -64,12 +63,12 @@ public class Spr12636Tests { // Validate those beans are indeed wrapped by a proxy UserService serviceOne = this.context.getBean("serviceOne", UserService.class); UserService serviceTwo = this.context.getBean("serviceTwo", UserService.class); - assertTrue(AopUtils.isAopProxy(serviceOne)); - assertTrue(AopUtils.isAopProxy(serviceTwo)); + assertThat(AopUtils.isAopProxy(serviceOne)).isTrue(); + assertThat(AopUtils.isAopProxy(serviceTwo)).isTrue(); UserServiceCollector bean = this.context.getBean(UserServiceCollector.class); - assertSame(serviceOne, bean.userServices.get(0)); - assertSame(serviceTwo, bean.userServices.get(1)); + assertThat(bean.userServices.get(0)).isSameAs(serviceOne); + assertThat(bean.userServices.get(1)).isSameAs(serviceTwo); } @Configuration diff --git a/spring-context/src/test/java/org/springframework/context/annotation/Spr15275Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/Spr15275Tests.java index eda88222130..75bc0338f32 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/Spr15275Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/Spr15275Tests.java @@ -22,10 +22,7 @@ import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.config.AbstractFactoryBean; import org.springframework.context.ApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -35,44 +32,44 @@ public class Spr15275Tests { @Test public void testWithFactoryBean() { ApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithFactoryBean.class); - assertEquals("x", context.getBean(Bar.class).foo.toString()); - assertSame(context.getBean(FooInterface.class), context.getBean(Bar.class).foo); + assertThat(context.getBean(Bar.class).foo.toString()).isEqualTo("x"); + assertThat(context.getBean(Bar.class).foo).isSameAs(context.getBean(FooInterface.class)); } @Test public void testWithAbstractFactoryBean() { ApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithAbstractFactoryBean.class); - assertEquals("x", context.getBean(Bar.class).foo.toString()); - assertSame(context.getBean(FooInterface.class), context.getBean(Bar.class).foo); + assertThat(context.getBean(Bar.class).foo.toString()).isEqualTo("x"); + assertThat(context.getBean(Bar.class).foo).isSameAs(context.getBean(FooInterface.class)); } @Test public void testWithAbstractFactoryBeanForInterface() { ApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithAbstractFactoryBeanForInterface.class); - assertEquals("x", context.getBean(Bar.class).foo.toString()); - assertSame(context.getBean(FooInterface.class), context.getBean(Bar.class).foo); + assertThat(context.getBean(Bar.class).foo.toString()).isEqualTo("x"); + assertThat(context.getBean(Bar.class).foo).isSameAs(context.getBean(FooInterface.class)); } @Test public void testWithAbstractFactoryBeanAsReturnType() { ApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithAbstractFactoryBeanAsReturnType.class); - assertEquals("x", context.getBean(Bar.class).foo.toString()); - assertSame(context.getBean(FooInterface.class), context.getBean(Bar.class).foo); + assertThat(context.getBean(Bar.class).foo.toString()).isEqualTo("x"); + assertThat(context.getBean(Bar.class).foo).isSameAs(context.getBean(FooInterface.class)); } @Test public void testWithFinalFactoryBean() { ApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithFinalFactoryBean.class); - assertEquals("x", context.getBean(Bar.class).foo.toString()); - assertSame(context.getBean(FooInterface.class), context.getBean(Bar.class).foo); + assertThat(context.getBean(Bar.class).foo.toString()).isEqualTo("x"); + assertThat(context.getBean(Bar.class).foo).isSameAs(context.getBean(FooInterface.class)); } @Test public void testWithFinalFactoryBeanAsReturnType() { ApplicationContext context = new AnnotationConfigApplicationContext(ConfigWithFinalFactoryBeanAsReturnType.class); - assertEquals("x", context.getBean(Bar.class).foo.toString()); + assertThat(context.getBean(Bar.class).foo.toString()).isEqualTo("x"); // not same due to fallback to raw FinalFactoryBean instance with repeated getObject() invocations - assertNotSame(context.getBean(FooInterface.class), context.getBean(Bar.class).foo); + assertThat(context.getBean(Bar.class).foo).isNotSameAs(context.getBean(FooInterface.class)); } @@ -95,7 +92,7 @@ public class Spr15275Tests { @Bean public Bar bar() throws Exception { - assertTrue(foo().isSingleton()); + assertThat(foo().isSingleton()).isTrue(); return new Bar(foo().getObject()); } } @@ -120,7 +117,7 @@ public class Spr15275Tests { @Bean public Bar bar() throws Exception { - assertTrue(foo().isSingleton()); + assertThat(foo().isSingleton()).isTrue(); return new Bar(foo().getObject()); } } @@ -145,7 +142,7 @@ public class Spr15275Tests { @Bean public Bar bar() throws Exception { - assertTrue(foo().isSingleton()); + assertThat(foo().isSingleton()).isTrue(); return new Bar(foo().getObject()); } } @@ -170,7 +167,7 @@ public class Spr15275Tests { @Bean public Bar bar() throws Exception { - assertTrue(foo().isSingleton()); + assertThat(foo().isSingleton()).isTrue(); return new Bar(foo().getObject()); } } @@ -186,7 +183,7 @@ public class Spr15275Tests { @Bean public Bar bar() throws Exception { - assertTrue(foo().isSingleton()); + assertThat(foo().isSingleton()).isTrue(); return new Bar(foo().getObject()); } } @@ -202,7 +199,7 @@ public class Spr15275Tests { @Bean public Bar bar() throws Exception { - assertTrue(foo().isSingleton()); + assertThat(foo().isSingleton()).isTrue(); return new Bar(foo().getObject()); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/Spr16179Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/Spr16179Tests.java index 99ddd1f3d90..5a05c18e6b0 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/Spr16179Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/Spr16179Tests.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -33,13 +33,13 @@ public class Spr16179Tests { AnnotationConfigApplicationContext bf = new AnnotationConfigApplicationContext(AssemblerConfig.class, AssemblerInjection.class); - assertSame(bf.getBean("someAssembler"), bf.getBean(AssemblerInjection.class).assembler0); + assertThat(bf.getBean(AssemblerInjection.class).assembler0).isSameAs(bf.getBean("someAssembler")); // assertNull(bf.getBean(AssemblerInjection.class).assembler1); TODO: accidental match // assertNull(bf.getBean(AssemblerInjection.class).assembler2); - assertSame(bf.getBean("pageAssembler"), bf.getBean(AssemblerInjection.class).assembler3); - assertSame(bf.getBean("pageAssembler"), bf.getBean(AssemblerInjection.class).assembler4); - assertSame(bf.getBean("pageAssembler"), bf.getBean(AssemblerInjection.class).assembler5); - assertSame(bf.getBean("pageAssembler"), bf.getBean(AssemblerInjection.class).assembler6); + assertThat(bf.getBean(AssemblerInjection.class).assembler3).isSameAs(bf.getBean("pageAssembler")); + assertThat(bf.getBean(AssemblerInjection.class).assembler4).isSameAs(bf.getBean("pageAssembler")); + assertThat(bf.getBean(AssemblerInjection.class).assembler5).isSameAs(bf.getBean("pageAssembler")); + assertThat(bf.getBean(AssemblerInjection.class).assembler6).isSameAs(bf.getBean("pageAssembler")); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/Spr3775InitDestroyLifecycleTests.java b/spring-context/src/test/java/org/springframework/context/annotation/Spr3775InitDestroyLifecycleTests.java index 012344e89ac..6f6d0a5b0a5 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/Spr3775InitDestroyLifecycleTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/Spr3775InitDestroyLifecycleTests.java @@ -32,7 +32,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.util.ObjectUtils; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** *

@@ -72,8 +72,7 @@ public class Spr3775InitDestroyLifecycleTests { private void assertMethodOrdering(Class clazz, String category, List expectedMethods, List actualMethods) { debugMethods(clazz, category, actualMethods); - assertTrue("Verifying " + category + ": expected<" + expectedMethods + "> but got<" + actualMethods + ">.", - ObjectUtils.nullSafeEquals(expectedMethods, actualMethods)); + assertThat(ObjectUtils.nullSafeEquals(expectedMethods, actualMethods)).as("Verifying " + category + ": expected<" + expectedMethods + "> but got<" + actualMethods + ">.").isTrue(); } private DefaultListableBeanFactory createBeanFactoryAndRegisterBean(final Class beanClass, diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/AutowiredConfigurationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/AutowiredConfigurationTests.java index db13aa174aa..6f7296d8b5c 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/AutowiredConfigurationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/AutowiredConfigurationTests.java @@ -45,9 +45,6 @@ import org.springframework.tests.sample.beans.Colour; import org.springframework.tests.sample.beans.TestBean; 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; /** * System tests covering use of {@link Autowired} and {@link Value} within @@ -91,7 +88,7 @@ public class AutowiredConfigurationTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( OptionalAutowiredMethodConfig.class); - assertTrue(context.getBeansOfType(Colour.class).isEmpty()); + assertThat(context.getBeansOfType(Colour.class).isEmpty()).isTrue(); assertThat(context.getBean(TestBean.class).getName()).isEqualTo(""); } @@ -104,7 +101,7 @@ public class AutowiredConfigurationTests { ctx.registerBeanDefinition("config1", new RootBeanDefinition(AutowiredConstructorConfig.class)); ctx.registerBeanDefinition("config2", new RootBeanDefinition(ColorConfig.class)); ctx.refresh(); - assertSame(ctx.getBean(AutowiredConstructorConfig.class).colour, ctx.getBean(Colour.class)); + assertThat(ctx.getBean(Colour.class)).isSameAs(ctx.getBean(AutowiredConstructorConfig.class).colour); } @Test @@ -116,7 +113,7 @@ public class AutowiredConfigurationTests { ctx.registerBeanDefinition("config1", new RootBeanDefinition(ObjectFactoryConstructorConfig.class)); ctx.registerBeanDefinition("config2", new RootBeanDefinition(ColorConfig.class)); ctx.refresh(); - assertSame(ctx.getBean(ObjectFactoryConstructorConfig.class).colour, ctx.getBean(Colour.class)); + assertThat(ctx.getBean(Colour.class)).isSameAs(ctx.getBean(ObjectFactoryConstructorConfig.class).colour); } @Test @@ -128,7 +125,7 @@ public class AutowiredConfigurationTests { ctx.registerBeanDefinition("config1", new RootBeanDefinition(MultipleConstructorConfig.class)); ctx.registerBeanDefinition("config2", new RootBeanDefinition(ColorConfig.class)); ctx.refresh(); - assertSame(ctx.getBean(MultipleConstructorConfig.class).colour, ctx.getBean(Colour.class)); + assertThat(ctx.getBean(Colour.class)).isSameAs(ctx.getBean(MultipleConstructorConfig.class).colour); } @Test @@ -177,10 +174,10 @@ public class AutowiredConfigurationTests { System.clearProperty("myProp"); TestBean testBean = context.getBean("testBean", TestBean.class); - assertNull(testBean.getName()); + assertThat((Object) testBean.getName()).isNull(); testBean = context.getBean("testBean2", TestBean.class); - assertNull(testBean.getName()); + assertThat((Object) testBean.getName()).isNull(); System.setProperty("myProp", "foo"); @@ -193,10 +190,10 @@ public class AutowiredConfigurationTests { System.clearProperty("myProp"); testBean = context.getBean("testBean", TestBean.class); - assertNull(testBean.getName()); + assertThat((Object) testBean.getName()).isNull(); testBean = context.getBean("testBean2", TestBean.class); - assertNull(testBean.getName()); + assertThat((Object) testBean.getName()).isNull(); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanAnnotationAttributePropagationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanAnnotationAttributePropagationTests.java index 7a80f066305..e4522ad5404 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanAnnotationAttributePropagationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanAnnotationAttributePropagationTests.java @@ -30,10 +30,7 @@ import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Primary; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests proving that the various attributes available via the {@link Bean} @@ -55,8 +52,7 @@ public class BeanAnnotationAttributePropagationTests { @Bean(autowire=Autowire.BY_TYPE) Object foo() { return null; } } - assertEquals("autowire mode was not propagated", - AbstractBeanDefinition.AUTOWIRE_BY_TYPE, beanDef(Config.class).getAutowireMode()); + assertThat(beanDef(Config.class).getAutowireMode()).as("autowire mode was not propagated").isEqualTo(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); } @Test @@ -65,8 +61,7 @@ public class BeanAnnotationAttributePropagationTests { @Bean(autowireCandidate=false) Object foo() { return null; } } - assertFalse("autowire candidate flag was not propagated", - beanDef(Config.class).isAutowireCandidate()); + assertThat(beanDef(Config.class).isAutowireCandidate()).as("autowire candidate flag was not propagated").isFalse(); } @Test @@ -75,8 +70,7 @@ public class BeanAnnotationAttributePropagationTests { @Bean(initMethod="start") Object foo() { return null; } } - assertEquals("init method name was not propagated", - "start", beanDef(Config.class).getInitMethodName()); + assertThat(beanDef(Config.class).getInitMethodName()).as("init method name was not propagated").isEqualTo("start"); } @Test @@ -85,8 +79,7 @@ public class BeanAnnotationAttributePropagationTests { @Bean(destroyMethod="destroy") Object foo() { return null; } } - assertEquals("destroy method name was not propagated", - "destroy", beanDef(Config.class).getDestroyMethodName()); + assertThat(beanDef(Config.class).getDestroyMethodName()).as("destroy method name was not propagated").isEqualTo("destroy"); } @Test @@ -95,8 +88,7 @@ public class BeanAnnotationAttributePropagationTests { @Bean() @DependsOn({"bar", "baz"}) Object foo() { return null; } } - assertArrayEquals("dependsOn metadata was not propagated", - new String[] {"bar", "baz"}, beanDef(Config.class).getDependsOn()); + assertThat(beanDef(Config.class).getDependsOn()).as("dependsOn metadata was not propagated").isEqualTo(new String[] {"bar", "baz"}); } @Test @@ -106,8 +98,7 @@ public class BeanAnnotationAttributePropagationTests { Object foo() { return null; } } - assertTrue("primary metadata was not propagated", - beanDef(Config.class).isPrimary()); + assertThat(beanDef(Config.class).isPrimary()).as("primary metadata was not propagated").isTrue(); } @Test @@ -116,8 +107,7 @@ public class BeanAnnotationAttributePropagationTests { @Bean Object foo() { return null; } } - assertFalse("@Bean methods should be non-primary by default", - beanDef(Config.class).isPrimary()); + assertThat(beanDef(Config.class).isPrimary()).as("@Bean methods should be non-primary by default").isFalse(); } @Test @@ -127,8 +117,7 @@ public class BeanAnnotationAttributePropagationTests { Object foo() { return null; } } - assertTrue("lazy metadata was not propagated", - beanDef(Config.class).isLazyInit()); + assertThat(beanDef(Config.class).isLazyInit()).as("lazy metadata was not propagated").isTrue(); } @Test @@ -137,8 +126,7 @@ public class BeanAnnotationAttributePropagationTests { @Bean Object foo() { return null; } } - assertFalse("@Bean methods should be non-lazy by default", - beanDef(Config.class).isLazyInit()); + assertThat(beanDef(Config.class).isLazyInit()).as("@Bean methods should be non-lazy by default").isFalse(); } @Test @@ -147,8 +135,7 @@ public class BeanAnnotationAttributePropagationTests { @Bean Object foo() { return null; } } - assertTrue("@Bean methods declared in a @Lazy @Configuration should be lazily instantiated", - beanDef(Config.class).isLazyInit()); + assertThat(beanDef(Config.class).isLazyInit()).as("@Bean methods declared in a @Lazy @Configuration should be lazily instantiated").isTrue(); } @Test @@ -157,8 +144,7 @@ public class BeanAnnotationAttributePropagationTests { @Lazy(false) @Bean Object foo() { return null; } } - assertFalse("@Lazy(false) @Bean methods declared in a @Lazy @Configuration should be eagerly instantiated", - beanDef(Config.class).isLazyInit()); + assertThat(beanDef(Config.class).isLazyInit()).as("@Lazy(false) @Bean methods declared in a @Lazy @Configuration should be eagerly instantiated").isFalse(); } @Test @@ -167,8 +153,7 @@ public class BeanAnnotationAttributePropagationTests { @Bean Object foo() { return null; } } - assertFalse("@Lazy(false) @Configuration should produce eager bean definitions", - beanDef(Config.class).isLazyInit()); + assertThat(beanDef(Config.class).isLazyInit()).as("@Lazy(false) @Configuration should produce eager bean definitions").isFalse(); } private AbstractBeanDefinition beanDef(Class configClass) { diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanMethodQualificationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanMethodQualificationTests.java index 4a47bff1860..e991ec2d2e1 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanMethodQualificationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanMethodQualificationTests.java @@ -36,9 +36,6 @@ import org.springframework.tests.sample.beans.NestedTestBean; import org.springframework.tests.sample.beans.TestBean; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Tests proving that @Qualifier annotations work when used @@ -53,7 +50,7 @@ public class BeanMethodQualificationTests { public void testStandard() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(StandardConfig.class, StandardPojo.class); - assertFalse(ctx.getBeanFactory().containsSingleton("testBean1")); + assertThat(ctx.getBeanFactory().containsSingleton("testBean1")).isFalse(); StandardPojo pojo = ctx.getBean(StandardPojo.class); assertThat(pojo.testBean.getName()).isEqualTo("interesting"); assertThat(pojo.testBean2.getName()).isEqualTo("boring"); @@ -63,7 +60,7 @@ public class BeanMethodQualificationTests { public void testScoped() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ScopedConfig.class, StandardPojo.class); - assertFalse(ctx.getBeanFactory().containsSingleton("testBean1")); + assertThat(ctx.getBeanFactory().containsSingleton("testBean1")).isFalse(); StandardPojo pojo = ctx.getBean(StandardPojo.class); assertThat(pojo.testBean.getName()).isEqualTo("interesting"); assertThat(pojo.testBean2.getName()).isEqualTo("boring"); @@ -73,7 +70,7 @@ public class BeanMethodQualificationTests { public void testScopedProxy() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ScopedProxyConfig.class, StandardPojo.class); - assertTrue(ctx.getBeanFactory().containsSingleton("testBean1")); // a shared scoped proxy + assertThat(ctx.getBeanFactory().containsSingleton("testBean1")).isTrue(); // a shared scoped proxy StandardPojo pojo = ctx.getBean(StandardPojo.class); assertThat(pojo.testBean.getName()).isEqualTo("interesting"); assertThat(pojo.testBean2.getName()).isEqualTo("boring"); @@ -83,10 +80,10 @@ public class BeanMethodQualificationTests { public void testCustomWithLazyResolution() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CustomConfig.class, CustomPojo.class); - assertFalse(ctx.getBeanFactory().containsSingleton("testBean1")); - assertFalse(ctx.getBeanFactory().containsSingleton("testBean2")); - assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"), - "testBean2", ctx.getDefaultListableBeanFactory())); + assertThat(ctx.getBeanFactory().containsSingleton("testBean1")).isFalse(); + assertThat(ctx.getBeanFactory().containsSingleton("testBean2")).isFalse(); + assertThat(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"), + "testBean2", ctx.getDefaultListableBeanFactory())).isTrue(); CustomPojo pojo = ctx.getBean(CustomPojo.class); assertThat(pojo.testBean.getName()).isEqualTo("interesting"); TestBean testBean2 = BeanFactoryAnnotationUtils.qualifiedBeanOfType( @@ -99,11 +96,11 @@ public class BeanMethodQualificationTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(CustomConfig.class, CustomPojo.class); ctx.refresh(); - assertFalse(ctx.getBeanFactory().containsSingleton("testBean1")); - assertFalse(ctx.getBeanFactory().containsSingleton("testBean2")); + assertThat(ctx.getBeanFactory().containsSingleton("testBean1")).isFalse(); + assertThat(ctx.getBeanFactory().containsSingleton("testBean2")).isFalse(); ctx.getBean("testBean2"); - assertTrue(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"), - "testBean2", ctx.getDefaultListableBeanFactory())); + assertThat(BeanFactoryAnnotationUtils.isQualifierMatch(value -> value.equals("boring"), + "testBean2", ctx.getDefaultListableBeanFactory())).isTrue(); CustomPojo pojo = ctx.getBean(CustomPojo.class); assertThat(pojo.testBean.getName()).isEqualTo("interesting"); } @@ -116,8 +113,8 @@ public class BeanMethodQualificationTests { customPojo.setLazyInit(true); ctx.registerBeanDefinition("customPojo", customPojo); ctx.refresh(); - assertFalse(ctx.getBeanFactory().containsSingleton("testBean1")); - assertFalse(ctx.getBeanFactory().containsSingleton("testBean2")); + assertThat(ctx.getBeanFactory().containsSingleton("testBean1")).isFalse(); + assertThat(ctx.getBeanFactory().containsSingleton("testBean2")).isFalse(); CustomPojo pojo = ctx.getBean(CustomPojo.class); assertThat(pojo.testBean.getName()).isEqualTo("interesting"); } @@ -126,7 +123,7 @@ public class BeanMethodQualificationTests { public void testCustomWithAttributeOverride() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CustomConfigWithAttributeOverride.class, CustomPojo.class); - assertFalse(ctx.getBeanFactory().containsSingleton("testBeanX")); + assertThat(ctx.getBeanFactory().containsSingleton("testBeanX")).isFalse(); CustomPojo pojo = ctx.getBean(CustomPojo.class); assertThat(pojo.testBean.getName()).isEqualTo("interesting"); } @@ -134,11 +131,10 @@ public class BeanMethodQualificationTests { @Test public void testBeanNamesForAnnotation() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(StandardConfig.class); - assertArrayEquals(new String[] {"beanMethodQualificationTests.StandardConfig"}, - ctx.getBeanNamesForAnnotation(Configuration.class)); - assertArrayEquals(new String[] {}, ctx.getBeanNamesForAnnotation(Scope.class)); - assertArrayEquals(new String[] {"testBean1"}, ctx.getBeanNamesForAnnotation(Lazy.class)); - assertArrayEquals(new String[] {"testBean2"}, ctx.getBeanNamesForAnnotation(Boring.class)); + assertThat(ctx.getBeanNamesForAnnotation(Configuration.class)).isEqualTo(new String[] {"beanMethodQualificationTests.StandardConfig"}); + assertThat(ctx.getBeanNamesForAnnotation(Scope.class)).isEqualTo(new String[] {}); + assertThat(ctx.getBeanNamesForAnnotation(Lazy.class)).isEqualTo(new String[] {"testBean1"}); + assertThat(ctx.getBeanNamesForAnnotation(Boring.class)).isEqualTo(new String[] {"testBean2"}); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java index 7d866c460df..f443cbbe6d3 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java @@ -58,13 +58,8 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.NestedTestBean; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Miscellaneous system tests covering {@link Bean} naming, aliases, scoping and @@ -94,7 +89,7 @@ public class ConfigurationClassProcessingTests { ac.registerBeanDefinition("config", new RootBeanDefinition(testClass)); ac.refresh(); - assertSame(testBeanSupplier.get(), ac.getBean(beanName)); + assertThat(ac.getBean(beanName)).isSameAs(testBeanSupplier.get()); // method name should not be registered assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> @@ -117,8 +112,8 @@ public class ConfigurationClassProcessingTests { TestBean testBean = testBeanSupplier.get(); BeanFactory factory = initBeanFactory(testClass); - assertSame(testBean, factory.getBean(beanName)); - Arrays.stream(factory.getAliases(beanName)).map(factory::getBean).forEach(alias -> assertSame(testBean, alias)); + assertThat(factory.getBean(beanName)).isSameAs(testBean); + Arrays.stream(factory.getAliases(beanName)).map(factory::getBean).forEach(alias -> assertThat(alias).isSameAs(testBean)); // method name should not be registered assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> @@ -131,7 +126,7 @@ public class ConfigurationClassProcessingTests { AnnotationConfigUtils.registerAnnotationConfigProcessors(ac); ac.registerBeanDefinition("config", new RootBeanDefinition(ConfigWithBeanWithProviderImplementation.class)); ac.refresh(); - assertSame(ac.getBean("customName"), ConfigWithBeanWithProviderImplementation.testBean); + assertThat(ConfigWithBeanWithProviderImplementation.testBean).isSameAs(ac.getBean("customName")); } @Test // SPR-11830 @@ -140,7 +135,7 @@ public class ConfigurationClassProcessingTests { AnnotationConfigUtils.registerAnnotationConfigProcessors(ac); ac.registerBeanDefinition("config", new RootBeanDefinition(ConfigWithSetWithProviderImplementation.class)); ac.refresh(); - assertSame(ac.getBean("customName"), ConfigWithSetWithProviderImplementation.set); + assertThat(ConfigWithSetWithProviderImplementation.set).isSameAs(ac.getBean("customName")); } @Test @@ -153,43 +148,44 @@ public class ConfigurationClassProcessingTests { public void simplestPossibleConfig() { BeanFactory factory = initBeanFactory(SimplestPossibleConfig.class); String stringBean = factory.getBean("stringBean", String.class); - assertEquals("foo", stringBean); + assertThat(stringBean).isEqualTo("foo"); } @Test public void configWithObjectReturnType() { BeanFactory factory = initBeanFactory(ConfigWithNonSpecificReturnTypes.class); - assertEquals(Object.class, factory.getType("stringBean")); - assertFalse(factory.isTypeMatch("stringBean", String.class)); + assertThat(factory.getType("stringBean")).isEqualTo(Object.class); + assertThat(factory.isTypeMatch("stringBean", String.class)).isFalse(); String stringBean = factory.getBean("stringBean", String.class); - assertEquals("foo", stringBean); + assertThat(stringBean).isEqualTo("foo"); } @Test public void configWithFactoryBeanReturnType() { ListableBeanFactory factory = initBeanFactory(ConfigWithNonSpecificReturnTypes.class); - assertEquals(List.class, factory.getType("factoryBean")); - assertTrue(factory.isTypeMatch("factoryBean", List.class)); - assertEquals(FactoryBean.class, factory.getType("&factoryBean")); - assertTrue(factory.isTypeMatch("&factoryBean", FactoryBean.class)); - assertFalse(factory.isTypeMatch("&factoryBean", BeanClassLoaderAware.class)); - assertFalse(factory.isTypeMatch("&factoryBean", ListFactoryBean.class)); - assertTrue(factory.getBean("factoryBean") instanceof List); + assertThat(factory.getType("factoryBean")).isEqualTo(List.class); + assertThat(factory.isTypeMatch("factoryBean", List.class)).isTrue(); + assertThat(factory.getType("&factoryBean")).isEqualTo(FactoryBean.class); + assertThat(factory.isTypeMatch("&factoryBean", FactoryBean.class)).isTrue(); + assertThat(factory.isTypeMatch("&factoryBean", BeanClassLoaderAware.class)).isFalse(); + assertThat(factory.isTypeMatch("&factoryBean", ListFactoryBean.class)).isFalse(); + boolean condition = factory.getBean("factoryBean") instanceof List; + assertThat(condition).isTrue(); String[] beanNames = factory.getBeanNamesForType(FactoryBean.class); - assertEquals(1, beanNames.length); - assertEquals("&factoryBean", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("&factoryBean"); beanNames = factory.getBeanNamesForType(BeanClassLoaderAware.class); - assertEquals(1, beanNames.length); - assertEquals("&factoryBean", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("&factoryBean"); beanNames = factory.getBeanNamesForType(ListFactoryBean.class); - assertEquals(1, beanNames.length); - assertEquals("&factoryBean", beanNames[0]); + assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames[0]).isEqualTo("&factoryBean"); beanNames = factory.getBeanNamesForType(List.class); - assertEquals("factoryBean", beanNames[0]); + assertThat(beanNames[0]).isEqualTo("factoryBean"); } @Test @@ -200,8 +196,8 @@ public class ConfigurationClassProcessingTests { ITestBean bar = factory.getBean("bar", ITestBean.class); ITestBean baz = factory.getBean("baz", ITestBean.class); - assertSame(foo.getSpouse(), bar); - assertNotSame(bar.getSpouse(), baz); + assertThat(bar).isSameAs(foo.getSpouse()); + assertThat(baz).isNotSameAs(bar.getSpouse()); } @Test @@ -209,8 +205,8 @@ public class ConfigurationClassProcessingTests { BeanFactory factory = initBeanFactory(ConfigWithNullReference.class); TestBean foo = factory.getBean("foo", TestBean.class); - assertTrue(factory.getBean("bar").equals(null)); - assertNull(foo.getSpouse()); + assertThat(factory.getBean("bar").equals(null)).isTrue(); + assertThat(foo.getSpouse()).isNull(); } @Test @@ -220,12 +216,12 @@ public class ConfigurationClassProcessingTests { ctx.refresh(); AdaptiveInjectionPoints adaptive = ctx.getBean(AdaptiveInjectionPoints.class); - assertEquals("adaptiveInjectionPoint1", adaptive.adaptiveInjectionPoint1.getName()); - assertEquals("setAdaptiveInjectionPoint2", adaptive.adaptiveInjectionPoint2.getName()); + assertThat(adaptive.adaptiveInjectionPoint1.getName()).isEqualTo("adaptiveInjectionPoint1"); + assertThat(adaptive.adaptiveInjectionPoint2.getName()).isEqualTo("setAdaptiveInjectionPoint2"); adaptive = ctx.getBean(AdaptiveInjectionPoints.class); - assertEquals("adaptiveInjectionPoint1", adaptive.adaptiveInjectionPoint1.getName()); - assertEquals("setAdaptiveInjectionPoint2", adaptive.adaptiveInjectionPoint2.getName()); + assertThat(adaptive.adaptiveInjectionPoint1.getName()).isEqualTo("adaptiveInjectionPoint1"); + assertThat(adaptive.adaptiveInjectionPoint2.getName()).isEqualTo("setAdaptiveInjectionPoint2"); ctx.close(); } @@ -236,12 +232,12 @@ public class ConfigurationClassProcessingTests { ctx.refresh(); AdaptiveResourceInjectionPoints adaptive = ctx.getBean(AdaptiveResourceInjectionPoints.class); - assertEquals("adaptiveInjectionPoint1", adaptive.adaptiveInjectionPoint1.getName()); - assertEquals("setAdaptiveInjectionPoint2", adaptive.adaptiveInjectionPoint2.getName()); + assertThat(adaptive.adaptiveInjectionPoint1.getName()).isEqualTo("adaptiveInjectionPoint1"); + assertThat(adaptive.adaptiveInjectionPoint2.getName()).isEqualTo("setAdaptiveInjectionPoint2"); adaptive = ctx.getBean(AdaptiveResourceInjectionPoints.class); - assertEquals("adaptiveInjectionPoint1", adaptive.adaptiveInjectionPoint1.getName()); - assertEquals("setAdaptiveInjectionPoint2", adaptive.adaptiveInjectionPoint2.getName()); + assertThat(adaptive.adaptiveInjectionPoint1.getName()).isEqualTo("adaptiveInjectionPoint1"); + assertThat(adaptive.adaptiveInjectionPoint2.getName()).isEqualTo("setAdaptiveInjectionPoint2"); ctx.close(); } @@ -258,12 +254,12 @@ public class ConfigurationClassProcessingTests { ITestBean bar = ctx.getBean("bar", ITestBean.class); ITestBean baz = ctx.getBean("baz", ITestBean.class); - assertEquals("foo-processed-myValue", foo.getName()); - assertEquals("bar-processed-myValue", bar.getName()); - assertEquals("baz-processed-myValue", baz.getName()); + assertThat(foo.getName()).isEqualTo("foo-processed-myValue"); + assertThat(bar.getName()).isEqualTo("bar-processed-myValue"); + assertThat(baz.getName()).isEqualTo("baz-processed-myValue"); SpousyTestBean listener = ctx.getBean("listenerTestBean", SpousyTestBean.class); - assertTrue(listener.refreshed); + assertThat(listener.refreshed).isTrue(); ctx.close(); } @@ -273,8 +269,8 @@ public class ConfigurationClassProcessingTests { ctx.register(ConfigWithFunctionalRegistration.class); ctx.refresh(); - assertSame(ctx.getBean("spouse"), ctx.getBean(TestBean.class).getSpouse()); - assertEquals("functional", ctx.getBean(NestedTestBean.class).getCompany()); + assertThat(ctx.getBean(TestBean.class).getSpouse()).isSameAs(ctx.getBean("spouse")); + assertThat(ctx.getBean(NestedTestBean.class).getCompany()).isEqualTo("functional"); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java index 296cb9169cd..0f7e0ba8855 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java @@ -35,8 +35,6 @@ import org.springframework.core.env.PropertySource; import org.springframework.tests.sample.beans.TestBean; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Integration tests for {@link ImportResource} support. @@ -50,25 +48,25 @@ public class ImportResourceTests { @Test public void importXml() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlConfig.class); - assertTrue("did not contain java-declared bean", ctx.containsBean("javaDeclaredBean")); - assertTrue("did not contain xml-declared bean", ctx.containsBean("xmlDeclaredBean")); + assertThat(ctx.containsBean("javaDeclaredBean")).as("did not contain java-declared bean").isTrue(); + assertThat(ctx.containsBean("xmlDeclaredBean")).as("did not contain xml-declared bean").isTrue(); TestBean tb = ctx.getBean("javaDeclaredBean", TestBean.class); - assertEquals("myName", tb.getName()); + assertThat(tb.getName()).isEqualTo("myName"); ctx.close(); } @Test public void importXmlIsInheritedFromSuperclassDeclarations() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(FirstLevelSubConfig.class); - assertTrue(ctx.containsBean("xmlDeclaredBean")); + assertThat(ctx.containsBean("xmlDeclaredBean")).isTrue(); ctx.close(); } @Test public void importXmlIsMergedFromSuperclassDeclarations() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SecondLevelSubConfig.class); - assertTrue("failed to pick up second-level-declared XML bean", ctx.containsBean("secondLevelXmlDeclaredBean")); - assertTrue("failed to pick up parent-declared XML bean", ctx.containsBean("xmlDeclaredBean")); + assertThat(ctx.containsBean("secondLevelXmlDeclaredBean")).as("failed to pick up second-level-declared XML bean").isTrue(); + assertThat(ctx.containsBean("xmlDeclaredBean")).as("failed to pick up parent-declared XML bean").isTrue(); ctx.close(); } @@ -76,17 +74,17 @@ public class ImportResourceTests { public void importXmlWithNamespaceConfig() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlWithAopNamespaceConfig.class); Object bean = ctx.getBean("proxiedXmlBean"); - assertTrue(AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).isTrue(); ctx.close(); } @Test public void importXmlWithOtherConfigurationClass() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlWithConfigurationClass.class); - assertTrue("did not contain java-declared bean", ctx.containsBean("javaDeclaredBean")); - assertTrue("did not contain xml-declared bean", ctx.containsBean("xmlDeclaredBean")); + assertThat(ctx.containsBean("javaDeclaredBean")).as("did not contain java-declared bean").isTrue(); + assertThat(ctx.containsBean("xmlDeclaredBean")).as("did not contain xml-declared bean").isTrue(); TestBean tb = ctx.getBean("javaDeclaredBean", TestBean.class); - assertEquals("myName", tb.getName()); + assertThat(tb.getName()).isEqualTo("myName"); ctx.close(); } @@ -98,7 +96,7 @@ public class ImportResourceTests { ctx.getEnvironment().getPropertySources().addFirst(propertySource); ctx.register(ImportXmlConfig.class); ctx.refresh(); - assertTrue("did not contain xml-declared bean", ctx.containsBean("xmlDeclaredBean")); + assertThat(ctx.containsBean("xmlDeclaredBean")).as("did not contain xml-declared bean").isTrue(); ctx.close(); } @@ -113,7 +111,7 @@ public class ImportResourceTests { @Test public void importNonXmlResource() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportNonXmlResourceConfig.class); - assertTrue(ctx.containsBean("propertiesDeclaredBean")); + assertThat(ctx.containsBean("propertiesDeclaredBean")).isTrue(); ctx.close(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportTests.java index d1dd4166a18..a34810c8436 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportTests.java @@ -30,7 +30,6 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; /** * System tests for {@link Import} annotation support. @@ -259,7 +258,7 @@ public class ImportTests { @DependsOn("org.springframework.context.annotation.configuration.ImportTests$InitBean") static class ThirdLevel { public ThirdLevel() { - assertTrue(InitBean.initialized); + assertThat(InitBean.initialized).isTrue(); } @Bean diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportWithConditionTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportWithConditionTests.java index cbb868de45d..4a9f904a32d 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportWithConditionTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportWithConditionTests.java @@ -28,8 +28,7 @@ import org.springframework.context.annotation.ConfigurationCondition; import org.springframework.context.annotation.Import; import org.springframework.core.type.AnnotatedTypeMetadata; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Andy Wilkinson @@ -42,16 +41,16 @@ public class ImportWithConditionTests { public void conditionalThenUnconditional() throws Exception { this.context.register(ConditionalThenUnconditional.class); this.context.refresh(); - assertFalse(this.context.containsBean("beanTwo")); - assertTrue(this.context.containsBean("beanOne")); + assertThat(this.context.containsBean("beanTwo")).isFalse(); + assertThat(this.context.containsBean("beanOne")).isTrue(); } @Test public void unconditionalThenConditional() throws Exception { this.context.register(UnconditionalThenConditional.class); this.context.refresh(); - assertFalse(this.context.containsBean("beanTwo")); - assertTrue(this.context.containsBean("beanOne")); + assertThat(this.context.containsBean("beanTwo")).isFalse(); + assertThat(this.context.containsBean("beanOne")).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java index 267263e7568..fd47f448c64 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java @@ -28,8 +28,6 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Unit tests cornering the bug exposed in SPR-6779. @@ -52,8 +50,7 @@ public class ImportedConfigurationClassEnhancementTests { private void autowiredConfigClassIsEnhanced(Class... configClasses) { ApplicationContext ctx = new AnnotationConfigApplicationContext(configClasses); Config config = ctx.getBean(Config.class); - assertTrue("autowired config class has not been enhanced", - ClassUtils.isCglibProxy(config.autowiredConfig)); + assertThat(ClassUtils.isCglibProxy(config.autowiredConfig)).as("autowired config class has not been enhanced").isTrue(); } @@ -82,7 +79,7 @@ public class ImportedConfigurationClassEnhancementTests { public void importingNonConfigurationClassCausesBeanDefinitionParsingException() { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigThatImportsNonConfigClass.class); ConfigThatImportsNonConfigClass config = ctx.getBean(ConfigThatImportsNonConfigClass.class); - assertSame(ctx.getBean(TestBean.class), config.testBean); + assertThat(config.testBean).isSameAs(ctx.getBean(TestBean.class)); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ScopingTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ScopingTests.java index c2a37137c38..f8377cb9c4c 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ScopingTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ScopingTests.java @@ -40,11 +40,7 @@ import org.springframework.context.support.GenericApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -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; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests that scopes are properly supported by using a custom Scope implementations @@ -104,33 +100,33 @@ public class ScopingTests { Object bean1 = ctx.getBean(beanName); Object bean2 = ctx.getBean(beanName); - assertSame(message, bean1, bean2); + assertThat(bean2).as(message).isSameAs(bean1); Object bean3 = ctx.getBean(beanName); - assertSame(message, bean1, bean3); + assertThat(bean3).as(message).isSameAs(bean1); // make the scope create a new object customScope.createNewScope = true; Object newBean1 = ctx.getBean(beanName); - assertNotSame(message, bean1, newBean1); + assertThat(newBean1).as(message).isNotSameAs(bean1); Object sameBean1 = ctx.getBean(beanName); - assertSame(message, newBean1, sameBean1); + assertThat(sameBean1).as(message).isSameAs(newBean1); // make the scope create a new object customScope.createNewScope = true; Object newBean2 = ctx.getBean(beanName); - assertNotSame(message, newBean1, newBean2); + assertThat(newBean2).as(message).isNotSameAs(newBean1); // make the scope create a new object .. again customScope.createNewScope = true; Object newBean3 = ctx.getBean(beanName); - assertNotSame(message, newBean2, newBean3); + assertThat(newBean3).as(message).isNotSameAs(newBean2); } @Test @@ -138,16 +134,16 @@ public class ScopingTests { Object beanAInScope = ctx.getBean("scopedClass"); Object beanBInScope = ctx.getBean("scopedInterface"); - assertNotSame(beanAInScope, beanBInScope); + assertThat(beanBInScope).isNotSameAs(beanAInScope); customScope.createNewScope = true; Object newBeanAInScope = ctx.getBean("scopedClass"); Object newBeanBInScope = ctx.getBean("scopedInterface"); - assertNotSame(newBeanAInScope, newBeanBInScope); - assertNotSame(newBeanAInScope, beanAInScope); - assertNotSame(newBeanBInScope, beanBInScope); + assertThat(newBeanBInScope).isNotSameAs(newBeanAInScope); + assertThat(beanAInScope).isNotSameAs(newBeanAInScope); + assertThat(beanBInScope).isNotSameAs(newBeanBInScope); } @Test @@ -157,26 +153,28 @@ public class ScopingTests { // get hidden bean Object bean = ctx.getBean("scopedTarget." + beanName); - assertFalse(bean instanceof ScopedObject); + boolean condition = bean instanceof ScopedObject; + assertThat(condition).isFalse(); } @Test public void testScopedProxyConfiguration() throws Exception { TestBean singleton = (TestBean) ctx.getBean("singletonWithScopedInterfaceDep"); ITestBean spouse = singleton.getSpouse(); - assertTrue("scoped bean is not wrapped by the scoped-proxy", spouse instanceof ScopedObject); + boolean condition = spouse instanceof ScopedObject; + assertThat(condition).as("scoped bean is not wrapped by the scoped-proxy").isTrue(); String beanName = "scopedProxyInterface"; String scopedBeanName = "scopedTarget." + beanName; // get hidden bean - assertEquals(flag, spouse.getName()); + assertThat(spouse.getName()).isEqualTo(flag); ITestBean spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName); - assertEquals(spouse.getName(), spouseFromBF.getName()); + assertThat(spouseFromBF.getName()).isEqualTo(spouse.getName()); // the scope proxy has kicked in - assertNotSame(spouse, spouseFromBF); + assertThat(spouseFromBF).isNotSameAs(spouse); // create a new bean customScope.createNewScope = true; @@ -184,31 +182,32 @@ public class ScopingTests { // get the bean again from the BF spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName); // make sure the name has been updated - assertSame(spouse.getName(), spouseFromBF.getName()); - assertNotSame(spouse, spouseFromBF); + assertThat(spouseFromBF.getName()).isSameAs(spouse.getName()); + assertThat(spouseFromBF).isNotSameAs(spouse); // get the bean again spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName); - assertSame(spouse.getName(), spouseFromBF.getName()); + assertThat(spouseFromBF.getName()).isSameAs(spouse.getName()); } @Test public void testScopedProxyConfigurationWithClasses() throws Exception { TestBean singleton = (TestBean) ctx.getBean("singletonWithScopedClassDep"); ITestBean spouse = singleton.getSpouse(); - assertTrue("scoped bean is not wrapped by the scoped-proxy", spouse instanceof ScopedObject); + boolean condition = spouse instanceof ScopedObject; + assertThat(condition).as("scoped bean is not wrapped by the scoped-proxy").isTrue(); String beanName = "scopedProxyClass"; String scopedBeanName = "scopedTarget." + beanName; // get hidden bean - assertEquals(flag, spouse.getName()); + assertThat(spouse.getName()).isEqualTo(flag); TestBean spouseFromBF = (TestBean) ctx.getBean(scopedBeanName); - assertEquals(spouse.getName(), spouseFromBF.getName()); + assertThat(spouseFromBF.getName()).isEqualTo(spouse.getName()); // the scope proxy has kicked in - assertNotSame(spouse, spouseFromBF); + assertThat(spouseFromBF).isNotSameAs(spouse); // create a new bean customScope.createNewScope = true; @@ -217,12 +216,12 @@ public class ScopingTests { // get the bean again from the BF spouseFromBF = (TestBean) ctx.getBean(scopedBeanName); // make sure the name has been updated - assertSame(spouse.getName(), spouseFromBF.getName()); - assertNotSame(spouse, spouseFromBF); + assertThat(spouseFromBF.getName()).isSameAs(spouse.getName()); + assertThat(spouseFromBF).isNotSameAs(spouse); // get the bean again spouseFromBF = (TestBean) ctx.getBean(scopedBeanName); - assertSame(spouse.getName(), spouseFromBF.getName()); + assertThat(spouseFromBF.getName()).isSameAs(spouse.getName()); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr10668Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr10668Tests.java index f27f8d775f4..2b7e27a2072 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr10668Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr10668Tests.java @@ -23,7 +23,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for SPR-10668. @@ -36,7 +36,7 @@ public class Spr10668Tests { @Test public void testSelfInjectHierarchy() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ChildConfig.class); - assertNotNull(context.getBean(MyComponent.class)); + assertThat(context.getBean(MyComponent.class)).isNotNull(); context.close(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr12526Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr12526Tests.java index ded8ca49d0c..b0805b40c8f 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr12526Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr12526Tests.java @@ -25,7 +25,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE; import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_SINGLETON; @@ -42,11 +42,11 @@ public class Spr12526Tests { condition.setCondition(true); FirstService firstService = (FirstService) ctx.getBean(Service.class); - assertNotNull("FirstService.dependency is null", firstService.getDependency()); + assertThat(firstService.getDependency()).as("FirstService.dependency is null").isNotNull(); condition.setCondition(false); SecondService secondService = (SecondService) ctx.getBean(Service.class); - assertNotNull("SecondService.dependency is null", secondService.getDependency()); + assertThat(secondService.getDependency()).as("SecondService.dependency is null").isNotNull(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr7167Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr7167Tests.java index 7d3907bfa6d..d27c6a39b2f 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr7167Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr7167Tests.java @@ -29,7 +29,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; public class Spr7167Tests { @@ -42,7 +41,7 @@ public class Spr7167Tests { .isEqualTo("post processed by MyPostProcessor"); MyConfig config = ctx.getBean(MyConfig.class); - assertTrue("Config class was not enhanced", ClassUtils.isCglibProxy(config)); + assertThat(ClassUtils.isCglibProxy(config)).as("Config class was not enhanced").isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/context/config/ContextNamespaceHandlerTests.java b/spring-context/src/test/java/org/springframework/context/config/ContextNamespaceHandlerTests.java index 9cc3ded3959..4608cda6e33 100644 --- a/spring-context/src/test/java/org/springframework/context/config/ContextNamespaceHandlerTests.java +++ b/spring-context/src/test/java/org/springframework/context/config/ContextNamespaceHandlerTests.java @@ -29,9 +29,8 @@ import org.springframework.context.support.GenericXmlApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.mock.env.MockEnvironment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Arjen Poutsma @@ -52,8 +51,8 @@ public class ContextNamespaceHandlerTests { public void propertyPlaceholder() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "contextNamespaceHandlerTests-replace.xml", getClass()); - assertEquals("bar", applicationContext.getBean("string")); - assertEquals("null", applicationContext.getBean("nullString")); + assertThat(applicationContext.getBean("string")).isEqualTo("bar"); + assertThat(applicationContext.getBean("nullString")).isEqualTo("null"); } @Test @@ -62,8 +61,8 @@ public class ContextNamespaceHandlerTests { try { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "contextNamespaceHandlerTests-system.xml", getClass()); - assertEquals("spam", applicationContext.getBean("string")); - assertEquals("none", applicationContext.getBean("fallback")); + assertThat(applicationContext.getBean("string")).isEqualTo("spam"); + assertThat(applicationContext.getBean("fallback")).isEqualTo("none"); } finally { if (value != null) { @@ -79,17 +78,17 @@ public class ContextNamespaceHandlerTests { applicationContext.setEnvironment(env); applicationContext.load(new ClassPathResource("contextNamespaceHandlerTests-simple.xml", getClass())); applicationContext.refresh(); - assertEquals("spam", applicationContext.getBean("string")); - assertEquals("none", applicationContext.getBean("fallback")); + assertThat(applicationContext.getBean("string")).isEqualTo("spam"); + assertThat(applicationContext.getBean("fallback")).isEqualTo("none"); } @Test public void propertyPlaceholderLocation() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "contextNamespaceHandlerTests-location.xml", getClass()); - assertEquals("bar", applicationContext.getBean("foo")); - assertEquals("foo", applicationContext.getBean("bar")); - assertEquals("maps", applicationContext.getBean("spam")); + assertThat(applicationContext.getBean("foo")).isEqualTo("bar"); + assertThat(applicationContext.getBean("bar")).isEqualTo("foo"); + assertThat(applicationContext.getBean("spam")).isEqualTo("maps"); } @Test @@ -99,9 +98,9 @@ public class ContextNamespaceHandlerTests { try { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "contextNamespaceHandlerTests-location-placeholder.xml", getClass()); - assertEquals("bar", applicationContext.getBean("foo")); - assertEquals("foo", applicationContext.getBean("bar")); - assertEquals("maps", applicationContext.getBean("spam")); + assertThat(applicationContext.getBean("foo")).isEqualTo("bar"); + assertThat(applicationContext.getBean("bar")).isEqualTo("foo"); + assertThat(applicationContext.getBean("spam")).isEqualTo("maps"); } finally { System.clearProperty("properties"); @@ -117,9 +116,9 @@ public class ContextNamespaceHandlerTests { try { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "contextNamespaceHandlerTests-location-placeholder.xml", getClass()); - assertEquals("bar", applicationContext.getBean("foo")); - assertEquals("foo", applicationContext.getBean("bar")); - assertEquals("maps", applicationContext.getBean("spam")); + assertThat(applicationContext.getBean("foo")).isEqualTo("bar"); + assertThat(applicationContext.getBean("bar")).isEqualTo("foo"); + assertThat(applicationContext.getBean("spam")).isEqualTo("maps"); } finally { System.clearProperty("properties"); @@ -128,24 +127,19 @@ public class ContextNamespaceHandlerTests { @Test public void propertyPlaceholderLocationWithSystemPropertyMissing() { - try { - new ClassPathXmlApplicationContext( - "contextNamespaceHandlerTests-location-placeholder.xml", getClass()); - fail("Should have thrown FatalBeanException"); - } - catch (FatalBeanException ex) { - Throwable cause = ex.getRootCause(); - assertTrue(cause instanceof IllegalArgumentException); - assertEquals("Could not resolve placeholder 'foo' in value \"${foo}\"", cause.getMessage()); - } + assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> + new ClassPathXmlApplicationContext("contextNamespaceHandlerTests-location-placeholder.xml", getClass())) + .satisfies(ex -> assertThat(ex.getRootCause()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Could not resolve placeholder 'foo' in value \"${foo}\"")); } @Test public void propertyPlaceholderIgnored() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "contextNamespaceHandlerTests-replace-ignore.xml", getClass()); - assertEquals("${bar}", applicationContext.getBean("string")); - assertEquals("null", applicationContext.getBean("nullString")); + assertThat(applicationContext.getBean("string")).isEqualTo("${bar}"); + assertThat(applicationContext.getBean("nullString")).isEqualTo("null"); } @Test @@ -155,7 +149,7 @@ public class ContextNamespaceHandlerTests { Date date = (Date) applicationContext.getBean("date"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); - assertEquals(42, calendar.get(Calendar.MINUTE)); + assertThat(calendar.get(Calendar.MINUTE)).isEqualTo(42); } } diff --git a/spring-context/src/test/java/org/springframework/context/conversionservice/ConversionServiceContextConfigTests.java b/spring-context/src/test/java/org/springframework/context/conversionservice/ConversionServiceContextConfigTests.java index ee079bb98dc..5498d6ce0b4 100644 --- a/spring-context/src/test/java/org/springframework/context/conversionservice/ConversionServiceContextConfigTests.java +++ b/spring-context/src/test/java/org/springframework/context/conversionservice/ConversionServiceContextConfigTests.java @@ -20,8 +20,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Keith Donald @@ -32,10 +31,10 @@ public class ConversionServiceContextConfigTests { public void testConfigOk() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("org/springframework/context/conversionservice/conversionService.xml"); TestClient client = context.getBean("testClient", TestClient.class); - assertEquals(2, client.getBars().size()); - assertEquals("value1", client.getBars().get(0).getValue()); - assertEquals("value2", client.getBars().get(1).getValue()); - assertTrue(client.isBool()); + assertThat(client.getBars().size()).isEqualTo(2); + assertThat(client.getBars().get(0).getValue()).isEqualTo("value1"); + assertThat(client.getBars().get(1).getValue()).isEqualTo("value2"); + assertThat(client.isBool()).isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java b/spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java index 5779f0947ca..1edfbb04474 100644 --- a/spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java @@ -67,9 +67,6 @@ import org.springframework.validation.beanvalidation.MethodValidationPostProcess import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; /** * @author Stephane Nicoll @@ -142,13 +139,13 @@ public class AnnotationDrivenEventListenerTests { ContextEventListener listener = this.context.getBean(ContextEventListener.class); List events = this.eventCollector.getEvents(listener); - assertEquals("Wrong number of initial context events", 1, events.size()); - assertEquals(ContextRefreshedEvent.class, events.get(0).getClass()); + assertThat(events.size()).as("Wrong number of initial context events").isEqualTo(1); + assertThat(events.get(0).getClass()).isEqualTo(ContextRefreshedEvent.class); this.context.stop(); List eventsAfterStop = this.eventCollector.getEvents(listener); - assertEquals("Wrong number of context events on shutdown", 2, eventsAfterStop.size()); - assertEquals(ContextStoppedEvent.class, eventsAfterStop.get(1).getClass()); + assertThat(eventsAfterStop.size()).as("Wrong number of context events on shutdown").isEqualTo(2); + assertThat(eventsAfterStop.get(1).getClass()).isEqualTo(ContextStoppedEvent.class); this.eventCollector.assertTotalEventsCount(2); } @@ -250,7 +247,7 @@ public class AnnotationDrivenEventListenerTests { load(ScopedProxyTestBean.class); SimpleService proxy = this.context.getBean(SimpleService.class); - assertTrue("bean should be a proxy", proxy instanceof Advised); + assertThat(proxy instanceof Advised).as("bean should be a proxy").isTrue(); this.eventCollector.assertNoEventReceived(proxy.getId()); this.context.publishEvent(new ContextRefreshedEvent(this.context)); @@ -267,7 +264,7 @@ public class AnnotationDrivenEventListenerTests { load(AnnotatedProxyTestBean.class); AnnotatedSimpleService proxy = this.context.getBean(AnnotatedSimpleService.class); - assertTrue("bean should be a proxy", proxy instanceof Advised); + assertThat(proxy instanceof Advised).as("bean should be a proxy").isTrue(); this.eventCollector.assertNoEventReceived(proxy.getId()); this.context.publishEvent(new ContextRefreshedEvent(this.context)); @@ -284,7 +281,7 @@ public class AnnotationDrivenEventListenerTests { load(CglibProxyTestBean.class); CglibProxyTestBean proxy = this.context.getBean(CglibProxyTestBean.class); - assertTrue("bean should be a cglib proxy", AopUtils.isCglibProxy(proxy)); + assertThat(AopUtils.isCglibProxy(proxy)).as("bean should be a cglib proxy").isTrue(); this.eventCollector.assertNoEventReceived(proxy.getId()); this.context.publishEvent(new ContextRefreshedEvent(this.context)); @@ -310,7 +307,7 @@ public class AnnotationDrivenEventListenerTests { this.context.getBeanFactory().registerScope("custom", customScope); CustomScopeTestBean proxy = this.context.getBean(CustomScopeTestBean.class); - assertTrue("bean should be a cglib proxy", AopUtils.isCglibProxy(proxy)); + assertThat(AopUtils.isCglibProxy(proxy)).as("bean should be a cglib proxy").isTrue(); this.eventCollector.assertNoEventReceived(proxy.getId()); this.context.publishEvent(new ContextRefreshedEvent(this.context)); @@ -545,7 +542,7 @@ public class AnnotationDrivenEventListenerTests { load(OrderedTestListener.class); OrderedTestListener listener = this.context.getBean(OrderedTestListener.class); - assertTrue(listener.order.isEmpty()); + assertThat(listener.order.isEmpty()).isTrue(); this.context.publishEvent("whatever"); assertThat(listener.order).contains("first", "second", "third"); } @@ -733,7 +730,7 @@ public class AnnotationDrivenEventListenerTests { @EventListener @Async public void handleAsync(AnotherTestEvent event) { - assertNotEquals(event.content, Thread.currentThread().getName()); + assertThat(Thread.currentThread().getName()).isNotEqualTo(event.content); collectEvent(event); this.countDownLatch.countDown(); } @@ -780,7 +777,7 @@ public class AnnotationDrivenEventListenerTests { @EventListener @Async public void handleAsync(AnotherTestEvent event) { - assertNotEquals(event.content, Thread.currentThread().getName()); + assertThat(Thread.currentThread().getName()).isNotEqualTo(event.content); this.eventCollector.addEvent(this, event); this.countDownLatch.countDown(); } @@ -806,7 +803,7 @@ public class AnnotationDrivenEventListenerTests { @EventListener @Async public void handleAsync(AnotherTestEvent event) { - assertNotEquals(event.content, Thread.currentThread().getName()); + assertThat(Thread.currentThread().getName()).isNotEqualTo(event.content); this.eventCollector.addEvent(this, event); this.countDownLatch.countDown(); } diff --git a/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java b/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java index fdd7dc78588..bedafcd5387 100644 --- a/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java @@ -50,10 +50,6 @@ import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; @@ -195,7 +191,7 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen smc.multicastEvent(new MyEvent(this)); smc.multicastEvent(new MyOtherEvent(this)); - assertEquals(2, listener1.seenEvents.size()); + assertThat(listener1.seenEvents.size()).isEqualTo(2); } @Test @@ -209,7 +205,7 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen smc.multicastEvent(new MyEvent(this)); smc.multicastEvent(new MyOtherEvent(this)); - assertEquals(2, listener1.seenEvents.size()); + assertThat(listener1.seenEvents.size()).isEqualTo(2); } @Test @@ -226,7 +222,7 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen smc.multicastEvent(new MyEvent(this)); smc.multicastEvent(new MyOtherEvent(this)); - assertEquals(2, listener1.seenEvents.size()); + assertThat(listener1.seenEvents.size()).isEqualTo(2); } @Test @@ -245,7 +241,7 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen smc.multicastEvent(new MyEvent(this)); smc.multicastEvent(new MyOtherEvent(this)); - assertEquals(2, listener1.seenEvents.size()); + assertThat(listener1.seenEvents.size()).isEqualTo(2); } @Test @@ -273,36 +269,36 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen listener2.setLazyInit(true); context.registerBeanDefinition("listener2", listener2); context.refresh(); - assertFalse(context.getDefaultListableBeanFactory().containsSingleton("listener2")); + assertThat(context.getDefaultListableBeanFactory().containsSingleton("listener2")).isFalse(); MyOrderedListener1 listener1 = context.getBean("listener1", MyOrderedListener1.class); MyOtherEvent event1 = new MyOtherEvent(context); context.publishEvent(event1); - assertFalse(context.getDefaultListableBeanFactory().containsSingleton("listener2")); + assertThat(context.getDefaultListableBeanFactory().containsSingleton("listener2")).isFalse(); MyEvent event2 = new MyEvent(context); context.publishEvent(event2); - assertTrue(context.getDefaultListableBeanFactory().containsSingleton("listener2")); + assertThat(context.getDefaultListableBeanFactory().containsSingleton("listener2")).isTrue(); MyEvent event3 = new MyEvent(context); context.publishEvent(event3); MyOtherEvent event4 = new MyOtherEvent(context); context.publishEvent(event4); - assertTrue(listener1.seenEvents.contains(event1)); - assertTrue(listener1.seenEvents.contains(event2)); - assertTrue(listener1.seenEvents.contains(event3)); - assertTrue(listener1.seenEvents.contains(event4)); + assertThat(listener1.seenEvents.contains(event1)).isTrue(); + assertThat(listener1.seenEvents.contains(event2)).isTrue(); + assertThat(listener1.seenEvents.contains(event3)).isTrue(); + assertThat(listener1.seenEvents.contains(event4)).isTrue(); listener1.seenEvents.clear(); context.publishEvent(event1); context.publishEvent(event2); context.publishEvent(event3); context.publishEvent(event4); - assertTrue(listener1.seenEvents.contains(event1)); - assertTrue(listener1.seenEvents.contains(event2)); - assertTrue(listener1.seenEvents.contains(event3)); - assertTrue(listener1.seenEvents.contains(event4)); + assertThat(listener1.seenEvents.contains(event1)).isTrue(); + assertThat(listener1.seenEvents.contains(event2)).isTrue(); + assertThat(listener1.seenEvents.contains(event3)).isTrue(); + assertThat(listener1.seenEvents.contains(event4)).isTrue(); AbstractApplicationEventMulticaster multicaster = context.getBean(AbstractApplicationEventMulticaster.class); - assertEquals(2, multicaster.retrieverCache.size()); + assertThat(multicaster.retrieverCache.size()).isEqualTo(2); context.close(); } @@ -318,13 +314,13 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen context.publishEvent("event2"); context.publishEvent("event3"); context.publishEvent("event4"); - assertTrue(listener.seenPayloads.contains("event1")); - assertTrue(listener.seenPayloads.contains("event2")); - assertTrue(listener.seenPayloads.contains("event3")); - assertTrue(listener.seenPayloads.contains("event4")); + assertThat(listener.seenPayloads.contains("event1")).isTrue(); + assertThat(listener.seenPayloads.contains("event2")).isTrue(); + assertThat(listener.seenPayloads.contains("event3")).isTrue(); + assertThat(listener.seenPayloads.contains("event4")).isTrue(); AbstractApplicationEventMulticaster multicaster = context.getBean(AbstractApplicationEventMulticaster.class); - assertEquals(2, multicaster.retrieverCache.size()); + assertThat(multicaster.retrieverCache.size()).isEqualTo(2); context.close(); } @@ -344,15 +340,15 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen MyOrderedListener1 listener1 = context.getBean("listener1", MyOrderedListener1.class); MyEvent event1 = new MyEvent(context); context.publishEvent(event1); - assertTrue(listener1.seenEvents.contains(event1)); + assertThat(listener1.seenEvents.contains(event1)).isTrue(); SimpleApplicationEventMulticaster multicaster = context.getBean( AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, SimpleApplicationEventMulticaster.class); - assertFalse(multicaster.getApplicationListeners().isEmpty()); + assertThat(multicaster.getApplicationListeners().isEmpty()).isFalse(); context.close(); - assertTrue(multicaster.getApplicationListeners().isEmpty()); + assertThat(multicaster.getApplicationListeners().isEmpty()).isTrue(); } @Test @@ -371,10 +367,10 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen context.publishEvent(event3); MyOtherEvent event4 = new MyOtherEvent(context); context.publishEvent(event4); - assertTrue(MyNonSingletonListener.seenEvents.contains(event1)); - assertTrue(MyNonSingletonListener.seenEvents.contains(event2)); - assertTrue(MyNonSingletonListener.seenEvents.contains(event3)); - assertTrue(MyNonSingletonListener.seenEvents.contains(event4)); + assertThat(MyNonSingletonListener.seenEvents.contains(event1)).isTrue(); + assertThat(MyNonSingletonListener.seenEvents.contains(event2)).isTrue(); + assertThat(MyNonSingletonListener.seenEvents.contains(event3)).isTrue(); + assertThat(MyNonSingletonListener.seenEvents.contains(event4)).isTrue(); MyNonSingletonListener.seenEvents.clear(); context.close(); @@ -391,7 +387,7 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen BeanThatBroadcasts broadcaster = context.getBean("broadcaster", BeanThatBroadcasts.class); context.publishEvent(new MyEvent(context)); - assertEquals("The event was not received by the listener", 2, broadcaster.receivedCount); + assertThat(broadcaster.receivedCount).as("The event was not received by the listener").isEqualTo(2); context.close(); } @@ -407,7 +403,7 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen context.publishEvent(new MyEvent(this)); context.publishEvent(new MyEvent(this)); TestBean listener = context.getBean(TestBean.class); - assertEquals(3, ((BeanThatListens) listener.getFriends().iterator().next()).getEventCount()); + assertThat(((BeanThatListens) listener.getFriends().iterator().next()).getEventCount()).isEqualTo(3); context.close(); } @@ -429,9 +425,9 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen context.publishEvent(new MyOtherEvent(context)); MyEvent event2 = new MyEvent(context); context.publishEvent(event2); - assertSame(2, seenEvents.size()); - assertTrue(seenEvents.contains(event1)); - assertTrue(seenEvents.contains(event2)); + assertThat(seenEvents.size()).isSameAs(2); + assertThat(seenEvents.contains(event1)).isTrue(); + assertThat(seenEvents.contains(event2)).isTrue(); context.close(); } @@ -449,9 +445,9 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen context.publishEvent(new MyOtherEvent(context)); MyEvent event2 = new MyEvent(context); context.publishEvent(event2); - assertSame(2, seenEvents.size()); - assertTrue(seenEvents.contains(event1)); - assertTrue(seenEvents.contains(event2)); + assertThat(seenEvents.size()).isSameAs(2); + assertThat(seenEvents.contains(event1)).isTrue(); + assertThat(seenEvents.contains(event2)).isTrue(); context.close(); } @@ -473,9 +469,9 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen context.publishEvent(new MyOtherEvent(context)); MyEvent event2 = new MyEvent(context); context.publishEvent(event2); - assertSame(2, seenEvents.size()); - assertTrue(seenEvents.contains(event1)); - assertTrue(seenEvents.contains(event2)); + assertThat(seenEvents.size()).isSameAs(2); + assertThat(seenEvents.contains(event1)).isTrue(); + assertThat(seenEvents.contains(event2)).isTrue(); context.close(); } @@ -514,7 +510,7 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen context.publishEvent(new MyEvent(this)); BeanThatListens listener = context.getBean(BeanThatListens.class); - assertEquals(4, listener.getEventCount()); + assertThat(listener.getEventCount()).isEqualTo(4); context.close(); } @@ -577,7 +573,7 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen @Override public void onApplicationEvent(MyEvent event) { - assertTrue(this.otherListener.seenEvents.contains(event)); + assertThat(this.otherListener.seenEvents.contains(event)).isTrue(); } } @@ -628,7 +624,7 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen @Override public void onApplicationEvent(MyEvent event) { - assertTrue(this.otherListener.seenEvents.contains(event)); + assertThat(this.otherListener.seenEvents.contains(event)).isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/context/event/ApplicationListenerMethodAdapterTests.java b/spring-context/src/test/java/org/springframework/context/event/ApplicationListenerMethodAdapterTests.java index 9714e2c5b6b..b8299c67e47 100644 --- a/spring-context/src/test/java/org/springframework/context/event/ApplicationListenerMethodAdapterTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/ApplicationListenerMethodAdapterTests.java @@ -31,9 +31,9 @@ import org.springframework.core.ResolvableTypeProvider; import org.springframework.core.annotation.Order; import org.springframework.util.ReflectionUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -165,7 +165,7 @@ public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEv Method method = ReflectionUtils.findMethod( SampleEvents.class, "handleGenericString", GenericTestEvent.class); ApplicationListenerMethodAdapter adapter = createTestInstance(method); - assertEquals(0, adapter.getOrder()); + assertThat(adapter.getOrder()).isEqualTo(0); } @Test @@ -173,7 +173,7 @@ public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEv Method method = ReflectionUtils.findMethod( SampleEvents.class, "handleRaw", ApplicationEvent.class); ApplicationListenerMethodAdapter adapter = createTestInstance(method); - assertEquals(42, adapter.getOrder()); + assertThat(adapter.getOrder()).isEqualTo(42); } @Test @@ -331,8 +331,7 @@ public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEv private void supportsEventType(boolean match, Method method, ResolvableType eventType) { ApplicationListenerMethodAdapter adapter = createTestInstance(method); - assertEquals("Wrong match for event '" + eventType + "' on " + method, - match, adapter.supportsEventType(eventType)); + assertThat(adapter.supportsEventType(eventType)).as("Wrong match for event '" + eventType + "' on " + method).isEqualTo(match); } private void invokeListener(Method method, ApplicationEvent event) { diff --git a/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java b/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java index ee4cd3d745a..d48cfa27ff6 100644 --- a/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java @@ -31,8 +31,8 @@ import org.springframework.context.support.StaticApplicationContext; import org.springframework.tests.sample.beans.ITestBean; 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.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; /** @@ -119,9 +119,9 @@ public class EventPublicationInterceptorTests { testBean.getAge(); // two events: ContextRefreshedEvent and TestEvent - assertTrue("Interceptor must have published 2 events", listener.getEventCount() == 2); + assertThat(listener.getEventCount() == 2).as("Interceptor must have published 2 events").isTrue(); TestListener otherListener = (TestListener) ctx.getBean("&otherListener"); - assertTrue("Interceptor must have published 2 events", otherListener.getEventCount() == 2); + assertThat(otherListener.getEventCount() == 2).as("Interceptor must have published 2 events").isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/context/event/GenericApplicationListenerAdapterTests.java b/spring-context/src/test/java/org/springframework/context/event/GenericApplicationListenerAdapterTests.java index 20a8912b2e3..c6586aaaf68 100644 --- a/spring-context/src/test/java/org/springframework/context/event/GenericApplicationListenerAdapterTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/GenericApplicationListenerAdapterTests.java @@ -22,7 +22,7 @@ import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.core.ResolvableType; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -144,13 +144,13 @@ public class GenericApplicationListenerAdapterTests extends AbstractApplicationE } + @SuppressWarnings("rawtypes") private void supportsEventType( boolean match, Class listenerType, ResolvableType eventType) { ApplicationListener listener = mock(listenerType); GenericApplicationListenerAdapter adapter = new GenericApplicationListenerAdapter(listener); - assertEquals("Wrong match for event '" + eventType + "' on " + listenerType.getClass().getName(), - match, adapter.supportsEventType(eventType)); + assertThat(adapter.supportsEventType(eventType)).as("Wrong match for event '" + eventType + "' on " + listenerType.getClass().getName()).isEqualTo(match); } } diff --git a/spring-context/src/test/java/org/springframework/context/event/LifecycleEventTests.java b/spring-context/src/test/java/org/springframework/context/event/LifecycleEventTests.java index 30ee1feba26..519151d7b42 100644 --- a/spring-context/src/test/java/org/springframework/context/event/LifecycleEventTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/LifecycleEventTests.java @@ -24,10 +24,7 @@ import org.springframework.context.ApplicationListener; import org.springframework.context.Lifecycle; import org.springframework.context.support.StaticApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -43,12 +40,12 @@ public class LifecycleEventTests { context.refresh(); LifecycleTestBean lifecycleBean = (LifecycleTestBean) context.getBean("lifecycle"); LifecycleListener listener = (LifecycleListener) context.getBean("listener"); - assertFalse(lifecycleBean.isRunning()); - assertEquals(0, listener.getStartedCount()); + assertThat(lifecycleBean.isRunning()).isFalse(); + assertThat(listener.getStartedCount()).isEqualTo(0); context.start(); - assertTrue(lifecycleBean.isRunning()); - assertEquals(1, listener.getStartedCount()); - assertSame(context, listener.getApplicationContext()); + assertThat(lifecycleBean.isRunning()).isTrue(); + assertThat(listener.getStartedCount()).isEqualTo(1); + assertThat(listener.getApplicationContext()).isSameAs(context); } @Test @@ -59,14 +56,14 @@ public class LifecycleEventTests { context.refresh(); LifecycleTestBean lifecycleBean = (LifecycleTestBean) context.getBean("lifecycle"); LifecycleListener listener = (LifecycleListener) context.getBean("listener"); - assertFalse(lifecycleBean.isRunning()); + assertThat(lifecycleBean.isRunning()).isFalse(); context.start(); - assertTrue(lifecycleBean.isRunning()); - assertEquals(0, listener.getStoppedCount()); + assertThat(lifecycleBean.isRunning()).isTrue(); + assertThat(listener.getStoppedCount()).isEqualTo(0); context.stop(); - assertFalse(lifecycleBean.isRunning()); - assertEquals(1, listener.getStoppedCount()); - assertSame(context, listener.getApplicationContext()); + assertThat(lifecycleBean.isRunning()).isFalse(); + assertThat(listener.getStoppedCount()).isEqualTo(1); + assertThat(listener.getApplicationContext()).isSameAs(context); } diff --git a/spring-context/src/test/java/org/springframework/context/event/PayloadApplicationEventTests.java b/spring-context/src/test/java/org/springframework/context/event/PayloadApplicationEventTests.java index 80fa2a3f5cc..6d414179854 100644 --- a/spring-context/src/test/java/org/springframework/context/event/PayloadApplicationEventTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/PayloadApplicationEventTests.java @@ -26,7 +26,7 @@ import org.springframework.context.PayloadApplicationEvent; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -38,7 +38,7 @@ public class PayloadApplicationEventTests { ApplicationContext ac = new AnnotationConfigApplicationContext(AuditableListener.class); AuditablePayloadEvent event = new AuditablePayloadEvent<>(this, "xyz"); ac.publishEvent(event); - assertTrue(ac.getBean(AuditableListener.class).events.contains(event)); + assertThat(ac.getBean(AuditableListener.class).events.contains(event)).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/context/event/test/EventCollector.java b/spring-context/src/test/java/org/springframework/context/event/test/EventCollector.java index a9850528924..fdd8fa81f95 100644 --- a/spring-context/src/test/java/org/springframework/context/event/test/EventCollector.java +++ b/spring-context/src/test/java/org/springframework/context/event/test/EventCollector.java @@ -24,7 +24,7 @@ import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Test utility to collect and assert events. @@ -58,7 +58,7 @@ public class EventCollector { */ public void assertNoEventReceived(String listenerId) { List events = this.content.getOrDefault(listenerId, Collections.emptyList()); - assertEquals("Expected no events but got " + events, 0, events.size()); + assertThat(events.size()).as("Expected no events but got " + events).isEqualTo(0); } /** @@ -74,9 +74,9 @@ public class EventCollector { */ public void assertEvent(String listenerId, Object... events) { List actual = this.content.getOrDefault(listenerId, Collections.emptyList()); - assertEquals("Wrong number of events", events.length, actual.size()); + assertThat(actual.size()).as("Wrong number of events").isEqualTo(events.length); for (int i = 0; i < events.length; i++) { - assertEquals("Wrong event at index " + i, events[i], actual.get(i)); + assertThat(actual.get(i)).as("Wrong event at index " + i).isEqualTo(events[i]); } } @@ -98,8 +98,8 @@ public class EventCollector { for (Map.Entry> entry : this.content.entrySet()) { actual += entry.getValue().size(); } - assertEquals("Wrong number of total events (" + this.content.size() + - ") registered listener(s)", number, actual); + assertThat(actual).as("Wrong number of total events (" + this.content.size() + + ") registered listener(s)").isEqualTo(number); } /** diff --git a/spring-context/src/test/java/org/springframework/context/expression/AnnotatedElementKeyTests.java b/spring-context/src/test/java/org/springframework/context/expression/AnnotatedElementKeyTests.java index b418b8507cb..a1bcc6a3a62 100644 --- a/spring-context/src/test/java/org/springframework/context/expression/AnnotatedElementKeyTests.java +++ b/spring-context/src/test/java/org/springframework/context/expression/AnnotatedElementKeyTests.java @@ -24,8 +24,7 @@ import org.junit.rules.TestName; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -66,12 +65,12 @@ public class AnnotatedElementKeyTests { AnnotatedElementKey first = new AnnotatedElementKey(m, getClass()); AnnotatedElementKey second = new AnnotatedElementKey(m, null); - assertFalse(first.equals(second)); + assertThat(first.equals(second)).isFalse(); } protected void assertKeyEquals(AnnotatedElementKey first, AnnotatedElementKey second) { - assertEquals(first, second); - assertEquals(first.hashCode(), second.hashCode()); + assertThat(second).isEqualTo(first); + assertThat(second.hashCode()).isEqualTo(first.hashCode()); } } diff --git a/spring-context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java b/spring-context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java index c838631c495..78b5bb6c12c 100644 --- a/spring-context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java +++ b/spring-context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java @@ -58,11 +58,7 @@ import org.springframework.util.FileCopyUtils; import org.springframework.util.SerializationTestUtils; import org.springframework.util.StopWatch; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -162,51 +158,51 @@ public class ApplicationContextExpressionTests { TestBean tb0 = ac.getBean("tb0", TestBean.class); TestBean tb1 = ac.getBean("tb1", TestBean.class); - assertEquals("XXXmyNameYYY42ZZZ", tb1.getName()); - assertEquals(42, tb1.getAge()); + assertThat(tb1.getName()).isEqualTo("XXXmyNameYYY42ZZZ"); + assertThat(tb1.getAge()).isEqualTo(42); TestBean tb2 = ac.getBean("tb2", TestBean.class); - assertEquals("{ XXXmyNameYYY42ZZZ }", tb2.getName()); - assertEquals(42, tb2.getAge()); - assertEquals("123 UK", tb2.getCountry()); + assertThat(tb2.getName()).isEqualTo("{ XXXmyNameYYY42ZZZ }"); + assertThat(tb2.getAge()).isEqualTo(42); + assertThat(tb2.getCountry()).isEqualTo("123 UK"); ValueTestBean tb3 = ac.getBean("tb3", ValueTestBean.class); - assertEquals("XXXmyNameYYY42ZZZ", tb3.name); - assertEquals(42, tb3.age); - assertEquals(42, tb3.ageFactory.getObject().intValue()); - assertEquals("123 UK", tb3.country); - assertEquals("123 UK", tb3.countryFactory.getObject()); + assertThat(tb3.name).isEqualTo("XXXmyNameYYY42ZZZ"); + assertThat(tb3.age).isEqualTo(42); + assertThat(tb3.ageFactory.getObject().intValue()).isEqualTo(42); + assertThat(tb3.country).isEqualTo("123 UK"); + assertThat(tb3.countryFactory.getObject()).isEqualTo("123 UK"); System.getProperties().put("country", "US"); - assertEquals("123 UK", tb3.country); - assertEquals("123 US", tb3.countryFactory.getObject()); + assertThat(tb3.country).isEqualTo("123 UK"); + assertThat(tb3.countryFactory.getObject()).isEqualTo("123 US"); System.getProperties().put("country", "UK"); - assertEquals("123 UK", tb3.country); - assertEquals("123 UK", tb3.countryFactory.getObject()); - assertEquals("123", tb3.optionalValue1.get()); - assertEquals("123", tb3.optionalValue2.get()); - assertFalse(tb3.optionalValue3.isPresent()); - assertSame(tb0, tb3.tb); + assertThat(tb3.country).isEqualTo("123 UK"); + assertThat(tb3.countryFactory.getObject()).isEqualTo("123 UK"); + assertThat(tb3.optionalValue1.get()).isEqualTo("123"); + assertThat(tb3.optionalValue2.get()).isEqualTo("123"); + assertThat(tb3.optionalValue3.isPresent()).isFalse(); + assertThat(tb3.tb).isSameAs(tb0); tb3 = (ValueTestBean) SerializationTestUtils.serializeAndDeserialize(tb3); - assertEquals("123 UK", tb3.countryFactory.getObject()); + assertThat(tb3.countryFactory.getObject()).isEqualTo("123 UK"); ConstructorValueTestBean tb4 = ac.getBean("tb4", ConstructorValueTestBean.class); - assertEquals("XXXmyNameYYY42ZZZ", tb4.name); - assertEquals(42, tb4.age); - assertEquals("123 UK", tb4.country); - assertSame(tb0, tb4.tb); + assertThat(tb4.name).isEqualTo("XXXmyNameYYY42ZZZ"); + assertThat(tb4.age).isEqualTo(42); + assertThat(tb4.country).isEqualTo("123 UK"); + assertThat(tb4.tb).isSameAs(tb0); MethodValueTestBean tb5 = ac.getBean("tb5", MethodValueTestBean.class); - assertEquals("XXXmyNameYYY42ZZZ", tb5.name); - assertEquals(42, tb5.age); - assertEquals("123 UK", tb5.country); - assertSame(tb0, tb5.tb); + assertThat(tb5.name).isEqualTo("XXXmyNameYYY42ZZZ"); + assertThat(tb5.age).isEqualTo(42); + assertThat(tb5.country).isEqualTo("123 UK"); + assertThat(tb5.tb).isSameAs(tb0); PropertyValueTestBean tb6 = ac.getBean("tb6", PropertyValueTestBean.class); - assertEquals("XXXmyNameYYY42ZZZ", tb6.name); - assertEquals(42, tb6.age); - assertEquals("123 UK", tb6.country); - assertSame(tb0, tb6.tb); + assertThat(tb6.name).isEqualTo("XXXmyNameYYY42ZZZ"); + assertThat(tb6.age).isEqualTo(42); + assertThat(tb6.country).isEqualTo("123 UK"); + assertThat(tb6.tb).isSameAs(tb0); } finally { System.getProperties().remove("country"); @@ -231,16 +227,16 @@ public class ApplicationContextExpressionTests { System.getProperties().put("name", "juergen1"); System.getProperties().put("country", " UK1 "); PrototypeTestBean tb = (PrototypeTestBean) ac.getBean("test"); - assertEquals("juergen1", tb.getName()); - assertEquals("UK1", tb.getCountry()); - assertEquals("-UK1-", tb.getCountry2()); + assertThat(tb.getName()).isEqualTo("juergen1"); + assertThat(tb.getCountry()).isEqualTo("UK1"); + assertThat(tb.getCountry2()).isEqualTo("-UK1-"); System.getProperties().put("name", "juergen2"); System.getProperties().put("country", " UK2 "); tb = (PrototypeTestBean) ac.getBean("test"); - assertEquals("juergen2", tb.getName()); - assertEquals("UK2", tb.getCountry()); - assertEquals("-UK2-", tb.getCountry2()); + assertThat(tb.getName()).isEqualTo("juergen2"); + assertThat(tb.getCountry()).isEqualTo("UK2"); + assertThat(tb.getCountry2()).isEqualTo("-UK2-"); } finally { System.getProperties().remove("name"); @@ -266,8 +262,8 @@ public class ApplicationContextExpressionTests { try { for (int i = 0; i < 100000; i++) { TestBean tb = (TestBean) ac.getBean("test"); - assertEquals("juergen", tb.getName()); - assertEquals("UK", tb.getCountry()); + assertThat(tb.getName()).isEqualTo("juergen"); + assertThat(tb.getCountry()).isEqualTo("UK"); } sw.stop(); } @@ -275,7 +271,7 @@ public class ApplicationContextExpressionTests { System.getProperties().remove("country"); System.getProperties().remove("name"); } - assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 6000); + assertThat(sw.getTotalTimeMillis() < 6000).as("Prototype creation took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -305,7 +301,7 @@ public class ApplicationContextExpressionTests { ac.refresh(); TestBean tb = ac.getBean("tb", TestBean.class); - assertEquals("NL", tb.getCountry()); + assertThat(tb.getCountry()).isEqualTo("NL"); } finally { @@ -325,7 +321,7 @@ public class ApplicationContextExpressionTests { ac.refresh(); String str = ac.getBean("str", String.class); - assertTrue(str.startsWith("test-")); + assertThat(str.startsWith("test-")).isTrue(); } @Test @@ -334,14 +330,12 @@ public class ApplicationContextExpressionTests { try (AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ResourceInjectionBean.class)) { ResourceInjectionBean resourceInjectionBean = ac.getBean(ResourceInjectionBean.class); Resource resource = new ClassPathResource("do_not_delete_me.txt"); - assertEquals(resource, resourceInjectionBean.resource); - assertEquals(resource.getURL(), resourceInjectionBean.url); - assertEquals(resource.getURI(), resourceInjectionBean.uri); - assertEquals(resource.getFile(), resourceInjectionBean.file); - assertArrayEquals(FileCopyUtils.copyToByteArray(resource.getInputStream()), - FileCopyUtils.copyToByteArray(resourceInjectionBean.inputStream)); - assertEquals(FileCopyUtils.copyToString(new EncodedResource(resource).getReader()), - FileCopyUtils.copyToString(resourceInjectionBean.reader)); + assertThat(resourceInjectionBean.resource).isEqualTo(resource); + assertThat(resourceInjectionBean.url).isEqualTo(resource.getURL()); + assertThat(resourceInjectionBean.uri).isEqualTo(resource.getURI()); + assertThat(resourceInjectionBean.file).isEqualTo(resource.getFile()); + assertThat(FileCopyUtils.copyToByteArray(resourceInjectionBean.inputStream)).isEqualTo(FileCopyUtils.copyToByteArray(resource.getInputStream())); + assertThat(FileCopyUtils.copyToString(resourceInjectionBean.reader)).isEqualTo(FileCopyUtils.copyToString(new EncodedResource(resource).getReader())); } finally { System.getProperties().remove("logfile"); diff --git a/spring-context/src/test/java/org/springframework/context/expression/CachedExpressionEvaluatorTests.java b/spring-context/src/test/java/org/springframework/context/expression/CachedExpressionEvaluatorTests.java index 8b917b7146d..9b1d4f42a61 100644 --- a/spring-context/src/test/java/org/springframework/context/expression/CachedExpressionEvaluatorTests.java +++ b/spring-context/src/test/java/org/springframework/context/expression/CachedExpressionEvaluatorTests.java @@ -26,7 +26,7 @@ import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -43,8 +43,8 @@ public class CachedExpressionEvaluatorTests { Method method = ReflectionUtils.findMethod(getClass(), "toString"); Expression expression = expressionEvaluator.getTestExpression("true", method, getClass()); hasParsedExpression("true"); - assertEquals(true, expression.getValue()); - assertEquals("Expression should be in cache", 1, expressionEvaluator.testCache.size()); + assertThat(expression.getValue()).isEqualTo(true); + assertThat(expressionEvaluator.testCache.size()).as("Expression should be in cache").isEqualTo(1); } @Test @@ -55,7 +55,7 @@ public class CachedExpressionEvaluatorTests { expressionEvaluator.getTestExpression("true", method, getClass()); expressionEvaluator.getTestExpression("true", method, getClass()); hasParsedExpression("true"); - assertEquals("Only one expression should be in cache", 1, expressionEvaluator.testCache.size()); + assertThat(expressionEvaluator.testCache.size()).as("Only one expression should be in cache").isEqualTo(1); } @Test @@ -63,7 +63,7 @@ public class CachedExpressionEvaluatorTests { Method method = ReflectionUtils.findMethod(getClass(), "toString"); expressionEvaluator.getTestExpression("true", method, getClass()); expressionEvaluator.getTestExpression("true", method, Object.class); - assertEquals("Cached expression should be based on type", 2, expressionEvaluator.testCache.size()); + assertThat(expressionEvaluator.testCache.size()).as("Cached expression should be based on type").isEqualTo(2); } private void hasParsedExpression(String expression) { diff --git a/spring-context/src/test/java/org/springframework/context/expression/FactoryBeanAccessTests.java b/spring-context/src/test/java/org/springframework/context/expression/FactoryBeanAccessTests.java index e8d0b34f310..178016dbca8 100644 --- a/spring-context/src/test/java/org/springframework/context/expression/FactoryBeanAccessTests.java +++ b/spring-context/src/test/java/org/springframework/context/expression/FactoryBeanAccessTests.java @@ -29,8 +29,8 @@ import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * Unit tests for expressions accessing beans and factory beans. @@ -44,12 +44,12 @@ public class FactoryBeanAccessTests { StandardEvaluationContext context = new StandardEvaluationContext(); context.setBeanResolver(new SimpleBeanResolver()); Expression expr = new SpelExpressionParser().parseRaw("@car.colour"); - assertEquals("red", expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo("red"); expr = new SpelExpressionParser().parseRaw("&car.class.name"); - assertEquals(CarFactoryBean.class.getName(), expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo(CarFactoryBean.class.getName()); expr = new SpelExpressionParser().parseRaw("@boat.colour"); - assertEquals("blue",expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo("blue"); Expression notFactoryExpr = new SpelExpressionParser().parseRaw("&boat.class.name"); assertThatExceptionOfType(BeanIsNotAFactoryException.class).isThrownBy(() -> notFactoryExpr.getValue(context)); diff --git a/spring-context/src/test/java/org/springframework/context/expression/MapAccessorTests.java b/spring-context/src/test/java/org/springframework/context/expression/MapAccessorTests.java index 6c04480f463..10027134418 100644 --- a/spring-context/src/test/java/org/springframework/context/expression/MapAccessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/expression/MapAccessorTests.java @@ -26,8 +26,7 @@ import org.springframework.expression.spel.standard.SpelCompiler; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for compilation of {@link MapAccessor}. @@ -45,29 +44,29 @@ public class MapAccessorTests { // basic Expression ex = sep.parseExpression("foo"); - assertEquals("bar",ex.getValue(sec,testMap)); - assertTrue(SpelCompiler.compile(ex)); - assertEquals("bar",ex.getValue(sec,testMap)); + assertThat(ex.getValue(sec,testMap)).isEqualTo("bar"); + assertThat(SpelCompiler.compile(ex)).isTrue(); + assertThat(ex.getValue(sec,testMap)).isEqualTo("bar"); // compound expression ex = sep.parseExpression("foo.toUpperCase()"); - assertEquals("BAR",ex.getValue(sec,testMap)); - assertTrue(SpelCompiler.compile(ex)); - assertEquals("BAR",ex.getValue(sec,testMap)); + assertThat(ex.getValue(sec,testMap)).isEqualTo("BAR"); + assertThat(SpelCompiler.compile(ex)).isTrue(); + assertThat(ex.getValue(sec,testMap)).isEqualTo("BAR"); // nested map Map> nestedMap = getNestedTestMap(); ex = sep.parseExpression("aaa.foo.toUpperCase()"); - assertEquals("BAR",ex.getValue(sec,nestedMap)); - assertTrue(SpelCompiler.compile(ex)); - assertEquals("BAR",ex.getValue(sec,nestedMap)); + assertThat(ex.getValue(sec,nestedMap)).isEqualTo("BAR"); + assertThat(SpelCompiler.compile(ex)).isTrue(); + assertThat(ex.getValue(sec,nestedMap)).isEqualTo("BAR"); // avoiding inserting checkcast because first part of expression returns a Map ex = sep.parseExpression("getMap().foo"); MapGetter mapGetter = new MapGetter(); - assertEquals("bar",ex.getValue(sec,mapGetter)); - assertTrue(SpelCompiler.compile(ex)); - assertEquals("bar",ex.getValue(sec,mapGetter)); + assertThat(ex.getValue(sec,mapGetter)).isEqualTo("bar"); + assertThat(SpelCompiler.compile(ex)).isTrue(); + assertThat(ex.getValue(sec,mapGetter)).isEqualTo("bar"); } public static class MapGetter { diff --git a/spring-context/src/test/java/org/springframework/context/expression/MethodBasedEvaluationContextTests.java b/spring-context/src/test/java/org/springframework/context/expression/MethodBasedEvaluationContextTests.java index 30b370cd3a5..7acf07c0905 100644 --- a/spring-context/src/test/java/org/springframework/context/expression/MethodBasedEvaluationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/expression/MethodBasedEvaluationContextTests.java @@ -24,9 +24,7 @@ import org.springframework.core.DefaultParameterNameDiscoverer; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link MethodBasedEvaluationContext}. @@ -45,16 +43,16 @@ public class MethodBasedEvaluationContextTests { Method method = ReflectionUtils.findMethod(SampleMethods.class, "hello", String.class, Boolean.class); MethodBasedEvaluationContext context = createEvaluationContext(method, "test", true); - assertEquals("test", context.lookupVariable("a0")); - assertEquals("test", context.lookupVariable("p0")); - assertEquals("test", context.lookupVariable("foo")); + assertThat(context.lookupVariable("a0")).isEqualTo("test"); + assertThat(context.lookupVariable("p0")).isEqualTo("test"); + assertThat(context.lookupVariable("foo")).isEqualTo("test"); - assertEquals(true, context.lookupVariable("a1")); - assertEquals(true, context.lookupVariable("p1")); - assertEquals(true, context.lookupVariable("flag")); + assertThat(context.lookupVariable("a1")).isEqualTo(true); + assertThat(context.lookupVariable("p1")).isEqualTo(true); + assertThat(context.lookupVariable("flag")).isEqualTo(true); - assertNull(context.lookupVariable("a2")); - assertNull(context.lookupVariable("p2")); + assertThat(context.lookupVariable("a2")).isNull(); + assertThat(context.lookupVariable("p2")).isNull(); } @Test @@ -62,13 +60,13 @@ public class MethodBasedEvaluationContextTests { Method method = ReflectionUtils.findMethod(SampleMethods.class, "hello", String.class, Boolean.class); MethodBasedEvaluationContext context = createEvaluationContext(method, null, null); - assertNull(context.lookupVariable("a0")); - assertNull(context.lookupVariable("p0")); - assertNull(context.lookupVariable("foo")); + assertThat(context.lookupVariable("a0")).isNull(); + assertThat(context.lookupVariable("p0")).isNull(); + assertThat(context.lookupVariable("foo")).isNull(); - assertNull(context.lookupVariable("a1")); - assertNull(context.lookupVariable("p1")); - assertNull(context.lookupVariable("flag")); + assertThat(context.lookupVariable("a1")).isNull(); + assertThat(context.lookupVariable("p1")).isNull(); + assertThat(context.lookupVariable("flag")).isNull(); } @Test @@ -76,13 +74,13 @@ public class MethodBasedEvaluationContextTests { Method method = ReflectionUtils.findMethod(SampleMethods.class, "hello", Boolean.class, String[].class); MethodBasedEvaluationContext context = createEvaluationContext(method, new Object[] {null}); - assertNull(context.lookupVariable("a0")); - assertNull(context.lookupVariable("p0")); - assertNull(context.lookupVariable("flag")); + assertThat(context.lookupVariable("a0")).isNull(); + assertThat(context.lookupVariable("p0")).isNull(); + assertThat(context.lookupVariable("flag")).isNull(); - assertNull(context.lookupVariable("a1")); - assertNull(context.lookupVariable("p1")); - assertNull(context.lookupVariable("vararg")); + assertThat(context.lookupVariable("a1")).isNull(); + assertThat(context.lookupVariable("p1")).isNull(); + assertThat(context.lookupVariable("vararg")).isNull(); } @Test @@ -90,13 +88,13 @@ public class MethodBasedEvaluationContextTests { Method method = ReflectionUtils.findMethod(SampleMethods.class, "hello", Boolean.class, String[].class); MethodBasedEvaluationContext context = createEvaluationContext(method, null, null); - assertNull(context.lookupVariable("a0")); - assertNull(context.lookupVariable("p0")); - assertNull(context.lookupVariable("flag")); + assertThat(context.lookupVariable("a0")).isNull(); + assertThat(context.lookupVariable("p0")).isNull(); + assertThat(context.lookupVariable("flag")).isNull(); - assertNull(context.lookupVariable("a1")); - assertNull(context.lookupVariable("p1")); - assertNull(context.lookupVariable("vararg")); + assertThat(context.lookupVariable("a1")).isNull(); + assertThat(context.lookupVariable("p1")).isNull(); + assertThat(context.lookupVariable("vararg")).isNull(); } @Test @@ -104,13 +102,13 @@ public class MethodBasedEvaluationContextTests { Method method = ReflectionUtils.findMethod(SampleMethods.class, "hello", Boolean.class, String[].class); MethodBasedEvaluationContext context = createEvaluationContext(method, null, "hello"); - assertNull(context.lookupVariable("a0")); - assertNull(context.lookupVariable("p0")); - assertNull(context.lookupVariable("flag")); + assertThat(context.lookupVariable("a0")).isNull(); + assertThat(context.lookupVariable("p0")).isNull(); + assertThat(context.lookupVariable("flag")).isNull(); - assertEquals("hello", context.lookupVariable("a1")); - assertEquals("hello", context.lookupVariable("p1")); - assertEquals("hello", context.lookupVariable("vararg")); + assertThat(context.lookupVariable("a1")).isEqualTo("hello"); + assertThat(context.lookupVariable("p1")).isEqualTo("hello"); + assertThat(context.lookupVariable("vararg")).isEqualTo("hello"); } @Test @@ -118,13 +116,13 @@ public class MethodBasedEvaluationContextTests { Method method = ReflectionUtils.findMethod(SampleMethods.class, "hello", Boolean.class, String[].class); MethodBasedEvaluationContext context = createEvaluationContext(method, null, "hello", "hi"); - assertNull(context.lookupVariable("a0")); - assertNull(context.lookupVariable("p0")); - assertNull(context.lookupVariable("flag")); + assertThat(context.lookupVariable("a0")).isNull(); + assertThat(context.lookupVariable("p0")).isNull(); + assertThat(context.lookupVariable("flag")).isNull(); - assertArrayEquals(new Object[] {"hello", "hi"}, (Object[]) context.lookupVariable("a1")); - assertArrayEquals(new Object[] {"hello", "hi"}, (Object[]) context.lookupVariable("p1")); - assertArrayEquals(new Object[] {"hello", "hi"}, (Object[]) context.lookupVariable("vararg")); + assertThat(context.lookupVariable("a1")).isEqualTo(new Object[] {"hello", "hi"}); + assertThat(context.lookupVariable("p1")).isEqualTo(new Object[] {"hello", "hi"}); + assertThat(context.lookupVariable("vararg")).isEqualTo(new Object[] {"hello", "hi"}); } private MethodBasedEvaluationContext createEvaluationContext(Method method, Object... args) { diff --git a/spring-context/src/test/java/org/springframework/context/groovy/GroovyApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/groovy/GroovyApplicationContextTests.java index cbe3a852726..a8c53429c66 100644 --- a/spring-context/src/test/java/org/springframework/context/groovy/GroovyApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/groovy/GroovyApplicationContextTests.java @@ -21,9 +21,8 @@ import org.junit.Test; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; import org.springframework.context.support.GenericGroovyApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * @author Jeff Brown @@ -37,8 +36,8 @@ public class GroovyApplicationContextTests { "org/springframework/context/groovy/applicationContext.groovy"); Object framework = ctx.getBean("framework"); - assertNotNull("could not find framework bean", framework); - assertEquals("Grails", framework); + assertThat(framework).as("could not find framework bean").isNotNull(); + assertThat(framework).isEqualTo("Grails"); } @Test @@ -48,12 +47,12 @@ public class GroovyApplicationContextTests { "org/springframework/context/groovy/applicationContext.groovy"); Object framework = ctx.getBean("framework"); - assertNotNull("could not find framework bean", framework); - assertEquals("Grails", framework); + assertThat(framework).as("could not find framework bean").isNotNull(); + assertThat(framework).isEqualTo("Grails"); Object company = ctx.getBean("company"); - assertNotNull("could not find company bean", company); - assertEquals("SpringSource", company); + assertThat(company).as("could not find company bean").isNotNull(); + assertThat(company).isEqualTo("SpringSource"); } @Test @@ -63,12 +62,12 @@ public class GroovyApplicationContextTests { ctx.refresh(); Object framework = ctx.getBean("framework"); - assertNotNull("could not find framework bean", framework); - assertEquals("Grails", framework); + assertThat(framework).as("could not find framework bean").isNotNull(); + assertThat(framework).isEqualTo("Grails"); Object company = ctx.getBean("company"); - assertNotNull("could not find company bean", company); - assertEquals("SpringSource", company); + assertThat(company).as("could not find company bean").isNotNull(); + assertThat(company).isEqualTo("SpringSource"); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/i18n/LocaleContextHolderTests.java b/spring-context/src/test/java/org/springframework/context/i18n/LocaleContextHolderTests.java index dcdeb0414f4..d9dafbf26fb 100644 --- a/spring-context/src/test/java/org/springframework/context/i18n/LocaleContextHolderTests.java +++ b/spring-context/src/test/java/org/springframework/context/i18n/LocaleContextHolderTests.java @@ -21,11 +21,7 @@ import java.util.TimeZone; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -36,134 +32,144 @@ public class LocaleContextHolderTests { public void testSetLocaleContext() { LocaleContext lc = new SimpleLocaleContext(Locale.GERMAN); LocaleContextHolder.setLocaleContext(lc); - assertSame(lc, LocaleContextHolder.getLocaleContext()); - assertEquals(Locale.GERMAN, LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); + assertThat(LocaleContextHolder.getLocaleContext()).isSameAs(lc); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); lc = new SimpleLocaleContext(Locale.GERMANY); LocaleContextHolder.setLocaleContext(lc); - assertSame(lc, LocaleContextHolder.getLocaleContext()); - assertEquals(Locale.GERMANY, LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); + assertThat(LocaleContextHolder.getLocaleContext()).isSameAs(lc); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMANY); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); LocaleContextHolder.resetLocaleContext(); - assertNull(LocaleContextHolder.getLocaleContext()); - assertEquals(Locale.getDefault(), LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); + assertThat(LocaleContextHolder.getLocaleContext()).isNull(); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault()); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); } @Test public void testSetTimeZoneAwareLocaleContext() { LocaleContext lc = new SimpleTimeZoneAwareLocaleContext(Locale.GERMANY, TimeZone.getTimeZone("GMT+1")); LocaleContextHolder.setLocaleContext(lc); - assertSame(lc, LocaleContextHolder.getLocaleContext()); - assertEquals(Locale.GERMANY, LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+1"), LocaleContextHolder.getTimeZone()); + assertThat(LocaleContextHolder.getLocaleContext()).isSameAs(lc); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMANY); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); LocaleContextHolder.resetLocaleContext(); - assertNull(LocaleContextHolder.getLocaleContext()); - assertEquals(Locale.getDefault(), LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); + assertThat(LocaleContextHolder.getLocaleContext()).isNull(); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault()); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); } @Test public void testSetLocale() { LocaleContextHolder.setLocale(Locale.GERMAN); - assertEquals(Locale.GERMAN, LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); - assertFalse(LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext); - assertEquals(Locale.GERMAN, LocaleContextHolder.getLocaleContext().getLocale()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); + boolean condition1 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext; + assertThat(condition1).isFalse(); + assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMAN); LocaleContextHolder.setLocale(Locale.GERMANY); - assertEquals(Locale.GERMANY, LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); - assertFalse(LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext); - assertEquals(Locale.GERMANY, LocaleContextHolder.getLocaleContext().getLocale()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMANY); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); + boolean condition = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isFalse(); + assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMANY); LocaleContextHolder.setLocale(null); - assertNull(LocaleContextHolder.getLocaleContext()); - assertEquals(Locale.getDefault(), LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); + assertThat(LocaleContextHolder.getLocaleContext()).isNull(); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault()); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); LocaleContextHolder.setDefaultLocale(Locale.GERMAN); - assertEquals(Locale.GERMAN, LocaleContextHolder.getLocale()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN); LocaleContextHolder.setDefaultLocale(null); - assertEquals(Locale.getDefault(), LocaleContextHolder.getLocale()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault()); } @Test public void testSetTimeZone() { LocaleContextHolder.setTimeZone(TimeZone.getTimeZone("GMT+1")); - assertEquals(Locale.getDefault(), LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+1"), LocaleContextHolder.getTimeZone()); - assertTrue(LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext); - assertNull(LocaleContextHolder.getLocaleContext().getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+1"), ((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault()); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); + boolean condition1 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext; + assertThat(condition1).isTrue(); + assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isNull(); + assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); LocaleContextHolder.setTimeZone(TimeZone.getTimeZone("GMT+2")); - assertEquals(Locale.getDefault(), LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+2"), LocaleContextHolder.getTimeZone()); - assertTrue(LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext); - assertNull(LocaleContextHolder.getLocaleContext().getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+2"), ((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault()); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2")); + boolean condition = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isNull(); + assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2")); LocaleContextHolder.setTimeZone(null); - assertNull(LocaleContextHolder.getLocaleContext()); - assertEquals(Locale.getDefault(), LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); + assertThat(LocaleContextHolder.getLocaleContext()).isNull(); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault()); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); LocaleContextHolder.setDefaultTimeZone(TimeZone.getTimeZone("GMT+1")); - assertEquals(TimeZone.getTimeZone("GMT+1"), LocaleContextHolder.getTimeZone()); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); LocaleContextHolder.setDefaultTimeZone(null); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); } @Test public void testSetLocaleAndSetTimeZoneMixed() { LocaleContextHolder.setLocale(Locale.GERMANY); - assertEquals(Locale.GERMANY, LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); - assertFalse(LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext); - assertEquals(Locale.GERMANY, LocaleContextHolder.getLocaleContext().getLocale()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMANY); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); + boolean condition5 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext; + assertThat(condition5).isFalse(); + assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMANY); LocaleContextHolder.setTimeZone(TimeZone.getTimeZone("GMT+1")); - assertEquals(Locale.GERMANY, LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+1"), LocaleContextHolder.getTimeZone()); - assertTrue(LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext); - assertEquals(Locale.GERMANY, LocaleContextHolder.getLocaleContext().getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+1"), ((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMANY); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); + boolean condition3 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext; + assertThat(condition3).isTrue(); + assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMANY); + assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); LocaleContextHolder.setLocale(Locale.GERMAN); - assertEquals(Locale.GERMAN, LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+1"), LocaleContextHolder.getTimeZone()); - assertTrue(LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext); - assertEquals(Locale.GERMAN, LocaleContextHolder.getLocaleContext().getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+1"), ((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); + boolean condition2 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext; + assertThat(condition2).isTrue(); + assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMAN); + assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); LocaleContextHolder.setTimeZone(null); - assertEquals(Locale.GERMAN, LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); - assertFalse(LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext); - assertEquals(Locale.GERMAN, LocaleContextHolder.getLocaleContext().getLocale()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); + boolean condition4 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext; + assertThat(condition4).isFalse(); + assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMAN); LocaleContextHolder.setTimeZone(TimeZone.getTimeZone("GMT+2")); - assertEquals(Locale.GERMAN, LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+2"), LocaleContextHolder.getTimeZone()); - assertTrue(LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext); - assertEquals(Locale.GERMAN, LocaleContextHolder.getLocaleContext().getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+2"), ((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.GERMAN); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2")); + boolean condition1 = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext; + assertThat(condition1).isTrue(); + assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isEqualTo(Locale.GERMAN); + assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2")); LocaleContextHolder.setLocale(null); - assertEquals(Locale.getDefault(), LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+2"), LocaleContextHolder.getTimeZone()); - assertTrue(LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext); - assertNull(LocaleContextHolder.getLocaleContext().getLocale()); - assertEquals(TimeZone.getTimeZone("GMT+2"), ((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault()); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2")); + boolean condition = LocaleContextHolder.getLocaleContext() instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(LocaleContextHolder.getLocaleContext().getLocale()).isNull(); + assertThat(((TimeZoneAwareLocaleContext) LocaleContextHolder.getLocaleContext()).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2")); LocaleContextHolder.setTimeZone(null); - assertEquals(Locale.getDefault(), LocaleContextHolder.getLocale()); - assertEquals(TimeZone.getDefault(), LocaleContextHolder.getTimeZone()); - assertNull(LocaleContextHolder.getLocaleContext()); + assertThat(LocaleContextHolder.getLocale()).isEqualTo(Locale.getDefault()); + assertThat(LocaleContextHolder.getTimeZone()).isEqualTo(TimeZone.getDefault()); + assertThat(LocaleContextHolder.getLocaleContext()).isNull(); } } diff --git a/spring-context/src/test/java/org/springframework/context/support/ApplicationContextLifecycleTests.java b/spring-context/src/test/java/org/springframework/context/support/ApplicationContextLifecycleTests.java index 2fc1c6cbf9d..fafe355c955 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ApplicationContextLifecycleTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/ApplicationContextLifecycleTests.java @@ -18,8 +18,7 @@ package org.springframework.context.support; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -36,10 +35,10 @@ public class ApplicationContextLifecycleTests { LifecycleTestBean bean3 = (LifecycleTestBean) context.getBean("bean3"); LifecycleTestBean bean4 = (LifecycleTestBean) context.getBean("bean4"); String error = "bean was not started"; - assertTrue(error, bean1.isRunning()); - assertTrue(error, bean2.isRunning()); - assertTrue(error, bean3.isRunning()); - assertTrue(error, bean4.isRunning()); + assertThat(bean1.isRunning()).as(error).isTrue(); + assertThat(bean2.isRunning()).as(error).isTrue(); + assertThat(bean3.isRunning()).as(error).isTrue(); + assertThat(bean4.isRunning()).as(error).isTrue(); } @Test @@ -51,16 +50,16 @@ public class ApplicationContextLifecycleTests { LifecycleTestBean bean3 = (LifecycleTestBean) context.getBean("bean3"); LifecycleTestBean bean4 = (LifecycleTestBean) context.getBean("bean4"); String startError = "bean was not started"; - assertTrue(startError, bean1.isRunning()); - assertTrue(startError, bean2.isRunning()); - assertTrue(startError, bean3.isRunning()); - assertTrue(startError, bean4.isRunning()); + assertThat(bean1.isRunning()).as(startError).isTrue(); + assertThat(bean2.isRunning()).as(startError).isTrue(); + assertThat(bean3.isRunning()).as(startError).isTrue(); + assertThat(bean4.isRunning()).as(startError).isTrue(); context.stop(); String stopError = "bean was not stopped"; - assertFalse(stopError, bean1.isRunning()); - assertFalse(stopError, bean2.isRunning()); - assertFalse(stopError, bean3.isRunning()); - assertFalse(stopError, bean4.isRunning()); + assertThat(bean1.isRunning()).as(stopError).isFalse(); + assertThat(bean2.isRunning()).as(stopError).isFalse(); + assertThat(bean3.isRunning()).as(stopError).isFalse(); + assertThat(bean4.isRunning()).as(stopError).isFalse(); } @Test @@ -72,14 +71,14 @@ public class ApplicationContextLifecycleTests { LifecycleTestBean bean3 = (LifecycleTestBean) context.getBean("bean3"); LifecycleTestBean bean4 = (LifecycleTestBean) context.getBean("bean4"); String notStartedError = "bean was not started"; - assertTrue(notStartedError, bean1.getStartOrder() > 0); - assertTrue(notStartedError, bean2.getStartOrder() > 0); - assertTrue(notStartedError, bean3.getStartOrder() > 0); - assertTrue(notStartedError, bean4.getStartOrder() > 0); + assertThat(bean1.getStartOrder() > 0).as(notStartedError).isTrue(); + assertThat(bean2.getStartOrder() > 0).as(notStartedError).isTrue(); + assertThat(bean3.getStartOrder() > 0).as(notStartedError).isTrue(); + assertThat(bean4.getStartOrder() > 0).as(notStartedError).isTrue(); String orderError = "dependent bean must start after the bean it depends on"; - assertTrue(orderError, bean2.getStartOrder() > bean1.getStartOrder()); - assertTrue(orderError, bean3.getStartOrder() > bean2.getStartOrder()); - assertTrue(orderError, bean4.getStartOrder() > bean2.getStartOrder()); + assertThat(bean2.getStartOrder() > bean1.getStartOrder()).as(orderError).isTrue(); + assertThat(bean3.getStartOrder() > bean2.getStartOrder()).as(orderError).isTrue(); + assertThat(bean4.getStartOrder() > bean2.getStartOrder()).as(orderError).isTrue(); } @Test @@ -92,14 +91,14 @@ public class ApplicationContextLifecycleTests { LifecycleTestBean bean3 = (LifecycleTestBean) context.getBean("bean3"); LifecycleTestBean bean4 = (LifecycleTestBean) context.getBean("bean4"); String notStoppedError = "bean was not stopped"; - assertTrue(notStoppedError, bean1.getStopOrder() > 0); - assertTrue(notStoppedError, bean2.getStopOrder() > 0); - assertTrue(notStoppedError, bean3.getStopOrder() > 0); - assertTrue(notStoppedError, bean4.getStopOrder() > 0); + assertThat(bean1.getStopOrder() > 0).as(notStoppedError).isTrue(); + assertThat(bean2.getStopOrder() > 0).as(notStoppedError).isTrue(); + assertThat(bean3.getStopOrder() > 0).as(notStoppedError).isTrue(); + assertThat(bean4.getStopOrder() > 0).as(notStoppedError).isTrue(); String orderError = "dependent bean must stop before the bean it depends on"; - assertTrue(orderError, bean2.getStopOrder() < bean1.getStopOrder()); - assertTrue(orderError, bean3.getStopOrder() < bean2.getStopOrder()); - assertTrue(orderError, bean4.getStopOrder() < bean2.getStopOrder()); + assertThat(bean2.getStopOrder() < bean1.getStopOrder()).as(orderError).isTrue(); + assertThat(bean3.getStopOrder() < bean2.getStopOrder()).as(orderError).isTrue(); + assertThat(bean4.getStopOrder() < bean2.getStopOrder()).as(orderError).isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/context/support/BeanFactoryPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/support/BeanFactoryPostProcessorTests.java index a4cdafe845b..1ddd43ef3f2 100644 --- a/spring-context/src/test/java/org/springframework/context/support/BeanFactoryPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/BeanFactoryPostProcessorTests.java @@ -36,9 +36,7 @@ import org.springframework.core.PriorityOrdered; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.Assert; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests the interaction between {@link ApplicationContext} implementations and @@ -60,9 +58,9 @@ public class BeanFactoryPostProcessorTests { ac.registerSingleton("tb2", TestBean.class); TestBeanFactoryPostProcessor bfpp = new TestBeanFactoryPostProcessor(); ac.addBeanFactoryPostProcessor(bfpp); - assertFalse(bfpp.wasCalled); + assertThat(bfpp.wasCalled).isFalse(); ac.refresh(); - assertTrue(bfpp.wasCalled); + assertThat(bfpp.wasCalled).isTrue(); } @Test @@ -73,7 +71,7 @@ public class BeanFactoryPostProcessorTests { ac.registerSingleton("bfpp", TestBeanFactoryPostProcessor.class); ac.refresh(); TestBeanFactoryPostProcessor bfpp = (TestBeanFactoryPostProcessor) ac.getBean("bfpp"); - assertTrue(bfpp.wasCalled); + assertThat(bfpp.wasCalled).isTrue(); } @Test @@ -89,8 +87,8 @@ public class BeanFactoryPostProcessorTests { ac.registerSingleton("bfpp2", PropertyPlaceholderConfigurer.class, pvs2); ac.refresh(); TestBeanFactoryPostProcessor bfpp = (TestBeanFactoryPostProcessor) ac.getBean("bfpp1"); - assertEquals("value", bfpp.initValue); - assertTrue(bfpp.wasCalled); + assertThat(bfpp.initValue).isEqualTo("value"); + assertThat(bfpp.wasCalled).isTrue(); } @Test @@ -100,7 +98,7 @@ public class BeanFactoryPostProcessorTests { bf.registerBeanDefinition("tb2", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("bfpp", new RootBeanDefinition(TestBeanFactoryPostProcessor.class)); TestBeanFactoryPostProcessor bfpp = (TestBeanFactoryPostProcessor) bf.getBean("bfpp"); - assertFalse(bfpp.wasCalled); + assertThat(bfpp.wasCalled).isFalse(); } @Test @@ -111,11 +109,11 @@ public class BeanFactoryPostProcessorTests { ac.addBeanFactoryPostProcessor(new PrioritizedBeanDefinitionRegistryPostProcessor()); TestBeanDefinitionRegistryPostProcessor bdrpp = new TestBeanDefinitionRegistryPostProcessor(); ac.addBeanFactoryPostProcessor(bdrpp); - assertFalse(bdrpp.wasCalled); + assertThat(bdrpp.wasCalled).isFalse(); ac.refresh(); - assertTrue(bdrpp.wasCalled); - assertTrue(ac.getBean("bfpp1", TestBeanFactoryPostProcessor.class).wasCalled); - assertTrue(ac.getBean("bfpp2", TestBeanFactoryPostProcessor.class).wasCalled); + assertThat(bdrpp.wasCalled).isTrue(); + assertThat(ac.getBean("bfpp1", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); + assertThat(ac.getBean("bfpp2", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); } @Test @@ -125,8 +123,8 @@ public class BeanFactoryPostProcessorTests { ac.registerSingleton("tb2", TestBean.class); ac.registerBeanDefinition("bdrpp2", new RootBeanDefinition(OuterBeanDefinitionRegistryPostProcessor.class)); ac.refresh(); - assertTrue(ac.getBean("bfpp1", TestBeanFactoryPostProcessor.class).wasCalled); - assertTrue(ac.getBean("bfpp2", TestBeanFactoryPostProcessor.class).wasCalled); + assertThat(ac.getBean("bfpp1", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); + assertThat(ac.getBean("bfpp2", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); } @Test @@ -136,8 +134,8 @@ public class BeanFactoryPostProcessorTests { ac.registerSingleton("tb2", TestBean.class); ac.registerBeanDefinition("bdrpp2", new RootBeanDefinition(PrioritizedOuterBeanDefinitionRegistryPostProcessor.class)); ac.refresh(); - assertTrue(ac.getBean("bfpp1", TestBeanFactoryPostProcessor.class).wasCalled); - assertTrue(ac.getBean("bfpp2", TestBeanFactoryPostProcessor.class).wasCalled); + assertThat(ac.getBean("bfpp1", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); + assertThat(ac.getBean("bfpp2", TestBeanFactoryPostProcessor.class).wasCalled).isTrue(); } @Test @@ -145,7 +143,8 @@ public class BeanFactoryPostProcessorTests { StaticApplicationContext ac = new StaticApplicationContext(); ac.registerBeanDefinition("bfpp", new RootBeanDefinition(ListeningBeanFactoryPostProcessor.class)); ac.refresh(); - assertTrue(ac.getBean(ListeningBeanFactoryPostProcessor.class).received instanceof ContextRefreshedEvent); + boolean condition = ac.getBean(ListeningBeanFactoryPostProcessor.class).received instanceof ContextRefreshedEvent; + assertThat(condition).isTrue(); } @Test @@ -155,7 +154,8 @@ public class BeanFactoryPostProcessorTests { rbd.getPropertyValues().add("listeningBean", new RootBeanDefinition(ListeningBean.class)); ac.registerBeanDefinition("bfpp", rbd); ac.refresh(); - assertTrue(ac.getBean(NestingBeanFactoryPostProcessor.class).getListeningBean().received instanceof ContextRefreshedEvent); + boolean condition = ac.getBean(NestingBeanFactoryPostProcessor.class).getListeningBean().received instanceof ContextRefreshedEvent; + assertThat(condition).isTrue(); } @@ -200,7 +200,7 @@ public class BeanFactoryPostProcessorTests { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { - assertTrue(registry.containsBeanDefinition("bfpp1")); + assertThat(registry.containsBeanDefinition("bfpp1")).isTrue(); registry.registerBeanDefinition("bfpp2", new RootBeanDefinition(TestBeanFactoryPostProcessor.class)); } @@ -235,7 +235,7 @@ public class BeanFactoryPostProcessorTests { } - public static class ListeningBeanFactoryPostProcessor implements BeanFactoryPostProcessor, ApplicationListener { + public static class ListeningBeanFactoryPostProcessor implements BeanFactoryPostProcessor, ApplicationListener { public ApplicationEvent received; @@ -251,7 +251,7 @@ public class BeanFactoryPostProcessorTests { } - public static class ListeningBean implements ApplicationListener { + public static class ListeningBean implements ApplicationListener { public ApplicationEvent received; diff --git a/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java index 0b5eab7b00f..61b54fbafb5 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java @@ -45,11 +45,6 @@ import org.springframework.util.ObjectUtils; import static org.assertj.core.api.Assertions.assertThat; 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.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -81,7 +76,7 @@ public class ClassPathXmlApplicationContextTests { @Test public void testSingleConfigLocation() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(FQ_SIMPLE_CONTEXT); - assertTrue(ctx.containsBean("someMessageSource")); + assertThat(ctx.containsBean("someMessageSource")).isTrue(); ctx.close(); } @@ -89,42 +84,42 @@ public class ClassPathXmlApplicationContextTests { public void testMultipleConfigLocations() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( FQ_CONTEXT_B, FQ_CONTEXT_C, FQ_CONTEXT_A); - assertTrue(ctx.containsBean("service")); - assertTrue(ctx.containsBean("logicOne")); - assertTrue(ctx.containsBean("logicTwo")); + assertThat(ctx.containsBean("service")).isTrue(); + assertThat(ctx.containsBean("logicOne")).isTrue(); + assertThat(ctx.containsBean("logicTwo")).isTrue(); // re-refresh (after construction refresh) Service service = (Service) ctx.getBean("service"); ctx.refresh(); - assertTrue(service.isProperlyDestroyed()); + assertThat(service.isProperlyDestroyed()).isTrue(); // regular close call service = (Service) ctx.getBean("service"); ctx.close(); - assertTrue(service.isProperlyDestroyed()); + assertThat(service.isProperlyDestroyed()).isTrue(); // re-activating and re-closing the context (SPR-13425) ctx.refresh(); service = (Service) ctx.getBean("service"); ctx.close(); - assertTrue(service.isProperlyDestroyed()); + assertThat(service.isProperlyDestroyed()).isTrue(); } @Test public void testConfigLocationPattern() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_WILDCARD); - assertTrue(ctx.containsBean("service")); - assertTrue(ctx.containsBean("logicOne")); - assertTrue(ctx.containsBean("logicTwo")); + assertThat(ctx.containsBean("service")).isTrue(); + assertThat(ctx.containsBean("logicOne")).isTrue(); + assertThat(ctx.containsBean("logicTwo")).isTrue(); Service service = (Service) ctx.getBean("service"); ctx.close(); - assertTrue(service.isProperlyDestroyed()); + assertThat(service.isProperlyDestroyed()).isTrue(); } @Test public void testSingleConfigLocationWithClass() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(SIMPLE_CONTEXT, getClass()); - assertTrue(ctx.containsBean("someMessageSource")); + assertThat(ctx.containsBean("someMessageSource")).isTrue(); ctx.close(); } @@ -132,9 +127,9 @@ public class ClassPathXmlApplicationContextTests { public void testAliasWithPlaceholder() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( FQ_CONTEXT_B, FQ_ALIASED_CONTEXT_C, FQ_CONTEXT_A); - assertTrue(ctx.containsBean("service")); - assertTrue(ctx.containsBean("logicOne")); - assertTrue(ctx.containsBean("logicTwo")); + assertThat(ctx.containsBean("service")).isTrue(); + assertThat(ctx.containsBean("logicOne")).isTrue(); + assertThat(ctx.containsBean("logicTwo")).isTrue(); ctx.refresh(); } @@ -149,7 +144,7 @@ public class ClassPathXmlApplicationContextTests { assertThat(ex.toString()).contains("someMessageSource", "useCodeAsDefaultMessage"); checkExceptionFromInvalidValueType(ex); checkExceptionFromInvalidValueType(new ExceptionInInitializerError(ex)); - assertFalse(context.isActive()); + assertThat(context.isActive()).isFalse(); }); } @@ -158,8 +153,8 @@ public class ClassPathXmlApplicationContextTests { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ex.printStackTrace(new PrintStream(baos)); String dump = FileCopyUtils.copyToString(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()))); - assertTrue(dump.contains("someMessageSource")); - assertTrue(dump.contains("useCodeAsDefaultMessage")); + assertThat(dump.contains("someMessageSource")).isTrue(); + assertThat(dump.contains("useCodeAsDefaultMessage")).isTrue(); } catch (IOException ioex) { throw new IllegalStateException(ioex); @@ -169,7 +164,7 @@ public class ClassPathXmlApplicationContextTests { @Test public void testContextWithInvalidLazyClass() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(INVALID_CLASS_CONTEXT, getClass()); - assertTrue(ctx.containsBean("someMessageSource")); + assertThat(ctx.containsBean("someMessageSource")).isTrue(); assertThatExceptionOfType(CannotLoadBeanClassException.class).isThrownBy(() -> ctx.getBean("someMessageSource")) .satisfies(ex -> assertThat(ex.contains(ClassNotFoundException.class)).isTrue()); @@ -179,8 +174,9 @@ public class ClassPathXmlApplicationContextTests { @Test public void testContextWithClassNameThatContainsPlaceholder() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CLASS_WITH_PLACEHOLDER_CONTEXT, getClass()); - assertTrue(ctx.containsBean("someMessageSource")); - assertTrue(ctx.getBean("someMessageSource") instanceof StaticMessageSource); + assertThat(ctx.containsBean("someMessageSource")).isTrue(); + boolean condition = ctx.getBean("someMessageSource") instanceof StaticMessageSource; + assertThat(condition).isTrue(); ctx.close(); } @@ -188,9 +184,9 @@ public class ClassPathXmlApplicationContextTests { public void testMultipleConfigLocationsWithClass() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] {CONTEXT_B, CONTEXT_C, CONTEXT_A}, getClass()); - assertTrue(ctx.containsBean("service")); - assertTrue(ctx.containsBean("logicOne")); - assertTrue(ctx.containsBean("logicTwo")); + assertThat(ctx.containsBean("service")).isTrue(); + assertThat(ctx.containsBean("logicOne")).isTrue(); + assertThat(ctx.containsBean("logicTwo")).isTrue(); ctx.close(); } @@ -198,7 +194,7 @@ public class ClassPathXmlApplicationContextTests { public void testFactoryBeanAndApplicationListener() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_WILDCARD); ctx.getBeanFactory().registerSingleton("manualFBAAL", new FactoryBeanAndApplicationListener()); - assertEquals(2, ctx.getBeansOfType(ApplicationListener.class).size()); + assertThat(ctx.getBeansOfType(ApplicationListener.class).size()).isEqualTo(2); ctx.close(); } @@ -207,13 +203,13 @@ public class ClassPathXmlApplicationContextTests { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_WILDCARD); MessageSource messageSource = (MessageSource) ctx.getBean("messageSource"); Service service1 = (Service) ctx.getBean("service"); - assertEquals(ctx, service1.getMessageSource()); + assertThat(service1.getMessageSource()).isEqualTo(ctx); Service service2 = (Service) ctx.getBean("service2"); - assertEquals(ctx, service2.getMessageSource()); + assertThat(service2.getMessageSource()).isEqualTo(ctx); AutowiredService autowiredService1 = (AutowiredService) ctx.getBean("autowiredService"); - assertEquals(messageSource, autowiredService1.getMessageSource()); + assertThat(autowiredService1.getMessageSource()).isEqualTo(messageSource); AutowiredService autowiredService2 = (AutowiredService) ctx.getBean("autowiredService2"); - assertEquals(messageSource, autowiredService2.getMessageSource()); + assertThat(autowiredService2.getMessageSource()).isEqualTo(messageSource); ctx.close(); } @@ -221,11 +217,11 @@ public class ClassPathXmlApplicationContextTests { public void testResourceArrayPropertyEditor() throws IOException { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_WILDCARD); Service service = (Service) ctx.getBean("service"); - assertEquals(3, service.getResources().length); + assertThat(service.getResources().length).isEqualTo(3); List resources = Arrays.asList(service.getResources()); - assertTrue(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_A).getFile()))); - assertTrue(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_B).getFile()))); - assertTrue(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_C).getFile()))); + assertThat(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_A).getFile()))).isTrue(); + assertThat(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_B).getFile()))).isTrue(); + assertThat(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_C).getFile()))).isTrue(); ctx.close(); } @@ -234,42 +230,42 @@ public class ClassPathXmlApplicationContextTests { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_WILDCARD); ClassPathXmlApplicationContext child = new ClassPathXmlApplicationContext( new String[] {CHILD_WITH_PROXY_CONTEXT}, ctx); - assertTrue(AopUtils.isAopProxy(child.getBean("assemblerOne"))); - assertTrue(AopUtils.isAopProxy(child.getBean("assemblerTwo"))); + assertThat(AopUtils.isAopProxy(child.getBean("assemblerOne"))).isTrue(); + assertThat(AopUtils.isAopProxy(child.getBean("assemblerTwo"))).isTrue(); ctx.close(); } @Test public void testAliasForParentContext() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(FQ_SIMPLE_CONTEXT); - assertTrue(ctx.containsBean("someMessageSource")); + assertThat(ctx.containsBean("someMessageSource")).isTrue(); ClassPathXmlApplicationContext child = new ClassPathXmlApplicationContext( new String[] {ALIAS_FOR_PARENT_CONTEXT}, ctx); - assertTrue(child.containsBean("someMessageSource")); - assertTrue(child.containsBean("yourMessageSource")); - assertTrue(child.containsBean("myMessageSource")); - assertTrue(child.isSingleton("someMessageSource")); - assertTrue(child.isSingleton("yourMessageSource")); - assertTrue(child.isSingleton("myMessageSource")); - assertEquals(StaticMessageSource.class, child.getType("someMessageSource")); - assertEquals(StaticMessageSource.class, child.getType("yourMessageSource")); - assertEquals(StaticMessageSource.class, child.getType("myMessageSource")); + assertThat(child.containsBean("someMessageSource")).isTrue(); + assertThat(child.containsBean("yourMessageSource")).isTrue(); + assertThat(child.containsBean("myMessageSource")).isTrue(); + assertThat(child.isSingleton("someMessageSource")).isTrue(); + assertThat(child.isSingleton("yourMessageSource")).isTrue(); + assertThat(child.isSingleton("myMessageSource")).isTrue(); + assertThat(child.getType("someMessageSource")).isEqualTo(StaticMessageSource.class); + assertThat(child.getType("yourMessageSource")).isEqualTo(StaticMessageSource.class); + assertThat(child.getType("myMessageSource")).isEqualTo(StaticMessageSource.class); Object someMs = child.getBean("someMessageSource"); Object yourMs = child.getBean("yourMessageSource"); Object myMs = child.getBean("myMessageSource"); - assertSame(someMs, yourMs); - assertSame(someMs, myMs); + assertThat(yourMs).isSameAs(someMs); + assertThat(myMs).isSameAs(someMs); String[] aliases = child.getAliases("someMessageSource"); - assertEquals(2, aliases.length); - assertEquals("myMessageSource", aliases[0]); - assertEquals("yourMessageSource", aliases[1]); + assertThat(aliases.length).isEqualTo(2); + assertThat(aliases[0]).isEqualTo("myMessageSource"); + assertThat(aliases[1]).isEqualTo("yourMessageSource"); aliases = child.getAliases("myMessageSource"); - assertEquals(2, aliases.length); - assertEquals("someMessageSource", aliases[0]); - assertEquals("yourMessageSource", aliases[1]); + assertThat(aliases.length).isEqualTo(2); + assertThat(aliases[0]).isEqualTo("someMessageSource"); + assertThat(aliases[1]).isEqualTo("yourMessageSource"); child.close(); ctx.close(); @@ -284,8 +280,8 @@ public class ClassPathXmlApplicationContextTests { new String[] {ALIAS_THAT_OVERRIDES_PARENT_CONTEXT}, ctx); Object myMs = child.getBean("myMessageSource"); Object someMs2 = child.getBean("someMessageSource"); - assertSame(myMs, someMs2); - assertNotSame(someMs, someMs2); + assertThat(someMs2).isSameAs(myMs); + assertThat(someMs2).isNotSameAs(someMs); assertOneMessageSourceOnly(child, myMs); } @@ -295,36 +291,36 @@ public class ClassPathXmlApplicationContextTests { FQ_SIMPLE_CONTEXT, ALIAS_THAT_OVERRIDES_PARENT_CONTEXT); Object myMs = ctx.getBean("myMessageSource"); Object someMs2 = ctx.getBean("someMessageSource"); - assertSame(myMs, someMs2); + assertThat(someMs2).isSameAs(myMs); assertOneMessageSourceOnly(ctx, myMs); } private void assertOneMessageSourceOnly(ClassPathXmlApplicationContext ctx, Object myMessageSource) { String[] beanNamesForType = ctx.getBeanNamesForType(StaticMessageSource.class); - assertEquals(1, beanNamesForType.length); - assertEquals("myMessageSource", beanNamesForType[0]); + assertThat(beanNamesForType.length).isEqualTo(1); + assertThat(beanNamesForType[0]).isEqualTo("myMessageSource"); beanNamesForType = ctx.getBeanNamesForType(StaticMessageSource.class, true, true); - assertEquals(1, beanNamesForType.length); - assertEquals("myMessageSource", beanNamesForType[0]); + assertThat(beanNamesForType.length).isEqualTo(1); + assertThat(beanNamesForType[0]).isEqualTo("myMessageSource"); beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, StaticMessageSource.class); - assertEquals(1, beanNamesForType.length); - assertEquals("myMessageSource", beanNamesForType[0]); + assertThat(beanNamesForType.length).isEqualTo(1); + assertThat(beanNamesForType[0]).isEqualTo("myMessageSource"); beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, StaticMessageSource.class, true, true); - assertEquals(1, beanNamesForType.length); - assertEquals("myMessageSource", beanNamesForType[0]); + assertThat(beanNamesForType.length).isEqualTo(1); + assertThat(beanNamesForType[0]).isEqualTo("myMessageSource"); Map beansOfType = ctx.getBeansOfType(StaticMessageSource.class); - assertEquals(1, beansOfType.size()); - assertSame(myMessageSource, beansOfType.values().iterator().next()); + assertThat(beansOfType.size()).isEqualTo(1); + assertThat(beansOfType.values().iterator().next()).isSameAs(myMessageSource); beansOfType = ctx.getBeansOfType(StaticMessageSource.class, true, true); - assertEquals(1, beansOfType.size()); - assertSame(myMessageSource, beansOfType.values().iterator().next()); + assertThat(beansOfType.size()).isEqualTo(1); + assertThat(beansOfType.values().iterator().next()).isSameAs(myMessageSource); beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, StaticMessageSource.class); - assertEquals(1, beansOfType.size()); - assertSame(myMessageSource, beansOfType.values().iterator().next()); + assertThat(beansOfType.size()).isEqualTo(1); + assertThat(beansOfType.values().iterator().next()).isSameAs(myMessageSource); beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, StaticMessageSource.class, true, true); - assertEquals(1, beansOfType.size()); - assertSame(myMessageSource, beansOfType.values().iterator().next()); + assertThat(beansOfType.size()).isEqualTo(1); + assertThat(beansOfType.values().iterator().next()).isSameAs(myMessageSource); } @Test @@ -340,19 +336,20 @@ public class ClassPathXmlApplicationContextTests { }; ResourceTestBean resource1 = (ResourceTestBean) ctx.getBean("resource1"); ResourceTestBean resource2 = (ResourceTestBean) ctx.getBean("resource2"); - assertTrue(resource1.getResource() instanceof ClassPathResource); + boolean condition = resource1.getResource() instanceof ClassPathResource; + assertThat(condition).isTrue(); StringWriter writer = new StringWriter(); FileCopyUtils.copy(new InputStreamReader(resource1.getResource().getInputStream()), writer); - assertEquals("contexttest", writer.toString()); + assertThat(writer.toString()).isEqualTo("contexttest"); writer = new StringWriter(); FileCopyUtils.copy(new InputStreamReader(resource1.getInputStream()), writer); - assertEquals("test", writer.toString()); + assertThat(writer.toString()).isEqualTo("test"); writer = new StringWriter(); FileCopyUtils.copy(new InputStreamReader(resource2.getResource().getInputStream()), writer); - assertEquals("contexttest", writer.toString()); + assertThat(writer.toString()).isEqualTo("contexttest"); writer = new StringWriter(); FileCopyUtils.copy(new InputStreamReader(resource2.getInputStream()), writer); - assertEquals("test", writer.toString()); + assertThat(writer.toString()).isEqualTo("test"); ctx.close(); } @@ -364,9 +361,9 @@ public class ClassPathXmlApplicationContextTests { reader.loadBeanDefinitions(new ClassPathResource(CONTEXT_C, getClass())); reader.loadBeanDefinitions(new ClassPathResource(CONTEXT_A, getClass())); ctx.refresh(); - assertTrue(ctx.containsBean("service")); - assertTrue(ctx.containsBean("logicOne")); - assertTrue(ctx.containsBean("logicTwo")); + assertThat(ctx.containsBean("service")).isTrue(); + assertThat(ctx.containsBean("logicOne")).isTrue(); + assertThat(ctx.containsBean("logicTwo")).isTrue(); ctx.close(); } @@ -379,11 +376,11 @@ public class ClassPathXmlApplicationContextTests { reader.loadBeanDefinitions(new ClassPathResource(CONTEXT_C, getClass())); reader.loadBeanDefinitions(new ClassPathResource(CONTEXT_A, getClass())); ctx.refresh(); - assertEquals(ObjectUtils.identityToString(ctx), ctx.getId()); - assertEquals(ObjectUtils.identityToString(ctx), ctx.getDisplayName()); - assertTrue(ctx.containsBean("service")); - assertTrue(ctx.containsBean("logicOne")); - assertTrue(ctx.containsBean("logicTwo")); + assertThat(ctx.getId()).isEqualTo(ObjectUtils.identityToString(ctx)); + assertThat(ctx.getDisplayName()).isEqualTo(ObjectUtils.identityToString(ctx)); + assertThat(ctx.containsBean("service")).isTrue(); + assertThat(ctx.containsBean("logicOne")).isTrue(); + assertThat(ctx.containsBean("logicTwo")).isTrue(); ctx.close(); } @@ -397,11 +394,11 @@ public class ClassPathXmlApplicationContextTests { reader.loadBeanDefinitions(new ClassPathResource(CONTEXT_C, getClass())); reader.loadBeanDefinitions(new ClassPathResource(CONTEXT_A, getClass())); ctx.refresh(); - assertEquals("testContext", ctx.getId()); - assertEquals("Test Context", ctx.getDisplayName()); - assertTrue(ctx.containsBean("service")); - assertTrue(ctx.containsBean("logicOne")); - assertTrue(ctx.containsBean("logicTwo")); + assertThat(ctx.getId()).isEqualTo("testContext"); + assertThat(ctx.getDisplayName()).isEqualTo("Test Context"); + assertThat(ctx.containsBean("service")).isTrue(); + assertThat(ctx.containsBean("logicOne")).isTrue(); + assertThat(ctx.containsBean("logicTwo")).isTrue(); ctx.close(); } diff --git a/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java index 1f99694cbce..545edec4f6f 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java @@ -36,7 +36,6 @@ import org.springframework.tests.sample.beans.ResourceTestBean; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertTrue; /** * @author Keith Donald @@ -49,7 +48,7 @@ public class ConversionServiceFactoryBeanTests { ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean(); factory.afterPropertiesSet(); ConversionService service = factory.getObject(); - assertTrue(service.canConvert(String.class, Integer.class)); + assertThat(service.canConvert(String.class, Integer.class)).isTrue(); } @Test @@ -88,10 +87,10 @@ public class ConversionServiceFactoryBeanTests { factory.setConverters(converters); factory.afterPropertiesSet(); ConversionService service = factory.getObject(); - assertTrue(service.canConvert(String.class, Integer.class)); - assertTrue(service.canConvert(String.class, Foo.class)); - assertTrue(service.canConvert(String.class, Bar.class)); - assertTrue(service.canConvert(String.class, Baz.class)); + assertThat(service.canConvert(String.class, Integer.class)).isTrue(); + assertThat(service.canConvert(String.class, Foo.class)).isTrue(); + assertThat(service.canConvert(String.class, Bar.class)).isTrue(); + assertThat(service.canConvert(String.class, Baz.class)).isTrue(); } @Test @@ -117,14 +116,14 @@ public class ConversionServiceFactoryBeanTests { private void doTestConversionServiceInApplicationContext(String fileName, Class resourceClass) { ApplicationContext ctx = new ClassPathXmlApplicationContext(fileName, getClass()); ResourceTestBean tb = ctx.getBean("resourceTestBean", ResourceTestBean.class); - assertTrue(resourceClass.isInstance(tb.getResource())); - assertTrue(tb.getResourceArray().length > 0); - assertTrue(resourceClass.isInstance(tb.getResourceArray()[0])); - assertTrue(tb.getResourceMap().size() == 1); - assertTrue(resourceClass.isInstance(tb.getResourceMap().get("key1"))); - assertTrue(tb.getResourceArrayMap().size() == 1); - assertTrue(tb.getResourceArrayMap().get("key1").length > 0); - assertTrue(resourceClass.isInstance(tb.getResourceArrayMap().get("key1")[0])); + assertThat(resourceClass.isInstance(tb.getResource())).isTrue(); + assertThat(tb.getResourceArray().length > 0).isTrue(); + assertThat(resourceClass.isInstance(tb.getResourceArray()[0])).isTrue(); + assertThat(tb.getResourceMap().size() == 1).isTrue(); + assertThat(resourceClass.isInstance(tb.getResourceMap().get("key1"))).isTrue(); + assertThat(tb.getResourceArrayMap().size() == 1).isTrue(); + assertThat(tb.getResourceArrayMap().get("key1").length > 0).isTrue(); + assertThat(resourceClass.isInstance(tb.getResourceArrayMap().get("key1")[0])).isTrue(); } @@ -140,7 +139,7 @@ public class ConversionServiceFactoryBeanTests { public static class ComplexConstructorArgument { public ComplexConstructorArgument(Map> map) { - assertTrue(!map.isEmpty()); + assertThat(!map.isEmpty()).isTrue(); assertThat(map.keySet().iterator().next()).isInstanceOf(String.class); assertThat(map.values().iterator().next()).isInstanceOf(Class.class); } diff --git a/spring-context/src/test/java/org/springframework/context/support/DefaultLifecycleProcessorTests.java b/spring-context/src/test/java/org/springframework/context/support/DefaultLifecycleProcessorTests.java index e107549d302..7f91807048d 100644 --- a/spring-context/src/test/java/org/springframework/context/support/DefaultLifecycleProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/DefaultLifecycleProcessorTests.java @@ -30,11 +30,7 @@ import org.springframework.context.SmartLifecycle; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -47,8 +43,8 @@ public class DefaultLifecycleProcessorTests { StaticApplicationContext context = new StaticApplicationContext(); context.refresh(); Object lifecycleProcessor = new DirectFieldAccessor(context).getPropertyValue("lifecycleProcessor"); - assertNotNull(lifecycleProcessor); - assertEquals(DefaultLifecycleProcessor.class, lifecycleProcessor.getClass()); + assertThat(lifecycleProcessor).isNotNull(); + assertThat(lifecycleProcessor.getClass()).isEqualTo(DefaultLifecycleProcessor.class); } @Test @@ -60,10 +56,10 @@ public class DefaultLifecycleProcessorTests { context.refresh(); LifecycleProcessor bean = context.getBean("lifecycleProcessor", LifecycleProcessor.class); Object contextLifecycleProcessor = new DirectFieldAccessor(context).getPropertyValue("lifecycleProcessor"); - assertNotNull(contextLifecycleProcessor); - assertSame(bean, contextLifecycleProcessor); - assertEquals(1000L, new DirectFieldAccessor(contextLifecycleProcessor).getPropertyValue( - "timeoutPerShutdownPhase")); + assertThat(contextLifecycleProcessor).isNotNull(); + assertThat(contextLifecycleProcessor).isSameAs(bean); + assertThat(new DirectFieldAccessor(contextLifecycleProcessor).getPropertyValue( + "timeoutPerShutdownPhase")).isEqualTo(1000L); } @Test @@ -73,12 +69,12 @@ public class DefaultLifecycleProcessorTests { bean.setAutoStartup(true); StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("bean", bean); - assertFalse(bean.isRunning()); + assertThat(bean.isRunning()).isFalse(); context.refresh(); - assertTrue(bean.isRunning()); + assertThat(bean.isRunning()).isTrue(); context.stop(); - assertFalse(bean.isRunning()); - assertEquals(1, startedBeans.size()); + assertThat(bean.isRunning()).isFalse(); + assertThat(startedBeans.size()).isEqualTo(1); } @Test @@ -89,9 +85,9 @@ public class DefaultLifecycleProcessorTests { context.registerBeanDefinition("bean", bd); context.refresh(); DummySmartLifecycleBean bean = context.getBean("bean", DummySmartLifecycleBean.class); - assertTrue(bean.isRunning()); + assertThat(bean.isRunning()).isTrue(); context.stop(); - assertFalse(bean.isRunning()); + assertThat(bean.isRunning()).isFalse(); } @Test @@ -102,9 +98,9 @@ public class DefaultLifecycleProcessorTests { context.registerBeanDefinition("bean", bd); context.refresh(); DummySmartLifecycleFactoryBean bean = context.getBean("&bean", DummySmartLifecycleFactoryBean.class); - assertTrue(bean.isRunning()); + assertThat(bean.isRunning()).isTrue(); context.stop(); - assertFalse(bean.isRunning()); + assertThat(bean.isRunning()).isFalse(); } @Test @@ -114,13 +110,13 @@ public class DefaultLifecycleProcessorTests { bean.setAutoStartup(false); StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("bean", bean); - assertFalse(bean.isRunning()); + assertThat(bean.isRunning()).isFalse(); context.refresh(); - assertFalse(bean.isRunning()); - assertEquals(0, startedBeans.size()); + assertThat(bean.isRunning()).isFalse(); + assertThat(startedBeans.size()).isEqualTo(0); context.start(); - assertTrue(bean.isRunning()); - assertEquals(1, startedBeans.size()); + assertThat(bean.isRunning()).isTrue(); + assertThat(startedBeans.size()).isEqualTo(1); context.stop(); } @@ -135,15 +131,15 @@ public class DefaultLifecycleProcessorTests { context.getBeanFactory().registerSingleton("bean", bean); context.getBeanFactory().registerSingleton("dependency", dependency); context.getBeanFactory().registerDependentBean("dependency", "bean"); - assertFalse(bean.isRunning()); - assertFalse(dependency.isRunning()); + assertThat(bean.isRunning()).isFalse(); + assertThat(dependency.isRunning()).isFalse(); context.refresh(); - assertTrue(bean.isRunning()); - assertFalse(dependency.isRunning()); + assertThat(bean.isRunning()).isTrue(); + assertThat(dependency.isRunning()).isFalse(); context.stop(); - assertFalse(bean.isRunning()); - assertFalse(dependency.isRunning()); - assertEquals(1, startedBeans.size()); + assertThat(bean.isRunning()).isFalse(); + assertThat(dependency.isRunning()).isFalse(); + assertThat(startedBeans.size()).isEqualTo(1); } @Test @@ -160,24 +156,24 @@ public class DefaultLifecycleProcessorTests { context.getBeanFactory().registerSingleton("bean2", bean2); context.getBeanFactory().registerSingleton("beanMax", beanMax); context.getBeanFactory().registerSingleton("bean1", bean1); - assertFalse(beanMin.isRunning()); - assertFalse(bean1.isRunning()); - assertFalse(bean2.isRunning()); - assertFalse(bean3.isRunning()); - assertFalse(beanMax.isRunning()); + assertThat(beanMin.isRunning()).isFalse(); + assertThat(bean1.isRunning()).isFalse(); + assertThat(bean2.isRunning()).isFalse(); + assertThat(bean3.isRunning()).isFalse(); + assertThat(beanMax.isRunning()).isFalse(); context.refresh(); - assertTrue(beanMin.isRunning()); - assertTrue(bean1.isRunning()); - assertTrue(bean2.isRunning()); - assertTrue(bean3.isRunning()); - assertTrue(beanMax.isRunning()); + assertThat(beanMin.isRunning()).isTrue(); + assertThat(bean1.isRunning()).isTrue(); + assertThat(bean2.isRunning()).isTrue(); + assertThat(bean3.isRunning()).isTrue(); + assertThat(beanMax.isRunning()).isTrue(); context.stop(); - assertEquals(5, startedBeans.size()); - assertEquals(Integer.MIN_VALUE, getPhase(startedBeans.get(0))); - assertEquals(1, getPhase(startedBeans.get(1))); - assertEquals(2, getPhase(startedBeans.get(2))); - assertEquals(3, getPhase(startedBeans.get(3))); - assertEquals(Integer.MAX_VALUE, getPhase(startedBeans.get(4))); + assertThat(startedBeans.size()).isEqualTo(5); + assertThat(getPhase(startedBeans.get(0))).isEqualTo(Integer.MIN_VALUE); + assertThat(getPhase(startedBeans.get(1))).isEqualTo(1); + assertThat(getPhase(startedBeans.get(2))).isEqualTo(2); + assertThat(getPhase(startedBeans.get(3))).isEqualTo(3); + assertThat(getPhase(startedBeans.get(4))).isEqualTo(Integer.MAX_VALUE); } @Test @@ -192,26 +188,26 @@ public class DefaultLifecycleProcessorTests { context.getBeanFactory().registerSingleton("smartBean1", smartBean1); context.getBeanFactory().registerSingleton("simpleBean2", simpleBean2); context.getBeanFactory().registerSingleton("smartBean2", smartBean2); - assertFalse(simpleBean1.isRunning()); - assertFalse(simpleBean2.isRunning()); - assertFalse(smartBean1.isRunning()); - assertFalse(smartBean2.isRunning()); + assertThat(simpleBean1.isRunning()).isFalse(); + assertThat(simpleBean2.isRunning()).isFalse(); + assertThat(smartBean1.isRunning()).isFalse(); + assertThat(smartBean2.isRunning()).isFalse(); context.refresh(); - assertTrue(smartBean1.isRunning()); - assertTrue(smartBean2.isRunning()); - assertFalse(simpleBean1.isRunning()); - assertFalse(simpleBean2.isRunning()); - assertEquals(2, startedBeans.size()); - assertEquals(-3, getPhase(startedBeans.get(0))); - assertEquals(5, getPhase(startedBeans.get(1))); + assertThat(smartBean1.isRunning()).isTrue(); + assertThat(smartBean2.isRunning()).isTrue(); + assertThat(simpleBean1.isRunning()).isFalse(); + assertThat(simpleBean2.isRunning()).isFalse(); + assertThat(startedBeans.size()).isEqualTo(2); + assertThat(getPhase(startedBeans.get(0))).isEqualTo(-3); + assertThat(getPhase(startedBeans.get(1))).isEqualTo(5); context.start(); - assertTrue(smartBean1.isRunning()); - assertTrue(smartBean2.isRunning()); - assertTrue(simpleBean1.isRunning()); - assertTrue(simpleBean2.isRunning()); - assertEquals(4, startedBeans.size()); - assertEquals(0, getPhase(startedBeans.get(2))); - assertEquals(0, getPhase(startedBeans.get(3))); + assertThat(smartBean1.isRunning()).isTrue(); + assertThat(smartBean2.isRunning()).isTrue(); + assertThat(simpleBean1.isRunning()).isTrue(); + assertThat(simpleBean2.isRunning()).isTrue(); + assertThat(startedBeans.size()).isEqualTo(4); + assertThat(getPhase(startedBeans.get(2))).isEqualTo(0); + assertThat(getPhase(startedBeans.get(3))).isEqualTo(0); } @Test @@ -226,33 +222,33 @@ public class DefaultLifecycleProcessorTests { context.getBeanFactory().registerSingleton("smartBean1", smartBean1); context.getBeanFactory().registerSingleton("simpleBean2", simpleBean2); context.getBeanFactory().registerSingleton("smartBean2", smartBean2); - assertFalse(simpleBean1.isRunning()); - assertFalse(simpleBean2.isRunning()); - assertFalse(smartBean1.isRunning()); - assertFalse(smartBean2.isRunning()); + assertThat(simpleBean1.isRunning()).isFalse(); + assertThat(simpleBean2.isRunning()).isFalse(); + assertThat(smartBean1.isRunning()).isFalse(); + assertThat(smartBean2.isRunning()).isFalse(); context.refresh(); - assertTrue(smartBean1.isRunning()); - assertTrue(smartBean2.isRunning()); - assertFalse(simpleBean1.isRunning()); - assertFalse(simpleBean2.isRunning()); - assertEquals(2, startedBeans.size()); - assertEquals(-3, getPhase(startedBeans.get(0))); - assertEquals(5, getPhase(startedBeans.get(1))); + assertThat(smartBean1.isRunning()).isTrue(); + assertThat(smartBean2.isRunning()).isTrue(); + assertThat(simpleBean1.isRunning()).isFalse(); + assertThat(simpleBean2.isRunning()).isFalse(); + assertThat(startedBeans.size()).isEqualTo(2); + assertThat(getPhase(startedBeans.get(0))).isEqualTo(-3); + assertThat(getPhase(startedBeans.get(1))).isEqualTo(5); context.stop(); - assertFalse(simpleBean1.isRunning()); - assertFalse(simpleBean2.isRunning()); - assertFalse(smartBean1.isRunning()); - assertFalse(smartBean2.isRunning()); + assertThat(simpleBean1.isRunning()).isFalse(); + assertThat(simpleBean2.isRunning()).isFalse(); + assertThat(smartBean1.isRunning()).isFalse(); + assertThat(smartBean2.isRunning()).isFalse(); context.start(); - assertTrue(smartBean1.isRunning()); - assertTrue(smartBean2.isRunning()); - assertTrue(simpleBean1.isRunning()); - assertTrue(simpleBean2.isRunning()); - assertEquals(6, startedBeans.size()); - assertEquals(-3, getPhase(startedBeans.get(2))); - assertEquals(0, getPhase(startedBeans.get(3))); - assertEquals(0, getPhase(startedBeans.get(4))); - assertEquals(5, getPhase(startedBeans.get(5))); + assertThat(smartBean1.isRunning()).isTrue(); + assertThat(smartBean2.isRunning()).isTrue(); + assertThat(simpleBean1.isRunning()).isTrue(); + assertThat(simpleBean2.isRunning()).isTrue(); + assertThat(startedBeans.size()).isEqualTo(6); + assertThat(getPhase(startedBeans.get(2))).isEqualTo(-3); + assertThat(getPhase(startedBeans.get(3))).isEqualTo(0); + assertThat(getPhase(startedBeans.get(4))).isEqualTo(0); + assertThat(getPhase(startedBeans.get(5))).isEqualTo(5); } @Test @@ -277,13 +273,13 @@ public class DefaultLifecycleProcessorTests { context.getBeanFactory().registerSingleton("bean7", bean7); context.refresh(); context.stop(); - assertEquals(Integer.MAX_VALUE, getPhase(stoppedBeans.get(0))); - assertEquals(3, getPhase(stoppedBeans.get(1))); - assertEquals(3, getPhase(stoppedBeans.get(2))); - assertEquals(2, getPhase(stoppedBeans.get(3))); - assertEquals(2, getPhase(stoppedBeans.get(4))); - assertEquals(1, getPhase(stoppedBeans.get(5))); - assertEquals(1, getPhase(stoppedBeans.get(6))); + assertThat(getPhase(stoppedBeans.get(0))).isEqualTo(Integer.MAX_VALUE); + assertThat(getPhase(stoppedBeans.get(1))).isEqualTo(3); + assertThat(getPhase(stoppedBeans.get(2))).isEqualTo(3); + assertThat(getPhase(stoppedBeans.get(3))).isEqualTo(2); + assertThat(getPhase(stoppedBeans.get(4))).isEqualTo(2); + assertThat(getPhase(stoppedBeans.get(5))).isEqualTo(1); + assertThat(getPhase(stoppedBeans.get(6))).isEqualTo(1); } @Test @@ -295,11 +291,11 @@ public class DefaultLifecycleProcessorTests { StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("bean", bean); context.refresh(); - assertTrue(bean.isRunning()); + assertThat(bean.isRunning()).isTrue(); context.stop(); - assertEquals(1, stoppedBeans.size()); - assertFalse(bean.isRunning()); - assertEquals(bean, stoppedBeans.get(0)); + assertThat(stoppedBeans.size()).isEqualTo(1); + assertThat(bean.isRunning()).isFalse(); + assertThat(stoppedBeans.get(0)).isEqualTo(bean); } @Test @@ -309,13 +305,13 @@ public class DefaultLifecycleProcessorTests { StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("bean", bean); context.refresh(); - assertFalse(bean.isRunning()); + assertThat(bean.isRunning()).isFalse(); bean.start(); - assertTrue(bean.isRunning()); + assertThat(bean.isRunning()).isTrue(); context.stop(); - assertEquals(1, stoppedBeans.size()); - assertFalse(bean.isRunning()); - assertEquals(bean, stoppedBeans.get(0)); + assertThat(stoppedBeans.size()).isEqualTo(1); + assertThat(bean.isRunning()).isFalse(); + assertThat(stoppedBeans.get(0)).isEqualTo(bean); } @Test @@ -337,33 +333,33 @@ public class DefaultLifecycleProcessorTests { context.getBeanFactory().registerSingleton("bean6", bean6); context.getBeanFactory().registerSingleton("bean7", bean7); context.refresh(); - assertTrue(bean2.isRunning()); - assertTrue(bean3.isRunning()); - assertTrue(bean5.isRunning()); - assertTrue(bean6.isRunning()); - assertTrue(bean7.isRunning()); - assertFalse(bean1.isRunning()); - assertFalse(bean4.isRunning()); + assertThat(bean2.isRunning()).isTrue(); + assertThat(bean3.isRunning()).isTrue(); + assertThat(bean5.isRunning()).isTrue(); + assertThat(bean6.isRunning()).isTrue(); + assertThat(bean7.isRunning()).isTrue(); + assertThat(bean1.isRunning()).isFalse(); + assertThat(bean4.isRunning()).isFalse(); bean1.start(); bean4.start(); - assertTrue(bean1.isRunning()); - assertTrue(bean4.isRunning()); + assertThat(bean1.isRunning()).isTrue(); + assertThat(bean4.isRunning()).isTrue(); context.stop(); - assertFalse(bean1.isRunning()); - assertFalse(bean2.isRunning()); - assertFalse(bean3.isRunning()); - assertFalse(bean4.isRunning()); - assertFalse(bean5.isRunning()); - assertFalse(bean6.isRunning()); - assertFalse(bean7.isRunning()); - assertEquals(7, stoppedBeans.size()); - assertEquals(Integer.MAX_VALUE, getPhase(stoppedBeans.get(0))); - assertEquals(500, getPhase(stoppedBeans.get(1))); - assertEquals(1, getPhase(stoppedBeans.get(2))); - assertEquals(0, getPhase(stoppedBeans.get(3))); - assertEquals(0, getPhase(stoppedBeans.get(4))); - assertEquals(-1, getPhase(stoppedBeans.get(5))); - assertEquals(Integer.MIN_VALUE, getPhase(stoppedBeans.get(6))); + assertThat(bean1.isRunning()).isFalse(); + assertThat(bean2.isRunning()).isFalse(); + assertThat(bean3.isRunning()).isFalse(); + assertThat(bean4.isRunning()).isFalse(); + assertThat(bean5.isRunning()).isFalse(); + assertThat(bean6.isRunning()).isFalse(); + assertThat(bean7.isRunning()).isFalse(); + assertThat(stoppedBeans.size()).isEqualTo(7); + assertThat(getPhase(stoppedBeans.get(0))).isEqualTo(Integer.MAX_VALUE); + assertThat(getPhase(stoppedBeans.get(1))).isEqualTo(500); + assertThat(getPhase(stoppedBeans.get(2))).isEqualTo(1); + assertThat(getPhase(stoppedBeans.get(3))).isEqualTo(0); + assertThat(getPhase(stoppedBeans.get(4))).isEqualTo(0); + assertThat(getPhase(stoppedBeans.get(5))).isEqualTo(-1); + assertThat(getPhase(stoppedBeans.get(6))).isEqualTo(Integer.MIN_VALUE); } @Test @@ -380,17 +376,17 @@ public class DefaultLifecycleProcessorTests { context.getBeanFactory().registerSingleton("beanMax", beanMax); context.getBeanFactory().registerDependentBean("bean99", "bean2"); context.refresh(); - assertTrue(beanMin.isRunning()); - assertTrue(bean2.isRunning()); - assertTrue(bean99.isRunning()); - assertTrue(beanMax.isRunning()); - assertEquals(4, startedBeans.size()); - assertEquals(Integer.MIN_VALUE, getPhase(startedBeans.get(0))); - assertEquals(99, getPhase(startedBeans.get(1))); - assertEquals(bean99, startedBeans.get(1)); - assertEquals(2, getPhase(startedBeans.get(2))); - assertEquals(bean2, startedBeans.get(2)); - assertEquals(Integer.MAX_VALUE, getPhase(startedBeans.get(3))); + assertThat(beanMin.isRunning()).isTrue(); + assertThat(bean2.isRunning()).isTrue(); + assertThat(bean99.isRunning()).isTrue(); + assertThat(beanMax.isRunning()).isTrue(); + assertThat(startedBeans.size()).isEqualTo(4); + assertThat(getPhase(startedBeans.get(0))).isEqualTo(Integer.MIN_VALUE); + assertThat(getPhase(startedBeans.get(1))).isEqualTo(99); + assertThat(startedBeans.get(1)).isEqualTo(bean99); + assertThat(getPhase(startedBeans.get(2))).isEqualTo(2); + assertThat(startedBeans.get(2)).isEqualTo(bean2); + assertThat(getPhase(startedBeans.get(3))).isEqualTo(Integer.MAX_VALUE); context.stop(); } @@ -414,28 +410,28 @@ public class DefaultLifecycleProcessorTests { context.getBeanFactory().registerSingleton("beanMax", beanMax); context.getBeanFactory().registerDependentBean("bean99", "bean2"); context.refresh(); - assertTrue(beanMin.isRunning()); - assertTrue(bean1.isRunning()); - assertTrue(bean2.isRunning()); - assertTrue(bean7.isRunning()); - assertTrue(bean99.isRunning()); - assertTrue(beanMax.isRunning()); + assertThat(beanMin.isRunning()).isTrue(); + assertThat(bean1.isRunning()).isTrue(); + assertThat(bean2.isRunning()).isTrue(); + assertThat(bean7.isRunning()).isTrue(); + assertThat(bean99.isRunning()).isTrue(); + assertThat(beanMax.isRunning()).isTrue(); context.stop(); - assertFalse(beanMin.isRunning()); - assertFalse(bean1.isRunning()); - assertFalse(bean2.isRunning()); - assertFalse(bean7.isRunning()); - assertFalse(bean99.isRunning()); - assertFalse(beanMax.isRunning()); - assertEquals(6, stoppedBeans.size()); - assertEquals(Integer.MAX_VALUE, getPhase(stoppedBeans.get(0))); - assertEquals(2, getPhase(stoppedBeans.get(1))); - assertEquals(bean2, stoppedBeans.get(1)); - assertEquals(99, getPhase(stoppedBeans.get(2))); - assertEquals(bean99, stoppedBeans.get(2)); - assertEquals(7, getPhase(stoppedBeans.get(3))); - assertEquals(1, getPhase(stoppedBeans.get(4))); - assertEquals(Integer.MIN_VALUE, getPhase(stoppedBeans.get(5))); + assertThat(beanMin.isRunning()).isFalse(); + assertThat(bean1.isRunning()).isFalse(); + assertThat(bean2.isRunning()).isFalse(); + assertThat(bean7.isRunning()).isFalse(); + assertThat(bean99.isRunning()).isFalse(); + assertThat(beanMax.isRunning()).isFalse(); + assertThat(stoppedBeans.size()).isEqualTo(6); + assertThat(getPhase(stoppedBeans.get(0))).isEqualTo(Integer.MAX_VALUE); + assertThat(getPhase(stoppedBeans.get(1))).isEqualTo(2); + assertThat(stoppedBeans.get(1)).isEqualTo(bean2); + assertThat(getPhase(stoppedBeans.get(2))).isEqualTo(99); + assertThat(stoppedBeans.get(2)).isEqualTo(bean99); + assertThat(getPhase(stoppedBeans.get(3))).isEqualTo(7); + assertThat(getPhase(stoppedBeans.get(4))).isEqualTo(1); + assertThat(getPhase(stoppedBeans.get(5))).isEqualTo(Integer.MIN_VALUE); } @Test @@ -456,15 +452,15 @@ public class DefaultLifecycleProcessorTests { startedBeans.clear(); // clean start so that simpleBean is included context.start(); - assertTrue(beanNegative.isRunning()); - assertTrue(bean99.isRunning()); - assertTrue(bean7.isRunning()); - assertTrue(simpleBean.isRunning()); - assertEquals(4, startedBeans.size()); - assertEquals(-99, getPhase(startedBeans.get(0))); - assertEquals(7, getPhase(startedBeans.get(1))); - assertEquals(0, getPhase(startedBeans.get(2))); - assertEquals(99, getPhase(startedBeans.get(3))); + assertThat(beanNegative.isRunning()).isTrue(); + assertThat(bean99.isRunning()).isTrue(); + assertThat(bean7.isRunning()).isTrue(); + assertThat(simpleBean.isRunning()).isTrue(); + assertThat(startedBeans.size()).isEqualTo(4); + assertThat(getPhase(startedBeans.get(0))).isEqualTo(-99); + assertThat(getPhase(startedBeans.get(1))).isEqualTo(7); + assertThat(getPhase(startedBeans.get(2))).isEqualTo(0); + assertThat(getPhase(startedBeans.get(3))).isEqualTo(99); context.stop(); } @@ -488,27 +484,27 @@ public class DefaultLifecycleProcessorTests { context.getBeanFactory().registerSingleton("simpleBean", simpleBean); context.getBeanFactory().registerDependentBean("simpleBean", "beanNegative"); context.refresh(); - assertTrue(beanMin.isRunning()); - assertTrue(beanNegative.isRunning()); - assertTrue(bean1.isRunning()); - assertTrue(bean2.isRunning()); - assertTrue(bean7.isRunning()); + assertThat(beanMin.isRunning()).isTrue(); + assertThat(beanNegative.isRunning()).isTrue(); + assertThat(bean1.isRunning()).isTrue(); + assertThat(bean2.isRunning()).isTrue(); + assertThat(bean7.isRunning()).isTrue(); // should start since it's a dependency of an auto-started bean - assertTrue(simpleBean.isRunning()); + assertThat(simpleBean.isRunning()).isTrue(); context.stop(); - assertFalse(beanMin.isRunning()); - assertFalse(beanNegative.isRunning()); - assertFalse(bean1.isRunning()); - assertFalse(bean2.isRunning()); - assertFalse(bean7.isRunning()); - assertFalse(simpleBean.isRunning()); - assertEquals(6, stoppedBeans.size()); - assertEquals(7, getPhase(stoppedBeans.get(0))); - assertEquals(2, getPhase(stoppedBeans.get(1))); - assertEquals(1, getPhase(stoppedBeans.get(2))); - assertEquals(-99, getPhase(stoppedBeans.get(3))); - assertEquals(0, getPhase(stoppedBeans.get(4))); - assertEquals(Integer.MIN_VALUE, getPhase(stoppedBeans.get(5))); + assertThat(beanMin.isRunning()).isFalse(); + assertThat(beanNegative.isRunning()).isFalse(); + assertThat(bean1.isRunning()).isFalse(); + assertThat(bean2.isRunning()).isFalse(); + assertThat(bean7.isRunning()).isFalse(); + assertThat(simpleBean.isRunning()).isFalse(); + assertThat(stoppedBeans.size()).isEqualTo(6); + assertThat(getPhase(stoppedBeans.get(0))).isEqualTo(7); + assertThat(getPhase(stoppedBeans.get(1))).isEqualTo(2); + assertThat(getPhase(stoppedBeans.get(2))).isEqualTo(1); + assertThat(getPhase(stoppedBeans.get(3))).isEqualTo(-99); + assertThat(getPhase(stoppedBeans.get(4))).isEqualTo(0); + assertThat(getPhase(stoppedBeans.get(5))).isEqualTo(Integer.MIN_VALUE); } @Test @@ -523,13 +519,13 @@ public class DefaultLifecycleProcessorTests { context.getBeanFactory().registerSingleton("simpleBean", simpleBean); context.getBeanFactory().registerDependentBean("simpleBean", "beanMin"); context.refresh(); - assertTrue(beanMin.isRunning()); - assertTrue(bean7.isRunning()); - assertTrue(simpleBean.isRunning()); - assertEquals(3, startedBeans.size()); - assertEquals(0, getPhase(startedBeans.get(0))); - assertEquals(Integer.MIN_VALUE, getPhase(startedBeans.get(1))); - assertEquals(7, getPhase(startedBeans.get(2))); + assertThat(beanMin.isRunning()).isTrue(); + assertThat(bean7.isRunning()).isTrue(); + assertThat(simpleBean.isRunning()).isTrue(); + assertThat(startedBeans.size()).isEqualTo(3); + assertThat(getPhase(startedBeans.get(0))).isEqualTo(0); + assertThat(getPhase(startedBeans.get(1))).isEqualTo(Integer.MIN_VALUE); + assertThat(getPhase(startedBeans.get(2))).isEqualTo(7); context.stop(); } @@ -551,25 +547,25 @@ public class DefaultLifecycleProcessorTests { context.getBeanFactory().registerSingleton("simpleBean", simpleBean); context.getBeanFactory().registerDependentBean("bean2", "simpleBean"); context.refresh(); - assertTrue(beanMin.isRunning()); - assertTrue(bean1.isRunning()); - assertTrue(bean2.isRunning()); - assertTrue(bean7.isRunning()); - assertFalse(simpleBean.isRunning()); + assertThat(beanMin.isRunning()).isTrue(); + assertThat(bean1.isRunning()).isTrue(); + assertThat(bean2.isRunning()).isTrue(); + assertThat(bean7.isRunning()).isTrue(); + assertThat(simpleBean.isRunning()).isFalse(); simpleBean.start(); - assertTrue(simpleBean.isRunning()); + assertThat(simpleBean.isRunning()).isTrue(); context.stop(); - assertFalse(beanMin.isRunning()); - assertFalse(bean1.isRunning()); - assertFalse(bean2.isRunning()); - assertFalse(bean7.isRunning()); - assertFalse(simpleBean.isRunning()); - assertEquals(5, stoppedBeans.size()); - assertEquals(7, getPhase(stoppedBeans.get(0))); - assertEquals(0, getPhase(stoppedBeans.get(1))); - assertEquals(2, getPhase(stoppedBeans.get(2))); - assertEquals(1, getPhase(stoppedBeans.get(3))); - assertEquals(Integer.MIN_VALUE, getPhase(stoppedBeans.get(4))); + assertThat(beanMin.isRunning()).isFalse(); + assertThat(bean1.isRunning()).isFalse(); + assertThat(bean2.isRunning()).isFalse(); + assertThat(bean7.isRunning()).isFalse(); + assertThat(simpleBean.isRunning()).isFalse(); + assertThat(stoppedBeans.size()).isEqualTo(5); + assertThat(getPhase(stoppedBeans.get(0))).isEqualTo(7); + assertThat(getPhase(stoppedBeans.get(1))).isEqualTo(0); + assertThat(getPhase(stoppedBeans.get(2))).isEqualTo(2); + assertThat(getPhase(stoppedBeans.get(3))).isEqualTo(1); + assertThat(getPhase(stoppedBeans.get(4))).isEqualTo(Integer.MIN_VALUE); } diff --git a/spring-context/src/test/java/org/springframework/context/support/GenericApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/support/GenericApplicationContextTests.java index a819d5e0125..bbf3568b8cf 100644 --- a/spring-context/src/test/java/org/springframework/context/support/GenericApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/GenericApplicationContextTests.java @@ -24,14 +24,9 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertArrayEquals; -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 Juergen Hoeller @@ -45,9 +40,9 @@ public class GenericApplicationContextTests { ac.registerBeanDefinition("testBean", new RootBeanDefinition(String.class)); ac.refresh(); - assertEquals("", ac.getBean("testBean")); - assertSame(ac.getBean("testBean"), ac.getBean(String.class)); - assertSame(ac.getBean("testBean"), ac.getBean(CharSequence.class)); + assertThat(ac.getBean("testBean")).isEqualTo(""); + assertThat(ac.getBean(String.class)).isSameAs(ac.getBean("testBean")); + assertThat(ac.getBean(CharSequence.class)).isSameAs(ac.getBean("testBean")); assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> ac.getBean(Object.class)); @@ -59,10 +54,10 @@ public class GenericApplicationContextTests { ac.registerBeanDefinition("testBean", new RootBeanDefinition(String.class, ac::toString)); ac.refresh(); - assertSame(ac.getBean("testBean"), ac.getBean("testBean")); - assertSame(ac.getBean("testBean"), ac.getBean(String.class)); - assertSame(ac.getBean("testBean"), ac.getBean(CharSequence.class)); - assertEquals(ac.toString(), ac.getBean("testBean")); + assertThat(ac.getBean("testBean")).isSameAs(ac.getBean("testBean")); + assertThat(ac.getBean(String.class)).isSameAs(ac.getBean("testBean")); + assertThat(ac.getBean(CharSequence.class)).isSameAs(ac.getBean("testBean")); + assertThat(ac.getBean("testBean")).isEqualTo(ac.toString()); } @Test @@ -72,10 +67,10 @@ public class GenericApplicationContextTests { new RootBeanDefinition(String.class, RootBeanDefinition.SCOPE_PROTOTYPE, ac::toString)); ac.refresh(); - assertNotSame(ac.getBean("testBean"), ac.getBean("testBean")); - assertEquals(ac.getBean("testBean"), ac.getBean(String.class)); - assertEquals(ac.getBean("testBean"), ac.getBean(CharSequence.class)); - assertEquals(ac.toString(), ac.getBean("testBean")); + assertThat(ac.getBean("testBean")).isNotSameAs(ac.getBean("testBean")); + assertThat(ac.getBean(String.class)).isEqualTo(ac.getBean("testBean")); + assertThat(ac.getBean(CharSequence.class)).isEqualTo(ac.getBean("testBean")); + assertThat(ac.getBean("testBean")).isEqualTo(ac.toString()); } @Test @@ -84,9 +79,8 @@ public class GenericApplicationContextTests { ac.registerBeanDefinition("testBean", new RootBeanDefinition(String.class)); ac.refresh(); - assertSame(ac.getBean("testBean"), ac.getBean(String.class)); - assertSame(ac.getAutowireCapableBeanFactory().getBean("testBean"), - ac.getAutowireCapableBeanFactory().getBean(String.class)); + assertThat(ac.getBean(String.class)).isSameAs(ac.getBean("testBean")); + assertThat(ac.getAutowireCapableBeanFactory().getBean(String.class)).isSameAs(ac.getAutowireCapableBeanFactory().getBean("testBean")); ac.close(); @@ -107,9 +101,9 @@ public class GenericApplicationContextTests { context.registerBean(BeanC.class); context.refresh(); - assertSame(context.getBean(BeanB.class), context.getBean(BeanA.class).b); - assertSame(context.getBean(BeanC.class), context.getBean(BeanA.class).c); - assertSame(context, context.getBean(BeanB.class).applicationContext); + assertThat(context.getBean(BeanA.class).b).isSameAs(context.getBean(BeanB.class)); + assertThat(context.getBean(BeanA.class).c).isSameAs(context.getBean(BeanC.class)); + assertThat(context.getBean(BeanB.class).applicationContext).isSameAs(context); } @Test @@ -120,9 +114,9 @@ public class GenericApplicationContextTests { context.registerBean("c", BeanC.class); context.refresh(); - assertSame(context.getBean("b"), context.getBean("a", BeanA.class).b); - assertSame(context.getBean("c"), context.getBean("a", BeanA.class).c); - assertSame(context, context.getBean("b", BeanB.class).applicationContext); + assertThat(context.getBean("a", BeanA.class).b).isSameAs(context.getBean("b")); + assertThat(context.getBean("a", BeanA.class).c).isSameAs(context.getBean("c")); + assertThat(context.getBean("b", BeanB.class).applicationContext).isSameAs(context); } @Test @@ -134,15 +128,13 @@ public class GenericApplicationContextTests { context.registerBean(BeanC.class, BeanC::new); context.refresh(); - assertTrue(context.getBeanFactory().containsSingleton(BeanA.class.getName())); - assertSame(context.getBean(BeanB.class), context.getBean(BeanA.class).b); - assertSame(context.getBean(BeanC.class), context.getBean(BeanA.class).c); - assertSame(context, context.getBean(BeanB.class).applicationContext); + assertThat(context.getBeanFactory().containsSingleton(BeanA.class.getName())).isTrue(); + assertThat(context.getBean(BeanA.class).b).isSameAs(context.getBean(BeanB.class)); + assertThat(context.getBean(BeanA.class).c).isSameAs(context.getBean(BeanC.class)); + assertThat(context.getBean(BeanB.class).applicationContext).isSameAs(context); - assertArrayEquals(new String[] {BeanA.class.getName()}, - context.getDefaultListableBeanFactory().getDependentBeans(BeanB.class.getName())); - assertArrayEquals(new String[] {BeanA.class.getName()}, - context.getDefaultListableBeanFactory().getDependentBeans(BeanC.class.getName())); + assertThat(context.getDefaultListableBeanFactory().getDependentBeans(BeanB.class.getName())).isEqualTo(new String[] {BeanA.class.getName()}); + assertThat(context.getDefaultListableBeanFactory().getDependentBeans(BeanC.class.getName())).isEqualTo(new String[] {BeanA.class.getName()}); } @Test @@ -155,10 +147,10 @@ public class GenericApplicationContextTests { context.registerBean(BeanC.class, BeanC::new); context.refresh(); - assertFalse(context.getBeanFactory().containsSingleton(BeanA.class.getName())); - assertSame(context.getBean(BeanB.class), context.getBean(BeanA.class).b); - assertSame(context.getBean(BeanC.class), context.getBean(BeanA.class).c); - assertSame(context, context.getBean(BeanB.class).applicationContext); + assertThat(context.getBeanFactory().containsSingleton(BeanA.class.getName())).isFalse(); + assertThat(context.getBean(BeanA.class).b).isSameAs(context.getBean(BeanB.class)); + assertThat(context.getBean(BeanA.class).c).isSameAs(context.getBean(BeanC.class)); + assertThat(context.getBean(BeanB.class).applicationContext).isSameAs(context); } @Test @@ -170,10 +162,10 @@ public class GenericApplicationContextTests { context.registerBean("c", BeanC.class, BeanC::new); context.refresh(); - assertTrue(context.getBeanFactory().containsSingleton("a")); - assertSame(context.getBean("b", BeanB.class), context.getBean(BeanA.class).b); - assertSame(context.getBean("c"), context.getBean("a", BeanA.class).c); - assertSame(context, context.getBean("b", BeanB.class).applicationContext); + assertThat(context.getBeanFactory().containsSingleton("a")).isTrue(); + assertThat(context.getBean(BeanA.class).b).isSameAs(context.getBean("b", BeanB.class)); + assertThat(context.getBean("a", BeanA.class).c).isSameAs(context.getBean("c")); + assertThat(context.getBean("b", BeanB.class).applicationContext).isSameAs(context); } @Test @@ -186,10 +178,10 @@ public class GenericApplicationContextTests { context.registerBean("c", BeanC.class, BeanC::new); context.refresh(); - assertFalse(context.getBeanFactory().containsSingleton("a")); - assertSame(context.getBean("b", BeanB.class), context.getBean(BeanA.class).b); - assertSame(context.getBean("c"), context.getBean("a", BeanA.class).c); - assertSame(context, context.getBean("b", BeanB.class).applicationContext); + assertThat(context.getBeanFactory().containsSingleton("a")).isFalse(); + assertThat(context.getBean(BeanA.class).b).isSameAs(context.getBean("b", BeanB.class)); + assertThat(context.getBean("a", BeanA.class).c).isSameAs(context.getBean("c")); + assertThat(context.getBean("b", BeanB.class).applicationContext).isSameAs(context); } @Test @@ -200,12 +192,12 @@ public class GenericApplicationContextTests { context.registerBean("c", BeanC.class, BeanC::new); context.refresh(); - assertTrue(ObjectUtils.containsElement(context.getBeanNamesForType(BeanA.class), "a")); - assertTrue(ObjectUtils.containsElement(context.getBeanNamesForType(BeanB.class), "b")); - assertTrue(ObjectUtils.containsElement(context.getBeanNamesForType(BeanC.class), "c")); - assertTrue(context.getBeansOfType(BeanA.class).isEmpty()); - assertSame(context.getBean(BeanB.class), context.getBeansOfType(BeanB.class).values().iterator().next()); - assertSame(context.getBean(BeanC.class), context.getBeansOfType(BeanC.class).values().iterator().next()); + assertThat(ObjectUtils.containsElement(context.getBeanNamesForType(BeanA.class), "a")).isTrue(); + assertThat(ObjectUtils.containsElement(context.getBeanNamesForType(BeanB.class), "b")).isTrue(); + assertThat(ObjectUtils.containsElement(context.getBeanNamesForType(BeanC.class), "c")).isTrue(); + assertThat(context.getBeansOfType(BeanA.class).isEmpty()).isTrue(); + assertThat(context.getBeansOfType(BeanB.class).values().iterator().next()).isSameAs(context.getBean(BeanB.class)); + assertThat(context.getBeansOfType(BeanC.class).values().iterator().next()).isSameAs(context.getBean(BeanC.class)); } diff --git a/spring-context/src/test/java/org/springframework/context/support/LiveBeansViewTests.java b/spring-context/src/test/java/org/springframework/context/support/LiveBeansViewTests.java index 601d2795b9b..09ea419e692 100644 --- a/spring-context/src/test/java/org/springframework/context/support/LiveBeansViewTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/LiveBeansViewTests.java @@ -28,7 +28,7 @@ import org.junit.rules.TestName; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.mock.env.MockEnvironment; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -47,9 +47,9 @@ public class LiveBeansViewTests { @Test public void registerIgnoredIfPropertyIsNotSet() throws MalformedObjectNameException { ConfigurableApplicationContext context = createApplicationContext("app"); - assertEquals(0, searchLiveBeansViewMeans().size()); + assertThat(searchLiveBeansViewMeans().size()).isEqualTo(0); LiveBeansView.registerApplicationContext(context); - assertEquals(0, searchLiveBeansViewMeans().size()); + assertThat(searchLiveBeansViewMeans().size()).isEqualTo(0); LiveBeansView.unregisterApplicationContext(context); } @@ -57,11 +57,11 @@ public class LiveBeansViewTests { public void registerUnregisterSingleContext() throws MalformedObjectNameException { this.environment.setProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME, this.name.getMethodName()); ConfigurableApplicationContext context = createApplicationContext("app"); - assertEquals(0, searchLiveBeansViewMeans().size()); + assertThat(searchLiveBeansViewMeans().size()).isEqualTo(0); LiveBeansView.registerApplicationContext(context); assertSingleLiveBeansViewMbean("app"); LiveBeansView.unregisterApplicationContext(context); - assertEquals(0, searchLiveBeansViewMeans().size()); + assertThat(searchLiveBeansViewMeans().size()).isEqualTo(0); } @Test @@ -69,15 +69,16 @@ public class LiveBeansViewTests { this.environment.setProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME, this.name.getMethodName()); ConfigurableApplicationContext context = createApplicationContext("app"); ConfigurableApplicationContext childContext = createApplicationContext("child"); - assertEquals(0, searchLiveBeansViewMeans().size()); + assertThat(searchLiveBeansViewMeans().size()).isEqualTo(0); LiveBeansView.registerApplicationContext(context); assertSingleLiveBeansViewMbean("app"); LiveBeansView.registerApplicationContext(childContext); - assertEquals(1, searchLiveBeansViewMeans().size()); // Only one MBean + // Only one MBean + assertThat(searchLiveBeansViewMeans().size()).isEqualTo(1); LiveBeansView.unregisterApplicationContext(childContext); assertSingleLiveBeansViewMbean("app"); // Root context removes it LiveBeansView.unregisterApplicationContext(context); - assertEquals(0, searchLiveBeansViewMeans().size()); + assertThat(searchLiveBeansViewMeans().size()).isEqualTo(0); } @Test @@ -85,14 +86,14 @@ public class LiveBeansViewTests { this.environment.setProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME, this.name.getMethodName()); ConfigurableApplicationContext context = createApplicationContext("app"); ConfigurableApplicationContext childContext = createApplicationContext("child"); - assertEquals(0, searchLiveBeansViewMeans().size()); + assertThat(searchLiveBeansViewMeans().size()).isEqualTo(0); LiveBeansView.registerApplicationContext(context); assertSingleLiveBeansViewMbean("app"); LiveBeansView.registerApplicationContext(childContext); assertSingleLiveBeansViewMbean("app"); // Only one MBean LiveBeansView.unregisterApplicationContext(context); LiveBeansView.unregisterApplicationContext(childContext); - assertEquals(0, searchLiveBeansViewMeans().size()); + assertThat(searchLiveBeansViewMeans().size()).isEqualTo(0); } private ConfigurableApplicationContext createApplicationContext(String applicationName) { @@ -104,10 +105,8 @@ public class LiveBeansViewTests { public void assertSingleLiveBeansViewMbean(String applicationName) throws MalformedObjectNameException { Set objectNames = searchLiveBeansViewMeans(); - assertEquals(1, objectNames.size()); - assertEquals("Wrong MBean name", - String.format("%s:application=%s", this.name.getMethodName(), applicationName), - objectNames.iterator().next().getCanonicalName()); + assertThat(objectNames.size()).isEqualTo(1); + assertThat(objectNames.iterator().next().getCanonicalName()).as("Wrong MBean name").isEqualTo(String.format("%s:application=%s", this.name.getMethodName(), applicationName)); } diff --git a/spring-context/src/test/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurerTests.java b/spring-context/src/test/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurerTests.java index ee7bb823032..b15ecb02821 100644 --- a/spring-context/src/test/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurerTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurerTests.java @@ -36,7 +36,6 @@ 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; @@ -106,7 +105,7 @@ public class PropertySourcesPlaceholderConfigurerTests { ppc.setPropertySources(propertySources); ppc.postProcessBeanFactory(bf); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("foo"); - assertEquals(ppc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next()); + assertThat(propertySources.iterator().next()).isEqualTo(ppc.getAppliedPropertySources().iterator().next()); } @Test @@ -126,7 +125,7 @@ public class PropertySourcesPlaceholderConfigurerTests { ppc.setIgnoreUnresolvablePlaceholders(true); ppc.postProcessBeanFactory(bf); assertThat(bf.getBean(TestBean.class).getName()).isEqualTo("${my.name}"); - assertEquals(ppc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next()); + assertThat(propertySources.iterator().next()).isEqualTo(ppc.getAppliedPropertySources().iterator().next()); } @Test diff --git a/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java b/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java index 4634db5eb00..fc139e1fe9f 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java @@ -29,10 +29,8 @@ import org.springframework.context.MessageSourceResolvable; import org.springframework.context.NoSuchMessageException; import org.springframework.context.i18n.LocaleContextHolder; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -130,71 +128,71 @@ public class ResourceBundleMessageSourceTests { ac.refresh(); Locale.setDefault(expectGermanFallback ? Locale.GERMAN : Locale.CANADA); - assertEquals("message1", ac.getMessage("code1", null, Locale.ENGLISH)); - assertEquals(fallbackToSystemLocale && expectGermanFallback ? "nachricht2" : "message2", - ac.getMessage("code2", null, Locale.ENGLISH)); + assertThat(ac.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + Object expected = fallbackToSystemLocale && expectGermanFallback ? "nachricht2" : "message2"; + assertThat(ac.getMessage("code2", null, Locale.ENGLISH)).isEqualTo(expected); - assertEquals("nachricht2", ac.getMessage("code2", null, Locale.GERMAN)); - assertEquals("nochricht2", ac.getMessage("code2", null, new Locale("DE", "at"))); - assertEquals("noochricht2", ac.getMessage("code2", null, new Locale("DE", "at", "oo"))); + assertThat(ac.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); + assertThat(ac.getMessage("code2", null, new Locale("DE", "at"))).isEqualTo("nochricht2"); + assertThat(ac.getMessage("code2", null, new Locale("DE", "at", "oo"))).isEqualTo("noochricht2"); if (reloadable) { - assertEquals("nachricht2xml", ac.getMessage("code2", null, Locale.GERMANY)); + assertThat(ac.getMessage("code2", null, Locale.GERMANY)).isEqualTo("nachricht2xml"); } MessageSourceAccessor accessor = new MessageSourceAccessor(ac); LocaleContextHolder.setLocale(new Locale("DE", "at")); try { - assertEquals("nochricht2", accessor.getMessage("code2")); + assertThat(accessor.getMessage("code2")).isEqualTo("nochricht2"); } finally { LocaleContextHolder.setLocale(null); } - assertEquals("message3", ac.getMessage("code3", null, Locale.ENGLISH)); + assertThat(ac.getMessage("code3", null, Locale.ENGLISH)).isEqualTo("message3"); MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable("code3"); - assertEquals("message3", ac.getMessage(resolvable, Locale.ENGLISH)); + assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("message3"); resolvable = new DefaultMessageSourceResolvable(new String[] {"code4", "code3"}); - assertEquals("message3", ac.getMessage(resolvable, Locale.ENGLISH)); + assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("message3"); - assertEquals("message3", ac.getMessage("code3", null, Locale.ENGLISH)); + assertThat(ac.getMessage("code3", null, Locale.ENGLISH)).isEqualTo("message3"); resolvable = new DefaultMessageSourceResolvable(new String[] {"code4", "code3"}); - assertEquals("message3", ac.getMessage(resolvable, Locale.ENGLISH)); + assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("message3"); Object[] args = new Object[] {"Hello", new DefaultMessageSourceResolvable(new String[] {"code1"})}; - assertEquals("Hello, message1", ac.getMessage("hello", args, Locale.ENGLISH)); + assertThat(ac.getMessage("hello", args, Locale.ENGLISH)).isEqualTo("Hello, message1"); // test default message without and with args - assertNull(ac.getMessage(null, null, null, Locale.ENGLISH)); - assertEquals("default", ac.getMessage(null, null, "default", Locale.ENGLISH)); - assertEquals("default", ac.getMessage(null, args, "default", Locale.ENGLISH)); - assertEquals("{0}, default", ac.getMessage(null, null, "{0}, default", Locale.ENGLISH)); - assertEquals("Hello, default", ac.getMessage(null, args, "{0}, default", Locale.ENGLISH)); + assertThat(ac.getMessage(null, null, null, Locale.ENGLISH)).isNull(); + assertThat(ac.getMessage(null, null, "default", Locale.ENGLISH)).isEqualTo("default"); + assertThat(ac.getMessage(null, args, "default", Locale.ENGLISH)).isEqualTo("default"); + assertThat(ac.getMessage(null, null, "{0}, default", Locale.ENGLISH)).isEqualTo("{0}, default"); + assertThat(ac.getMessage(null, args, "{0}, default", Locale.ENGLISH)).isEqualTo("Hello, default"); // test resolvable with default message, without and with args resolvable = new DefaultMessageSourceResolvable(null, null, "default"); - assertEquals("default", ac.getMessage(resolvable, Locale.ENGLISH)); + assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("default"); resolvable = new DefaultMessageSourceResolvable(null, args, "default"); - assertEquals("default", ac.getMessage(resolvable, Locale.ENGLISH)); + assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("default"); resolvable = new DefaultMessageSourceResolvable(null, null, "{0}, default"); - assertEquals("{0}, default", ac.getMessage(resolvable, Locale.ENGLISH)); + assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("{0}, default"); resolvable = new DefaultMessageSourceResolvable(null, args, "{0}, default"); - assertEquals("Hello, default", ac.getMessage(resolvable, Locale.ENGLISH)); + assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("Hello, default"); // test message args - assertEquals("Arg1, Arg2", ac.getMessage("hello", new Object[] {"Arg1", "Arg2"}, Locale.ENGLISH)); - assertEquals("{0}, {1}", ac.getMessage("hello", null, Locale.ENGLISH)); + assertThat(ac.getMessage("hello", new Object[]{"Arg1", "Arg2"}, Locale.ENGLISH)).isEqualTo("Arg1, Arg2"); + assertThat(ac.getMessage("hello", null, Locale.ENGLISH)).isEqualTo("{0}, {1}"); if (alwaysUseMessageFormat) { - assertEquals("I'm", ac.getMessage("escaped", null, Locale.ENGLISH)); + assertThat(ac.getMessage("escaped", null, Locale.ENGLISH)).isEqualTo("I'm"); } else { - assertEquals("I''m", ac.getMessage("escaped", null, Locale.ENGLISH)); + assertThat(ac.getMessage("escaped", null, Locale.ENGLISH)).isEqualTo("I''m"); } - assertEquals("I'm", ac.getMessage("escaped", new Object[] {"some arg"}, Locale.ENGLISH)); + assertThat(ac.getMessage("escaped", new Object[]{"some arg"}, Locale.ENGLISH)).isEqualTo("I'm"); if (useCodeAsDefaultMessage) { - assertEquals("code4", ac.getMessage("code4", null, Locale.GERMAN)); + assertThat(ac.getMessage("code4", null, Locale.GERMAN)).isEqualTo("code4"); } else { assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> @@ -206,8 +204,8 @@ public class ResourceBundleMessageSourceTests { public void testDefaultApplicationContextMessageSource() { GenericApplicationContext ac = new GenericApplicationContext(); ac.refresh(); - assertEquals("default", ac.getMessage("code1", null, "default", Locale.ENGLISH)); - assertEquals("default value", ac.getMessage("code1", new Object[] {"value"}, "default {0}", Locale.ENGLISH)); + assertThat(ac.getMessage("code1", null, "default", Locale.ENGLISH)).isEqualTo("default"); + assertThat(ac.getMessage("code1", new Object[]{"value"}, "default {0}", Locale.ENGLISH)).isEqualTo("default value"); } @Test @@ -217,8 +215,8 @@ public class ResourceBundleMessageSourceTests { parent.refresh(); ac.setParent(parent); ac.refresh(); - assertEquals("default", ac.getMessage("code1", null, "default", Locale.ENGLISH)); - assertEquals("default value", ac.getMessage("code1", new Object[] {"value"}, "default {0}", Locale.ENGLISH)); + assertThat(ac.getMessage("code1", null, "default", Locale.ENGLISH)).isEqualTo("default"); + assertThat(ac.getMessage("code1", new Object[]{"value"}, "default {0}", Locale.ENGLISH)).isEqualTo("default value"); } @Test @@ -228,8 +226,8 @@ public class ResourceBundleMessageSourceTests { parent.refresh(); ac.setParent(parent); ac.refresh(); - assertEquals("default", ac.getMessage("code1", null, "default", Locale.ENGLISH)); - assertEquals("default value", ac.getMessage("code1", new Object[] {"value"}, "default {0}", Locale.ENGLISH)); + assertThat(ac.getMessage("code1", null, "default", Locale.ENGLISH)).isEqualTo("default"); + assertThat(ac.getMessage("code1", new Object[]{"value"}, "default {0}", Locale.ENGLISH)).isEqualTo("default value"); } @Test @@ -239,24 +237,24 @@ public class ResourceBundleMessageSourceTests { parent.refresh(); ac.setParent(parent); ac.refresh(); - assertEquals("default", ac.getMessage("code1", null, "default", Locale.ENGLISH)); - assertEquals("default value", ac.getMessage("code1", new Object[] {"value"}, "default {0}", Locale.ENGLISH)); + assertThat(ac.getMessage("code1", null, "default", Locale.ENGLISH)).isEqualTo("default"); + assertThat(ac.getMessage("code1", new Object[]{"value"}, "default {0}", Locale.ENGLISH)).isEqualTo("default value"); } @Test public void testResourceBundleMessageSourceStandalone() { ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); ms.setBasename("org/springframework/context/support/messages"); - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); } @Test public void testResourceBundleMessageSourceWithWhitespaceInBasename() { ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); ms.setBasename(" org/springframework/context/support/messages "); - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); } @Test @@ -264,8 +262,8 @@ public class ResourceBundleMessageSourceTests { ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); ms.setBasename("org/springframework/context/support/messages"); ms.setDefaultEncoding("ISO-8859-1"); - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); } @Test @@ -282,8 +280,8 @@ public class ResourceBundleMessageSourceTests { public void testReloadableResourceBundleMessageSourceStandalone() { ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource(); ms.setBasename("org/springframework/context/support/messages"); - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); } @Test @@ -292,12 +290,12 @@ public class ResourceBundleMessageSourceTests { ms.setBasename("org/springframework/context/support/messages"); ms.setCacheSeconds(1); // Initial cache attempt - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); Thread.sleep(1100); // Late enough for a re-cache attempt - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); } @Test @@ -307,12 +305,12 @@ public class ResourceBundleMessageSourceTests { ms.setCacheSeconds(1); ms.setConcurrentRefresh(false); // Initial cache attempt - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); Thread.sleep(1100); // Late enough for a re-cache attempt - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); } @Test @@ -322,18 +320,18 @@ public class ResourceBundleMessageSourceTests { commonMessages.setProperty("warning", "Do not do {0}"); ms.setCommonMessages(commonMessages); ms.setBasename("org/springframework/context/support/messages"); - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); - assertEquals("Do not do this", ms.getMessage("warning", new Object[] {"this"}, Locale.ENGLISH)); - assertEquals("Do not do that", ms.getMessage("warning", new Object[] {"that"}, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); + assertThat(ms.getMessage("warning", new Object[]{"this"}, Locale.ENGLISH)).isEqualTo("Do not do this"); + assertThat(ms.getMessage("warning", new Object[]{"that"}, Locale.GERMAN)).isEqualTo("Do not do that"); } @Test public void testReloadableResourceBundleMessageSourceWithWhitespaceInBasename() { ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource(); ms.setBasename(" org/springframework/context/support/messages "); - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); } @Test @@ -341,8 +339,8 @@ public class ResourceBundleMessageSourceTests { ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource(); ms.setBasename("org/springframework/context/support/messages"); ms.setDefaultEncoding("ISO-8859-1"); - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2"); } @Test @@ -378,8 +376,8 @@ public class ResourceBundleMessageSourceTests { Properties fileCharsets = new Properties(); fileCharsets.setProperty("org/springframework/context/support/messages_de", "unicode"); ms.setFileEncodings(fileCharsets); - assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); - assertEquals("message2", ms.getMessage("code2", null, Locale.GERMAN)); + assertThat(ms.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1"); + assertThat(ms.getMessage("code2", null, Locale.GERMAN)).isEqualTo("message2"); } @Test @@ -387,32 +385,32 @@ public class ResourceBundleMessageSourceTests { ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource(); List filenames = ms.calculateFilenamesForLocale("messages", Locale.ENGLISH); - assertEquals(1, filenames.size()); - assertEquals("messages_en", filenames.get(0)); + assertThat(filenames.size()).isEqualTo(1); + assertThat(filenames.get(0)).isEqualTo("messages_en"); filenames = ms.calculateFilenamesForLocale("messages", Locale.UK); - assertEquals(2, filenames.size()); - assertEquals("messages_en", filenames.get(1)); - assertEquals("messages_en_GB", filenames.get(0)); + assertThat(filenames.size()).isEqualTo(2); + assertThat(filenames.get(1)).isEqualTo("messages_en"); + assertThat(filenames.get(0)).isEqualTo("messages_en_GB"); filenames = ms.calculateFilenamesForLocale("messages", new Locale("en", "GB", "POSIX")); - assertEquals(3, filenames.size()); - assertEquals("messages_en", filenames.get(2)); - assertEquals("messages_en_GB", filenames.get(1)); - assertEquals("messages_en_GB_POSIX", filenames.get(0)); + assertThat(filenames.size()).isEqualTo(3); + assertThat(filenames.get(2)).isEqualTo("messages_en"); + assertThat(filenames.get(1)).isEqualTo("messages_en_GB"); + assertThat(filenames.get(0)).isEqualTo("messages_en_GB_POSIX"); filenames = ms.calculateFilenamesForLocale("messages", new Locale("en", "", "POSIX")); - assertEquals(2, filenames.size()); - assertEquals("messages_en", filenames.get(1)); - assertEquals("messages_en__POSIX", filenames.get(0)); + assertThat(filenames.size()).isEqualTo(2); + assertThat(filenames.get(1)).isEqualTo("messages_en"); + assertThat(filenames.get(0)).isEqualTo("messages_en__POSIX"); filenames = ms.calculateFilenamesForLocale("messages", new Locale("", "UK", "POSIX")); - assertEquals(2, filenames.size()); - assertEquals("messages__UK", filenames.get(1)); - assertEquals("messages__UK_POSIX", filenames.get(0)); + assertThat(filenames.size()).isEqualTo(2); + assertThat(filenames.get(1)).isEqualTo("messages__UK"); + assertThat(filenames.get(0)).isEqualTo("messages__UK_POSIX"); filenames = ms.calculateFilenamesForLocale("messages", new Locale("", "", "POSIX")); - assertEquals(0, filenames.size()); + assertThat(filenames.size()).isEqualTo(0); } @Test @@ -420,11 +418,11 @@ public class ResourceBundleMessageSourceTests { ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); ms.setBasename("org/springframework/context/support/messages"); MessageSourceResourceBundle rbe = new MessageSourceResourceBundle(ms, Locale.ENGLISH); - assertEquals("message1", rbe.getString("code1")); - assertTrue(rbe.containsKey("code1")); + assertThat(rbe.getString("code1")).isEqualTo("message1"); + assertThat(rbe.containsKey("code1")).isTrue(); MessageSourceResourceBundle rbg = new MessageSourceResourceBundle(ms, Locale.GERMAN); - assertEquals("nachricht2", rbg.getString("code2")); - assertTrue(rbg.containsKey("code2")); + assertThat(rbg.getString("code2")).isEqualTo("nachricht2"); + assertThat(rbg.containsKey("code2")).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/context/support/SimpleThreadScopeTests.java b/spring-context/src/test/java/org/springframework/context/support/SimpleThreadScopeTests.java index 10a0f6f5aa7..bae8630c3e7 100644 --- a/spring-context/src/test/java/org/springframework/context/support/SimpleThreadScopeTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/SimpleThreadScopeTests.java @@ -24,9 +24,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -42,10 +40,10 @@ public class SimpleThreadScopeTests { public void getFromScope() throws Exception { String name = "threadScopedObject"; TestBean bean = this.applicationContext.getBean(name, TestBean.class); - assertNotNull(bean); - assertSame(bean, this.applicationContext.getBean(name)); + assertThat(bean).isNotNull(); + assertThat(this.applicationContext.getBean(name)).isSameAs(bean); TestBean bean2 = this.applicationContext.getBean(name, TestBean.class); - assertSame(bean, bean2); + assertThat(bean2).isSameAs(bean); } @Test @@ -62,7 +60,7 @@ public class SimpleThreadScopeTests { .atMost(500, TimeUnit.MILLISECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(() -> (beans[0] != null) && (beans[1] != null)); - assertNotSame(beans[0], beans[1]); + assertThat(beans[1]).isNotSameAs(beans[0]); } } diff --git a/spring-context/src/test/java/org/springframework/context/support/Spr7283Tests.java b/spring-context/src/test/java/org/springframework/context/support/Spr7283Tests.java index aef06dc77a0..dee3e0167da 100644 --- a/spring-context/src/test/java/org/springframework/context/support/Spr7283Tests.java +++ b/spring-context/src/test/java/org/springframework/context/support/Spr7283Tests.java @@ -20,8 +20,7 @@ import java.util.List; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Scott Andrews @@ -33,9 +32,11 @@ public class Spr7283Tests { public void testListWithInconsistentElementType() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spr7283.xml", getClass()); List list = ctx.getBean("list", List.class); - assertEquals(2, list.size()); - assertTrue(list.get(0) instanceof A); - assertTrue(list.get(1) instanceof B); + assertThat(list.size()).isEqualTo(2); + boolean condition1 = list.get(0) instanceof A; + assertThat(condition1).isTrue(); + boolean condition = list.get(1) instanceof B; + assertThat(condition).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/context/support/Spr7816Tests.java b/spring-context/src/test/java/org/springframework/context/support/Spr7816Tests.java index 3c6034c22e8..643a4c379d9 100644 --- a/spring-context/src/test/java/org/springframework/context/support/Spr7816Tests.java +++ b/spring-context/src/test/java/org/springframework/context/support/Spr7816Tests.java @@ -22,7 +22,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Keith Donald @@ -34,9 +34,9 @@ public class Spr7816Tests { public void spr7816() { ApplicationContext ctx = new ClassPathXmlApplicationContext("spr7816.xml", getClass()); FilterAdapter adapter = ctx.getBean(FilterAdapter.class); - assertEquals(Building.class, adapter.getSupportedTypes().get("Building")); - assertEquals(Entrance.class, adapter.getSupportedTypes().get("Entrance")); - assertEquals(Dwelling.class, adapter.getSupportedTypes().get("Dwelling")); + assertThat(adapter.getSupportedTypes().get("Building")).isEqualTo(Building.class); + assertThat(adapter.getSupportedTypes().get("Entrance")).isEqualTo(Entrance.class); + assertThat(adapter.getSupportedTypes().get("Dwelling")).isEqualTo(Dwelling.class); } public static class FilterAdapter { diff --git a/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java b/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java index 011f1b73bfb..bce7e26f109 100644 --- a/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java @@ -37,7 +37,7 @@ import org.springframework.core.io.support.EncodedResource; import org.springframework.lang.Nullable; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for static application context with custom application event multicaster. @@ -89,7 +89,7 @@ public class StaticApplicationContextMulticasterTests extends AbstractApplicatio public void events() throws Exception { TestApplicationEventMulticaster.counter = 0; super.events(); - assertEquals(1, TestApplicationEventMulticaster.counter); + assertThat(TestApplicationEventMulticaster.counter).isEqualTo(1); } diff --git a/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java b/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java index 373194c6e51..44c68e9facb 100644 --- a/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java @@ -33,9 +33,8 @@ import org.springframework.context.MessageSourceResolvable; import org.springframework.context.NoSuchMessageException; import org.springframework.core.io.ClassPathResource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -73,17 +72,15 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { @Test public void getMessageWithDefaultPassedInAndFoundInMsgCatalog() { // Try with Locale.US - assertTrue("valid msg from staticMsgSource with default msg passed in returned msg from msg catalog for Locale.US", - sac.getMessage("message.format.example2", null, "This is a default msg if not found in MessageSource.", Locale.US) - .equals("This is a test message in the message catalog with no args.")); + assertThat(sac.getMessage("message.format.example2", null, "This is a default msg if not found in MessageSource.", Locale.US) + .equals("This is a test message in the message catalog with no args.")).as("valid msg from staticMsgSource with default msg passed in returned msg from msg catalog for Locale.US").isTrue(); } @Test public void getMessageWithDefaultPassedInAndNotFoundInMsgCatalog() { // Try with Locale.US - assertTrue("bogus msg from staticMsgSource with default msg passed in returned default msg for Locale.US", - sac.getMessage("bogus.message", null, "This is a default msg if not found in MessageSource.", Locale.US) - .equals("This is a default msg if not found in MessageSource.")); + assertThat(sac.getMessage("bogus.message", null, "This is a default msg if not found in MessageSource.", Locale.US) + .equals("This is a default msg if not found in MessageSource.")).as("bogus msg from staticMsgSource with default msg passed in returned default msg for Locale.US").isTrue(); } /** @@ -105,9 +102,8 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { sac.getMessage("message.format.example1", arguments, Locale.US); // Now msg better be as expected - assertTrue("2nd search within MsgFormat cache returned expected message for Locale.US", - sac.getMessage("message.format.example1", arguments, Locale.US). - contains("there was \"a disturbance in the Force\" on planet 7.")); + assertThat(sac.getMessage("message.format.example1", arguments, Locale.US). + contains("there was \"a disturbance in the Force\" on planet 7.")).as("2nd search within MsgFormat cache returned expected message for Locale.US").isTrue(); Object[] newArguments = { new Integer(8), new Date(System.currentTimeMillis()), @@ -115,9 +111,8 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { }; // Now msg better be as expected even with different args - assertTrue("2nd search within MsgFormat cache with different args returned expected message for Locale.US", - sac.getMessage("message.format.example1", newArguments, Locale.US). - contains("there was \"a disturbance in the Force\" on planet 8.")); + assertThat(sac.getMessage("message.format.example1", newArguments, Locale.US). + contains("there was \"a disturbance in the Force\" on planet 8.")).as("2nd search within MsgFormat cache with different args returned expected message for Locale.US").isTrue(); } /** @@ -138,19 +133,16 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { and the time the ResourceBundleMessageSource resolves the msg the minutes of the time might not be the same. */ - assertTrue("msg from staticMsgSource for Locale.US substituting args for placeholders is as expected", - sac.getMessage("message.format.example1", arguments, Locale.US). - contains("there was \"a disturbance in the Force\" on planet 7.")); + assertThat(sac.getMessage("message.format.example1", arguments, Locale.US). + contains("there was \"a disturbance in the Force\" on planet 7.")).as("msg from staticMsgSource for Locale.US substituting args for placeholders is as expected").isTrue(); // Try with Locale.UK - assertTrue("msg from staticMsgSource for Locale.UK substituting args for placeholders is as expected", - sac.getMessage("message.format.example1", arguments, Locale.UK). - contains("there was \"a disturbance in the Force\" on station number 7.")); + assertThat(sac.getMessage("message.format.example1", arguments, Locale.UK). + contains("there was \"a disturbance in the Force\" on station number 7.")).as("msg from staticMsgSource for Locale.UK substituting args for placeholders is as expected").isTrue(); // Try with Locale.US - Use a different test msg that requires no args - assertTrue("msg from staticMsgSource for Locale.US that requires no args is as expected", - sac.getMessage("message.format.example2", null, Locale.US) - .equals("This is a test message in the message catalog with no args.")); + assertThat(sac.getMessage("message.format.example2", null, Locale.US) + .equals("This is a test message in the message catalog with no args.")).as("msg from staticMsgSource for Locale.US that requires no args is as expected").isTrue(); } @Test @@ -165,17 +157,17 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { // first code valid String[] codes1 = new String[] {"message.format.example3", "message.format.example2"}; MessageSourceResolvable resolvable1 = new DefaultMessageSourceResolvable(codes1, null, "default"); - assertTrue("correct message retrieved", MSG_TXT3_US.equals(sac.getMessage(resolvable1, Locale.US))); + assertThat(MSG_TXT3_US.equals(sac.getMessage(resolvable1, Locale.US))).as("correct message retrieved").isTrue(); // only second code valid String[] codes2 = new String[] {"message.format.example99", "message.format.example2"}; MessageSourceResolvable resolvable2 = new DefaultMessageSourceResolvable(codes2, null, "default"); - assertTrue("correct message retrieved", MSG_TXT2_US.equals(sac.getMessage(resolvable2, Locale.US))); + assertThat(MSG_TXT2_US.equals(sac.getMessage(resolvable2, Locale.US))).as("correct message retrieved").isTrue(); // no code valid, but default given String[] codes3 = new String[] {"message.format.example99", "message.format.example98"}; MessageSourceResolvable resolvable3 = new DefaultMessageSourceResolvable(codes3, null, "default"); - assertTrue("correct message retrieved", "default".equals(sac.getMessage(resolvable3, Locale.US))); + assertThat("default".equals(sac.getMessage(resolvable3, Locale.US))).as("correct message retrieved").isTrue(); // no code valid, no default String[] codes4 = new String[] {"message.format.example99", "message.format.example98"}; @@ -234,7 +226,7 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable( new String[] {"with.param"}, new Object[] {new DefaultMessageSourceResolvable("param")}); - assertEquals("put value here", source.getMessage(resolvable, Locale.ENGLISH)); + assertThat(source.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("put value here"); } @Test @@ -249,7 +241,7 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable( new String[] {"with.param"}, new Object[] {new DefaultMessageSourceResolvable("param")}); - assertEquals("put value here", source.getMessage(resolvable, Locale.ENGLISH)); + assertThat(source.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("put value here"); } } diff --git a/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java b/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java index 1f8dd1785a3..8f5876be1fd 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java @@ -29,7 +29,6 @@ import org.springframework.jndi.JndiTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -63,7 +62,7 @@ public class LocalSlsbInvokerInterceptorTests { JndiTemplate jt = new JndiTemplate() { @Override public Object lookup(String name) throws NamingException { - assertTrue(jndiName.equals(name)); + assertThat(jndiName.equals(name)).isTrue(); throw nex; } }; @@ -93,7 +92,7 @@ public class LocalSlsbInvokerInterceptorTests { pf.addAdvice(si); BusinessMethods target = (BusinessMethods) pf.getProxy(); - assertTrue(target.targetMethod() == retVal); + assertThat(target.targetMethod() == retVal).isTrue(); verify(mockContext).close(); verify(ejb).remove(); @@ -114,7 +113,7 @@ public class LocalSlsbInvokerInterceptorTests { pf.addAdvice(si); BusinessMethods target = (BusinessMethods) pf.getProxy(); - assertTrue(target.targetMethod() == retVal); + assertThat(target.targetMethod() == retVal).isTrue(); verify(mockContext).close(); verify(ejb).remove(); diff --git a/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java index a85703e2779..b07b347f766 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java @@ -26,10 +26,9 @@ import org.junit.Test; import org.springframework.jndi.JndiTemplate; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.Mockito.mock; import static org.mockito.Mockito.verify; @@ -58,7 +57,7 @@ public class LocalStatelessSessionProxyFactoryBeanTests { @Override public Object lookup(String name) throws NamingException { // parameterize - assertTrue(name.equals("java:comp/env/" + jndiName)); + assertThat(name.equals("java:comp/env/" + jndiName)).isTrue(); return home; } }; @@ -73,8 +72,8 @@ public class LocalStatelessSessionProxyFactoryBeanTests { fb.afterPropertiesSet(); MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject(); - assertTrue(Proxy.isProxyClass(mbm.getClass())); - assertTrue(mbm.getValue() == value); + assertThat(Proxy.isProxyClass(mbm.getClass())).isTrue(); + assertThat(mbm.getValue() == value).isTrue(); verify(myEjb).remove(); } @@ -90,7 +89,7 @@ public class LocalStatelessSessionProxyFactoryBeanTests { @Override public Object lookup(String name) throws NamingException { // parameterize - assertTrue(name.equals("java:comp/env/" + jndiName)); + assertThat(name.equals("java:comp/env/" + jndiName)).isTrue(); return myEjb; } }; @@ -105,8 +104,8 @@ public class LocalStatelessSessionProxyFactoryBeanTests { fb.afterPropertiesSet(); MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject(); - assertTrue(Proxy.isProxyClass(mbm.getClass())); - assertTrue(mbm.getValue() == value); + assertThat(Proxy.isProxyClass(mbm.getClass())).isTrue(); + assertThat(mbm.getValue() == value).isTrue(); } @Test @@ -121,7 +120,7 @@ public class LocalStatelessSessionProxyFactoryBeanTests { @Override public Object lookup(String name) throws NamingException { // parameterize - assertTrue(name.equals(jndiName)); + assertThat(name.equals(jndiName)).isTrue(); return home; } }; @@ -130,14 +129,14 @@ public class LocalStatelessSessionProxyFactoryBeanTests { fb.setJndiName(jndiName); fb.setResourceRef(false); // no java:comp/env prefix fb.setBusinessInterface(MyBusinessMethods.class); - assertEquals(fb.getBusinessInterface(), MyBusinessMethods.class); + assertThat(MyBusinessMethods.class).isEqualTo(fb.getBusinessInterface()); fb.setJndiTemplate(jt); // Need lifecycle methods fb.afterPropertiesSet(); MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject(); - assertTrue(Proxy.isProxyClass(mbm.getClass())); + assertThat(Proxy.isProxyClass(mbm.getClass())).isTrue(); assertThatExceptionOfType(EjbAccessException.class).isThrownBy( mbm::getValue) @@ -156,7 +155,7 @@ public class LocalStatelessSessionProxyFactoryBeanTests { @Override public Object lookup(String name) throws NamingException { // parameterize - assertTrue(name.equals("java:comp/env/" + jndiName)); + assertThat(name.equals("java:comp/env/" + jndiName)).isTrue(); return home; } }; @@ -168,7 +167,7 @@ public class LocalStatelessSessionProxyFactoryBeanTests { fb.setJndiTemplate(jt); // Check it's a singleton - assertTrue(fb.isSingleton()); + assertThat(fb.isSingleton()).isTrue(); assertThatIllegalArgumentException().isThrownBy( fb::afterPropertiesSet) diff --git a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java index 68f381be589..7369acce549 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java @@ -32,8 +32,6 @@ import org.springframework.remoting.RemoteAccessException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -107,7 +105,7 @@ public class SimpleRemoteSlsbInvokerInterceptorTests { SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName); si.setExposeAccessContext(true); RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class); - assertNull(target.targetMethod()); + assertThat(target.targetMethod()).isNull(); verify(mockContext, times(2)).close(); verify(ejb).targetMethod(); @@ -121,7 +119,7 @@ public class SimpleRemoteSlsbInvokerInterceptorTests { JndiTemplate jt = new JndiTemplate() { @Override public Object lookup(String name) throws NamingException { - assertTrue(jndiName.equals(name)); + assertThat(jndiName.equals(name)).isTrue(); throw nex; } }; @@ -177,8 +175,8 @@ public class SimpleRemoteSlsbInvokerInterceptorTests { si.setCacheHome(cacheHome); RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class); - assertTrue(target.targetMethod() == retVal); - assertTrue(target.targetMethod() == retVal); + assertThat(target.targetMethod() == retVal).isTrue(); + assertThat(target.targetMethod() == retVal).isTrue(); verify(mockContext, times(lookupCount)).close(); verify(ejb, times(2)).remove(); @@ -265,7 +263,7 @@ public class SimpleRemoteSlsbInvokerInterceptorTests { SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName); BusinessInterface target = (BusinessInterface) configuredProxy(si, BusinessInterface.class); - assertTrue(target.targetMethod() == retVal); + assertThat(target.targetMethod() == retVal).isTrue(); verify(mockContext).close(); verify(ejb).remove(); diff --git a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java index 6b967561250..422e8aa98f0 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java @@ -31,8 +31,6 @@ import org.springframework.remoting.RemoteAccessException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.Mockito.mock; import static org.mockito.Mockito.verify; @@ -73,7 +71,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem @Override public Object lookup(String name) { // parameterize - assertTrue(name.equals("java:comp/env/" + jndiName)); + assertThat(name.equals("java:comp/env/" + jndiName)).isTrue(); return home; } }; @@ -88,8 +86,8 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem fb.afterPropertiesSet(); MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject(); - assertTrue(Proxy.isProxyClass(mbm.getClass())); - assertEquals("Returns expected value", value, mbm.getValue()); + assertThat(Proxy.isProxyClass(mbm.getClass())).isTrue(); + assertThat(mbm.getValue()).as("Returns expected value").isEqualTo(value); verify(myEjb).remove(); } @@ -105,7 +103,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem @Override public Object lookup(String name) { // parameterize - assertTrue(name.equals("java:comp/env/" + jndiName)); + assertThat(name.equals("java:comp/env/" + jndiName)).isTrue(); return myEjb; } }; @@ -120,8 +118,8 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem fb.afterPropertiesSet(); MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject(); - assertTrue(Proxy.isProxyClass(mbm.getClass())); - assertEquals("Returns expected value", value, mbm.getValue()); + assertThat(Proxy.isProxyClass(mbm.getClass())).isTrue(); + assertThat(mbm.getValue()).as("Returns expected value").isEqualTo(value); } @Override @@ -142,7 +140,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem @Override public Object lookup(String name) { // parameterize - assertTrue(name.equals("java:comp/env/" + jndiName)); + assertThat(name.equals("java:comp/env/" + jndiName)).isTrue(); return home; } }; @@ -157,7 +155,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem fb.afterPropertiesSet(); MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject(); - assertTrue(Proxy.isProxyClass(mbm.getClass())); + assertThat(Proxy.isProxyClass(mbm.getClass())).isTrue(); assertThatExceptionOfType(RemoteException.class).isThrownBy( mbm::getValue) .satisfies(ex -> assertThat(ex).isSameAs(rex)); @@ -176,7 +174,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem @Override public Object lookup(String name) { // parameterize - assertTrue(name.equals(jndiName)); + assertThat(name.equals(jndiName)).isTrue(); return home; } }; @@ -185,14 +183,14 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem fb.setJndiName(jndiName); // rely on default setting of resourceRef=false, no auto addition of java:/comp/env prefix fb.setBusinessInterface(MyBusinessMethods.class); - assertEquals(fb.getBusinessInterface(), MyBusinessMethods.class); + assertThat(MyBusinessMethods.class).isEqualTo(fb.getBusinessInterface()); fb.setJndiTemplate(jt); // Need lifecycle methods fb.afterPropertiesSet(); MyBusinessMethods mbm = (MyBusinessMethods) fb.getObject(); - assertTrue(Proxy.isProxyClass(mbm.getClass())); + assertThat(Proxy.isProxyClass(mbm.getClass())).isTrue(); assertThatExceptionOfType(RemoteException.class).isThrownBy(mbm::getValue); } @@ -208,7 +206,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem @Override public Object lookup(String name) { // parameterize - assertTrue(name.equals(jndiName)); + assertThat(name.equals(jndiName)).isTrue(); return home; } }; @@ -217,14 +215,14 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem fb.setJndiName(jndiName); // rely on default setting of resourceRef=false, no auto addition of java:/comp/env prefix fb.setBusinessInterface(MyLocalBusinessMethods.class); - assertEquals(fb.getBusinessInterface(), MyLocalBusinessMethods.class); + assertThat(MyLocalBusinessMethods.class).isEqualTo(fb.getBusinessInterface()); fb.setJndiTemplate(jt); // Need lifecycle methods fb.afterPropertiesSet(); MyLocalBusinessMethods mbm = (MyLocalBusinessMethods) fb.getObject(); - assertTrue(Proxy.isProxyClass(mbm.getClass())); + assertThat(Proxy.isProxyClass(mbm.getClass())).isTrue(); assertThatExceptionOfType(RemoteAccessException.class).isThrownBy( mbm::getValue) .withCause(cex); @@ -242,7 +240,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem @Override public Object lookup(String name) throws NamingException { // parameterize - assertTrue(name.equals(jndiName)); + assertThat(name.equals(jndiName)).isTrue(); return home; } }; @@ -254,7 +252,7 @@ public class SimpleRemoteStatelessSessionProxyFactoryBeanTests extends SimpleRem fb.setJndiTemplate(jt); // Check it's a singleton - assertTrue(fb.isSingleton()); + assertThat(fb.isSingleton()).isTrue(); assertThatIllegalArgumentException().isThrownBy( fb::afterPropertiesSet) diff --git a/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerEventTests.java b/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerEventTests.java index d6dba4ae5d8..16369a478fa 100644 --- a/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerEventTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerEventTests.java @@ -26,7 +26,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.beans.CollectingReaderEventListener; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Torsten Juergeleit @@ -52,19 +52,22 @@ public class JeeNamespaceHandlerEventTests { @Test public void testJndiLookupComponentEventReceived() { ComponentDefinition component = this.eventListener.getComponentDefinition("simple"); - assertTrue(component instanceof BeanComponentDefinition); + boolean condition = component instanceof BeanComponentDefinition; + assertThat(condition).isTrue(); } @Test public void testLocalSlsbComponentEventReceived() { ComponentDefinition component = this.eventListener.getComponentDefinition("simpleLocalEjb"); - assertTrue(component instanceof BeanComponentDefinition); + boolean condition = component instanceof BeanComponentDefinition; + assertThat(condition).isTrue(); } @Test public void testRemoteSlsbComponentEventReceived() { ComponentDefinition component = this.eventListener.getComponentDefinition("simpleRemoteEjb"); - assertTrue(component instanceof BeanComponentDefinition); + boolean condition = component instanceof BeanComponentDefinition; + assertThat(condition).isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerTests.java b/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerTests.java index 4256ab427a2..093051cd1d6 100644 --- a/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerTests.java @@ -30,9 +30,7 @@ import org.springframework.ejb.access.SimpleRemoteStatelessSessionProxyFactoryBe import org.springframework.jndi.JndiObjectFactoryBean; import org.springframework.tests.sample.beans.ITestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -57,7 +55,7 @@ public class JeeNamespaceHandlerTests { @Test public void testSimpleDefinition() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getMergedBeanDefinition("simple"); - assertEquals(JndiObjectFactoryBean.class.getName(), beanDefinition.getBeanClassName()); + assertThat(beanDefinition.getBeanClassName()).isEqualTo(JndiObjectFactoryBean.class.getName()); assertPropertyValue(beanDefinition, "jndiName", "jdbc/MyDataSource"); assertPropertyValue(beanDefinition, "resourceRef", "true"); } @@ -65,7 +63,7 @@ public class JeeNamespaceHandlerTests { @Test public void testComplexDefinition() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getMergedBeanDefinition("complex"); - assertEquals(JndiObjectFactoryBean.class.getName(), beanDefinition.getBeanClassName()); + assertThat(beanDefinition.getBeanClassName()).isEqualTo(JndiObjectFactoryBean.class.getName()); assertPropertyValue(beanDefinition, "jndiName", "jdbc/MyDataSource"); assertPropertyValue(beanDefinition, "resourceRef", "true"); assertPropertyValue(beanDefinition, "cache", "true"); @@ -87,13 +85,13 @@ public class JeeNamespaceHandlerTests { public void testWithReferencedEnvironment() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getMergedBeanDefinition("withReferencedEnvironment"); assertPropertyValue(beanDefinition, "jndiEnvironment", new RuntimeBeanReference("myEnvironment")); - assertFalse(beanDefinition.getPropertyValues().contains("environmentRef")); + assertThat(beanDefinition.getPropertyValues().contains("environmentRef")).isFalse(); } @Test public void testSimpleLocalSlsb() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getMergedBeanDefinition("simpleLocalEjb"); - assertEquals(LocalStatelessSessionProxyFactoryBean.class.getName(), beanDefinition.getBeanClassName()); + assertThat(beanDefinition.getBeanClassName()).isEqualTo(LocalStatelessSessionProxyFactoryBean.class.getName()); assertPropertyValue(beanDefinition, "businessInterface", ITestBean.class.getName()); assertPropertyValue(beanDefinition, "jndiName", "ejb/MyLocalBean"); } @@ -101,7 +99,7 @@ public class JeeNamespaceHandlerTests { @Test public void testSimpleRemoteSlsb() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getMergedBeanDefinition("simpleRemoteEjb"); - assertEquals(SimpleRemoteStatelessSessionProxyFactoryBean.class.getName(), beanDefinition.getBeanClassName()); + assertThat(beanDefinition.getBeanClassName()).isEqualTo(SimpleRemoteStatelessSessionProxyFactoryBean.class.getName()); assertPropertyValue(beanDefinition, "businessInterface", ITestBean.class.getName()); assertPropertyValue(beanDefinition, "jndiName", "ejb/MyRemoteBean"); } @@ -109,7 +107,7 @@ public class JeeNamespaceHandlerTests { @Test public void testComplexLocalSlsb() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getMergedBeanDefinition("complexLocalEjb"); - assertEquals(LocalStatelessSessionProxyFactoryBean.class.getName(), beanDefinition.getBeanClassName()); + assertThat(beanDefinition.getBeanClassName()).isEqualTo(LocalStatelessSessionProxyFactoryBean.class.getName()); assertPropertyValue(beanDefinition, "businessInterface", ITestBean.class.getName()); assertPropertyValue(beanDefinition, "jndiName", "ejb/MyLocalBean"); assertPropertyValue(beanDefinition, "cacheHome", "true"); @@ -121,7 +119,7 @@ public class JeeNamespaceHandlerTests { @Test public void testComplexRemoteSlsb() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getMergedBeanDefinition("complexRemoteEjb"); - assertEquals(SimpleRemoteStatelessSessionProxyFactoryBean.class.getName(), beanDefinition.getBeanClassName()); + assertThat(beanDefinition.getBeanClassName()).isEqualTo(SimpleRemoteStatelessSessionProxyFactoryBean.class.getName()); assertPropertyValue(beanDefinition, "businessInterface", ITestBean.class.getName()); assertPropertyValue(beanDefinition, "jndiName", "ejb/MyRemoteBean"); assertPropertyValue(beanDefinition, "cacheHome", "true"); @@ -136,16 +134,15 @@ public class JeeNamespaceHandlerTests { @Test public void testLazyInitJndiLookup() throws Exception { BeanDefinition definition = this.beanFactory.getMergedBeanDefinition("lazyDataSource"); - assertTrue(definition.isLazyInit()); + assertThat(definition.isLazyInit()).isTrue(); definition = this.beanFactory.getMergedBeanDefinition("lazyLocalBean"); - assertTrue(definition.isLazyInit()); + assertThat(definition.isLazyInit()).isTrue(); definition = this.beanFactory.getMergedBeanDefinition("lazyRemoteBean"); - assertTrue(definition.isLazyInit()); + assertThat(definition.isLazyInit()).isTrue(); } private void assertPropertyValue(BeanDefinition beanDefinition, String propertyName, Object expectedValue) { - assertEquals("Property '" + propertyName + "' incorrect", - expectedValue, beanDefinition.getPropertyValues().getPropertyValue(propertyName).getValue()); + assertThat(beanDefinition.getPropertyValues().getPropertyValue(propertyName).getValue()).as("Property '" + propertyName + "' incorrect").isEqualTo(expectedValue); } } diff --git a/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java index 8e75001da57..6535b9efdbc 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java @@ -37,8 +37,6 @@ import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.DataBinder; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * @author Phillip Webb @@ -81,8 +79,8 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("millis", "1256961600"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("1256961600", binder.getBindingResult().getFieldValue("millis")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("millis")).isEqualTo("1256961600"); } @Test @@ -90,8 +88,8 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("millisAnnotated", "10/31/09"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09", binder.getBindingResult().getFieldValue("millisAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("millisAnnotated")).isEqualTo("10/31/09"); } @Test @@ -99,8 +97,8 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("calendarAnnotated", "10/31/09"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09", binder.getBindingResult().getFieldValue("calendarAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("calendarAnnotated")).isEqualTo("10/31/09"); } @Test @@ -108,8 +106,8 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateAnnotated", "10/31/09"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09", binder.getBindingResult().getFieldValue("dateAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("dateAnnotated")).isEqualTo("10/31/09"); } @Test @@ -117,7 +115,7 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateAnnotated", new String[]{"10/31/09 12:00 PM"}); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); } @Test @@ -125,8 +123,8 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateAnnotated", "Oct X31, 2009"); binder.bind(propertyValues); - assertEquals(1, binder.getBindingResult().getFieldErrorCount("dateAnnotated")); - assertEquals("Oct X31, 2009", binder.getBindingResult().getFieldValue("dateAnnotated")); + assertThat(binder.getBindingResult().getFieldErrorCount("dateAnnotated")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("dateAnnotated")).isEqualTo("Oct X31, 2009"); } @Test @@ -136,8 +134,8 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateAnnotated", "Oct 031, 2009"); binder.bind(propertyValues); - assertEquals(1, binder.getBindingResult().getFieldErrorCount("dateAnnotated")); - assertEquals("Oct 031, 2009", binder.getBindingResult().getFieldValue("dateAnnotated")); + assertThat(binder.getBindingResult().getFieldErrorCount("dateAnnotated")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("dateAnnotated")).isEqualTo("Oct 031, 2009"); } @Test @@ -145,8 +143,8 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateAnnotatedPattern", "10/31/09 1:05"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09 1:05", binder.getBindingResult().getFieldValue("dateAnnotatedPattern")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("dateAnnotatedPattern")).isEqualTo("10/31/09 1:05"); } @Test @@ -154,7 +152,7 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateAnnotatedPattern", "02/29/09 12:00 PM"); binder.bind(propertyValues); - assertEquals(1, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(1); } @Test @@ -162,8 +160,8 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("isoDate", "2009-10-31"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("2009-10-31", binder.getBindingResult().getFieldValue("isoDate")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("isoDate")).isEqualTo("2009-10-31"); } @Test @@ -171,8 +169,8 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("isoTime", "12:00:00.000-05:00"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("17:00:00.000Z", binder.getBindingResult().getFieldValue("isoTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("isoTime")).isEqualTo("17:00:00.000Z"); } @Test @@ -180,8 +178,8 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("isoDateTime", "2009-10-31T12:00:00.000-08:00"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("2009-10-31T20:00:00.000Z", binder.getBindingResult().getFieldValue("isoDateTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("isoDateTime")).isEqualTo("2009-10-31T20:00:00.000Z"); } @Test @@ -189,8 +187,8 @@ public class DateFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("children[0].dateAnnotated", "10/31/09"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09", binder.getBindingResult().getFieldValue("children[0].dateAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("children[0].dateAnnotated")).isEqualTo("10/31/09"); } @Test @@ -198,7 +196,7 @@ public class DateFormattingTests { Date date = new Date(); Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class)); String expected = date.toString(); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -209,7 +207,7 @@ public class DateFormattingTests { Date date = new Date(); Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class)); String expected = new DateFormatter().print(date, Locale.US); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test // SPR-10105 @@ -230,7 +228,7 @@ public class DateFormattingTests { // This is a format that cannot be parsed by new Date(String) String string = "2009-06-01T14:23:05.003+00:00"; Date date = this.conversionService.convert(string, Date.class); - assertNotNull(date); + assertThat(date).isNotNull(); } diff --git a/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryBeanTests.java index 37660758938..b26cc5f7993 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryBeanTests.java @@ -41,7 +41,6 @@ public class DateTimeFormatterFactoryBeanTests { } @Test - @SuppressWarnings("rawtypes") public void getObjectType() { assertThat(factory.getObjectType()).isEqualTo(DateTimeFormatter.class); } diff --git a/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryTests.java b/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryTests.java index da2f14c4936..457711e7f6a 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryTests.java @@ -28,7 +28,6 @@ import org.junit.Test; import org.springframework.format.annotation.DateTimeFormat.ISO; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; /** * @author Phillip Webb @@ -78,8 +77,8 @@ public class DateTimeFormatterFactoryTests { public void createDateTimeFormatterInOrderOfPropertyPriority() { factory.setStyle("SS"); String value = applyLocale(factory.createDateTimeFormatter()).print(dateTime); - assertTrue(value.startsWith("10/21/09")); - assertTrue(value.endsWith("12:10 PM")); + assertThat(value.startsWith("10/21/09")).isTrue(); + assertThat(value.endsWith("12:10 PM")).isTrue(); factory.setIso(ISO.DATE); assertThat(applyLocale(factory.createDateTimeFormatter()).print(dateTime)).isEqualTo("2009-10-21"); diff --git a/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java index 3804e53b04e..254d6d0f231 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java @@ -47,9 +47,6 @@ import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.DataBinder; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * @author Keith Donald @@ -105,8 +102,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDate", "10/31/09"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09", binder.getBindingResult().getFieldValue("localDate")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localDate")).isEqualTo("10/31/09"); } @Test @@ -117,8 +114,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDate", "October 31, 2009"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("October 31, 2009", binder.getBindingResult().getFieldValue("localDate")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localDate")).isEqualTo("October 31, 2009"); } @Test @@ -129,8 +126,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDate", "20091031"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("20091031", binder.getBindingResult().getFieldValue("localDate")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localDate")).isEqualTo("20091031"); } @Test @@ -138,7 +135,7 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDate", new String[]{"10/31/09"}); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); } @Test @@ -146,8 +143,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateAnnotated", "Oct 31, 2009"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("Oct 31, 2009", binder.getBindingResult().getFieldValue("localDateAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct 31, 2009"); } @Test @@ -155,8 +152,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateAnnotated", "Oct 031, 2009"); binder.bind(propertyValues); - assertEquals(1, binder.getBindingResult().getFieldErrorCount("localDateAnnotated")); - assertEquals("Oct 031, 2009", binder.getBindingResult().getFieldValue("localDateAnnotated")); + assertThat(binder.getBindingResult().getFieldErrorCount("localDateAnnotated")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct 031, 2009"); } @Test @@ -164,8 +161,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("children[0].localDateAnnotated", "Oct 31, 2009"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("Oct 31, 2009", binder.getBindingResult().getFieldValue("children[0].localDateAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("children[0].localDateAnnotated")).isEqualTo("Oct 31, 2009"); } @Test @@ -174,8 +171,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateAnnotated", "Oct 31, 2009"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("Oct 31, 2009", binder.getBindingResult().getFieldValue("localDateAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct 31, 2009"); } @Test @@ -184,8 +181,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateAnnotated", "Oct 031, 2009"); binder.bind(propertyValues); - assertEquals(1, binder.getBindingResult().getFieldErrorCount("localDateAnnotated")); - assertEquals("Oct 031, 2009", binder.getBindingResult().getFieldValue("localDateAnnotated")); + assertThat(binder.getBindingResult().getFieldErrorCount("localDateAnnotated")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct 031, 2009"); } @Test @@ -193,8 +190,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localTime", "12:00 PM"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("12:00 PM", binder.getBindingResult().getFieldValue("localTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localTime")).isEqualTo("12:00 PM"); } @Test @@ -205,8 +202,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localTime", "12:00:00 PM"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("12:00:00 PM", binder.getBindingResult().getFieldValue("localTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localTime")).isEqualTo("12:00:00 PM"); } @Test @@ -217,8 +214,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localTime", "130000"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("130000", binder.getBindingResult().getFieldValue("localTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localTime")).isEqualTo("130000"); } @Test @@ -226,8 +223,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localTimeAnnotated", "12:00:00 PM"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("12:00:00 PM", binder.getBindingResult().getFieldValue("localTimeAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localTimeAnnotated")).isEqualTo("12:00:00 PM"); } @Test @@ -235,10 +232,10 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateTime", new LocalDateTime(2009, 10, 31, 12, 0)); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); String value = binder.getBindingResult().getFieldValue("localDateTime").toString(); - assertTrue(value.startsWith("10/31/09")); - assertTrue(value.endsWith("12:00 PM")); + assertThat(value.startsWith("10/31/09")).isTrue(); + assertThat(value.endsWith("12:00 PM")).isTrue(); } @Test @@ -246,10 +243,10 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateTimeAnnotated", new LocalDateTime(2009, 10, 31, 12, 0)); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); String value = binder.getBindingResult().getFieldValue("localDateTimeAnnotated").toString(); - assertTrue(value.startsWith("Oct 31, 2009")); - assertTrue(value.endsWith("12:00 PM")); + assertThat(value.startsWith("Oct 31, 2009")).isTrue(); + assertThat(value.endsWith("12:00 PM")).isTrue(); } @Test @@ -257,9 +254,9 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateTime", new DateTime(2009, 10, 31, 12, 0, ISOChronology.getInstanceUTC())); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); String value = binder.getBindingResult().getFieldValue("dateTime").toString(); - assertTrue(value.startsWith("10/31/09")); + assertThat(value.startsWith("10/31/09")).isTrue(); } @Test @@ -270,10 +267,10 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateTime", new LocalDateTime(2009, 10, 31, 12, 0)); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); String value = binder.getBindingResult().getFieldValue("localDateTime").toString(); - assertTrue(value.startsWith("Oct 31, 2009")); - assertTrue(value.endsWith("12:00:00 PM")); + assertThat(value.startsWith("Oct 31, 2009")).isTrue(); + assertThat(value.endsWith("12:00:00 PM")).isTrue(); } @Test @@ -284,8 +281,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateTime", "2009-10-31T12:00:00.000Z"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("2009-10-31T07:00:00.000-05:00", binder.getBindingResult().getFieldValue("dateTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("dateTime")).isEqualTo("2009-10-31T07:00:00.000-05:00"); } @Test @@ -296,8 +293,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateTime", "20091031130000"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("20091031130000", binder.getBindingResult().getFieldValue("dateTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("dateTime")).isEqualTo("20091031130000"); } @Test @@ -305,9 +302,9 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateTimeAnnotated", new DateTime(2009, 10, 31, 12, 0, ISOChronology.getInstanceUTC())); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); String value = binder.getBindingResult().getFieldValue("dateTimeAnnotated").toString(); - assertTrue(value.startsWith("Oct 31, 2009")); + assertThat(value.startsWith("Oct 31, 2009")).isTrue(); } @Test @@ -315,8 +312,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateTimeAnnotatedPattern", "10/31/09 12:00 PM"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09 12:00 PM", binder.getBindingResult().getFieldValue("dateTimeAnnotatedPattern")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("dateTimeAnnotatedPattern")).isEqualTo("10/31/09 12:00 PM"); } @Test @@ -324,7 +321,7 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateTimeAnnotatedPattern", "02/29/09 12:00 PM"); binder.bind(propertyValues); - assertEquals(1, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(1); } @Test @@ -332,9 +329,9 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateTimeAnnotatedDefault", new DateTime(2009, 10, 31, 12, 0, ISOChronology.getInstanceUTC())); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); String value = binder.getBindingResult().getFieldValue("dateTimeAnnotatedDefault").toString(); - assertTrue(value.startsWith("10/31/09")); + assertThat(value.startsWith("10/31/09")).isTrue(); } @Test @@ -342,8 +339,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("date", "Sat, 12 Aug 1995 13:30:00 GMT"); binder.bind(propertyValues); - assertEquals(1, binder.getBindingResult().getErrorCount()); - assertEquals("Sat, 12 Aug 1995 13:30:00 GMT", binder.getBindingResult().getFieldValue("date")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("date")).isEqualTo("Sat, 12 Aug 1995 13:30:00 GMT"); } @Test @@ -352,7 +349,7 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("date", "Sat, 12 Aug 1995 13:30:00 GMT"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); } @Test @@ -360,8 +357,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateAnnotated", "10/31/09"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09", binder.getBindingResult().getFieldValue("dateAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("dateAnnotated")).isEqualTo("10/31/09"); } @Test @@ -369,8 +366,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("calendarAnnotated", "10/31/09"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09", binder.getBindingResult().getFieldValue("calendarAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("calendarAnnotated")).isEqualTo("10/31/09"); } @Test @@ -378,8 +375,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("millis", "1256961600"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("1256961600", binder.getBindingResult().getFieldValue("millis")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("millis")).isEqualTo("1256961600"); } @Test @@ -387,8 +384,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("millisAnnotated", "10/31/09"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09", binder.getBindingResult().getFieldValue("millisAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("millisAnnotated")).isEqualTo("10/31/09"); } @Test @@ -396,8 +393,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("isoDate", "2009-10-31"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("2009-10-31", binder.getBindingResult().getFieldValue("isoDate")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("isoDate")).isEqualTo("2009-10-31"); } @Test @@ -405,8 +402,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("isoTime", "12:00:00.000-05:00"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("12:00:00.000", binder.getBindingResult().getFieldValue("isoTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("isoTime")).isEqualTo("12:00:00.000"); } @Test @@ -414,8 +411,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("isoDateTime", "2009-10-31T12:00:00.000Z"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("2009-10-31T07:00:00.000-05:00", binder.getBindingResult().getFieldValue("isoDateTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("isoDateTime")).isEqualTo("2009-10-31T07:00:00.000-05:00"); } @Test @@ -423,8 +420,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("instantAnnotated", "2009-10-31T12:00:00.000Z"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("2009-10-31T07:00:00.000-05:00", binder.getBindingResult().getFieldValue("instantAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("instantAnnotated")).isEqualTo("2009-10-31T07:00:00.000-05:00"); } @Test @@ -432,8 +429,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("mutableDateTimeAnnotated", "2009-10-31T12:00:00.000Z"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("2009-10-31T07:00:00.000-05:00", binder.getBindingResult().getFieldValue("mutableDateTimeAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("mutableDateTimeAnnotated")).isEqualTo("2009-10-31T07:00:00.000-05:00"); } @Test @@ -444,7 +441,7 @@ public class JodaTimeFormattingTests { Date date = new Date(); Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class)); String expected = JodaTimeContextHolder.getFormatter(org.joda.time.format.DateTimeFormat.shortDateTime(), Locale.US).print(new DateTime(date)); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test // SPR-10105 @@ -465,7 +462,7 @@ public class JodaTimeFormattingTests { // This is a format that cannot be parsed by new Date(String) String string = "2009-10-31T07:00:00.000-05:00"; Date date = this.conversionService.convert(string, Date.class); - assertNotNull(date); + assertThat(date).isNotNull(); } @Test @@ -473,8 +470,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("period", "P6Y3M1D"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("period").toString().equals("P6Y3M1D")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("period").toString().equals("P6Y3M1D")).isTrue(); } @Test @@ -482,8 +479,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("duration", "PT72.345S"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("duration").toString().equals("PT72.345S")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("duration").toString().equals("PT72.345S")).isTrue(); } @Test @@ -491,8 +488,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("yearMonth", "2007-12"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("yearMonth").toString().equals("2007-12")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("yearMonth").toString().equals("2007-12")).isTrue(); } @Test @@ -500,8 +497,8 @@ public class JodaTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("monthDay", "--12-03"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("monthDay").toString().equals("--12-03")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("monthDay").toString().equals("--12-03")).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormatterFactoryTests.java b/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormatterFactoryTests.java index 645fce3d62a..24038f085f6 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormatterFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormatterFactoryTests.java @@ -29,7 +29,6 @@ import org.junit.Test; import org.springframework.format.annotation.DateTimeFormat.ISO; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; /** * @author Phillip Webb @@ -79,8 +78,8 @@ public class DateTimeFormatterFactoryTests { public void createDateTimeFormatterInOrderOfPropertyPriority() { factory.setStylePattern("SS"); String value = applyLocale(factory.createDateTimeFormatter()).format(dateTime); - assertTrue(value.startsWith("10/21/09")); - assertTrue(value.endsWith("12:10 PM")); + assertThat(value.startsWith("10/21/09")).isTrue(); + assertThat(value.endsWith("12:10 PM")).isTrue(); factory.setIso(ISO.DATE); assertThat(applyLocale(factory.createDateTimeFormatter()).format(dateTime)).isEqualTo("2009-10-21"); diff --git a/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormattingTests.java index 219a687799b..29e7a5b75bd 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/standard/DateTimeFormattingTests.java @@ -48,8 +48,7 @@ import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.DataBinder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Keith Donald @@ -97,8 +96,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDate", "10/31/09"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09", binder.getBindingResult().getFieldValue("localDate")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localDate")).isEqualTo("10/31/09"); } @Test @@ -109,8 +108,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDate", "October 31, 2009"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("October 31, 2009", binder.getBindingResult().getFieldValue("localDate")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localDate")).isEqualTo("October 31, 2009"); } @Test @@ -121,8 +120,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDate", "20091031"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("20091031", binder.getBindingResult().getFieldValue("localDate")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localDate")).isEqualTo("20091031"); } @Test @@ -130,7 +129,7 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDate", new String[] {"10/31/09"}); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); } @Test @@ -138,8 +137,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateAnnotated", "Oct 31, 2009"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("Oct 31, 2009", binder.getBindingResult().getFieldValue("localDateAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct 31, 2009"); } @Test @@ -147,8 +146,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateAnnotated", "Oct -31, 2009"); binder.bind(propertyValues); - assertEquals(1, binder.getBindingResult().getFieldErrorCount("localDateAnnotated")); - assertEquals("Oct -31, 2009", binder.getBindingResult().getFieldValue("localDateAnnotated")); + assertThat(binder.getBindingResult().getFieldErrorCount("localDateAnnotated")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct -31, 2009"); } @Test @@ -156,8 +155,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("children[0].localDateAnnotated", "Oct 31, 2009"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("Oct 31, 2009", binder.getBindingResult().getFieldValue("children[0].localDateAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("children[0].localDateAnnotated")).isEqualTo("Oct 31, 2009"); } @Test @@ -166,8 +165,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateAnnotated", "Oct 31, 2009"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("Oct 31, 2009", binder.getBindingResult().getFieldValue("localDateAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct 31, 2009"); } @Test @@ -176,8 +175,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateAnnotated", "Oct -31, 2009"); binder.bind(propertyValues); - assertEquals(1, binder.getBindingResult().getFieldErrorCount("localDateAnnotated")); - assertEquals("Oct -31, 2009", binder.getBindingResult().getFieldValue("localDateAnnotated")); + assertThat(binder.getBindingResult().getFieldErrorCount("localDateAnnotated")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldValue("localDateAnnotated")).isEqualTo("Oct -31, 2009"); } @Test @@ -185,8 +184,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDate", new GregorianCalendar(2009, 9, 31, 0, 0)); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09", binder.getBindingResult().getFieldValue("localDate")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localDate")).isEqualTo("10/31/09"); } @Test @@ -194,8 +193,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localTime", "12:00 PM"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("12:00 PM", binder.getBindingResult().getFieldValue("localTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localTime")).isEqualTo("12:00 PM"); } @Test @@ -206,8 +205,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localTime", "12:00:00 PM"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("12:00:00 PM", binder.getBindingResult().getFieldValue("localTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localTime")).isEqualTo("12:00:00 PM"); } @Test @@ -218,8 +217,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localTime", "130000"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("130000", binder.getBindingResult().getFieldValue("localTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localTime")).isEqualTo("130000"); } @Test @@ -227,8 +226,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localTimeAnnotated", "12:00:00 PM"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("12:00:00 PM", binder.getBindingResult().getFieldValue("localTimeAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localTimeAnnotated")).isEqualTo("12:00:00 PM"); } @Test @@ -236,8 +235,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localTime", new GregorianCalendar(1970, 0, 0, 12, 0)); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("12:00 PM", binder.getBindingResult().getFieldValue("localTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("localTime")).isEqualTo("12:00 PM"); } @Test @@ -245,10 +244,10 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateTime", LocalDateTime.of(2009, 10, 31, 12, 0)); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); String value = binder.getBindingResult().getFieldValue("localDateTime").toString(); - assertTrue(value.startsWith("10/31/09")); - assertTrue(value.endsWith("12:00 PM")); + assertThat(value.startsWith("10/31/09")).isTrue(); + assertThat(value.endsWith("12:00 PM")).isTrue(); } @Test @@ -256,10 +255,10 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateTimeAnnotated", LocalDateTime.of(2009, 10, 31, 12, 0)); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); String value = binder.getBindingResult().getFieldValue("localDateTimeAnnotated").toString(); - assertTrue(value.startsWith("Oct 31, 2009")); - assertTrue(value.endsWith("12:00:00 PM")); + assertThat(value.startsWith("Oct 31, 2009")).isTrue(); + assertThat(value.endsWith("12:00:00 PM")).isTrue(); } @Test @@ -267,10 +266,10 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateTime", new GregorianCalendar(2009, 9, 31, 12, 0)); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); String value = binder.getBindingResult().getFieldValue("localDateTime").toString(); - assertTrue(value.startsWith("10/31/09")); - assertTrue(value.endsWith("12:00 PM")); + assertThat(value.startsWith("10/31/09")).isTrue(); + assertThat(value.endsWith("12:00 PM")).isTrue(); } @Test @@ -281,10 +280,10 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("localDateTime", LocalDateTime.of(2009, 10, 31, 12, 0)); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); String value = binder.getBindingResult().getFieldValue("localDateTime").toString(); - assertTrue(value.startsWith("Oct 31, 2009")); - assertTrue(value.endsWith("12:00:00 PM")); + assertThat(value.startsWith("Oct 31, 2009")).isTrue(); + assertThat(value.endsWith("12:00:00 PM")).isTrue(); } @Test @@ -292,8 +291,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateTimeAnnotatedPattern", "10/31/09 12:00 PM"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10/31/09 12:00 PM", binder.getBindingResult().getFieldValue("dateTimeAnnotatedPattern")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("dateTimeAnnotatedPattern")).isEqualTo("10/31/09 12:00 PM"); } @Test @@ -301,7 +300,7 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("dateTimeAnnotatedPattern", "02/29/09 12:00 PM"); binder.bind(propertyValues); - assertEquals(1, binder.getBindingResult().getErrorCount()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(1); } @Test @@ -309,8 +308,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("isoDate", "2009-10-31"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("2009-10-31", binder.getBindingResult().getFieldValue("isoDate")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("isoDate")).isEqualTo("2009-10-31"); } @Test @@ -318,8 +317,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("isoTime", "12:00:00"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("12:00:00", binder.getBindingResult().getFieldValue("isoTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("isoTime")).isEqualTo("12:00:00"); } @Test @@ -327,8 +326,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("isoTime", "12:00:00.000-05:00"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("12:00:00", binder.getBindingResult().getFieldValue("isoTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("isoTime")).isEqualTo("12:00:00"); } @Test @@ -336,8 +335,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("isoDateTime", "2009-10-31T12:00:00"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("2009-10-31T12:00:00", binder.getBindingResult().getFieldValue("isoDateTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("isoDateTime")).isEqualTo("2009-10-31T12:00:00"); } @Test @@ -345,8 +344,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("isoDateTime", "2009-10-31T12:00:00.000Z"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("2009-10-31T12:00:00", binder.getBindingResult().getFieldValue("isoDateTime")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("isoDateTime")).isEqualTo("2009-10-31T12:00:00"); } @Test @@ -354,8 +353,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("instant", "2009-10-31T12:00:00.000Z"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("instant").toString().startsWith("2009-10-31T12:00")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("instant").toString().startsWith("2009-10-31T12:00")).isTrue(); } @Test @@ -367,8 +366,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("instant", new Date(109, 9, 31, 12, 0)); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("instant").toString().startsWith("2009-10-31")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("instant").toString().startsWith("2009-10-31")).isTrue(); } finally { TimeZone.setDefault(defaultZone); @@ -380,8 +379,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("period", "P6Y3M1D"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("period").toString().equals("P6Y3M1D")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("period").toString().equals("P6Y3M1D")).isTrue(); } @Test @@ -389,8 +388,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("duration", "PT8H6M12.345S"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("duration").toString().equals("PT8H6M12.345S")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("duration").toString().equals("PT8H6M12.345S")).isTrue(); } @Test @@ -398,8 +397,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("year", "2007"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("year").toString().equals("2007")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("year").toString().equals("2007")).isTrue(); } @Test @@ -407,8 +406,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("month", "JULY"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("month").toString().equals("JULY")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("month").toString().equals("JULY")).isTrue(); } @Test @@ -416,8 +415,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("month", "July"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("month").toString().equals("JULY")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("month").toString().equals("JULY")).isTrue(); } @Test @@ -425,8 +424,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("yearMonth", "2007-12"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("yearMonth").toString().equals("2007-12")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("yearMonth").toString().equals("2007-12")).isTrue(); } @Test @@ -434,8 +433,8 @@ public class DateTimeFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("monthDay", "--12-03"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertTrue(binder.getBindingResult().getFieldValue("monthDay").toString().equals("--12-03")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("monthDay").toString().equals("--12-03")).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/format/number/CurrencyStyleFormatterTests.java b/spring-context/src/test/java/org/springframework/format/number/CurrencyStyleFormatterTests.java index 35f4825e103..464812afc39 100644 --- a/spring-context/src/test/java/org/springframework/format/number/CurrencyStyleFormatterTests.java +++ b/spring-context/src/test/java/org/springframework/format/number/CurrencyStyleFormatterTests.java @@ -23,8 +23,8 @@ import java.util.Locale; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Keith Donald @@ -36,12 +36,12 @@ public class CurrencyStyleFormatterTests { @Test public void formatValue() { - assertEquals("$23.00", formatter.print(new BigDecimal("23"), Locale.US)); + assertThat(formatter.print(new BigDecimal("23"), Locale.US)).isEqualTo("$23.00"); } @Test public void parseValue() throws ParseException { - assertEquals(new BigDecimal("23.56"), formatter.parse("$23.56", Locale.US)); + assertThat(formatter.parse("$23.56", Locale.US)).isEqualTo(new BigDecimal("23.56")); } @Test @@ -53,12 +53,12 @@ public class CurrencyStyleFormatterTests { @Test public void parseValueDefaultRoundDown() throws ParseException { this.formatter.setRoundingMode(RoundingMode.DOWN); - assertEquals(new BigDecimal("23.56"), formatter.parse("$23.567", Locale.US)); + assertThat(formatter.parse("$23.567", Locale.US)).isEqualTo(new BigDecimal("23.56")); } @Test public void parseWholeValue() throws ParseException { - assertEquals(new BigDecimal("23.00"), formatter.parse("$23", Locale.US)); + assertThat(formatter.parse("$23", Locale.US)).isEqualTo(new BigDecimal("23.00")); } @Test diff --git a/spring-context/src/test/java/org/springframework/format/number/NumberFormattingTests.java b/spring-context/src/test/java/org/springframework/format/number/NumberFormattingTests.java index 67160c5df4d..9c8a2ec7184 100644 --- a/spring-context/src/test/java/org/springframework/format/number/NumberFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/number/NumberFormattingTests.java @@ -33,7 +33,7 @@ import org.springframework.format.support.FormattingConversionService; import org.springframework.util.StringValueResolver; import org.springframework.validation.DataBinder; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Keith Donald @@ -78,8 +78,8 @@ public class NumberFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("numberDefault", "3,339.12"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("3,339", binder.getBindingResult().getFieldValue("numberDefault")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("numberDefault")).isEqualTo("3,339"); } @Test @@ -87,8 +87,8 @@ public class NumberFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("numberDefaultAnnotated", "3,339.12"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("3,339.12", binder.getBindingResult().getFieldValue("numberDefaultAnnotated")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("numberDefaultAnnotated")).isEqualTo("3,339.12"); } @Test @@ -96,8 +96,8 @@ public class NumberFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("currency", "$3,339.12"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("$3,339.12", binder.getBindingResult().getFieldValue("currency")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("currency")).isEqualTo("$3,339.12"); } @Test @@ -105,8 +105,8 @@ public class NumberFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("percent", "53%"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("53%", binder.getBindingResult().getFieldValue("percent")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("percent")).isEqualTo("53%"); } @Test @@ -114,8 +114,8 @@ public class NumberFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("pattern", "1,25.00"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("1,25.00", binder.getBindingResult().getFieldValue("pattern")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("pattern")).isEqualTo("1,25.00"); } @Test @@ -123,17 +123,17 @@ public class NumberFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("patternArray", new String[] { "1,25.00", "2,35.00" }); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("1,25.00", binder.getBindingResult().getFieldValue("patternArray[0]")); - assertEquals("2,35.00", binder.getBindingResult().getFieldValue("patternArray[1]")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("patternArray[0]")).isEqualTo("1,25.00"); + assertThat(binder.getBindingResult().getFieldValue("patternArray[1]")).isEqualTo("2,35.00"); propertyValues = new MutablePropertyValues(); propertyValues.add("patternArray[0]", "1,25.00"); propertyValues.add("patternArray[1]", "2,35.00"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("1,25.00", binder.getBindingResult().getFieldValue("patternArray[0]")); - assertEquals("2,35.00", binder.getBindingResult().getFieldValue("patternArray[1]")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("patternArray[0]")).isEqualTo("1,25.00"); + assertThat(binder.getBindingResult().getFieldValue("patternArray[1]")).isEqualTo("2,35.00"); } @Test @@ -141,17 +141,17 @@ public class NumberFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("patternList", new String[] { "1,25.00", "2,35.00" }); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("1,25.00", binder.getBindingResult().getFieldValue("patternList[0]")); - assertEquals("2,35.00", binder.getBindingResult().getFieldValue("patternList[1]")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("patternList[0]")).isEqualTo("1,25.00"); + assertThat(binder.getBindingResult().getFieldValue("patternList[1]")).isEqualTo("2,35.00"); propertyValues = new MutablePropertyValues(); propertyValues.add("patternList[0]", "1,25.00"); propertyValues.add("patternList[1]", "2,35.00"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("1,25.00", binder.getBindingResult().getFieldValue("patternList[0]")); - assertEquals("2,35.00", binder.getBindingResult().getFieldValue("patternList[1]")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("patternList[0]")).isEqualTo("1,25.00"); + assertThat(binder.getBindingResult().getFieldValue("patternList[1]")).isEqualTo("2,35.00"); } @Test @@ -160,9 +160,9 @@ public class NumberFormattingTests { propertyValues.add("patternList2[0]", "1,25.00"); propertyValues.add("patternList2[1]", "2,35.00"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("1,25.00", binder.getBindingResult().getFieldValue("patternList2[0]")); - assertEquals("2,35.00", binder.getBindingResult().getFieldValue("patternList2[1]")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("patternList2[0]")).isEqualTo("1,25.00"); + assertThat(binder.getBindingResult().getFieldValue("patternList2[1]")).isEqualTo("2,35.00"); } @Test @@ -171,8 +171,8 @@ public class NumberFormattingTests { propertyValues.add("patternList2[0]", "1,25.00"); propertyValues.add("patternList2[1]", "2,35.00"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("1,25.00,2,35.00", binder.getBindingResult().getFieldValue("patternList2")); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("patternList2")).isEqualTo("1,25.00,2,35.00"); } diff --git a/spring-context/src/test/java/org/springframework/format/number/NumberStyleFormatterTests.java b/spring-context/src/test/java/org/springframework/format/number/NumberStyleFormatterTests.java index 9981601d54a..49ac2b76ac2 100644 --- a/spring-context/src/test/java/org/springframework/format/number/NumberStyleFormatterTests.java +++ b/spring-context/src/test/java/org/springframework/format/number/NumberStyleFormatterTests.java @@ -22,8 +22,8 @@ import java.util.Locale; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Keith Donald @@ -35,12 +35,12 @@ public class NumberStyleFormatterTests { @Test public void formatValue() { - assertEquals("23.56", formatter.print(new BigDecimal("23.56"), Locale.US)); + assertThat(formatter.print(new BigDecimal("23.56"), Locale.US)).isEqualTo("23.56"); } @Test public void parseValue() throws ParseException { - assertEquals(new BigDecimal("23.56"), formatter.parse("23.56", Locale.US)); + assertThat(formatter.parse("23.56", Locale.US)).isEqualTo(new BigDecimal("23.56")); } @Test diff --git a/spring-context/src/test/java/org/springframework/format/number/PercentStyleFormatterTests.java b/spring-context/src/test/java/org/springframework/format/number/PercentStyleFormatterTests.java index 70eca26a3b6..c91679adbd4 100644 --- a/spring-context/src/test/java/org/springframework/format/number/PercentStyleFormatterTests.java +++ b/spring-context/src/test/java/org/springframework/format/number/PercentStyleFormatterTests.java @@ -22,8 +22,8 @@ import java.util.Locale; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Keith Donald @@ -35,12 +35,12 @@ public class PercentStyleFormatterTests { @Test public void formatValue() { - assertEquals("23%", formatter.print(new BigDecimal(".23"), Locale.US)); + assertThat(formatter.print(new BigDecimal(".23"), Locale.US)).isEqualTo("23%"); } @Test public void parseValue() throws ParseException { - assertEquals(new BigDecimal(".2356"), formatter.parse("23.56%", Locale.US)); + assertThat(formatter.parse("23.56%", Locale.US)).isEqualTo(new BigDecimal(".2356")); } @Test diff --git a/spring-context/src/test/java/org/springframework/format/number/money/MoneyFormattingTests.java b/spring-context/src/test/java/org/springframework/format/number/money/MoneyFormattingTests.java index c07cbf846e4..0890abc7ba9 100644 --- a/spring-context/src/test/java/org/springframework/format/number/money/MoneyFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/number/money/MoneyFormattingTests.java @@ -31,8 +31,7 @@ import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.DataBinder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -64,20 +63,20 @@ public class MoneyFormattingTests { propertyValues.add("amount", "USD 10.50"); propertyValues.add("unit", "USD"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("USD10.50", binder.getBindingResult().getFieldValue("amount")); - assertEquals("USD", binder.getBindingResult().getFieldValue("unit")); - assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); - assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("amount")).isEqualTo("USD10.50"); + assertThat(binder.getBindingResult().getFieldValue("unit")).isEqualTo("USD"); + assertThat(bean.getAmount().getNumber().doubleValue() == 10.5d).isTrue(); + assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); LocaleContextHolder.setLocale(Locale.CANADA); binder.bind(propertyValues); LocaleContextHolder.setLocale(Locale.US); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("USD10.50", binder.getBindingResult().getFieldValue("amount")); - assertEquals("USD", binder.getBindingResult().getFieldValue("unit")); - assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); - assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("amount")).isEqualTo("USD10.50"); + assertThat(binder.getBindingResult().getFieldValue("unit")).isEqualTo("USD"); + assertThat(bean.getAmount().getNumber().doubleValue() == 10.5d).isTrue(); + assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); } @Test @@ -89,18 +88,18 @@ public class MoneyFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("amount", "$10.50"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("$10.50", binder.getBindingResult().getFieldValue("amount")); - assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); - assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("amount")).isEqualTo("$10.50"); + assertThat(bean.getAmount().getNumber().doubleValue() == 10.5d).isTrue(); + assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); LocaleContextHolder.setLocale(Locale.CANADA); binder.bind(propertyValues); LocaleContextHolder.setLocale(Locale.US); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("$10.50", binder.getBindingResult().getFieldValue("amount")); - assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); - assertEquals("CAD", bean.getAmount().getCurrency().getCurrencyCode()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("amount")).isEqualTo("$10.50"); + assertThat(bean.getAmount().getNumber().doubleValue() == 10.5d).isTrue(); + assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("CAD"); } @Test @@ -112,10 +111,10 @@ public class MoneyFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("amount", "10.50"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10.5", binder.getBindingResult().getFieldValue("amount")); - assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); - assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("amount")).isEqualTo("10.5"); + assertThat(bean.getAmount().getNumber().doubleValue() == 10.5d).isTrue(); + assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); } @Test @@ -127,10 +126,10 @@ public class MoneyFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("amount", "10%"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("10%", binder.getBindingResult().getFieldValue("amount")); - assertTrue(bean.getAmount().getNumber().doubleValue() == 0.1d); - assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("amount")).isEqualTo("10%"); + assertThat(bean.getAmount().getNumber().doubleValue() == 0.1d).isTrue(); + assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); } @Test @@ -142,10 +141,10 @@ public class MoneyFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("amount", "010.500"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("010.500", binder.getBindingResult().getFieldValue("amount")); - assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); - assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("amount")).isEqualTo("010.500"); + assertThat(bean.getAmount().getNumber().doubleValue() == 10.5d).isTrue(); + assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); } @Test @@ -157,18 +156,18 @@ public class MoneyFormattingTests { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.add("amount", "USD 10.50"); binder.bind(propertyValues); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("USD 010.500", binder.getBindingResult().getFieldValue("amount")); - assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); - assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("amount")).isEqualTo("USD 010.500"); + assertThat(bean.getAmount().getNumber().doubleValue() == 10.5d).isTrue(); + assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); LocaleContextHolder.setLocale(Locale.CANADA); binder.bind(propertyValues); LocaleContextHolder.setLocale(Locale.US); - assertEquals(0, binder.getBindingResult().getErrorCount()); - assertEquals("USD 010.500", binder.getBindingResult().getFieldValue("amount")); - assertTrue(bean.getAmount().getNumber().doubleValue() == 10.5d); - assertEquals("USD", bean.getAmount().getCurrency().getCurrencyCode()); + assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); + assertThat(binder.getBindingResult().getFieldValue("amount")).isEqualTo("USD 010.500"); + assertThat(bean.getAmount().getNumber().doubleValue() == 10.5d).isTrue(); + assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); } diff --git a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java index 40d62e179d8..5fe063b0b3a 100644 --- a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java @@ -39,9 +39,9 @@ import org.springframework.format.Parser; import org.springframework.format.Printer; import org.springframework.format.annotation.NumberFormat; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @author Rossen Stoyanchev @@ -59,9 +59,9 @@ public class FormattingConversionServiceFactoryBeanTests { LocaleContextHolder.setLocale(Locale.GERMAN); try { Object value = fcs.convert("15,00", TypeDescriptor.valueOf(String.class), descriptor); - assertEquals(15.0, value); + assertThat(value).isEqualTo(15.0); value = fcs.convert(15.0, descriptor, TypeDescriptor.valueOf(String.class)); - assertEquals("15", value); + assertThat(value).isEqualTo("15"); } finally { LocaleContextHolder.resetLocaleContext(); @@ -92,14 +92,14 @@ public class FormattingConversionServiceFactoryBeanTests { FormattingConversionService fcs = factory.getObject(); TestBean testBean = fcs.convert("5", TestBean.class); - assertEquals(5, testBean.getSpecialInt()); - assertEquals("5", fcs.convert(testBean, String.class)); + assertThat(testBean.getSpecialInt()).isEqualTo(5); + assertThat(fcs.convert(testBean, String.class)).isEqualTo("5"); TypeDescriptor descriptor = new TypeDescriptor(TestBean.class.getDeclaredField("specialInt")); Object value = fcs.convert(":5", TypeDescriptor.valueOf(String.class), descriptor); - assertEquals(5, value); + assertThat(value).isEqualTo(5); value = fcs.convert(5, descriptor, TypeDescriptor.valueOf(String.class)); - assertEquals(":5", value); + assertThat(value).isEqualTo(":5"); } @Test @@ -112,8 +112,8 @@ public class FormattingConversionServiceFactoryBeanTests { FormattingConversionService fcs = factory.getObject(); TestBean testBean = fcs.convert("5", TestBean.class); - assertEquals(5, testBean.getSpecialInt()); - assertEquals("5", fcs.convert(testBean, String.class)); + assertThat(testBean.getSpecialInt()).isEqualTo(5); + assertThat(fcs.convert(testBean, String.class)).isEqualTo("5"); } @Test @@ -187,8 +187,8 @@ public class FormattingConversionServiceFactoryBeanTests { @Override public Printer getPrinter(SpecialInt annotation, Class fieldType) { - assertEquals("aliased", annotation.value()); - assertEquals("aliased", annotation.alias()); + assertThat(annotation.value()).isEqualTo("aliased"); + assertThat(annotation.alias()).isEqualTo("aliased"); return new Printer() { @Override public String print(Integer object, Locale locale) { @@ -199,8 +199,8 @@ public class FormattingConversionServiceFactoryBeanTests { @Override public Parser getParser(SpecialInt annotation, Class fieldType) { - assertEquals("aliased", annotation.value()); - assertEquals("aliased", annotation.alias()); + assertThat(annotation.value()).isEqualTo("aliased"); + assertThat(annotation.alias()).isEqualTo("aliased"); return new Parser() { @Override public Integer parse(String text, Locale locale) throws ParseException { diff --git a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java index 27b19bafbd1..b31b751ed87 100644 --- a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java +++ b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java @@ -55,9 +55,8 @@ import org.springframework.format.datetime.joda.JodaDateTimeFormatAnnotationForm import org.springframework.format.datetime.joda.ReadablePartialPrinter; import org.springframework.format.number.NumberStyleFormatter; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * @author Keith Donald @@ -87,9 +86,9 @@ public class FormattingConversionServiceTests { public void formatFieldForTypeWithFormatter() throws ParseException { formattingService.addFormatterForFieldType(Number.class, new NumberStyleFormatter()); String formatted = formattingService.convert(3, String.class); - assertEquals("3", formatted); + assertThat(formatted).isEqualTo("3"); Integer i = formattingService.convert("3", Integer.class); - assertEquals(new Integer(3), i); + assertThat(i).isEqualTo(new Integer(3)); } @Test @@ -103,9 +102,9 @@ public class FormattingConversionServiceTests { formattingService.addFormatterForFieldType(LocalDate.class, new ReadablePartialPrinter(DateTimeFormat .shortDate()), new DateTimeParser(DateTimeFormat.shortDate())); String formatted = formattingService.convert(new LocalDate(2009, 10, 31), String.class); - assertEquals("10/31/09", formatted); + assertThat(formatted).isEqualTo("10/31/09"); LocalDate date = formattingService.convert("10/31/09", LocalDate.class); - assertEquals(new LocalDate(2009, 10, 31), date); + assertThat(date).isEqualTo(new LocalDate(2009, 10, 31)); } @Test @@ -116,7 +115,7 @@ public class FormattingConversionServiceTests { ac.registerBeanDefinition("conversionService", new RootBeanDefinition(FormattingConversionServiceFactoryBean.class)); ac.refresh(); ValueBean valueBean = ac.getBean(ValueBean.class); - assertEquals(new LocalDate(2009, 10, 31), new LocalDate(valueBean.date)); + assertThat(new LocalDate(valueBean.date)).isEqualTo(new LocalDate(2009, 10, 31)); } @Test @@ -133,8 +132,8 @@ public class FormattingConversionServiceTests { System.setProperty("myNumber", "99.99%"); try { MetaValueBean valueBean = ac.getBean(MetaValueBean.class); - assertEquals(new LocalDate(2009, 10, 31), new LocalDate(valueBean.date)); - assertEquals(Double.valueOf(0.9999), valueBean.number); + assertThat(new LocalDate(valueBean.date)).isEqualTo(new LocalDate(2009, 10, 31)); + assertThat(valueBean.number).isEqualTo(Double.valueOf(0.9999)); } finally { System.clearProperty("myDate"); @@ -203,10 +202,10 @@ public class FormattingConversionServiceTests { String formatted = (String) formattingService.convert(new LocalDate(2009, 10, 31).toDateTimeAtCurrentTime() .toDate(), new TypeDescriptor(modelClass.getField("date")), TypeDescriptor.valueOf(String.class)); - assertEquals("10/31/09", formatted); + assertThat(formatted).isEqualTo("10/31/09"); LocalDate date = new LocalDate(formattingService.convert("10/31/09", TypeDescriptor.valueOf(String.class), new TypeDescriptor(modelClass.getField("date")))); - assertEquals(new LocalDate(2009, 10, 31), date); + assertThat(date).isEqualTo(new LocalDate(2009, 10, 31)); List dates = new ArrayList<>(); dates.add(new LocalDate(2009, 10, 31).toDateTimeAtCurrentTime().toDate()); @@ -214,12 +213,12 @@ public class FormattingConversionServiceTests { dates.add(new LocalDate(2009, 11, 2).toDateTimeAtCurrentTime().toDate()); formatted = (String) formattingService.convert(dates, new TypeDescriptor(modelClass.getField("dates")), TypeDescriptor.valueOf(String.class)); - assertEquals("10-31-09,11-1-09,11-2-09", formatted); + assertThat(formatted).isEqualTo("10-31-09,11-1-09,11-2-09"); dates = (List) formattingService.convert("10-31-09,11-1-09,11-2-09", TypeDescriptor.valueOf(String.class), new TypeDescriptor(modelClass.getField("dates"))); - assertEquals(new LocalDate(2009, 10, 31), new LocalDate(dates.get(0))); - assertEquals(new LocalDate(2009, 11, 1), new LocalDate(dates.get(1))); - assertEquals(new LocalDate(2009, 11, 2), new LocalDate(dates.get(2))); + assertThat(new LocalDate(dates.get(0))).isEqualTo(new LocalDate(2009, 10, 31)); + assertThat(new LocalDate(dates.get(1))).isEqualTo(new LocalDate(2009, 11, 1)); + assertThat(new LocalDate(dates.get(2))).isEqualTo(new LocalDate(2009, 11, 2)); Object model = modelClass.newInstance(); ConfigurablePropertyAccessor accessor = directFieldAccess ? PropertyAccessorFactory.forDirectFieldAccess(model) : @@ -227,43 +226,43 @@ public class FormattingConversionServiceTests { accessor.setConversionService(formattingService); accessor.setPropertyValue("dates", "10-31-09,11-1-09,11-2-09"); dates = (List) accessor.getPropertyValue("dates"); - assertEquals(new LocalDate(2009, 10, 31), new LocalDate(dates.get(0))); - assertEquals(new LocalDate(2009, 11, 1), new LocalDate(dates.get(1))); - assertEquals(new LocalDate(2009, 11, 2), new LocalDate(dates.get(2))); + assertThat(new LocalDate(dates.get(0))).isEqualTo(new LocalDate(2009, 10, 31)); + assertThat(new LocalDate(dates.get(1))).isEqualTo(new LocalDate(2009, 11, 1)); + assertThat(new LocalDate(dates.get(2))).isEqualTo(new LocalDate(2009, 11, 2)); if (!directFieldAccess) { accessor.setPropertyValue("dates[0]", "10-30-09"); accessor.setPropertyValue("dates[1]", "10-1-09"); accessor.setPropertyValue("dates[2]", "10-2-09"); dates = (List) accessor.getPropertyValue("dates"); - assertEquals(new LocalDate(2009, 10, 30), new LocalDate(dates.get(0))); - assertEquals(new LocalDate(2009, 10, 1), new LocalDate(dates.get(1))); - assertEquals(new LocalDate(2009, 10, 2), new LocalDate(dates.get(2))); + assertThat(new LocalDate(dates.get(0))).isEqualTo(new LocalDate(2009, 10, 30)); + assertThat(new LocalDate(dates.get(1))).isEqualTo(new LocalDate(2009, 10, 1)); + assertThat(new LocalDate(dates.get(2))).isEqualTo(new LocalDate(2009, 10, 2)); } } @Test public void printNull() throws ParseException { formattingService.addFormatterForFieldType(Number.class, new NumberStyleFormatter()); - assertEquals("", formattingService.convert(null, TypeDescriptor.valueOf(Integer.class), TypeDescriptor.valueOf(String.class))); + assertThat(formattingService.convert(null, TypeDescriptor.valueOf(Integer.class), TypeDescriptor.valueOf(String.class))).isEqualTo(""); } @Test public void parseNull() throws ParseException { formattingService.addFormatterForFieldType(Number.class, new NumberStyleFormatter()); - assertNull(formattingService - .convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))); + assertThat(formattingService + .convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))).isNull(); } @Test public void parseEmptyString() throws ParseException { formattingService.addFormatterForFieldType(Number.class, new NumberStyleFormatter()); - assertNull(formattingService.convert("", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))); + assertThat(formattingService.convert("", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))).isNull(); } @Test public void parseBlankString() throws ParseException { formattingService.addFormatterForFieldType(Number.class, new NumberStyleFormatter()); - assertNull(formattingService.convert(" ", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))); + assertThat(formattingService.convert(" ", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))).isNull(); } @Test @@ -282,19 +281,19 @@ public class FormattingConversionServiceTests { @Test public void printNullDefault() throws ParseException { - assertEquals(null, formattingService - .convert(null, TypeDescriptor.valueOf(Integer.class), TypeDescriptor.valueOf(String.class))); + assertThat(formattingService + .convert(null, TypeDescriptor.valueOf(Integer.class), TypeDescriptor.valueOf(String.class))).isEqualTo(null); } @Test public void parseNullDefault() throws ParseException { - assertNull(formattingService - .convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))); + assertThat(formattingService + .convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))).isNull(); } @Test public void parseEmptyStringDefault() throws ParseException { - assertNull(formattingService.convert("", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))); + assertThat(formattingService.convert("", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))).isNull(); } @Test @@ -302,7 +301,7 @@ public class FormattingConversionServiceTests { formattingService.addFormatterForFieldAnnotation(new JodaDateTimeFormatAnnotationFormatterFactory() { @Override public Printer getPrinter(org.springframework.format.annotation.DateTimeFormat annotation, Class fieldType) { - assertEquals(MyDate.class, fieldType); + assertThat(fieldType).isEqualTo(MyDate.class); return super.getPrinter(annotation, fieldType); } }); @@ -348,40 +347,40 @@ public class FormattingConversionServiceTests { @Test public void introspectedFormatter() throws ParseException { formattingService.addFormatter(new NumberStyleFormatter()); - assertNull(formattingService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))); + assertThat(formattingService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))).isNull(); } @Test public void proxiedFormatter() throws ParseException { Formatter formatter = new NumberStyleFormatter(); formattingService.addFormatter((Formatter) new ProxyFactory(formatter).getProxy()); - assertNull(formattingService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))); + assertThat(formattingService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))).isNull(); } @Test public void introspectedConverter() { formattingService.addConverter(new IntegerConverter()); - assertEquals(Integer.valueOf(1), formattingService.convert("1", Integer.class)); + assertThat(formattingService.convert("1", Integer.class)).isEqualTo(Integer.valueOf(1)); } @Test public void proxiedConverter() { Converter converter = new IntegerConverter(); formattingService.addConverter((Converter) new ProxyFactory(converter).getProxy()); - assertEquals(Integer.valueOf(1), formattingService.convert("1", Integer.class)); + assertThat(formattingService.convert("1", Integer.class)).isEqualTo(Integer.valueOf(1)); } @Test public void introspectedConverterFactory() { formattingService.addConverterFactory(new IntegerConverterFactory()); - assertEquals(Integer.valueOf(1), formattingService.convert("1", Integer.class)); + assertThat(formattingService.convert("1", Integer.class)).isEqualTo(Integer.valueOf(1)); } @Test public void proxiedConverterFactory() { ConverterFactory converterFactory = new IntegerConverterFactory(); formattingService.addConverterFactory((ConverterFactory) new ProxyFactory(converterFactory).getProxy()); - assertEquals(Integer.valueOf(1), formattingService.convert("1", Integer.class)); + assertThat(formattingService.convert("1", Integer.class)).isEqualTo(Integer.valueOf(1)); } diff --git a/spring-context/src/test/java/org/springframework/instrument/classloading/InstrumentableClassLoaderTests.java b/spring-context/src/test/java/org/springframework/instrument/classloading/InstrumentableClassLoaderTests.java index 14003fb4c37..26d9ce0b43d 100644 --- a/spring-context/src/test/java/org/springframework/instrument/classloading/InstrumentableClassLoaderTests.java +++ b/spring-context/src/test/java/org/springframework/instrument/classloading/InstrumentableClassLoaderTests.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.springframework.util.ClassUtils; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Costin Leau @@ -33,7 +33,7 @@ public class InstrumentableClassLoaderTests { public void testDefaultLoadTimeWeaver() { ClassLoader loader = new SimpleInstrumentableClassLoader(ClassUtils.getDefaultClassLoader()); ReflectiveLoadTimeWeaver handler = new ReflectiveLoadTimeWeaver(loader); - assertSame(loader, handler.getInstrumentableClassLoader()); + assertThat(handler.getInstrumentableClassLoader()).isSameAs(loader); } } diff --git a/spring-context/src/test/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaverTests.java b/spring-context/src/test/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaverTests.java index b4a91764dd3..4ed15afb7be 100644 --- a/spring-context/src/test/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaverTests.java +++ b/spring-context/src/test/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaverTests.java @@ -21,10 +21,9 @@ import java.security.ProtectionDomain; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Unit tests for the {@link ReflectiveLoadTimeWeaver} class. @@ -56,7 +55,7 @@ public class ReflectiveLoadTimeWeaverTests { return "CAFEDEAD".getBytes(); } }); - assertEquals(1, classLoader.getNumTimesGetThrowawayClassLoaderCalled()); + assertThat(classLoader.getNumTimesGetThrowawayClassLoaderCalled()).isEqualTo(1); } @Test @@ -69,7 +68,7 @@ public class ReflectiveLoadTimeWeaverTests { public void testGetThrowawayClassLoaderWithClassLoaderThatDoesNotExposeAGetThrowawayClassLoaderMethodYieldsFallbackClassLoader() { ReflectiveLoadTimeWeaver weaver = new ReflectiveLoadTimeWeaver(new JustAddTransformerClassLoader()); ClassLoader throwawayClassLoader = weaver.getThrowawayClassLoader(); - assertNotNull(throwawayClassLoader); + assertThat(throwawayClassLoader).isNotNull(); } @Test @@ -77,8 +76,8 @@ public class ReflectiveLoadTimeWeaverTests { TotallyCompliantClassLoader classLoader = new TotallyCompliantClassLoader(); ReflectiveLoadTimeWeaver weaver = new ReflectiveLoadTimeWeaver(classLoader); ClassLoader throwawayClassLoader = weaver.getThrowawayClassLoader(); - assertNotNull(throwawayClassLoader); - assertEquals(1, classLoader.getNumTimesGetThrowawayClassLoaderCalled()); + assertThat(throwawayClassLoader).isNotNull(); + assertThat(classLoader.getNumTimesGetThrowawayClassLoaderCalled()).isEqualTo(1); } diff --git a/spring-context/src/test/java/org/springframework/instrument/classloading/ResourceOverridingShadowingClassLoaderTests.java b/spring-context/src/test/java/org/springframework/instrument/classloading/ResourceOverridingShadowingClassLoaderTests.java index 3897810fc1c..3e31bb4bb6f 100644 --- a/spring-context/src/test/java/org/springframework/instrument/classloading/ResourceOverridingShadowingClassLoaderTests.java +++ b/spring-context/src/test/java/org/springframework/instrument/classloading/ResourceOverridingShadowingClassLoaderTests.java @@ -21,9 +21,7 @@ import java.util.Enumeration; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -41,42 +39,42 @@ public class ResourceOverridingShadowingClassLoaderTests { @Test public void testFindsExistingResourceWithGetResourceAndNoOverrides() { - assertNotNull(thisClassLoader.getResource(EXISTING_RESOURCE)); - assertNotNull(overridingLoader.getResource(EXISTING_RESOURCE)); + assertThat(thisClassLoader.getResource(EXISTING_RESOURCE)).isNotNull(); + assertThat(overridingLoader.getResource(EXISTING_RESOURCE)).isNotNull(); } @Test public void testDoesNotFindExistingResourceWithGetResourceAndNullOverride() { - assertNotNull(thisClassLoader.getResource(EXISTING_RESOURCE)); + assertThat(thisClassLoader.getResource(EXISTING_RESOURCE)).isNotNull(); overridingLoader.override(EXISTING_RESOURCE, null); - assertNull(overridingLoader.getResource(EXISTING_RESOURCE)); + assertThat(overridingLoader.getResource(EXISTING_RESOURCE)).isNull(); } @Test public void testFindsExistingResourceWithGetResourceAsStreamAndNoOverrides() { - assertNotNull(thisClassLoader.getResourceAsStream(EXISTING_RESOURCE)); - assertNotNull(overridingLoader.getResourceAsStream(EXISTING_RESOURCE)); + assertThat(thisClassLoader.getResourceAsStream(EXISTING_RESOURCE)).isNotNull(); + assertThat(overridingLoader.getResourceAsStream(EXISTING_RESOURCE)).isNotNull(); } @Test public void testDoesNotFindExistingResourceWithGetResourceAsStreamAndNullOverride() { - assertNotNull(thisClassLoader.getResourceAsStream(EXISTING_RESOURCE)); + assertThat(thisClassLoader.getResourceAsStream(EXISTING_RESOURCE)).isNotNull(); overridingLoader.override(EXISTING_RESOURCE, null); - assertNull(overridingLoader.getResourceAsStream(EXISTING_RESOURCE)); + assertThat(overridingLoader.getResourceAsStream(EXISTING_RESOURCE)).isNull(); } @Test public void testFindsExistingResourceWithGetResourcesAndNoOverrides() throws IOException { - assertNotNull(thisClassLoader.getResources(EXISTING_RESOURCE)); - assertNotNull(overridingLoader.getResources(EXISTING_RESOURCE)); - assertEquals(1, countElements(overridingLoader.getResources(EXISTING_RESOURCE))); + assertThat(thisClassLoader.getResources(EXISTING_RESOURCE)).isNotNull(); + assertThat(overridingLoader.getResources(EXISTING_RESOURCE)).isNotNull(); + assertThat(countElements(overridingLoader.getResources(EXISTING_RESOURCE))).isEqualTo(1); } @Test public void testDoesNotFindExistingResourceWithGetResourcesAndNullOverride() throws IOException { - assertNotNull(thisClassLoader.getResources(EXISTING_RESOURCE)); + assertThat(thisClassLoader.getResources(EXISTING_RESOURCE)).isNotNull(); overridingLoader.override(EXISTING_RESOURCE, null); - assertEquals(0, countElements(overridingLoader.getResources(EXISTING_RESOURCE))); + assertThat(countElements(overridingLoader.getResources(EXISTING_RESOURCE))).isEqualTo(0); } private int countElements(Enumeration e) { diff --git a/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java b/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java index 20612dcae07..ea4b0af3e93 100644 --- a/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java @@ -29,8 +29,7 @@ import org.springframework.context.support.GenericApplicationContext; import org.springframework.jmx.export.MBeanExporter; import org.springframework.util.MBeanTestUtils; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** *

If you run into the "Unsupported protocol: jmxmp" error, you will need to @@ -106,11 +105,11 @@ public abstract class AbstractMBeanServerTests { } protected void assertIsRegistered(String message, ObjectName objectName) { - assertTrue(message, getServer().isRegistered(objectName)); + assertThat(getServer().isRegistered(objectName)).as(message).isTrue(); } protected void assertIsNotRegistered(String message, ObjectName objectName) { - assertFalse(message, getServer().isRegistered(objectName)); + assertThat(getServer().isRegistered(objectName)).as(message).isFalse(); } } diff --git a/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java b/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java index 74ba772e17f..ab5c628fb10 100644 --- a/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java @@ -37,13 +37,10 @@ import org.springframework.jmx.export.MBeanExporter; import org.springframework.jmx.export.assembler.AbstractReflectiveMBeanInfoAssembler; import org.springframework.util.SocketUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIOException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; /** @@ -92,7 +89,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { public void testProxyClassIsDifferent() throws Exception { assumeTrue(runTests); IJmxTestBean proxy = getProxy(); - assertTrue("The proxy class should be different than the base class", (proxy.getClass() != IJmxTestBean.class)); + assertThat((proxy.getClass() != IJmxTestBean.class)).as("The proxy class should be different than the base class").isTrue(); } @Test @@ -101,8 +98,8 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { IJmxTestBean proxy1 = getProxy(); IJmxTestBean proxy2 = getProxy(); - assertNotSame("The proxies should NOT be the same", proxy1, proxy2); - assertSame("The proxy classes should be the same", proxy1.getClass(), proxy2.getClass()); + assertThat(proxy2).as("The proxies should NOT be the same").isNotSameAs(proxy1); + assertThat(proxy2.getClass()).as("The proxy classes should be the same").isSameAs(proxy1.getClass()); } @Test @@ -110,7 +107,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assumeTrue(runTests); IJmxTestBean proxy1 = getProxy(); int age = proxy1.getAge(); - assertEquals("The age should be 100", 100, age); + assertThat(age).as("The age should be 100").isEqualTo(100); } @Test @@ -118,7 +115,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assumeTrue(runTests); IJmxTestBean proxy = getProxy(); proxy.setName("Rob Harrop"); - assertEquals("The name of the bean should have been updated", "Rob Harrop", target.getName()); + assertThat(target.getName()).as("The name of the bean should have been updated").isEqualTo("Rob Harrop"); } @Test @@ -158,7 +155,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assumeTrue(runTests); IJmxTestBean proxy = getProxy(); long result = proxy.myOperation(); - assertEquals("The operation should return 1", 1, result); + assertThat(result).as("The operation should return 1").isEqualTo(1); } @Test @@ -166,7 +163,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assumeTrue(runTests); IJmxTestBean proxy = getProxy(); int result = proxy.add(1, 2); - assertEquals("The operation should return 3", 3, result); + assertThat(result).as("The operation should return 3").isEqualTo(3); } @Test @@ -208,8 +205,8 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { // should now be able to access data via the lazy proxy try { - assertEquals("Rob Harrop", bean.getName()); - assertEquals(100, bean.getAge()); + assertThat(bean.getName()).isEqualTo("Rob Harrop"); + assertThat(bean.getAge()).isEqualTo(100); } finally { connector.stop(); @@ -227,8 +224,8 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { // should now be able to access data via the lazy proxy try { - assertEquals("Rob Harrop", bean.getName()); - assertEquals(100, bean.getAge()); + assertThat(bean.getName()).isEqualTo("Rob Harrop"); + assertThat(bean.getAge()).isEqualTo(100); } finally { connector.stop(); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/CustomEditorConfigurerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/CustomEditorConfigurerTests.java index 0949658c4a2..5f4a71b7afa 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/CustomEditorConfigurerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/CustomEditorConfigurerTests.java @@ -25,7 +25,7 @@ import org.junit.Test; import org.springframework.jmx.AbstractJmxTests; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -47,16 +47,16 @@ public class CustomEditorConfigurerTests extends AbstractJmxTests { Date startJmx = (Date) getServer().getAttribute(oname, "StartDate"); Date endJmx = (Date) getServer().getAttribute(oname, "EndDate"); - assertEquals("startDate ", getStartDate(), startJmx); - assertEquals("endDate ", getEndDate(), endJmx); + assertThat(startJmx).as("startDate ").isEqualTo(getStartDate()); + assertThat(endJmx).as("endDate ").isEqualTo(getEndDate()); } @Test public void testGetDates() throws Exception { DateRange dr = (DateRange) getContext().getBean("dateRange"); - assertEquals("startDate ", getStartDate(), dr.getStartDate()); - assertEquals("endDate ", getEndDate(), dr.getEndDate()); + assertThat(dr.getStartDate()).as("startDate ").isEqualTo(getStartDate()); + assertThat(dr.getEndDate()).as("endDate ").isEqualTo(getEndDate()); } private Date getStartDate() throws ParseException { diff --git a/spring-context/src/test/java/org/springframework/jmx/export/LazyInitMBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/export/LazyInitMBeanTests.java index 8a71334a8b4..0b45b86871b 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/LazyInitMBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/LazyInitMBeanTests.java @@ -24,8 +24,7 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jmx.support.ObjectNameManager; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -36,13 +35,13 @@ public class LazyInitMBeanTests { @Test public void invokeOnLazyInitBean() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/lazyInit.xml"); - assertFalse(ctx.getBeanFactory().containsSingleton("testBean")); - assertFalse(ctx.getBeanFactory().containsSingleton("testBean2")); + assertThat(ctx.getBeanFactory().containsSingleton("testBean")).isFalse(); + assertThat(ctx.getBeanFactory().containsSingleton("testBean2")).isFalse(); try { MBeanServer server = (MBeanServer) ctx.getBean("server"); ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean2"); String name = (String) server.getAttribute(oname, "Name"); - assertEquals("Invalid name returned", "foo", name); + assertThat(name).as("Invalid name returned").isEqualTo("foo"); } finally { ctx.close(); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java index 2c6eca07e33..a970dadfef1 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java @@ -30,8 +30,8 @@ import org.springframework.jmx.JmxTestBean; import org.springframework.jmx.export.naming.ObjectNamingStrategy; import org.springframework.jmx.support.ObjectNameManager; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Rob Harrop @@ -51,7 +51,7 @@ public class MBeanExporterOperationsTests extends AbstractMBeanServerTests { exporter.registerManagedResource(bean, objectName); String name = (String) getServer().getAttribute(objectName, "Name"); - assertEquals("Incorrect name on MBean", name, bean.getName()); + assertThat(bean.getName()).as("Incorrect name on MBean").isEqualTo(name); } @Test @@ -65,7 +65,7 @@ public class MBeanExporterOperationsTests extends AbstractMBeanServerTests { exporter.registerManagedResource(bean, objectName); MBeanInfo infoFromServer = getServer().getMBeanInfo(objectName); - assertEquals(info, infoFromServer); + assertThat(infoFromServer).isEqualTo(info); } @Test @@ -120,7 +120,7 @@ public class MBeanExporterOperationsTests extends AbstractMBeanServerTests { } private void assertObjectNameMatchesTemplate(ObjectName objectNameTemplate, ObjectName registeredName) { - assertEquals("Domain is incorrect", objectNameTemplate.getDomain(), registeredName.getDomain()); + assertThat(registeredName.getDomain()).as("Domain is incorrect").isEqualTo(objectNameTemplate.getDomain()); } } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java index 8f8321ed59d..09e2954bab9 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java @@ -58,9 +58,6 @@ 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.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; /** * Integration tests for the {@link MBeanExporter} class. @@ -139,8 +136,8 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { try { start(exporter); Object name = server.getAttribute(ObjectNameManager.getInstance("spring:name=dynBean"), "Name"); - assertEquals("The name attribute is incorrect", "Rob Harrop", name); - assertFalse("Assembler should not have been invoked", asm.invoked); + assertThat(name).as("The name attribute is incorrect").isEqualTo("Rob Harrop"); + assertThat(asm.invoked).as("Assembler should not have been invoked").isFalse(); } finally { exporter.destroy(); @@ -154,11 +151,11 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { ctx.getBean("exporter"); MBeanServer server = ctx.getBean("server", MBeanServer.class); ObjectInstance instance = server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean=true")); - assertNotNull(instance); + assertThat(instance).isNotNull(); instance = server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean2=true")); - assertNotNull(instance); + assertThat(instance).isNotNull(); instance = server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean3=true")); - assertNotNull(instance); + assertThat(instance).isNotNull(); } finally { ctx.close(); @@ -172,7 +169,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { ctx.getBean("exporter"); MBeanServer server = ctx.getBean("server", MBeanServer.class); ObjectInstance instance = server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean=true")); - assertNotNull(instance); + assertThat(instance).isNotNull(); assertThatExceptionOfType(InstanceNotFoundException.class).isThrownBy(() -> server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean=false"))); @@ -190,14 +187,14 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { MBeanServer server = ctx.getBean("server", MBeanServer.class); ObjectName oname = ObjectNameManager.getInstance("spring:mbean=true"); - assertNotNull(server.getObjectInstance(oname)); + assertThat(server.getObjectInstance(oname)).isNotNull(); String name = (String) server.getAttribute(oname, "Name"); - assertEquals("Invalid name returned", "Rob Harrop", name); + assertThat(name).as("Invalid name returned").isEqualTo("Rob Harrop"); oname = ObjectNameManager.getInstance("spring:mbean=another"); - assertNotNull(server.getObjectInstance(oname)); + assertThat(server.getObjectInstance(oname)).isNotNull(); name = (String) server.getAttribute(oname, "Name"); - assertEquals("Invalid name returned", "Juergen Hoeller", name); + assertThat(name).as("Invalid name returned").isEqualTo("Juergen Hoeller"); } finally { ctx.close(); @@ -254,7 +251,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { ObjectName oname = ObjectName.getInstance(name); Object nameValue = server.getAttribute(oname, "Name"); - assertEquals("Rob Harrop", nameValue); + assertThat(nameValue).isEqualTo("Rob Harrop"); } @Test @@ -273,7 +270,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { start(exporter); ObjectInstance instance = server.getObjectInstance(objectName); - assertNotNull(instance); + assertThat(instance).isNotNull(); } @Test @@ -302,12 +299,12 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { start(exporter); ObjectInstance instance = server.getObjectInstance(objectName); - assertNotNull(instance); + assertThat(instance).isNotNull(); ObjectInstance instance2 = server.getObjectInstance(new ObjectName(objectName2)); - assertNotNull(instance2); + assertThat(instance2).isNotNull(); // should still be the first bean with name Rob Harrop - assertEquals("Rob Harrop", server.getAttribute(objectName, "Name")); + assertThat(server.getAttribute(objectName, "Name")).isEqualTo("Rob Harrop"); } @Test @@ -333,10 +330,10 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { start(exporter); ObjectInstance instance = server.getObjectInstance(objectName); - assertNotNull(instance); + assertThat(instance).isNotNull(); // should still be the new bean with name Sally Greenwood - assertEquals("Sally Greenwood", server.getAttribute(objectName, "Name")); + assertThat(server.getAttribute(objectName, "Name")).isEqualTo("Sally Greenwood"); } @Test @@ -362,11 +359,11 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { Object result = server.invoke(objectName, "add", new Object[] {new Integer(2), new Integer(3)}, new String[] { int.class.getName(), int.class.getName()}); - assertEquals("Incorrect result return from add", result, new Integer(5)); - assertEquals("Incorrect attribute value", name, server.getAttribute(objectName, "Name")); + assertThat(new Integer(5)).as("Incorrect result return from add").isEqualTo(result); + assertThat(server.getAttribute(objectName, "Name")).as("Incorrect attribute value").isEqualTo(name); server.setAttribute(objectName, new Attribute("Name", otherName)); - assertEquals("Incorrect updated name.", otherName, bean.getName()); + assertThat(bean.getName()).as("Incorrect updated name.").isEqualTo(otherName); } @Test @@ -542,8 +539,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { this.server.unregisterMBean(new ObjectName(OBJECT_NAME)); exporter.destroy(); - assertEquals("Listener should not have been invoked (MBean previously unregistered by external agent)", 0, - listener.getUnregistered().size()); + assertThat(listener.getUnregistered().size()).as("Listener should not have been invoked (MBean previously unregistered by external agent)").isEqualTo(0); } @Test // SPR-3302 @@ -685,10 +681,10 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { private void assertListener(MockMBeanExporterListener listener) throws MalformedObjectNameException { ObjectName desired = ObjectNameManager.getInstance(OBJECT_NAME); - assertEquals("Incorrect number of registrations", 1, listener.getRegistered().size()); - assertEquals("Incorrect number of unregistrations", 1, listener.getUnregistered().size()); - assertEquals("Incorrect ObjectName in register", desired, listener.getRegistered().get(0)); - assertEquals("Incorrect ObjectName in unregister", desired, listener.getUnregistered().get(0)); + assertThat(listener.getRegistered().size()).as("Incorrect number of registrations").isEqualTo(1); + assertThat(listener.getUnregistered().size()).as("Incorrect number of unregistrations").isEqualTo(1); + assertThat(listener.getRegistered().get(0)).as("Incorrect ObjectName in register").isEqualTo(desired); + assertThat(listener.getUnregistered().get(0)).as("Incorrect ObjectName in unregister").isEqualTo(desired); } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java index 486571d0f75..edd2c178d4d 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java @@ -35,8 +35,8 @@ import org.springframework.jmx.access.NotificationListenerRegistrar; import org.springframework.jmx.export.naming.SelfNaming; import org.springframework.jmx.support.ObjectNameManager; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @author Rob Harrop @@ -68,7 +68,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { // update the attribute String attributeName = "Name"; server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop")); - assertEquals("Listener not notified", 1, listener.getCount(attributeName)); + assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -94,7 +94,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { // update the attribute String attributeName = "Name"; server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop")); - assertEquals("Listener not notified", 1, listener.getCount(attributeName)); + assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1); } @Test @@ -124,8 +124,8 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { server.setAttribute(ObjectNameManager.getInstance("spring:name=Test"), new Attribute(attributeName, "Rob Harrop")); - assertEquals("Listener not notified", 1, listener.getCount(attributeName)); - assertEquals("Handback object not transmitted correctly", handback, listener.getLastHandback(attributeName)); + assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1); + assertThat(listener.getLastHandback(attributeName)).as("Handback object not transmitted correctly").isEqualTo(handback); } @Test @@ -151,7 +151,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { String attributeName = "Name"; server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop")); - assertEquals("Listener not notified", 1, listener.getCount(attributeName)); + assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1); } @SuppressWarnings("serial") @@ -193,8 +193,8 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { server.setAttribute(objectName, new Attribute(nameAttribute, "Rob Harrop")); server.setAttribute(objectName, new Attribute(ageAttribute, new Integer(90))); - assertEquals("Listener not notified for Name", 1, listener.getCount(nameAttribute)); - assertEquals("Listener incorrectly notified for Age", 0, listener.getCount(ageAttribute)); + assertThat(listener.getCount(nameAttribute)).as("Listener not notified for Name").isEqualTo(1); + assertThat(listener.getCount(ageAttribute)).as("Listener incorrectly notified for Age").isEqualTo(0); } @Test @@ -231,7 +231,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { assertIsRegistered("Should have registered MBean", objectName); server.setAttribute(objectName, new Attribute("Age", new Integer(77))); - assertEquals("Listener not notified", 1, listener.getCount("Age")); + assertThat(listener.getCount("Age")).as("Listener not notified").isEqualTo(1); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -262,7 +262,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { assertIsRegistered("Should have registered MBean", objectName); server.setAttribute(objectName, new Attribute("Age", new Integer(77))); - assertEquals("Listener not notified", 1, listener.getCount("Age")); + assertThat(listener.getCount("Age")).as("Listener not notified").isEqualTo(1); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -294,7 +294,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { assertIsRegistered("Should have registered MBean", objectName); server.setAttribute(objectName, new Attribute("Age", new Integer(77))); - assertEquals("Listener should have been notified exactly once", 1, listener.getCount("Age")); + assertThat(listener.getCount("Age")).as("Listener should have been notified exactly once").isEqualTo(1); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -326,7 +326,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { assertIsRegistered("Should have registered MBean", objectName); server.setAttribute(objectName, new Attribute("Age", new Integer(77))); - assertEquals("Listener should have been notified exactly once", 1, listener.getCount("Age")); + assertThat(listener.getCount("Age")).as("Listener should have been notified exactly once").isEqualTo(1); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -367,10 +367,10 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { assertIsRegistered("Should have registered MBean", objectName2); server.setAttribute(ObjectNameManager.getInstance(objectName1), new Attribute("Age", new Integer(77))); - assertEquals("Listener not notified for testBean1", 1, listener.getCount("Age")); + assertThat(listener.getCount("Age")).as("Listener not notified for testBean1").isEqualTo(1); server.setAttribute(ObjectNameManager.getInstance(objectName2), new Attribute("Age", new Integer(33))); - assertEquals("Listener not notified for testBean2", 2, listener.getCount("Age")); + assertThat(listener.getCount("Age")).as("Listener not notified for testBean2").isEqualTo(2); } @Test @@ -397,13 +397,13 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { // update the attribute String attributeName = "Name"; server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop")); - assertEquals("Listener not notified", 1, listener.getCount(attributeName)); + assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1); registrar.destroy(); // try to update the attribute again server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop")); - assertEquals("Listener notified after destruction", 1, listener.getCount(attributeName)); + assertThat(listener.getCount(attributeName)).as("Listener notified after destruction").isEqualTo(1); } @Test @@ -434,13 +434,13 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { // update the attribute String attributeName = "Name"; server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop")); - assertEquals("Listener not notified", 1, listener.getCount(attributeName)); + assertThat(listener.getCount(attributeName)).as("Listener not notified").isEqualTo(1); registrar.destroy(); // try to update the attribute again server.setAttribute(objectName, new Attribute(attributeName, "Rob Harrop")); - assertEquals("Listener notified after destruction", 1, listener.getCount(attributeName)); + assertThat(listener.getCount(attributeName)).as("Listener notified after destruction").isEqualTo(1); } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/NotificationPublisherTests.java b/spring-context/src/test/java/org/springframework/jmx/export/NotificationPublisherTests.java index 13102030b36..49334a42467 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/NotificationPublisherTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/NotificationPublisherTests.java @@ -40,9 +40,7 @@ import org.springframework.jmx.export.notification.NotificationPublisher; import org.springframework.jmx.export.notification.NotificationPublisherAware; import org.springframework.jmx.support.ObjectNameManager; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for the Spring JMX {@link NotificationPublisher} functionality. @@ -62,9 +60,9 @@ public class NotificationPublisherTests extends AbstractMBeanServerTests { null); MyNotificationPublisher publisher = (MyNotificationPublisher) ctx.getBean("publisher"); - assertNotNull("NotificationPublisher should not be null", publisher.getNotificationPublisher()); + assertThat(publisher.getNotificationPublisher()).as("NotificationPublisher should not be null").isNotNull(); publisher.sendNotification(); - assertEquals("Notification not sent", 1, listener.count); + assertThat(listener.count).as("Notification not sent").isEqualTo(1); } @Test @@ -77,9 +75,9 @@ public class NotificationPublisherTests extends AbstractMBeanServerTests { this.server.addNotificationListener(ObjectNameManager.getInstance("spring:type=Publisher2"), listener, null, null); - assertNotNull("NotificationPublisher should not be null", publisher.getNotificationPublisher()); + assertThat(publisher.getNotificationPublisher()).as("NotificationPublisher should not be null").isNotNull(); publisher.sendNotification(); - assertEquals("Notification not sent", 1, listener.count); + assertThat(listener.count).as("Notification not sent").isEqualTo(1); } @Test @@ -91,7 +89,7 @@ public class NotificationPublisherTests extends AbstractMBeanServerTests { MyNotificationPublisherMBean publisher = (MyNotificationPublisherMBean) ctx.getBean("publisherMBean"); publisher.sendNotification(); - assertEquals("Notification not sent", 1, listener.count); + assertThat(listener.count).as("Notification not sent").isEqualTo(1); } /* @@ -111,7 +109,7 @@ public class NotificationPublisherTests extends AbstractMBeanServerTests { public void testLazyInit() throws Exception { // start the MBeanExporter ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherLazyTests.xml"); - assertFalse("Should not have instantiated the bean yet", ctx.getBeanFactory().containsSingleton("publisher")); + assertThat(ctx.getBeanFactory().containsSingleton("publisher")).as("Should not have instantiated the bean yet").isFalse(); // need to touch the MBean proxy server.getAttribute(ObjectNameManager.getInstance("spring:type=Publisher"), "Name"); @@ -119,9 +117,9 @@ public class NotificationPublisherTests extends AbstractMBeanServerTests { null); MyNotificationPublisher publisher = (MyNotificationPublisher) ctx.getBean("publisher"); - assertNotNull("NotificationPublisher should not be null", publisher.getNotificationPublisher()); + assertThat(publisher.getNotificationPublisher()).as("NotificationPublisher should not be null").isNotNull(); publisher.sendNotification(); - assertEquals("Notification not sent", 1, listener.count); + assertThat(listener.count).as("Notification not sent").isEqualTo(1); } private static class CountingNotificationListener implements NotificationListener { diff --git a/spring-context/src/test/java/org/springframework/jmx/export/PropertyPlaceholderConfigurerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/PropertyPlaceholderConfigurerTests.java index 1b0929e875b..3e5aa271a2d 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/PropertyPlaceholderConfigurerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/PropertyPlaceholderConfigurerTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.jmx.AbstractJmxTests; import org.springframework.jmx.IJmxTestBean; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -40,8 +40,8 @@ public class PropertyPlaceholderConfigurerTests extends AbstractJmxTests { public void testPropertiesReplaced() { IJmxTestBean bean = (IJmxTestBean) getContext().getBean("testBean"); - assertEquals("Name is incorrect", "Rob Harrop", bean.getName()); - assertEquals("Age is incorrect", 100, bean.getAge()); + assertThat(bean.getName()).as("Name is incorrect").isEqualTo("Rob Harrop"); + assertThat(bean.getAge()).as("Age is incorrect").isEqualTo(100); } @Test @@ -50,8 +50,8 @@ public class PropertyPlaceholderConfigurerTests extends AbstractJmxTests { Object name = getServer().getAttribute(oname, "Name"); Integer age = (Integer) getServer().getAttribute(oname, "Age"); - assertEquals("Name is incorrect in JMX", "Rob Harrop", name); - assertEquals("Age is incorrect in JMX", 100, age.intValue()); + assertThat(name).as("Name is incorrect in JMX").isEqualTo("Rob Harrop"); + assertThat(age.intValue()).as("Age is incorrect in JMX").isEqualTo(100); } } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java index 1e547282a89..0f1a355359d 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java @@ -25,9 +25,7 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jmx.support.ObjectNameManager; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -42,9 +40,9 @@ public class AnnotationLazyInitMBeanTests { try { MBeanServer server = (MBeanServer) ctx.getBean("server"); ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4"); - assertNotNull(server.getObjectInstance(oname)); + assertThat(server.getObjectInstance(oname)).isNotNull(); String name = (String) server.getAttribute(oname, "Name"); - assertEquals("Invalid name returned", "TEST", name); + assertThat(name).as("Invalid name returned").isEqualTo("TEST"); } finally { ctx.close(); @@ -60,24 +58,24 @@ public class AnnotationLazyInitMBeanTests { MBeanServer server = (MBeanServer) ctx.getBean("server"); ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4"); - assertNotNull(server.getObjectInstance(oname)); + assertThat(server.getObjectInstance(oname)).isNotNull(); String name = (String) server.getAttribute(oname, "Name"); - assertEquals("Invalid name returned", "TEST", name); + assertThat(name).as("Invalid name returned").isEqualTo("TEST"); oname = ObjectNameManager.getInstance("bean:name=testBean5"); - assertNotNull(server.getObjectInstance(oname)); + assertThat(server.getObjectInstance(oname)).isNotNull(); name = (String) server.getAttribute(oname, "Name"); - assertEquals("Invalid name returned", "FACTORY", name); + assertThat(name).as("Invalid name returned").isEqualTo("FACTORY"); oname = ObjectNameManager.getInstance("spring:mbean=true"); - assertNotNull(server.getObjectInstance(oname)); + assertThat(server.getObjectInstance(oname)).isNotNull(); name = (String) server.getAttribute(oname, "Name"); - assertEquals("Invalid name returned", "Rob Harrop", name); + assertThat(name).as("Invalid name returned").isEqualTo("Rob Harrop"); oname = ObjectNameManager.getInstance("spring:mbean=another"); - assertNotNull(server.getObjectInstance(oname)); + assertThat(server.getObjectInstance(oname)).isNotNull(); name = (String) server.getAttribute(oname, "Name"); - assertEquals("Invalid name returned", "Juergen Hoeller", name); + assertThat(name).as("Invalid name returned").isEqualTo("Juergen Hoeller"); } finally { System.clearProperty("domain"); @@ -92,9 +90,9 @@ public class AnnotationLazyInitMBeanTests { try { MBeanServer server = (MBeanServer) ctx.getBean("server"); ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4"); - assertNotNull(server.getObjectInstance(oname)); + assertThat(server.getObjectInstance(oname)).isNotNull(); String name = (String) server.getAttribute(oname, "Name"); - assertNull(name); + assertThat(name).isNull(); } finally { ctx.close(); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationMetadataAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationMetadataAssemblerTests.java index 490bab9a778..34556d09f62 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationMetadataAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationMetadataAssemblerTests.java @@ -26,10 +26,7 @@ import org.springframework.jmx.IJmxTestBean; import org.springframework.jmx.export.assembler.AbstractMetadataAssemblerTests; import org.springframework.jmx.export.metadata.JmxAttributeSource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -44,45 +41,44 @@ public class AnnotationMetadataAssemblerTests extends AbstractMetadataAssemblerT public void testAttributeFromInterface() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute("Colour"); - assertTrue("The name attribute should be writable", attr.isWritable()); - assertTrue("The name attribute should be readable", attr.isReadable()); + assertThat(attr.isWritable()).as("The name attribute should be writable").isTrue(); + assertThat(attr.isReadable()).as("The name attribute should be readable").isTrue(); } @Test public void testOperationFromInterface() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanOperationInfo op = inf.getOperation("fromInterface"); - assertNotNull(op); + assertThat(op).isNotNull(); } @Test public void testOperationOnGetter() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanOperationInfo op = inf.getOperation("getExpensiveToCalculate"); - assertNotNull(op); + assertThat(op).isNotNull(); } @Test public void testRegistrationOnInterface() throws Exception { Object bean = getContext().getBean("testInterfaceBean"); ModelMBeanInfo inf = getAssembler().getMBeanInfo(bean, "bean:name=interfaceTestBean"); - assertNotNull(inf); - assertEquals("My Managed Bean", inf.getDescription()); + assertThat(inf).isNotNull(); + assertThat(inf.getDescription()).isEqualTo("My Managed Bean"); ModelMBeanOperationInfo op = inf.getOperation("foo"); - assertNotNull("foo operation not exposed", op); - assertEquals("invoke foo", op.getDescription()); + assertThat(op).as("foo operation not exposed").isNotNull(); + assertThat(op.getDescription()).isEqualTo("invoke foo"); - assertNull("doNotExpose operation should not be exposed", inf.getOperation("doNotExpose")); + assertThat(inf.getOperation("doNotExpose")).as("doNotExpose operation should not be exposed").isNull(); ModelMBeanAttributeInfo attr = inf.getAttribute("Bar"); - assertNotNull("bar attribute not exposed", attr); - assertEquals("Bar description", attr.getDescription()); + assertThat(attr).as("bar attribute not exposed").isNotNull(); + assertThat(attr.getDescription()).isEqualTo("Bar description"); ModelMBeanAttributeInfo attr2 = inf.getAttribute("CacheEntries"); - assertNotNull("cacheEntries attribute not exposed", attr2); - assertEquals("Metric Type should be COUNTER", "COUNTER", - attr2.getDescriptor().getFieldValue("metricType")); + assertThat(attr2).as("cacheEntries attribute not exposed").isNotNull(); + assertThat(attr2.getDescriptor().getFieldValue("metricType")).as("Metric Type should be COUNTER").isEqualTo("COUNTER"); } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/annotation/EnableMBeanExportConfigurationTests.java b/spring-context/src/test/java/org/springframework/jmx/export/annotation/EnableMBeanExportConfigurationTests.java index 781e64fbbf6..e68e411b394 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/annotation/EnableMBeanExportConfigurationTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/annotation/EnableMBeanExportConfigurationTests.java @@ -39,9 +39,8 @@ import org.springframework.jmx.support.ObjectNameManager; import org.springframework.jmx.support.RegistrationPolicy; import org.springframework.mock.env.MockEnvironment; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Tests for {@link EnableMBeanExport} and {@link MBeanExportConfiguration}. @@ -146,9 +145,9 @@ public class EnableMBeanExportConfigurationTests { private void validateMBeanAttribute(MBeanServer server, String objectName, String expected) throws Exception { ObjectName oname = ObjectNameManager.getInstance(objectName); - assertNotNull(server.getObjectInstance(oname)); + assertThat(server.getObjectInstance(oname)).isNotNull(); String name = (String) server.getAttribute(oname, "Name"); - assertEquals("Invalid name returned", expected, name); + assertThat(name).as("Invalid name returned").isEqualTo(expected); } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/annotation/JmxUtilsAnnotationTests.java b/spring-context/src/test/java/org/springframework/jmx/export/annotation/JmxUtilsAnnotationTests.java index 03c78bd7c98..b7f6135ac54 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/annotation/JmxUtilsAnnotationTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/annotation/JmxUtilsAnnotationTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.jmx.support.JmxUtils; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -32,12 +31,12 @@ public class JmxUtilsAnnotationTests { @Test public void notMXBean() throws Exception { - assertFalse("MXBean annotation not detected correctly", JmxUtils.isMBean(FooNotX.class)); + assertThat(JmxUtils.isMBean(FooNotX.class)).as("MXBean annotation not detected correctly").isFalse(); } @Test public void annotatedMXBean() throws Exception { - assertTrue("MXBean annotation not detected correctly", JmxUtils.isMBean(FooX.class)); + assertThat(JmxUtils.isMBean(FooX.class)).as("MXBean annotation not detected correctly").isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractAutodetectTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractAutodetectTests.java index a0252ee9143..b57362bcd75 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractAutodetectTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractAutodetectTests.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.springframework.jmx.JmxTestBean; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -32,7 +32,7 @@ public abstract class AbstractAutodetectTests { JmxTestBean bean = new JmxTestBean(); AutodetectCapableMBeanInfoAssembler assembler = getAssembler(); - assertTrue("The bean should be included", assembler.includeBean(bean.getClass(), "testBean")); + assertThat(assembler.includeBean(bean.getClass(), "testBean")).as("The bean should be included").isTrue(); } protected abstract AutodetectCapableMBeanInfoAssembler getAssembler(); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java index 20f14d5ffed..5d7caaf1487 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java @@ -34,8 +34,7 @@ import org.springframework.jmx.AbstractJmxTests; import org.springframework.jmx.IJmxTestBean; import org.springframework.jmx.support.ObjectNameManager; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -53,45 +52,40 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { public void testMBeanRegistration() throws Exception { // beans are registered at this point - just grab them from the server ObjectInstance instance = getObjectInstance(); - assertNotNull("Bean should not be null", instance); + assertThat(instance).as("Bean should not be null").isNotNull(); } @Test public void testRegisterOperations() throws Exception { IJmxTestBean bean = getBean(); - assertNotNull(bean); + assertThat(bean).isNotNull(); MBeanInfo inf = getMBeanInfo(); - assertEquals("Incorrect number of operations registered", - getExpectedOperationCount(), inf.getOperations().length); + assertThat(inf.getOperations().length).as("Incorrect number of operations registered").isEqualTo(getExpectedOperationCount()); } @Test public void testRegisterAttributes() throws Exception { IJmxTestBean bean = getBean(); - assertNotNull(bean); + assertThat(bean).isNotNull(); MBeanInfo inf = getMBeanInfo(); - assertEquals("Incorrect number of attributes registered", - getExpectedAttributeCount(), inf.getAttributes().length); + assertThat(inf.getAttributes().length).as("Incorrect number of attributes registered").isEqualTo(getExpectedAttributeCount()); } @Test public void testGetMBeanInfo() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); - assertNotNull("MBeanInfo should not be null", info); + assertThat(info).as("MBeanInfo should not be null").isNotNull(); } @Test public void testGetMBeanAttributeInfo() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); MBeanAttributeInfo[] inf = info.getAttributes(); - assertEquals("Invalid number of Attributes returned", - getExpectedAttributeCount(), inf.length); + assertThat(inf.length).as("Invalid number of Attributes returned").isEqualTo(getExpectedAttributeCount()); for (int x = 0; x < inf.length; x++) { - assertNotNull("MBeanAttributeInfo should not be null", inf[x]); - assertNotNull( - "Description for MBeanAttributeInfo should not be null", - inf[x].getDescription()); + assertThat(inf[x]).as("MBeanAttributeInfo should not be null").isNotNull(); + assertThat(inf[x].getDescription()).as("Description for MBeanAttributeInfo should not be null").isNotNull(); } } @@ -99,14 +93,11 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { public void testGetMBeanOperationInfo() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); MBeanOperationInfo[] inf = info.getOperations(); - assertEquals("Invalid number of Operations returned", - getExpectedOperationCount(), inf.length); + assertThat(inf.length).as("Invalid number of Operations returned").isEqualTo(getExpectedOperationCount()); for (int x = 0; x < inf.length; x++) { - assertNotNull("MBeanOperationInfo should not be null", inf[x]); - assertNotNull( - "Description for MBeanOperationInfo should not be null", - inf[x].getDescription()); + assertThat(inf[x]).as("MBeanOperationInfo should not be null").isNotNull(); + assertThat(inf[x].getDescription()).as("Description for MBeanOperationInfo should not be null").isNotNull(); } } @@ -114,8 +105,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { public void testDescriptionNotNull() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); - assertNotNull("The MBean description should not be null", - info.getDescription()); + assertThat(info.getDescription()).as("The MBean description should not be null").isNotNull(); } @Test @@ -123,7 +113,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { ObjectName objectName = ObjectNameManager.getInstance(getObjectName()); getServer().setAttribute(objectName, new Attribute(NAME_ATTRIBUTE, "Rob Harrop")); IJmxTestBean bean = (IJmxTestBean) getContext().getBean("testBean"); - assertEquals("Rob Harrop", bean.getName()); + assertThat(bean.getName()).isEqualTo("Rob Harrop"); } @Test @@ -131,7 +121,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { ObjectName objectName = ObjectNameManager.getInstance(getObjectName()); getBean().setName("John Smith"); Object val = getServer().getAttribute(objectName, NAME_ATTRIBUTE); - assertEquals("Incorrect result", "John Smith", val); + assertThat(val).as("Incorrect result").isEqualTo("John Smith"); } @Test @@ -139,7 +129,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { ObjectName objectName = ObjectNameManager.getInstance(getObjectName()); Object result = getServer().invoke(objectName, "add", new Object[] {new Integer(20), new Integer(30)}, new String[] {"int", "int"}); - assertEquals("Incorrect result", new Integer(50), result); + assertThat(result).as("Incorrect result").isEqualTo(new Integer(50)); } @Test @@ -148,14 +138,10 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { ModelMBeanAttributeInfo attr = info.getAttribute(NAME_ATTRIBUTE); Descriptor desc = attr.getDescriptor(); - assertNotNull("getMethod field should not be null", - desc.getFieldValue("getMethod")); - assertNotNull("setMethod field should not be null", - desc.getFieldValue("setMethod")); - assertEquals("getMethod field has incorrect value", "getName", - desc.getFieldValue("getMethod")); - assertEquals("setMethod field has incorrect value", "setName", - desc.getFieldValue("setMethod")); + assertThat(desc.getFieldValue("getMethod")).as("getMethod field should not be null").isNotNull(); + assertThat(desc.getFieldValue("setMethod")).as("setMethod field should not be null").isNotNull(); + assertThat(desc.getFieldValue("getMethod")).as("getMethod field has incorrect value").isEqualTo("getName"); + assertThat(desc.getFieldValue("setMethod")).as("setMethod field has incorrect value").isEqualTo("setName"); } @Test @@ -163,32 +149,28 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanOperationInfo get = info.getOperation("getName"); - assertNotNull("get operation should not be null", get); - assertEquals("get operation should have visibility of four", - get.getDescriptor().getFieldValue("visibility"), - new Integer(4)); - assertEquals("get operation should have role \"getter\"", "getter", get.getDescriptor().getFieldValue("role")); + assertThat(get).as("get operation should not be null").isNotNull(); + assertThat(new Integer(4)).as("get operation should have visibility of four").isEqualTo(get.getDescriptor().getFieldValue("visibility")); + assertThat(get.getDescriptor().getFieldValue("role")).as("get operation should have role \"getter\"").isEqualTo("getter"); ModelMBeanOperationInfo set = info.getOperation("setName"); - assertNotNull("set operation should not be null", set); - assertEquals("set operation should have visibility of four", - set.getDescriptor().getFieldValue("visibility"), - new Integer(4)); - assertEquals("set operation should have role \"setter\"", "setter", set.getDescriptor().getFieldValue("role")); + assertThat(set).as("set operation should not be null").isNotNull(); + assertThat(new Integer(4)).as("set operation should have visibility of four").isEqualTo(set.getDescriptor().getFieldValue("visibility")); + assertThat(set.getDescriptor().getFieldValue("role")).as("set operation should have role \"setter\"").isEqualTo("setter"); } @Test public void testNotificationMetadata() throws Exception { ModelMBeanInfo info = (ModelMBeanInfo) getMBeanInfo(); MBeanNotificationInfo[] notifications = info.getNotifications(); - assertEquals("Incorrect number of notifications", 1, notifications.length); - assertEquals("Incorrect notification name", "My Notification", notifications[0].getName()); + assertThat(notifications.length).as("Incorrect number of notifications").isEqualTo(1); + assertThat(notifications[0].getName()).as("Incorrect notification name").isEqualTo("My Notification"); String[] notifTypes = notifications[0].getNotifTypes(); - assertEquals("Incorrect number of notification types", 2, notifTypes.length); - assertEquals("Notification type.foo not found", "type.foo", notifTypes[0]); - assertEquals("Notification type.bar not found", "type.bar", notifTypes[1]); + assertThat(notifTypes.length).as("Incorrect number of notification types").isEqualTo(2); + assertThat(notifTypes[0]).as("Notification type.foo not found").isEqualTo("type.foo"); + assertThat(notifTypes[1]).as("Notification type.bar not found").isEqualTo("type.bar"); } protected ModelMBeanInfo getMBeanInfoFromAssembler() throws Exception { diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java index 950fdd45008..66863ee8339 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java @@ -35,11 +35,7 @@ import org.springframework.jmx.export.metadata.JmxAttributeSource; import org.springframework.jmx.support.ObjectNameManager; import org.springframework.tests.aop.interceptor.NopInterceptor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -54,24 +50,21 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble @Test public void testDescription() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); - assertEquals("The descriptions are not the same", "My Managed Bean", - info.getDescription()); + assertThat(info.getDescription()).as("The descriptions are not the same").isEqualTo("My Managed Bean"); } @Test public void testAttributeDescriptionOnSetter() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute(AGE_ATTRIBUTE); - assertEquals("The description for the age attribute is incorrect", - "The Age Attribute", attr.getDescription()); + assertThat(attr.getDescription()).as("The description for the age attribute is incorrect").isEqualTo("The Age Attribute"); } @Test public void testAttributeDescriptionOnGetter() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute(NAME_ATTRIBUTE); - assertEquals("The description for the name attribute is incorrect", - "The Name Attribute", attr.getDescription()); + assertThat(attr.getDescription()).as("The description for the name attribute is incorrect").isEqualTo("The Name Attribute"); } /** @@ -81,15 +74,15 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble public void testReadOnlyAttribute() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute(AGE_ATTRIBUTE); - assertFalse("The age attribute should not be writable", attr.isWritable()); + assertThat(attr.isWritable()).as("The age attribute should not be writable").isFalse(); } @Test public void testReadWriteAttribute() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute(NAME_ATTRIBUTE); - assertTrue("The name attribute should be writable", attr.isWritable()); - assertTrue("The name attribute should be readable", attr.isReadable()); + assertThat(attr.isWritable()).as("The name attribute should be writable").isTrue(); + assertThat(attr.isReadable()).as("The name attribute should be readable").isTrue(); } /** @@ -99,7 +92,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble public void testWithOnlySetter() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute("NickName"); - assertNotNull("Attribute should not be null", attr); + assertThat(attr).as("Attribute should not be null").isNotNull(); } /** @@ -109,7 +102,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble public void testWithOnlyGetter() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute("Superman"); - assertNotNull("Attribute should not be null", attr); + assertThat(attr).as("Attribute should not be null").isNotNull(); } @Test @@ -117,13 +110,13 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble ModelMBeanInfo info = getMBeanInfoFromAssembler(); Descriptor desc = info.getMBeanDescriptor(); - assertEquals("Logging should be set to true", "true", desc.getFieldValue("log")); - assertEquals("Log file should be jmx.log", "jmx.log", desc.getFieldValue("logFile")); - assertEquals("Currency Time Limit should be 15", "15", desc.getFieldValue("currencyTimeLimit")); - assertEquals("Persist Policy should be OnUpdate", "OnUpdate", desc.getFieldValue("persistPolicy")); - assertEquals("Persist Period should be 200", "200", desc.getFieldValue("persistPeriod")); - assertEquals("Persist Location should be foo", "./foo", desc.getFieldValue("persistLocation")); - assertEquals("Persist Name should be bar", "bar.jmx", desc.getFieldValue("persistName")); + assertThat(desc.getFieldValue("log")).as("Logging should be set to true").isEqualTo("true"); + assertThat(desc.getFieldValue("logFile")).as("Log file should be jmx.log").isEqualTo("jmx.log"); + assertThat(desc.getFieldValue("currencyTimeLimit")).as("Currency Time Limit should be 15").isEqualTo("15"); + assertThat(desc.getFieldValue("persistPolicy")).as("Persist Policy should be OnUpdate").isEqualTo("OnUpdate"); + assertThat(desc.getFieldValue("persistPeriod")).as("Persist Period should be 200").isEqualTo("200"); + assertThat(desc.getFieldValue("persistLocation")).as("Persist Location should be foo").isEqualTo("./foo"); + assertThat(desc.getFieldValue("persistName")).as("Persist Name should be bar").isEqualTo("bar.jmx"); } @Test @@ -131,10 +124,10 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble ModelMBeanInfo info = getMBeanInfoFromAssembler(); Descriptor desc = info.getAttribute(NAME_ATTRIBUTE).getDescriptor(); - assertEquals("Default value should be foo", "foo", desc.getFieldValue("default")); - assertEquals("Currency Time Limit should be 20", "20", desc.getFieldValue("currencyTimeLimit")); - assertEquals("Persist Policy should be OnUpdate", "OnUpdate", desc.getFieldValue("persistPolicy")); - assertEquals("Persist Period should be 300", "300", desc.getFieldValue("persistPeriod")); + assertThat(desc.getFieldValue("default")).as("Default value should be foo").isEqualTo("foo"); + assertThat(desc.getFieldValue("currencyTimeLimit")).as("Currency Time Limit should be 20").isEqualTo("20"); + assertThat(desc.getFieldValue("persistPolicy")).as("Persist Policy should be OnUpdate").isEqualTo("OnUpdate"); + assertThat(desc.getFieldValue("persistPeriod")).as("Persist Period should be 300").isEqualTo("300"); } @Test @@ -142,8 +135,8 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble ModelMBeanInfo info = getMBeanInfoFromAssembler(); Descriptor desc = info.getOperation("myOperation").getDescriptor(); - assertEquals("Currency Time Limit should be 30", "30", desc.getFieldValue("currencyTimeLimit")); - assertEquals("Role should be \"operation\"", "operation", desc.getFieldValue("role")); + assertThat(desc.getFieldValue("currencyTimeLimit")).as("Currency Time Limit should be 30").isEqualTo("30"); + assertThat(desc.getFieldValue("role")).as("Role should be \"operation\"").isEqualTo("operation"); } @Test @@ -152,12 +145,12 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble ModelMBeanOperationInfo oper = info.getOperation("add"); MBeanParameterInfo[] params = oper.getSignature(); - assertEquals("Invalid number of params", 2, params.length); - assertEquals("Incorrect name for x param", "x", params[0].getName()); - assertEquals("Incorrect type for x param", int.class.getName(), params[0].getType()); + assertThat(params.length).as("Invalid number of params").isEqualTo(2); + assertThat(params[0].getName()).as("Incorrect name for x param").isEqualTo("x"); + assertThat(params[0].getType()).as("Incorrect type for x param").isEqualTo(int.class.getName()); - assertEquals("Incorrect name for y param", "y", params[1].getName()); - assertEquals("Incorrect type for y param", int.class.getName(), params[1].getType()); + assertThat(params[1].getName()).as("Incorrect name for y param").isEqualTo("y"); + assertThat(params[1].getType()).as("Incorrect type for y param").isEqualTo(int.class.getName()); } @Test @@ -182,10 +175,10 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble start(exporter); MBeanInfo inf = getServer().getMBeanInfo(ObjectNameManager.getInstance(objectName)); - assertEquals("Incorrect number of operations", getExpectedOperationCount(), inf.getOperations().length); - assertEquals("Incorrect number of attributes", getExpectedAttributeCount(), inf.getAttributes().length); + assertThat(inf.getOperations().length).as("Incorrect number of operations").isEqualTo(getExpectedOperationCount()); + assertThat(inf.getAttributes().length).as("Incorrect number of attributes").isEqualTo(getExpectedAttributeCount()); - assertTrue("Not included in autodetection", assembler.includeBean(proxy.getClass(), "some bean name")); + assertThat(assembler.includeBean(proxy.getClass(), "some bean name")).as("Not included in autodetection").isTrue(); } @Test @@ -193,36 +186,34 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo metric = inf.getAttribute(QUEUE_SIZE_METRIC); ModelMBeanOperationInfo operation = inf.getOperation("getQueueSize"); - assertEquals("The description for the queue size metric is incorrect", - "The QueueSize metric", metric.getDescription()); - assertEquals("The description for the getter operation of the queue size metric is incorrect", - "The QueueSize metric", operation.getDescription()); + assertThat(metric.getDescription()).as("The description for the queue size metric is incorrect").isEqualTo("The QueueSize metric"); + assertThat(operation.getDescription()).as("The description for the getter operation of the queue size metric is incorrect").isEqualTo("The QueueSize metric"); } @Test public void testMetricDescriptor() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); Descriptor desc = info.getAttribute(QUEUE_SIZE_METRIC).getDescriptor(); - assertEquals("Currency Time Limit should be 20", "20", desc.getFieldValue("currencyTimeLimit")); - assertEquals("Persist Policy should be OnUpdate", "OnUpdate", desc.getFieldValue("persistPolicy")); - assertEquals("Persist Period should be 300", "300", desc.getFieldValue("persistPeriod")); - assertEquals("Unit should be messages", "messages",desc.getFieldValue("units")); - assertEquals("Display Name should be Queue Size", "Queue Size",desc.getFieldValue("displayName")); - assertEquals("Metric Type should be COUNTER", "COUNTER",desc.getFieldValue("metricType")); - assertEquals("Metric Category should be utilization", "utilization",desc.getFieldValue("metricCategory")); + assertThat(desc.getFieldValue("currencyTimeLimit")).as("Currency Time Limit should be 20").isEqualTo("20"); + assertThat(desc.getFieldValue("persistPolicy")).as("Persist Policy should be OnUpdate").isEqualTo("OnUpdate"); + assertThat(desc.getFieldValue("persistPeriod")).as("Persist Period should be 300").isEqualTo("300"); + assertThat(desc.getFieldValue("units")).as("Unit should be messages").isEqualTo("messages"); + assertThat(desc.getFieldValue("displayName")).as("Display Name should be Queue Size").isEqualTo("Queue Size"); + assertThat(desc.getFieldValue("metricType")).as("Metric Type should be COUNTER").isEqualTo("COUNTER"); + assertThat(desc.getFieldValue("metricCategory")).as("Metric Category should be utilization").isEqualTo("utilization"); } @Test public void testMetricDescriptorDefaults() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); Descriptor desc = info.getAttribute(CACHE_ENTRIES_METRIC).getDescriptor(); - assertNull("Currency Time Limit should not be populated", desc.getFieldValue("currencyTimeLimit")); - assertNull("Persist Policy should not be populated", desc.getFieldValue("persistPolicy")); - assertNull("Persist Period should not be populated", desc.getFieldValue("persistPeriod")); - assertNull("Unit should not be populated", desc.getFieldValue("units")); - assertEquals("Display Name should be populated by default via JMX", CACHE_ENTRIES_METRIC,desc.getFieldValue("displayName")); - assertEquals("Metric Type should be GAUGE", "GAUGE",desc.getFieldValue("metricType")); - assertNull("Metric Category should not be populated", desc.getFieldValue("metricCategory")); + assertThat(desc.getFieldValue("currencyTimeLimit")).as("Currency Time Limit should not be populated").isNull(); + assertThat(desc.getFieldValue("persistPolicy")).as("Persist Policy should not be populated").isNull(); + assertThat(desc.getFieldValue("persistPeriod")).as("Persist Period should not be populated").isNull(); + assertThat(desc.getFieldValue("units")).as("Unit should not be populated").isNull(); + assertThat(desc.getFieldValue("displayName")).as("Display Name should be populated by default via JMX").isEqualTo(CACHE_ENTRIES_METRIC); + assertThat(desc.getFieldValue("metricType")).as("Metric Type should be GAUGE").isEqualTo("GAUGE"); + assertThat(desc.getFieldValue("metricCategory")).as("Metric Category should not be populated").isNull(); } @Override diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerCustomTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerCustomTests.java index c28d669f37b..241a4bbdeba 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerCustomTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerCustomTests.java @@ -21,8 +21,7 @@ import javax.management.modelmbean.ModelMBeanInfo; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -60,8 +59,8 @@ public class InterfaceBasedMBeanInfoAssemblerCustomTests extends AbstractJmxAsse ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); - assertTrue(attr.isReadable()); - assertFalse(attr.isWritable()); + assertThat(attr.isReadable()).isTrue(); + assertThat(attr.isWritable()).isFalse(); } @Override diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java index f5e50bde8af..584085edeec 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java @@ -23,10 +23,8 @@ import javax.management.modelmbean.ModelMBeanInfo; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * @author Rob Harrop @@ -41,8 +39,8 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); - assertTrue("Age is not readable", attr.isReadable()); - assertFalse("Age is not writable", attr.isWritable()); + assertThat(attr.isReadable()).as("Age is not readable").isTrue(); + assertThat(attr.isWritable()).as("Age is not writable").isFalse(); } @Test @@ -118,9 +116,9 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse } private void assertNickName(MBeanAttributeInfo attr) { - assertNotNull("Nick Name should not be null", attr); - assertTrue("Nick Name should be writable", attr.isWritable()); - assertTrue("Nick Name should be readable", attr.isReadable()); + assertThat(attr).as("Nick Name should not be null").isNotNull(); + assertThat(attr.isWritable()).as("Nick Name should be writable").isTrue(); + assertThat(attr.isReadable()).as("Nick Name should be readable").isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerComboTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerComboTests.java index 152c37d7a3c..0f1bc4c949b 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerComboTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerComboTests.java @@ -23,9 +23,7 @@ import javax.management.modelmbean.ModelMBeanInfo; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -40,17 +38,17 @@ public class MethodExclusionMBeanInfoAssemblerComboTests extends AbstractJmxAsse public void testGetAgeIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); - assertTrue("Age is not readable", attr.isReadable()); - assertFalse("Age is not writable", attr.isWritable()); + assertThat(attr.isReadable()).as("Age is not readable").isTrue(); + assertThat(attr.isWritable()).as("Age is not writable").isFalse(); } @Test public void testNickNameIsExposed() throws Exception { ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo(); MBeanAttributeInfo attr = inf.getAttribute("NickName"); - assertNotNull("Nick Name should not be null", attr); - assertTrue("Nick Name should be writable", attr.isWritable()); - assertTrue("Nick Name should be readable", attr.isReadable()); + assertThat(attr).as("Nick Name should not be null").isNotNull(); + assertThat(attr.isWritable()).as("Nick Name should be writable").isTrue(); + assertThat(attr.isReadable()).as("Nick Name should be readable").isTrue(); } @Override diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerMappedTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerMappedTests.java index 9d3500808b8..927d337ab47 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerMappedTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerMappedTests.java @@ -23,9 +23,7 @@ import javax.management.modelmbean.ModelMBeanInfo; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -39,17 +37,17 @@ public class MethodExclusionMBeanInfoAssemblerMappedTests extends AbstractJmxAss public void testGetAgeIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); - assertTrue("Age is not readable", attr.isReadable()); - assertFalse("Age is not writable", attr.isWritable()); + assertThat(attr.isReadable()).as("Age is not readable").isTrue(); + assertThat(attr.isWritable()).as("Age is not writable").isFalse(); } @Test public void testNickNameIsExposed() throws Exception { ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo(); MBeanAttributeInfo attr = inf.getAttribute("NickName"); - assertNotNull("Nick Name should not be null", attr); - assertTrue("Nick Name should be writable", attr.isWritable()); - assertTrue("Nick Name should be readable", attr.isReadable()); + assertThat(attr).as("Nick Name should not be null").isNotNull(); + assertThat(attr.isWritable()).as("Nick Name should be writable").isTrue(); + assertThat(attr.isReadable()).as("Nick Name should be readable").isTrue(); } @Override diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerNotMappedTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerNotMappedTests.java index a0e19805fb5..f20181d9dee 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerNotMappedTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerNotMappedTests.java @@ -23,8 +23,7 @@ import javax.management.modelmbean.ModelMBeanInfo; import org.junit.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -39,17 +38,17 @@ public class MethodExclusionMBeanInfoAssemblerNotMappedTests extends AbstractJmx public void testGetAgeIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); - assertTrue("Age is not readable", attr.isReadable()); - assertTrue("Age is not writable", attr.isWritable()); + assertThat(attr.isReadable()).as("Age is not readable").isTrue(); + assertThat(attr.isWritable()).as("Age is not writable").isTrue(); } @Test public void testNickNameIsExposed() throws Exception { ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo(); MBeanAttributeInfo attr = inf.getAttribute("NickName"); - assertNotNull("Nick Name should not be null", attr); - assertTrue("Nick Name should be writable", attr.isWritable()); - assertTrue("Nick Name should be readable", attr.isReadable()); + assertThat(attr).as("Nick Name should not be null").isNotNull(); + assertThat(attr.isWritable()).as("Nick Name should be writable").isTrue(); + assertThat(attr.isReadable()).as("Nick Name should be readable").isTrue(); } @Override diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerTests.java index a481366da5e..7fb37d4bf37 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerTests.java @@ -25,8 +25,7 @@ import org.junit.Test; import org.springframework.jmx.JmxTestBean; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -70,8 +69,8 @@ public class MethodExclusionMBeanInfoAssemblerTests extends AbstractJmxAssembler ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute("Superman"); - assertTrue(attr.isReadable()); - assertFalse(attr.isWritable()); + assertThat(attr.isReadable()).isTrue(); + assertThat(attr.isWritable()).isFalse(); } /* @@ -85,9 +84,9 @@ public class MethodExclusionMBeanInfoAssemblerTests extends AbstractJmxAssembler ignored.setProperty(beanKey, "dontExposeMe,setSuperman"); assembler.setIgnoredMethodMappings(ignored); Method method = JmxTestBean.class.getMethod("dontExposeMe"); - assertFalse(assembler.isNotIgnored(method, beanKey)); + assertThat(assembler.isNotIgnored(method, beanKey)).isFalse(); // this bean does not have any ignored methods on it, so must obviously not be ignored... - assertTrue(assembler.isNotIgnored(method, "someOtherBeanKey")); + assertThat(assembler.isNotIgnored(method, "someOtherBeanKey")).isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerMappedTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerMappedTests.java index 1c2401551d1..786bbdd2195 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerMappedTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerMappedTests.java @@ -23,9 +23,7 @@ import javax.management.modelmbean.ModelMBeanInfo; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -41,8 +39,8 @@ public class MethodNameBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAss ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); - assertTrue("Age is not readable", attr.isReadable()); - assertFalse("Age is not writable", attr.isWritable()); + assertThat(attr.isReadable()).as("Age is not readable").isTrue(); + assertThat(attr.isWritable()).as("Age is not writable").isFalse(); } @Test @@ -103,9 +101,9 @@ public class MethodNameBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAss } private void assertNickName(MBeanAttributeInfo attr) { - assertNotNull("Nick Name should not be null", attr); - assertTrue("Nick Name should be writable", attr.isWritable()); - assertTrue("Nick Name should be readable", attr.isReadable()); + assertThat(attr).as("Nick Name should not be null").isNotNull(); + assertThat(attr.isWritable()).as("Nick Name should be writable").isTrue(); + assertThat(attr.isReadable()).as("Nick Name should be readable").isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java index d261303da84..c7c00034043 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java @@ -22,9 +22,7 @@ import javax.management.modelmbean.ModelMBeanInfo; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -63,8 +61,8 @@ public class MethodNameBasedMBeanInfoAssemblerTests extends AbstractJmxAssembler ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); - assertTrue(attr.isReadable()); - assertFalse(attr.isWritable()); + assertThat(attr.isReadable()).isTrue(); + assertThat(attr.isWritable()).isFalse(); } @Test @@ -72,7 +70,7 @@ public class MethodNameBasedMBeanInfoAssemblerTests extends AbstractJmxAssembler ModelMBeanInfo info = getMBeanInfoFromAssembler(); MBeanOperationInfo operationSetAge = info.getOperation("setName"); - assertEquals("name", operationSetAge.getSignature()[0].getName()); + assertThat(operationSetAge.getSignature()[0].getName()).isEqualTo("name"); } @Override diff --git a/spring-context/src/test/java/org/springframework/jmx/export/naming/AbstractNamingStrategyTests.java b/spring-context/src/test/java/org/springframework/jmx/export/naming/AbstractNamingStrategyTests.java index bd915ea7690..c85496c0f89 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/naming/AbstractNamingStrategyTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/naming/AbstractNamingStrategyTests.java @@ -20,7 +20,7 @@ import javax.management.ObjectName; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -31,7 +31,7 @@ public abstract class AbstractNamingStrategyTests { public void naming() throws Exception { ObjectNamingStrategy strat = getStrategy(); ObjectName objectName = strat.getObjectName(getManagedResource(), getKey()); - assertEquals(objectName.getCanonicalName(), getCorrectObjectName()); + assertThat(getCorrectObjectName()).isEqualTo(objectName.getCanonicalName()); } protected abstract ObjectNamingStrategy getStrategy() throws Exception; diff --git a/spring-context/src/test/java/org/springframework/jmx/export/naming/IdentityNamingStrategyTests.java b/spring-context/src/test/java/org/springframework/jmx/export/naming/IdentityNamingStrategyTests.java index 7dc59f273f7..4571ccb8e89 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/naming/IdentityNamingStrategyTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/naming/IdentityNamingStrategyTests.java @@ -25,7 +25,7 @@ import org.springframework.jmx.JmxTestBean; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -37,12 +37,9 @@ public class IdentityNamingStrategyTests { JmxTestBean bean = new JmxTestBean(); IdentityNamingStrategy strategy = new IdentityNamingStrategy(); ObjectName objectName = strategy.getObjectName(bean, "null"); - assertEquals("Domain is incorrect", bean.getClass().getPackage().getName(), - objectName.getDomain()); - assertEquals("Type property is incorrect", ClassUtils.getShortName(bean.getClass()), - objectName.getKeyProperty(IdentityNamingStrategy.TYPE_KEY)); - assertEquals("HashCode property is incorrect", ObjectUtils.getIdentityHexString(bean), - objectName.getKeyProperty(IdentityNamingStrategy.HASH_CODE_KEY)); + assertThat(objectName.getDomain()).as("Domain is incorrect").isEqualTo(bean.getClass().getPackage().getName()); + assertThat(objectName.getKeyProperty(IdentityNamingStrategy.TYPE_KEY)).as("Type property is incorrect").isEqualTo(ClassUtils.getShortName(bean.getClass())); + assertThat(objectName.getKeyProperty(IdentityNamingStrategy.HASH_CODE_KEY)).as("HashCode property is incorrect").isEqualTo(ObjectUtils.getIdentityHexString(bean)); } } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/notification/ModelMBeanNotificationPublisherTests.java b/spring-context/src/test/java/org/springframework/jmx/export/notification/ModelMBeanNotificationPublisherTests.java index 79fa59a9be8..92b5275bd5e 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/notification/ModelMBeanNotificationPublisherTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/notification/ModelMBeanNotificationPublisherTests.java @@ -27,10 +27,8 @@ import org.junit.Test; import org.springframework.jmx.export.SpringModelMBean; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Rick Evans @@ -72,9 +70,9 @@ public class ModelMBeanNotificationPublisherTests { NotificationPublisher publisher = new ModelMBeanNotificationPublisher(mbean, objectName, mbean); publisher.sendNotification(notification); - assertNotNull(mbean.getActualNotification()); - assertSame("The exact same Notification is not being passed through from the publisher to the mbean.", notification, mbean.getActualNotification()); - assertSame("The 'source' property of the Notification is not being set to the ObjectName of the associated MBean.", objectName, mbean.getActualNotification().getSource()); + assertThat(mbean.getActualNotification()).isNotNull(); + assertThat(mbean.getActualNotification()).as("The exact same Notification is not being passed through from the publisher to the mbean.").isSameAs(notification); + assertThat(mbean.getActualNotification().getSource()).as("The 'source' property of the Notification is not being set to the ObjectName of the associated MBean.").isSameAs(objectName); } public void testSendAttributeChangeNotification() throws Exception { @@ -85,10 +83,11 @@ public class ModelMBeanNotificationPublisherTests { NotificationPublisher publisher = new ModelMBeanNotificationPublisher(mbean, objectName, mbean); publisher.sendNotification(notification); - assertNotNull(mbean.getActualNotification()); - assertTrue(mbean.getActualNotification() instanceof AttributeChangeNotification); - assertSame("The exact same Notification is not being passed through from the publisher to the mbean.", notification, mbean.getActualNotification()); - assertSame("The 'source' property of the Notification is not being set to the ObjectName of the associated MBean.", objectName, mbean.getActualNotification().getSource()); + assertThat(mbean.getActualNotification()).isNotNull(); + boolean condition = mbean.getActualNotification() instanceof AttributeChangeNotification; + assertThat(condition).isTrue(); + assertThat(mbean.getActualNotification()).as("The exact same Notification is not being passed through from the publisher to the mbean.").isSameAs(notification); + assertThat(mbean.getActualNotification().getSource()).as("The 'source' property of the Notification is not being set to the ObjectName of the associated MBean.").isSameAs(objectName); } public void testSendAttributeChangeNotificationWhereSourceIsNotTheManagedResource() throws Exception { @@ -99,10 +98,11 @@ public class ModelMBeanNotificationPublisherTests { NotificationPublisher publisher = new ModelMBeanNotificationPublisher(mbean, objectName, mbean); publisher.sendNotification(notification); - assertNotNull(mbean.getActualNotification()); - assertTrue(mbean.getActualNotification() instanceof AttributeChangeNotification); - assertSame("The exact same Notification is not being passed through from the publisher to the mbean.", notification, mbean.getActualNotification()); - assertSame("The 'source' property of the Notification is *wrongly* being set to the ObjectName of the associated MBean.", this, mbean.getActualNotification().getSource()); + assertThat(mbean.getActualNotification()).isNotNull(); + boolean condition = mbean.getActualNotification() instanceof AttributeChangeNotification; + assertThat(condition).isTrue(); + assertThat(mbean.getActualNotification()).as("The exact same Notification is not being passed through from the publisher to the mbean.").isSameAs(notification); + assertThat(mbean.getActualNotification().getSource()).as("The 'source' property of the Notification is *wrongly* being set to the ObjectName of the associated MBean.").isSameAs(this); } private static ObjectName createObjectName() throws MalformedObjectNameException { diff --git a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java index 0cda82b944f..03bc5d5d45c 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java @@ -31,9 +31,8 @@ import org.junit.Test; import org.springframework.jmx.AbstractMBeanServerTests; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * @author Rob Harrop @@ -88,7 +87,7 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { try { // Try to get the connector bean. ObjectInstance instance = getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME)); - assertNotNull("ObjectInstance should not be null", instance); + assertThat(instance).as("ObjectInstance should not be null").isNotNull(); } finally { bean.destroy(); @@ -114,15 +113,14 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { JMXServiceURL serviceURL = new JMXServiceURL(ConnectorServerFactoryBean.DEFAULT_SERVICE_URL); JMXConnector connector = JMXConnectorFactory.connect(serviceURL); - assertNotNull("Client Connector should not be null", connector); + assertThat(connector).as("Client Connector should not be null").isNotNull(); // Get the MBean server connection. MBeanServerConnection connection = connector.getMBeanServerConnection(); - assertNotNull("MBeanServerConnection should not be null", connection); + assertThat(connection).as("MBeanServerConnection should not be null").isNotNull(); // Test for MBean server equality. - assertEquals("Registered MBean count should be the same", hostedServer.getMBeanCount(), - connection.getMBeanCount()); + assertThat(connection.getMBeanCount()).as("Registered MBean count should be the same").isEqualTo(hostedServer.getMBeanCount()); } } diff --git a/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java b/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java index a5e2c167a5d..70867a89137 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/JmxUtilsTests.java @@ -33,9 +33,7 @@ import org.springframework.jmx.JmxTestBean; import org.springframework.jmx.export.TestDynamicMBean; import org.springframework.util.ObjectUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -46,60 +44,58 @@ public class JmxUtilsTests { @Test public void testIsMBeanWithDynamicMBean() throws Exception { DynamicMBean mbean = new TestDynamicMBean(); - assertTrue("Dynamic MBean not detected correctly", JmxUtils.isMBean(mbean.getClass())); + assertThat(JmxUtils.isMBean(mbean.getClass())).as("Dynamic MBean not detected correctly").isTrue(); } @Test public void testIsMBeanWithStandardMBeanWrapper() throws Exception { StandardMBean mbean = new StandardMBean(new JmxTestBean(), IJmxTestBean.class); - assertTrue("Standard MBean not detected correctly", JmxUtils.isMBean(mbean.getClass())); + assertThat(JmxUtils.isMBean(mbean.getClass())).as("Standard MBean not detected correctly").isTrue(); } @Test public void testIsMBeanWithStandardMBeanInherited() throws Exception { StandardMBean mbean = new StandardMBeanImpl(); - assertTrue("Standard MBean not detected correctly", JmxUtils.isMBean(mbean.getClass())); + assertThat(JmxUtils.isMBean(mbean.getClass())).as("Standard MBean not detected correctly").isTrue(); } @Test public void testNotAnMBean() throws Exception { - assertFalse("Object incorrectly identified as an MBean", JmxUtils.isMBean(Object.class)); + assertThat(JmxUtils.isMBean(Object.class)).as("Object incorrectly identified as an MBean").isFalse(); } @Test public void testSimpleMBean() throws Exception { Foo foo = new Foo(); - assertTrue("Simple MBean not detected correctly", JmxUtils.isMBean(foo.getClass())); + assertThat(JmxUtils.isMBean(foo.getClass())).as("Simple MBean not detected correctly").isTrue(); } @Test public void testSimpleMXBean() throws Exception { FooX foo = new FooX(); - assertTrue("Simple MXBean not detected correctly", JmxUtils.isMBean(foo.getClass())); + assertThat(JmxUtils.isMBean(foo.getClass())).as("Simple MXBean not detected correctly").isTrue(); } @Test public void testSimpleMBeanThroughInheritance() throws Exception { Bar bar = new Bar(); Abc abc = new Abc(); - assertTrue("Simple MBean (through inheritance) not detected correctly", - JmxUtils.isMBean(bar.getClass())); - assertTrue("Simple MBean (through 2 levels of inheritance) not detected correctly", - JmxUtils.isMBean(abc.getClass())); + assertThat(JmxUtils.isMBean(bar.getClass())).as("Simple MBean (through inheritance) not detected correctly").isTrue(); + assertThat(JmxUtils.isMBean(abc.getClass())).as("Simple MBean (through 2 levels of inheritance) not detected correctly").isTrue(); } @Test public void testGetAttributeNameWithStrictCasing() { PropertyDescriptor pd = new BeanWrapperImpl(AttributeTestBean.class).getPropertyDescriptor("name"); String attributeName = JmxUtils.getAttributeName(pd, true); - assertEquals("Incorrect casing on attribute name", "Name", attributeName); + assertThat(attributeName).as("Incorrect casing on attribute name").isEqualTo("Name"); } @Test public void testGetAttributeNameWithoutStrictCasing() { PropertyDescriptor pd = new BeanWrapperImpl(AttributeTestBean.class).getPropertyDescriptor("name"); String attributeName = JmxUtils.getAttributeName(pd, false); - assertEquals("Incorrect casing on attribute name", "name", attributeName); + assertThat(attributeName).as("Incorrect casing on attribute name").isEqualTo("name"); } @Test @@ -110,9 +106,9 @@ public class JmxUtilsTests { String typeProperty = "type"; - assertEquals("Domain of transformed name is incorrect", objectName.getDomain(), uniqueName.getDomain()); - assertEquals("Type key is incorrect", objectName.getKeyProperty(typeProperty), uniqueName.getKeyProperty("type")); - assertEquals("Identity key is incorrect", ObjectUtils.getIdentityHexString(managedResource), uniqueName.getKeyProperty(JmxUtils.IDENTITY_OBJECT_NAME_KEY)); + assertThat(uniqueName.getDomain()).as("Domain of transformed name is incorrect").isEqualTo(objectName.getDomain()); + assertThat(uniqueName.getKeyProperty("type")).as("Type key is incorrect").isEqualTo(objectName.getKeyProperty(typeProperty)); + assertThat(uniqueName.getKeyProperty(JmxUtils.IDENTITY_OBJECT_NAME_KEY)).as("Identity key is incorrect").isEqualTo(ObjectUtils.getIdentityHexString(managedResource)); } @Test @@ -131,13 +127,13 @@ public class JmxUtilsTests { @Test public void testIsMBean() { // Correctly returns true for a class - assertTrue(JmxUtils.isMBean(JmxClass.class)); + assertThat(JmxUtils.isMBean(JmxClass.class)).isTrue(); // Correctly returns false since JmxUtils won't navigate to the extended interface - assertFalse(JmxUtils.isMBean(SpecializedJmxInterface.class)); + assertThat(JmxUtils.isMBean(SpecializedJmxInterface.class)).isFalse(); // Incorrectly returns true since it doesn't detect that this is an interface - assertFalse(JmxUtils.isMBean(JmxInterface.class)); + assertThat(JmxUtils.isMBean(JmxInterface.class)).isFalse(); } diff --git a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java index 7639e404c9d..1fb9add38d9 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java @@ -28,10 +28,8 @@ import org.springframework.aop.support.AopUtils; import org.springframework.jmx.AbstractMBeanServerTests; import org.springframework.util.SocketUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * @author Rob Harrop @@ -63,10 +61,10 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe try { MBeanServerConnection connection = bean.getObject(); - assertNotNull("Connection should not be null", connection); + assertThat(connection).as("Connection should not be null").isNotNull(); // perform simple MBean count test - assertEquals("MBean count should be the same", getServer().getMBeanCount(), connection.getMBeanCount()); + assertThat(connection.getMBeanCount()).as("MBean count should be the same").isEqualTo(getServer().getMBeanCount()); } finally { bean.destroy(); @@ -92,13 +90,13 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe bean.afterPropertiesSet(); MBeanServerConnection connection = bean.getObject(); - assertTrue(AopUtils.isAopProxy(connection)); + assertThat(AopUtils.isAopProxy(connection)).isTrue(); JMXConnectorServer connector = null; try { connector = getConnectorServer(); connector.start(); - assertEquals("Incorrect MBean count", getServer().getMBeanCount(), connection.getMBeanCount()); + assertThat(connection.getMBeanCount()).as("Incorrect MBean count").isEqualTo(getServer().getMBeanCount()); } finally { bean.destroy(); @@ -116,7 +114,7 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe bean.afterPropertiesSet(); MBeanServerConnection connection = bean.getObject(); - assertTrue(AopUtils.isAopProxy(connection)); + assertThat(AopUtils.isAopProxy(connection)).isTrue(); bean.destroy(); } diff --git a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java index c2a5cfbe068..1fa9022a0af 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java @@ -28,9 +28,6 @@ import org.junit.Test; import org.springframework.util.MBeanTestUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; /** * @author Rob Harrop @@ -57,7 +54,7 @@ public class MBeanServerFactoryBeanTests { bean.afterPropertiesSet(); try { MBeanServer server = bean.getObject(); - assertNotNull("The MBeanServer should not be null", server); + assertThat(server).as("The MBeanServer should not be null").isNotNull(); } finally { bean.destroy(); @@ -71,7 +68,7 @@ public class MBeanServerFactoryBeanTests { bean.afterPropertiesSet(); try { MBeanServer server = bean.getObject(); - assertEquals("The default domain should be foo", "foo", server.getDefaultDomain()); + assertThat(server.getDefaultDomain()).as("The default domain should be foo").isEqualTo("foo"); } finally { bean.destroy(); @@ -87,7 +84,7 @@ public class MBeanServerFactoryBeanTests { bean.afterPropertiesSet(); try { MBeanServer otherServer = bean.getObject(); - assertSame("Existing MBeanServer not located", server, otherServer); + assertThat(otherServer).as("Existing MBeanServer not located").isSameAs(server); } finally { bean.destroy(); @@ -104,7 +101,7 @@ public class MBeanServerFactoryBeanTests { bean.setLocateExistingServerIfPossible(true); bean.afterPropertiesSet(); try { - assertSame(ManagementFactory.getPlatformMBeanServer(), bean.getObject()); + assertThat(bean.getObject()).isSameAs(ManagementFactory.getPlatformMBeanServer()); } finally { bean.destroy(); @@ -117,7 +114,7 @@ public class MBeanServerFactoryBeanTests { bean.setAgentId(""); bean.afterPropertiesSet(); try { - assertSame(ManagementFactory.getPlatformMBeanServer(), bean.getObject()); + assertThat(bean.getObject()).isSameAs(ManagementFactory.getPlatformMBeanServer()); } finally { bean.destroy(); diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java index 632764ffd13..a769de951fd 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java @@ -27,12 +27,10 @@ import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.tests.sample.beans.ITestBean; 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.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -59,7 +57,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("java:comp/env/foo"); jof.setResourceRef(true); jof.afterPropertiesSet(); - assertTrue(jof.getObject() == o); + assertThat(jof.getObject() == o).isTrue(); } @Test @@ -70,7 +68,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("java:comp/env/foo"); jof.setResourceRef(false); jof.afterPropertiesSet(); - assertTrue(jof.getObject() == o); + assertThat(jof.getObject() == o).isTrue(); } @Test @@ -81,7 +79,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("java:foo"); jof.setResourceRef(true); jof.afterPropertiesSet(); - assertTrue(jof.getObject() == o); + assertThat(jof.getObject() == o).isTrue(); } @Test @@ -92,7 +90,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("java:foo"); jof.setResourceRef(false); jof.afterPropertiesSet(); - assertTrue(jof.getObject() == o); + assertThat(jof.getObject() == o).isTrue(); } @Test @@ -103,7 +101,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("foo"); jof.setResourceRef(true); jof.afterPropertiesSet(); - assertTrue(jof.getObject() == o); + assertThat(jof.getObject() == o).isTrue(); } @Test @@ -124,7 +122,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("foo"); jof.setResourceRef(false); jof.afterPropertiesSet(); - assertTrue(jof.getObject() == o); + assertThat(jof.getObject() == o).isTrue(); } @Test @@ -135,7 +133,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("foo"); jof.setExpectedType(String.class); jof.afterPropertiesSet(); - assertTrue(jof.getObject() == s); + assertThat(jof.getObject() == s).isTrue(); } @Test @@ -157,7 +155,7 @@ public class JndiObjectFactoryBeanTests { jof.setExpectedType(String.class); jof.setDefaultObject("myString"); jof.afterPropertiesSet(); - assertEquals("myString", jof.getObject()); + assertThat(jof.getObject()).isEqualTo("myString"); } @Test @@ -168,7 +166,7 @@ public class JndiObjectFactoryBeanTests { jof.setExpectedType(String.class); jof.setDefaultObject("myString"); jof.afterPropertiesSet(); - assertEquals("myString", jof.getObject()); + assertThat(jof.getObject()).isEqualTo("myString"); } @Test @@ -179,7 +177,7 @@ public class JndiObjectFactoryBeanTests { jof.setExpectedType(Integer.class); jof.setDefaultObject("5"); jof.afterPropertiesSet(); - assertEquals(new Integer(5), jof.getObject()); + assertThat(jof.getObject()).isEqualTo(new Integer(5)); } @Test @@ -191,7 +189,7 @@ public class JndiObjectFactoryBeanTests { jof.setDefaultObject("5"); jof.setBeanFactory(new DefaultListableBeanFactory()); jof.afterPropertiesSet(); - assertEquals(new Integer(5), jof.getObject()); + assertThat(jof.getObject()).isEqualTo(new Integer(5)); } @Test @@ -212,11 +210,12 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("foo"); jof.setProxyInterface(ITestBean.class); jof.afterPropertiesSet(); - assertTrue(jof.getObject() instanceof ITestBean); + boolean condition = jof.getObject() instanceof ITestBean; + assertThat(condition).isTrue(); ITestBean proxy = (ITestBean) jof.getObject(); - assertEquals(0, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(0); proxy.setAge(99); - assertEquals(99, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(99); } @Test @@ -248,13 +247,14 @@ public class JndiObjectFactoryBeanTests { jof.setProxyInterface(ITestBean.class); jof.setLookupOnStartup(false); jof.afterPropertiesSet(); - assertTrue(jof.getObject() instanceof ITestBean); + boolean condition = jof.getObject() instanceof ITestBean; + assertThat(condition).isTrue(); ITestBean proxy = (ITestBean) jof.getObject(); - assertNull(tb.getName()); - assertEquals(0, tb.getAge()); + assertThat(tb.getName()).isNull(); + assertThat(tb.getAge()).isEqualTo(0); proxy.setAge(99); - assertEquals("tb", tb.getName()); - assertEquals(99, tb.getAge()); + assertThat(tb.getName()).isEqualTo("tb"); + assertThat(tb.getAge()).isEqualTo(99); } @Test @@ -276,14 +276,15 @@ public class JndiObjectFactoryBeanTests { jof.setProxyInterface(ITestBean.class); jof.setCache(false); jof.afterPropertiesSet(); - assertTrue(jof.getObject() instanceof ITestBean); + boolean condition = jof.getObject() instanceof ITestBean; + assertThat(condition).isTrue(); ITestBean proxy = (ITestBean) jof.getObject(); - assertEquals("tb", tb.getName()); - assertEquals(1, tb.getAge()); + assertThat(tb.getName()).isEqualTo("tb"); + assertThat(tb.getAge()).isEqualTo(1); proxy.returnsThis(); - assertEquals(2, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(2); proxy.haveBirthday(); - assertEquals(4, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(4); } @Test @@ -306,17 +307,18 @@ public class JndiObjectFactoryBeanTests { jof.setLookupOnStartup(false); jof.setCache(false); jof.afterPropertiesSet(); - assertTrue(jof.getObject() instanceof ITestBean); + boolean condition = jof.getObject() instanceof ITestBean; + assertThat(condition).isTrue(); ITestBean proxy = (ITestBean) jof.getObject(); - assertNull(tb.getName()); - assertEquals(0, tb.getAge()); + assertThat(tb.getName()).isNull(); + assertThat(tb.getAge()).isEqualTo(0); proxy.returnsThis(); - assertEquals("tb", tb.getName()); - assertEquals(1, tb.getAge()); + assertThat(tb.getName()).isEqualTo("tb"); + assertThat(tb.getAge()).isEqualTo(1); proxy.returnsThis(); - assertEquals(2, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(2); proxy.haveBirthday(); - assertEquals(4, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(4); } @Test @@ -345,11 +347,12 @@ public class JndiObjectFactoryBeanTests { jof.setExpectedType(TestBean.class); jof.setProxyInterface(ITestBean.class); jof.afterPropertiesSet(); - assertTrue(jof.getObject() instanceof ITestBean); + boolean condition = jof.getObject() instanceof ITestBean; + assertThat(condition).isTrue(); ITestBean proxy = (ITestBean) jof.getObject(); - assertEquals(0, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(0); proxy.setAge(99); - assertEquals(99, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(99); } @Test @@ -381,11 +384,12 @@ public class JndiObjectFactoryBeanTests { jof.setProxyInterface(ITestBean.class); jof.setExposeAccessContext(true); jof.afterPropertiesSet(); - assertTrue(jof.getObject() instanceof ITestBean); + boolean condition = jof.getObject() instanceof ITestBean; + assertThat(condition).isTrue(); ITestBean proxy = (ITestBean) jof.getObject(); - assertEquals(0, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(0); proxy.setAge(99); - assertEquals(99, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(99); proxy.equals(proxy); proxy.hashCode(); proxy.toString(); diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java index e8f17baf12b..2c0ff609839 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java @@ -24,7 +24,6 @@ import org.junit.Test; import org.springframework.tests.mock.jndi.SimpleNamingContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link JndiPropertySource}. @@ -98,7 +97,7 @@ public class JndiPropertySourceTests { JndiLocatorDelegate jndiLocator = new JndiLocatorDelegate() { @Override public Object lookup(String jndiName) throws NamingException { - assertEquals("my:key", jndiName); + assertThat(jndiName).isEqualTo("my:key"); return "my:value"; } }; diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiTemplateEditorTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiTemplateEditorTests.java index 376f91ca30b..695d2e3cda9 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiTemplateEditorTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiTemplateEditorTests.java @@ -18,8 +18,8 @@ package org.springframework.jndi; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -38,7 +38,7 @@ public class JndiTemplateEditorTests { JndiTemplateEditor je = new JndiTemplateEditor(); je.setAsText(""); JndiTemplate jt = (JndiTemplate) je.getValue(); - assertTrue(jt.getEnvironment() == null); + assertThat(jt.getEnvironment() == null).isTrue(); } @Test @@ -49,9 +49,9 @@ public class JndiTemplateEditorTests { // to look anything up je.setAsText("jndiInitialSomethingOrOther=org.springframework.myjndi.CompleteRubbish\nfoo=bar"); JndiTemplate jt = (JndiTemplate) je.getValue(); - assertTrue(jt.getEnvironment().size() == 2); - assertTrue(jt.getEnvironment().getProperty("jndiInitialSomethingOrOther").equals("org.springframework.myjndi.CompleteRubbish")); - assertTrue(jt.getEnvironment().getProperty("foo").equals("bar")); + assertThat(jt.getEnvironment().size() == 2).isTrue(); + assertThat(jt.getEnvironment().getProperty("jndiInitialSomethingOrOther").equals("org.springframework.myjndi.CompleteRubbish")).isTrue(); + assertThat(jt.getEnvironment().getProperty("foo").equals("bar")).isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java index 163ca418061..ddf504d4fb8 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java @@ -21,8 +21,8 @@ import javax.naming.NameNotFoundException; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -50,7 +50,7 @@ public class JndiTemplateTests { }; Object o2 = jt.lookup(name); - assertEquals(o, o2); + assertThat(o2).isEqualTo(o); verify(context).close(); } diff --git a/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java b/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java index 7f7c297b2a6..c4265263876 100644 --- a/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java @@ -38,9 +38,8 @@ import org.junit.Test; import org.springframework.tests.mock.jndi.SimpleNamingContext; import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -59,16 +58,16 @@ public class SimpleNamingContextTests { builder.bind("myobject", obj); Context context1 = factory.getInitialContext(null); - assertTrue("Correct DataSource registered", context1.lookup("java:comp/env/jdbc/myds") == ds); - assertTrue("Correct Object registered", context1.lookup("myobject") == obj); + assertThat(context1.lookup("java:comp/env/jdbc/myds") == ds).as("Correct DataSource registered").isTrue(); + assertThat(context1.lookup("myobject") == obj).as("Correct Object registered").isTrue(); Hashtable env2 = new Hashtable<>(); env2.put("key1", "value1"); Context context2 = factory.getInitialContext(env2); - assertTrue("Correct DataSource registered", context2.lookup("java:comp/env/jdbc/myds") == ds); - assertTrue("Correct Object registered", context2.lookup("myobject") == obj); - assertTrue("Correct environment", context2.getEnvironment() != env2); - assertTrue("Correct key1", "value1".equals(context2.getEnvironment().get("key1"))); + assertThat(context2.lookup("java:comp/env/jdbc/myds") == ds).as("Correct DataSource registered").isTrue(); + assertThat(context2.lookup("myobject") == obj).as("Correct Object registered").isTrue(); + assertThat(context2.getEnvironment() != env2).as("Correct environment").isTrue(); + assertThat("value1".equals(context2.getEnvironment().get("key1"))).as("Correct key1").isTrue(); Integer i = new Integer(0); context1.rebind("myinteger", i); @@ -79,29 +78,29 @@ public class SimpleNamingContextTests { context3.rename("java:comp/env/jdbc/myds", "jdbc/myds"); context3.unbind("myobject"); - assertTrue("Correct environment", context3.getEnvironment() != context2.getEnvironment()); + assertThat(context3.getEnvironment() != context2.getEnvironment()).as("Correct environment").isTrue(); context3.addToEnvironment("key2", "value2"); - assertTrue("key2 added", "value2".equals(context3.getEnvironment().get("key2"))); + assertThat("value2".equals(context3.getEnvironment().get("key2"))).as("key2 added").isTrue(); context3.removeFromEnvironment("key1"); - assertTrue("key1 removed", context3.getEnvironment().get("key1") == null); + assertThat(context3.getEnvironment().get("key1") == null).as("key1 removed").isTrue(); - assertTrue("Correct DataSource registered", context1.lookup("jdbc/myds") == ds); + assertThat(context1.lookup("jdbc/myds") == ds).as("Correct DataSource registered").isTrue(); assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() -> context1.lookup("myobject")); - assertTrue("Correct Integer registered", context1.lookup("myinteger") == i); - assertTrue("Correct String registered", context1.lookup("mystring") == s); + assertThat(context1.lookup("myinteger") == i).as("Correct Integer registered").isTrue(); + assertThat(context1.lookup("mystring") == s).as("Correct String registered").isTrue(); - assertTrue("Correct DataSource registered", context2.lookup("jdbc/myds") == ds); + assertThat(context2.lookup("jdbc/myds") == ds).as("Correct DataSource registered").isTrue(); assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() -> context2.lookup("myobject")); - assertTrue("Correct Integer registered", context2.lookup("myinteger") == i); - assertTrue("Correct String registered", context2.lookup("mystring") == s); + assertThat(context2.lookup("myinteger") == i).as("Correct Integer registered").isTrue(); + assertThat(context2.lookup("mystring") == s).as("Correct String registered").isTrue(); - assertTrue("Correct DataSource registered", context3.lookup("jdbc/myds") == ds); + assertThat(context3.lookup("jdbc/myds") == ds).as("Correct DataSource registered").isTrue(); assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() -> context3.lookup("myobject")); - assertTrue("Correct Integer registered", context3.lookup("myinteger") == i); - assertTrue("Correct String registered", context3.lookup("mystring") == s); + assertThat(context3.lookup("myinteger") == i).as("Correct Integer registered").isTrue(); + assertThat(context3.lookup("mystring") == s).as("Correct String registered").isTrue(); Map bindingMap = new HashMap<>(); NamingEnumeration bindingEnum = context3.listBindings(""); @@ -109,8 +108,9 @@ public class SimpleNamingContextTests { Binding binding = (Binding) bindingEnum.nextElement(); bindingMap.put(binding.getName(), binding); } - assertTrue("Correct jdbc subcontext", bindingMap.get("jdbc").getObject() instanceof Context); - assertTrue("Correct jdbc subcontext", SimpleNamingContext.class.getName().equals(bindingMap.get("jdbc").getClassName())); + boolean condition = bindingMap.get("jdbc").getObject() instanceof Context; + assertThat(condition).as("Correct jdbc subcontext").isTrue(); + assertThat(SimpleNamingContext.class.getName().equals(bindingMap.get("jdbc").getClassName())).as("Correct jdbc subcontext").isTrue(); Context jdbcContext = (Context) context3.lookup("jdbc"); jdbcContext.bind("mydsX", ds); @@ -121,14 +121,14 @@ public class SimpleNamingContextTests { subBindingMap.put(binding.getName(), binding); } - assertTrue("Correct DataSource registered", ds.equals(subBindingMap.get("myds").getObject())); - assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subBindingMap.get("myds").getClassName())); - assertTrue("Correct DataSource registered", ds.equals(subBindingMap.get("mydsX").getObject())); - assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subBindingMap.get("mydsX").getClassName())); - assertTrue("Correct Integer registered", i.equals(bindingMap.get("myinteger").getObject())); - assertTrue("Correct Integer registered", Integer.class.getName().equals(bindingMap.get("myinteger").getClassName())); - assertTrue("Correct String registered", s.equals(bindingMap.get("mystring").getObject())); - assertTrue("Correct String registered", String.class.getName().equals(bindingMap.get("mystring").getClassName())); + assertThat(ds.equals(subBindingMap.get("myds").getObject())).as("Correct DataSource registered").isTrue(); + assertThat(StubDataSource.class.getName().equals(subBindingMap.get("myds").getClassName())).as("Correct DataSource registered").isTrue(); + assertThat(ds.equals(subBindingMap.get("mydsX").getObject())).as("Correct DataSource registered").isTrue(); + assertThat(StubDataSource.class.getName().equals(subBindingMap.get("mydsX").getClassName())).as("Correct DataSource registered").isTrue(); + assertThat(i.equals(bindingMap.get("myinteger").getObject())).as("Correct Integer registered").isTrue(); + assertThat(Integer.class.getName().equals(bindingMap.get("myinteger").getClassName())).as("Correct Integer registered").isTrue(); + assertThat(s.equals(bindingMap.get("mystring").getObject())).as("Correct String registered").isTrue(); + assertThat(String.class.getName().equals(bindingMap.get("mystring").getClassName())).as("Correct String registered").isTrue(); context1.createSubcontext("jdbc").bind("sub/subds", ds); @@ -138,7 +138,7 @@ public class SimpleNamingContextTests { NameClassPair pair = (NameClassPair) pairEnum.next(); pairMap.put(pair.getName(), pair.getClassName()); } - assertTrue("Correct sub subcontext", SimpleNamingContext.class.getName().equals(pairMap.get("sub"))); + assertThat(SimpleNamingContext.class.getName().equals(pairMap.get("sub"))).as("Correct sub subcontext").isTrue(); Context subContext = (Context) context2.lookup("jdbc/sub"); Map subPairMap = new HashMap<>(); @@ -148,9 +148,9 @@ public class SimpleNamingContextTests { subPairMap.put(pair.getName(), pair.getClassName()); } - assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subPairMap.get("subds"))); - assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("myds"))); - assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("mydsX"))); + assertThat(StubDataSource.class.getName().equals(subPairMap.get("subds"))).as("Correct DataSource registered").isTrue(); + assertThat(StubDataSource.class.getName().equals(pairMap.get("myds"))).as("Correct DataSource registered").isTrue(); + assertThat(StubDataSource.class.getName().equals(pairMap.get("mydsX"))).as("Correct DataSource registered").isTrue(); pairMap.clear(); pairEnum = context1.list("jdbc/"); @@ -158,8 +158,8 @@ public class SimpleNamingContextTests { NameClassPair pair = (NameClassPair) pairEnum.next(); pairMap.put(pair.getName(), pair.getClassName()); } - assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("myds"))); - assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("mydsX"))); + assertThat(StubDataSource.class.getName().equals(pairMap.get("myds"))).as("Correct DataSource registered").isTrue(); + assertThat(StubDataSource.class.getName().equals(pairMap.get("mydsX"))).as("Correct DataSource registered").isTrue(); } /** @@ -174,7 +174,7 @@ public class SimpleNamingContextTests { builder.bind(name, o); // Check it affects JNDI Context ctx = new InitialContext(); - assertTrue(ctx.lookup(name) == o); + assertThat(ctx.lookup(name) == o).isTrue(); // Check it returns mutable contexts ctx.unbind(name); InitialContext badCtx1 = new InitialContext(); @@ -188,7 +188,7 @@ public class SimpleNamingContextTests { badCtx2.lookup(name)); Object o2 = new Object(); builder.bind(name, o2); - assertEquals(badCtx2.lookup(name), o2); + assertThat(o2).isEqualTo(badCtx2.lookup(name)); } diff --git a/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java b/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java index 8ec2b4b54ed..87faf4e2c61 100644 --- a/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java +++ b/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java @@ -40,9 +40,6 @@ import org.springframework.remoting.support.RemoteInvocation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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 Juergen Hoeller @@ -56,12 +53,13 @@ public class RmiSupportTests { factory.setServiceInterface(IRemoteBean.class); factory.setServiceUrl("rmi://localhost:1090/test"); factory.afterPropertiesSet(); - assertTrue("Correct singleton value", factory.isSingleton()); - assertTrue(factory.getObject() instanceof IRemoteBean); + assertThat(factory.isSingleton()).as("Correct singleton value").isTrue(); + boolean condition = factory.getObject() instanceof IRemoteBean; + assertThat(condition).isTrue(); IRemoteBean proxy = (IRemoteBean) factory.getObject(); proxy.setName("myName"); - assertEquals("myName", RemoteBean.name); - assertEquals(1, factory.counter); + assertThat(RemoteBean.name).isEqualTo("myName"); + assertThat(factory.counter).isEqualTo(1); } @Test @@ -109,11 +107,12 @@ public class RmiSupportTests { factory.setServiceInterface(IRemoteBean.class); factory.setServiceUrl("rmi://localhost:1090/test"); factory.afterPropertiesSet(); - assertTrue(factory.getObject() instanceof IRemoteBean); + boolean condition = factory.getObject() instanceof IRemoteBean; + assertThat(condition).isTrue(); IRemoteBean proxy = (IRemoteBean) factory.getObject(); assertThatExceptionOfType(exceptionClass).isThrownBy(() -> proxy.setName(exceptionClass.getName())); - assertEquals(1, factory.counter); + assertThat(factory.counter).isEqualTo(1); } @Test @@ -147,11 +146,12 @@ public class RmiSupportTests { factory.setServiceUrl("rmi://localhost:1090/test"); factory.setRefreshStubOnConnectFailure(true); factory.afterPropertiesSet(); - assertTrue(factory.getObject() instanceof IRemoteBean); + boolean condition = factory.getObject() instanceof IRemoteBean; + assertThat(condition).isTrue(); IRemoteBean proxy = (IRemoteBean) factory.getObject(); assertThatExceptionOfType(exceptionClass).isThrownBy(() -> proxy.setName(exceptionClass.getName())); - assertEquals(2, factory.counter); + assertThat(factory.counter).isEqualTo(2); } @Test @@ -160,12 +160,14 @@ public class RmiSupportTests { factory.setServiceInterface(IBusinessBean.class); factory.setServiceUrl("rmi://localhost:1090/test"); factory.afterPropertiesSet(); - assertTrue(factory.getObject() instanceof IBusinessBean); + boolean condition = factory.getObject() instanceof IBusinessBean; + assertThat(condition).isTrue(); IBusinessBean proxy = (IBusinessBean) factory.getObject(); - assertFalse(proxy instanceof IRemoteBean); + boolean condition1 = proxy instanceof IRemoteBean; + assertThat(condition1).isFalse(); proxy.setName("myName"); - assertEquals("myName", RemoteBean.name); - assertEquals(1, factory.counter); + assertThat(RemoteBean.name).isEqualTo("myName"); + assertThat(factory.counter).isEqualTo(1); } @Test @@ -174,15 +176,17 @@ public class RmiSupportTests { factory.setServiceInterface(IWrongBusinessBean.class); factory.setServiceUrl("rmi://localhost:1090/test"); factory.afterPropertiesSet(); - assertTrue(factory.getObject() instanceof IWrongBusinessBean); + boolean condition = factory.getObject() instanceof IWrongBusinessBean; + assertThat(condition).isTrue(); IWrongBusinessBean proxy = (IWrongBusinessBean) factory.getObject(); - assertFalse(proxy instanceof IRemoteBean); + boolean condition1 = proxy instanceof IRemoteBean; + assertThat(condition1).isFalse(); assertThatExceptionOfType(RemoteProxyFailureException.class).isThrownBy(() -> proxy.setOtherName("name")) .withCauseInstanceOf(NoSuchMethodException.class) .withMessageContaining("setOtherName") .withMessageContaining("IWrongBusinessBean"); - assertEquals(1, factory.counter); + assertThat(factory.counter).isEqualTo(1); } @Test @@ -228,12 +232,14 @@ public class RmiSupportTests { factory.setServiceInterface(IBusinessBean.class); factory.setServiceUrl("rmi://localhost:1090/test"); factory.afterPropertiesSet(); - assertTrue(factory.getObject() instanceof IBusinessBean); + boolean condition = factory.getObject() instanceof IBusinessBean; + assertThat(condition).isTrue(); IBusinessBean proxy = (IBusinessBean) factory.getObject(); - assertFalse(proxy instanceof IRemoteBean); + boolean condition1 = proxy instanceof IRemoteBean; + assertThat(condition1).isFalse(); assertThatExceptionOfType(springExceptionClass).isThrownBy(() -> proxy.setName(rmiExceptionClass.getName())); - assertEquals(1, factory.counter); + assertThat(factory.counter).isEqualTo(1); } @Test @@ -280,9 +286,11 @@ public class RmiSupportTests { factory.setServiceUrl("rmi://localhost:1090/test"); factory.setRefreshStubOnConnectFailure(true); factory.afterPropertiesSet(); - assertTrue(factory.getObject() instanceof IBusinessBean); + boolean condition = factory.getObject() instanceof IBusinessBean; + assertThat(condition).isTrue(); IBusinessBean proxy = (IBusinessBean) factory.getObject(); - assertFalse(proxy instanceof IRemoteBean); + boolean condition1 = proxy instanceof IRemoteBean; + assertThat(condition1).isFalse(); assertThatExceptionOfType(springExceptionClass).isThrownBy(() -> proxy.setName(rmiExceptionClass.getName())); boolean isRemoteConnectFaiure = RemoteConnectFailureException.class.isAssignableFrom(springExceptionClass); @@ -328,23 +336,23 @@ public class RmiSupportTests { RemoteInvocation inv = new RemoteInvocation(mi); - assertEquals("setName", inv.getMethodName()); - assertEquals("bla", inv.getArguments()[0]); - assertEquals(String.class, inv.getParameterTypes()[0]); + assertThat(inv.getMethodName()).isEqualTo("setName"); + assertThat(inv.getArguments()[0]).isEqualTo("bla"); + assertThat(inv.getParameterTypes()[0]).isEqualTo(String.class); // this is a bit BS, but we need to test it inv = new RemoteInvocation(); inv.setArguments(new Object[] { "bla" }); - assertEquals("bla", inv.getArguments()[0]); + assertThat(inv.getArguments()[0]).isEqualTo("bla"); inv.setMethodName("setName"); - assertEquals("setName", inv.getMethodName()); + assertThat(inv.getMethodName()).isEqualTo("setName"); inv.setParameterTypes(new Class[] {String.class}); - assertEquals(String.class, inv.getParameterTypes()[0]); + assertThat(inv.getParameterTypes()[0]).isEqualTo(String.class); inv = new RemoteInvocation("setName", new Class[] {String.class}, new Object[] {"bla"}); - assertEquals("bla", inv.getArguments()[0]); - assertEquals("setName", inv.getMethodName()); - assertEquals(String.class, inv.getParameterTypes()[0]); + assertThat(inv.getArguments()[0]).isEqualTo("bla"); + assertThat(inv.getMethodName()).isEqualTo("setName"); + assertThat(inv.getParameterTypes()[0]).isEqualTo(String.class); } @Test @@ -371,10 +379,10 @@ public class RmiSupportTests { IBusinessBean proxy = (IBusinessBean) factory.getObject(); // shouldn't go through to remote service - assertTrue(proxy.toString().contains("RMI invoker")); - assertTrue(proxy.toString().contains(serviceUrl)); - assertEquals(proxy.hashCode(), proxy.hashCode()); - assertTrue(proxy.equals(proxy)); + assertThat(proxy.toString().contains("RMI invoker")).isTrue(); + assertThat(proxy.toString().contains(serviceUrl)).isTrue(); + assertThat(proxy.hashCode()).isEqualTo(proxy.hashCode()); + assertThat(proxy.equals(proxy)).isTrue(); // should go through assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(() -> diff --git a/spring-context/src/test/java/org/springframework/remoting/support/RemoteInvocationUtilsTests.java b/spring-context/src/test/java/org/springframework/remoting/support/RemoteInvocationUtilsTests.java index 2913615ad93..b00a76e9b7d 100644 --- a/spring-context/src/test/java/org/springframework/remoting/support/RemoteInvocationUtilsTests.java +++ b/spring-context/src/test/java/org/springframework/remoting/support/RemoteInvocationUtilsTests.java @@ -18,7 +18,7 @@ package org.springframework.remoting.support; import org.junit.Test; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rick Evans @@ -33,8 +33,7 @@ public class RemoteInvocationUtilsTests { catch (Exception ex) { int originalStackTraceLngth = ex.getStackTrace().length; RemoteInvocationUtils.fillInClientStackTraceIfPossible(ex); - assertTrue("Stack trace not being filled in", - ex.getStackTrace().length > originalStackTraceLngth); + assertThat(ex.getStackTrace().length > originalStackTraceLngth).as("Stack trace not being filled in").isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessorTests.java index 5320741f45a..1106ba51b8e 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessorTests.java @@ -42,10 +42,8 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.util.ReflectionUtils; import org.springframework.util.concurrent.ListenableFuture; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * @author Mark Fisher @@ -59,7 +57,7 @@ public class AsyncAnnotationBeanPostProcessorTests { ConfigurableApplicationContext context = initContext( new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class)); Object target = context.getBean("target"); - assertTrue(AopUtils.isAopProxy(target)); + assertThat(AopUtils.isAopProxy(target)).isTrue(); context.close(); } @@ -73,7 +71,7 @@ public class AsyncAnnotationBeanPostProcessorTests { Thread mainThread = Thread.currentThread(); testBean.await(3000); Thread asyncThread = testBean.getThread(); - assertNotSame(mainThread, asyncThread); + assertThat(asyncThread).isNotSameAs(mainThread); context.close(); } @@ -92,7 +90,7 @@ public class AsyncAnnotationBeanPostProcessorTests { Thread mainThread = Thread.currentThread(); testBean.await(3000); Thread asyncThread = testBean.getThread(); - assertNotSame(mainThread, asyncThread); + assertThat(asyncThread).isNotSameAs(mainThread); context.close(); } @@ -109,7 +107,7 @@ public class AsyncAnnotationBeanPostProcessorTests { testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); - assertTrue(asyncThread.getName().startsWith("testExecutor")); + assertThat(asyncThread.getName().startsWith("testExecutor")).isTrue(); context.close(); } @@ -134,7 +132,7 @@ public class AsyncAnnotationBeanPostProcessorTests { testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); - assertTrue(asyncThread.getName().startsWith("testExecutor")); + assertThat(asyncThread.getName().startsWith("testExecutor")).isTrue(); context.close(); } @@ -163,7 +161,7 @@ public class AsyncAnnotationBeanPostProcessorTests { testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); - assertTrue(asyncThread.getName().startsWith("testExecutor2")); + assertThat(asyncThread.getName().startsWith("testExecutor2")).isTrue(); context.close(); } @@ -176,11 +174,11 @@ public class AsyncAnnotationBeanPostProcessorTests { testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); - assertTrue(asyncThread.getName().startsWith("testExecutor")); + assertThat(asyncThread.getName().startsWith("testExecutor")).isTrue(); TestableAsyncUncaughtExceptionHandler exceptionHandler = context.getBean("exceptionHandler", TestableAsyncUncaughtExceptionHandler.class); - assertFalse("handler should not have been called yet", exceptionHandler.isCalled()); + assertThat(exceptionHandler.isCalled()).as("handler should not have been called yet").isFalse(); testBean.failWithVoid(); exceptionHandler.await(3000); @@ -198,7 +196,7 @@ public class AsyncAnnotationBeanPostProcessorTests { TestableAsyncUncaughtExceptionHandler exceptionHandler = context.getBean("exceptionHandler", TestableAsyncUncaughtExceptionHandler.class); - assertFalse("handler should not have been called yet", exceptionHandler.isCalled()); + assertThat(exceptionHandler.isCalled()).as("handler should not have been called yet").isFalse(); Future result = testBean.failWithFuture(); assertFutureWithException(result, exceptionHandler); } @@ -212,7 +210,7 @@ public class AsyncAnnotationBeanPostProcessorTests { TestableAsyncUncaughtExceptionHandler exceptionHandler = context.getBean("exceptionHandler", TestableAsyncUncaughtExceptionHandler.class); - assertFalse("handler should not have been called yet", exceptionHandler.isCalled()); + assertThat(exceptionHandler.isCalled()).as("handler should not have been called yet").isFalse(); Future result = testBean.failWithListenableFuture(); assertFutureWithException(result, exceptionHandler); } @@ -222,7 +220,7 @@ public class AsyncAnnotationBeanPostProcessorTests { assertThatExceptionOfType(ExecutionException.class).isThrownBy( result::get) .withCauseExactlyInstanceOf(UnsupportedOperationException.class); - assertFalse("handler should never be called with Future return type", exceptionHandler.isCalled()); + assertThat(exceptionHandler.isCalled()).as("handler should never be called with Future return type").isFalse(); } @Test @@ -236,7 +234,7 @@ public class AsyncAnnotationBeanPostProcessorTests { ConfigurableApplicationContext context = initContext(processorDefinition); ITestBean testBean = context.getBean("target", ITestBean.class); - assertFalse("Handler should not have been called", exceptionHandler.isCalled()); + assertThat(exceptionHandler.isCalled()).as("Handler should not have been called").isFalse(); testBean.failWithVoid(); exceptionHandler.await(3000); exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class); @@ -254,7 +252,7 @@ public class AsyncAnnotationBeanPostProcessorTests { ConfigurableApplicationContext context = initContext(processorDefinition); ITestBean testBean = context.getBean("target", ITestBean.class); - assertFalse("Handler should not have been called", exceptionHandler.isCalled()); + assertThat(exceptionHandler.isCalled()).as("Handler should not have been called").isFalse(); testBean.failWithVoid(); exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java index 64e6c2149c0..d4f41029c9d 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java @@ -43,9 +43,8 @@ import org.springframework.context.support.GenericApplicationContext; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.util.concurrent.ListenableFuture; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -74,11 +73,11 @@ public class AsyncExecutionTests { asyncTest.doNothing(5); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); ListenableFuture listenableFuture = asyncTest.returnSomethingListenable(20); - assertEquals("20", listenableFuture.get()); + assertThat(listenableFuture.get()).isEqualTo("20"); CompletableFuture completableFuture = asyncTest.returnSomethingCompletable(20); - assertEquals("20", completableFuture.get()); + assertThat(completableFuture.get()).isEqualTo("20"); assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> asyncTest.returnSomething(0).get()) @@ -114,7 +113,7 @@ public class AsyncExecutionTests { asyncTest.doNothing(5); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); } @Test @@ -133,9 +132,9 @@ public class AsyncExecutionTests { asyncTest.doNothing(5); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); Future future2 = asyncTest.returnSomething2(30); - assertEquals("30", future2.get()); + assertThat(future2.get()).isEqualTo("30"); } @Test @@ -154,9 +153,9 @@ public class AsyncExecutionTests { asyncTest.doNothing(5); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); Future future2 = asyncTest.returnSomething2(30); - assertEquals("30", future2.get()); + assertThat(future2.get()).isEqualTo("30"); } @Test @@ -171,11 +170,11 @@ public class AsyncExecutionTests { AsyncClassBean asyncTest = context.getBean("asyncTest", AsyncClassBean.class); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); ListenableFuture listenableFuture = asyncTest.returnSomethingListenable(20); - assertEquals("20", listenableFuture.get()); + assertThat(listenableFuture.get()).isEqualTo("20"); CompletableFuture completableFuture = asyncTest.returnSomethingCompletable(20); - assertEquals("20", completableFuture.get()); + assertThat(completableFuture.get()).isEqualTo("20"); assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> asyncTest.returnSomething(0).get()) @@ -201,7 +200,7 @@ public class AsyncExecutionTests { AsyncClassBean asyncTest = context.getBean("asyncTest", AsyncClassBean.class); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); } @Test @@ -216,7 +215,7 @@ public class AsyncExecutionTests { RegularInterface asyncTest = context.getBean("asyncTest", RegularInterface.class); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); } @Test @@ -230,7 +229,7 @@ public class AsyncExecutionTests { RegularInterface asyncTest = context.getBean("asyncTest", RegularInterface.class); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); } @Test @@ -245,7 +244,7 @@ public class AsyncExecutionTests { AsyncInterface asyncTest = context.getBean("asyncTest", AsyncInterface.class); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); } @Test @@ -259,7 +258,7 @@ public class AsyncExecutionTests { AsyncInterface asyncTest = context.getBean("asyncTest", AsyncInterface.class); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); } @Test @@ -274,7 +273,7 @@ public class AsyncExecutionTests { AsyncInterface asyncTest = context.getBean("asyncTest", AsyncInterface.class); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); } @Test @@ -288,7 +287,7 @@ public class AsyncExecutionTests { AsyncInterface asyncTest = context.getBean("asyncTest", AsyncInterface.class); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); } @Test @@ -304,7 +303,7 @@ public class AsyncExecutionTests { asyncTest.doNothing(5); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); } @Test @@ -319,7 +318,7 @@ public class AsyncExecutionTests { asyncTest.doNothing(5); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); } @Test @@ -333,7 +332,7 @@ public class AsyncExecutionTests { AsyncMethodsInterface asyncTest = context.getBean("asyncTest", AsyncMethodsInterface.class); asyncTest.doSomething(10); Future future = asyncTest.returnSomething(20); - assertEquals("20", future.get()); + assertThat(future.get()).isEqualTo("20"); } @Test @@ -373,7 +372,7 @@ public class AsyncExecutionTests { .atMost(1, TimeUnit.SECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(() -> listenerCalled == 2); - assertEquals(1, listenerConstructed); + assertThat(listenerConstructed).isEqualTo(1); } @Test @@ -396,7 +395,7 @@ public class AsyncExecutionTests { .atMost(1, TimeUnit.SECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(() -> listenerCalled == 2); - assertEquals(2, listenerConstructed); + assertThat(listenerConstructed).isEqualTo(2); } @@ -415,17 +414,19 @@ public class AsyncExecutionTests { public static class AsyncMethodBean { public void doNothing(int i) { - assertTrue(Thread.currentThread().getName().equals(originalThreadName)); + assertThat(Thread.currentThread().getName().equals(originalThreadName)).isTrue(); } @Async public void doSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); } @Async public Future returnSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); if (i == 0) { throw new IllegalArgumentException(); } @@ -437,7 +438,8 @@ public class AsyncExecutionTests { @Async public ListenableFuture returnSomethingListenable(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); if (i == 0) { throw new IllegalArgumentException(); } @@ -449,7 +451,8 @@ public class AsyncExecutionTests { @Async public CompletableFuture returnSomethingCompletable(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); if (i == 0) { throw new IllegalArgumentException(); } @@ -471,25 +474,28 @@ public class AsyncExecutionTests { public static class AsyncMethodWithQualifierBean { public void doNothing(int i) { - assertTrue(Thread.currentThread().getName().equals(originalThreadName)); + assertThat(Thread.currentThread().getName().equals(originalThreadName)).isTrue(); } @Async("e1") public void doSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); - assertTrue(Thread.currentThread().getName().startsWith("e1-")); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); + assertThat(Thread.currentThread().getName().startsWith("e1-")).isTrue(); } @MyAsync public Future returnSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); - assertTrue(Thread.currentThread().getName().startsWith("e2-")); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); + assertThat(Thread.currentThread().getName().startsWith("e2-")).isTrue(); return new AsyncResult<>(Integer.toString(i)); } public Future returnSomething2(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); - assertTrue(Thread.currentThread().getName().startsWith("e0-")); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); + assertThat(Thread.currentThread().getName().startsWith("e0-")).isTrue(); return new AsyncResult<>(Integer.toString(i)); } } @@ -510,11 +516,13 @@ public class AsyncExecutionTests { public static class AsyncClassBean implements Serializable, DisposableBean { public void doSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); } public Future returnSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); if (i == 0) { throw new IllegalArgumentException(); } @@ -522,7 +530,8 @@ public class AsyncExecutionTests { } public ListenableFuture returnSomethingListenable(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); if (i == 0) { throw new IllegalArgumentException(); } @@ -531,7 +540,8 @@ public class AsyncExecutionTests { @Async public CompletableFuture returnSomethingCompletable(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); if (i == 0) { throw new IllegalArgumentException(); } @@ -556,11 +566,13 @@ public class AsyncExecutionTests { public static class AsyncClassBeanWithInterface implements RegularInterface { public void doSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); } public Future returnSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); return new AsyncResult<>(Integer.toString(i)); } } @@ -579,12 +591,14 @@ public class AsyncExecutionTests { @Override public void doSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); } @Override public Future returnSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); return new AsyncResult<>(Integer.toString(i)); } } @@ -599,7 +613,8 @@ public class AsyncExecutionTests { DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(new MethodInterceptor() { @Override public Object invoke(MethodInvocation invocation) throws Throwable { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); if (Future.class.equals(invocation.getMethod().getReturnType())) { return new AsyncResult<>(invocation.getArguments()[0].toString()); } @@ -644,17 +659,19 @@ public class AsyncExecutionTests { @Override public void doNothing(int i) { - assertTrue(Thread.currentThread().getName().equals(originalThreadName)); + assertThat(Thread.currentThread().getName().equals(originalThreadName)).isTrue(); } @Override public void doSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); } @Override public Future returnSomething(int i) { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); return new AsyncResult<>(Integer.toString(i)); } } @@ -669,7 +686,8 @@ public class AsyncExecutionTests { DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(new MethodInterceptor() { @Override public Object invoke(MethodInvocation invocation) throws Throwable { - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); if (Future.class.equals(invocation.getMethod().getReturnType())) { return new AsyncResult<>(invocation.getArguments()[0].toString()); } @@ -704,7 +722,8 @@ public class AsyncExecutionTests { @Async public void onApplicationEvent(ApplicationEvent event) { listenerCalled++; - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); } } @@ -719,7 +738,8 @@ public class AsyncExecutionTests { @Override public void onApplicationEvent(ApplicationEvent event) { listenerCalled++; - assertTrue(!Thread.currentThread().getName().equals(originalThreadName)); + boolean condition = !Thread.currentThread().getName().equals(originalThreadName); + assertThat(condition).isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncResultTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncResultTests.java index 6fe92288603..fc9cecc0866 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncResultTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncResultTests.java @@ -26,8 +26,8 @@ import org.junit.Test; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertSame; /** * @author Juergen Hoeller @@ -49,10 +49,10 @@ public class AsyncResultTests { throw new AssertionError("Failure callback not expected: " + ex, ex); } }); - assertSame(value, values.iterator().next()); - assertSame(value, future.get()); - assertSame(value, future.completable().get()); - future.completable().thenAccept(v -> assertSame(value, v)); + assertThat(values.iterator().next()).isSameAs(value); + assertThat(future.get()).isSameAs(value); + assertThat(future.completable().get()).isSameAs(value); + future.completable().thenAccept(v -> assertThat(v).isSameAs(value)); } @Test @@ -70,7 +70,7 @@ public class AsyncResultTests { values.add(ex); } }); - assertSame(ex, values.iterator().next()); + assertThat(values.iterator().next()).isSameAs(ex); assertThatExceptionOfType(ExecutionException.class).isThrownBy( future::get) .withCause(ex); @@ -85,10 +85,10 @@ public class AsyncResultTests { final Set values = new HashSet<>(1); ListenableFuture future = AsyncResult.forValue(value); future.addCallback(values::add, ex -> new AssertionError("Failure callback not expected: " + ex)); - assertSame(value, values.iterator().next()); - assertSame(value, future.get()); - assertSame(value, future.completable().get()); - future.completable().thenAccept(v -> assertSame(value, v)); + assertThat(values.iterator().next()).isSameAs(value); + assertThat(future.get()).isSameAs(value); + assertThat(future.completable().get()).isSameAs(value); + future.completable().thenAccept(v -> assertThat(v).isSameAs(value)); } @Test @@ -97,7 +97,7 @@ public class AsyncResultTests { final Set values = new HashSet<>(1); ListenableFuture future = AsyncResult.forExecutionException(ex); future.addCallback(result -> new AssertionError("Success callback not expected: " + result), values::add); - assertSame(ex, values.iterator().next()); + assertThat(values.iterator().next()).isSameAs(ex); assertThatExceptionOfType(ExecutionException.class).isThrownBy( future::get) .withCause(ex); diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java index 436e3bbd11e..b1352508ed8 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java @@ -56,8 +56,6 @@ import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Tests use of @EnableAsync on @Configuration classes. @@ -163,7 +161,7 @@ public class EnableAsyncTests { ctx.refresh(); Object bean = ctx.getBean(CustomAsyncBean.class); - assertTrue(AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).isTrue(); boolean isAsyncAdvised = false; for (Advisor advisor : ((Advised) bean).getAdvisors()) { if (advisor instanceof AsyncAnnotationAdvisor) { @@ -171,7 +169,7 @@ public class EnableAsyncTests { break; } } - assertTrue("bean was not async advised as expected", isAsyncAdvised); + assertThat(isAsyncAdvised).as("bean was not async advised as expected").isTrue(); ctx.close(); } @@ -234,7 +232,7 @@ public class EnableAsyncTests { Method method = ReflectionUtils.findMethod(AsyncBean.class, "fail"); TestableAsyncUncaughtExceptionHandler exceptionHandler = (TestableAsyncUncaughtExceptionHandler) ctx.getBean("exceptionHandler"); - assertFalse("handler should not have been called yet", exceptionHandler.isCalled()); + assertThat(exceptionHandler.isCalled()).as("handler should not have been called yet").isFalse(); // Act asyncBean.fail(); // Assert @@ -272,7 +270,7 @@ public class EnableAsyncTests { AsyncBean asyncBean = ctx.getBean(AsyncBean.class); TestableAsyncUncaughtExceptionHandler exceptionHandler = (TestableAsyncUncaughtExceptionHandler) ctx.getBean("exceptionHandler"); - assertFalse("handler should not have been called yet", exceptionHandler.isCalled()); + assertThat(exceptionHandler.isCalled()).as("handler should not have been called yet").isFalse(); Method method = ReflectionUtils.findMethod(AsyncBean.class, "fail"); // Act asyncBean.fail(); diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableSchedulingTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableSchedulingTests.java index 78ec3116530..564303d4373 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableSchedulingTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableSchedulingTests.java @@ -36,8 +36,6 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Tests use of @EnableScheduling on @Configuration classes. @@ -64,7 +62,7 @@ public class EnableSchedulingTests { Assume.group(TestGroup.PERFORMANCE); ctx = new AnnotationConfigApplicationContext(FixedRateTaskConfig.class); - assertEquals(2, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); + assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()).isEqualTo(2); Thread.sleep(100); assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10); @@ -75,7 +73,7 @@ public class EnableSchedulingTests { Assume.group(TestGroup.PERFORMANCE); ctx = new AnnotationConfigApplicationContext(FixedRateTaskConfigSubclass.class); - assertEquals(2, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); + assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()).isEqualTo(2); Thread.sleep(100); assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10); @@ -86,13 +84,13 @@ public class EnableSchedulingTests { Assume.group(TestGroup.PERFORMANCE); ctx = new AnnotationConfigApplicationContext(ExplicitSchedulerConfig.class); - assertEquals(1, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); + assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()).isEqualTo(1); Thread.sleep(100); assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10); assertThat(ctx.getBean(ExplicitSchedulerConfig.class).threadName).startsWith("explicitScheduler-"); - assertTrue(Arrays.asList(ctx.getDefaultListableBeanFactory().getDependentBeans("myTaskScheduler")).contains( - TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)); + assertThat(Arrays.asList(ctx.getDefaultListableBeanFactory().getDependentBeans("myTaskScheduler")).contains( + TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); } @Test @@ -106,7 +104,7 @@ public class EnableSchedulingTests { Assume.group(TestGroup.PERFORMANCE); ctx = new AnnotationConfigApplicationContext(ExplicitScheduledTaskRegistrarConfig.class); - assertEquals(1, ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()); + assertThat(ctx.getBean(ScheduledTaskHolder.class).getScheduledTasks().size()).isEqualTo(1); Thread.sleep(100); assertThat(ctx.getBean(AtomicInteger.class).get()).isGreaterThanOrEqualTo(10); diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java index c4c5f113bb6..5aacb9c4914 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java @@ -58,10 +58,8 @@ import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * @author Mark Fisher @@ -90,7 +88,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -98,15 +96,15 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List fixedDelayTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("fixedDelayTasks"); - assertEquals(1, fixedDelayTasks.size()); + assertThat(fixedDelayTasks.size()).isEqualTo(1); IntervalTask task = fixedDelayTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("fixedDelay", targetMethod.getName()); - assertEquals(0L, task.getInitialDelay()); - assertEquals(5000L, task.getInterval()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("fixedDelay"); + assertThat(task.getInitialDelay()).isEqualTo(0L); + assertThat(task.getInterval()).isEqualTo(5000L); } @Test @@ -118,7 +116,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -126,15 +124,15 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List fixedRateTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks"); - assertEquals(1, fixedRateTasks.size()); + assertThat(fixedRateTasks.size()).isEqualTo(1); IntervalTask task = fixedRateTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("fixedRate", targetMethod.getName()); - assertEquals(0L, task.getInitialDelay()); - assertEquals(3000L, task.getInterval()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("fixedRate"); + assertThat(task.getInitialDelay()).isEqualTo(0L); + assertThat(task.getInterval()).isEqualTo(3000L); } @Test @@ -146,7 +144,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -154,15 +152,15 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List fixedRateTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks"); - assertEquals(1, fixedRateTasks.size()); + assertThat(fixedRateTasks.size()).isEqualTo(1); IntervalTask task = fixedRateTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("fixedRate", targetMethod.getName()); - assertEquals(1000L, task.getInitialDelay()); - assertEquals(3000L, task.getInterval()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("fixedRate"); + assertThat(task.getInitialDelay()).isEqualTo(1000L); + assertThat(task.getInterval()).isEqualTo(3000L); } @Test @@ -209,7 +207,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(2, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(2); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -217,23 +215,23 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List fixedRateTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks"); - assertEquals(2, fixedRateTasks.size()); + assertThat(fixedRateTasks.size()).isEqualTo(2); IntervalTask task1 = fixedRateTasks.get(0); ScheduledMethodRunnable runnable1 = (ScheduledMethodRunnable) task1.getRunnable(); Object targetObject = runnable1.getTarget(); Method targetMethod = runnable1.getMethod(); - assertEquals(target, targetObject); - assertEquals("fixedRate", targetMethod.getName()); - assertEquals(0, task1.getInitialDelay()); - assertEquals(4000L, task1.getInterval()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("fixedRate"); + assertThat(task1.getInitialDelay()).isEqualTo(0); + assertThat(task1.getInterval()).isEqualTo(4000L); IntervalTask task2 = fixedRateTasks.get(1); ScheduledMethodRunnable runnable2 = (ScheduledMethodRunnable) task2.getRunnable(); targetObject = runnable2.getTarget(); targetMethod = runnable2.getMethod(); - assertEquals(target, targetObject); - assertEquals("fixedRate", targetMethod.getName()); - assertEquals(2000L, task2.getInitialDelay()); - assertEquals(4000L, task2.getInterval()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("fixedRate"); + assertThat(task2.getInitialDelay()).isEqualTo(2000L); + assertThat(task2.getInterval()).isEqualTo(4000L); } @Test @@ -245,7 +243,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -253,14 +251,14 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List cronTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("cronTasks"); - assertEquals(1, cronTasks.size()); + assertThat(cronTasks.size()).isEqualTo(1); CronTask task = cronTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("cron", targetMethod.getName()); - assertEquals("*/7 * * * * ?", task.getExpression()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("cron"); + assertThat(task.getExpression()).isEqualTo("*/7 * * * * ?"); } @Test @@ -272,7 +270,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -280,17 +278,18 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List cronTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("cronTasks"); - assertEquals(1, cronTasks.size()); + assertThat(cronTasks.size()).isEqualTo(1); CronTask task = cronTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("cron", targetMethod.getName()); - assertEquals("0 0 0-4,6-23 * * ?", task.getExpression()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("cron"); + assertThat(task.getExpression()).isEqualTo("0 0 0-4,6-23 * * ?"); Trigger trigger = task.getTrigger(); - assertNotNull(trigger); - assertTrue(trigger instanceof CronTrigger); + assertThat(trigger).isNotNull(); + boolean condition = trigger instanceof CronTrigger; + assertThat(condition).isTrue(); CronTrigger cronTrigger = (CronTrigger) trigger; Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+10")); cal.clear(); @@ -304,7 +303,8 @@ public class ScheduledAnnotationBeanPostProcessorTests { cal.add(Calendar.MINUTE, 30); cal.add(Calendar.HOUR_OF_DAY, 1); // 6:00 Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext); - assertEquals(cal.getTime(), nextExecutionTime); // assert that 6:00 is next execution time + // assert that 6:00 is next execution time + assertThat(nextExecutionTime).isEqualTo(cal.getTime()); } @Test @@ -337,21 +337,21 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) new DirectFieldAccessor(postProcessor).getPropertyValue("registrar"); @SuppressWarnings("unchecked") List cronTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("cronTasks"); - assertEquals(1, cronTasks.size()); + assertThat(cronTasks.size()).isEqualTo(1); CronTask task = cronTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(context.getBean(ScopedProxyUtils.getTargetBeanName("target")), targetObject); - assertEquals("cron", targetMethod.getName()); - assertEquals("*/7 * * * * ?", task.getExpression()); + assertThat(targetObject).isEqualTo(context.getBean(ScopedProxyUtils.getTargetBeanName("target"))); + assertThat(targetMethod.getName()).isEqualTo("cron"); + assertThat(task.getExpression()).isEqualTo("*/7 * * * * ?"); } @Test @@ -363,7 +363,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -371,14 +371,14 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List fixedRateTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks"); - assertEquals(1, fixedRateTasks.size()); + assertThat(fixedRateTasks.size()).isEqualTo(1); IntervalTask task = fixedRateTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("checkForUpdates", targetMethod.getName()); - assertEquals(5000L, task.getInterval()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("checkForUpdates"); + assertThat(task.getInterval()).isEqualTo(5000L); } @Test @@ -390,7 +390,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -398,15 +398,15 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List fixedRateTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks"); - assertEquals(1, fixedRateTasks.size()); + assertThat(fixedRateTasks.size()).isEqualTo(1); IntervalTask task = fixedRateTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("checkForUpdates", targetMethod.getName()); - assertEquals(5000L, task.getInterval()); - assertEquals(1000L, task.getInitialDelay()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("checkForUpdates"); + assertThat(task.getInterval()).isEqualTo(5000L); + assertThat(task.getInitialDelay()).isEqualTo(1000L); } @Test @@ -418,7 +418,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -426,14 +426,14 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List cronTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("cronTasks"); - assertEquals(1, cronTasks.size()); + assertThat(cronTasks.size()).isEqualTo(1); CronTask task = cronTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("generateReport", targetMethod.getName()); - assertEquals("0 0 * * * ?", task.getExpression()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("generateReport"); + assertThat(task.getExpression()).isEqualTo("0 0 * * * ?"); } @Test @@ -451,7 +451,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -459,14 +459,14 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List cronTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("cronTasks"); - assertEquals(1, cronTasks.size()); + assertThat(cronTasks.size()).isEqualTo(1); CronTask task = cronTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("x", targetMethod.getName()); - assertEquals(businessHoursCronExpression, task.getExpression()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("x"); + assertThat(task.getExpression()).isEqualTo(businessHoursCronExpression); } @Test @@ -484,7 +484,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertTrue(postProcessor.getScheduledTasks().isEmpty()); + assertThat(postProcessor.getScheduledTasks().isEmpty()).isTrue(); } @Test @@ -511,7 +511,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -519,15 +519,15 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List fixedDelayTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("fixedDelayTasks"); - assertEquals(1, fixedDelayTasks.size()); + assertThat(fixedDelayTasks.size()).isEqualTo(1); IntervalTask task = fixedDelayTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("fixedDelay", targetMethod.getName()); - assertEquals(1000L, task.getInitialDelay()); - assertEquals(5000L, task.getInterval()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("fixedDelay"); + assertThat(task.getInitialDelay()).isEqualTo(1000L); + assertThat(task.getInterval()).isEqualTo(5000L); } @Test @@ -554,7 +554,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -562,15 +562,15 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List fixedRateTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks"); - assertEquals(1, fixedRateTasks.size()); + assertThat(fixedRateTasks.size()).isEqualTo(1); IntervalTask task = fixedRateTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("fixedRate", targetMethod.getName()); - assertEquals(1000L, task.getInitialDelay()); - assertEquals(3000L, task.getInterval()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("fixedRate"); + assertThat(task.getInitialDelay()).isEqualTo(1000L); + assertThat(task.getInterval()).isEqualTo(3000L); } @Test @@ -586,7 +586,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -594,14 +594,14 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List cronTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("cronTasks"); - assertEquals(1, cronTasks.size()); + assertThat(cronTasks.size()).isEqualTo(1); CronTask task = cronTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("x", targetMethod.getName()); - assertEquals(businessHoursCronExpression, task.getExpression()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("x"); + assertThat(task.getExpression()).isEqualTo(businessHoursCronExpression); } @Test @@ -619,7 +619,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -627,14 +627,14 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List cronTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("cronTasks"); - assertEquals(1, cronTasks.size()); + assertThat(cronTasks.size()).isEqualTo(1); CronTask task = cronTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("y", targetMethod.getName()); - assertEquals(businessHoursCronExpression, task.getExpression()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("y"); + assertThat(task.getExpression()).isEqualTo(businessHoursCronExpression); } @Test @@ -646,7 +646,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class); - assertEquals(1, postProcessor.getScheduledTasks().size()); + assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) @@ -654,14 +654,14 @@ public class ScheduledAnnotationBeanPostProcessorTests { @SuppressWarnings("unchecked") List cronTasks = (List) new DirectFieldAccessor(registrar).getPropertyValue("cronTasks"); - assertEquals(1, cronTasks.size()); + assertThat(cronTasks.size()).isEqualTo(1); CronTask task = cronTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); - assertEquals(target, targetObject); - assertEquals("cron", targetMethod.getName()); - assertEquals("0 0 9-17 * * MON-FRI", task.getExpression()); + assertThat(targetObject).isEqualTo(target); + assertThat(targetMethod.getName()).isEqualTo("cron"); + assertThat(task.getExpression()).isEqualTo("0 0 9-17 * * MON-FRI"); } @Test diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/TestableAsyncUncaughtExceptionHandler.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/TestableAsyncUncaughtExceptionHandler.java index 309f5474f04..9ff3b8c9536 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/TestableAsyncUncaughtExceptionHandler.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/TestableAsyncUncaughtExceptionHandler.java @@ -22,8 +22,7 @@ import java.util.concurrent.TimeUnit; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * An {@link AsyncUncaughtExceptionHandler} implementation used for testing purposes. @@ -60,9 +59,9 @@ class TestableAsyncUncaughtExceptionHandler } public void assertCalledWith(Method expectedMethod, Class expectedExceptionType) { - assertNotNull("Handler not called", descriptor); - assertEquals("Wrong exception type", expectedExceptionType, descriptor.ex.getClass()); - assertEquals("Wrong method", expectedMethod, descriptor.method); + assertThat(descriptor).as("Handler not called").isNotNull(); + assertThat(descriptor.ex.getClass()).as("Wrong exception type").isEqualTo(expectedExceptionType); + assertThat(descriptor.method).as("Wrong method").isEqualTo(expectedMethod); } public void await(long timeout) { diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java index 5ab755704c4..e75a863aab1 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java @@ -33,11 +33,8 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.core.task.AsyncListenableTaskExecutor; import org.springframework.util.concurrent.ListenableFuture; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -87,7 +84,7 @@ public abstract class AbstractSchedulingTaskExecutorTests { TestTask task = new TestTask(1); Future future = executor.submit(task); Object result = future.get(1000, TimeUnit.MILLISECONDS); - assertNull(result); + assertThat(result).isNull(); assertThreadNamePrefix(task); } @@ -97,7 +94,7 @@ public abstract class AbstractSchedulingTaskExecutorTests { Future future = executor.submit(task); assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> future.get(1000, TimeUnit.MILLISECONDS)); - assertTrue(future.isDone()); + assertThat(future.isDone()).isTrue(); } @Test @@ -124,7 +121,7 @@ public abstract class AbstractSchedulingTaskExecutorTests { .atMost(1, TimeUnit.SECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(future::isDone); - assertNull(outcome); + assertThat(outcome).isNull(); assertThreadNamePrefix(task); } @@ -139,7 +136,7 @@ public abstract class AbstractSchedulingTaskExecutorTests { .atMost(1, TimeUnit.SECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(() -> future.isDone() && outcome != null); - assertSame(RuntimeException.class, outcome.getClass()); + assertThat(outcome.getClass()).isSameAs(RuntimeException.class); } @Test @@ -160,7 +157,7 @@ public abstract class AbstractSchedulingTaskExecutorTests { TestCallable task = new TestCallable(1); Future future = executor.submit(task); String result = future.get(1000, TimeUnit.MILLISECONDS); - assertEquals(THREAD_NAME_PREFIX, result.substring(0, THREAD_NAME_PREFIX.length())); + assertThat(result.substring(0, THREAD_NAME_PREFIX.length())).isEqualTo(THREAD_NAME_PREFIX); } @Test @@ -169,7 +166,7 @@ public abstract class AbstractSchedulingTaskExecutorTests { Future future = executor.submit(task); assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> future.get(1000, TimeUnit.MILLISECONDS)); - assertTrue(future.isDone()); + assertThat(future.isDone()).isTrue(); } @Test @@ -196,7 +193,7 @@ public abstract class AbstractSchedulingTaskExecutorTests { .atMost(1, TimeUnit.SECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(() -> future.isDone() && outcome != null); - assertEquals(THREAD_NAME_PREFIX, outcome.toString().substring(0, THREAD_NAME_PREFIX.length())); + assertThat(outcome.toString().substring(0, THREAD_NAME_PREFIX.length())).isEqualTo(THREAD_NAME_PREFIX); } @Test @@ -211,7 +208,7 @@ public abstract class AbstractSchedulingTaskExecutorTests { .atMost(1, TimeUnit.SECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) .until(() -> future.isDone() && outcome != null); - assertSame(RuntimeException.class, outcome.getClass()); + assertThat(outcome.getClass()).isSameAs(RuntimeException.class); } @Test @@ -228,7 +225,7 @@ public abstract class AbstractSchedulingTaskExecutorTests { private void assertThreadNamePrefix(TestTask task) { - assertEquals(THREAD_NAME_PREFIX, task.lastThread.getName().substring(0, THREAD_NAME_PREFIX.length())); + assertThat(task.lastThread.getName().substring(0, THREAD_NAME_PREFIX.length())).isEqualTo(THREAD_NAME_PREFIX); } private void await(TestTask task) { @@ -242,7 +239,7 @@ public abstract class AbstractSchedulingTaskExecutorTests { catch (InterruptedException ex) { throw new IllegalStateException(ex); } - assertEquals("latch did not count down,", 0, latch.getCount()); + assertThat(latch.getCount()).as("latch did not count down,").isEqualTo(0); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java index da2247ca894..424ef91aae7 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java @@ -27,9 +27,8 @@ import org.springframework.core.task.NoOpRunnable; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; @@ -195,7 +194,7 @@ public class ScheduledExecutorFactoryBeanTests { ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() { @Override protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) { - assertNotNull("Bah; the setThreadFactory(..) method must use a default ThreadFactory if a null arg is passed in."); + assertThat("Bah; the setThreadFactory(..) method must use a default ThreadFactory if a null arg is passed in.").isNotNull(); return super.createExecutor(poolSize, threadFactory, rejectedExecutionHandler); } }; @@ -213,7 +212,7 @@ public class ScheduledExecutorFactoryBeanTests { ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() { @Override protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) { - assertNotNull("Bah; the setRejectedExecutionHandler(..) method must use a default RejectedExecutionHandler if a null arg is passed in."); + assertThat("Bah; the setRejectedExecutionHandler(..) method must use a default RejectedExecutionHandler if a null arg is passed in.").isNotNull(); return super.createExecutor(poolSize, threadFactory, rejectedExecutionHandler); } }; @@ -228,7 +227,7 @@ public class ScheduledExecutorFactoryBeanTests { @Test public void testObjectTypeReportsCorrectType() throws Exception { ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean(); - assertEquals(ScheduledExecutorService.class, factory.getObjectType()); + assertThat(factory.getObjectType()).isEqualTo(ScheduledExecutorService.class); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolExecutorFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolExecutorFactoryBeanTests.java index c114f44aaba..322578efd9c 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolExecutorFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolExecutorFactoryBeanTests.java @@ -26,7 +26,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -40,7 +40,7 @@ public class ThreadPoolExecutorFactoryBeanTests { FutureTask task = new FutureTask<>(() -> "foo"); executor.execute(task); - assertEquals("foo", task.get()); + assertThat(task.get()).isEqualTo("foo"); context.close(); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java index 7ee86c3d907..fefb94aa1c4 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java @@ -31,11 +31,8 @@ import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.util.ErrorHandler; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * @author Mark Fisher @@ -62,7 +59,7 @@ public class ThreadPoolTaskSchedulerTests extends AbstractSchedulingTaskExecutor scheduler.setErrorHandler(errorHandler); scheduler.execute(task); await(errorHandler); - assertNotNull(errorHandler.lastError); + assertThat(errorHandler.lastError).isNotNull(); } @Test @@ -72,9 +69,9 @@ public class ThreadPoolTaskSchedulerTests extends AbstractSchedulingTaskExecutor scheduler.setErrorHandler(errorHandler); Future future = scheduler.submit(task); Object result = future.get(1000, TimeUnit.MILLISECONDS); - assertTrue(future.isDone()); - assertNull(result); - assertNotNull(errorHandler.lastError); + assertThat(future.isDone()).isTrue(); + assertThat(result).isNull(); + assertThat(errorHandler.lastError).isNotNull(); } @Test @@ -84,9 +81,9 @@ public class ThreadPoolTaskSchedulerTests extends AbstractSchedulingTaskExecutor scheduler.setErrorHandler(errorHandler); Future future = scheduler.submit(task); Object result = future.get(1000, TimeUnit.MILLISECONDS); - assertTrue(future.isDone()); - assertNull(result); - assertNotNull(errorHandler.lastError); + assertThat(future.isDone()).isTrue(); + assertThat(result).isNull(); + assertThat(errorHandler.lastError).isNotNull(); } @Test @@ -94,8 +91,8 @@ public class ThreadPoolTaskSchedulerTests extends AbstractSchedulingTaskExecutor TestTask task = new TestTask(1); Future future = scheduler.schedule(task, new Date()); Object result = future.get(1000, TimeUnit.MILLISECONDS); - assertNull(result); - assertTrue(future.isDone()); + assertThat(result).isNull(); + assertThat(future.isDone()).isTrue(); assertThreadNamePrefix(task); } @@ -105,7 +102,7 @@ public class ThreadPoolTaskSchedulerTests extends AbstractSchedulingTaskExecutor Future future = scheduler.schedule(task, new Date()); assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> future.get(1000, TimeUnit.MILLISECONDS)); - assertTrue(future.isDone()); + assertThat(future.isDone()).isTrue(); } @Test @@ -115,9 +112,9 @@ public class ThreadPoolTaskSchedulerTests extends AbstractSchedulingTaskExecutor scheduler.setErrorHandler(errorHandler); Future future = scheduler.schedule(task, new Date()); Object result = future.get(1000, TimeUnit.MILLISECONDS); - assertTrue(future.isDone()); - assertNull(result); - assertNotNull(errorHandler.lastError); + assertThat(future.isDone()).isTrue(); + assertThat(result).isNull(); + assertThat(errorHandler.lastError).isNotNull(); } @Test @@ -125,7 +122,7 @@ public class ThreadPoolTaskSchedulerTests extends AbstractSchedulingTaskExecutor TestTask task = new TestTask(3); Future future = scheduler.schedule(task, new TestTrigger(3)); Object result = future.get(1000, TimeUnit.MILLISECONDS); - assertNull(result); + assertThat(result).isNull(); await(task); assertThreadNamePrefix(task); } @@ -139,7 +136,7 @@ public class ThreadPoolTaskSchedulerTests extends AbstractSchedulingTaskExecutor private void assertThreadNamePrefix(TestTask task) { - assertEquals(THREAD_NAME_PREFIX, task.lastThread.getName().substring(0, THREAD_NAME_PREFIX.length())); + assertThat(task.lastThread.getName().substring(0, THREAD_NAME_PREFIX.length())).isEqualTo(THREAD_NAME_PREFIX); } private void await(TestTask task) { @@ -157,7 +154,7 @@ public class ThreadPoolTaskSchedulerTests extends AbstractSchedulingTaskExecutor catch (InterruptedException ex) { throw new IllegalStateException(ex); } - assertEquals("latch did not count down,", 0, latch.getCount()); + assertThat(latch.getCount()).as("latch did not count down,").isEqualTo(0); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/config/AnnotationDrivenBeanDefinitionParserTests.java b/spring-context/src/test/java/org/springframework/scheduling/config/AnnotationDrivenBeanDefinitionParserTests.java index 93a3bbfe59d..759f24b433c 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/config/AnnotationDrivenBeanDefinitionParserTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/config/AnnotationDrivenBeanDefinitionParserTests.java @@ -25,8 +25,7 @@ import org.springframework.beans.DirectFieldAccessor; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -46,33 +45,33 @@ public class AnnotationDrivenBeanDefinitionParserTests { @Test public void asyncPostProcessorRegistered() { - assertTrue(context.containsBean(TaskManagementConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME)); + assertThat(context.containsBean(TaskManagementConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); } @Test public void scheduledPostProcessorRegistered() { - assertTrue(context.containsBean(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)); + assertThat(context.containsBean(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)).isTrue(); } @Test public void asyncPostProcessorExecutorReference() { Object executor = context.getBean("testExecutor"); Object postProcessor = context.getBean(TaskManagementConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME); - assertSame(executor, ((Supplier) new DirectFieldAccessor(postProcessor).getPropertyValue("executor")).get()); + assertThat(((Supplier) new DirectFieldAccessor(postProcessor).getPropertyValue("executor")).get()).isSameAs(executor); } @Test public void scheduledPostProcessorSchedulerReference() { Object scheduler = context.getBean("testScheduler"); Object postProcessor = context.getBean(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME); - assertSame(scheduler, new DirectFieldAccessor(postProcessor).getPropertyValue("scheduler")); + assertThat(new DirectFieldAccessor(postProcessor).getPropertyValue("scheduler")).isSameAs(scheduler); } @Test public void asyncPostProcessorExceptionHandlerReference() { Object exceptionHandler = context.getBean("testExceptionHandler"); Object postProcessor = context.getBean(TaskManagementConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME); - assertSame(exceptionHandler, ((Supplier) new DirectFieldAccessor(postProcessor).getPropertyValue("exceptionHandler")).get()); + assertThat(((Supplier) new DirectFieldAccessor(postProcessor).getPropertyValue("exceptionHandler")).get()).isSameAs(exceptionHandler); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/config/ExecutorBeanDefinitionParserTests.java b/spring-context/src/test/java/org/springframework/scheduling/config/ExecutorBeanDefinitionParserTests.java index 284080b5833..2919a286217 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/config/ExecutorBeanDefinitionParserTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/config/ExecutorBeanDefinitionParserTests.java @@ -31,9 +31,8 @@ import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.util.CustomizableThreadCreator; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Mark Fisher @@ -54,11 +53,11 @@ public class ExecutorBeanDefinitionParserTests { @Test public void defaultExecutor() throws Exception { ThreadPoolTaskExecutor executor = this.context.getBean("default", ThreadPoolTaskExecutor.class); - assertEquals(1, getCorePoolSize(executor)); - assertEquals(Integer.MAX_VALUE, getMaxPoolSize(executor)); - assertEquals(Integer.MAX_VALUE, getQueueCapacity(executor)); - assertEquals(60, getKeepAliveSeconds(executor)); - assertEquals(false, getAllowCoreThreadTimeOut(executor)); + assertThat(getCorePoolSize(executor)).isEqualTo(1); + assertThat(getMaxPoolSize(executor)).isEqualTo(Integer.MAX_VALUE); + assertThat(getQueueCapacity(executor)).isEqualTo(Integer.MAX_VALUE); + assertThat(getKeepAliveSeconds(executor)).isEqualTo(60); + assertThat(getAllowCoreThreadTimeOut(executor)).isEqualTo(false); FutureTask task = new FutureTask<>(new Callable() { @Override @@ -67,14 +66,14 @@ public class ExecutorBeanDefinitionParserTests { } }); executor.execute(task); - assertEquals("foo", task.get()); + assertThat(task.get()).isEqualTo("foo"); } @Test public void singleSize() { Object executor = this.context.getBean("singleSize"); - assertEquals(42, getCorePoolSize(executor)); - assertEquals(42, getMaxPoolSize(executor)); + assertThat(getCorePoolSize(executor)).isEqualTo(42); + assertThat(getMaxPoolSize(executor)).isEqualTo(42); } @Test @@ -86,46 +85,46 @@ public class ExecutorBeanDefinitionParserTests { @Test public void rangeWithBoundedQueue() { Object executor = this.context.getBean("rangeWithBoundedQueue"); - assertEquals(7, getCorePoolSize(executor)); - assertEquals(42, getMaxPoolSize(executor)); - assertEquals(11, getQueueCapacity(executor)); + assertThat(getCorePoolSize(executor)).isEqualTo(7); + assertThat(getMaxPoolSize(executor)).isEqualTo(42); + assertThat(getQueueCapacity(executor)).isEqualTo(11); } @Test public void rangeWithUnboundedQueue() { Object executor = this.context.getBean("rangeWithUnboundedQueue"); - assertEquals(9, getCorePoolSize(executor)); - assertEquals(9, getMaxPoolSize(executor)); - assertEquals(37, getKeepAliveSeconds(executor)); - assertEquals(true, getAllowCoreThreadTimeOut(executor)); - assertEquals(Integer.MAX_VALUE, getQueueCapacity(executor)); + assertThat(getCorePoolSize(executor)).isEqualTo(9); + assertThat(getMaxPoolSize(executor)).isEqualTo(9); + assertThat(getKeepAliveSeconds(executor)).isEqualTo(37); + assertThat(getAllowCoreThreadTimeOut(executor)).isEqualTo(true); + assertThat(getQueueCapacity(executor)).isEqualTo(Integer.MAX_VALUE); } @Test public void propertyPlaceholderWithSingleSize() { Object executor = this.context.getBean("propertyPlaceholderWithSingleSize"); - assertEquals(123, getCorePoolSize(executor)); - assertEquals(123, getMaxPoolSize(executor)); - assertEquals(60, getKeepAliveSeconds(executor)); - assertEquals(false, getAllowCoreThreadTimeOut(executor)); - assertEquals(Integer.MAX_VALUE, getQueueCapacity(executor)); + assertThat(getCorePoolSize(executor)).isEqualTo(123); + assertThat(getMaxPoolSize(executor)).isEqualTo(123); + assertThat(getKeepAliveSeconds(executor)).isEqualTo(60); + assertThat(getAllowCoreThreadTimeOut(executor)).isEqualTo(false); + assertThat(getQueueCapacity(executor)).isEqualTo(Integer.MAX_VALUE); } @Test public void propertyPlaceholderWithRange() { Object executor = this.context.getBean("propertyPlaceholderWithRange"); - assertEquals(5, getCorePoolSize(executor)); - assertEquals(25, getMaxPoolSize(executor)); - assertEquals(false, getAllowCoreThreadTimeOut(executor)); - assertEquals(10, getQueueCapacity(executor)); + assertThat(getCorePoolSize(executor)).isEqualTo(5); + assertThat(getMaxPoolSize(executor)).isEqualTo(25); + assertThat(getAllowCoreThreadTimeOut(executor)).isEqualTo(false); + assertThat(getQueueCapacity(executor)).isEqualTo(10); } @Test public void propertyPlaceholderWithRangeAndCoreThreadTimeout() { Object executor = this.context.getBean("propertyPlaceholderWithRangeAndCoreThreadTimeout"); - assertEquals(99, getCorePoolSize(executor)); - assertEquals(99, getMaxPoolSize(executor)); - assertEquals(true, getAllowCoreThreadTimeOut(executor)); + assertThat(getCorePoolSize(executor)).isEqualTo(99); + assertThat(getMaxPoolSize(executor)).isEqualTo(99); + assertThat(getAllowCoreThreadTimeOut(executor)).isEqualTo(true); } @Test @@ -137,14 +136,14 @@ public class ExecutorBeanDefinitionParserTests { @Test public void threadNamePrefix() { CustomizableThreadCreator executor = this.context.getBean("default", CustomizableThreadCreator.class); - assertEquals("default-", executor.getThreadNamePrefix()); + assertThat(executor.getThreadNamePrefix()).isEqualTo("default-"); } @Test public void typeCheck() { - assertTrue(this.context.isTypeMatch("default", Executor.class)); - assertTrue(this.context.isTypeMatch("default", TaskExecutor.class)); - assertTrue(this.context.isTypeMatch("default", ThreadPoolTaskExecutor.class)); + assertThat(this.context.isTypeMatch("default", Executor.class)).isTrue(); + assertThat(this.context.isTypeMatch("default", TaskExecutor.class)).isTrue(); + assertThat(this.context.isTypeMatch("default", ThreadPoolTaskExecutor.class)).isTrue(); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTaskRegistrarTests.java b/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTaskRegistrarTests.java index 6e0a560ef55..832a9bd45e3 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTaskRegistrarTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTaskRegistrarTests.java @@ -21,8 +21,7 @@ import java.util.List; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -39,10 +38,10 @@ public class ScheduledTaskRegistrarTests { @Test public void emptyTaskLists() { - assertTrue(this.taskRegistrar.getTriggerTaskList().isEmpty()); - assertTrue(this.taskRegistrar.getCronTaskList().isEmpty()); - assertTrue(this.taskRegistrar.getFixedRateTaskList().isEmpty()); - assertTrue(this.taskRegistrar.getFixedDelayTaskList().isEmpty()); + assertThat(this.taskRegistrar.getTriggerTaskList().isEmpty()).isTrue(); + assertThat(this.taskRegistrar.getCronTaskList().isEmpty()).isTrue(); + assertThat(this.taskRegistrar.getFixedRateTaskList().isEmpty()).isTrue(); + assertThat(this.taskRegistrar.getFixedDelayTaskList().isEmpty()).isTrue(); } @Test @@ -51,8 +50,8 @@ public class ScheduledTaskRegistrarTests { List triggerTaskList = Collections.singletonList(mockTriggerTask); this.taskRegistrar.setTriggerTasksList(triggerTaskList); List retrievedList = this.taskRegistrar.getTriggerTaskList(); - assertEquals(1, retrievedList.size()); - assertEquals(mockTriggerTask, retrievedList.get(0)); + assertThat(retrievedList.size()).isEqualTo(1); + assertThat(retrievedList.get(0)).isEqualTo(mockTriggerTask); } @Test @@ -61,8 +60,8 @@ public class ScheduledTaskRegistrarTests { List cronTaskList = Collections.singletonList(mockCronTask); this.taskRegistrar.setCronTasksList(cronTaskList); List retrievedList = this.taskRegistrar.getCronTaskList(); - assertEquals(1, retrievedList.size()); - assertEquals(mockCronTask, retrievedList.get(0)); + assertThat(retrievedList.size()).isEqualTo(1); + assertThat(retrievedList.get(0)).isEqualTo(mockCronTask); } @Test @@ -71,8 +70,8 @@ public class ScheduledTaskRegistrarTests { List fixedRateTaskList = Collections.singletonList(mockFixedRateTask); this.taskRegistrar.setFixedRateTasksList(fixedRateTaskList); List retrievedList = this.taskRegistrar.getFixedRateTaskList(); - assertEquals(1, retrievedList.size()); - assertEquals(mockFixedRateTask, retrievedList.get(0)); + assertThat(retrievedList.size()).isEqualTo(1); + assertThat(retrievedList.get(0)).isEqualTo(mockFixedRateTask); } @Test @@ -81,8 +80,8 @@ public class ScheduledTaskRegistrarTests { List fixedDelayTaskList = Collections.singletonList(mockFixedDelayTask); this.taskRegistrar.setFixedDelayTasksList(fixedDelayTaskList); List retrievedList = this.taskRegistrar.getFixedDelayTaskList(); - assertEquals(1, retrievedList.size()); - assertEquals(mockFixedDelayTask, retrievedList.get(0)); + assertThat(retrievedList.size()).isEqualTo(1); + assertThat(retrievedList.get(0)).isEqualTo(mockFixedDelayTask); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java b/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java index 29b52734f16..ce2e34440e6 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java @@ -31,7 +31,6 @@ import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.support.ScheduledMethodRunnable; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * @author Mark Fisher @@ -60,7 +59,7 @@ public class ScheduledTasksBeanDefinitionParserTests { public void checkScheduler() { Object schedulerBean = this.context.getBean("testScheduler"); Object schedulerRef = new DirectFieldAccessor(this.registrar).getPropertyValue("taskScheduler"); - assertEquals(schedulerBean, schedulerRef); + assertThat(schedulerRef).isEqualTo(schedulerBean); } @Test @@ -68,47 +67,47 @@ public class ScheduledTasksBeanDefinitionParserTests { List tasks = (List) new DirectFieldAccessor( this.registrar).getPropertyValue("fixedRateTasks"); Runnable runnable = tasks.get(0).getRunnable(); - assertEquals(ScheduledMethodRunnable.class, runnable.getClass()); + assertThat(runnable.getClass()).isEqualTo(ScheduledMethodRunnable.class); Object targetObject = ((ScheduledMethodRunnable) runnable).getTarget(); Method targetMethod = ((ScheduledMethodRunnable) runnable).getMethod(); - assertEquals(this.testBean, targetObject); - assertEquals("test", targetMethod.getName()); + assertThat(targetObject).isEqualTo(this.testBean); + assertThat(targetMethod.getName()).isEqualTo("test"); } @Test public void fixedRateTasks() { List tasks = (List) new DirectFieldAccessor( this.registrar).getPropertyValue("fixedRateTasks"); - assertEquals(3, tasks.size()); - assertEquals(1000L, tasks.get(0).getInterval()); - assertEquals(2000L, tasks.get(1).getInterval()); - assertEquals(4000L, tasks.get(2).getInterval()); - assertEquals(500, tasks.get(2).getInitialDelay()); + assertThat(tasks.size()).isEqualTo(3); + assertThat(tasks.get(0).getInterval()).isEqualTo(1000L); + assertThat(tasks.get(1).getInterval()).isEqualTo(2000L); + assertThat(tasks.get(2).getInterval()).isEqualTo(4000L); + assertThat(tasks.get(2).getInitialDelay()).isEqualTo(500); } @Test public void fixedDelayTasks() { List tasks = (List) new DirectFieldAccessor( this.registrar).getPropertyValue("fixedDelayTasks"); - assertEquals(2, tasks.size()); - assertEquals(3000L, tasks.get(0).getInterval()); - assertEquals(3500L, tasks.get(1).getInterval()); - assertEquals(250, tasks.get(1).getInitialDelay()); + assertThat(tasks.size()).isEqualTo(2); + assertThat(tasks.get(0).getInterval()).isEqualTo(3000L); + assertThat(tasks.get(1).getInterval()).isEqualTo(3500L); + assertThat(tasks.get(1).getInitialDelay()).isEqualTo(250); } @Test public void cronTasks() { List tasks = (List) new DirectFieldAccessor( this.registrar).getPropertyValue("cronTasks"); - assertEquals(1, tasks.size()); - assertEquals("*/4 * 9-17 * * MON-FRI", tasks.get(0).getExpression()); + assertThat(tasks.size()).isEqualTo(1); + assertThat(tasks.get(0).getExpression()).isEqualTo("*/4 * 9-17 * * MON-FRI"); } @Test public void triggerTasks() { List tasks = (List) new DirectFieldAccessor( this.registrar).getPropertyValue("triggerTasks"); - assertEquals(1, tasks.size()); + assertThat(tasks.size()).isEqualTo(1); assertThat(tasks.get(0).getTrigger()).isInstanceOf(TestTrigger.class); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/config/SchedulerBeanDefinitionParserTests.java b/spring-context/src/test/java/org/springframework/scheduling/config/SchedulerBeanDefinitionParserTests.java index 591aa914184..2649618f2ca 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/config/SchedulerBeanDefinitionParserTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/config/SchedulerBeanDefinitionParserTests.java @@ -24,7 +24,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -44,20 +44,20 @@ public class SchedulerBeanDefinitionParserTests { public void defaultScheduler() { ThreadPoolTaskScheduler scheduler = (ThreadPoolTaskScheduler) this.context.getBean("defaultScheduler"); Integer size = (Integer) new DirectFieldAccessor(scheduler).getPropertyValue("poolSize"); - assertEquals(new Integer(1), size); + assertThat(size).isEqualTo(new Integer(1)); } @Test public void customScheduler() { ThreadPoolTaskScheduler scheduler = (ThreadPoolTaskScheduler) this.context.getBean("customScheduler"); Integer size = (Integer) new DirectFieldAccessor(scheduler).getPropertyValue("poolSize"); - assertEquals(new Integer(42), size); + assertThat(size).isEqualTo(new Integer(42)); } @Test public void threadNamePrefix() { ThreadPoolTaskScheduler scheduler = (ThreadPoolTaskScheduler) this.context.getBean("customScheduler"); - assertEquals("customScheduler-", scheduler.getThreadNamePrefix()); + assertThat(scheduler.getThreadNamePrefix()).isEqualTo("customScheduler-"); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java index 500b04519ad..994b24ec917 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java @@ -20,10 +20,8 @@ import java.util.Date; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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 Juergen Hoeller @@ -34,20 +32,17 @@ public class CronSequenceGeneratorTests { @Test public void at50Seconds() { - assertEquals(new Date(2012, 6, 2, 1, 0), - new CronSequenceGenerator("*/15 * 1-4 * * *").next(new Date(2012, 6, 1, 9, 53, 50))); + assertThat(new CronSequenceGenerator("*/15 * 1-4 * * *").next(new Date(2012, 6, 1, 9, 53, 50))).isEqualTo(new Date(2012, 6, 2, 1, 0)); } @Test public void at0Seconds() { - assertEquals(new Date(2012, 6, 2, 1, 0), - new CronSequenceGenerator("*/15 * 1-4 * * *").next(new Date(2012, 6, 1, 9, 53))); + assertThat(new CronSequenceGenerator("*/15 * 1-4 * * *").next(new Date(2012, 6, 1, 9, 53))).isEqualTo(new Date(2012, 6, 2, 1, 0)); } @Test public void at0Minutes() { - assertEquals(new Date(2012, 6, 2, 1, 0), - new CronSequenceGenerator("0 */2 1-4 * * *").next(new Date(2012, 6, 1, 9, 0))); + assertThat(new CronSequenceGenerator("0 */2 1-4 * * *").next(new Date(2012, 6, 1, 9, 0))).isEqualTo(new Date(2012, 6, 2, 1, 0)); } @Test @@ -86,27 +81,27 @@ public class CronSequenceGeneratorTests { @Test public void validExpression() { - assertTrue(CronSequenceGenerator.isValidExpression("0 */2 1-4 * * *")); + assertThat(CronSequenceGenerator.isValidExpression("0 */2 1-4 * * *")).isTrue(); } @Test public void invalidExpressionWithLength() { - assertFalse(CronSequenceGenerator.isValidExpression("0 */2 1-4 * * * *")); + assertThat(CronSequenceGenerator.isValidExpression("0 */2 1-4 * * * *")).isFalse(); } @Test public void invalidExpressionWithSeconds() { - assertFalse(CronSequenceGenerator.isValidExpression("100 */2 1-4 * * *")); + assertThat(CronSequenceGenerator.isValidExpression("100 */2 1-4 * * *")).isFalse(); } @Test public void invalidExpressionWithMonths() { - assertFalse(CronSequenceGenerator.isValidExpression("0 */2 1-4 * INVALID *")); + assertThat(CronSequenceGenerator.isValidExpression("0 */2 1-4 * INVALID *")).isFalse(); } @Test public void nullExpression() { - assertFalse(CronSequenceGenerator.isValidExpression(null)); + assertThat(CronSequenceGenerator.isValidExpression(null)).isFalse(); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java index 26f1b334dc5..afe35ef4178 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java @@ -31,8 +31,8 @@ import org.junit.runners.Parameterized.Parameters; import org.springframework.scheduling.TriggerContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @author Dave Syer @@ -79,7 +79,7 @@ public class CronTriggerTests { public void testMatchAll() throws Exception { CronTrigger trigger = new CronTrigger("* * * * * *", timeZone); TriggerContext context = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); } @Test @@ -105,7 +105,7 @@ public class CronTriggerTests { Date date = calendar.getTime(); calendar.add(Calendar.SECOND, 1); TriggerContext context = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); } @Test @@ -116,7 +116,7 @@ public class CronTriggerTests { context.update(calendar.getTime(), new Date(calendar.getTimeInMillis() - 100), new Date(calendar.getTimeInMillis() - 90)); calendar.add(Calendar.MINUTE, 1); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); } @Test @@ -126,7 +126,7 @@ public class CronTriggerTests { Date date = calendar.getTime(); calendar.add(Calendar.SECOND, 59); TriggerContext context = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); } @Test @@ -147,11 +147,11 @@ public class CronTriggerTests { calendar.set(Calendar.SECOND, 0); TriggerContext context1 = getTriggerContext(date); date = trigger.nextExecutionTime(context1); - assertEquals(calendar.getTime(), date); + assertThat(date).isEqualTo(calendar.getTime()); calendar.add(Calendar.MINUTE, 1); TriggerContext context2 = getTriggerContext(date); date = trigger.nextExecutionTime(context2); - assertEquals(calendar.getTime(), date); + assertThat(date).isEqualTo(calendar.getTime()); } @Test @@ -161,7 +161,7 @@ public class CronTriggerTests { TriggerContext context = getTriggerContext(calendar.getTime()); calendar.add(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); } @Test @@ -172,7 +172,7 @@ public class CronTriggerTests { Date date = calendar.getTime(); calendar.add(Calendar.MINUTE, 59); TriggerContext context = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); } @Test @@ -187,10 +187,11 @@ public class CronTriggerTests { calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 12); TriggerContext context1 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual = date = trigger.nextExecutionTime(context1); + assertThat(actual).isEqualTo(calendar.getTime()); calendar.set(Calendar.HOUR_OF_DAY, 13); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context2)); + assertThat(trigger.nextExecutionTime(context2)).isEqualTo(calendar.getTime()); } @Test @@ -206,10 +207,11 @@ public class CronTriggerTests { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.DAY_OF_MONTH, 11); TriggerContext context1 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual = date = trigger.nextExecutionTime(context1); + assertThat(actual).isEqualTo(calendar.getTime()); calendar.set(Calendar.HOUR_OF_DAY, 1); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context2)); + assertThat(trigger.nextExecutionTime(context2)).isEqualTo(calendar.getTime()); } @Test @@ -222,12 +224,14 @@ public class CronTriggerTests { calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); TriggerContext context1 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); - assertEquals(2, calendar.get(Calendar.DAY_OF_MONTH)); + Object actual1 = date = trigger.nextExecutionTime(context1); + assertThat(actual1).isEqualTo(calendar.getTime()); + assertThat(calendar.get(Calendar.DAY_OF_MONTH)).isEqualTo(2); calendar.add(Calendar.DAY_OF_MONTH, 1); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2)); - assertEquals(3, calendar.get(Calendar.DAY_OF_MONTH)); + Object actual = date = trigger.nextExecutionTime(context2); + assertThat(actual).isEqualTo(calendar.getTime()); + assertThat(calendar.get(Calendar.DAY_OF_MONTH)).isEqualTo(3); } @Test @@ -240,7 +244,7 @@ public class CronTriggerTests { calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); TriggerContext context = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); } @Test @@ -254,7 +258,7 @@ public class CronTriggerTests { calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); TriggerContext context = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); } @Test @@ -269,10 +273,11 @@ public class CronTriggerTests { calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.DAY_OF_MONTH, 1); TriggerContext context1 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual = date = trigger.nextExecutionTime(context1); + assertThat(actual).isEqualTo(calendar.getTime()); calendar.set(Calendar.DAY_OF_MONTH, 2); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context2)); + assertThat(trigger.nextExecutionTime(context2)).isEqualTo(calendar.getTime()); } @Test @@ -286,11 +291,12 @@ public class CronTriggerTests { calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.DAY_OF_MONTH, 31); TriggerContext context1 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual = date = trigger.nextExecutionTime(context1); + assertThat(actual).isEqualTo(calendar.getTime()); calendar.set(Calendar.MONTH, 8); // September calendar.set(Calendar.DAY_OF_MONTH, 1); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context2)); + assertThat(trigger.nextExecutionTime(context2)).isEqualTo(calendar.getTime()); } @Test @@ -304,11 +310,12 @@ public class CronTriggerTests { calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.DAY_OF_MONTH, 31); TriggerContext context1 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual = date = trigger.nextExecutionTime(context1); + assertThat(actual).isEqualTo(calendar.getTime()); calendar.set(Calendar.MONTH, 10); // November calendar.set(Calendar.DAY_OF_MONTH, 1); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context2)); + assertThat(trigger.nextExecutionTime(context2)).isEqualTo(calendar.getTime()); } @Test @@ -323,10 +330,11 @@ public class CronTriggerTests { calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MONTH, 10); TriggerContext context1 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual = date = trigger.nextExecutionTime(context1); + assertThat(actual).isEqualTo(calendar.getTime()); calendar.set(Calendar.MONTH, 11); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context2)); + assertThat(trigger.nextExecutionTime(context2)).isEqualTo(calendar.getTime()); } @Test @@ -343,10 +351,11 @@ public class CronTriggerTests { calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.YEAR, 2011); TriggerContext context1 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual = date = trigger.nextExecutionTime(context1); + assertThat(actual).isEqualTo(calendar.getTime()); calendar.set(Calendar.MONTH, 1); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context2)); + assertThat(trigger.nextExecutionTime(context2)).isEqualTo(calendar.getTime()); } @Test @@ -360,7 +369,7 @@ public class CronTriggerTests { calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); TriggerContext context = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); } @Test @@ -375,7 +384,7 @@ public class CronTriggerTests { calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); TriggerContext context = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); } @Test @@ -388,8 +397,8 @@ public class CronTriggerTests { calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); TriggerContext context = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); - assertEquals(Calendar.TUESDAY, calendar.get(Calendar.DAY_OF_WEEK)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); + assertThat(calendar.get(Calendar.DAY_OF_WEEK)).isEqualTo(Calendar.TUESDAY); } @Test @@ -402,8 +411,8 @@ public class CronTriggerTests { calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); TriggerContext context = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); - assertEquals(Calendar.TUESDAY, calendar.get(Calendar.DAY_OF_WEEK)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); + assertThat(calendar.get(Calendar.DAY_OF_WEEK)).isEqualTo(Calendar.TUESDAY); } @Test @@ -415,10 +424,12 @@ public class CronTriggerTests { TriggerContext context1 = getTriggerContext(date); calendar.add(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 55); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual1 = date = trigger.nextExecutionTime(context1); + assertThat(actual1).isEqualTo(calendar.getTime()); calendar.add(Calendar.HOUR, 1); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2)); + Object actual = date = trigger.nextExecutionTime(context2); + assertThat(actual).isEqualTo(calendar.getTime()); } @Test @@ -431,10 +442,12 @@ public class CronTriggerTests { calendar.add(Calendar.HOUR_OF_DAY, 1); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 55); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual1 = date = trigger.nextExecutionTime(context1); + assertThat(actual1).isEqualTo(calendar.getTime()); calendar.add(Calendar.MINUTE, 1); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2)); + Object actual = date = trigger.nextExecutionTime(context2); + assertThat(actual).isEqualTo(calendar.getTime()); } @Test @@ -447,11 +460,13 @@ public class CronTriggerTests { calendar.add(Calendar.HOUR_OF_DAY, 1); calendar.set(Calendar.SECOND, 0); TriggerContext context1 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual1 = date = trigger.nextExecutionTime(context1); + assertThat(actual1).isEqualTo(calendar.getTime()); // next trigger is in one second because second is wildcard calendar.add(Calendar.SECOND, 1); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2)); + Object actual = date = trigger.nextExecutionTime(context2); + assertThat(actual).isEqualTo(calendar.getTime()); } @Test @@ -465,10 +480,12 @@ public class CronTriggerTests { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 55); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual1 = date = trigger.nextExecutionTime(context1); + assertThat(actual1).isEqualTo(calendar.getTime()); calendar.add(Calendar.MINUTE, 1); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2)); + Object actual = date = trigger.nextExecutionTime(context2); + assertThat(actual).isEqualTo(calendar.getTime()); } @Test @@ -483,10 +500,12 @@ public class CronTriggerTests { calendar.set(Calendar.MONTH, 10); // 10=November calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual1 = date = trigger.nextExecutionTime(context1); + assertThat(actual1).isEqualTo(calendar.getTime()); calendar.add(Calendar.SECOND, 1); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2)); + Object actual = date = trigger.nextExecutionTime(context2); + assertThat(actual).isEqualTo(calendar.getTime()); } @Test @@ -515,10 +534,12 @@ public class CronTriggerTests { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual1 = date = trigger.nextExecutionTime(context1); + assertThat(actual1).isEqualTo(calendar.getTime()); calendar.add(Calendar.YEAR, 4); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2)); + Object actual = date = trigger.nextExecutionTime(context2); + assertThat(actual).isEqualTo(calendar.getTime()); } @Test @@ -534,77 +555,80 @@ public class CronTriggerTests { // Add two days because we start on Saturday calendar.add(Calendar.DAY_OF_MONTH, 2); TriggerContext context1 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual2 = date = trigger.nextExecutionTime(context1); + assertThat(actual2).isEqualTo(calendar.getTime()); // Next day is a week day so add one calendar.add(Calendar.DAY_OF_MONTH, 1); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2)); + Object actual1 = date = trigger.nextExecutionTime(context2); + assertThat(actual1).isEqualTo(calendar.getTime()); calendar.add(Calendar.DAY_OF_MONTH, 1); TriggerContext context3 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context3)); + Object actual = date = trigger.nextExecutionTime(context3); + assertThat(actual).isEqualTo(calendar.getTime()); } @Test public void testDayOfWeekIndifferent() throws Exception { CronTrigger trigger1 = new CronTrigger("* * * 2 * *", timeZone); CronTrigger trigger2 = new CronTrigger("* * * 2 * ?", timeZone); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); } @Test public void testSecondIncrementer() throws Exception { CronTrigger trigger1 = new CronTrigger("57,59 * * * * *", timeZone); CronTrigger trigger2 = new CronTrigger("57/2 * * * * *", timeZone); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); } @Test public void testSecondIncrementerWithRange() throws Exception { CronTrigger trigger1 = new CronTrigger("1,3,5 * * * * *", timeZone); CronTrigger trigger2 = new CronTrigger("1-6/2 * * * * *", timeZone); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); } @Test public void testHourIncrementer() throws Exception { CronTrigger trigger1 = new CronTrigger("* * 4,8,12,16,20 * * *", timeZone); CronTrigger trigger2 = new CronTrigger("* * 4/4 * * *", timeZone); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); } @Test public void testDayNames() throws Exception { CronTrigger trigger1 = new CronTrigger("* * * * * 0-6", timeZone); CronTrigger trigger2 = new CronTrigger("* * * * * TUE,WED,THU,FRI,SAT,SUN,MON", timeZone); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); } @Test public void testSundayIsZero() throws Exception { CronTrigger trigger1 = new CronTrigger("* * * * * 0", timeZone); CronTrigger trigger2 = new CronTrigger("* * * * * SUN", timeZone); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); } @Test public void testSundaySynonym() throws Exception { CronTrigger trigger1 = new CronTrigger("* * * * * 0", timeZone); CronTrigger trigger2 = new CronTrigger("* * * * * 7", timeZone); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); } @Test public void testMonthNames() throws Exception { CronTrigger trigger1 = new CronTrigger("* * * * 1-12 *", timeZone); CronTrigger trigger2 = new CronTrigger("* * * * FEB,JAN,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC *", timeZone); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); } @Test public void testMonthNamesMixedCase() throws Exception { CronTrigger trigger1 = new CronTrigger("* * * * 2 *", timeZone); CronTrigger trigger2 = new CronTrigger("* * * * Feb *", timeZone); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); } @Test @@ -683,7 +707,7 @@ public class CronTriggerTests { public void testWhitespace() throws Exception { CronTrigger trigger1 = new CronTrigger("* * * * 1 *", timeZone); CronTrigger trigger2 = new CronTrigger("* * * * 1 *", timeZone); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); } @Test @@ -697,15 +721,18 @@ public class CronTriggerTests { calendar.set(Calendar.SECOND, 0); calendar.add(Calendar.MONTH, 1); TriggerContext context1 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual2 = date = trigger.nextExecutionTime(context1); + assertThat(actual2).isEqualTo(calendar.getTime()); // Next trigger is 3 months latter calendar.add(Calendar.MONTH, 3); TriggerContext context2 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2)); + Object actual1 = date = trigger.nextExecutionTime(context2); + assertThat(actual1).isEqualTo(calendar.getTime()); // Next trigger is 3 months latter calendar.add(Calendar.MONTH, 3); TriggerContext context3 = getTriggerContext(date); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context3)); + Object actual = date = trigger.nextExecutionTime(context3); + assertThat(actual).isEqualTo(calendar.getTime()); } @Test @@ -726,14 +753,15 @@ public class CronTriggerTests { calendar.add(Calendar.HOUR_OF_DAY, 1); calendar.set(Calendar.MINUTE, 10); calendar.set(Calendar.SECOND, 0); - assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + Object actual = date = trigger.nextExecutionTime(context1); + assertThat(actual).isEqualTo(calendar.getTime()); } private void assertMatchesNextSecond(CronTrigger trigger, Calendar calendar) { Date date = calendar.getTime(); roundup(calendar); TriggerContext context = getTriggerContext(date); - assertEquals(calendar.getTime(), trigger.nextExecutionTime(context)); + assertThat(trigger.nextExecutionTime(context)).isEqualTo(calendar.getTime()); } private static TriggerContext getTriggerContext(Date lastCompletionTime) { diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java index b4038229436..99beab8ee91 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/PeriodicTriggerTests.java @@ -24,9 +24,7 @@ import org.junit.Test; import org.springframework.scheduling.TriggerContext; import org.springframework.util.NumberUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -179,28 +177,28 @@ public class PeriodicTriggerTests { public void equalsVerification() { PeriodicTrigger trigger1 = new PeriodicTrigger(3000); PeriodicTrigger trigger2 = new PeriodicTrigger(3000); - assertFalse(trigger1.equals(new String("not a trigger"))); - assertFalse(trigger1.equals(null)); - assertEquals(trigger1, trigger1); - assertEquals(trigger2, trigger2); - assertEquals(trigger1, trigger2); + assertThat(trigger1.equals(new String("not a trigger"))).isFalse(); + assertThat(trigger1.equals(null)).isFalse(); + assertThat(trigger1).isEqualTo(trigger1); + assertThat(trigger2).isEqualTo(trigger2); + assertThat(trigger2).isEqualTo(trigger1); trigger2.setInitialDelay(1234); - assertFalse(trigger1.equals(trigger2)); - assertFalse(trigger2.equals(trigger1)); + assertThat(trigger1.equals(trigger2)).isFalse(); + assertThat(trigger2.equals(trigger1)).isFalse(); trigger1.setInitialDelay(1234); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); trigger2.setFixedRate(true); - assertFalse(trigger1.equals(trigger2)); - assertFalse(trigger2.equals(trigger1)); + assertThat(trigger1.equals(trigger2)).isFalse(); + assertThat(trigger2.equals(trigger1)).isFalse(); trigger1.setFixedRate(true); - assertEquals(trigger1, trigger2); + assertThat(trigger2).isEqualTo(trigger1); PeriodicTrigger trigger3 = new PeriodicTrigger(3, TimeUnit.SECONDS); trigger3.setInitialDelay(7); trigger3.setFixedRate(true); - assertFalse(trigger1.equals(trigger3)); - assertFalse(trigger3.equals(trigger1)); + assertThat(trigger1.equals(trigger3)).isFalse(); + assertThat(trigger3.equals(trigger1)).isFalse(); trigger1.setInitialDelay(7000); - assertEquals(trigger1, trigger3); + assertThat(trigger3).isEqualTo(trigger1); } @@ -208,14 +206,14 @@ public class PeriodicTriggerTests { private static void assertNegligibleDifference(Date d1, Date d2) { long diff = Math.abs(d1.getTime() - d2.getTime()); - assertTrue("difference exceeds threshold: " + diff, diff < 100); + assertThat(diff < 100).as("difference exceeds threshold: " + diff).isTrue(); } private static void assertApproximateDifference(Date lesser, Date greater, long expected) { long diff = greater.getTime() - lesser.getTime(); long variance = Math.abs(expected - diff); - assertTrue("expected approximate difference of " + expected + - ", but actual difference was " + diff, variance < 100); + assertThat(variance < 100).as("expected approximate difference of " + expected + + ", but actual difference was " + diff).isTrue(); } private static TriggerContext context(Object scheduled, Object actual, Object completion) { diff --git a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptEvaluatorTests.java b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptEvaluatorTests.java index 37e25031cd3..710a732cf42 100644 --- a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptEvaluatorTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptEvaluatorTests.java @@ -26,7 +26,7 @@ import org.springframework.scripting.ScriptEvaluator; import org.springframework.scripting.support.ResourceScriptSource; import org.springframework.scripting.support.StaticScriptSource; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -37,14 +37,14 @@ public class BshScriptEvaluatorTests { public void testBshScriptFromString() { ScriptEvaluator evaluator = new BshScriptEvaluator(); Object result = evaluator.evaluate(new StaticScriptSource("return 3 * 2;")); - assertEquals(6, result); + assertThat(result).isEqualTo(6); } @Test public void testBshScriptFromFile() { ScriptEvaluator evaluator = new BshScriptEvaluator(); Object result = evaluator.evaluate(new ResourceScriptSource(new ClassPathResource("simple.bsh", getClass()))); - assertEquals(6, result); + assertThat(result).isEqualTo(6); } @Test @@ -54,7 +54,7 @@ public class BshScriptEvaluatorTests { arguments.put("a", 3); arguments.put("b", 2); Object result = evaluator.evaluate(new StaticScriptSource("return a * b;"), arguments); - assertEquals(6, result); + assertThat(result).isEqualTo(6); } } diff --git a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java index 8e655c42f55..335ead34e1a 100644 --- a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java @@ -37,15 +37,9 @@ import org.springframework.scripting.TestBeanAwareMessenger; import org.springframework.scripting.support.ScriptFactoryPostProcessor; 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.assertThatIllegalArgumentException; -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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -60,81 +54,85 @@ public class BshScriptFactoryTests { public void staticScript() { ApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Calculator.class)).contains("calculator")); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messenger")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Calculator.class)).contains("calculator")).isTrue(); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messenger")).isTrue(); Calculator calc = (Calculator) ctx.getBean("calculator"); Messenger messenger = (Messenger) ctx.getBean("messenger"); - assertFalse("Scripted object should not be instance of Refreshable", calc instanceof Refreshable); - assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + boolean condition3 = calc instanceof Refreshable; + assertThat(condition3).as("Scripted object should not be instance of Refreshable").isFalse(); + boolean condition2 = messenger instanceof Refreshable; + assertThat(condition2).as("Scripted object should not be instance of Refreshable").isFalse(); - assertEquals(calc, calc); - assertEquals(messenger, messenger); - assertTrue(!messenger.equals(calc)); - assertTrue(messenger.hashCode() != calc.hashCode()); - assertTrue(!messenger.toString().equals(calc.toString())); + assertThat(calc).isEqualTo(calc); + assertThat(messenger).isEqualTo(messenger); + boolean condition1 = !messenger.equals(calc); + assertThat(condition1).isTrue(); + assertThat(messenger.hashCode() != calc.hashCode()).isTrue(); + boolean condition = !messenger.toString().equals(calc.toString()); + assertThat(condition).isTrue(); - assertEquals(5, calc.add(2, 3)); + assertThat(calc.add(2, 3)).isEqualTo(5); String desiredMessage = "Hello World!"; - assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); + assertThat(messenger.getMessage()).as("Message is incorrect").isEqualTo(desiredMessage); - assertTrue(ctx.getBeansOfType(Calculator.class).values().contains(calc)); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(ctx.getBeansOfType(Calculator.class).values().contains(calc)).isTrue(); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); } @Test public void staticScriptWithNullReturnValue() { ApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithConfig")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithConfig")).isTrue(); ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerWithConfig"); messenger.setMessage(null); - assertNull(messenger.getMessage()); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(messenger.getMessage()).isNull(); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); } @Test public void staticScriptWithTwoInterfacesSpecified() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithConfigExtra")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithConfigExtra")).isTrue(); ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerWithConfigExtra"); messenger.setMessage(null); - assertNull(messenger.getMessage()); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(messenger.getMessage()).isNull(); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); ctx.close(); - assertNull(messenger.getMessage()); + assertThat(messenger.getMessage()).isNull(); } @Test public void staticWithScriptReturningInstance() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstance")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstance")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("messengerInstance"); String desiredMessage = "Hello World!"; - assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(messenger.getMessage()).as("Message is incorrect").isEqualTo(desiredMessage); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); ctx.close(); - assertNull(messenger.getMessage()); + assertThat(messenger.getMessage()).isNull(); } @Test public void staticScriptImplementingInterface() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerImpl")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerImpl")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("messengerImpl"); String desiredMessage = "Hello World!"; - assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(messenger.getMessage()).as("Message is incorrect").isEqualTo(desiredMessage); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); ctx.close(); - assertNull(messenger.getMessage()); + assertThat(messenger.getMessage()).isNull(); } @Test @@ -143,17 +141,18 @@ public class BshScriptFactoryTests { ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); - assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); - assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + assertThat(AopUtils.isAopProxy(messenger)).as("Shouldn't get proxy when refresh is disabled").isFalse(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Scripted object should not be instance of Refreshable").isFalse(); - assertNotSame(messenger, messenger2); - assertSame(messenger.getClass(), messenger2.getClass()); - assertEquals("Hello World!", messenger.getMessage()); - assertEquals("Hello World!", messenger2.getMessage()); + assertThat(messenger2).isNotSameAs(messenger); + assertThat(messenger2.getClass()).isSameAs(messenger.getClass()); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + assertThat(messenger2.getMessage()).isEqualTo("Hello World!"); messenger.setMessage("Bye World!"); messenger2.setMessage("Byebye World!"); - assertEquals("Bye World!", messenger.getMessage()); - assertEquals("Byebye World!", messenger2.getMessage()); + assertThat(messenger.getMessage()).isEqualTo("Bye World!"); + assertThat(messenger2.getMessage()).isEqualTo("Byebye World!"); } @Test @@ -161,17 +160,18 @@ public class BshScriptFactoryTests { ApplicationContext ctx = new ClassPathXmlApplicationContext("bshRefreshableContext.xml", getClass()); Messenger messenger = (Messenger) ctx.getBean("messenger"); - assertTrue("Should be a proxy for refreshable scripts", AopUtils.isAopProxy(messenger)); - assertTrue("Should be an instance of Refreshable", messenger instanceof Refreshable); + assertThat(AopUtils.isAopProxy(messenger)).as("Should be a proxy for refreshable scripts").isTrue(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Should be an instance of Refreshable").isTrue(); String desiredMessage = "Hello World!"; - assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); + assertThat(messenger.getMessage()).as("Message is incorrect").isEqualTo(desiredMessage); Refreshable refreshable = (Refreshable) messenger; refreshable.refresh(); - assertEquals("Message is incorrect after refresh", desiredMessage, messenger.getMessage()); - assertEquals("Incorrect refresh count", 2, refreshable.getRefreshCount()); + assertThat(messenger.getMessage()).as("Message is incorrect after refresh").isEqualTo(desiredMessage); + assertThat(refreshable.getRefreshCount()).as("Incorrect refresh count").isEqualTo(2); } @Test @@ -180,22 +180,23 @@ public class BshScriptFactoryTests { ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); - assertTrue("Should be a proxy for refreshable scripts", AopUtils.isAopProxy(messenger)); - assertTrue("Should be an instance of Refreshable", messenger instanceof Refreshable); + assertThat(AopUtils.isAopProxy(messenger)).as("Should be a proxy for refreshable scripts").isTrue(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Should be an instance of Refreshable").isTrue(); - assertEquals("Hello World!", messenger.getMessage()); - assertEquals("Hello World!", messenger2.getMessage()); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + assertThat(messenger2.getMessage()).isEqualTo("Hello World!"); messenger.setMessage("Bye World!"); messenger2.setMessage("Byebye World!"); - assertEquals("Bye World!", messenger.getMessage()); - assertEquals("Byebye World!", messenger2.getMessage()); + assertThat(messenger.getMessage()).isEqualTo("Bye World!"); + assertThat(messenger2.getMessage()).isEqualTo("Byebye World!"); Refreshable refreshable = (Refreshable) messenger; refreshable.refresh(); - assertEquals("Hello World!", messenger.getMessage()); - assertEquals("Byebye World!", messenger2.getMessage()); - assertEquals("Incorrect refresh count", 2, refreshable.getRefreshCount()); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + assertThat(messenger2.getMessage()).isEqualTo("Byebye World!"); + assertThat(refreshable.getRefreshCount()).as("Incorrect refresh count").isEqualTo(2); } @Test @@ -243,37 +244,38 @@ public class BshScriptFactoryTests { TestBean testBean = (TestBean) ctx.getBean("testBean"); Collection beanNames = Arrays.asList(ctx.getBeanNamesForType(Messenger.class)); - assertTrue(beanNames.contains("messenger")); - assertTrue(beanNames.contains("messengerImpl")); - assertTrue(beanNames.contains("messengerInstance")); + assertThat(beanNames.contains("messenger")).isTrue(); + assertThat(beanNames.contains("messengerImpl")).isTrue(); + assertThat(beanNames.contains("messengerInstance")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("messenger"); - assertEquals("Hello World!", messenger.getMessage()); - assertFalse(messenger instanceof Refreshable); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).isFalse(); Messenger messengerImpl = (Messenger) ctx.getBean("messengerImpl"); - assertEquals("Hello World!", messengerImpl.getMessage()); + assertThat(messengerImpl.getMessage()).isEqualTo("Hello World!"); Messenger messengerInstance = (Messenger) ctx.getBean("messengerInstance"); - assertEquals("Hello World!", messengerInstance.getMessage()); + assertThat(messengerInstance.getMessage()).isEqualTo("Hello World!"); TestBeanAwareMessenger messengerByType = (TestBeanAwareMessenger) ctx.getBean("messengerByType"); - assertEquals(testBean, messengerByType.getTestBean()); + assertThat(messengerByType.getTestBean()).isEqualTo(testBean); TestBeanAwareMessenger messengerByName = (TestBeanAwareMessenger) ctx.getBean("messengerByName"); - assertEquals(testBean, messengerByName.getTestBean()); + assertThat(messengerByName.getTestBean()).isEqualTo(testBean); Collection beans = ctx.getBeansOfType(Messenger.class).values(); - assertTrue(beans.contains(messenger)); - assertTrue(beans.contains(messengerImpl)); - assertTrue(beans.contains(messengerInstance)); - assertTrue(beans.contains(messengerByType)); - assertTrue(beans.contains(messengerByName)); + assertThat(beans.contains(messenger)).isTrue(); + assertThat(beans.contains(messengerImpl)).isTrue(); + assertThat(beans.contains(messengerInstance)).isTrue(); + assertThat(beans.contains(messengerByType)).isTrue(); + assertThat(beans.contains(messengerByName)).isTrue(); ctx.close(); - assertNull(messenger.getMessage()); - assertNull(messengerImpl.getMessage()); - assertNull(messengerInstance.getMessage()); + assertThat(messenger.getMessage()).isNull(); + assertThat(messengerImpl.getMessage()).isNull(); + assertThat(messengerInstance.getMessage()).isNull(); } @Test @@ -282,30 +284,32 @@ public class BshScriptFactoryTests { ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); - assertNotSame(messenger, messenger2); - assertSame(messenger.getClass(), messenger2.getClass()); - assertEquals("Hello World!", messenger.getMessage()); - assertEquals("Hello World!", messenger2.getMessage()); + assertThat(messenger2).isNotSameAs(messenger); + assertThat(messenger2.getClass()).isSameAs(messenger.getClass()); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + assertThat(messenger2.getMessage()).isEqualTo("Hello World!"); messenger.setMessage("Bye World!"); messenger2.setMessage("Byebye World!"); - assertEquals("Bye World!", messenger.getMessage()); - assertEquals("Byebye World!", messenger2.getMessage()); + assertThat(messenger.getMessage()).isEqualTo("Bye World!"); + assertThat(messenger2.getMessage()).isEqualTo("Byebye World!"); } @Test public void inlineScriptFromTag() { ApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass()); Calculator calculator = (Calculator) ctx.getBean("calculator"); - assertNotNull(calculator); - assertFalse(calculator instanceof Refreshable); + assertThat(calculator).isNotNull(); + boolean condition = calculator instanceof Refreshable; + assertThat(condition).isFalse(); } @Test public void refreshableFromTag() { ApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass()); Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger"); - assertEquals("Hello World!", messenger.getMessage()); - assertTrue("Messenger should be Refreshable", messenger instanceof Refreshable); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Messenger should be Refreshable").isTrue(); } @Test @@ -313,7 +317,7 @@ public class BshScriptFactoryTests { ApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass()); Messenger eventListener = (Messenger) ctx.getBean("eventListener"); ctx.publishEvent(new MyEvent(ctx)); - assertEquals("count=2", eventListener.getMessage()); + assertThat(eventListener.getMessage()).isEqualTo("count=2"); } diff --git a/spring-context/src/test/java/org/springframework/scripting/config/ScriptingDefaultsTests.java b/spring-context/src/test/java/org/springframework/scripting/config/ScriptingDefaultsTests.java index 781870fc4e2..c29af4e2800 100644 --- a/spring-context/src/test/java/org/springframework/scripting/config/ScriptingDefaultsTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/config/ScriptingDefaultsTests.java @@ -26,9 +26,7 @@ import org.springframework.aop.target.dynamic.AbstractRefreshableTargetSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -53,30 +51,30 @@ public class ScriptingDefaultsTests { Field field = AbstractRefreshableTargetSource.class.getDeclaredField("refreshCheckDelay"); field.setAccessible(true); long delay = ((Long) field.get(targetSource)).longValue(); - assertEquals(5000L, delay); + assertThat(delay).isEqualTo(5000L); } @Test public void defaultInitMethod() { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("testBean"); - assertTrue(testBean.isInitialized()); + assertThat(testBean.isInitialized()).isTrue(); } @Test public void nameAsAlias() { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("/url"); - assertTrue(testBean.isInitialized()); + assertThat(testBean.isInitialized()).isTrue(); } @Test public void defaultDestroyMethod() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("nonRefreshableTestBean"); - assertFalse(testBean.isDestroyed()); + assertThat(testBean.isDestroyed()).isFalse(); context.close(); - assertTrue(testBean.isDestroyed()); + assertThat(testBean.isDestroyed()).isTrue(); } @Test @@ -84,14 +82,14 @@ public class ScriptingDefaultsTests { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("testBean"); ITestBean otherBean = (ITestBean) context.getBean("otherBean"); - assertEquals(otherBean, testBean.getOtherBean()); + assertThat(testBean.getOtherBean()).isEqualTo(otherBean); } @Test public void defaultProxyTargetClass() { ApplicationContext context = new ClassPathXmlApplicationContext(PROXY_CONFIG); Object testBean = context.getBean("testBean"); - assertTrue(AopUtils.isCglibProxy(testBean)); + assertThat(AopUtils.isCglibProxy(testBean)).isTrue(); } } diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests.java index 4f13f20a1bf..a5a6c2ab22c 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests.java @@ -21,8 +21,8 @@ import org.junit.Test; import org.springframework.context.support.GenericXmlApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Dave Syer @@ -37,11 +37,11 @@ public class GroovyAspectIntegrationTests { TestService bean = context.getBean("javaBean", TestService.class); LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); - assertEquals(0, logAdvice.getCountThrows()); + assertThat(logAdvice.getCountThrows()).isEqualTo(0); assertThatExceptionOfType(RuntimeException.class).isThrownBy( bean::sayHello) .withMessage("TestServiceImpl"); - assertEquals(1, logAdvice.getCountThrows()); + assertThat(logAdvice.getCountThrows()).isEqualTo(1); } @Test @@ -50,11 +50,11 @@ public class GroovyAspectIntegrationTests { TestService bean = context.getBean("groovyBean", TestService.class); LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); - assertEquals(0, logAdvice.getCountThrows()); + assertThat(logAdvice.getCountThrows()).isEqualTo(0); assertThatExceptionOfType(RuntimeException.class).isThrownBy( bean::sayHello) .withMessage("GroovyServiceImpl"); - assertEquals(1, logAdvice.getCountThrows()); + assertThat(logAdvice.getCountThrows()).isEqualTo(1); } @@ -64,13 +64,13 @@ public class GroovyAspectIntegrationTests { TestService bean = context.getBean("groovyBean", TestService.class); LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); - assertEquals(0, logAdvice.getCountThrows()); + assertThat(logAdvice.getCountThrows()).isEqualTo(0); assertThatExceptionOfType(RuntimeException.class).isThrownBy( bean::sayHello) .withMessage("GroovyServiceImpl"); // No proxy here because the pointcut only applies to the concrete class, not the interface - assertEquals(0, logAdvice.getCountThrows()); - assertEquals(0, logAdvice.getCountBefore()); + assertThat(logAdvice.getCountThrows()).isEqualTo(0); + assertThat(logAdvice.getCountBefore()).isEqualTo(0); } @Test @@ -79,12 +79,12 @@ public class GroovyAspectIntegrationTests { TestService bean = context.getBean("groovyBean", TestService.class); LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); - assertEquals(0, logAdvice.getCountThrows()); + assertThat(logAdvice.getCountThrows()).isEqualTo(0); assertThatExceptionOfType(RuntimeException.class).isThrownBy( bean::sayHello) .withMessage("GroovyServiceImpl"); - assertEquals(1, logAdvice.getCountBefore()); - assertEquals(1, logAdvice.getCountThrows()); + assertThat(logAdvice.getCountBefore()).isEqualTo(1); + assertThat(logAdvice.getCountThrows()).isEqualTo(1); } @After diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java index 7e5a772ba1c..0d1290e2c3c 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java @@ -26,8 +26,8 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.scripting.support.ResourceScriptSource; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Dave Syer @@ -94,11 +94,11 @@ public class GroovyAspectTests { factory.addAdvisor(advisor); TestService bean = (TestService) factory.getProxy(); - assertEquals(0, logAdvice.getCountThrows()); + assertThat(logAdvice.getCountThrows()).isEqualTo(0); assertThatExceptionOfType(TestException.class).isThrownBy( bean::sayHello) .withMessage(message); - assertEquals(1, logAdvice.getCountThrows()); + assertThat(logAdvice.getCountThrows()).isEqualTo(1); } } diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyClassLoadingTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyClassLoadingTests.java index 6cefaf0e143..623db3253c9 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyClassLoadingTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyClassLoadingTests.java @@ -25,7 +25,7 @@ import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.support.StaticApplicationContext; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -45,14 +45,14 @@ public class GroovyClassLoadingTests { Object testBean1 = context.getBean("testBean"); Method method1 = class1.getDeclaredMethod("myMethod", new Class[0]); Object result1 = ReflectionUtils.invokeMethod(method1, testBean1); - assertEquals("foo", result1); + assertThat(result1).isEqualTo("foo"); context.removeBeanDefinition("testBean"); context.registerBeanDefinition("testBean", new RootBeanDefinition(class2)); Object testBean2 = context.getBean("testBean"); Method method2 = class2.getDeclaredMethod("myMethod", new Class[0]); Object result2 = ReflectionUtils.invokeMethod(method2, testBean2); - assertEquals("bar", result2); + assertThat(result2).isEqualTo("bar"); } } diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptEvaluatorTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptEvaluatorTests.java index ef65f61b8e7..8719bf149f5 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptEvaluatorTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptEvaluatorTests.java @@ -28,8 +28,7 @@ import org.springframework.scripting.support.ResourceScriptSource; import org.springframework.scripting.support.StandardScriptEvaluator; import org.springframework.scripting.support.StaticScriptSource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -40,14 +39,14 @@ public class GroovyScriptEvaluatorTests { public void testGroovyScriptFromString() { ScriptEvaluator evaluator = new GroovyScriptEvaluator(); Object result = evaluator.evaluate(new StaticScriptSource("return 3 * 2")); - assertEquals(6, result); + assertThat(result).isEqualTo(6); } @Test public void testGroovyScriptFromFile() { ScriptEvaluator evaluator = new GroovyScriptEvaluator(); Object result = evaluator.evaluate(new ResourceScriptSource(new ClassPathResource("simple.groovy", getClass()))); - assertEquals(6, result); + assertThat(result).isEqualTo(6); } @Test @@ -57,7 +56,7 @@ public class GroovyScriptEvaluatorTests { arguments.put("a", 3); arguments.put("b", 2); Object result = evaluator.evaluate(new StaticScriptSource("return a * b"), arguments); - assertEquals(6, result); + assertThat(result).isEqualTo(6); } @Test @@ -66,8 +65,8 @@ public class GroovyScriptEvaluatorTests { MyBytecodeProcessor processor = new MyBytecodeProcessor(); evaluator.getCompilerConfiguration().setBytecodePostprocessor(processor); Object result = evaluator.evaluate(new StaticScriptSource("return 3 * 2")); - assertEquals(6, result); - assertTrue(processor.processed.contains("Script1")); + assertThat(result).isEqualTo(6); + assertThat(processor.processed.contains("Script1")).isTrue(); } @Test @@ -77,7 +76,7 @@ public class GroovyScriptEvaluatorTests { importCustomizer.addStarImports("org.springframework.util"); evaluator.setCompilationCustomizers(importCustomizer); Object result = evaluator.evaluate(new StaticScriptSource("return ResourceUtils.CLASSPATH_URL_PREFIX")); - assertEquals("classpath:", result); + assertThat(result).isEqualTo("classpath:"); } @Test @@ -85,14 +84,14 @@ public class GroovyScriptEvaluatorTests { StandardScriptEvaluator evaluator = new StandardScriptEvaluator(); evaluator.setLanguage("Groovy"); Object result = evaluator.evaluate(new StaticScriptSource("return 3 * 2")); - assertEquals(6, result); + assertThat(result).isEqualTo(6); } @Test public void testGroovyScriptFromFileUsingJsr223() { ScriptEvaluator evaluator = new StandardScriptEvaluator(); Object result = evaluator.evaluate(new ResourceScriptSource(new ClassPathResource("simple.groovy", getClass()))); - assertEquals(6, result); + assertThat(result).isEqualTo(6); } @Test @@ -103,7 +102,7 @@ public class GroovyScriptEvaluatorTests { arguments.put("a", 3); arguments.put("b", 2); Object result = evaluator.evaluate(new StaticScriptSource("return a * b"), arguments); - assertEquals(6, result); + assertThat(result).isEqualTo(6); } } diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java index c3fd6af88b6..551dc941d39 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java @@ -45,16 +45,11 @@ import org.springframework.stereotype.Component; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatNullPointerException; -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.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -73,58 +68,66 @@ public class GroovyScriptFactoryTests { public void testStaticScript() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContext.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Calculator.class)).contains("calculator")); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messenger")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Calculator.class)).contains("calculator")).isTrue(); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messenger")).isTrue(); Calculator calc = (Calculator) ctx.getBean("calculator"); Messenger messenger = (Messenger) ctx.getBean("messenger"); - assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(calc)); - assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); + assertThat(AopUtils.isAopProxy(calc)).as("Shouldn't get proxy when refresh is disabled").isFalse(); + assertThat(AopUtils.isAopProxy(messenger)).as("Shouldn't get proxy when refresh is disabled").isFalse(); - assertFalse("Scripted object should not be instance of Refreshable", calc instanceof Refreshable); - assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + boolean condition3 = calc instanceof Refreshable; + assertThat(condition3).as("Scripted object should not be instance of Refreshable").isFalse(); + boolean condition2 = messenger instanceof Refreshable; + assertThat(condition2).as("Scripted object should not be instance of Refreshable").isFalse(); - assertEquals(calc, calc); - assertEquals(messenger, messenger); - assertTrue(!messenger.equals(calc)); - assertTrue(messenger.hashCode() != calc.hashCode()); - assertTrue(!messenger.toString().equals(calc.toString())); + assertThat(calc).isEqualTo(calc); + assertThat(messenger).isEqualTo(messenger); + boolean condition1 = !messenger.equals(calc); + assertThat(condition1).isTrue(); + assertThat(messenger.hashCode() != calc.hashCode()).isTrue(); + boolean condition = !messenger.toString().equals(calc.toString()); + assertThat(condition).isTrue(); String desiredMessage = "Hello World!"; - assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); + assertThat(messenger.getMessage()).as("Message is incorrect").isEqualTo(desiredMessage); - assertTrue(ctx.getBeansOfType(Calculator.class).values().contains(calc)); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(ctx.getBeansOfType(Calculator.class).values().contains(calc)).isTrue(); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); } @Test public void testStaticScriptUsingJsr223() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContextWithJsr223.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Calculator.class)).contains("calculator")); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messenger")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Calculator.class)).contains("calculator")).isTrue(); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messenger")).isTrue(); Calculator calc = (Calculator) ctx.getBean("calculator"); Messenger messenger = (Messenger) ctx.getBean("messenger"); - assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(calc)); - assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); + assertThat(AopUtils.isAopProxy(calc)).as("Shouldn't get proxy when refresh is disabled").isFalse(); + assertThat(AopUtils.isAopProxy(messenger)).as("Shouldn't get proxy when refresh is disabled").isFalse(); - assertFalse("Scripted object should not be instance of Refreshable", calc instanceof Refreshable); - assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + boolean condition3 = calc instanceof Refreshable; + assertThat(condition3).as("Scripted object should not be instance of Refreshable").isFalse(); + boolean condition2 = messenger instanceof Refreshable; + assertThat(condition2).as("Scripted object should not be instance of Refreshable").isFalse(); - assertEquals(calc, calc); - assertEquals(messenger, messenger); - assertTrue(!messenger.equals(calc)); - assertTrue(messenger.hashCode() != calc.hashCode()); - assertTrue(!messenger.toString().equals(calc.toString())); + assertThat(calc).isEqualTo(calc); + assertThat(messenger).isEqualTo(messenger); + boolean condition1 = !messenger.equals(calc); + assertThat(condition1).isTrue(); + assertThat(messenger.hashCode() != calc.hashCode()).isTrue(); + boolean condition = !messenger.toString().equals(calc.toString()); + assertThat(condition).isTrue(); String desiredMessage = "Hello World!"; - assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); + assertThat(messenger.getMessage()).as("Message is incorrect").isEqualTo(desiredMessage); - assertTrue(ctx.getBeansOfType(Calculator.class).values().contains(calc)); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(ctx.getBeansOfType(Calculator.class).values().contains(calc)).isTrue(); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); } @Test @@ -133,17 +136,18 @@ public class GroovyScriptFactoryTests { ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); - assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); - assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + assertThat(AopUtils.isAopProxy(messenger)).as("Shouldn't get proxy when refresh is disabled").isFalse(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Scripted object should not be instance of Refreshable").isFalse(); - assertNotSame(messenger, messenger2); - assertSame(messenger.getClass(), messenger2.getClass()); - assertEquals("Hello World!", messenger.getMessage()); - assertEquals("Hello World!", messenger2.getMessage()); + assertThat(messenger2).isNotSameAs(messenger); + assertThat(messenger2.getClass()).isSameAs(messenger.getClass()); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + assertThat(messenger2.getMessage()).isEqualTo("Hello World!"); messenger.setMessage("Bye World!"); messenger2.setMessage("Byebye World!"); - assertEquals("Bye World!", messenger.getMessage()); - assertEquals("Byebye World!", messenger2.getMessage()); + assertThat(messenger.getMessage()).isEqualTo("Bye World!"); + assertThat(messenger2.getMessage()).isEqualTo("Byebye World!"); } @Test @@ -152,73 +156,78 @@ public class GroovyScriptFactoryTests { ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); - assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); - assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + assertThat(AopUtils.isAopProxy(messenger)).as("Shouldn't get proxy when refresh is disabled").isFalse(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Scripted object should not be instance of Refreshable").isFalse(); - assertNotSame(messenger, messenger2); - assertSame(messenger.getClass(), messenger2.getClass()); - assertEquals("Hello World!", messenger.getMessage()); - assertEquals("Hello World!", messenger2.getMessage()); + assertThat(messenger2).isNotSameAs(messenger); + assertThat(messenger2.getClass()).isSameAs(messenger.getClass()); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + assertThat(messenger2.getMessage()).isEqualTo("Hello World!"); messenger.setMessage("Bye World!"); messenger2.setMessage("Byebye World!"); - assertEquals("Bye World!", messenger.getMessage()); - assertEquals("Byebye World!", messenger2.getMessage()); + assertThat(messenger.getMessage()).isEqualTo("Bye World!"); + assertThat(messenger2.getMessage()).isEqualTo("Byebye World!"); } @Test public void testStaticScriptWithInstance() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContext.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstance")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstance")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("messengerInstance"); - assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); - assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + assertThat(AopUtils.isAopProxy(messenger)).as("Shouldn't get proxy when refresh is disabled").isFalse(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Scripted object should not be instance of Refreshable").isFalse(); String desiredMessage = "Hello World!"; - assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(messenger.getMessage()).as("Message is incorrect").isEqualTo(desiredMessage); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); } @Test public void testStaticScriptWithInstanceUsingJsr223() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContextWithJsr223.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstance")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstance")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("messengerInstance"); - assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); - assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + assertThat(AopUtils.isAopProxy(messenger)).as("Shouldn't get proxy when refresh is disabled").isFalse(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Scripted object should not be instance of Refreshable").isFalse(); String desiredMessage = "Hello World!"; - assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(messenger.getMessage()).as("Message is incorrect").isEqualTo(desiredMessage); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); } @Test public void testStaticScriptWithInlineDefinedInstance() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContext.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstanceInline")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstanceInline")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("messengerInstanceInline"); - assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); - assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + assertThat(AopUtils.isAopProxy(messenger)).as("Shouldn't get proxy when refresh is disabled").isFalse(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Scripted object should not be instance of Refreshable").isFalse(); String desiredMessage = "Hello World!"; - assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(messenger.getMessage()).as("Message is incorrect").isEqualTo(desiredMessage); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); } @Test public void testStaticScriptWithInlineDefinedInstanceUsingJsr223() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContextWithJsr223.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstanceInline")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstanceInline")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("messengerInstanceInline"); - assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger)); - assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable); + assertThat(AopUtils.isAopProxy(messenger)).as("Shouldn't get proxy when refresh is disabled").isFalse(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Scripted object should not be instance of Refreshable").isFalse(); String desiredMessage = "Hello World!"; - assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(messenger.getMessage()).as("Message is incorrect").isEqualTo(desiredMessage); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); } @Test @@ -226,17 +235,18 @@ public class GroovyScriptFactoryTests { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyRefreshableContext.xml", getClass()); Messenger messenger = (Messenger) ctx.getBean("messenger"); - assertTrue("Should be a proxy for refreshable scripts", AopUtils.isAopProxy(messenger)); - assertTrue("Should be an instance of Refreshable", messenger instanceof Refreshable); + assertThat(AopUtils.isAopProxy(messenger)).as("Should be a proxy for refreshable scripts").isTrue(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Should be an instance of Refreshable").isTrue(); String desiredMessage = "Hello World!"; - assertEquals("Message is incorrect", desiredMessage, messenger.getMessage()); + assertThat(messenger.getMessage()).as("Message is incorrect").isEqualTo(desiredMessage); Refreshable refreshable = (Refreshable) messenger; refreshable.refresh(); - assertEquals("Message is incorrect after refresh.", desiredMessage, messenger.getMessage()); - assertEquals("Incorrect refresh count", 2, refreshable.getRefreshCount()); + assertThat(messenger.getMessage()).as("Message is incorrect after refresh.").isEqualTo(desiredMessage); + assertThat(refreshable.getRefreshCount()).as("Incorrect refresh count").isEqualTo(2); } @Test @@ -245,22 +255,23 @@ public class GroovyScriptFactoryTests { ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); - assertTrue("Should be a proxy for refreshable scripts", AopUtils.isAopProxy(messenger)); - assertTrue("Should be an instance of Refreshable", messenger instanceof Refreshable); + assertThat(AopUtils.isAopProxy(messenger)).as("Should be a proxy for refreshable scripts").isTrue(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).as("Should be an instance of Refreshable").isTrue(); - assertEquals("Hello World!", messenger.getMessage()); - assertEquals("Hello World!", messenger2.getMessage()); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + assertThat(messenger2.getMessage()).isEqualTo("Hello World!"); messenger.setMessage("Bye World!"); messenger2.setMessage("Byebye World!"); - assertEquals("Bye World!", messenger.getMessage()); - assertEquals("Byebye World!", messenger2.getMessage()); + assertThat(messenger.getMessage()).isEqualTo("Bye World!"); + assertThat(messenger2.getMessage()).isEqualTo("Byebye World!"); Refreshable refreshable = (Refreshable) messenger; refreshable.refresh(); - assertEquals("Hello World!", messenger.getMessage()); - assertEquals("Byebye World!", messenger2.getMessage()); - assertEquals("Incorrect refresh count", 2, refreshable.getRefreshCount()); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + assertThat(messenger2.getMessage()).isEqualTo("Byebye World!"); + assertThat(refreshable.getRefreshCount()).as("Incorrect refresh count").isEqualTo(2); } @Test @@ -290,19 +301,19 @@ public class GroovyScriptFactoryTests { given(script.getScriptAsString()).willReturn(badScript); given(script.suggestedClassName()).willReturn("someName"); GroovyScriptFactory factory = new GroovyScriptFactory(ScriptFactoryPostProcessor.INLINE_SCRIPT_PREFIX + badScript); - assertEquals("X", factory.getScriptedObject(script).toString()); + assertThat(factory.getScriptedObject(script).toString()).isEqualTo("X"); } @Test public void testWithTwoClassesDefinedInTheOneGroovyFile_CorrectClassFirst() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("twoClassesCorrectOneFirst.xml", getClass()); Messenger messenger = (Messenger) ctx.getBean("messenger"); - assertNotNull(messenger); - assertEquals("Hello World!", messenger.getMessage()); + assertThat(messenger).isNotNull(); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); // Check can cast to GroovyObject GroovyObject goo = (GroovyObject) messenger; - assertNotNull(goo); + assertThat(goo).isNotNull(); } @Test @@ -346,7 +357,7 @@ public class GroovyScriptFactoryTests { GroovyScriptFactory factory = new GroovyScriptFactory("a script source locator (doesn't matter here)"); Object scriptedObject = factory.getScriptedObject(script); - assertNotNull(scriptedObject); + assertThat(scriptedObject).isNotNull(); } @Test @@ -362,14 +373,15 @@ public class GroovyScriptFactoryTests { Messenger messenger = (Messenger) ctx.getBean("messenger"); CallCounter countingAspect = (CallCounter) ctx.getBean("getMessageAspect"); - assertTrue(AopUtils.isAopProxy(messenger)); - assertFalse(messenger instanceof Refreshable); - assertEquals(0, countingAspect.getCalls()); - assertEquals("Hello World!", messenger.getMessage()); - assertEquals(1, countingAspect.getCalls()); + assertThat(AopUtils.isAopProxy(messenger)).isTrue(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).isFalse(); + assertThat(countingAspect.getCalls()).isEqualTo(0); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + assertThat(countingAspect.getCalls()).isEqualTo(1); ctx.close(); - assertEquals(-200, countingAspect.getCalls()); + assertThat(countingAspect.getCalls()).isEqualTo(-200); } @Test @@ -378,59 +390,62 @@ public class GroovyScriptFactoryTests { ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); - assertNotSame(messenger, messenger2); - assertSame(messenger.getClass(), messenger2.getClass()); - assertEquals("Hello World!", messenger.getMessage()); - assertEquals("Hello World!", messenger2.getMessage()); + assertThat(messenger2).isNotSameAs(messenger); + assertThat(messenger2.getClass()).isSameAs(messenger.getClass()); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + assertThat(messenger2.getMessage()).isEqualTo("Hello World!"); messenger.setMessage("Bye World!"); messenger2.setMessage("Byebye World!"); - assertEquals("Bye World!", messenger.getMessage()); - assertEquals("Byebye World!", messenger2.getMessage()); + assertThat(messenger.getMessage()).isEqualTo("Bye World!"); + assertThat(messenger2.getMessage()).isEqualTo("Byebye World!"); } @Test public void testInlineScriptFromTag() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd.xml", getClass()); BeanDefinition bd = ctx.getBeanFactory().getBeanDefinition("calculator"); - assertTrue(ObjectUtils.containsElement(bd.getDependsOn(), "messenger")); + assertThat(ObjectUtils.containsElement(bd.getDependsOn(), "messenger")).isTrue(); Calculator calculator = (Calculator) ctx.getBean("calculator"); - assertNotNull(calculator); - assertFalse(calculator instanceof Refreshable); + assertThat(calculator).isNotNull(); + boolean condition = calculator instanceof Refreshable; + assertThat(condition).isFalse(); } @Test public void testRefreshableFromTag() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger"); CallCounter countingAspect = (CallCounter) ctx.getBean("getMessageAspect"); - assertTrue(AopUtils.isAopProxy(messenger)); - assertTrue(messenger instanceof Refreshable); - assertEquals(0, countingAspect.getCalls()); - assertEquals("Hello World!", messenger.getMessage()); - assertEquals(1, countingAspect.getCalls()); + assertThat(AopUtils.isAopProxy(messenger)).isTrue(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).isTrue(); + assertThat(countingAspect.getCalls()).isEqualTo(0); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); + assertThat(countingAspect.getCalls()).isEqualTo(1); - assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); + assertThat(ctx.getBeansOfType(Messenger.class).values().contains(messenger)).isTrue(); } @Test // SPR-6268 public void testRefreshableFromTagProxyTargetClass() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-proxy-target-class.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger"); - assertTrue(AopUtils.isAopProxy(messenger)); - assertTrue(messenger instanceof Refreshable); - assertEquals("Hello World!", messenger.getMessage()); + assertThat(AopUtils.isAopProxy(messenger)).isTrue(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).isTrue(); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); - assertTrue(ctx.getBeansOfType(ConcreteMessenger.class).values().contains(messenger)); + assertThat(ctx.getBeansOfType(ConcreteMessenger.class).values().contains(messenger)).isTrue(); // Check that AnnotationUtils works with concrete proxied script classes - assertNotNull(AnnotationUtils.findAnnotation(messenger.getClass(), Component.class)); + assertThat(AnnotationUtils.findAnnotation(messenger.getClass(), Component.class)).isNotNull(); } @Test // SPR-6268 @@ -439,7 +454,7 @@ public class GroovyScriptFactoryTests { new ClassPathXmlApplicationContext("groovy-with-xsd-proxy-target-class.xml", getClass()); } catch (BeanCreationException ex) { - assertTrue(ex.getMessage().contains("Cannot use proxyTargetClass=true")); + assertThat(ex.getMessage().contains("Cannot use proxyTargetClass=true")).isTrue(); } } @@ -447,52 +462,53 @@ public class GroovyScriptFactoryTests { public void testAnonymousScriptDetected() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd.xml", getClass()); Map beans = ctx.getBeansOfType(Messenger.class); - assertEquals(4, beans.size()); - assertTrue(ctx.getBean(MyBytecodeProcessor.class).processed.contains( - "org.springframework.scripting.groovy.GroovyMessenger2")); + assertThat(beans.size()).isEqualTo(4); + assertThat(ctx.getBean(MyBytecodeProcessor.class).processed.contains( + "org.springframework.scripting.groovy.GroovyMessenger2")).isTrue(); } @Test public void testJsr223FromTag() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-jsr223.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messenger")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messenger")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("messenger"); - assertFalse(AopUtils.isAopProxy(messenger)); - assertEquals("Hello World!", messenger.getMessage()); + assertThat(AopUtils.isAopProxy(messenger)).isFalse(); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); } @Test public void testJsr223FromTagWithInterface() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-jsr223.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithInterface")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithInterface")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("messengerWithInterface"); - assertFalse(AopUtils.isAopProxy(messenger)); + assertThat(AopUtils.isAopProxy(messenger)).isFalse(); } @Test public void testRefreshableJsr223FromTag() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-jsr223.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger"); - assertTrue(AopUtils.isAopProxy(messenger)); - assertTrue(messenger instanceof Refreshable); - assertEquals("Hello World!", messenger.getMessage()); + assertThat(AopUtils.isAopProxy(messenger)).isTrue(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).isTrue(); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); } @Test public void testInlineJsr223FromTag() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-jsr223.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("inlineMessenger")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("inlineMessenger")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("inlineMessenger"); - assertFalse(AopUtils.isAopProxy(messenger)); + assertThat(AopUtils.isAopProxy(messenger)).isFalse(); } @Test public void testInlineJsr223FromTagWithInterface() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-jsr223.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("inlineMessengerWithInterface")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("inlineMessengerWithInterface")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("inlineMessengerWithInterface"); - assertFalse(AopUtils.isAopProxy(messenger)); + assertThat(AopUtils.isAopProxy(messenger)).isFalse(); } /** @@ -505,14 +521,14 @@ public class GroovyScriptFactoryTests { TestBean tb = (TestBean) ctx.getBean("testBean"); ContextScriptBean bean = (ContextScriptBean) ctx.getBean("bean"); - assertEquals("The first property ain't bein' injected.", "Sophie Marceau", bean.getName()); - assertEquals("The second property ain't bein' injected.", 31, bean.getAge()); - assertEquals(tb, bean.getTestBean()); - assertEquals(ctx, bean.getApplicationContext()); + assertThat(bean.getName()).as("The first property ain't bein' injected.").isEqualTo("Sophie Marceau"); + assertThat(bean.getAge()).as("The second property ain't bein' injected.").isEqualTo(31); + assertThat(bean.getTestBean()).isEqualTo(tb); + assertThat(bean.getApplicationContext()).isEqualTo(ctx); ContextScriptBean bean2 = (ContextScriptBean) ctx.getBean("bean2"); - assertEquals(tb, bean2.getTestBean()); - assertEquals(ctx, bean2.getApplicationContext()); + assertThat(bean2.getTestBean()).isEqualTo(tb); + assertThat(bean2.getApplicationContext()).isEqualTo(ctx); } @Test @@ -538,20 +554,24 @@ public class GroovyScriptFactoryTests { public void testFactoryBean() { ApplicationContext context = new ClassPathXmlApplicationContext("groovyContext.xml", getClass()); Object factory = context.getBean("&factory"); - assertTrue(factory instanceof FactoryBean); + boolean condition1 = factory instanceof FactoryBean; + assertThat(condition1).isTrue(); Object result = context.getBean("factory"); - assertTrue(result instanceof String); - assertEquals("test", result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo("test"); } @Test public void testRefreshableFactoryBean() { ApplicationContext context = new ClassPathXmlApplicationContext("groovyContext.xml", getClass()); Object factory = context.getBean("&refreshableFactory"); - assertTrue(factory instanceof FactoryBean); + boolean condition1 = factory instanceof FactoryBean; + assertThat(condition1).isTrue(); Object result = context.getBean("refreshableFactory"); - assertTrue(result instanceof String); - assertEquals("test", result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo("test"); } diff --git a/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java b/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java index 303952088ef..2bc78a118c3 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java @@ -24,9 +24,7 @@ import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.util.StreamUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -43,14 +41,14 @@ public class ResourceScriptSourceTests { ResourceScriptSource scriptSource = new ResourceScriptSource(resource); long lastModified = scriptSource.retrieveLastModifiedTime(); - assertEquals(0, lastModified); + assertThat(lastModified).isEqualTo(0); } @Test public void beginsInModifiedState() throws Exception { Resource resource = mock(Resource.class); ResourceScriptSource scriptSource = new ResourceScriptSource(resource); - assertTrue(scriptSource.isModified()); + assertThat(scriptSource.isModified()).isTrue(); } @Test @@ -65,22 +63,22 @@ public class ResourceScriptSourceTests { given(resource.getInputStream()).willReturn(StreamUtils.emptyInput()); ResourceScriptSource scriptSource = new ResourceScriptSource(resource); - assertTrue("ResourceScriptSource must start off in the 'isModified' state (it obviously isn't).", scriptSource.isModified()); + assertThat(scriptSource.isModified()).as("ResourceScriptSource must start off in the 'isModified' state (it obviously isn't).").isTrue(); scriptSource.getScriptAsString(); - assertFalse("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.", scriptSource.isModified()); + assertThat(scriptSource.isModified()).as("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.").isFalse(); // Must now report back as having been modified - assertTrue("ResourceScriptSource must report back as being modified if the underlying File resource is reporting a changed lastModified time.", scriptSource.isModified()); + assertThat(scriptSource.isModified()).as("ResourceScriptSource must report back as being modified if the underlying File resource is reporting a changed lastModified time.").isTrue(); } @Test public void lastModifiedWorksWithResourceThatDoesNotSupportFileBasedAccessAtAll() throws Exception { Resource resource = new ByteArrayResource(new byte[0]); ResourceScriptSource scriptSource = new ResourceScriptSource(resource); - assertTrue("ResourceScriptSource must start off in the 'isModified' state (it obviously isn't).", scriptSource.isModified()); + assertThat(scriptSource.isModified()).as("ResourceScriptSource must start off in the 'isModified' state (it obviously isn't).").isTrue(); scriptSource.getScriptAsString(); - assertFalse("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.", scriptSource.isModified()); + assertThat(scriptSource.isModified()).as("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.").isFalse(); // Must now continue to report back as not having been modified 'cos the Resource does not support access as a File (and so the lastModified date cannot be determined). - assertFalse("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.", scriptSource.isModified()); + assertThat(scriptSource.isModified()).as("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.").isFalse(); } } diff --git a/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java b/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java index f359005706c..1bdaf6a9153 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java @@ -31,11 +31,9 @@ import org.springframework.scripting.groovy.GroovyScriptFactory; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; /** @@ -86,7 +84,7 @@ public class ScriptFactoryPostProcessorTests { @Test public void testDoesNothingWhenPostProcessingNonScriptFactoryTypeBeforeInstantiation() throws Exception { - assertNull(new ScriptFactoryPostProcessor().postProcessBeforeInstantiation(getClass(), "a.bean")); + assertThat(new ScriptFactoryPostProcessor().postProcessBeforeInstantiation(getClass(), "a.bean")).isNull(); } @Test @@ -106,14 +104,14 @@ public class ScriptFactoryPostProcessorTests { ctx.refresh(); Messenger messenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME); - assertEquals(MESSAGE_TEXT, messenger.getMessage()); + assertThat(messenger.getMessage()).isEqualTo(MESSAGE_TEXT); // cool; now let's change the script and check the refresh behaviour... pauseToLetRefreshDelayKickIn(DEFAULT_SECONDS_TO_PAUSE); StaticScriptSource source = getScriptSource(ctx); source.setScript(CHANGED_SCRIPT); Messenger refreshedMessenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME); // the updated script surrounds the message in quotes before returning... - assertEquals(EXPECTED_CHANGED_MESSAGE_TEXT, refreshedMessenger.getMessage()); + assertThat(refreshedMessenger.getMessage()).isEqualTo(EXPECTED_CHANGED_MESSAGE_TEXT); } @Test @@ -127,14 +125,13 @@ public class ScriptFactoryPostProcessorTests { ctx.refresh(); Messenger messenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME); - assertEquals(MESSAGE_TEXT, messenger.getMessage()); + assertThat(messenger.getMessage()).isEqualTo(MESSAGE_TEXT); // cool; now let's change the script and check the refresh behaviour... pauseToLetRefreshDelayKickIn(DEFAULT_SECONDS_TO_PAUSE); StaticScriptSource source = getScriptSource(ctx); source.setScript(CHANGED_SCRIPT); Messenger refreshedMessenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME); - assertEquals("Script seems to have been refreshed (must not be as no refreshCheckDelay set on ScriptFactoryPostProcessor)", - MESSAGE_TEXT, refreshedMessenger.getMessage()); + assertThat(refreshedMessenger.getMessage()).as("Script seems to have been refreshed (must not be as no refreshCheckDelay set on ScriptFactoryPostProcessor)").isEqualTo(MESSAGE_TEXT); } @Test @@ -152,17 +149,17 @@ public class ScriptFactoryPostProcessorTests { ctx.refresh(); Messenger messenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME); - assertEquals(MESSAGE_TEXT, messenger.getMessage()); + assertThat(messenger.getMessage()).isEqualTo(MESSAGE_TEXT); // cool; now let's change the script and check the refresh behaviour... pauseToLetRefreshDelayKickIn(DEFAULT_SECONDS_TO_PAUSE); StaticScriptSource source = getScriptSource(ctx); source.setScript(CHANGED_SCRIPT); Messenger refreshedMessenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME); // the updated script surrounds the message in quotes before returning... - assertEquals(EXPECTED_CHANGED_MESSAGE_TEXT, refreshedMessenger.getMessage()); + assertThat(refreshedMessenger.getMessage()).isEqualTo(EXPECTED_CHANGED_MESSAGE_TEXT); // ok, is this change reflected in the reference that the collaborator has? DefaultMessengerService collaborator = (DefaultMessengerService) ctx.getBean(collaboratorBeanName); - assertEquals(EXPECTED_CHANGED_MESSAGE_TEXT, collaborator.getMessage()); + assertThat(collaborator.getMessage()).isEqualTo(EXPECTED_CHANGED_MESSAGE_TEXT); } @Test @@ -202,7 +199,7 @@ public class ScriptFactoryPostProcessorTests { ctx.refresh(); Messenger messenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME); - assertEquals(MESSAGE_TEXT, messenger.getMessage()); + assertThat(messenger.getMessage()).isEqualTo(MESSAGE_TEXT); // cool; now let's change the script and check the refresh behaviour... pauseToLetRefreshDelayKickIn(DEFAULT_SECONDS_TO_PAUSE); StaticScriptSource source = getScriptSource(ctx); @@ -231,7 +228,7 @@ public class ScriptFactoryPostProcessorTests { Messenger messenger1 = (Messenger) ctx.getBean(BEAN_WITH_DEPENDENCY_NAME); Messenger messenger2 = (Messenger) ctx.getBean(BEAN_WITH_DEPENDENCY_NAME); - assertNotSame(messenger1, messenger2); + assertThat(messenger2).isNotSameAs(messenger1); } private static StaticScriptSource getScriptSource(GenericApplicationContext ctx) throws Exception { diff --git a/spring-context/src/test/java/org/springframework/scripting/support/StandardScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/support/StandardScriptFactoryTests.java index aa1d73fe7f3..2d1d9d962f0 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/StandardScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/StandardScriptFactoryTests.java @@ -26,9 +26,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.scripting.Messenger; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * {@link StandardScriptFactory} (lang:std) tests for JavaScript. @@ -41,29 +39,30 @@ public class StandardScriptFactoryTests { @Test public void testJsr223FromTagWithInterface() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("jsr223-with-xsd.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithInterface")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithInterface")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("messengerWithInterface"); - assertFalse(AopUtils.isAopProxy(messenger)); - assertEquals("Hello World!", messenger.getMessage()); + assertThat(AopUtils.isAopProxy(messenger)).isFalse(); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); } @Test public void testRefreshableJsr223FromTagWithInterface() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("jsr223-with-xsd.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessengerWithInterface")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessengerWithInterface")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("refreshableMessengerWithInterface"); - assertTrue(AopUtils.isAopProxy(messenger)); - assertTrue(messenger instanceof Refreshable); - assertEquals("Hello World!", messenger.getMessage()); + assertThat(AopUtils.isAopProxy(messenger)).isTrue(); + boolean condition = messenger instanceof Refreshable; + assertThat(condition).isTrue(); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); } @Test public void testInlineJsr223FromTagWithInterface() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("jsr223-with-xsd.xml", getClass()); - assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("inlineMessengerWithInterface")); + assertThat(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("inlineMessengerWithInterface")).isTrue(); Messenger messenger = (Messenger) ctx.getBean("inlineMessengerWithInterface"); - assertFalse(AopUtils.isAopProxy(messenger)); - assertEquals("Hello World!", messenger.getMessage()); + assertThat(AopUtils.isAopProxy(messenger)).isFalse(); + assertThat(messenger.getMessage()).isEqualTo("Hello World!"); } } diff --git a/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java b/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java index 00a65b6ef97..9ebce57c509 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java @@ -18,10 +18,8 @@ package org.springframework.scripting.support; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for the StaticScriptSource class. @@ -56,32 +54,32 @@ public class StaticScriptSourceTests { @Test public void isModifiedIsTrueByDefault() throws Exception { - assertTrue("Script must be flagged as 'modified' when first created.", source.isModified()); + assertThat(source.isModified()).as("Script must be flagged as 'modified' when first created.").isTrue(); } @Test public void gettingScriptTogglesIsModified() throws Exception { source.getScriptAsString(); - assertFalse("Script must be flagged as 'not modified' after script is read.", source.isModified()); + assertThat(source.isModified()).as("Script must be flagged as 'not modified' after script is read.").isFalse(); } @Test public void gettingScriptViaToStringDoesNotToggleIsModified() throws Exception { boolean isModifiedState = source.isModified(); source.toString(); - assertEquals("Script's 'modified' flag must not change after script is read via toString().", isModifiedState, source.isModified()); + assertThat(source.isModified()).as("Script's 'modified' flag must not change after script is read via toString().").isEqualTo(isModifiedState); } @Test public void isModifiedToggledWhenDifferentScriptIsSet() throws Exception { source.setScript("use warnings;"); - assertTrue("Script must be flagged as 'modified' when different script is passed in.", source.isModified()); + assertThat(source.isModified()).as("Script must be flagged as 'modified' when different script is passed in.").isTrue(); } @Test public void isModifiedNotToggledWhenSameScriptIsSet() throws Exception { source.setScript(SCRIPT_TEXT); - assertFalse("Script must not be flagged as 'modified' when same script is passed in.", source.isModified()); + assertThat(source.isModified()).as("Script must not be flagged as 'modified' when same script is passed in.").isFalse(); } } diff --git a/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java b/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java index 4010da14105..9a85a76396f 100644 --- a/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java +++ b/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java @@ -34,12 +34,8 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Rick Evans @@ -50,7 +46,7 @@ public class ModelMapTests { @Test public void testNoArgCtorYieldsEmptyModel() throws Exception { - assertEquals(0, new ModelMap().size()); + assertThat(new ModelMap().size()).isEqualTo(0); } /* @@ -60,8 +56,8 @@ public class ModelMapTests { public void testAddNullObjectWithExplicitKey() throws Exception { ModelMap model = new ModelMap(); model.addAttribute("foo", null); - assertTrue(model.containsKey("foo")); - assertNull(model.get("foo")); + assertThat(model.containsKey("foo")).isTrue(); + assertThat(model.get("foo")).isNull(); } /* @@ -70,35 +66,35 @@ public class ModelMapTests { @Test public void testAddNullObjectViaCtorWithExplicitKey() throws Exception { ModelMap model = new ModelMap("foo", null); - assertTrue(model.containsKey("foo")); - assertNull(model.get("foo")); + assertThat(model.containsKey("foo")).isTrue(); + assertThat(model.get("foo")).isNull(); } @Test public void testNamedObjectCtor() throws Exception { ModelMap model = new ModelMap("foo", "bing"); - assertEquals(1, model.size()); + assertThat(model.size()).isEqualTo(1); String bing = (String) model.get("foo"); - assertNotNull(bing); - assertEquals("bing", bing); + assertThat(bing).isNotNull(); + assertThat(bing).isEqualTo("bing"); } @Test public void testUnnamedCtorScalar() throws Exception { ModelMap model = new ModelMap("foo", "bing"); - assertEquals(1, model.size()); + assertThat(model.size()).isEqualTo(1); String bing = (String) model.get("foo"); - assertNotNull(bing); - assertEquals("bing", bing); + assertThat(bing).isNotNull(); + assertThat(bing).isEqualTo("bing"); } @Test public void testOneArgCtorWithScalar() throws Exception { ModelMap model = new ModelMap("bing"); - assertEquals(1, model.size()); + assertThat(model.size()).isEqualTo(1); String string = (String) model.get("string"); - assertNotNull(string); - assertEquals("bing", string); + assertThat(string).isNotNull(); + assertThat(string).isEqualTo("bing"); } @Test @@ -111,19 +107,19 @@ public class ModelMapTests { @Test public void testOneArgCtorWithCollection() throws Exception { ModelMap model = new ModelMap(new String[]{"foo", "boing"}); - assertEquals(1, model.size()); + assertThat(model.size()).isEqualTo(1); String[] strings = (String[]) model.get("stringList"); - assertNotNull(strings); - assertEquals(2, strings.length); - assertEquals("foo", strings[0]); - assertEquals("boing", strings[1]); + assertThat(strings).isNotNull(); + assertThat(strings.length).isEqualTo(2); + assertThat(strings[0]).isEqualTo("foo"); + assertThat(strings[1]).isEqualTo("boing"); } @Test public void testOneArgCtorWithEmptyCollection() throws Exception { ModelMap model = new ModelMap(new HashSet<>()); // must not add if collection is empty... - assertEquals(0, model.size()); + assertThat(model.size()).isEqualTo(0); } @Test @@ -137,24 +133,24 @@ public class ModelMapTests { @Test public void testAddObjectWithEmptyArray() throws Exception { ModelMap model = new ModelMap(new int[]{}); - assertEquals(1, model.size()); + assertThat(model.size()).isEqualTo(1); int[] ints = (int[]) model.get("intList"); - assertNotNull(ints); - assertEquals(0, ints.length); + assertThat(ints).isNotNull(); + assertThat(ints.length).isEqualTo(0); } @Test public void testAddAllObjectsWithNullMap() throws Exception { ModelMap model = new ModelMap(); model.addAllAttributes((Map) null); - assertEquals(0, model.size()); + assertThat(model.size()).isEqualTo(0); } @Test public void testAddAllObjectsWithNullCollection() throws Exception { ModelMap model = new ModelMap(); model.addAllAttributes((Collection) null); - assertEquals(0, model.size()); + assertThat(model.size()).isEqualTo(0); } @Test @@ -175,9 +171,9 @@ public class ModelMapTests { map.put("two", "two-value"); ModelMap model = new ModelMap(); model.addAttribute(map); - assertEquals(1, model.size()); + assertThat(model.size()).isEqualTo(1); String key = StringUtils.uncapitalize(ClassUtils.getShortName(map.getClass())); - assertTrue(model.containsKey(key)); + assertThat(model.containsKey(key)).isTrue(); } @Test @@ -185,9 +181,9 @@ public class ModelMapTests { ModelMap model = new ModelMap(); model.addAttribute("foo"); model.addAttribute("bar"); - assertEquals(1, model.size()); + assertThat(model.size()).isEqualTo(1); String bar = (String) model.get("string"); - assertEquals("bar", bar); + assertThat(bar).isEqualTo("bar"); } @Test @@ -198,7 +194,7 @@ public class ModelMapTests { beans.add(new TestBean("three")); ModelMap model = new ModelMap(); model.addAllAttributes(beans); - assertEquals(1, model.size()); + assertThat(model.size()).isEqualTo(1); } @Test @@ -210,8 +206,8 @@ public class ModelMapTests { ModelMap model = new ModelMap(); model.put("one", new TestBean("oneOld")); model.mergeAttributes(beans); - assertEquals(3, model.size()); - assertEquals("oneOld", ((TestBean) model.get("one")).getName()); + assertThat(model.size()).isEqualTo(3); + assertThat(((TestBean) model.get("one")).getName()).isEqualTo("oneOld"); } @Test @@ -219,7 +215,7 @@ public class ModelMapTests { ModelMap map = new ModelMap(); SomeInnerClass inner = new SomeInnerClass(); map.addAttribute(inner); - assertSame(inner, map.get("someInnerClass")); + assertThat(map.get("someInnerClass")).isSameAs(inner); } @Test @@ -227,7 +223,7 @@ public class ModelMapTests { ModelMap map = new ModelMap(); UKInnerClass inner = new UKInnerClass(); map.addAttribute(inner); - assertSame(inner, map.get("UKInnerClass")); + assertThat(map.get("UKInnerClass")).isSameAs(inner); } @Test @@ -238,8 +234,8 @@ public class ModelMapTests { factory.setTarget(val); factory.setProxyTargetClass(true); map.addAttribute(factory.getProxy()); - assertTrue(map.containsKey("someInnerClass")); - assertEquals(val, map.get("someInnerClass")); + assertThat(map.containsKey("someInnerClass")).isTrue(); + assertThat(val).isEqualTo(map.get("someInnerClass")); } @Test @@ -251,7 +247,7 @@ public class ModelMapTests { factory.addInterface(Map.class); Object proxy = factory.getProxy(); map.addAttribute(proxy); - assertSame(proxy, map.get("map")); + assertThat(map.get("map")).isSameAs(proxy); } @Test @@ -266,7 +262,7 @@ public class ModelMapTests { factory.addInterface(Map.class); Object proxy = factory.getProxy(); map.addAttribute(proxy); - assertSame(proxy, map.get("map")); + assertThat(map.get("map")).isSameAs(proxy); } @Test @@ -276,7 +272,7 @@ public class ModelMapTests { ProxyFactory factory = new ProxyFactory(target); Object proxy = factory.getProxy(); map.addAttribute(proxy); - assertSame(proxy, map.get("map")); + assertThat(map.get("map")).isSameAs(proxy); } @Test @@ -292,7 +288,7 @@ public class ModelMapTests { } }); map.addAttribute(proxy); - assertSame(proxy, map.get("map")); + assertThat(map.get("map")).isSameAs(proxy); } diff --git a/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java b/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java index 55aec0b3aa0..bcd425f9ff3 100644 --- a/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java @@ -30,8 +30,6 @@ 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -44,7 +42,7 @@ public class DataBinderFieldAccessTests { public void bindingNoErrors() throws Exception { FieldAccessBean rod = new FieldAccessBean(); DataBinder binder = new DataBinder(rod, "person"); - assertTrue(binder.isIgnoreUnknownFields()); + assertThat(binder.isIgnoreUnknownFields()).isTrue(); binder.initDirectFieldAccess(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("name", "Rod")); @@ -54,13 +52,13 @@ public class DataBinderFieldAccessTests { binder.bind(pvs); binder.close(); - assertTrue("changed name correctly", rod.getName().equals("Rod")); - assertTrue("changed age correctly", rod.getAge() == 32); + assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue(); + assertThat(rod.getAge() == 32).as("changed age correctly").isTrue(); Map m = binder.getBindingResult().getModel(); - assertTrue("There is one element in map", m.size() == 2); + assertThat(m.size() == 2).as("There is one element in map").isTrue(); FieldAccessBean tb = (FieldAccessBean) m.get("person"); - assertTrue("Same object", tb.equals(rod)); + assertThat(tb.equals(rod)).as("Same object").isTrue(); } @Test @@ -110,7 +108,7 @@ public class DataBinderFieldAccessTests { public void nestedBindingWithDefaultConversionNoErrors() throws Exception { FieldAccessBean rod = new FieldAccessBean(); DataBinder binder = new DataBinder(rod, "person"); - assertTrue(binder.isIgnoreUnknownFields()); + assertThat(binder.isIgnoreUnknownFields()).isTrue(); binder.initDirectFieldAccess(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("spouse.name", "Kerry")); @@ -119,8 +117,8 @@ public class DataBinderFieldAccessTests { binder.bind(pvs); binder.close(); - assertEquals("Kerry", rod.getSpouse().getName()); - assertTrue((rod.getSpouse()).isJedi()); + assertThat(rod.getSpouse().getName()).isEqualTo("Kerry"); + assertThat((rod.getSpouse()).isJedi()).isTrue(); } @Test diff --git a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java index 5e8af88d687..a05f1072c06 100644 --- a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java @@ -70,11 +70,6 @@ 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -88,7 +83,7 @@ public class DataBinderTests { public void testBindingNoErrors() throws BindException { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); - assertTrue(binder.isIgnoreUnknownFields()); + assertThat(binder.isIgnoreUnknownFields()).isTrue(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("name", "Rod"); pvs.add("age", "032"); @@ -97,32 +92,33 @@ public class DataBinderTests { binder.bind(pvs); binder.close(); - assertTrue("changed name correctly", rod.getName().equals("Rod")); - assertTrue("changed age correctly", rod.getAge() == 32); + assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue(); + assertThat(rod.getAge() == 32).as("changed age correctly").isTrue(); Map map = binder.getBindingResult().getModel(); - assertTrue("There is one element in map", map.size() == 2); + assertThat(map.size() == 2).as("There is one element in map").isTrue(); TestBean tb = (TestBean) map.get("person"); - assertTrue("Same object", tb.equals(rod)); + assertThat(tb.equals(rod)).as("Same object").isTrue(); BindingResult other = new BeanPropertyBindingResult(rod, "person"); - assertEquals(other, binder.getBindingResult()); - assertEquals(binder.getBindingResult(), other); + assertThat(binder.getBindingResult()).isEqualTo(other); + assertThat(other).isEqualTo(binder.getBindingResult()); BindException ex = new BindException(other); - assertEquals(ex, other); - assertEquals(other, ex); - assertEquals(ex, binder.getBindingResult()); - assertEquals(binder.getBindingResult(), ex); + assertThat(other).isEqualTo(ex); + assertThat(ex).isEqualTo(other); + assertThat(binder.getBindingResult()).isEqualTo(ex); + assertThat(ex).isEqualTo(binder.getBindingResult()); other.reject("xxx"); - assertTrue(!other.equals(binder.getBindingResult())); + boolean condition = !other.equals(binder.getBindingResult()); + assertThat(condition).isTrue(); } @Test public void testBindingWithDefaultConversionNoErrors() throws BindException { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); - assertTrue(binder.isIgnoreUnknownFields()); + assertThat(binder.isIgnoreUnknownFields()).isTrue(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("name", "Rod"); pvs.add("jedi", "on"); @@ -130,15 +126,15 @@ public class DataBinderTests { binder.bind(pvs); binder.close(); - assertEquals("Rod", rod.getName()); - assertTrue(rod.isJedi()); + assertThat(rod.getName()).isEqualTo("Rod"); + assertThat(rod.isJedi()).isTrue(); } @Test public void testNestedBindingWithDefaultConversionNoErrors() throws BindException { TestBean rod = new TestBean(new TestBean()); DataBinder binder = new DataBinder(rod, "person"); - assertTrue(binder.isIgnoreUnknownFields()); + assertThat(binder.isIgnoreUnknownFields()).isTrue(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("spouse.name", "Kerry"); pvs.add("spouse.jedi", "on"); @@ -146,8 +142,8 @@ public class DataBinderTests { binder.bind(pvs); binder.close(); - assertEquals("Kerry", rod.getSpouse().getName()); - assertTrue(((TestBean) rod.getSpouse()).isJedi()); + assertThat(rod.getSpouse().getName()).isEqualTo("Kerry"); + assertThat(((TestBean) rod.getSpouse()).isJedi()).isTrue(); } @Test @@ -244,8 +240,8 @@ public class DataBinderTests { pvs2.add("age", "32x"); pvs2.add("touchy", "m.y"); binder2.bind(pvs2); - assertEquals(binder2.getBindingResult(), ex.getBindingResult()); - }); + assertThat(ex.getBindingResult()).isEqualTo(binder2.getBindingResult()); + }); } @Test @@ -336,7 +332,7 @@ public class DataBinderTests { MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("object", "1"); binder.bind(pvs); - assertEquals(new Integer(1), tb.getObject()); + assertThat(tb.getObject()).isEqualTo(new Integer(1)); } @Test @@ -353,18 +349,18 @@ public class DataBinderTests { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertEquals(new Float(1.2), tb.getMyFloat()); - assertEquals("1,2", binder.getBindingResult().getFieldValue("myFloat")); + assertThat(tb.getMyFloat()).isEqualTo(new Float(1.2)); + assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1,2"); PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class); - assertNotNull(editor); + assertThat(editor).isNotNull(); editor.setValue(new Float(1.4)); - assertEquals("1,4", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo("1,4"); editor = binder.getBindingResult().findEditor("myFloat", null); - assertNotNull(editor); + assertThat(editor).isNotNull(); editor.setAsText("1,6"); - assertEquals(new Float(1.6), editor.getValue()); + assertThat(editor.getValue()).isEqualTo(new Float(1.6)); } finally { LocaleContextHolder.resetLocaleContext(); @@ -385,9 +381,9 @@ public class DataBinderTests { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertEquals(new Float(0.0), tb.getMyFloat()); - assertEquals("1x2", binder.getBindingResult().getFieldValue("myFloat")); - assertTrue(binder.getBindingResult().hasFieldErrors("myFloat")); + assertThat(tb.getMyFloat()).isEqualTo(new Float(0.0)); + assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1x2"); + assertThat(binder.getBindingResult().hasFieldErrors("myFloat")).isTrue(); } finally { LocaleContextHolder.resetLocaleContext(); @@ -417,9 +413,9 @@ public class DataBinderTests { pvs.add("name", "test"); binder.bind(pvs); - assertTrue(binder.getBindingResult().hasFieldErrors("name")); - assertEquals("typeMismatch", binder.getBindingResult().getFieldError("name").getCode()); - assertEquals("test", binder.getBindingResult().getFieldValue("name")); + assertThat(binder.getBindingResult().hasFieldErrors("name")).isTrue(); + assertThat(binder.getBindingResult().getFieldError("name").getCode()).isEqualTo("typeMismatch"); + assertThat(binder.getBindingResult().getFieldValue("name")).isEqualTo("test"); } @Test @@ -445,9 +441,9 @@ public class DataBinderTests { pvs.add("name", "test"); binder.bind(pvs); - assertTrue(binder.getBindingResult().hasFieldErrors("name")); - assertEquals("typeMismatch", binder.getBindingResult().getFieldError("name").getCode()); - assertEquals("test", binder.getBindingResult().getFieldValue("name")); + assertThat(binder.getBindingResult().hasFieldErrors("name")).isTrue(); + assertThat(binder.getBindingResult().getFieldError("name").getCode()).isEqualTo("typeMismatch"); + assertThat(binder.getBindingResult().getFieldValue("name")).isEqualTo("test"); } @Test @@ -464,8 +460,8 @@ public class DataBinderTests { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertEquals(new Integer(1), tb.getIntegerList().get(0)); - assertEquals("1", binder.getBindingResult().getFieldValue("integerList[0]")); + assertThat(tb.getIntegerList().get(0)).isEqualTo(new Integer(1)); + assertThat(binder.getBindingResult().getFieldValue("integerList[0]")).isEqualTo("1"); } finally { LocaleContextHolder.resetLocaleContext(); @@ -486,9 +482,9 @@ public class DataBinderTests { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertTrue(tb.getIntegerList().isEmpty()); - assertEquals("1x2", binder.getBindingResult().getFieldValue("integerList[0]")); - assertTrue(binder.getBindingResult().hasFieldErrors("integerList[0]")); + assertThat(tb.getIntegerList().isEmpty()).isTrue(); + assertThat(binder.getBindingResult().getFieldValue("integerList[0]")).isEqualTo("1x2"); + assertThat(binder.getBindingResult().hasFieldErrors("integerList[0]")).isTrue(); } finally { LocaleContextHolder.resetLocaleContext(); @@ -510,18 +506,18 @@ public class DataBinderTests { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertEquals(new Float(1.2), tb.getMyFloat()); - assertEquals("1,2", binder.getBindingResult().getFieldValue("myFloat")); + assertThat(tb.getMyFloat()).isEqualTo(new Float(1.2)); + assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1,2"); PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class); - assertNotNull(editor); + assertThat(editor).isNotNull(); editor.setValue(new Float(1.4)); - assertEquals("1,4", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo("1,4"); editor = binder.getBindingResult().findEditor("myFloat", null); - assertNotNull(editor); + assertThat(editor).isNotNull(); editor.setAsText("1,6"); - assertEquals(new Float(1.6), editor.getValue()); + assertThat(editor.getValue()).isEqualTo(new Float(1.6)); } finally { LocaleContextHolder.resetLocaleContext(); @@ -543,9 +539,9 @@ public class DataBinderTests { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertEquals(new Float(0.0), tb.getMyFloat()); - assertEquals("1x2", binder.getBindingResult().getFieldValue("myFloat")); - assertTrue(binder.getBindingResult().hasFieldErrors("myFloat")); + assertThat(tb.getMyFloat()).isEqualTo(new Float(0.0)); + assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1x2"); + assertThat(binder.getBindingResult().hasFieldErrors("myFloat")).isTrue(); } finally { LocaleContextHolder.resetLocaleContext(); @@ -563,18 +559,18 @@ public class DataBinderTests { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertEquals(new Float(1.2), tb.getMyFloat()); - assertEquals("1,2", binder.getBindingResult().getFieldValue("myFloat")); + assertThat(tb.getMyFloat()).isEqualTo(new Float(1.2)); + assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1,2"); PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class); - assertNotNull(editor); + assertThat(editor).isNotNull(); editor.setValue(new Float(1.4)); - assertEquals("1,4", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo("1,4"); editor = binder.getBindingResult().findEditor("myFloat", null); - assertNotNull(editor); + assertThat(editor).isNotNull(); editor.setAsText("1,6"); - assertTrue(((Number) editor.getValue()).floatValue() == 1.6f); + assertThat(((Number) editor.getValue()).floatValue() == 1.6f).isTrue(); } finally { LocaleContextHolder.resetLocaleContext(); @@ -592,10 +588,10 @@ public class DataBinderTests { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertEquals(new Float(0.0), tb.getMyFloat()); - assertEquals("1x2", binder.getBindingResult().getFieldValue("myFloat")); - assertTrue(binder.getBindingResult().hasFieldErrors("myFloat")); - assertEquals("typeMismatch", binder.getBindingResult().getFieldError("myFloat").getCode()); + assertThat(tb.getMyFloat()).isEqualTo(new Float(0.0)); + assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1x2"); + assertThat(binder.getBindingResult().hasFieldErrors("myFloat")).isTrue(); + assertThat(binder.getBindingResult().getFieldError("myFloat").getCode()).isEqualTo("typeMismatch"); } finally { LocaleContextHolder.resetLocaleContext(); @@ -622,9 +618,9 @@ public class DataBinderTests { pvs.add("name", "test"); binder.bind(pvs); - assertTrue(binder.getBindingResult().hasFieldErrors("name")); - assertEquals("test", binder.getBindingResult().getFieldValue("name")); - assertEquals("typeMismatch", binder.getBindingResult().getFieldError("name").getCode()); + assertThat(binder.getBindingResult().hasFieldErrors("name")).isTrue(); + assertThat(binder.getBindingResult().getFieldValue("name")).isEqualTo("test"); + assertThat(binder.getBindingResult().getFieldError("name").getCode()).isEqualTo("typeMismatch"); } @Test @@ -647,9 +643,9 @@ public class DataBinderTests { pvs.add("name", "test"); binder.bind(pvs); - assertTrue(binder.getBindingResult().hasFieldErrors("name")); - assertEquals("test", binder.getBindingResult().getFieldValue("name")); - assertEquals("typeMismatch", binder.getBindingResult().getFieldError("name").getCode()); + assertThat(binder.getBindingResult().hasFieldErrors("name")).isTrue(); + assertThat(binder.getBindingResult().getFieldValue("name")).isEqualTo("test"); + assertThat(binder.getBindingResult().getFieldError("name").getCode()).isEqualTo("typeMismatch"); } @Test @@ -660,9 +656,9 @@ public class DataBinderTests { dataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); NameBean bean = new NameBean("Fred"); - assertEquals("ConversionService should have invoked toString()", "Fred", dataBinder.convertIfNecessary(bean, String.class)); + assertThat(dataBinder.convertIfNecessary(bean, String.class)).as("ConversionService should have invoked toString()").isEqualTo("Fred"); conversionService.addConverter(new NameBeanConverter()); - assertEquals("Type converter should have been used", "[Fred]", dataBinder.convertIfNecessary(bean, String.class)); + assertThat(dataBinder.convertIfNecessary(bean, String.class)).as("Type converter should have been used").isEqualTo("[Fred]"); } @Test @@ -676,8 +672,8 @@ public class DataBinderTests { binder.bind(pvs); binder.close(); - assertTrue("changed name correctly", rod.getName().equals("Rod")); - assertTrue("did not change age", rod.getAge() == 0); + assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue(); + assertThat(rod.getAge() == 0).as("did not change age").isTrue(); } @Test @@ -691,11 +687,11 @@ public class DataBinderTests { binder.bind(pvs); binder.close(); - assertTrue("changed name correctly", rod.getName().equals("Rod")); - assertTrue("did not change age", rod.getAge() == 0); + assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue(); + assertThat(rod.getAge() == 0).as("did not change age").isTrue(); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); - assertEquals(1, disallowedFields.length); - assertEquals("age", disallowedFields[0]); + assertThat(disallowedFields.length).isEqualTo(1); + assertThat(disallowedFields[0]).isEqualTo("age"); } @Test @@ -710,11 +706,11 @@ public class DataBinderTests { binder.bind(pvs); binder.close(); - assertTrue("changed name correctly", rod.getName().equals("Rod")); - assertTrue("did not change age", rod.getAge() == 0); + assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue(); + assertThat(rod.getAge() == 0).as("did not change age").isTrue(); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); - assertEquals(1, disallowedFields.length); - assertEquals("age", disallowedFields[0]); + assertThat(disallowedFields.length).isEqualTo(1); + assertThat(disallowedFields[0]).isEqualTo("age"); } @Test @@ -729,11 +725,11 @@ public class DataBinderTests { binder.bind(pvs); binder.close(); - assertTrue("changed name correctly", rod.getName().equals("Rod")); - assertTrue("did not change age", rod.getAge() == 0); + assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue(); + assertThat(rod.getAge() == 0).as("did not change age").isTrue(); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); - assertEquals(1, disallowedFields.length); - assertEquals("age", disallowedFields[0]); + assertThat(disallowedFields.length).isEqualTo(1); + assertThat(disallowedFields[0]).isEqualTo("age"); } @Test @@ -750,17 +746,17 @@ public class DataBinderTests { binder.bind(pvs); binder.close(); - assertTrue("changed name correctly", "Rod".equals(rod.getName())); - assertTrue("changed touchy correctly", "Rod".equals(rod.getTouchy())); - assertTrue("did not change age", rod.getAge() == 0); + assertThat("Rod".equals(rod.getName())).as("changed name correctly").isTrue(); + assertThat("Rod".equals(rod.getTouchy())).as("changed touchy correctly").isTrue(); + assertThat(rod.getAge() == 0).as("did not change age").isTrue(); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); - assertEquals(1, disallowedFields.length); - assertEquals("age", disallowedFields[0]); + assertThat(disallowedFields.length).isEqualTo(1); + assertThat(disallowedFields[0]).isEqualTo("age"); Map m = binder.getBindingResult().getModel(); - assertTrue("There is one element in map", m.size() == 2); + assertThat(m.size() == 2).as("There is one element in map").isTrue(); TestBean tb = (TestBean) m.get("person"); - assertTrue("Same object", tb.equals(rod)); + assertThat(tb.equals(rod)).as("Same object").isTrue(); } @Test @@ -778,14 +774,14 @@ public class DataBinderTests { binder.bind(pvs); binder.close(); - assertEquals("value1", rod.getSomeMap().get("key1")); - assertEquals("value2", rod.getSomeMap().get("key2")); - assertNull(rod.getSomeMap().get("key3")); - assertNull(rod.getSomeMap().get("key4")); + assertThat(rod.getSomeMap().get("key1")).isEqualTo("value1"); + assertThat(rod.getSomeMap().get("key2")).isEqualTo("value2"); + assertThat(rod.getSomeMap().get("key3")).isNull(); + assertThat(rod.getSomeMap().get("key4")).isNull(); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); - assertEquals(2, disallowedFields.length); - assertTrue(ObjectUtils.containsElement(disallowedFields, "someMap[key3]")); - assertTrue(ObjectUtils.containsElement(disallowedFields, "someMap[key4]")); + assertThat(disallowedFields.length).isEqualTo(2); + assertThat(ObjectUtils.containsElement(disallowedFields, "someMap[key3]")).isTrue(); + assertThat(ObjectUtils.containsElement(disallowedFields, "someMap[key4]")).isTrue(); } /** @@ -808,18 +804,18 @@ public class DataBinderTests { binder.bind(pvs); BindingResult br = binder.getBindingResult(); - assertEquals("Wrong number of errors", 5, br.getErrorCount()); + assertThat(br.getErrorCount()).as("Wrong number of errors").isEqualTo(5); - assertEquals("required", br.getFieldError("touchy").getCode()); - assertEquals("", br.getFieldValue("touchy")); - assertEquals("required", br.getFieldError("name").getCode()); - assertEquals("", br.getFieldValue("name")); - assertEquals("required", br.getFieldError("age").getCode()); - assertEquals("", br.getFieldValue("age")); - assertEquals("required", br.getFieldError("date").getCode()); - assertEquals("", br.getFieldValue("date")); - assertEquals("required", br.getFieldError("spouse.name").getCode()); - assertEquals("", br.getFieldValue("spouse.name")); + assertThat(br.getFieldError("touchy").getCode()).isEqualTo("required"); + assertThat(br.getFieldValue("touchy")).isEqualTo(""); + assertThat(br.getFieldError("name").getCode()).isEqualTo("required"); + assertThat(br.getFieldValue("name")).isEqualTo(""); + assertThat(br.getFieldError("age").getCode()).isEqualTo("required"); + assertThat(br.getFieldValue("age")).isEqualTo(""); + assertThat(br.getFieldError("date").getCode()).isEqualTo("required"); + assertThat(br.getFieldValue("date")).isEqualTo(""); + assertThat(br.getFieldError("spouse.name").getCode()).isEqualTo("required"); + assertThat(br.getFieldValue("spouse.name")).isEqualTo(""); } @Test @@ -838,8 +834,8 @@ public class DataBinderTests { binder.bind(pvs); BindingResult br = binder.getBindingResult(); - assertEquals("Wrong number of errors", 1, br.getErrorCount()); - assertEquals("required", br.getFieldError("someMap[key4]").getCode()); + assertThat(br.getErrorCount()).as("Wrong number of errors").isEqualTo(1); + assertThat(br.getFieldError("someMap[key4]").getCode()).isEqualTo("required"); } @Test @@ -859,8 +855,8 @@ public class DataBinderTests { pvs.add("spouse.name", "test"); binder.bind(pvs); - assertNotNull(tb.getSpouse()); - assertEquals("test", tb.getSpouse().getName()); + assertThat(tb.getSpouse()).isNotNull(); + assertThat(tb.getSpouse().getName()).isEqualTo("test"); } @Test @@ -880,12 +876,12 @@ public class DataBinderTests { MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("name", "value"); binder.bind(pvs); - assertEquals("value", tb.getName()); + assertThat(tb.getName()).isEqualTo("value"); pvs = new MutablePropertyValues(); pvs.add("name", "vaLue"); binder.bind(pvs); - assertEquals("value", tb.getName()); + assertThat(tb.getName()).isEqualTo("value"); } @Test @@ -915,17 +911,17 @@ public class DataBinderTests { binder.getBindingResult().rejectValue("touchy", "someCode", "someMessage"); binder.getBindingResult().rejectValue("spouse.name", "someCode", "someMessage"); - assertEquals("", binder.getBindingResult().getNestedPath()); - assertEquals("value", binder.getBindingResult().getFieldValue("name")); - assertEquals("prefixvalue", binder.getBindingResult().getFieldError("name").getRejectedValue()); - assertEquals("prefixvalue", tb.getName()); - assertEquals("value", binder.getBindingResult().getFieldValue("touchy")); - assertEquals("value", binder.getBindingResult().getFieldError("touchy").getRejectedValue()); - assertEquals("value", tb.getTouchy()); + assertThat(binder.getBindingResult().getNestedPath()).isEqualTo(""); + assertThat(binder.getBindingResult().getFieldValue("name")).isEqualTo("value"); + assertThat(binder.getBindingResult().getFieldError("name").getRejectedValue()).isEqualTo("prefixvalue"); + assertThat(tb.getName()).isEqualTo("prefixvalue"); + assertThat(binder.getBindingResult().getFieldValue("touchy")).isEqualTo("value"); + assertThat(binder.getBindingResult().getFieldError("touchy").getRejectedValue()).isEqualTo("value"); + assertThat(tb.getTouchy()).isEqualTo("value"); - assertTrue(binder.getBindingResult().hasFieldErrors("spouse.*")); - assertEquals(1, binder.getBindingResult().getFieldErrorCount("spouse.*")); - assertEquals("spouse.name", binder.getBindingResult().getFieldError("spouse.*").getField()); + assertThat(binder.getBindingResult().hasFieldErrors("spouse.*")).isTrue(); + assertThat(binder.getBindingResult().getFieldErrorCount("spouse.*")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldError("spouse.*").getField()).isEqualTo("spouse.name"); } @Test @@ -948,8 +944,8 @@ public class DataBinderTests { pvs.add("age", ""); binder.bind(pvs); - assertEquals("argh", binder.getBindingResult().getFieldValue("age")); - assertEquals(99, tb.getAge()); + assertThat(binder.getBindingResult().getFieldValue("age")).isEqualTo("argh"); + assertThat(tb.getAge()).isEqualTo(99); } @Test @@ -976,12 +972,12 @@ public class DataBinderTests { binder.getBindingResult().rejectValue("name", "someCode", "someMessage"); binder.getBindingResult().rejectValue("touchy", "someCode", "someMessage"); - assertEquals("value", binder.getBindingResult().getFieldValue("name")); - assertEquals("prefixvalue", binder.getBindingResult().getFieldError("name").getRejectedValue()); - assertEquals("prefixvalue", tb.getName()); - assertEquals("value", binder.getBindingResult().getFieldValue("touchy")); - assertEquals("prefixvalue", binder.getBindingResult().getFieldError("touchy").getRejectedValue()); - assertEquals("prefixvalue", tb.getTouchy()); + assertThat(binder.getBindingResult().getFieldValue("name")).isEqualTo("value"); + assertThat(binder.getBindingResult().getFieldError("name").getRejectedValue()).isEqualTo("prefixvalue"); + assertThat(tb.getName()).isEqualTo("prefixvalue"); + assertThat(binder.getBindingResult().getFieldValue("touchy")).isEqualTo("value"); + assertThat(binder.getBindingResult().getFieldError("touchy").getRejectedValue()).isEqualTo("prefixvalue"); + assertThat(tb.getTouchy()).isEqualTo("prefixvalue"); } @Test @@ -1011,17 +1007,17 @@ public class DataBinderTests { binder.getBindingResult().rejectValue("touchy", "someCode", "someMessage"); binder.getBindingResult().rejectValue("spouse.name", "someCode", "someMessage"); - assertEquals("", binder.getBindingResult().getNestedPath()); - assertEquals("value", binder.getBindingResult().getFieldValue("name")); - assertEquals("prefixvalue", binder.getBindingResult().getFieldError("name").getRejectedValue()); - assertEquals("prefixvalue", tb.getName()); - assertEquals("value", binder.getBindingResult().getFieldValue("touchy")); - assertEquals("value", binder.getBindingResult().getFieldError("touchy").getRejectedValue()); - assertEquals("value", tb.getTouchy()); + assertThat(binder.getBindingResult().getNestedPath()).isEqualTo(""); + assertThat(binder.getBindingResult().getFieldValue("name")).isEqualTo("value"); + assertThat(binder.getBindingResult().getFieldError("name").getRejectedValue()).isEqualTo("prefixvalue"); + assertThat(tb.getName()).isEqualTo("prefixvalue"); + assertThat(binder.getBindingResult().getFieldValue("touchy")).isEqualTo("value"); + assertThat(binder.getBindingResult().getFieldError("touchy").getRejectedValue()).isEqualTo("value"); + assertThat(tb.getTouchy()).isEqualTo("value"); - assertTrue(binder.getBindingResult().hasFieldErrors("spouse.*")); - assertEquals(1, binder.getBindingResult().getFieldErrorCount("spouse.*")); - assertEquals("spouse.name", binder.getBindingResult().getFieldError("spouse.*").getField()); + assertThat(binder.getBindingResult().hasFieldErrors("spouse.*")).isTrue(); + assertThat(binder.getBindingResult().getFieldErrorCount("spouse.*")).isEqualTo(1); + assertThat(binder.getBindingResult().getFieldError("spouse.*").getField()).isEqualTo("spouse.name"); } @Test @@ -1044,8 +1040,8 @@ public class DataBinderTests { pvs.add("age", "x"); binder.bind(pvs); - assertEquals("argh", binder.getBindingResult().getFieldValue("age")); - assertEquals(99, tb.getAge()); + assertThat(binder.getBindingResult().getFieldValue("age")).isEqualTo("argh"); + assertThat(tb.getAge()).isEqualTo(99); } @Test @@ -1072,12 +1068,12 @@ public class DataBinderTests { binder.getBindingResult().rejectValue("name", "someCode", "someMessage"); binder.getBindingResult().rejectValue("touchy", "someCode", "someMessage"); - assertEquals("value", binder.getBindingResult().getFieldValue("name")); - assertEquals("prefixvalue", binder.getBindingResult().getFieldError("name").getRejectedValue()); - assertEquals("prefixvalue", tb.getName()); - assertEquals("value", binder.getBindingResult().getFieldValue("touchy")); - assertEquals("prefixvalue", binder.getBindingResult().getFieldError("touchy").getRejectedValue()); - assertEquals("prefixvalue", tb.getTouchy()); + assertThat(binder.getBindingResult().getFieldValue("name")).isEqualTo("value"); + assertThat(binder.getBindingResult().getFieldError("name").getRejectedValue()).isEqualTo("prefixvalue"); + assertThat(tb.getName()).isEqualTo("prefixvalue"); + assertThat(binder.getBindingResult().getFieldValue("touchy")).isEqualTo("value"); + assertThat(binder.getBindingResult().getFieldError("touchy").getRejectedValue()).isEqualTo("prefixvalue"); + assertThat(tb.getTouchy()).isEqualTo("prefixvalue"); } @Test @@ -1090,18 +1086,18 @@ public class DataBinderTests { pvs.add("ISBN", "1234"); pvs.add("NInStock", "5"); binder.bind(pvs); - assertEquals("my book", book.getTitle()); - assertEquals("1234", book.getISBN()); - assertEquals(5, book.getNInStock()); + assertThat(book.getTitle()).isEqualTo("my book"); + assertThat(book.getISBN()).isEqualTo("1234"); + assertThat(book.getNInStock()).isEqualTo(5); pvs = new MutablePropertyValues(); pvs.add("Title", "my other book"); pvs.add("iSBN", "6789"); pvs.add("nInStock", "0"); binder.bind(pvs); - assertEquals("my other book", book.getTitle()); - assertEquals("6789", book.getISBN()); - assertEquals(0, book.getNInStock()); + assertThat(book.getTitle()).isEqualTo("my other book"); + assertThat(book.getISBN()).isEqualTo("6789"); + assertThat(book.getNInStock()).isEqualTo(0); } @Test @@ -1114,15 +1110,15 @@ public class DataBinderTests { pvs.add("id", "1"); pvs.add("name", null); binder.bind(pvs); - assertEquals("1", bean.getId()); - assertFalse(bean.getName().isPresent()); + assertThat(bean.getId()).isEqualTo("1"); + assertThat(bean.getName().isPresent()).isFalse(); pvs = new MutablePropertyValues(); pvs.add("id", "2"); pvs.add("name", "myName"); binder.bind(pvs); - assertEquals("2", bean.getId()); - assertEquals("myName", bean.getName().get()); + assertThat(bean.getId()).isEqualTo("2"); + assertThat(bean.getName().get()).isEqualTo("myName"); } @Test @@ -1143,21 +1139,21 @@ public class DataBinderTests { testValidator.validate(tb, errors); errors.setNestedPath("spouse"); - assertEquals("spouse.", errors.getNestedPath()); - assertEquals("argh", errors.getFieldValue("age")); + assertThat(errors.getNestedPath()).isEqualTo("spouse."); + assertThat(errors.getFieldValue("age")).isEqualTo("argh"); Validator spouseValidator = new SpouseValidator(); spouseValidator.validate(tb.getSpouse(), errors); errors.setNestedPath(""); - assertEquals("", errors.getNestedPath()); + assertThat(errors.getNestedPath()).isEqualTo(""); errors.pushNestedPath("spouse"); - assertEquals("spouse.", errors.getNestedPath()); + assertThat(errors.getNestedPath()).isEqualTo("spouse."); errors.pushNestedPath("spouse"); - assertEquals("spouse.spouse.", errors.getNestedPath()); + assertThat(errors.getNestedPath()).isEqualTo("spouse.spouse."); errors.popNestedPath(); - assertEquals("spouse.", errors.getNestedPath()); + assertThat(errors.getNestedPath()).isEqualTo("spouse."); errors.popNestedPath(); - assertEquals("", errors.getNestedPath()); + assertThat(errors.getNestedPath()).isEqualTo(""); try { errors.popNestedPath(); } @@ -1165,9 +1161,9 @@ public class DataBinderTests { // expected, because stack was empty } errors.pushNestedPath("spouse"); - assertEquals("spouse.", errors.getNestedPath()); + assertThat(errors.getNestedPath()).isEqualTo("spouse."); errors.setNestedPath(""); - assertEquals("", errors.getNestedPath()); + assertThat(errors.getNestedPath()).isEqualTo(""); try { errors.popNestedPath(); } @@ -1176,12 +1172,14 @@ public class DataBinderTests { } errors.pushNestedPath("spouse"); - assertEquals("spouse.", errors.getNestedPath()); + assertThat(errors.getNestedPath()).isEqualTo("spouse."); - assertEquals(1, errors.getErrorCount()); - assertTrue(!errors.hasGlobalErrors()); - assertEquals(1, errors.getFieldErrorCount("age")); - assertTrue(!errors.hasFieldErrors("name")); + assertThat(errors.getErrorCount()).isEqualTo(1); + boolean condition1 = !errors.hasGlobalErrors(); + assertThat(condition1).isTrue(); + assertThat(errors.getFieldErrorCount("age")).isEqualTo(1); + boolean condition = !errors.hasFieldErrors("name"); + assertThat(condition).isTrue(); } @Test @@ -1195,62 +1193,62 @@ public class DataBinderTests { testValidator.validate(tb, errors); errors.setNestedPath("spouse."); - assertEquals("spouse.", errors.getNestedPath()); + assertThat(errors.getNestedPath()).isEqualTo("spouse."); Validator spouseValidator = new SpouseValidator(); spouseValidator.validate(tb.getSpouse(), errors); errors.setNestedPath(""); - assertTrue(errors.hasErrors()); - assertEquals(6, errors.getErrorCount()); + assertThat(errors.hasErrors()).isTrue(); + assertThat(errors.getErrorCount()).isEqualTo(6); - assertEquals(2, errors.getGlobalErrorCount()); - assertEquals("NAME_TOUCHY_MISMATCH", errors.getGlobalError().getCode()); - assertEquals("NAME_TOUCHY_MISMATCH", (errors.getGlobalErrors().get(0)).getCode()); - assertEquals("NAME_TOUCHY_MISMATCH.tb", (errors.getGlobalErrors().get(0)).getCodes()[0]); - assertEquals("NAME_TOUCHY_MISMATCH", (errors.getGlobalErrors().get(0)).getCodes()[1]); - assertEquals("tb", (errors.getGlobalErrors().get(0)).getObjectName()); - assertEquals("GENERAL_ERROR", (errors.getGlobalErrors().get(1)).getCode()); - assertEquals("GENERAL_ERROR.tb", (errors.getGlobalErrors().get(1)).getCodes()[0]); - assertEquals("GENERAL_ERROR", (errors.getGlobalErrors().get(1)).getCodes()[1]); - assertEquals("msg", (errors.getGlobalErrors().get(1)).getDefaultMessage()); - assertEquals("arg", (errors.getGlobalErrors().get(1)).getArguments()[0]); + assertThat(errors.getGlobalErrorCount()).isEqualTo(2); + assertThat(errors.getGlobalError().getCode()).isEqualTo("NAME_TOUCHY_MISMATCH"); + assertThat((errors.getGlobalErrors().get(0)).getCode()).isEqualTo("NAME_TOUCHY_MISMATCH"); + assertThat((errors.getGlobalErrors().get(0)).getCodes()[0]).isEqualTo("NAME_TOUCHY_MISMATCH.tb"); + assertThat((errors.getGlobalErrors().get(0)).getCodes()[1]).isEqualTo("NAME_TOUCHY_MISMATCH"); + assertThat((errors.getGlobalErrors().get(0)).getObjectName()).isEqualTo("tb"); + assertThat((errors.getGlobalErrors().get(1)).getCode()).isEqualTo("GENERAL_ERROR"); + assertThat((errors.getGlobalErrors().get(1)).getCodes()[0]).isEqualTo("GENERAL_ERROR.tb"); + assertThat((errors.getGlobalErrors().get(1)).getCodes()[1]).isEqualTo("GENERAL_ERROR"); + assertThat((errors.getGlobalErrors().get(1)).getDefaultMessage()).isEqualTo("msg"); + assertThat((errors.getGlobalErrors().get(1)).getArguments()[0]).isEqualTo("arg"); - assertTrue(errors.hasFieldErrors()); - assertEquals(4, errors.getFieldErrorCount()); - assertEquals("TOO_YOUNG", errors.getFieldError().getCode()); - assertEquals("TOO_YOUNG", (errors.getFieldErrors().get(0)).getCode()); - assertEquals("age", (errors.getFieldErrors().get(0)).getField()); - assertEquals("AGE_NOT_ODD", (errors.getFieldErrors().get(1)).getCode()); - assertEquals("age", (errors.getFieldErrors().get(1)).getField()); - assertEquals("NOT_ROD", (errors.getFieldErrors().get(2)).getCode()); - assertEquals("name", (errors.getFieldErrors().get(2)).getField()); - assertEquals("TOO_YOUNG", (errors.getFieldErrors().get(3)).getCode()); - assertEquals("spouse.age", (errors.getFieldErrors().get(3)).getField()); + assertThat(errors.hasFieldErrors()).isTrue(); + assertThat(errors.getFieldErrorCount()).isEqualTo(4); + assertThat(errors.getFieldError().getCode()).isEqualTo("TOO_YOUNG"); + assertThat((errors.getFieldErrors().get(0)).getCode()).isEqualTo("TOO_YOUNG"); + assertThat((errors.getFieldErrors().get(0)).getField()).isEqualTo("age"); + assertThat((errors.getFieldErrors().get(1)).getCode()).isEqualTo("AGE_NOT_ODD"); + assertThat((errors.getFieldErrors().get(1)).getField()).isEqualTo("age"); + assertThat((errors.getFieldErrors().get(2)).getCode()).isEqualTo("NOT_ROD"); + assertThat((errors.getFieldErrors().get(2)).getField()).isEqualTo("name"); + assertThat((errors.getFieldErrors().get(3)).getCode()).isEqualTo("TOO_YOUNG"); + assertThat((errors.getFieldErrors().get(3)).getField()).isEqualTo("spouse.age"); - assertTrue(errors.hasFieldErrors("age")); - assertEquals(2, errors.getFieldErrorCount("age")); - assertEquals("TOO_YOUNG", errors.getFieldError("age").getCode()); - assertEquals("TOO_YOUNG", (errors.getFieldErrors("age").get(0)).getCode()); - assertEquals("tb", (errors.getFieldErrors("age").get(0)).getObjectName()); - assertEquals("age", (errors.getFieldErrors("age").get(0)).getField()); - assertEquals(new Integer(0), (errors.getFieldErrors("age").get(0)).getRejectedValue()); - assertEquals("AGE_NOT_ODD", (errors.getFieldErrors("age").get(1)).getCode()); + assertThat(errors.hasFieldErrors("age")).isTrue(); + assertThat(errors.getFieldErrorCount("age")).isEqualTo(2); + assertThat(errors.getFieldError("age").getCode()).isEqualTo("TOO_YOUNG"); + assertThat((errors.getFieldErrors("age").get(0)).getCode()).isEqualTo("TOO_YOUNG"); + assertThat((errors.getFieldErrors("age").get(0)).getObjectName()).isEqualTo("tb"); + assertThat((errors.getFieldErrors("age").get(0)).getField()).isEqualTo("age"); + assertThat((errors.getFieldErrors("age").get(0)).getRejectedValue()).isEqualTo(new Integer(0)); + assertThat((errors.getFieldErrors("age").get(1)).getCode()).isEqualTo("AGE_NOT_ODD"); - assertTrue(errors.hasFieldErrors("name")); - assertEquals(1, errors.getFieldErrorCount("name")); - assertEquals("NOT_ROD", errors.getFieldError("name").getCode()); - assertEquals("NOT_ROD.tb.name", errors.getFieldError("name").getCodes()[0]); - assertEquals("NOT_ROD.name", errors.getFieldError("name").getCodes()[1]); - assertEquals("NOT_ROD.java.lang.String", errors.getFieldError("name").getCodes()[2]); - assertEquals("NOT_ROD", errors.getFieldError("name").getCodes()[3]); - assertEquals("name", (errors.getFieldErrors("name").get(0)).getField()); - assertEquals(null, (errors.getFieldErrors("name").get(0)).getRejectedValue()); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldErrorCount("name")).isEqualTo(1); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("NOT_ROD"); + assertThat(errors.getFieldError("name").getCodes()[0]).isEqualTo("NOT_ROD.tb.name"); + assertThat(errors.getFieldError("name").getCodes()[1]).isEqualTo("NOT_ROD.name"); + assertThat(errors.getFieldError("name").getCodes()[2]).isEqualTo("NOT_ROD.java.lang.String"); + assertThat(errors.getFieldError("name").getCodes()[3]).isEqualTo("NOT_ROD"); + assertThat((errors.getFieldErrors("name").get(0)).getField()).isEqualTo("name"); + assertThat((errors.getFieldErrors("name").get(0)).getRejectedValue()).isEqualTo(null); - assertTrue(errors.hasFieldErrors("spouse.age")); - assertEquals(1, errors.getFieldErrorCount("spouse.age")); - assertEquals("TOO_YOUNG", errors.getFieldError("spouse.age").getCode()); - assertEquals("tb", (errors.getFieldErrors("spouse.age").get(0)).getObjectName()); - assertEquals(new Integer(0), (errors.getFieldErrors("spouse.age").get(0)).getRejectedValue()); + assertThat(errors.hasFieldErrors("spouse.age")).isTrue(); + assertThat(errors.getFieldErrorCount("spouse.age")).isEqualTo(1); + assertThat(errors.getFieldError("spouse.age").getCode()).isEqualTo("TOO_YOUNG"); + assertThat((errors.getFieldErrors("spouse.age").get(0)).getObjectName()).isEqualTo("tb"); + assertThat((errors.getFieldErrors("spouse.age").get(0)).getRejectedValue()).isEqualTo(new Integer(0)); } @Test @@ -1267,62 +1265,62 @@ public class DataBinderTests { testValidator.validate(tb, errors); errors.setNestedPath("spouse."); - assertEquals("spouse.", errors.getNestedPath()); + assertThat(errors.getNestedPath()).isEqualTo("spouse."); Validator spouseValidator = new SpouseValidator(); spouseValidator.validate(tb.getSpouse(), errors); errors.setNestedPath(""); - assertTrue(errors.hasErrors()); - assertEquals(6, errors.getErrorCount()); + assertThat(errors.hasErrors()).isTrue(); + assertThat(errors.getErrorCount()).isEqualTo(6); - assertEquals(2, errors.getGlobalErrorCount()); - assertEquals("validation.NAME_TOUCHY_MISMATCH", errors.getGlobalError().getCode()); - assertEquals("validation.NAME_TOUCHY_MISMATCH", (errors.getGlobalErrors().get(0)).getCode()); - assertEquals("validation.NAME_TOUCHY_MISMATCH.tb", (errors.getGlobalErrors().get(0)).getCodes()[0]); - assertEquals("validation.NAME_TOUCHY_MISMATCH", (errors.getGlobalErrors().get(0)).getCodes()[1]); - assertEquals("tb", (errors.getGlobalErrors().get(0)).getObjectName()); - assertEquals("validation.GENERAL_ERROR", (errors.getGlobalErrors().get(1)).getCode()); - assertEquals("validation.GENERAL_ERROR.tb", (errors.getGlobalErrors().get(1)).getCodes()[0]); - assertEquals("validation.GENERAL_ERROR", (errors.getGlobalErrors().get(1)).getCodes()[1]); - assertEquals("msg", (errors.getGlobalErrors().get(1)).getDefaultMessage()); - assertEquals("arg", (errors.getGlobalErrors().get(1)).getArguments()[0]); + assertThat(errors.getGlobalErrorCount()).isEqualTo(2); + assertThat(errors.getGlobalError().getCode()).isEqualTo("validation.NAME_TOUCHY_MISMATCH"); + assertThat((errors.getGlobalErrors().get(0)).getCode()).isEqualTo("validation.NAME_TOUCHY_MISMATCH"); + assertThat((errors.getGlobalErrors().get(0)).getCodes()[0]).isEqualTo("validation.NAME_TOUCHY_MISMATCH.tb"); + assertThat((errors.getGlobalErrors().get(0)).getCodes()[1]).isEqualTo("validation.NAME_TOUCHY_MISMATCH"); + assertThat((errors.getGlobalErrors().get(0)).getObjectName()).isEqualTo("tb"); + assertThat((errors.getGlobalErrors().get(1)).getCode()).isEqualTo("validation.GENERAL_ERROR"); + assertThat((errors.getGlobalErrors().get(1)).getCodes()[0]).isEqualTo("validation.GENERAL_ERROR.tb"); + assertThat((errors.getGlobalErrors().get(1)).getCodes()[1]).isEqualTo("validation.GENERAL_ERROR"); + assertThat((errors.getGlobalErrors().get(1)).getDefaultMessage()).isEqualTo("msg"); + assertThat((errors.getGlobalErrors().get(1)).getArguments()[0]).isEqualTo("arg"); - assertTrue(errors.hasFieldErrors()); - assertEquals(4, errors.getFieldErrorCount()); - assertEquals("validation.TOO_YOUNG", errors.getFieldError().getCode()); - assertEquals("validation.TOO_YOUNG", (errors.getFieldErrors().get(0)).getCode()); - assertEquals("age", (errors.getFieldErrors().get(0)).getField()); - assertEquals("validation.AGE_NOT_ODD", (errors.getFieldErrors().get(1)).getCode()); - assertEquals("age", (errors.getFieldErrors().get(1)).getField()); - assertEquals("validation.NOT_ROD", (errors.getFieldErrors().get(2)).getCode()); - assertEquals("name", (errors.getFieldErrors().get(2)).getField()); - assertEquals("validation.TOO_YOUNG", (errors.getFieldErrors().get(3)).getCode()); - assertEquals("spouse.age", (errors.getFieldErrors().get(3)).getField()); + assertThat(errors.hasFieldErrors()).isTrue(); + assertThat(errors.getFieldErrorCount()).isEqualTo(4); + assertThat(errors.getFieldError().getCode()).isEqualTo("validation.TOO_YOUNG"); + assertThat((errors.getFieldErrors().get(0)).getCode()).isEqualTo("validation.TOO_YOUNG"); + assertThat((errors.getFieldErrors().get(0)).getField()).isEqualTo("age"); + assertThat((errors.getFieldErrors().get(1)).getCode()).isEqualTo("validation.AGE_NOT_ODD"); + assertThat((errors.getFieldErrors().get(1)).getField()).isEqualTo("age"); + assertThat((errors.getFieldErrors().get(2)).getCode()).isEqualTo("validation.NOT_ROD"); + assertThat((errors.getFieldErrors().get(2)).getField()).isEqualTo("name"); + assertThat((errors.getFieldErrors().get(3)).getCode()).isEqualTo("validation.TOO_YOUNG"); + assertThat((errors.getFieldErrors().get(3)).getField()).isEqualTo("spouse.age"); - assertTrue(errors.hasFieldErrors("age")); - assertEquals(2, errors.getFieldErrorCount("age")); - assertEquals("validation.TOO_YOUNG", errors.getFieldError("age").getCode()); - assertEquals("validation.TOO_YOUNG", (errors.getFieldErrors("age").get(0)).getCode()); - assertEquals("tb", (errors.getFieldErrors("age").get(0)).getObjectName()); - assertEquals("age", (errors.getFieldErrors("age").get(0)).getField()); - assertEquals(new Integer(0), (errors.getFieldErrors("age").get(0)).getRejectedValue()); - assertEquals("validation.AGE_NOT_ODD", (errors.getFieldErrors("age").get(1)).getCode()); + assertThat(errors.hasFieldErrors("age")).isTrue(); + assertThat(errors.getFieldErrorCount("age")).isEqualTo(2); + assertThat(errors.getFieldError("age").getCode()).isEqualTo("validation.TOO_YOUNG"); + assertThat((errors.getFieldErrors("age").get(0)).getCode()).isEqualTo("validation.TOO_YOUNG"); + assertThat((errors.getFieldErrors("age").get(0)).getObjectName()).isEqualTo("tb"); + assertThat((errors.getFieldErrors("age").get(0)).getField()).isEqualTo("age"); + assertThat((errors.getFieldErrors("age").get(0)).getRejectedValue()).isEqualTo(new Integer(0)); + assertThat((errors.getFieldErrors("age").get(1)).getCode()).isEqualTo("validation.AGE_NOT_ODD"); - assertTrue(errors.hasFieldErrors("name")); - assertEquals(1, errors.getFieldErrorCount("name")); - assertEquals("validation.NOT_ROD", errors.getFieldError("name").getCode()); - assertEquals("validation.NOT_ROD.tb.name", errors.getFieldError("name").getCodes()[0]); - assertEquals("validation.NOT_ROD.name", errors.getFieldError("name").getCodes()[1]); - assertEquals("validation.NOT_ROD.java.lang.String", errors.getFieldError("name").getCodes()[2]); - assertEquals("validation.NOT_ROD", errors.getFieldError("name").getCodes()[3]); - assertEquals("name", (errors.getFieldErrors("name").get(0)).getField()); - assertEquals(null, (errors.getFieldErrors("name").get(0)).getRejectedValue()); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldErrorCount("name")).isEqualTo(1); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("validation.NOT_ROD"); + assertThat(errors.getFieldError("name").getCodes()[0]).isEqualTo("validation.NOT_ROD.tb.name"); + assertThat(errors.getFieldError("name").getCodes()[1]).isEqualTo("validation.NOT_ROD.name"); + assertThat(errors.getFieldError("name").getCodes()[2]).isEqualTo("validation.NOT_ROD.java.lang.String"); + assertThat(errors.getFieldError("name").getCodes()[3]).isEqualTo("validation.NOT_ROD"); + assertThat((errors.getFieldErrors("name").get(0)).getField()).isEqualTo("name"); + assertThat((errors.getFieldErrors("name").get(0)).getRejectedValue()).isEqualTo(null); - assertTrue(errors.hasFieldErrors("spouse.age")); - assertEquals(1, errors.getFieldErrorCount("spouse.age")); - assertEquals("validation.TOO_YOUNG", errors.getFieldError("spouse.age").getCode()); - assertEquals("tb", (errors.getFieldErrors("spouse.age").get(0)).getObjectName()); - assertEquals(new Integer(0), (errors.getFieldErrors("spouse.age").get(0)).getRejectedValue()); + assertThat(errors.hasFieldErrors("spouse.age")).isTrue(); + assertThat(errors.getFieldErrorCount("spouse.age")).isEqualTo(1); + assertThat(errors.getFieldError("spouse.age").getCode()).isEqualTo("validation.TOO_YOUNG"); + assertThat((errors.getFieldErrors("spouse.age").get(0)).getObjectName()).isEqualTo("tb"); + assertThat((errors.getFieldErrors("spouse.age").get(0)).getRejectedValue()).isEqualTo(new Integer(0)); } @Test @@ -1332,16 +1330,16 @@ public class DataBinderTests { Validator testValidator = new TestBeanValidator(); testValidator.validate(tb, errors); errors.setNestedPath("spouse."); - assertEquals("spouse.", errors.getNestedPath()); + assertThat(errors.getNestedPath()).isEqualTo("spouse."); Validator spouseValidator = new SpouseValidator(); spouseValidator.validate(tb.getSpouse(), errors); errors.setNestedPath(""); - assertTrue(errors.hasFieldErrors("spouse")); - assertEquals(1, errors.getFieldErrorCount("spouse")); - assertEquals("SPOUSE_NOT_AVAILABLE", errors.getFieldError("spouse").getCode()); - assertEquals("tb", (errors.getFieldErrors("spouse").get(0)).getObjectName()); - assertEquals(null, (errors.getFieldErrors("spouse").get(0)).getRejectedValue()); + assertThat(errors.hasFieldErrors("spouse")).isTrue(); + assertThat(errors.getFieldErrorCount("spouse")).isEqualTo(1); + assertThat(errors.getFieldError("spouse").getCode()).isEqualTo("SPOUSE_NOT_AVAILABLE"); + assertThat((errors.getFieldErrors("spouse").get(0)).getObjectName()).isEqualTo("tb"); + assertThat((errors.getFieldErrors("spouse").get(0)).getRejectedValue()).isEqualTo(null); } @Test @@ -1352,10 +1350,10 @@ public class DataBinderTests { Validator spouseValidator = new SpouseValidator(); spouseValidator.validate(tb, errors); - assertTrue(errors.hasGlobalErrors()); - assertEquals(1, errors.getGlobalErrorCount()); - assertEquals("SPOUSE_NOT_AVAILABLE", errors.getGlobalError().getCode()); - assertEquals("tb", (errors.getGlobalErrors().get(0)).getObjectName()); + assertThat(errors.hasGlobalErrors()).isTrue(); + assertThat(errors.getGlobalErrorCount()).isEqualTo(1); + assertThat(errors.getGlobalError().getCode()).isEqualTo("SPOUSE_NOT_AVAILABLE"); + assertThat((errors.getGlobalErrors().get(0)).getObjectName()).isEqualTo("tb"); } @Test @@ -1372,18 +1370,19 @@ public class DataBinderTests { pvs.add("set", new String[] {"10", "20", "30"}); binder.bind(pvs); - assertEquals(tb.getSet(), binder.getBindingResult().getFieldValue("set")); - assertTrue(tb.getSet() instanceof TreeSet); - assertEquals(3, tb.getSet().size()); - assertTrue(tb.getSet().contains(new Integer(10))); - assertTrue(tb.getSet().contains(new Integer(20))); - assertTrue(tb.getSet().contains(new Integer(30))); + assertThat(binder.getBindingResult().getFieldValue("set")).isEqualTo(tb.getSet()); + boolean condition = tb.getSet() instanceof TreeSet; + assertThat(condition).isTrue(); + assertThat(tb.getSet().size()).isEqualTo(3); + assertThat(tb.getSet().contains(new Integer(10))).isTrue(); + assertThat(tb.getSet().contains(new Integer(20))).isTrue(); + assertThat(tb.getSet().contains(new Integer(30))).isTrue(); pvs = new MutablePropertyValues(); pvs.add("set", null); binder.bind(pvs); - assertNull(tb.getSet()); + assertThat(tb.getSet()).isNull(); } @Test @@ -1395,8 +1394,9 @@ public class DataBinderTests { pvs.add("set", null); binder.bind(pvs); - assertTrue(tb.getSet() instanceof TreeSet); - assertTrue(tb.getSet().isEmpty()); + boolean condition = tb.getSet() instanceof TreeSet; + assertThat(condition).isTrue(); + assertThat(tb.getSet().isEmpty()).isTrue(); } @Test @@ -1416,26 +1416,26 @@ public class DataBinderTests { errors.rejectValue("array[0].name", "NOT_ROD", "are you sure you're not Rod?"); errors.rejectValue("map[key1].name", "NOT_ROD", "are you sure you're not Rod?"); - assertEquals(1, errors.getFieldErrorCount("array[0].name")); - assertEquals("NOT_ROD", errors.getFieldError("array[0].name").getCode()); - assertEquals("NOT_ROD.tb.array[0].name", errors.getFieldError("array[0].name").getCodes()[0]); - assertEquals("NOT_ROD.tb.array.name", errors.getFieldError("array[0].name").getCodes()[1]); - assertEquals("NOT_ROD.array[0].name", errors.getFieldError("array[0].name").getCodes()[2]); - assertEquals("NOT_ROD.array.name", errors.getFieldError("array[0].name").getCodes()[3]); - assertEquals("NOT_ROD.name", errors.getFieldError("array[0].name").getCodes()[4]); - assertEquals("NOT_ROD.java.lang.String", errors.getFieldError("array[0].name").getCodes()[5]); - assertEquals("NOT_ROD", errors.getFieldError("array[0].name").getCodes()[6]); - assertEquals(1, errors.getFieldErrorCount("map[key1].name")); - assertEquals(1, errors.getFieldErrorCount("map['key1'].name")); - assertEquals(1, errors.getFieldErrorCount("map[\"key1\"].name")); - assertEquals("NOT_ROD", errors.getFieldError("map[key1].name").getCode()); - assertEquals("NOT_ROD.tb.map[key1].name", errors.getFieldError("map[key1].name").getCodes()[0]); - assertEquals("NOT_ROD.tb.map.name", errors.getFieldError("map[key1].name").getCodes()[1]); - assertEquals("NOT_ROD.map[key1].name", errors.getFieldError("map[key1].name").getCodes()[2]); - assertEquals("NOT_ROD.map.name", errors.getFieldError("map[key1].name").getCodes()[3]); - assertEquals("NOT_ROD.name", errors.getFieldError("map[key1].name").getCodes()[4]); - assertEquals("NOT_ROD.java.lang.String", errors.getFieldError("map[key1].name").getCodes()[5]); - assertEquals("NOT_ROD", errors.getFieldError("map[key1].name").getCodes()[6]); + assertThat(errors.getFieldErrorCount("array[0].name")).isEqualTo(1); + assertThat(errors.getFieldError("array[0].name").getCode()).isEqualTo("NOT_ROD"); + assertThat(errors.getFieldError("array[0].name").getCodes()[0]).isEqualTo("NOT_ROD.tb.array[0].name"); + assertThat(errors.getFieldError("array[0].name").getCodes()[1]).isEqualTo("NOT_ROD.tb.array.name"); + assertThat(errors.getFieldError("array[0].name").getCodes()[2]).isEqualTo("NOT_ROD.array[0].name"); + assertThat(errors.getFieldError("array[0].name").getCodes()[3]).isEqualTo("NOT_ROD.array.name"); + assertThat(errors.getFieldError("array[0].name").getCodes()[4]).isEqualTo("NOT_ROD.name"); + assertThat(errors.getFieldError("array[0].name").getCodes()[5]).isEqualTo("NOT_ROD.java.lang.String"); + assertThat(errors.getFieldError("array[0].name").getCodes()[6]).isEqualTo("NOT_ROD"); + assertThat(errors.getFieldErrorCount("map[key1].name")).isEqualTo(1); + assertThat(errors.getFieldErrorCount("map['key1'].name")).isEqualTo(1); + assertThat(errors.getFieldErrorCount("map[\"key1\"].name")).isEqualTo(1); + assertThat(errors.getFieldError("map[key1].name").getCode()).isEqualTo("NOT_ROD"); + assertThat(errors.getFieldError("map[key1].name").getCodes()[0]).isEqualTo("NOT_ROD.tb.map[key1].name"); + assertThat(errors.getFieldError("map[key1].name").getCodes()[1]).isEqualTo("NOT_ROD.tb.map.name"); + assertThat(errors.getFieldError("map[key1].name").getCodes()[2]).isEqualTo("NOT_ROD.map[key1].name"); + assertThat(errors.getFieldError("map[key1].name").getCodes()[3]).isEqualTo("NOT_ROD.map.name"); + assertThat(errors.getFieldError("map[key1].name").getCodes()[4]).isEqualTo("NOT_ROD.name"); + assertThat(errors.getFieldError("map[key1].name").getCodes()[5]).isEqualTo("NOT_ROD.java.lang.String"); + assertThat(errors.getFieldError("map[key1].name").getCodes()[6]).isEqualTo("NOT_ROD"); } @Test @@ -1456,24 +1456,17 @@ public class DataBinderTests { Errors errors = binder.getBindingResult(); errors.rejectValue("array[0].nestedIndexedBean.list[0].name", "NOT_ROD", "are you sure you're not Rod?"); - assertEquals(1, errors.getFieldErrorCount("array[0].nestedIndexedBean.list[0].name")); - assertEquals("NOT_ROD", errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCode()); - assertEquals("NOT_ROD.tb.array[0].nestedIndexedBean.list[0].name", - errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[0]); - assertEquals("NOT_ROD.tb.array[0].nestedIndexedBean.list.name", - errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[1]); - assertEquals("NOT_ROD.tb.array.nestedIndexedBean.list.name", - errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[2]); - assertEquals("NOT_ROD.array[0].nestedIndexedBean.list[0].name", - errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[3]); - assertEquals("NOT_ROD.array[0].nestedIndexedBean.list.name", - errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[4]); - assertEquals("NOT_ROD.array.nestedIndexedBean.list.name", - errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[5]); - assertEquals("NOT_ROD.name", errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[6]); - assertEquals("NOT_ROD.java.lang.String", - errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[7]); - assertEquals("NOT_ROD", errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[8]); + assertThat(errors.getFieldErrorCount("array[0].nestedIndexedBean.list[0].name")).isEqualTo(1); + assertThat(errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCode()).isEqualTo("NOT_ROD"); + assertThat(errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[0]).isEqualTo("NOT_ROD.tb.array[0].nestedIndexedBean.list[0].name"); + assertThat(errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[1]).isEqualTo("NOT_ROD.tb.array[0].nestedIndexedBean.list.name"); + assertThat(errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[2]).isEqualTo("NOT_ROD.tb.array.nestedIndexedBean.list.name"); + assertThat(errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[3]).isEqualTo("NOT_ROD.array[0].nestedIndexedBean.list[0].name"); + assertThat(errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[4]).isEqualTo("NOT_ROD.array[0].nestedIndexedBean.list.name"); + assertThat(errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[5]).isEqualTo("NOT_ROD.array.nestedIndexedBean.list.name"); + assertThat(errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[6]).isEqualTo("NOT_ROD.name"); + assertThat(errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[7]).isEqualTo("NOT_ROD.java.lang.String"); + assertThat(errors.getFieldError("array[0].nestedIndexedBean.list[0].name").getCodes()[8]).isEqualTo("NOT_ROD"); } @Test @@ -1496,10 +1489,10 @@ public class DataBinderTests { pvs.add("array[0].nestedIndexedBean.list[0].name", "test1"); pvs.add("array[1].nestedIndexedBean.list[1].name", "test2"); binder.bind(pvs); - assertEquals("listtest1", ((TestBean)tb.getArray()[0].getNestedIndexedBean().getList().get(0)).getName()); - assertEquals("listtest2", ((TestBean)tb.getArray()[1].getNestedIndexedBean().getList().get(1)).getName()); - assertEquals("test1", binder.getBindingResult().getFieldValue("array[0].nestedIndexedBean.list[0].name")); - assertEquals("test2", binder.getBindingResult().getFieldValue("array[1].nestedIndexedBean.list[1].name")); + assertThat(((TestBean) tb.getArray()[0].getNestedIndexedBean().getList().get(0)).getName()).isEqualTo("listtest1"); + assertThat(((TestBean) tb.getArray()[1].getNestedIndexedBean().getList().get(1)).getName()).isEqualTo("listtest2"); + assertThat(binder.getBindingResult().getFieldValue("array[0].nestedIndexedBean.list[0].name")).isEqualTo("test1"); + assertThat(binder.getBindingResult().getFieldValue("array[1].nestedIndexedBean.list[1].name")).isEqualTo("test2"); } @Test @@ -1522,10 +1515,10 @@ public class DataBinderTests { pvs.add("array[0].nestedIndexedBean.list[0].name", "test1"); pvs.add("array[1].nestedIndexedBean.list[1].name", "test2"); binder.bind(pvs); - assertEquals("listtest1", ((TestBean)tb.getArray()[0].getNestedIndexedBean().getList().get(0)).getName()); - assertEquals("test2", ((TestBean)tb.getArray()[1].getNestedIndexedBean().getList().get(1)).getName()); - assertEquals("test1", binder.getBindingResult().getFieldValue("array[0].nestedIndexedBean.list[0].name")); - assertEquals("test2", binder.getBindingResult().getFieldValue("array[1].nestedIndexedBean.list[1].name")); + assertThat(((TestBean) tb.getArray()[0].getNestedIndexedBean().getList().get(0)).getName()).isEqualTo("listtest1"); + assertThat(((TestBean) tb.getArray()[1].getNestedIndexedBean().getList().get(1)).getName()).isEqualTo("test2"); + assertThat(binder.getBindingResult().getFieldValue("array[0].nestedIndexedBean.list[0].name")).isEqualTo("test1"); + assertThat(binder.getBindingResult().getFieldValue("array[1].nestedIndexedBean.list[1].name")).isEqualTo("test2"); } @Test @@ -1548,10 +1541,10 @@ public class DataBinderTests { pvs.add("array[0].nestedIndexedBean.list[0].name", "test1"); pvs.add("array[1].nestedIndexedBean.list[1].name", "test2"); binder.bind(pvs); - assertEquals("listtest1", ((TestBean)tb.getArray()[0].getNestedIndexedBean().getList().get(0)).getName()); - assertEquals("test2", ((TestBean)tb.getArray()[1].getNestedIndexedBean().getList().get(1)).getName()); - assertEquals("test1", binder.getBindingResult().getFieldValue("array[0].nestedIndexedBean.list[0].name")); - assertEquals("test2", binder.getBindingResult().getFieldValue("array[1].nestedIndexedBean.list[1].name")); + assertThat(((TestBean) tb.getArray()[0].getNestedIndexedBean().getList().get(0)).getName()).isEqualTo("listtest1"); + assertThat(((TestBean) tb.getArray()[1].getNestedIndexedBean().getList().get(1)).getName()).isEqualTo("test2"); + assertThat(binder.getBindingResult().getFieldValue("array[0].nestedIndexedBean.list[0].name")).isEqualTo("test1"); + assertThat(binder.getBindingResult().getFieldValue("array[1].nestedIndexedBean.list[1].name")).isEqualTo("test2"); } @Test @@ -1578,33 +1571,33 @@ public class DataBinderTests { errors.rejectValue("map[key1]", "NOT_ROD", "are you sure you're not Rod?"); errors.rejectValue("map[key0]", "NOT_NULL", "should not be null"); - assertEquals("arraya", errors.getFieldValue("array[0]")); - assertEquals(1, errors.getFieldErrorCount("array[0]")); - assertEquals("NOT_ROD", errors.getFieldError("array[0]").getCode()); - assertEquals("NOT_ROD.tb.array[0]", errors.getFieldError("array[0]").getCodes()[0]); - assertEquals("NOT_ROD.tb.array", errors.getFieldError("array[0]").getCodes()[1]); - assertEquals("NOT_ROD.array[0]", errors.getFieldError("array[0]").getCodes()[2]); - assertEquals("NOT_ROD.array", errors.getFieldError("array[0]").getCodes()[3]); - assertEquals("NOT_ROD.org.springframework.tests.sample.beans.DerivedTestBean", errors.getFieldError("array[0]").getCodes()[4]); - assertEquals("NOT_ROD", errors.getFieldError("array[0]").getCodes()[5]); - assertEquals("arraya", errors.getFieldValue("array[0]")); + assertThat(errors.getFieldValue("array[0]")).isEqualTo("arraya"); + assertThat(errors.getFieldErrorCount("array[0]")).isEqualTo(1); + assertThat(errors.getFieldError("array[0]").getCode()).isEqualTo("NOT_ROD"); + assertThat(errors.getFieldError("array[0]").getCodes()[0]).isEqualTo("NOT_ROD.tb.array[0]"); + assertThat(errors.getFieldError("array[0]").getCodes()[1]).isEqualTo("NOT_ROD.tb.array"); + assertThat(errors.getFieldError("array[0]").getCodes()[2]).isEqualTo("NOT_ROD.array[0]"); + assertThat(errors.getFieldError("array[0]").getCodes()[3]).isEqualTo("NOT_ROD.array"); + assertThat(errors.getFieldError("array[0]").getCodes()[4]).isEqualTo("NOT_ROD.org.springframework.tests.sample.beans.DerivedTestBean"); + assertThat(errors.getFieldError("array[0]").getCodes()[5]).isEqualTo("NOT_ROD"); + assertThat(errors.getFieldValue("array[0]")).isEqualTo("arraya"); - assertEquals(1, errors.getFieldErrorCount("map[key1]")); - assertEquals("NOT_ROD", errors.getFieldError("map[key1]").getCode()); - assertEquals("NOT_ROD.tb.map[key1]", errors.getFieldError("map[key1]").getCodes()[0]); - assertEquals("NOT_ROD.tb.map", errors.getFieldError("map[key1]").getCodes()[1]); - assertEquals("NOT_ROD.map[key1]", errors.getFieldError("map[key1]").getCodes()[2]); - assertEquals("NOT_ROD.map", errors.getFieldError("map[key1]").getCodes()[3]); - assertEquals("NOT_ROD.org.springframework.tests.sample.beans.TestBean", errors.getFieldError("map[key1]").getCodes()[4]); - assertEquals("NOT_ROD", errors.getFieldError("map[key1]").getCodes()[5]); + assertThat(errors.getFieldErrorCount("map[key1]")).isEqualTo(1); + assertThat(errors.getFieldError("map[key1]").getCode()).isEqualTo("NOT_ROD"); + assertThat(errors.getFieldError("map[key1]").getCodes()[0]).isEqualTo("NOT_ROD.tb.map[key1]"); + assertThat(errors.getFieldError("map[key1]").getCodes()[1]).isEqualTo("NOT_ROD.tb.map"); + assertThat(errors.getFieldError("map[key1]").getCodes()[2]).isEqualTo("NOT_ROD.map[key1]"); + assertThat(errors.getFieldError("map[key1]").getCodes()[3]).isEqualTo("NOT_ROD.map"); + assertThat(errors.getFieldError("map[key1]").getCodes()[4]).isEqualTo("NOT_ROD.org.springframework.tests.sample.beans.TestBean"); + assertThat(errors.getFieldError("map[key1]").getCodes()[5]).isEqualTo("NOT_ROD"); - assertEquals(1, errors.getFieldErrorCount("map[key0]")); - assertEquals("NOT_NULL", errors.getFieldError("map[key0]").getCode()); - assertEquals("NOT_NULL.tb.map[key0]", errors.getFieldError("map[key0]").getCodes()[0]); - assertEquals("NOT_NULL.tb.map", errors.getFieldError("map[key0]").getCodes()[1]); - assertEquals("NOT_NULL.map[key0]", errors.getFieldError("map[key0]").getCodes()[2]); - assertEquals("NOT_NULL.map", errors.getFieldError("map[key0]").getCodes()[3]); - assertEquals("NOT_NULL", errors.getFieldError("map[key0]").getCodes()[4]); + assertThat(errors.getFieldErrorCount("map[key0]")).isEqualTo(1); + assertThat(errors.getFieldError("map[key0]").getCode()).isEqualTo("NOT_NULL"); + assertThat(errors.getFieldError("map[key0]").getCodes()[0]).isEqualTo("NOT_NULL.tb.map[key0]"); + assertThat(errors.getFieldError("map[key0]").getCodes()[1]).isEqualTo("NOT_NULL.tb.map"); + assertThat(errors.getFieldError("map[key0]").getCodes()[2]).isEqualTo("NOT_NULL.map[key0]"); + assertThat(errors.getFieldError("map[key0]").getCodes()[3]).isEqualTo("NOT_NULL.map"); + assertThat(errors.getFieldError("map[key0]").getCodes()[4]).isEqualTo("NOT_NULL"); } @Test @@ -1626,16 +1619,16 @@ public class DataBinderTests { Errors errors = binder.getBindingResult(); errors.rejectValue("map[key0]", "NOT_NULL", "should not be null"); - assertEquals(1, errors.getFieldErrorCount("map[key0]")); - assertEquals("NOT_NULL", errors.getFieldError("map[key0]").getCode()); - assertEquals("NOT_NULL.tb.map[key0]", errors.getFieldError("map[key0]").getCodes()[0]); - assertEquals("NOT_NULL.tb.map", errors.getFieldError("map[key0]").getCodes()[1]); - assertEquals("NOT_NULL.map[key0]", errors.getFieldError("map[key0]").getCodes()[2]); - assertEquals("NOT_NULL.map", errors.getFieldError("map[key0]").getCodes()[3]); + assertThat(errors.getFieldErrorCount("map[key0]")).isEqualTo(1); + assertThat(errors.getFieldError("map[key0]").getCode()).isEqualTo("NOT_NULL"); + assertThat(errors.getFieldError("map[key0]").getCodes()[0]).isEqualTo("NOT_NULL.tb.map[key0]"); + assertThat(errors.getFieldError("map[key0]").getCodes()[1]).isEqualTo("NOT_NULL.tb.map"); + assertThat(errors.getFieldError("map[key0]").getCodes()[2]).isEqualTo("NOT_NULL.map[key0]"); + assertThat(errors.getFieldError("map[key0]").getCodes()[3]).isEqualTo("NOT_NULL.map"); // This next code is only generated because of the registered editor, using the // registered type of the editor as guess for the content type of the collection. - assertEquals("NOT_NULL.org.springframework.tests.sample.beans.TestBean", errors.getFieldError("map[key0]").getCodes()[4]); - assertEquals("NOT_NULL", errors.getFieldError("map[key0]").getCodes()[5]); + assertThat(errors.getFieldError("map[key0]").getCodes()[4]).isEqualTo("NOT_NULL.org.springframework.tests.sample.beans.TestBean"); + assertThat(errors.getFieldError("map[key0]").getCodes()[5]).isEqualTo("NOT_NULL"); } @Test @@ -1657,16 +1650,16 @@ public class DataBinderTests { Errors errors = binder.getBindingResult(); errors.rejectValue("map[key0]", "NOT_NULL", "should not be null"); - assertEquals(1, errors.getFieldErrorCount("map[key0]")); - assertEquals("NOT_NULL", errors.getFieldError("map[key0]").getCode()); - assertEquals("NOT_NULL.tb.map[key0]", errors.getFieldError("map[key0]").getCodes()[0]); - assertEquals("NOT_NULL.tb.map", errors.getFieldError("map[key0]").getCodes()[1]); - assertEquals("NOT_NULL.map[key0]", errors.getFieldError("map[key0]").getCodes()[2]); - assertEquals("NOT_NULL.map", errors.getFieldError("map[key0]").getCodes()[3]); + assertThat(errors.getFieldErrorCount("map[key0]")).isEqualTo(1); + assertThat(errors.getFieldError("map[key0]").getCode()).isEqualTo("NOT_NULL"); + assertThat(errors.getFieldError("map[key0]").getCodes()[0]).isEqualTo("NOT_NULL.tb.map[key0]"); + assertThat(errors.getFieldError("map[key0]").getCodes()[1]).isEqualTo("NOT_NULL.tb.map"); + assertThat(errors.getFieldError("map[key0]").getCodes()[2]).isEqualTo("NOT_NULL.map[key0]"); + assertThat(errors.getFieldError("map[key0]").getCodes()[3]).isEqualTo("NOT_NULL.map"); // This next code is only generated because of the registered editor, using the // registered type of the editor as guess for the content type of the collection. - assertEquals("NOT_NULL.org.springframework.tests.sample.beans.TestBean", errors.getFieldError("map[key0]").getCodes()[4]); - assertEquals("NOT_NULL", errors.getFieldError("map[key0]").getCodes()[5]); + assertThat(errors.getFieldError("map[key0]").getCodes()[4]).isEqualTo("NOT_NULL.org.springframework.tests.sample.beans.TestBean"); + assertThat(errors.getFieldError("map[key0]").getCodes()[5]).isEqualTo("NOT_NULL"); } @Test @@ -1691,16 +1684,16 @@ public class DataBinderTests { Errors errors = binder.getBindingResult(); errors.rejectValue("array[0]", "NOT_ROD", "are you sure you're not Rod?"); - assertEquals("arraya", errors.getFieldValue("array[0]")); - assertEquals(1, errors.getFieldErrorCount("array[0]")); - assertEquals("NOT_ROD", errors.getFieldError("array[0]").getCode()); - assertEquals("NOT_ROD.tb.array[0]", errors.getFieldError("array[0]").getCodes()[0]); - assertEquals("NOT_ROD.tb.array", errors.getFieldError("array[0]").getCodes()[1]); - assertEquals("NOT_ROD.array[0]", errors.getFieldError("array[0]").getCodes()[2]); - assertEquals("NOT_ROD.array", errors.getFieldError("array[0]").getCodes()[3]); - assertEquals("NOT_ROD.org.springframework.tests.sample.beans.DerivedTestBean", errors.getFieldError("array[0]").getCodes()[4]); - assertEquals("NOT_ROD", errors.getFieldError("array[0]").getCodes()[5]); - assertEquals("arraya", errors.getFieldValue("array[0]")); + assertThat(errors.getFieldValue("array[0]")).isEqualTo("arraya"); + assertThat(errors.getFieldErrorCount("array[0]")).isEqualTo(1); + assertThat(errors.getFieldError("array[0]").getCode()).isEqualTo("NOT_ROD"); + assertThat(errors.getFieldError("array[0]").getCodes()[0]).isEqualTo("NOT_ROD.tb.array[0]"); + assertThat(errors.getFieldError("array[0]").getCodes()[1]).isEqualTo("NOT_ROD.tb.array"); + assertThat(errors.getFieldError("array[0]").getCodes()[2]).isEqualTo("NOT_ROD.array[0]"); + assertThat(errors.getFieldError("array[0]").getCodes()[3]).isEqualTo("NOT_ROD.array"); + assertThat(errors.getFieldError("array[0]").getCodes()[4]).isEqualTo("NOT_ROD.org.springframework.tests.sample.beans.DerivedTestBean"); + assertThat(errors.getFieldError("array[0]").getCodes()[5]).isEqualTo("NOT_ROD"); + assertThat(errors.getFieldValue("array[0]")).isEqualTo("arraya"); } @Test @@ -1716,10 +1709,11 @@ public class DataBinderTests { MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("stringArray", "a1-b2"); binder.bind(pvs); - assertTrue(!binder.getBindingResult().hasErrors()); - assertEquals(2, tb.getStringArray().length); - assertEquals("a1", tb.getStringArray()[0]); - assertEquals("b2", tb.getStringArray()[1]); + boolean condition = !binder.getBindingResult().hasErrors(); + assertThat(condition).isTrue(); + assertThat(tb.getStringArray().length).isEqualTo(2); + assertThat(tb.getStringArray()[0]).isEqualTo("a1"); + assertThat(tb.getStringArray()[1]).isEqualTo("b2"); } @Test @@ -1735,10 +1729,11 @@ public class DataBinderTests { MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("stringArray", new String[] {"a1", "b2"}); binder.bind(pvs); - assertTrue(!binder.getBindingResult().hasErrors()); - assertEquals(2, tb.getStringArray().length); - assertEquals("Xa1", tb.getStringArray()[0]); - assertEquals("Xb2", tb.getStringArray()[1]); + boolean condition = !binder.getBindingResult().hasErrors(); + assertThat(condition).isTrue(); + assertThat(tb.getStringArray().length).isEqualTo(2); + assertThat(tb.getStringArray()[0]).isEqualTo("Xa1"); + assertThat(tb.getStringArray()[1]).isEqualTo("Xb2"); } @Test @@ -1750,22 +1745,22 @@ public class DataBinderTests { binder.bind(pvs); Errors errors = binder.getBindingResult(); FieldError ageError = errors.getFieldError("age"); - assertEquals("typeMismatch", ageError.getCode()); + assertThat(ageError.getCode()).isEqualTo("typeMismatch"); ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("org.springframework.validation.messages1"); String msg = messageSource.getMessage(ageError, Locale.getDefault()); - assertEquals("Field age did not have correct type", msg); + assertThat(msg).isEqualTo("Field age did not have correct type"); messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("org.springframework.validation.messages2"); msg = messageSource.getMessage(ageError, Locale.getDefault()); - assertEquals("Field Age did not have correct type", msg); + assertThat(msg).isEqualTo("Field Age did not have correct type"); messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("org.springframework.validation.messages3"); msg = messageSource.getMessage(ageError, Locale.getDefault()); - assertEquals("Field Person Age did not have correct type", msg); + assertThat(msg).isEqualTo("Field Person Age did not have correct type"); } @Test @@ -1782,9 +1777,9 @@ public class DataBinderTests { errors.addAllErrors(errors2); FieldError ageError = errors.getFieldError("age"); - assertEquals("typeMismatch", ageError.getCode()); + assertThat(ageError.getCode()).isEqualTo("typeMismatch"); FieldError nameError = errors.getFieldError("name"); - assertEquals("badName", nameError.getCode()); + assertThat(nameError.getCode()).isEqualTo("badName"); } @Test @@ -1797,12 +1792,12 @@ public class DataBinderTests { pvs.add("list[0]", tb1); pvs.add("list[1]", tb2); binder.bind(pvs); - assertEquals(tb1.getName(), binder.getBindingResult().getFieldValue("list[0].name")); - assertEquals(tb2.getName(), binder.getBindingResult().getFieldValue("list[1].name")); + assertThat(binder.getBindingResult().getFieldValue("list[0].name")).isEqualTo(tb1.getName()); + assertThat(binder.getBindingResult().getFieldValue("list[1].name")).isEqualTo(tb2.getName()); tb.getList().set(0, tb2); tb.getList().set(1, tb1); - assertEquals(tb2.getName(), binder.getBindingResult().getFieldValue("list[0].name")); - assertEquals(tb1.getName(), binder.getBindingResult().getFieldValue("list[1].name")); + assertThat(binder.getBindingResult().getFieldValue("list[0].name")).isEqualTo(tb2.getName()); + assertThat(binder.getBindingResult().getFieldValue("list[1].name")).isEqualTo(tb1.getName()); } @Test @@ -1819,8 +1814,8 @@ public class DataBinderTests { ms.addMessage("invalid", Locale.US, "general error"); ms.addMessage("invalidField", Locale.US, "invalid field"); - assertEquals("general error", ms.getMessage(ex.getGlobalError(), Locale.US)); - assertEquals("invalid field", ms.getMessage(ex.getFieldError("age"), Locale.US)); + assertThat(ms.getMessage(ex.getGlobalError(), Locale.US)).isEqualTo("general error"); + assertThat(ms.getMessage(ex.getFieldError("age"), Locale.US)).isEqualTo("invalid field"); } @Test @@ -1840,16 +1835,16 @@ public class DataBinderTests { ObjectInputStream ois = new ObjectInputStream(bais); BindException ex2 = (BindException) ois.readObject(); - assertTrue(ex2.hasGlobalErrors()); - assertEquals("invalid", ex2.getGlobalError().getCode()); - assertTrue(ex2.hasFieldErrors("age")); - assertEquals("invalidField", ex2.getFieldError("age").getCode()); - assertEquals(new Integer(99), ex2.getFieldValue("age")); + assertThat(ex2.hasGlobalErrors()).isTrue(); + assertThat(ex2.getGlobalError().getCode()).isEqualTo("invalid"); + assertThat(ex2.hasFieldErrors("age")).isTrue(); + assertThat(ex2.getFieldError("age").getCode()).isEqualTo("invalidField"); + assertThat(ex2.getFieldValue("age")).isEqualTo(new Integer(99)); ex2.rejectValue("name", "invalidField", "someMessage"); - assertTrue(ex2.hasFieldErrors("name")); - assertEquals("invalidField", ex2.getFieldError("name").getCode()); - assertEquals("myName", ex2.getFieldValue("name")); + assertThat(ex2.hasFieldErrors("name")).isTrue(); + assertThat(ex2.getFieldError("name").getCode()).isEqualTo("invalidField"); + assertThat(ex2.getFieldValue("name")).isEqualTo("myName"); } @Test @@ -1866,10 +1861,10 @@ public class DataBinderTests { mpvs.add("beanName", beanName); binder.bind(mpvs); - assertEquals(name, testBean.getName()); + assertThat(testBean.getName()).isEqualTo(name); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); - assertEquals(1, disallowedFields.length); - assertEquals("beanName", disallowedFields[0]); + assertThat(disallowedFields.length).isEqualTo(1); + assertThat(disallowedFields[0]).isEqualTo("beanName"); } @Test @@ -1881,7 +1876,7 @@ public class DataBinderTests { mpvs.add("friends[4]", ""); binder.bind(mpvs); - assertEquals(5, testBean.getFriends().size()); + assertThat(testBean.getFriends().size()).isEqualTo(5); } @Test @@ -1906,7 +1901,7 @@ public class DataBinderTests { mpvs.add("friends[4]", ""); binder.bind(mpvs); - assertEquals(5, testBean.getFriends().size()); + assertThat(testBean.getFriends().size()).isEqualTo(5); } @Test @@ -1930,33 +1925,33 @@ public class DataBinderTests { mpv.add("f[list][0]", "firstValue"); mpv.add("f[list][1]", "secondValue"); binder.bind(mpv); - assertFalse(binder.getBindingResult().hasErrors()); + assertThat(binder.getBindingResult().hasErrors()).isFalse(); @SuppressWarnings("unchecked") List list = (List) form.getF().get("list"); - assertEquals("firstValue", list.get(0)); - assertEquals("secondValue", list.get(1)); - assertEquals(2, list.size()); + assertThat(list.get(0)).isEqualTo("firstValue"); + assertThat(list.get(1)).isEqualTo("secondValue"); + assertThat(list.size()).isEqualTo(2); } @Test public void testFieldErrorAccessVariations() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); - assertNull(binder.getBindingResult().getGlobalError()); - assertNull(binder.getBindingResult().getFieldError()); - assertNull(binder.getBindingResult().getFieldError("")); + assertThat(binder.getBindingResult().getGlobalError()).isNull(); + assertThat(binder.getBindingResult().getFieldError()).isNull(); + assertThat(binder.getBindingResult().getFieldError("")).isNull(); MutablePropertyValues mpv = new MutablePropertyValues(); mpv.add("age", "invalid"); binder.bind(mpv); - assertNull(binder.getBindingResult().getGlobalError()); - assertNull(binder.getBindingResult().getFieldError("")); - assertNull(binder.getBindingResult().getFieldError("b*")); - assertEquals("age", binder.getBindingResult().getFieldError().getField()); - assertEquals("age", binder.getBindingResult().getFieldError("*").getField()); - assertEquals("age", binder.getBindingResult().getFieldError("a*").getField()); - assertEquals("age", binder.getBindingResult().getFieldError("ag*").getField()); - assertEquals("age", binder.getBindingResult().getFieldError("age").getField()); + assertThat(binder.getBindingResult().getGlobalError()).isNull(); + assertThat(binder.getBindingResult().getFieldError("")).isNull(); + assertThat(binder.getBindingResult().getFieldError("b*")).isNull(); + assertThat(binder.getBindingResult().getFieldError().getField()).isEqualTo("age"); + assertThat(binder.getBindingResult().getFieldError("*").getField()).isEqualTo("age"); + assertThat(binder.getBindingResult().getFieldError("a*").getField()).isEqualTo("age"); + assertThat(binder.getBindingResult().getFieldError("ag*").getField()).isEqualTo("age"); + assertThat(binder.getBindingResult().getFieldError("age").getField()).isEqualTo("age"); } @Test // SPR-14888 @@ -1968,9 +1963,9 @@ public class DataBinderTests { pvs.add("integerList[256]", "1"); binder.bind(pvs); - assertEquals(257, tb.getIntegerList().size()); - assertEquals(Integer.valueOf(1), tb.getIntegerList().get(256)); - assertEquals(Integer.valueOf(1), binder.getBindingResult().getFieldValue("integerList[256]")); + assertThat(tb.getIntegerList().size()).isEqualTo(257); + assertThat(tb.getIntegerList().get(256)).isEqualTo(Integer.valueOf(1)); + assertThat(binder.getBindingResult().getFieldValue("integerList[256]")).isEqualTo(Integer.valueOf(1)); } @Test // SPR-14888 @@ -1995,8 +1990,8 @@ public class DataBinderTests { MutablePropertyValues mpv = new MutablePropertyValues(); mpv.add("age", "invalid"); binder.bind(mpv); - assertEquals("errors.typeMismatch", binder.getBindingResult().getFieldError("age").getCode()); - assertEquals(512, BeanWrapper.class.cast(binder.getInternalBindingResult().getPropertyAccessor()).getAutoGrowCollectionLimit()); + assertThat(binder.getBindingResult().getFieldError("age").getCode()).isEqualTo("errors.typeMismatch"); + assertThat(BeanWrapper.class.cast(binder.getInternalBindingResult().getPropertyAccessor()).getAutoGrowCollectionLimit()).isEqualTo(512); } @Test // SPR-15009 @@ -2011,7 +2006,7 @@ public class DataBinderTests { MutablePropertyValues mpv = new MutablePropertyValues(); mpv.add("age", "invalid"); binder.bind(mpv); - assertEquals("errors.typeMismatch", binder.getBindingResult().getFieldError("age").getCode()); + assertThat(binder.getBindingResult().getFieldError("age").getCode()).isEqualTo("errors.typeMismatch"); } @Test // SPR-15009 @@ -2026,7 +2021,7 @@ public class DataBinderTests { MutablePropertyValues mpv = new MutablePropertyValues(); mpv.add("age", "invalid"); binder.bind(mpv); - assertEquals("errors.typeMismatch", binder.getBindingResult().getFieldError("age").getCode()); + assertThat(binder.getBindingResult().getFieldError("age").getCode()).isEqualTo("errors.typeMismatch"); } @Test // SPR-15009 @@ -2039,7 +2034,8 @@ public class DataBinderTests { MutablePropertyValues mpv = new MutablePropertyValues(); mpv.add("age", "invalid"); binder.bind(mpv); - assertEquals("typeMismatch", binder.getBindingResult().getFieldError("age").getCode()); // Keep a default MessageCodesResolver + // Keep a default MessageCodesResolver + assertThat(binder.getBindingResult().getFieldError("age").getCode()).isEqualTo("typeMismatch"); } @Test // SPR-15009 diff --git a/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java b/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java index 77703ef58ea..c82077ab9f8 100644 --- a/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java +++ b/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java @@ -21,10 +21,8 @@ import org.junit.Test; import org.springframework.lang.Nullable; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link ValidationUtils}. @@ -56,8 +54,8 @@ public class ValidationUtilsTests { TestBean tb = new TestBean(); Errors errors = new BeanPropertyBindingResult(tb, "tb"); ValidationUtils.invokeValidator(new EmptyValidator(), tb, errors); - assertTrue(errors.hasFieldErrors("name")); - assertEquals("EMPTY", errors.getFieldError("name").getCode()); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY"); } @Test @@ -68,12 +66,12 @@ public class ValidationUtilsTests { tb.setName(" "); Errors errors = new BeanPropertyBindingResult(tb, "tb"); testValidator.validate(tb, errors); - assertFalse(errors.hasFieldErrors("name")); + assertThat(errors.hasFieldErrors("name")).isFalse(); tb.setName("Roddy"); errors = new BeanPropertyBindingResult(tb, "tb"); testValidator.validate(tb, errors); - assertFalse(errors.hasFieldErrors("name")); + assertThat(errors.hasFieldErrors("name")).isFalse(); } @Test @@ -82,8 +80,8 @@ public class ValidationUtilsTests { Errors errors = new BeanPropertyBindingResult(tb, "tb"); Validator testValidator = new EmptyValidator(); testValidator.validate(tb, errors); - assertTrue(errors.hasFieldErrors("name")); - assertEquals("EMPTY", errors.getFieldError("name").getCode()); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY"); } @Test @@ -92,8 +90,8 @@ public class ValidationUtilsTests { Errors errors = new BeanPropertyBindingResult(tb, "tb"); Validator testValidator = new EmptyValidator(); testValidator.validate(tb, errors); - assertTrue(errors.hasFieldErrors("name")); - assertEquals("EMPTY", errors.getFieldError("name").getCode()); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY"); } @Test @@ -102,16 +100,16 @@ public class ValidationUtilsTests { Errors errors = new BeanPropertyBindingResult(tb, "tb"); ValidationUtils.rejectIfEmpty(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"}); - assertTrue(errors.hasFieldErrors("name")); - assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode()); - assertEquals("arg", errors.getFieldError("name").getArguments()[0]); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE"); + assertThat(errors.getFieldError("name").getArguments()[0]).isEqualTo("arg"); errors = new BeanPropertyBindingResult(tb, "tb"); ValidationUtils.rejectIfEmpty(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"}, "msg"); - assertTrue(errors.hasFieldErrors("name")); - assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode()); - assertEquals("arg", errors.getFieldError("name").getArguments()[0]); - assertEquals("msg", errors.getFieldError("name").getDefaultMessage()); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE"); + assertThat(errors.getFieldError("name").getArguments()[0]).isEqualTo("arg"); + assertThat(errors.getFieldError("name").getDefaultMessage()).isEqualTo("msg"); } @Test @@ -122,28 +120,28 @@ public class ValidationUtilsTests { // Test null Errors errors = new BeanPropertyBindingResult(tb, "tb"); testValidator.validate(tb, errors); - assertTrue(errors.hasFieldErrors("name")); - assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode()); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE"); // Test empty String tb.setName(""); errors = new BeanPropertyBindingResult(tb, "tb"); testValidator.validate(tb, errors); - assertTrue(errors.hasFieldErrors("name")); - assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode()); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE"); // Test whitespace String tb.setName(" "); errors = new BeanPropertyBindingResult(tb, "tb"); testValidator.validate(tb, errors); - assertTrue(errors.hasFieldErrors("name")); - assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode()); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE"); // Test OK tb.setName("Roddy"); errors = new BeanPropertyBindingResult(tb, "tb"); testValidator.validate(tb, errors); - assertFalse(errors.hasFieldErrors("name")); + assertThat(errors.hasFieldErrors("name")).isFalse(); } @Test @@ -153,16 +151,16 @@ public class ValidationUtilsTests { Errors errors = new BeanPropertyBindingResult(tb, "tb"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"}); - assertTrue(errors.hasFieldErrors("name")); - assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode()); - assertEquals("arg", errors.getFieldError("name").getArguments()[0]); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE"); + assertThat(errors.getFieldError("name").getArguments()[0]).isEqualTo("arg"); errors = new BeanPropertyBindingResult(tb, "tb"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"}, "msg"); - assertTrue(errors.hasFieldErrors("name")); - assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode()); - assertEquals("arg", errors.getFieldError("name").getArguments()[0]); - assertEquals("msg", errors.getFieldError("name").getDefaultMessage()); + assertThat(errors.hasFieldErrors("name")).isTrue(); + assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE"); + assertThat(errors.getFieldError("name").getArguments()[0]).isEqualTo("arg"); + assertThat(errors.getFieldError("name").getDefaultMessage()).isEqualTo("msg"); } diff --git a/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java index 0c7eb5632c5..c2ced70336f 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java @@ -33,7 +33,6 @@ 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.junit.Assert.assertNotNull; /** * @author Juergen Hoeller @@ -143,7 +142,7 @@ public class BeanValidationPostProcessorTests { @PostConstruct public void init() { - assertNotNull("Shouldn't be here after constraint checking", this.testBean); + assertThat(this.testBean).as("Shouldn't be here after constraint checking").isNotNull(); } } diff --git a/spring-context/src/test/java/org/springframework/validation/beanvalidation/MethodValidationTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/MethodValidationTests.java index cea70093b79..304900b22ac 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/MethodValidationTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/MethodValidationTests.java @@ -39,9 +39,8 @@ import org.springframework.scheduling.annotation.AsyncAnnotationAdvisor; import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor; import org.springframework.validation.annotation.Validated; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * @author Juergen Hoeller @@ -71,7 +70,7 @@ public class MethodValidationTests { } private void doTestProxyValidation(MyValidInterface proxy) { - assertNotNull(proxy.myValidMethod("value", 5)); + assertThat(proxy.myValidMethod("value", 5)).isNotNull(); assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myValidMethod("value", 15)); assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> @@ -83,7 +82,7 @@ public class MethodValidationTests { proxy.myValidAsyncMethod("value", 15)); assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myValidAsyncMethod(null, 5)); - assertEquals("myValue", proxy.myGenericMethod("myValue")); + assertThat(proxy.myGenericMethod("myValue")).isEqualTo("myValue"); assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> proxy.myGenericMethod(null)); } diff --git a/spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java index 3fa7d8a2602..05fa662abc1 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java @@ -55,9 +55,6 @@ import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; 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 Kazuki Shimizu @@ -84,7 +81,7 @@ public class SpringValidatorAdapterTests { @Test public void testUnwrap() { Validator nativeValidator = validatorAdapter.unwrap(Validator.class); - assertSame(this.nativeValidator, nativeValidator); + assertThat(nativeValidator).isSameAs(this.nativeValidator); } @Test // SPR-13406 @@ -99,9 +96,9 @@ public class SpringValidatorAdapterTests { assertThat(errors.getFieldErrorCount("password")).isEqualTo(1); assertThat(errors.getFieldValue("password")).isEqualTo("pass"); FieldError error = errors.getFieldError("password"); - assertNotNull(error); + assertThat(error).isNotNull(); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Size of Password is must be between 8 and 128"); - assertTrue(error.contains(ConstraintViolation.class)); + assertThat(error.contains(ConstraintViolation.class)).isTrue(); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password"); } @@ -117,9 +114,9 @@ public class SpringValidatorAdapterTests { assertThat(errors.getFieldErrorCount("password")).isEqualTo(1); assertThat(errors.getFieldValue("password")).isEqualTo("password"); FieldError error = errors.getFieldError("password"); - assertNotNull(error); + assertThat(error).isNotNull(); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).isEqualTo("Password must be same value as Password(Confirm)"); - assertTrue(error.contains(ConstraintViolation.class)); + assertThat(error.contains(ConstraintViolation.class)).isTrue(); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("password"); } @@ -137,13 +134,13 @@ public class SpringValidatorAdapterTests { assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1); FieldError error1 = errors.getFieldError("email"); FieldError error2 = errors.getFieldError("confirmEmail"); - assertNotNull(error1); - assertNotNull(error2); + assertThat(error1).isNotNull(); + assertThat(error2).isNotNull(); assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail"); assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required"); - assertTrue(error1.contains(ConstraintViolation.class)); + assertThat(error1.contains(ConstraintViolation.class)).isTrue(); assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); - assertTrue(error2.contains(ConstraintViolation.class)); + assertThat(error2.contains(ConstraintViolation.class)).isTrue(); assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail"); } @@ -163,13 +160,13 @@ public class SpringValidatorAdapterTests { assertThat(errors.getFieldErrorCount("confirmEmail")).isEqualTo(1); FieldError error1 = errors.getFieldError("email"); FieldError error2 = errors.getFieldError("confirmEmail"); - assertNotNull(error1); - assertNotNull(error2); + assertThat(error1).isNotNull(); + assertThat(error2).isNotNull(); assertThat(messageSource.getMessage(error1, Locale.ENGLISH)).isEqualTo("email must be same value as confirmEmail"); assertThat(messageSource.getMessage(error2, Locale.ENGLISH)).isEqualTo("Email required"); - assertTrue(error1.contains(ConstraintViolation.class)); + assertThat(error1.contains(ConstraintViolation.class)).isTrue(); assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); - assertTrue(error2.contains(ConstraintViolation.class)); + assertThat(error2.contains(ConstraintViolation.class)).isTrue(); assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("confirmEmail"); } @@ -185,9 +182,9 @@ public class SpringValidatorAdapterTests { assertThat(errors.getFieldErrorCount("email")).isEqualTo(1); assertThat(errors.getFieldValue("email")).isEqualTo("X"); FieldError error = errors.getFieldError("email"); - assertNotNull(error); + assertThat(error).isNotNull(); assertThat(messageSource.getMessage(error, Locale.ENGLISH)).contains("[\\w.'-]{1,}@[\\w.'-]{1,}"); - assertTrue(error.contains(ConstraintViolation.class)); + assertThat(error.contains(ConstraintViolation.class)).isTrue(); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString()).isEqualTo("email"); } @@ -200,7 +197,7 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(parent, "parent"); validatorAdapter.validate(parent, errors); - assertTrue(errors.getErrorCount() > 0); + assertThat(errors.getErrorCount() > 0).isTrue(); } @Test // SPR-16177 @@ -212,7 +209,7 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(parent, "parent"); validatorAdapter.validate(parent, errors); - assertTrue(errors.getErrorCount() > 0); + assertThat(errors.getErrorCount() > 0).isTrue(); } private List createChildren(Parent parent) { diff --git a/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java index dbfc1f5f719..0d2e23cc47c 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java @@ -52,10 +52,6 @@ import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -69,7 +65,7 @@ public class ValidatorFactoryTests { ValidPerson person = new ValidPerson(); Set> result = validator.validate(person); - assertEquals(2, result.size()); + assertThat(result.size()).isEqualTo(2); for (ConstraintViolation cv : result) { String path = cv.getPropertyPath().toString(); assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual)); @@ -77,9 +73,9 @@ public class ValidatorFactoryTests { } Validator nativeValidator = validator.unwrap(Validator.class); - assertTrue(nativeValidator.getClass().getName().startsWith("org.hibernate")); - assertTrue(validator.unwrap(ValidatorFactory.class) instanceof HibernateValidatorFactory); - assertTrue(validator.unwrap(HibernateValidatorFactory.class) instanceof HibernateValidatorFactory); + assertThat(nativeValidator.getClass().getName().startsWith("org.hibernate")).isTrue(); + assertThat(validator.unwrap(ValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); + assertThat(validator.unwrap(HibernateValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); validator.destroy(); } @@ -92,7 +88,7 @@ public class ValidatorFactoryTests { ValidPerson person = new ValidPerson(); Set> result = validator.validate(person); - assertEquals(2, result.size()); + assertThat(result.size()).isEqualTo(2); for (ConstraintViolation cv : result) { String path = cv.getPropertyPath().toString(); assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual)); @@ -100,9 +96,9 @@ public class ValidatorFactoryTests { } Validator nativeValidator = validator.unwrap(Validator.class); - assertTrue(nativeValidator.getClass().getName().startsWith("org.hibernate")); - assertTrue(validator.unwrap(ValidatorFactory.class) instanceof HibernateValidatorFactory); - assertTrue(validator.unwrap(HibernateValidatorFactory.class) instanceof HibernateValidatorFactory); + assertThat(nativeValidator.getClass().getName().startsWith("org.hibernate")).isTrue(); + assertThat(validator.unwrap(ValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); + assertThat(validator.unwrap(HibernateValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); validator.destroy(); } @@ -116,11 +112,11 @@ public class ValidatorFactoryTests { person.setName("Juergen"); person.getAddress().setStreet("Juergen's Street"); Set> result = validator.validate(person); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); Iterator> iterator = result.iterator(); ConstraintViolation cv = iterator.next(); - assertEquals("", cv.getPropertyPath().toString()); - assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NameAddressValid); + assertThat(cv.getPropertyPath().toString()).isEqualTo(""); + assertThat(cv.getConstraintDescriptor().getAnnotation() instanceof NameAddressValid).isTrue(); } @Test @@ -133,7 +129,7 @@ public class ValidatorFactoryTests { person.getAddress().setStreet("Phil's Street"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person"); validator.validate(person, errors); - assertEquals(1, errors.getErrorCount()); + assertThat(errors.getErrorCount()).isEqualTo(1); assertThat(errors.getFieldError("address").getRejectedValue()) .as("Field/Value type mismatch") .isInstanceOf(ValidAddress.class); @@ -147,24 +143,24 @@ public class ValidatorFactoryTests { ValidPerson person = new ValidPerson(); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); - assertEquals(2, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(2); FieldError fieldError = result.getFieldError("name"); - assertEquals("name", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("name"); List errorCodes = Arrays.asList(fieldError.getCodes()); - assertEquals(4, errorCodes.size()); - assertTrue(errorCodes.contains("NotNull.person.name")); - assertTrue(errorCodes.contains("NotNull.name")); - assertTrue(errorCodes.contains("NotNull.java.lang.String")); - assertTrue(errorCodes.contains("NotNull")); + assertThat(errorCodes.size()).isEqualTo(4); + assertThat(errorCodes.contains("NotNull.person.name")).isTrue(); + assertThat(errorCodes.contains("NotNull.name")).isTrue(); + assertThat(errorCodes.contains("NotNull.java.lang.String")).isTrue(); + assertThat(errorCodes.contains("NotNull")).isTrue(); fieldError = result.getFieldError("address.street"); - assertEquals("address.street", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("address.street"); errorCodes = Arrays.asList(fieldError.getCodes()); - assertEquals(5, errorCodes.size()); - assertTrue(errorCodes.contains("NotNull.person.address.street")); - assertTrue(errorCodes.contains("NotNull.address.street")); - assertTrue(errorCodes.contains("NotNull.street")); - assertTrue(errorCodes.contains("NotNull.java.lang.String")); - assertTrue(errorCodes.contains("NotNull")); + assertThat(errorCodes.size()).isEqualTo(5); + assertThat(errorCodes.contains("NotNull.person.address.street")).isTrue(); + assertThat(errorCodes.contains("NotNull.address.street")).isTrue(); + assertThat(errorCodes.contains("NotNull.street")).isTrue(); + assertThat(errorCodes.contains("NotNull.java.lang.String")).isTrue(); + assertThat(errorCodes.contains("NotNull")).isTrue(); } @Test @@ -177,12 +173,12 @@ public class ValidatorFactoryTests { person.getAddress().setStreet("Juergen's Street"); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); - assertEquals(1, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(1); ObjectError globalError = result.getGlobalError(); List errorCodes = Arrays.asList(globalError.getCodes()); - assertEquals(2, errorCodes.size()); - assertTrue(errorCodes.contains("NameAddressValid.person")); - assertTrue(errorCodes.contains("NameAddressValid")); + assertThat(errorCodes.size()).isEqualTo(2); + assertThat(errorCodes.contains("NameAddressValid.person")).isTrue(); + assertThat(errorCodes.contains("NameAddressValid")).isTrue(); } @Test @@ -197,12 +193,12 @@ public class ValidatorFactoryTests { person.getAddress().setStreet("Juergen's Street"); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); - assertEquals(1, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(1); ObjectError globalError = result.getGlobalError(); List errorCodes = Arrays.asList(globalError.getCodes()); - assertEquals(2, errorCodes.size()); - assertTrue(errorCodes.contains("NameAddressValid.person")); - assertTrue(errorCodes.contains("NameAddressValid")); + assertThat(errorCodes.size()).isEqualTo(2); + assertThat(errorCodes.contains("NameAddressValid.person")).isTrue(); + assertThat(errorCodes.contains("NameAddressValid")).isTrue(); ctx.close(); } @@ -215,13 +211,13 @@ public class ValidatorFactoryTests { person.getAddressList().add(new ValidAddress()); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); - assertEquals(3, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(3); FieldError fieldError = result.getFieldError("name"); - assertEquals("name", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("name"); fieldError = result.getFieldError("address.street"); - assertEquals("address.street", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("address.street"); fieldError = result.getFieldError("addressList[0].street"); - assertEquals("addressList[0].street", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("addressList[0].street"); } @Test @@ -233,13 +229,13 @@ public class ValidatorFactoryTests { person.getAddressSet().add(new ValidAddress()); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); - assertEquals(3, result.getErrorCount()); + assertThat(result.getErrorCount()).isEqualTo(3); FieldError fieldError = result.getFieldError("name"); - assertEquals("name", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("name"); fieldError = result.getFieldError("address.street"); - assertEquals("address.street", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("address.street"); fieldError = result.getFieldError("addressSet[].street"); - assertEquals("addressSet[].street", fieldError.getField()); + assertThat(fieldError.getField()).isEqualTo("addressSet[].street"); } @Test @@ -251,7 +247,7 @@ public class ValidatorFactoryTests { Errors errors = new BeanPropertyBindingResult(mainBean, "mainBean"); validator.validate(mainBean, errors); Object rejected = errors.getFieldValue("inner.value"); - assertNull(rejected); + assertThat(rejected).isNull(); } @Test @@ -263,7 +259,7 @@ public class ValidatorFactoryTests { Errors errors = new BeanPropertyBindingResult(mainBean, "mainBean"); validator.validate(mainBean, errors); Object rejected = errors.getFieldValue("inner.value"); - assertNull(rejected); + assertThat(rejected).isNull(); } @Test @@ -280,9 +276,9 @@ public class ValidatorFactoryTests { validator.validate(listContainer, errors); FieldError fieldError = errors.getFieldError("list[1]"); - assertNotNull(fieldError); - assertEquals("X", fieldError.getRejectedValue()); - assertEquals("X", errors.getFieldValue("list[1]")); + assertThat(fieldError).isNotNull(); + assertThat(fieldError.getRejectedValue()).isEqualTo("X"); + assertThat(errors.getFieldValue("list[1]")).isEqualTo("X"); } @@ -377,7 +373,7 @@ public class ValidatorFactoryTests { @Override public boolean isValid(ValidPerson value, ConstraintValidatorContext context) { if (value.expectsAutowiredValidator) { - assertNotNull(this.environment); + assertThat(this.environment).isNotNull(); } boolean valid = (value.name == null || !value.address.street.contains(value.name)); if (!valid && "Phil".equals(value.name)) { diff --git a/spring-core/src/test/java/org/springframework/core/AttributeAccessorSupportTests.java b/spring-core/src/test/java/org/springframework/core/AttributeAccessorSupportTests.java index 09b6f33463c..05e6f619d9f 100644 --- a/spring-core/src/test/java/org/springframework/core/AttributeAccessorSupportTests.java +++ b/spring-core/src/test/java/org/springframework/core/AttributeAccessorSupportTests.java @@ -20,9 +20,7 @@ import java.util.Arrays; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -40,22 +38,22 @@ public class AttributeAccessorSupportTests { @Test public void setAndGet() throws Exception { this.attributeAccessor.setAttribute(NAME, VALUE); - assertEquals(VALUE, this.attributeAccessor.getAttribute(NAME)); + assertThat(this.attributeAccessor.getAttribute(NAME)).isEqualTo(VALUE); } @Test public void setAndHas() throws Exception { - assertFalse(this.attributeAccessor.hasAttribute(NAME)); + assertThat(this.attributeAccessor.hasAttribute(NAME)).isFalse(); this.attributeAccessor.setAttribute(NAME, VALUE); - assertTrue(this.attributeAccessor.hasAttribute(NAME)); + assertThat(this.attributeAccessor.hasAttribute(NAME)).isTrue(); } @Test public void remove() throws Exception { - assertFalse(this.attributeAccessor.hasAttribute(NAME)); + assertThat(this.attributeAccessor.hasAttribute(NAME)).isFalse(); this.attributeAccessor.setAttribute(NAME, VALUE); - assertEquals(VALUE, this.attributeAccessor.removeAttribute(NAME)); - assertFalse(this.attributeAccessor.hasAttribute(NAME)); + assertThat(this.attributeAccessor.removeAttribute(NAME)).isEqualTo(VALUE); + assertThat(this.attributeAccessor.hasAttribute(NAME)).isFalse(); } @Test @@ -64,8 +62,8 @@ public class AttributeAccessorSupportTests { this.attributeAccessor.setAttribute("abc", "123"); String[] attributeNames = this.attributeAccessor.attributeNames(); Arrays.sort(attributeNames); - assertTrue(Arrays.binarySearch(attributeNames, NAME) > -1); - assertTrue(Arrays.binarySearch(attributeNames, "abc") > -1); + assertThat(Arrays.binarySearch(attributeNames, NAME) > -1).isTrue(); + assertThat(Arrays.binarySearch(attributeNames, "abc") > -1).isTrue(); } @SuppressWarnings("serial") diff --git a/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java b/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java index c3579b2beae..59e0c59aa4c 100644 --- a/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java @@ -32,11 +32,7 @@ import org.junit.Test; import org.springframework.util.ReflectionUtils; -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.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -61,33 +57,33 @@ public class BridgeMethodResolverTests { public void testFindBridgedMethod() throws Exception { Method unbridged = MyFoo.class.getDeclaredMethod("someMethod", String.class, Object.class); Method bridged = MyFoo.class.getDeclaredMethod("someMethod", Serializable.class, Object.class); - assertFalse(unbridged.isBridge()); - assertTrue(bridged.isBridge()); + assertThat(unbridged.isBridge()).isFalse(); + assertThat(bridged.isBridge()).isTrue(); - assertEquals("Unbridged method not returned directly", unbridged, BridgeMethodResolver.findBridgedMethod(unbridged)); - assertEquals("Incorrect bridged method returned", unbridged, BridgeMethodResolver.findBridgedMethod(bridged)); + assertThat(BridgeMethodResolver.findBridgedMethod(unbridged)).as("Unbridged method not returned directly").isEqualTo(unbridged); + assertThat(BridgeMethodResolver.findBridgedMethod(bridged)).as("Incorrect bridged method returned").isEqualTo(unbridged); } @Test public void testFindBridgedVarargMethod() throws Exception { Method unbridged = MyFoo.class.getDeclaredMethod("someVarargMethod", String.class, Object[].class); Method bridged = MyFoo.class.getDeclaredMethod("someVarargMethod", Serializable.class, Object[].class); - assertFalse(unbridged.isBridge()); - assertTrue(bridged.isBridge()); + assertThat(unbridged.isBridge()).isFalse(); + assertThat(bridged.isBridge()).isTrue(); - assertEquals("Unbridged method not returned directly", unbridged, BridgeMethodResolver.findBridgedMethod(unbridged)); - assertEquals("Incorrect bridged method returned", unbridged, BridgeMethodResolver.findBridgedMethod(bridged)); + assertThat(BridgeMethodResolver.findBridgedMethod(unbridged)).as("Unbridged method not returned directly").isEqualTo(unbridged); + assertThat(BridgeMethodResolver.findBridgedMethod(bridged)).as("Incorrect bridged method returned").isEqualTo(unbridged); } @Test public void testFindBridgedMethodInHierarchy() throws Exception { Method bridgeMethod = DateAdder.class.getMethod("add", Object.class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(bridgeMethod); - assertFalse(bridgedMethod.isBridge()); - assertEquals("add", bridgedMethod.getName()); - assertEquals(1, bridgedMethod.getParameterCount()); - assertEquals(Date.class, bridgedMethod.getParameterTypes()[0]); + assertThat(bridgedMethod.isBridge()).isFalse(); + assertThat(bridgedMethod.getName()).isEqualTo("add"); + assertThat(bridgedMethod.getParameterCount()).isEqualTo(1); + assertThat(bridgedMethod.getParameterTypes()[0]).isEqualTo(Date.class); } @Test @@ -96,8 +92,8 @@ public class BridgeMethodResolverTests { Method other = MyBar.class.getDeclaredMethod("someMethod", Integer.class, Object.class); Method bridge = MyBar.class.getDeclaredMethod("someMethod", Object.class, Object.class); - assertTrue("Should be bridge method", BridgeMethodResolver.isBridgeMethodFor(bridge, bridged, MyBar.class)); - assertFalse("Should not be bridge method", BridgeMethodResolver.isBridgeMethodFor(bridge, other, MyBar.class)); + assertThat(BridgeMethodResolver.isBridgeMethodFor(bridge, bridged, MyBar.class)).as("Should be bridge method").isTrue(); + assertThat(BridgeMethodResolver.isBridgeMethodFor(bridge, other, MyBar.class)).as("Should not be bridge method").isFalse(); } @Test @@ -108,51 +104,51 @@ public class BridgeMethodResolverTests { Method stringFoo = MyBoo.class.getDeclaredMethod("foo", String.class); Method integerFoo = MyBoo.class.getDeclaredMethod("foo", Integer.class); - assertEquals("foo(String) not resolved.", stringFoo, BridgeMethodResolver.findBridgedMethod(objectBridge)); - assertEquals("foo(Integer) not resolved.", integerFoo, BridgeMethodResolver.findBridgedMethod(serializableBridge)); + assertThat(BridgeMethodResolver.findBridgedMethod(objectBridge)).as("foo(String) not resolved.").isEqualTo(stringFoo); + assertThat(BridgeMethodResolver.findBridgedMethod(serializableBridge)).as("foo(Integer) not resolved.").isEqualTo(integerFoo); } @Test public void testFindBridgedMethodFromMultipleBridges() throws Exception { Method loadWithObjectReturn = findMethodWithReturnType("load", Object.class, SettingsDaoImpl.class); - assertNotNull(loadWithObjectReturn); + assertThat(loadWithObjectReturn).isNotNull(); Method loadWithSettingsReturn = findMethodWithReturnType("load", Settings.class, SettingsDaoImpl.class); - assertNotNull(loadWithSettingsReturn); - assertNotSame(loadWithObjectReturn, loadWithSettingsReturn); + assertThat(loadWithSettingsReturn).isNotNull(); + assertThat(loadWithSettingsReturn).isNotSameAs(loadWithObjectReturn); Method method = SettingsDaoImpl.class.getMethod("load"); - assertEquals(method, BridgeMethodResolver.findBridgedMethod(loadWithObjectReturn)); - assertEquals(method, BridgeMethodResolver.findBridgedMethod(loadWithSettingsReturn)); + assertThat(BridgeMethodResolver.findBridgedMethod(loadWithObjectReturn)).isEqualTo(method); + assertThat(BridgeMethodResolver.findBridgedMethod(loadWithSettingsReturn)).isEqualTo(method); } @Test public void testFindBridgedMethodFromParent() throws Exception { Method loadFromParentBridge = SettingsDaoImpl.class.getMethod("loadFromParent"); - assertTrue(loadFromParentBridge.isBridge()); + assertThat(loadFromParentBridge.isBridge()).isTrue(); Method loadFromParent = AbstractDaoImpl.class.getMethod("loadFromParent"); - assertFalse(loadFromParent.isBridge()); + assertThat(loadFromParent.isBridge()).isFalse(); - assertEquals(loadFromParent, BridgeMethodResolver.findBridgedMethod(loadFromParentBridge)); + assertThat(BridgeMethodResolver.findBridgedMethod(loadFromParentBridge)).isEqualTo(loadFromParent); } @Test public void testWithSingleBoundParameterizedOnInstantiate() throws Exception { Method bridgeMethod = DelayQueue.class.getMethod("add", Object.class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); Method actualMethod = DelayQueue.class.getMethod("add", Delayed.class); - assertFalse(actualMethod.isBridge()); - assertEquals(actualMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); + assertThat(actualMethod.isBridge()).isFalse(); + assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(actualMethod); } @Test public void testWithDoubleBoundParameterizedOnInstantiate() throws Exception { Method bridgeMethod = SerializableBounded.class.getMethod("boundedOperation", Object.class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); Method actualMethod = SerializableBounded.class.getMethod("boundedOperation", HashMap.class); - assertFalse(actualMethod.isBridge()); - assertEquals(actualMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); + assertThat(actualMethod.isBridge()).isFalse(); + assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(actualMethod); } @Test @@ -170,33 +166,34 @@ public class BridgeMethodResolverTests { } } } - assertTrue(bridgeMethod != null && bridgeMethod.isBridge()); - assertTrue(bridgedMethod != null && !bridgedMethod.isBridge()); - assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); + assertThat(bridgeMethod != null && bridgeMethod.isBridge()).isTrue(); + boolean condition = bridgedMethod != null && !bridgedMethod.isBridge(); + assertThat(condition).isTrue(); + assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod); } @Test public void testOnAllMethods() throws Exception { Method[] methods = StringList.class.getMethods(); for (Method method : methods) { - assertNotNull(BridgeMethodResolver.findBridgedMethod(method)); + assertThat(BridgeMethodResolver.findBridgedMethod(method)).isNotNull(); } } @Test public void testSPR2583() throws Exception { Method bridgedMethod = MessageBroadcasterImpl.class.getMethod("receive", MessageEvent.class); - assertFalse(bridgedMethod.isBridge()); + assertThat(bridgedMethod.isBridge()).isFalse(); Method bridgeMethod = MessageBroadcasterImpl.class.getMethod("receive", Event.class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); Method otherMethod = MessageBroadcasterImpl.class.getMethod("receive", NewMessageEvent.class); - assertFalse(otherMethod.isBridge()); + assertThat(otherMethod.isBridge()).isFalse(); - assertFalse("Match identified incorrectly", BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, otherMethod, MessageBroadcasterImpl.class)); - assertTrue("Match not found correctly", BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, bridgedMethod, MessageBroadcasterImpl.class)); + assertThat(BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, otherMethod, MessageBroadcasterImpl.class)).as("Match identified incorrectly").isFalse(); + assertThat(BridgeMethodResolver.isBridgeMethodFor(bridgeMethod, bridgedMethod, MessageBroadcasterImpl.class)).as("Match not found correctly").isTrue(); - assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); + assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod); } @Test @@ -205,106 +202,106 @@ public class BridgeMethodResolverTests { Method abstractBoundedFoo = YourHomer.class.getDeclaredMethod("foo", AbstractBounded.class); Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(objectBridge); - assertEquals("foo(AbstractBounded) not resolved.", abstractBoundedFoo, bridgedMethod); + assertThat(bridgedMethod).as("foo(AbstractBounded) not resolved.").isEqualTo(abstractBoundedFoo); } @Test public void testSPR2648() throws Exception { Method bridgeMethod = ReflectionUtils.findMethod(GenericSqlMapIntegerDao.class, "saveOrUpdate", Object.class); - assertTrue(bridgeMethod != null && bridgeMethod.isBridge()); + assertThat(bridgeMethod != null && bridgeMethod.isBridge()).isTrue(); Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(bridgeMethod); - assertFalse(bridgedMethod.isBridge()); - assertEquals("saveOrUpdate", bridgedMethod.getName()); + assertThat(bridgedMethod.isBridge()).isFalse(); + assertThat(bridgedMethod.getName()).isEqualTo("saveOrUpdate"); } @Test public void testSPR2763() throws Exception { Method bridgedMethod = AbstractDao.class.getDeclaredMethod("save", Object.class); - assertFalse(bridgedMethod.isBridge()); + assertThat(bridgedMethod.isBridge()).isFalse(); Method bridgeMethod = UserDaoImpl.class.getDeclaredMethod("save", User.class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); - assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); + assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod); } @Test public void testSPR3041() throws Exception { Method bridgedMethod = BusinessDao.class.getDeclaredMethod("save", Business.class); - assertFalse(bridgedMethod.isBridge()); + assertThat(bridgedMethod.isBridge()).isFalse(); Method bridgeMethod = BusinessDao.class.getDeclaredMethod("save", Object.class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); - assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); + assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod); } @Test public void testSPR3173() throws Exception { Method bridgedMethod = UserDaoImpl.class.getDeclaredMethod("saveVararg", User.class, Object[].class); - assertFalse(bridgedMethod.isBridge()); + assertThat(bridgedMethod.isBridge()).isFalse(); Method bridgeMethod = UserDaoImpl.class.getDeclaredMethod("saveVararg", Object.class, Object[].class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); - assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); + assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod); } @Test public void testSPR3304() throws Exception { Method bridgedMethod = MegaMessageProducerImpl.class.getDeclaredMethod("receive", MegaMessageEvent.class); - assertFalse(bridgedMethod.isBridge()); + assertThat(bridgedMethod.isBridge()).isFalse(); Method bridgeMethod = MegaMessageProducerImpl.class.getDeclaredMethod("receive", MegaEvent.class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); - assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); + assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod); } @Test public void testSPR3324() throws Exception { Method bridgedMethod = BusinessDao.class.getDeclaredMethod("get", Long.class); - assertFalse(bridgedMethod.isBridge()); + assertThat(bridgedMethod.isBridge()).isFalse(); Method bridgeMethod = BusinessDao.class.getDeclaredMethod("get", Object.class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); - assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); + assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod); } @Test public void testSPR3357() throws Exception { Method bridgedMethod = ExtendsAbstractImplementsInterface.class.getDeclaredMethod( "doSomething", DomainObjectExtendsSuper.class, Object.class); - assertFalse(bridgedMethod.isBridge()); + assertThat(bridgedMethod.isBridge()).isFalse(); Method bridgeMethod = ExtendsAbstractImplementsInterface.class.getDeclaredMethod( "doSomething", DomainObjectSuper.class, Object.class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); - assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); + assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod); } @Test public void testSPR3485() throws Exception { Method bridgedMethod = DomainObject.class.getDeclaredMethod( "method2", ParameterType.class, byte[].class); - assertFalse(bridgedMethod.isBridge()); + assertThat(bridgedMethod.isBridge()).isFalse(); Method bridgeMethod = DomainObject.class.getDeclaredMethod( "method2", Serializable.class, Object.class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); - assertEquals(bridgedMethod, BridgeMethodResolver.findBridgedMethod(bridgeMethod)); + assertThat(BridgeMethodResolver.findBridgedMethod(bridgeMethod)).isEqualTo(bridgedMethod); } @Test public void testSPR3534() throws Exception { Method bridgeMethod = ReflectionUtils.findMethod(TestEmailProvider.class, "findBy", Object.class); - assertTrue(bridgeMethod != null && bridgeMethod.isBridge()); + assertThat(bridgeMethod != null && bridgeMethod.isBridge()).isTrue(); Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(bridgeMethod); - assertFalse(bridgedMethod.isBridge()); - assertEquals("findBy", bridgedMethod.getName()); + assertThat(bridgedMethod.isBridge()).isFalse(); + assertThat(bridgedMethod.getName()).isEqualTo("findBy"); } @Test // SPR-16103 @@ -321,7 +318,7 @@ public class BridgeMethodResolverTests { for (Method method : clazz.getDeclaredMethods()){ Method bridged = BridgeMethodResolver.findBridgedMethod(method); Method expected = clazz.getMethod("test", FooEntity.class); - assertEquals(expected, bridged); + assertThat(bridged).isEqualTo(expected); } } diff --git a/spring-core/src/test/java/org/springframework/core/ConstantsTests.java b/spring-core/src/test/java/org/springframework/core/ConstantsTests.java index 1a33e21da40..e2d9a832ee9 100644 --- a/spring-core/src/test/java/org/springframework/core/ConstantsTests.java +++ b/spring-core/src/test/java/org/springframework/core/ConstantsTests.java @@ -21,11 +21,9 @@ import java.util.Set; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -38,17 +36,17 @@ public class ConstantsTests { @Test public void constants() { Constants c = new Constants(A.class); - assertEquals(A.class.getName(), c.getClassName()); - assertEquals(9, c.getSize()); + assertThat(c.getClassName()).isEqualTo(A.class.getName()); + assertThat(c.getSize()).isEqualTo(9); - assertEquals(A.DOG, c.asNumber("DOG").intValue()); - assertEquals(A.DOG, c.asNumber("dog").intValue()); - assertEquals(A.CAT, c.asNumber("cat").intValue()); + assertThat(c.asNumber("DOG").intValue()).isEqualTo(A.DOG); + assertThat(c.asNumber("dog").intValue()).isEqualTo(A.DOG); + assertThat(c.asNumber("cat").intValue()).isEqualTo(A.CAT); assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> c.asNumber("bogus")); - assertTrue(c.asString("S1").equals(A.S1)); + assertThat(c.asString("S1").equals(A.S1)).isTrue(); assertThatExceptionOfType(Constants.ConstantException.class).as("wrong type").isThrownBy(() -> c.asNumber("S1")); } @@ -58,18 +56,18 @@ public class ConstantsTests { Constants c = new Constants(A.class); Set names = c.getNames(""); - assertEquals(c.getSize(), names.size()); - assertTrue(names.contains("DOG")); - assertTrue(names.contains("CAT")); - assertTrue(names.contains("S1")); + assertThat(names.size()).isEqualTo(c.getSize()); + assertThat(names.contains("DOG")).isTrue(); + assertThat(names.contains("CAT")).isTrue(); + assertThat(names.contains("S1")).isTrue(); names = c.getNames("D"); - assertEquals(1, names.size()); - assertTrue(names.contains("DOG")); + assertThat(names.size()).isEqualTo(1); + assertThat(names.contains("DOG")).isTrue(); names = c.getNames("d"); - assertEquals(1, names.size()); - assertTrue(names.contains("DOG")); + assertThat(names.size()).isEqualTo(1); + assertThat(names.contains("DOG")).isTrue(); } @Test @@ -77,24 +75,24 @@ public class ConstantsTests { Constants c = new Constants(A.class); Set values = c.getValues(""); - assertEquals(7, values.size()); - assertTrue(values.contains(Integer.valueOf(0))); - assertTrue(values.contains(Integer.valueOf(66))); - assertTrue(values.contains("")); + assertThat(values.size()).isEqualTo(7); + assertThat(values.contains(Integer.valueOf(0))).isTrue(); + assertThat(values.contains(Integer.valueOf(66))).isTrue(); + assertThat(values.contains("")).isTrue(); values = c.getValues("D"); - assertEquals(1, values.size()); - assertTrue(values.contains(Integer.valueOf(0))); + assertThat(values.size()).isEqualTo(1); + assertThat(values.contains(Integer.valueOf(0))).isTrue(); values = c.getValues("prefix"); - assertEquals(2, values.size()); - assertTrue(values.contains(Integer.valueOf(1))); - assertTrue(values.contains(Integer.valueOf(2))); + assertThat(values.size()).isEqualTo(2); + assertThat(values.contains(Integer.valueOf(1))).isTrue(); + assertThat(values.contains(Integer.valueOf(2))).isTrue(); values = c.getValuesForProperty("myProperty"); - assertEquals(2, values.size()); - assertTrue(values.contains(Integer.valueOf(1))); - assertTrue(values.contains(Integer.valueOf(2))); + assertThat(values.size()).isEqualTo(2); + assertThat(values.contains(Integer.valueOf(1))).isTrue(); + assertThat(values.contains(Integer.valueOf(2))).isTrue(); } @Test @@ -105,24 +103,24 @@ public class ConstantsTests { Constants c = new Constants(A.class); Set values = c.getValues(""); - assertEquals(7, values.size()); - assertTrue(values.contains(Integer.valueOf(0))); - assertTrue(values.contains(Integer.valueOf(66))); - assertTrue(values.contains("")); + assertThat(values.size()).isEqualTo(7); + assertThat(values.contains(Integer.valueOf(0))).isTrue(); + assertThat(values.contains(Integer.valueOf(66))).isTrue(); + assertThat(values.contains("")).isTrue(); values = c.getValues("D"); - assertEquals(1, values.size()); - assertTrue(values.contains(Integer.valueOf(0))); + assertThat(values.size()).isEqualTo(1); + assertThat(values.contains(Integer.valueOf(0))).isTrue(); values = c.getValues("prefix"); - assertEquals(2, values.size()); - assertTrue(values.contains(Integer.valueOf(1))); - assertTrue(values.contains(Integer.valueOf(2))); + assertThat(values.size()).isEqualTo(2); + assertThat(values.contains(Integer.valueOf(1))).isTrue(); + assertThat(values.contains(Integer.valueOf(2))).isTrue(); values = c.getValuesForProperty("myProperty"); - assertEquals(2, values.size()); - assertTrue(values.contains(Integer.valueOf(1))); - assertTrue(values.contains(Integer.valueOf(2))); + assertThat(values.size()).isEqualTo(2); + assertThat(values.contains(Integer.valueOf(1))).isTrue(); + assertThat(values.contains(Integer.valueOf(2))).isTrue(); } finally { Locale.setDefault(oldLocale); @@ -134,58 +132,58 @@ public class ConstantsTests { Constants c = new Constants(A.class); Set names = c.getNamesForSuffix("_PROPERTY"); - assertEquals(2, names.size()); - assertTrue(names.contains("NO_PROPERTY")); - assertTrue(names.contains("YES_PROPERTY")); + assertThat(names.size()).isEqualTo(2); + assertThat(names.contains("NO_PROPERTY")).isTrue(); + assertThat(names.contains("YES_PROPERTY")).isTrue(); Set values = c.getValuesForSuffix("_PROPERTY"); - assertEquals(2, values.size()); - assertTrue(values.contains(Integer.valueOf(3))); - assertTrue(values.contains(Integer.valueOf(4))); + assertThat(values.size()).isEqualTo(2); + assertThat(values.contains(Integer.valueOf(3))).isTrue(); + assertThat(values.contains(Integer.valueOf(4))).isTrue(); } @Test public void toCode() { Constants c = new Constants(A.class); - assertEquals("DOG", c.toCode(Integer.valueOf(0), "")); - assertEquals("DOG", c.toCode(Integer.valueOf(0), "D")); - assertEquals("DOG", c.toCode(Integer.valueOf(0), "DO")); - assertEquals("DOG", c.toCode(Integer.valueOf(0), "DoG")); - assertEquals("DOG", c.toCode(Integer.valueOf(0), null)); - assertEquals("CAT", c.toCode(Integer.valueOf(66), "")); - assertEquals("CAT", c.toCode(Integer.valueOf(66), "C")); - assertEquals("CAT", c.toCode(Integer.valueOf(66), "ca")); - assertEquals("CAT", c.toCode(Integer.valueOf(66), "cAt")); - assertEquals("CAT", c.toCode(Integer.valueOf(66), null)); - assertEquals("S1", c.toCode("", "")); - assertEquals("S1", c.toCode("", "s")); - assertEquals("S1", c.toCode("", "s1")); - assertEquals("S1", c.toCode("", null)); + assertThat(c.toCode(Integer.valueOf(0), "")).isEqualTo("DOG"); + assertThat(c.toCode(Integer.valueOf(0), "D")).isEqualTo("DOG"); + assertThat(c.toCode(Integer.valueOf(0), "DO")).isEqualTo("DOG"); + assertThat(c.toCode(Integer.valueOf(0), "DoG")).isEqualTo("DOG"); + assertThat(c.toCode(Integer.valueOf(0), null)).isEqualTo("DOG"); + assertThat(c.toCode(Integer.valueOf(66), "")).isEqualTo("CAT"); + assertThat(c.toCode(Integer.valueOf(66), "C")).isEqualTo("CAT"); + assertThat(c.toCode(Integer.valueOf(66), "ca")).isEqualTo("CAT"); + assertThat(c.toCode(Integer.valueOf(66), "cAt")).isEqualTo("CAT"); + assertThat(c.toCode(Integer.valueOf(66), null)).isEqualTo("CAT"); + assertThat(c.toCode("", "")).isEqualTo("S1"); + assertThat(c.toCode("", "s")).isEqualTo("S1"); + assertThat(c.toCode("", "s1")).isEqualTo("S1"); + assertThat(c.toCode("", null)).isEqualTo("S1"); assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> c.toCode("bogus", "bogus")); assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> c.toCode("bogus", null)); - assertEquals("MY_PROPERTY_NO", c.toCodeForProperty(Integer.valueOf(1), "myProperty")); - assertEquals("MY_PROPERTY_YES", c.toCodeForProperty(Integer.valueOf(2), "myProperty")); + assertThat(c.toCodeForProperty(Integer.valueOf(1), "myProperty")).isEqualTo("MY_PROPERTY_NO"); + assertThat(c.toCodeForProperty(Integer.valueOf(2), "myProperty")).isEqualTo("MY_PROPERTY_YES"); assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> c.toCodeForProperty("bogus", "bogus")); - assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), "")); - assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), "G")); - assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), "OG")); - assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), "DoG")); - assertEquals("DOG", c.toCodeForSuffix(Integer.valueOf(0), null)); - assertEquals("CAT", c.toCodeForSuffix(Integer.valueOf(66), "")); - assertEquals("CAT", c.toCodeForSuffix(Integer.valueOf(66), "T")); - assertEquals("CAT", c.toCodeForSuffix(Integer.valueOf(66), "at")); - assertEquals("CAT", c.toCodeForSuffix(Integer.valueOf(66), "cAt")); - assertEquals("CAT", c.toCodeForSuffix(Integer.valueOf(66), null)); - assertEquals("S1", c.toCodeForSuffix("", "")); - assertEquals("S1", c.toCodeForSuffix("", "1")); - assertEquals("S1", c.toCodeForSuffix("", "s1")); - assertEquals("S1", c.toCodeForSuffix("", null)); + assertThat(c.toCodeForSuffix(Integer.valueOf(0), "")).isEqualTo("DOG"); + assertThat(c.toCodeForSuffix(Integer.valueOf(0), "G")).isEqualTo("DOG"); + assertThat(c.toCodeForSuffix(Integer.valueOf(0), "OG")).isEqualTo("DOG"); + assertThat(c.toCodeForSuffix(Integer.valueOf(0), "DoG")).isEqualTo("DOG"); + assertThat(c.toCodeForSuffix(Integer.valueOf(0), null)).isEqualTo("DOG"); + assertThat(c.toCodeForSuffix(Integer.valueOf(66), "")).isEqualTo("CAT"); + assertThat(c.toCodeForSuffix(Integer.valueOf(66), "T")).isEqualTo("CAT"); + assertThat(c.toCodeForSuffix(Integer.valueOf(66), "at")).isEqualTo("CAT"); + assertThat(c.toCodeForSuffix(Integer.valueOf(66), "cAt")).isEqualTo("CAT"); + assertThat(c.toCodeForSuffix(Integer.valueOf(66), null)).isEqualTo("CAT"); + assertThat(c.toCodeForSuffix("", "")).isEqualTo("S1"); + assertThat(c.toCodeForSuffix("", "1")).isEqualTo("S1"); + assertThat(c.toCodeForSuffix("", "s1")).isEqualTo("S1"); + assertThat(c.toCodeForSuffix("", null)).isEqualTo("S1"); assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> c.toCodeForSuffix("bogus", "bogus")); assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> @@ -196,30 +194,30 @@ public class ConstantsTests { public void getValuesWithNullPrefix() throws Exception { Constants c = new Constants(A.class); Set values = c.getValues(null); - assertEquals("Must have returned *all* public static final values", 7, values.size()); + assertThat(values.size()).as("Must have returned *all* public static final values").isEqualTo(7); } @Test public void getValuesWithEmptyStringPrefix() throws Exception { Constants c = new Constants(A.class); Set values = c.getValues(""); - assertEquals("Must have returned *all* public static final values", 7, values.size()); + assertThat(values.size()).as("Must have returned *all* public static final values").isEqualTo(7); } @Test public void getValuesWithWhitespacedStringPrefix() throws Exception { Constants c = new Constants(A.class); Set values = c.getValues(" "); - assertEquals("Must have returned *all* public static final values", 7, values.size()); + assertThat(values.size()).as("Must have returned *all* public static final values").isEqualTo(7); } @Test public void withClassThatExposesNoConstants() throws Exception { Constants c = new Constants(NoConstants.class); - assertEquals(0, c.getSize()); + assertThat(c.getSize()).isEqualTo(0); final Set values = c.getValues(""); - assertNotNull(values); - assertEquals(0, values.size()); + assertThat(values).isNotNull(); + assertThat(values.size()).isEqualTo(0); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/ConventionsTests.java b/spring-core/src/test/java/org/springframework/core/ConventionsTests.java index 7fbba70d76a..db159aa0964 100644 --- a/spring-core/src/test/java/org/springframework/core/ConventionsTests.java +++ b/spring-core/src/test/java/org/springframework/core/ConventionsTests.java @@ -32,8 +32,8 @@ import reactor.core.publisher.Mono; import org.springframework.tests.sample.objects.TestObject; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link Conventions}. @@ -45,28 +45,22 @@ public class ConventionsTests { @Test public void simpleObject() { - assertEquals("Incorrect singular variable name", - "testObject", Conventions.getVariableName(new TestObject())); - assertEquals("Incorrect singular variable name", "testObject", - Conventions.getVariableNameForParameter(getMethodParameter(TestObject.class))); - assertEquals("Incorrect singular variable name", "testObject", - Conventions.getVariableNameForReturnType(getMethodForReturnType(TestObject.class))); + assertThat(Conventions.getVariableName(new TestObject())).as("Incorrect singular variable name").isEqualTo("testObject"); + assertThat(Conventions.getVariableNameForParameter(getMethodParameter(TestObject.class))).as("Incorrect singular variable name").isEqualTo("testObject"); + assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(TestObject.class))).as("Incorrect singular variable name").isEqualTo("testObject"); } @Test public void array() { - assertEquals("Incorrect plural array form", - "testObjectList", Conventions.getVariableName(new TestObject[0])); + Object actual = Conventions.getVariableName(new TestObject[0]); + assertThat(actual).as("Incorrect plural array form").isEqualTo("testObjectList"); } @Test public void list() { - assertEquals("Incorrect plural List form", "testObjectList", - Conventions.getVariableName(Collections.singletonList(new TestObject()))); - assertEquals("Incorrect plural List form", "testObjectList", - Conventions.getVariableNameForParameter(getMethodParameter(List.class))); - assertEquals("Incorrect plural List form", "testObjectList", - Conventions.getVariableNameForReturnType(getMethodForReturnType(List.class))); + assertThat(Conventions.getVariableName(Collections.singletonList(new TestObject()))).as("Incorrect plural List form").isEqualTo("testObjectList"); + assertThat(Conventions.getVariableNameForParameter(getMethodParameter(List.class))).as("Incorrect plural List form").isEqualTo("testObjectList"); + assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(List.class))).as("Incorrect plural List form").isEqualTo("testObjectList"); } @Test @@ -77,43 +71,32 @@ public class ConventionsTests { @Test public void set() { - assertEquals("Incorrect plural Set form", "testObjectList", - Conventions.getVariableName(Collections.singleton(new TestObject()))); - assertEquals("Incorrect plural Set form", "testObjectList", - Conventions.getVariableNameForParameter(getMethodParameter(Set.class))); - assertEquals("Incorrect plural Set form", "testObjectList", - Conventions.getVariableNameForReturnType(getMethodForReturnType(Set.class))); + assertThat(Conventions.getVariableName(Collections.singleton(new TestObject()))).as("Incorrect plural Set form").isEqualTo("testObjectList"); + assertThat(Conventions.getVariableNameForParameter(getMethodParameter(Set.class))).as("Incorrect plural Set form").isEqualTo("testObjectList"); + assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(Set.class))).as("Incorrect plural Set form").isEqualTo("testObjectList"); } @Test public void reactiveParameters() { - assertEquals("testObjectMono", - Conventions.getVariableNameForParameter(getMethodParameter(Mono.class))); - assertEquals("testObjectFlux", - Conventions.getVariableNameForParameter(getMethodParameter(Flux.class))); - assertEquals("testObjectSingle", - Conventions.getVariableNameForParameter(getMethodParameter(Single.class))); - assertEquals("testObjectObservable", - Conventions.getVariableNameForParameter(getMethodParameter(Observable.class))); + assertThat(Conventions.getVariableNameForParameter(getMethodParameter(Mono.class))).isEqualTo("testObjectMono"); + assertThat(Conventions.getVariableNameForParameter(getMethodParameter(Flux.class))).isEqualTo("testObjectFlux"); + assertThat(Conventions.getVariableNameForParameter(getMethodParameter(Single.class))).isEqualTo("testObjectSingle"); + assertThat(Conventions.getVariableNameForParameter(getMethodParameter(Observable.class))).isEqualTo("testObjectObservable"); } @Test public void reactiveReturnTypes() { - assertEquals("testObjectMono", - Conventions.getVariableNameForReturnType(getMethodForReturnType(Mono.class))); - assertEquals("testObjectFlux", - Conventions.getVariableNameForReturnType(getMethodForReturnType(Flux.class))); - assertEquals("testObjectSingle", - Conventions.getVariableNameForReturnType(getMethodForReturnType(Single.class))); - assertEquals("testObjectObservable", - Conventions.getVariableNameForReturnType(getMethodForReturnType(Observable.class))); + assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(Mono.class))).isEqualTo("testObjectMono"); + assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(Flux.class))).isEqualTo("testObjectFlux"); + assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(Single.class))).isEqualTo("testObjectSingle"); + assertThat(Conventions.getVariableNameForReturnType(getMethodForReturnType(Observable.class))).isEqualTo("testObjectObservable"); } @Test public void attributeNameToPropertyName() { - assertEquals("transactionManager", Conventions.attributeNameToPropertyName("transaction-manager")); - assertEquals("pointcutRef", Conventions.attributeNameToPropertyName("pointcut-ref")); - assertEquals("lookupOnStartup", Conventions.attributeNameToPropertyName("lookup-on-startup")); + assertThat(Conventions.attributeNameToPropertyName("transaction-manager")).isEqualTo("transactionManager"); + assertThat(Conventions.attributeNameToPropertyName("pointcut-ref")).isEqualTo("pointcutRef"); + assertThat(Conventions.attributeNameToPropertyName("lookup-on-startup")).isEqualTo("lookupOnStartup"); } @Test @@ -121,7 +104,7 @@ public class ConventionsTests { String baseName = "foo"; Class cls = String.class; String desiredResult = "java.lang.String.foo"; - assertEquals(desiredResult, Conventions.getQualifiedAttributeName(cls, baseName)); + assertThat(Conventions.getQualifiedAttributeName(cls, baseName)).isEqualTo(desiredResult); } diff --git a/spring-core/src/test/java/org/springframework/core/ExceptionDepthComparatorTests.java b/spring-core/src/test/java/org/springframework/core/ExceptionDepthComparatorTests.java index be03bf5137a..601aba89639 100644 --- a/spring-core/src/test/java/org/springframework/core/ExceptionDepthComparatorTests.java +++ b/spring-core/src/test/java/org/springframework/core/ExceptionDepthComparatorTests.java @@ -20,7 +20,7 @@ import java.util.Arrays; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -32,55 +32,55 @@ public class ExceptionDepthComparatorTests { @Test public void targetBeforeSameDepth() throws Exception { Class foundClass = findClosestMatch(TargetException.class, SameDepthException.class); - assertEquals(TargetException.class, foundClass); + assertThat(foundClass).isEqualTo(TargetException.class); } @Test public void sameDepthBeforeTarget() throws Exception { Class foundClass = findClosestMatch(SameDepthException.class, TargetException.class); - assertEquals(TargetException.class, foundClass); + assertThat(foundClass).isEqualTo(TargetException.class); } @Test public void lowestDepthBeforeTarget() throws Exception { Class foundClass = findClosestMatch(LowestDepthException.class, TargetException.class); - assertEquals(TargetException.class, foundClass); + assertThat(foundClass).isEqualTo(TargetException.class); } @Test public void targetBeforeLowestDepth() throws Exception { Class foundClass = findClosestMatch(TargetException.class, LowestDepthException.class); - assertEquals(TargetException.class, foundClass); + assertThat(foundClass).isEqualTo(TargetException.class); } @Test public void noDepthBeforeTarget() throws Exception { Class foundClass = findClosestMatch(NoDepthException.class, TargetException.class); - assertEquals(TargetException.class, foundClass); + assertThat(foundClass).isEqualTo(TargetException.class); } @Test public void noDepthBeforeHighestDepth() throws Exception { Class foundClass = findClosestMatch(NoDepthException.class, HighestDepthException.class); - assertEquals(HighestDepthException.class, foundClass); + assertThat(foundClass).isEqualTo(HighestDepthException.class); } @Test public void highestDepthBeforeNoDepth() throws Exception { Class foundClass = findClosestMatch(HighestDepthException.class, NoDepthException.class); - assertEquals(HighestDepthException.class, foundClass); + assertThat(foundClass).isEqualTo(HighestDepthException.class); } @Test public void highestDepthBeforeLowestDepth() throws Exception { Class foundClass = findClosestMatch(HighestDepthException.class, LowestDepthException.class); - assertEquals(LowestDepthException.class, foundClass); + assertThat(foundClass).isEqualTo(LowestDepthException.class); } @Test public void lowestDepthBeforeHighestDepth() throws Exception { Class foundClass = findClosestMatch(LowestDepthException.class, HighestDepthException.class); - assertEquals(LowestDepthException.class, foundClass); + assertThat(foundClass).isEqualTo(LowestDepthException.class); } private Class findClosestMatch( diff --git a/spring-core/src/test/java/org/springframework/core/GenericTypeResolverTests.java b/spring-core/src/test/java/org/springframework/core/GenericTypeResolverTests.java index 7fcb3fc2804..d8bc57cbfa0 100644 --- a/spring-core/src/test/java/org/springframework/core/GenericTypeResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/GenericTypeResolverTests.java @@ -28,9 +28,6 @@ import java.util.Map; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.springframework.core.GenericTypeResolver.getTypeVariableMap; import static org.springframework.core.GenericTypeResolver.resolveReturnTypeArgument; import static org.springframework.core.GenericTypeResolver.resolveType; @@ -46,64 +43,59 @@ public class GenericTypeResolverTests { @Test public void simpleInterfaceType() { - assertEquals(String.class, resolveTypeArgument(MySimpleInterfaceType.class, MyInterfaceType.class)); + assertThat(resolveTypeArgument(MySimpleInterfaceType.class, MyInterfaceType.class)).isEqualTo(String.class); } @Test public void simpleCollectionInterfaceType() { - assertEquals(Collection.class, resolveTypeArgument(MyCollectionInterfaceType.class, MyInterfaceType.class)); + assertThat(resolveTypeArgument(MyCollectionInterfaceType.class, MyInterfaceType.class)).isEqualTo(Collection.class); } @Test public void simpleSuperclassType() { - assertEquals(String.class, resolveTypeArgument(MySimpleSuperclassType.class, MySuperclassType.class)); + assertThat(resolveTypeArgument(MySimpleSuperclassType.class, MySuperclassType.class)).isEqualTo(String.class); } @Test public void simpleCollectionSuperclassType() { - assertEquals(Collection.class, resolveTypeArgument(MyCollectionSuperclassType.class, MySuperclassType.class)); + assertThat(resolveTypeArgument(MyCollectionSuperclassType.class, MySuperclassType.class)).isEqualTo(Collection.class); } @Test public void nullIfNotResolvable() { GenericClass obj = new GenericClass<>(); - assertNull(resolveTypeArgument(obj.getClass(), GenericClass.class)); + assertThat((Object) resolveTypeArgument(obj.getClass(), GenericClass.class)).isNull(); } @Test public void methodReturnTypes() { - assertEquals(Integer.class, - resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "integer"), MyInterfaceType.class)); - assertEquals(String.class, - resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "string"), MyInterfaceType.class)); - assertEquals(null, resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "raw"), MyInterfaceType.class)); - assertEquals(null, - resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "object"), MyInterfaceType.class)); + assertThat(resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "integer"), MyInterfaceType.class)).isEqualTo(Integer.class); + assertThat(resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "string"), MyInterfaceType.class)).isEqualTo(String.class); + assertThat(resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "raw"), MyInterfaceType.class)).isEqualTo(null); + assertThat(resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "object"), MyInterfaceType.class)).isEqualTo(null); } @Test public void testResolveType() { Method intMessageMethod = findMethod(MyTypeWithMethods.class, "readIntegerInputMessage", MyInterfaceType.class); MethodParameter intMessageMethodParam = new MethodParameter(intMessageMethod, 0); - assertEquals(MyInterfaceType.class, - resolveType(intMessageMethodParam.getGenericParameterType(), new HashMap<>())); + assertThat(resolveType(intMessageMethodParam.getGenericParameterType(), new HashMap<>())).isEqualTo(MyInterfaceType.class); Method intArrMessageMethod = findMethod(MyTypeWithMethods.class, "readIntegerArrayInputMessage", MyInterfaceType[].class); MethodParameter intArrMessageMethodParam = new MethodParameter(intArrMessageMethod, 0); - assertEquals(MyInterfaceType[].class, - resolveType(intArrMessageMethodParam.getGenericParameterType(), new HashMap<>())); + assertThat(resolveType(intArrMessageMethodParam.getGenericParameterType(), new HashMap<>())).isEqualTo(MyInterfaceType[].class); Method genericArrMessageMethod = findMethod(MySimpleTypeWithMethods.class, "readGenericArrayInputMessage", Object[].class); MethodParameter genericArrMessageMethodParam = new MethodParameter(genericArrMessageMethod, 0); Map varMap = getTypeVariableMap(MySimpleTypeWithMethods.class); - assertEquals(Integer[].class, resolveType(genericArrMessageMethodParam.getGenericParameterType(), varMap)); + assertThat(resolveType(genericArrMessageMethodParam.getGenericParameterType(), varMap)).isEqualTo(Integer[].class); } @Test public void testBoundParameterizedType() { - assertEquals(B.class, resolveTypeArgument(TestImpl.class, TestIfc.class)); + assertThat(resolveTypeArgument(TestImpl.class, TestIfc.class)).isEqualTo(B.class); } @Test @@ -147,13 +139,13 @@ public class GenericTypeResolverTests { @Test // SPR-11030 public void getGenericsCannotBeResolved() throws Exception { Class[] resolved = GenericTypeResolver.resolveTypeArguments(List.class, Iterable.class); - assertNull(resolved); + assertThat((Object) resolved).isNull(); } @Test // SPR-11052 public void getRawMapTypeCannotBeResolved() throws Exception { Class[] resolved = GenericTypeResolver.resolveTypeArguments(Map.class, Map.class); - assertNull(resolved); + assertThat((Object) resolved).isNull(); } @Test // SPR-11044 @@ -174,10 +166,10 @@ public class GenericTypeResolverTests { @Test // SPR-11763 public void resolveIncompleteTypeVariables() { Class[] resolved = GenericTypeResolver.resolveTypeArguments(IdFixingRepository.class, Repository.class); - assertNotNull(resolved); - assertEquals(2, resolved.length); - assertEquals(Object.class, resolved[0]); - assertEquals(Long.class, resolved[1]); + assertThat(resolved).isNotNull(); + assertThat(resolved.length).isEqualTo(2); + assertThat(resolved[0]).isEqualTo(Object.class); + assertThat(resolved[1]).isEqualTo(Long.class); } diff --git a/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java b/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java index 9c043e8c4ce..bba252a8bd4 100644 --- a/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java +++ b/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java @@ -27,9 +27,7 @@ import org.junit.Test; import org.springframework.tests.sample.objects.TestObject; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Adrian Colyer @@ -43,43 +41,43 @@ public class LocalVariableTableParameterNameDiscovererTests { public void methodParameterNameDiscoveryNoArgs() throws NoSuchMethodException { Method getName = TestObject.class.getMethod("getName"); String[] names = discoverer.getParameterNames(getName); - assertNotNull("should find method info", names); - assertEquals("no argument names", 0, names.length); + assertThat(names).as("should find method info").isNotNull(); + assertThat(names.length).as("no argument names").isEqualTo(0); } @Test public void methodParameterNameDiscoveryWithArgs() throws NoSuchMethodException { Method setName = TestObject.class.getMethod("setName", String.class); String[] names = discoverer.getParameterNames(setName); - assertNotNull("should find method info", names); - assertEquals("one argument", 1, names.length); - assertEquals("name", names[0]); + assertThat(names).as("should find method info").isNotNull(); + assertThat(names.length).as("one argument").isEqualTo(1); + assertThat(names[0]).isEqualTo("name"); } @Test public void consParameterNameDiscoveryNoArgs() throws NoSuchMethodException { Constructor noArgsCons = TestObject.class.getConstructor(); String[] names = discoverer.getParameterNames(noArgsCons); - assertNotNull("should find cons info", names); - assertEquals("no argument names", 0, names.length); + assertThat(names).as("should find cons info").isNotNull(); + assertThat(names.length).as("no argument names").isEqualTo(0); } @Test public void consParameterNameDiscoveryArgs() throws NoSuchMethodException { Constructor twoArgCons = TestObject.class.getConstructor(String.class, int.class); String[] names = discoverer.getParameterNames(twoArgCons); - assertNotNull("should find cons info", names); - assertEquals("one argument", 2, names.length); - assertEquals("name", names[0]); - assertEquals("age", names[1]); + assertThat(names).as("should find cons info").isNotNull(); + assertThat(names.length).as("one argument").isEqualTo(2); + assertThat(names[0]).isEqualTo("name"); + assertThat(names[1]).isEqualTo("age"); } @Test public void staticMethodParameterNameDiscoveryNoArgs() throws NoSuchMethodException { Method m = getClass().getMethod("staticMethodNoLocalVars"); String[] names = discoverer.getParameterNames(m); - assertNotNull("should find method info", names); - assertEquals("no argument names", 0, names.length); + assertThat(names).as("should find method info").isNotNull(); + assertThat(names.length).as("no argument names").isEqualTo(0); } @Test @@ -88,18 +86,18 @@ public class LocalVariableTableParameterNameDiscovererTests { Method m1 = clazz.getMethod("staticMethod", Long.TYPE, Long.TYPE); String[] names = discoverer.getParameterNames(m1); - assertNotNull("should find method info", names); - assertEquals("two arguments", 2, names.length); - assertEquals("x", names[0]); - assertEquals("y", names[1]); + assertThat(names).as("should find method info").isNotNull(); + assertThat(names.length).as("two arguments").isEqualTo(2); + assertThat(names[0]).isEqualTo("x"); + assertThat(names[1]).isEqualTo("y"); Method m2 = clazz.getMethod("staticMethod", Long.TYPE, Long.TYPE, Long.TYPE); names = discoverer.getParameterNames(m2); - assertNotNull("should find method info", names); - assertEquals("three arguments", 3, names.length); - assertEquals("x", names[0]); - assertEquals("y", names[1]); - assertEquals("z", names[2]); + assertThat(names).as("should find method info").isNotNull(); + assertThat(names.length).as("three arguments").isEqualTo(3); + assertThat(names[0]).isEqualTo("x"); + assertThat(names[1]).isEqualTo("y"); + assertThat(names[2]).isEqualTo("z"); } @Test @@ -108,16 +106,16 @@ public class LocalVariableTableParameterNameDiscovererTests { Method m1 = clazz.getMethod("staticMethod", Long.TYPE); String[] names = discoverer.getParameterNames(m1); - assertNotNull("should find method info", names); - assertEquals("one argument", 1, names.length); - assertEquals("x", names[0]); + assertThat(names).as("should find method info").isNotNull(); + assertThat(names.length).as("one argument").isEqualTo(1); + assertThat(names[0]).isEqualTo("x"); Method m2 = clazz.getMethod("staticMethod", Long.TYPE, Long.TYPE); names = discoverer.getParameterNames(m2); - assertNotNull("should find method info", names); - assertEquals("two arguments", 2, names.length); - assertEquals("x", names[0]); - assertEquals("y", names[1]); + assertThat(names).as("should find method info").isNotNull(); + assertThat(names.length).as("two arguments").isEqualTo(2); + assertThat(names[0]).isEqualTo("x"); + assertThat(names[1]).isEqualTo("y"); } @Test @@ -126,18 +124,18 @@ public class LocalVariableTableParameterNameDiscovererTests { Method m1 = clazz.getMethod("instanceMethod", Double.TYPE, Double.TYPE); String[] names = discoverer.getParameterNames(m1); - assertNotNull("should find method info", names); - assertEquals("two arguments", 2, names.length); - assertEquals("x", names[0]); - assertEquals("y", names[1]); + assertThat(names).as("should find method info").isNotNull(); + assertThat(names.length).as("two arguments").isEqualTo(2); + assertThat(names[0]).isEqualTo("x"); + assertThat(names[1]).isEqualTo("y"); Method m2 = clazz.getMethod("instanceMethod", Double.TYPE, Double.TYPE, Double.TYPE); names = discoverer.getParameterNames(m2); - assertNotNull("should find method info", names); - assertEquals("three arguments", 3, names.length); - assertEquals("x", names[0]); - assertEquals("y", names[1]); - assertEquals("z", names[2]); + assertThat(names).as("should find method info").isNotNull(); + assertThat(names.length).as("three arguments").isEqualTo(3); + assertThat(names[0]).isEqualTo("x"); + assertThat(names[1]).isEqualTo("y"); + assertThat(names[2]).isEqualTo("z"); } @Test @@ -146,16 +144,16 @@ public class LocalVariableTableParameterNameDiscovererTests { Method m1 = clazz.getMethod("instanceMethod", String.class); String[] names = discoverer.getParameterNames(m1); - assertNotNull("should find method info", names); - assertEquals("one argument", 1, names.length); - assertEquals("aa", names[0]); + assertThat(names).as("should find method info").isNotNull(); + assertThat(names.length).as("one argument").isEqualTo(1); + assertThat(names[0]).isEqualTo("aa"); Method m2 = clazz.getMethod("instanceMethod", String.class, String.class); names = discoverer.getParameterNames(m2); - assertNotNull("should find method info", names); - assertEquals("two arguments", 2, names.length); - assertEquals("aa", names[0]); - assertEquals("bb", names[1]); + assertThat(names).as("should find method info").isNotNull(); + assertThat(names.length).as("two arguments").isEqualTo(2); + assertThat(names[0]).isEqualTo("aa"); + assertThat(names[1]).isEqualTo("bb"); } @Test @@ -164,45 +162,45 @@ public class LocalVariableTableParameterNameDiscovererTests { Constructor ctor = clazz.getDeclaredConstructor(Object.class); String[] names = discoverer.getParameterNames(ctor); - assertEquals(1, names.length); - assertEquals("key", names[0]); + assertThat(names.length).isEqualTo(1); + assertThat(names[0]).isEqualTo("key"); ctor = clazz.getDeclaredConstructor(Object.class, Object.class); names = discoverer.getParameterNames(ctor); - assertEquals(2, names.length); - assertEquals("key", names[0]); - assertEquals("value", names[1]); + assertThat(names.length).isEqualTo(2); + assertThat(names[0]).isEqualTo("key"); + assertThat(names[1]).isEqualTo("value"); Method m = clazz.getMethod("generifiedStaticMethod", Object.class); names = discoverer.getParameterNames(m); - assertEquals(1, names.length); - assertEquals("param", names[0]); + assertThat(names.length).isEqualTo(1); + assertThat(names[0]).isEqualTo("param"); m = clazz.getMethod("generifiedMethod", Object.class, long.class, Object.class, Object.class); names = discoverer.getParameterNames(m); - assertEquals(4, names.length); - assertEquals("param", names[0]); - assertEquals("x", names[1]); - assertEquals("key", names[2]); - assertEquals("value", names[3]); + assertThat(names.length).isEqualTo(4); + assertThat(names[0]).isEqualTo("param"); + assertThat(names[1]).isEqualTo("x"); + assertThat(names[2]).isEqualTo("key"); + assertThat(names[3]).isEqualTo("value"); m = clazz.getMethod("voidStaticMethod", Object.class, long.class, int.class); names = discoverer.getParameterNames(m); - assertEquals(3, names.length); - assertEquals("obj", names[0]); - assertEquals("x", names[1]); - assertEquals("i", names[2]); + assertThat(names.length).isEqualTo(3); + assertThat(names[0]).isEqualTo("obj"); + assertThat(names[1]).isEqualTo("x"); + assertThat(names[2]).isEqualTo("i"); m = clazz.getMethod("nonVoidStaticMethod", Object.class, long.class, int.class); names = discoverer.getParameterNames(m); - assertEquals(3, names.length); - assertEquals("obj", names[0]); - assertEquals("x", names[1]); - assertEquals("i", names[2]); + assertThat(names.length).isEqualTo(3); + assertThat(names[0]).isEqualTo("obj"); + assertThat(names[1]).isEqualTo("x"); + assertThat(names[2]).isEqualTo("i"); m = clazz.getMethod("getDate"); names = discoverer.getParameterNames(m); - assertEquals(0, names.length); + assertThat(names.length).isEqualTo(0); } @Ignore("Ignored because Ubuntu packages OpenJDK with debug symbols enabled. See SPR-8078.") @@ -214,15 +212,15 @@ public class LocalVariableTableParameterNameDiscovererTests { Method m = clazz.getMethod(methodName); String[] names = discoverer.getParameterNames(m); - assertNull(names); + assertThat(names).isNull(); m = clazz.getMethod(methodName, PrintStream.class); names = discoverer.getParameterNames(m); - assertNull(names); + assertThat(names).isNull(); m = clazz.getMethod(methodName, PrintStream.class, int.class); names = discoverer.getParameterNames(m); - assertNull(names); + assertThat(names).isNull(); } diff --git a/spring-core/src/test/java/org/springframework/core/MethodParameterTests.java b/spring-core/src/test/java/org/springframework/core/MethodParameterTests.java index 11d746a1004..ab412ede15c 100644 --- a/spring-core/src/test/java/org/springframework/core/MethodParameterTests.java +++ b/spring-core/src/test/java/org/springframework/core/MethodParameterTests.java @@ -27,12 +27,8 @@ import java.util.concurrent.Callable; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; /** * @author Arjen Poutsma @@ -61,48 +57,48 @@ public class MethodParameterTests { @Test public void testEquals() throws NoSuchMethodException { - assertEquals(stringParameter, stringParameter); - assertEquals(longParameter, longParameter); - assertEquals(intReturnType, intReturnType); + assertThat(stringParameter).isEqualTo(stringParameter); + assertThat(longParameter).isEqualTo(longParameter); + assertThat(intReturnType).isEqualTo(intReturnType); - assertFalse(stringParameter.equals(longParameter)); - assertFalse(stringParameter.equals(intReturnType)); - assertFalse(longParameter.equals(stringParameter)); - assertFalse(longParameter.equals(intReturnType)); - assertFalse(intReturnType.equals(stringParameter)); - assertFalse(intReturnType.equals(longParameter)); + assertThat(stringParameter.equals(longParameter)).isFalse(); + assertThat(stringParameter.equals(intReturnType)).isFalse(); + assertThat(longParameter.equals(stringParameter)).isFalse(); + assertThat(longParameter.equals(intReturnType)).isFalse(); + assertThat(intReturnType.equals(stringParameter)).isFalse(); + assertThat(intReturnType.equals(longParameter)).isFalse(); Method method = getClass().getMethod("method", String.class, Long.TYPE); MethodParameter methodParameter = new MethodParameter(method, 0); - assertEquals(stringParameter, methodParameter); - assertEquals(methodParameter, stringParameter); - assertNotEquals(longParameter, methodParameter); - assertNotEquals(methodParameter, longParameter); + assertThat(methodParameter).isEqualTo(stringParameter); + assertThat(stringParameter).isEqualTo(methodParameter); + assertThat(methodParameter).isNotEqualTo(longParameter); + assertThat(longParameter).isNotEqualTo(methodParameter); } @Test public void testHashCode() throws NoSuchMethodException { - assertEquals(stringParameter.hashCode(), stringParameter.hashCode()); - assertEquals(longParameter.hashCode(), longParameter.hashCode()); - assertEquals(intReturnType.hashCode(), intReturnType.hashCode()); + assertThat(stringParameter.hashCode()).isEqualTo(stringParameter.hashCode()); + assertThat(longParameter.hashCode()).isEqualTo(longParameter.hashCode()); + assertThat(intReturnType.hashCode()).isEqualTo(intReturnType.hashCode()); Method method = getClass().getMethod("method", String.class, Long.TYPE); MethodParameter methodParameter = new MethodParameter(method, 0); - assertEquals(stringParameter.hashCode(), methodParameter.hashCode()); - assertNotEquals(longParameter.hashCode(), methodParameter.hashCode()); + assertThat(methodParameter.hashCode()).isEqualTo(stringParameter.hashCode()); + assertThat(methodParameter.hashCode()).isNotEqualTo((long) longParameter.hashCode()); } @Test @SuppressWarnings("deprecation") public void testFactoryMethods() { - assertEquals(stringParameter, MethodParameter.forMethodOrConstructor(method, 0)); - assertEquals(longParameter, MethodParameter.forMethodOrConstructor(method, 1)); + assertThat(MethodParameter.forMethodOrConstructor(method, 0)).isEqualTo(stringParameter); + assertThat(MethodParameter.forMethodOrConstructor(method, 1)).isEqualTo(longParameter); - assertEquals(stringParameter, MethodParameter.forExecutable(method, 0)); - assertEquals(longParameter, MethodParameter.forExecutable(method, 1)); + assertThat(MethodParameter.forExecutable(method, 0)).isEqualTo(stringParameter); + assertThat(MethodParameter.forExecutable(method, 1)).isEqualTo(longParameter); - assertEquals(stringParameter, MethodParameter.forParameter(method.getParameters()[0])); - assertEquals(longParameter, MethodParameter.forParameter(method.getParameters()[1])); + assertThat(MethodParameter.forParameter(method.getParameters()[0])).isEqualTo(stringParameter); + assertThat(MethodParameter.forParameter(method.getParameters()[1])).isEqualTo(longParameter); } @Test @@ -115,8 +111,8 @@ public class MethodParameterTests { public void annotatedConstructorParameterInStaticNestedClass() throws Exception { Constructor constructor = NestedClass.class.getDeclaredConstructor(String.class); MethodParameter methodParameter = MethodParameter.forExecutable(constructor, 0); - assertEquals(String.class, methodParameter.getParameterType()); - assertNotNull("Failed to find @Param annotation", methodParameter.getParameterAnnotation(Param.class)); + assertThat(methodParameter.getParameterType()).isEqualTo(String.class); + assertThat(methodParameter.getParameterAnnotation(Param.class)).as("Failed to find @Param annotation").isNotNull(); } @Test // SPR-16652 @@ -124,16 +120,16 @@ public class MethodParameterTests { Constructor constructor = InnerClass.class.getConstructor(getClass(), String.class, Callable.class); MethodParameter methodParameter = MethodParameter.forExecutable(constructor, 0); - assertEquals(getClass(), methodParameter.getParameterType()); - assertNull(methodParameter.getParameterAnnotation(Param.class)); + assertThat(methodParameter.getParameterType()).isEqualTo(getClass()); + assertThat(methodParameter.getParameterAnnotation(Param.class)).isNull(); methodParameter = MethodParameter.forExecutable(constructor, 1); - assertEquals(String.class, methodParameter.getParameterType()); - assertNotNull("Failed to find @Param annotation", methodParameter.getParameterAnnotation(Param.class)); + assertThat(methodParameter.getParameterType()).isEqualTo(String.class); + assertThat(methodParameter.getParameterAnnotation(Param.class)).as("Failed to find @Param annotation").isNotNull(); methodParameter = MethodParameter.forExecutable(constructor, 2); - assertEquals(Callable.class, methodParameter.getParameterType()); - assertNull(methodParameter.getParameterAnnotation(Param.class)); + assertThat(methodParameter.getParameterType()).isEqualTo(Callable.class); + assertThat(methodParameter.getParameterAnnotation(Param.class)).isNull(); } @Test // SPR-16734 @@ -141,17 +137,16 @@ public class MethodParameterTests { Constructor constructor = InnerClass.class.getConstructor(getClass(), String.class, Callable.class); MethodParameter methodParameter = MethodParameter.forExecutable(constructor, 0); - assertEquals(getClass(), methodParameter.getParameterType()); - assertEquals(getClass(), methodParameter.getGenericParameterType()); + assertThat(methodParameter.getParameterType()).isEqualTo(getClass()); + assertThat(methodParameter.getGenericParameterType()).isEqualTo(getClass()); methodParameter = MethodParameter.forExecutable(constructor, 1); - assertEquals(String.class, methodParameter.getParameterType()); - assertEquals(String.class, methodParameter.getGenericParameterType()); + assertThat(methodParameter.getParameterType()).isEqualTo(String.class); + assertThat(methodParameter.getGenericParameterType()).isEqualTo(String.class); methodParameter = MethodParameter.forExecutable(constructor, 2); - assertEquals(Callable.class, methodParameter.getParameterType()); - assertEquals(ResolvableType.forClassWithGenerics(Callable.class, Integer.class).getType(), - methodParameter.getGenericParameterType()); + assertThat(methodParameter.getParameterType()).isEqualTo(Callable.class); + assertThat(methodParameter.getGenericParameterType()).isEqualTo(ResolvableType.forClassWithGenerics(Callable.class, Integer.class).getType()); } diff --git a/spring-core/src/test/java/org/springframework/core/NestedExceptionTests.java b/spring-core/src/test/java/org/springframework/core/NestedExceptionTests.java index cea1c50f38a..947dfbc8586 100644 --- a/spring-core/src/test/java/org/springframework/core/NestedExceptionTests.java +++ b/spring-core/src/test/java/org/springframework/core/NestedExceptionTests.java @@ -21,9 +21,7 @@ import java.io.PrintWriter; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -37,8 +35,8 @@ public class NestedExceptionTests { String mesg = "mesg of mine"; // Making a class abstract doesn't _really_ prevent instantiation :-) NestedRuntimeException nex = new NestedRuntimeException(mesg) {}; - assertNull(nex.getCause()); - assertEquals(nex.getMessage(), mesg); + assertThat(nex.getCause()).isNull(); + assertThat(mesg).isEqualTo(nex.getMessage()); // Check printStackTrace ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -46,7 +44,7 @@ public class NestedExceptionTests { nex.printStackTrace(pw); pw.flush(); String stackTrace = new String(baos.toByteArray()); - assertTrue(stackTrace.contains(mesg)); + assertThat(stackTrace.contains(mesg)).isTrue(); } @Test @@ -56,9 +54,9 @@ public class NestedExceptionTests { Exception rootCause = new Exception(rootCauseMsg); // Making a class abstract doesn't _really_ prevent instantiation :-) NestedRuntimeException nex = new NestedRuntimeException(myMessage, rootCause) {}; - assertEquals(nex.getCause(), rootCause); - assertTrue(nex.getMessage().contains(myMessage)); - assertTrue(nex.getMessage().endsWith(rootCauseMsg)); + assertThat(rootCause).isEqualTo(nex.getCause()); + assertThat(nex.getMessage().contains(myMessage)).isTrue(); + assertThat(nex.getMessage().endsWith(rootCauseMsg)).isTrue(); // check PrintStackTrace ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -66,8 +64,8 @@ public class NestedExceptionTests { nex.printStackTrace(pw); pw.flush(); String stackTrace = new String(baos.toByteArray()); - assertTrue(stackTrace.contains(rootCause.getClass().getName())); - assertTrue(stackTrace.contains(rootCauseMsg)); + assertThat(stackTrace.contains(rootCause.getClass().getName())).isTrue(); + assertThat(stackTrace.contains(rootCauseMsg)).isTrue(); } @Test @@ -75,8 +73,8 @@ public class NestedExceptionTests { String mesg = "mesg of mine"; // Making a class abstract doesn't _really_ prevent instantiation :-) NestedCheckedException nex = new NestedCheckedException(mesg) {}; - assertNull(nex.getCause()); - assertEquals(nex.getMessage(), mesg); + assertThat(nex.getCause()).isNull(); + assertThat(mesg).isEqualTo(nex.getMessage()); // Check printStackTrace ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -84,7 +82,7 @@ public class NestedExceptionTests { nex.printStackTrace(pw); pw.flush(); String stackTrace = new String(baos.toByteArray()); - assertTrue(stackTrace.contains(mesg)); + assertThat(stackTrace.contains(mesg)).isTrue(); } @Test @@ -94,9 +92,9 @@ public class NestedExceptionTests { Exception rootCause = new Exception(rootCauseMsg); // Making a class abstract doesn't _really_ prevent instantiation :-) NestedCheckedException nex = new NestedCheckedException(myMessage, rootCause) {}; - assertEquals(nex.getCause(), rootCause); - assertTrue(nex.getMessage().contains(myMessage)); - assertTrue(nex.getMessage().endsWith(rootCauseMsg)); + assertThat(rootCause).isEqualTo(nex.getCause()); + assertThat(nex.getMessage().contains(myMessage)).isTrue(); + assertThat(nex.getMessage().endsWith(rootCauseMsg)).isTrue(); // check PrintStackTrace ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -104,8 +102,8 @@ public class NestedExceptionTests { nex.printStackTrace(pw); pw.flush(); String stackTrace = new String(baos.toByteArray()); - assertTrue(stackTrace.contains(rootCause.getClass().getName())); - assertTrue(stackTrace.contains(rootCauseMsg)); + assertThat(stackTrace.contains(rootCause.getClass().getName())).isTrue(); + assertThat(stackTrace.contains(rootCauseMsg)).isTrue(); } } diff --git a/spring-core/src/test/java/org/springframework/core/OrderComparatorTests.java b/spring-core/src/test/java/org/springframework/core/OrderComparatorTests.java index d9feda5d602..881450f4c31 100644 --- a/spring-core/src/test/java/org/springframework/core/OrderComparatorTests.java +++ b/spring-core/src/test/java/org/springframework/core/OrderComparatorTests.java @@ -20,7 +20,7 @@ import java.util.Comparator; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for the {@link OrderComparator} class. @@ -36,65 +36,65 @@ public class OrderComparatorTests { @Test public void compareOrderedInstancesBefore() { - assertEquals(-1, this.comparator.compare(new StubOrdered(100), new StubOrdered(2000))); + assertThat(this.comparator.compare(new StubOrdered(100), new StubOrdered(2000))).isEqualTo(-1); } @Test public void compareOrderedInstancesSame() { - assertEquals(0, this.comparator.compare(new StubOrdered(100), new StubOrdered(100))); + assertThat(this.comparator.compare(new StubOrdered(100), new StubOrdered(100))).isEqualTo(0); } @Test public void compareOrderedInstancesAfter() { - assertEquals(1, this.comparator.compare(new StubOrdered(982300), new StubOrdered(100))); + assertThat(this.comparator.compare(new StubOrdered(982300), new StubOrdered(100))).isEqualTo(1); } @Test public void compareOrderedInstancesNullFirst() { - assertEquals(1, this.comparator.compare(null, new StubOrdered(100))); + assertThat(this.comparator.compare(null, new StubOrdered(100))).isEqualTo(1); } @Test public void compareOrderedInstancesNullLast() { - assertEquals(-1, this.comparator.compare(new StubOrdered(100), null)); + assertThat(this.comparator.compare(new StubOrdered(100), null)).isEqualTo(-1); } @Test public void compareOrderedInstancesDoubleNull() { - assertEquals(0, this.comparator.compare(null, null)); + assertThat(this.comparator.compare(null, null)).isEqualTo(0); } @Test public void compareTwoNonOrderedInstancesEndsUpAsSame() { - assertEquals(0, this.comparator.compare(new Object(), new Object())); + assertThat(this.comparator.compare(new Object(), new Object())).isEqualTo(0); } @Test public void compareWithSimpleSourceProvider() { Comparator customComparator = this.comparator.withSourceProvider( new TestSourceProvider(5L, new StubOrdered(25))); - assertEquals(-1, customComparator.compare(new StubOrdered(10), 5L)); + assertThat(customComparator.compare(new StubOrdered(10), 5L)).isEqualTo(-1); } @Test public void compareWithSourceProviderArray() { Comparator customComparator = this.comparator.withSourceProvider( new TestSourceProvider(5L, new Object[] {new StubOrdered(10), new StubOrdered(-25)})); - assertEquals(-1, customComparator.compare(5L, new Object())); + assertThat(customComparator.compare(5L, new Object())).isEqualTo(-1); } @Test public void compareWithSourceProviderArrayNoMatch() { Comparator customComparator = this.comparator.withSourceProvider( new TestSourceProvider(5L, new Object[]{new Object(), new Object()})); - assertEquals(0, customComparator.compare(new Object(), 5L)); + assertThat(customComparator.compare(new Object(), 5L)).isEqualTo(0); } @Test public void compareWithSourceProviderEmpty() { Comparator customComparator = this.comparator.withSourceProvider( new TestSourceProvider(50L, new Object())); - assertEquals(0, customComparator.compare(new Object(), 5L)); + assertThat(customComparator.compare(new Object(), 5L)).isEqualTo(0); } diff --git a/spring-core/src/test/java/org/springframework/core/ParameterizedTypeReferenceTests.java b/spring-core/src/test/java/org/springframework/core/ParameterizedTypeReferenceTests.java index 173328df164..b05368f8f27 100644 --- a/spring-core/src/test/java/org/springframework/core/ParameterizedTypeReferenceTests.java +++ b/spring-core/src/test/java/org/springframework/core/ParameterizedTypeReferenceTests.java @@ -22,7 +22,7 @@ import java.util.Map; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link ParameterizedTypeReference}. @@ -35,35 +35,35 @@ public class ParameterizedTypeReferenceTests { @Test public void stringTypeReference() { ParameterizedTypeReference typeReference = new ParameterizedTypeReference() {}; - assertEquals(String.class, typeReference.getType()); + assertThat(typeReference.getType()).isEqualTo(String.class); } @Test public void mapTypeReference() throws Exception { Type mapType = getClass().getMethod("mapMethod").getGenericReturnType(); ParameterizedTypeReference> typeReference = new ParameterizedTypeReference>() {}; - assertEquals(mapType, typeReference.getType()); + assertThat(typeReference.getType()).isEqualTo(mapType); } @Test public void listTypeReference() throws Exception { Type listType = getClass().getMethod("listMethod").getGenericReturnType(); ParameterizedTypeReference> typeReference = new ParameterizedTypeReference>() {}; - assertEquals(listType, typeReference.getType()); + assertThat(typeReference.getType()).isEqualTo(listType); } @Test public void reflectiveTypeReferenceWithSpecificDeclaration() throws Exception{ Type listType = getClass().getMethod("listMethod").getGenericReturnType(); ParameterizedTypeReference> typeReference = ParameterizedTypeReference.forType(listType); - assertEquals(listType, typeReference.getType()); + assertThat(typeReference.getType()).isEqualTo(listType); } @Test public void reflectiveTypeReferenceWithGenericDeclaration() throws Exception{ Type listType = getClass().getMethod("listMethod").getGenericReturnType(); ParameterizedTypeReference typeReference = ParameterizedTypeReference.forType(listType); - assertEquals(listType, typeReference.getType()); + assertThat(typeReference.getType()).isEqualTo(listType); } diff --git a/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java b/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java index 3753310f949..47db5a3ac08 100644 --- a/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java +++ b/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java @@ -24,8 +24,7 @@ import org.junit.Test; import org.springframework.tests.sample.objects.TestObject; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class PrioritizedParameterNameDiscovererTests { @@ -64,30 +63,30 @@ public class PrioritizedParameterNameDiscovererTests { @Test public void noParametersDiscoverers() { ParameterNameDiscoverer pnd = new PrioritizedParameterNameDiscoverer(); - assertNull(pnd.getParameterNames(anyMethod)); - assertNull(pnd.getParameterNames((Constructor) null)); + assertThat(pnd.getParameterNames(anyMethod)).isNull(); + assertThat(pnd.getParameterNames((Constructor) null)).isNull(); } @Test public void orderedParameterDiscoverers1() { PrioritizedParameterNameDiscoverer pnd = new PrioritizedParameterNameDiscoverer(); pnd.addDiscoverer(returnsFooBar); - assertTrue(Arrays.equals(FOO_BAR, pnd.getParameterNames(anyMethod))); - assertTrue(Arrays.equals(FOO_BAR, pnd.getParameterNames((Constructor) null))); + assertThat(Arrays.equals(FOO_BAR, pnd.getParameterNames(anyMethod))).isTrue(); + assertThat(Arrays.equals(FOO_BAR, pnd.getParameterNames((Constructor) null))).isTrue(); pnd.addDiscoverer(returnsSomethingElse); - assertTrue(Arrays.equals(FOO_BAR, pnd.getParameterNames(anyMethod))); - assertTrue(Arrays.equals(FOO_BAR, pnd.getParameterNames((Constructor) null))); + assertThat(Arrays.equals(FOO_BAR, pnd.getParameterNames(anyMethod))).isTrue(); + assertThat(Arrays.equals(FOO_BAR, pnd.getParameterNames((Constructor) null))).isTrue(); } @Test public void orderedParameterDiscoverers2() { PrioritizedParameterNameDiscoverer pnd = new PrioritizedParameterNameDiscoverer(); pnd.addDiscoverer(returnsSomethingElse); - assertTrue(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames(anyMethod))); - assertTrue(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames((Constructor) null))); + assertThat(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames(anyMethod))).isTrue(); + assertThat(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames((Constructor) null))).isTrue(); pnd.addDiscoverer(returnsFooBar); - assertTrue(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames(anyMethod))); - assertTrue(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames((Constructor) null))); + assertThat(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames(anyMethod))).isTrue(); + assertThat(Arrays.equals(SOMETHING_ELSE, pnd.getParameterNames((Constructor) null))).isTrue(); } } diff --git a/spring-core/src/test/java/org/springframework/core/ReactiveAdapterRegistryTests.java b/spring-core/src/test/java/org/springframework/core/ReactiveAdapterRegistryTests.java index 332ec2d6d94..d0e89ab2cba 100644 --- a/spring-core/src/test/java/org/springframework/core/ReactiveAdapterRegistryTests.java +++ b/spring-core/src/test/java/org/springframework/core/ReactiveAdapterRegistryTests.java @@ -33,12 +33,7 @@ import rx.Completable; import rx.Observable; import rx.Single; -import static org.junit.Assert.assertEquals; -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; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ReactiveAdapterRegistry}. @@ -54,29 +49,29 @@ public class ReactiveAdapterRegistryTests { public void defaultAdapterRegistrations() { // Reactor - assertNotNull(getAdapter(Mono.class)); - assertNotNull(getAdapter(Flux.class)); + assertThat(getAdapter(Mono.class)).isNotNull(); + assertThat(getAdapter(Flux.class)).isNotNull(); // Publisher - assertNotNull(getAdapter(Publisher.class)); + assertThat(getAdapter(Publisher.class)).isNotNull(); // Completable - assertNotNull(getAdapter(CompletableFuture.class)); + assertThat(getAdapter(CompletableFuture.class)).isNotNull(); // RxJava 1 - assertNotNull(getAdapter(Observable.class)); - assertNotNull(getAdapter(Single.class)); - assertNotNull(getAdapter(Completable.class)); + assertThat(getAdapter(Observable.class)).isNotNull(); + assertThat(getAdapter(Single.class)).isNotNull(); + assertThat(getAdapter(Completable.class)).isNotNull(); // RxJava 2 - assertNotNull(getAdapter(Flowable.class)); - assertNotNull(getAdapter(io.reactivex.Observable.class)); - assertNotNull(getAdapter(io.reactivex.Single.class)); - assertNotNull(getAdapter(Maybe.class)); - assertNotNull(getAdapter(io.reactivex.Completable.class)); + assertThat(getAdapter(Flowable.class)).isNotNull(); + assertThat(getAdapter(io.reactivex.Observable.class)).isNotNull(); + assertThat(getAdapter(io.reactivex.Single.class)).isNotNull(); + assertThat(getAdapter(Maybe.class)).isNotNull(); + assertThat(getAdapter(io.reactivex.Completable.class)).isNotNull(); // Coroutines - assertNotNull(getAdapter(Deferred.class)); + assertThat(getAdapter(Deferred.class)).isNotNull(); } @Test @@ -85,7 +80,7 @@ public class ReactiveAdapterRegistryTests { ReactiveAdapter adapter1 = getAdapter(Flux.class); ReactiveAdapter adapter2 = getAdapter(FluxProcessor.class); - assertSame(adapter1, adapter2); + assertThat(adapter2).isSameAs(adapter1); this.registry.registerReactiveType( ReactiveTypeDescriptor.multiValue(FluxProcessor.class, FluxProcessor::empty), @@ -94,8 +89,8 @@ public class ReactiveAdapterRegistryTests { ReactiveAdapter adapter3 = getAdapter(FluxProcessor.class); - assertNotNull(adapter3); - assertNotSame(adapter1, adapter3); + assertThat(adapter3).isNotNull(); + assertThat(adapter3).isNotSameAs(adapter1); } @Test @@ -103,8 +98,9 @@ public class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Publisher source = Flowable.fromIterable(sequence); Object target = getAdapter(Flux.class).fromPublisher(source); - assertTrue(target instanceof Flux); - assertEquals(sequence, ((Flux) target).collectList().block(Duration.ofMillis(1000))); + boolean condition = target instanceof Flux; + assertThat(condition).isTrue(); + assertThat(((Flux) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence); } // TODO: publisherToMono/CompletableFuture vs Single (ISE on multiple elements)? @@ -113,16 +109,18 @@ public class ReactiveAdapterRegistryTests { public void publisherToMono() { Publisher source = Flowable.fromArray(1, 2, 3); Object target = getAdapter(Mono.class).fromPublisher(source); - assertTrue(target instanceof Mono); - assertEquals(Integer.valueOf(1), ((Mono) target).block(Duration.ofMillis(1000))); + boolean condition = target instanceof Mono; + assertThat(condition).isTrue(); + assertThat(((Mono) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1)); } @Test public void publisherToCompletableFuture() throws Exception { Publisher source = Flowable.fromArray(1, 2, 3); Object target = getAdapter(CompletableFuture.class).fromPublisher(source); - assertTrue(target instanceof CompletableFuture); - assertEquals(Integer.valueOf(1), ((CompletableFuture) target).get()); + boolean condition = target instanceof CompletableFuture; + assertThat(condition).isTrue(); + assertThat(((CompletableFuture) target).get()).isEqualTo(Integer.valueOf(1)); } @Test @@ -130,24 +128,27 @@ public class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Publisher source = Flowable.fromIterable(sequence); Object target = getAdapter(rx.Observable.class).fromPublisher(source); - assertTrue(target instanceof rx.Observable); - assertEquals(sequence, ((rx.Observable) target).toList().toBlocking().first()); + boolean condition = target instanceof Observable; + assertThat(condition).isTrue(); + assertThat(((Observable) target).toList().toBlocking().first()).isEqualTo(sequence); } @Test public void publisherToRxSingle() { Publisher source = Flowable.fromArray(1); Object target = getAdapter(rx.Single.class).fromPublisher(source); - assertTrue(target instanceof rx.Single); - assertEquals(Integer.valueOf(1), ((rx.Single) target).toBlocking().value()); + boolean condition = target instanceof Single; + assertThat(condition).isTrue(); + assertThat(((Single) target).toBlocking().value()).isEqualTo(Integer.valueOf(1)); } @Test public void publisherToRxCompletable() { Publisher source = Flowable.fromArray(1, 2, 3); Object target = getAdapter(rx.Completable.class).fromPublisher(source); - assertTrue(target instanceof rx.Completable); - assertNull(((rx.Completable) target).get()); + boolean condition = target instanceof Completable; + assertThat(condition).isTrue(); + assertThat(((Completable) target).get()).isNull(); } @Test @@ -155,8 +156,9 @@ public class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Publisher source = Flux.fromIterable(sequence); Object target = getAdapter(io.reactivex.Flowable.class).fromPublisher(source); - assertTrue(target instanceof io.reactivex.Flowable); - assertEquals(sequence, ((io.reactivex.Flowable) target).toList().blockingGet()); + boolean condition = target instanceof Flowable; + assertThat(condition).isTrue(); + assertThat(((Flowable) target).toList().blockingGet()).isEqualTo(sequence); } @Test @@ -164,24 +166,27 @@ public class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Publisher source = Flowable.fromIterable(sequence); Object target = getAdapter(io.reactivex.Observable.class).fromPublisher(source); - assertTrue(target instanceof io.reactivex.Observable); - assertEquals(sequence, ((io.reactivex.Observable) target).toList().blockingGet()); + boolean condition = target instanceof io.reactivex.Observable; + assertThat(condition).isTrue(); + assertThat(((io.reactivex.Observable) target).toList().blockingGet()).isEqualTo(sequence); } @Test public void publisherToReactivexSingle() { Publisher source = Flowable.fromArray(1); Object target = getAdapter(io.reactivex.Single.class).fromPublisher(source); - assertTrue(target instanceof io.reactivex.Single); - assertEquals(Integer.valueOf(1), ((io.reactivex.Single) target).blockingGet()); + boolean condition = target instanceof io.reactivex.Single; + assertThat(condition).isTrue(); + assertThat(((io.reactivex.Single) target).blockingGet()).isEqualTo(Integer.valueOf(1)); } @Test public void publisherToReactivexCompletable() { Publisher source = Flowable.fromArray(1, 2, 3); Object target = getAdapter(io.reactivex.Completable.class).fromPublisher(source); - assertTrue(target instanceof io.reactivex.Completable); - assertNull(((io.reactivex.Completable) target).blockingGet()); + boolean condition = target instanceof io.reactivex.Completable; + assertThat(condition).isTrue(); + assertThat(((io.reactivex.Completable) target).blockingGet()).isNull(); } @Test @@ -189,23 +194,26 @@ public class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Object source = rx.Observable.from(sequence); Object target = getAdapter(rx.Observable.class).toPublisher(source); - assertTrue("Expected Flux Publisher: " + target.getClass().getName(), target instanceof Flux); - assertEquals(sequence, ((Flux) target).collectList().block(Duration.ofMillis(1000))); + boolean condition = target instanceof Flux; + assertThat(condition).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue(); + assertThat(((Flux) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence); } @Test public void rxSingleToPublisher() { Object source = rx.Single.just(1); Object target = getAdapter(rx.Single.class).toPublisher(source); - assertTrue("Expected Mono Publisher: " + target.getClass().getName(), target instanceof Mono); - assertEquals(Integer.valueOf(1), ((Mono) target).block(Duration.ofMillis(1000))); + boolean condition = target instanceof Mono; + assertThat(condition).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue(); + assertThat(((Mono) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1)); } @Test public void rxCompletableToPublisher() { Object source = rx.Completable.complete(); Object target = getAdapter(rx.Completable.class).toPublisher(source); - assertTrue("Expected Mono Publisher: " + target.getClass().getName(), target instanceof Mono); + boolean condition = target instanceof Mono; + assertThat(condition).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue(); ((Mono) target).block(Duration.ofMillis(1000)); } @@ -214,8 +222,9 @@ public class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Object source = io.reactivex.Flowable.fromIterable(sequence); Object target = getAdapter(io.reactivex.Flowable.class).toPublisher(source); - assertTrue("Expected Flux Publisher: " + target.getClass().getName(), target instanceof Flux); - assertEquals(sequence, ((Flux) target).collectList().block(Duration.ofMillis(1000))); + boolean condition = target instanceof Flux; + assertThat(condition).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue(); + assertThat(((Flux) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence); } @Test @@ -223,23 +232,26 @@ public class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Object source = io.reactivex.Observable.fromIterable(sequence); Object target = getAdapter(io.reactivex.Observable.class).toPublisher(source); - assertTrue("Expected Flux Publisher: " + target.getClass().getName(), target instanceof Flux); - assertEquals(sequence, ((Flux) target).collectList().block(Duration.ofMillis(1000))); + boolean condition = target instanceof Flux; + assertThat(condition).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue(); + assertThat(((Flux) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence); } @Test public void reactivexSingleToPublisher() { Object source = io.reactivex.Single.just(1); Object target = getAdapter(io.reactivex.Single.class).toPublisher(source); - assertTrue("Expected Mono Publisher: " + target.getClass().getName(), target instanceof Mono); - assertEquals(Integer.valueOf(1), ((Mono) target).block(Duration.ofMillis(1000))); + boolean condition = target instanceof Mono; + assertThat(condition).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue(); + assertThat(((Mono) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1)); } @Test public void reactivexCompletableToPublisher() { Object source = io.reactivex.Completable.complete(); Object target = getAdapter(io.reactivex.Completable.class).toPublisher(source); - assertTrue("Expected Mono Publisher: " + target.getClass().getName(), target instanceof Mono); + boolean condition = target instanceof Mono; + assertThat(condition).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue(); ((Mono) target).block(Duration.ofMillis(1000)); } @@ -248,8 +260,9 @@ public class ReactiveAdapterRegistryTests { CompletableFuture future = new CompletableFuture<>(); future.complete(1); Object target = getAdapter(CompletableFuture.class).toPublisher(future); - assertTrue("Expected Mono Publisher: " + target.getClass().getName(), target instanceof Mono); - assertEquals(Integer.valueOf(1), ((Mono) target).block(Duration.ofMillis(1000))); + boolean condition = target instanceof Mono; + assertThat(condition).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue(); + assertThat(((Mono) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1)); } diff --git a/spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java b/spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java index 4e7a748f16d..192d54d0eda 100644 --- a/spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java +++ b/spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java @@ -54,9 +54,6 @@ import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; 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.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; @@ -106,8 +103,8 @@ public class ResolvableTypeTests { ResolvableType type = ResolvableType.forClass(ExtendsList.class); assertThat(type.getType()).isEqualTo(ExtendsList.class); assertThat(type.getRawClass()).isEqualTo(ExtendsList.class); - assertTrue(type.isAssignableFrom(ExtendsList.class)); - assertFalse(type.isAssignableFrom(ArrayList.class)); + assertThat(type.isAssignableFrom(ExtendsList.class)).isTrue(); + assertThat(type.isAssignableFrom(ArrayList.class)).isFalse(); } @Test @@ -115,8 +112,8 @@ public class ResolvableTypeTests { ResolvableType type = ResolvableType.forClass(null); assertThat(type.getType()).isEqualTo(Object.class); assertThat(type.getRawClass()).isEqualTo(Object.class); - assertTrue(type.isAssignableFrom(Object.class)); - assertTrue(type.isAssignableFrom(String.class)); + assertThat(type.isAssignableFrom(Object.class)).isTrue(); + assertThat(type.isAssignableFrom(String.class)).isTrue(); } @Test @@ -124,8 +121,8 @@ public class ResolvableTypeTests { ResolvableType type = ResolvableType.forRawClass(ExtendsList.class); assertThat(type.getType()).isEqualTo(ExtendsList.class); assertThat(type.getRawClass()).isEqualTo(ExtendsList.class); - assertTrue(type.isAssignableFrom(ExtendsList.class)); - assertFalse(type.isAssignableFrom(ArrayList.class)); + assertThat(type.isAssignableFrom(ExtendsList.class)).isTrue(); + assertThat(type.isAssignableFrom(ArrayList.class)).isFalse(); } @Test @@ -133,8 +130,8 @@ public class ResolvableTypeTests { ResolvableType type = ResolvableType.forRawClass(null); assertThat(type.getType()).isEqualTo(Object.class); assertThat(type.getRawClass()).isEqualTo(Object.class); - assertTrue(type.isAssignableFrom(Object.class)); - assertTrue(type.isAssignableFrom(String.class)); + assertThat(type.isAssignableFrom(Object.class)).isTrue(); + assertThat(type.isAssignableFrom(String.class)).isTrue(); } @Test @@ -186,8 +183,8 @@ public class ResolvableTypeTests { assertThat(type2.resolve()).isEqualTo(List.class); assertThat(type2.getSource()).isSameAs(field2); - assertEquals(type, type2); - assertEquals(type.hashCode(), type2.hashCode()); + assertThat(type2).isEqualTo(type); + assertThat(type2.hashCode()).isEqualTo(type.hashCode()); } @Test @@ -899,7 +896,7 @@ public class ResolvableTypeTests { Type sourceType = Methods.class.getMethod("charSequenceReturn").getGenericReturnType(); ResolvableType reflectiveType = ResolvableType.forType(sourceType); ResolvableType declaredType = ResolvableType.forType(new ParameterizedTypeReference>() {}); - assertEquals(reflectiveType, declaredType); + assertThat(declaredType).isEqualTo(reflectiveType); } @Test @@ -985,19 +982,19 @@ public class ResolvableTypeTests { assertThatResolvableType(charSequenceType).isAssignableFrom(charSequenceType, stringType).isNotAssignableFrom(objectType); assertThatResolvableType(stringType).isAssignableFrom(stringType).isNotAssignableFrom(objectType, charSequenceType); - assertTrue(objectType.isAssignableFrom(String.class)); - assertTrue(objectType.isAssignableFrom(StringBuilder.class)); - assertTrue(charSequenceType.isAssignableFrom(String.class)); - assertTrue(charSequenceType.isAssignableFrom(StringBuilder.class)); - assertTrue(stringType.isAssignableFrom(String.class)); - assertFalse(stringType.isAssignableFrom(StringBuilder.class)); + assertThat(objectType.isAssignableFrom(String.class)).isTrue(); + assertThat(objectType.isAssignableFrom(StringBuilder.class)).isTrue(); + assertThat(charSequenceType.isAssignableFrom(String.class)).isTrue(); + assertThat(charSequenceType.isAssignableFrom(StringBuilder.class)).isTrue(); + assertThat(stringType.isAssignableFrom(String.class)).isTrue(); + assertThat(stringType.isAssignableFrom(StringBuilder.class)).isFalse(); - assertTrue(objectType.isInstance("a String")); - assertTrue(objectType.isInstance(new StringBuilder("a StringBuilder"))); - assertTrue(charSequenceType.isInstance("a String")); - assertTrue(charSequenceType.isInstance(new StringBuilder("a StringBuilder"))); - assertTrue(stringType.isInstance("a String")); - assertFalse(stringType.isInstance(new StringBuilder("a StringBuilder"))); + assertThat(objectType.isInstance("a String")).isTrue(); + assertThat(objectType.isInstance(new StringBuilder("a StringBuilder"))).isTrue(); + assertThat(charSequenceType.isInstance("a String")).isTrue(); + assertThat(charSequenceType.isInstance(new StringBuilder("a StringBuilder"))).isTrue(); + assertThat(stringType.isInstance("a String")).isTrue(); + assertThat(stringType.isInstance(new StringBuilder("a StringBuilder"))).isFalse(); } @Test @@ -1282,8 +1279,8 @@ public class ResolvableTypeTests { @Test public void testSpr11219() throws Exception { ResolvableType type = ResolvableType.forField(BaseProvider.class.getField("stuff"), BaseProvider.class); - assertTrue(type.getNested(2).isAssignableFrom(ResolvableType.forClass(BaseImplementation.class))); - assertEquals("java.util.Collection>", type.toString()); + assertThat(type.getNested(2).isAssignableFrom(ResolvableType.forClass(BaseImplementation.class))).isTrue(); + assertThat(type.toString()).isEqualTo("java.util.Collection>"); } @Test @@ -1301,8 +1298,8 @@ public class ResolvableTypeTests { ResolvableType collectionClass = ResolvableType.forRawClass(Collection.class); ResolvableType setClass = ResolvableType.forRawClass(Set.class); ResolvableType fromReturnType = ResolvableType.forMethodReturnType(Methods.class.getMethod("wildcardSet")); - assertTrue(collectionClass.isAssignableFrom(fromReturnType)); - assertTrue(setClass.isAssignableFrom(fromReturnType)); + assertThat(collectionClass.isAssignableFrom(fromReturnType)).isTrue(); + assertThat(setClass.isAssignableFrom(fromReturnType)).isTrue(); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/SimpleAliasRegistryTests.java b/spring-core/src/test/java/org/springframework/core/SimpleAliasRegistryTests.java index 88c9449fd2c..4011032420d 100644 --- a/spring-core/src/test/java/org/springframework/core/SimpleAliasRegistryTests.java +++ b/spring-core/src/test/java/org/springframework/core/SimpleAliasRegistryTests.java @@ -18,8 +18,7 @@ package org.springframework.core; import org.junit.Test; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -33,12 +32,12 @@ public class SimpleAliasRegistryTests { registry.registerAlias("testAlias", "testAlias2"); registry.registerAlias("testAlias2", "testAlias3"); - assertTrue(registry.hasAlias("test", "testAlias")); - assertTrue(registry.hasAlias("test", "testAlias2")); - assertTrue(registry.hasAlias("test", "testAlias3")); - assertSame("test", registry.canonicalName("testAlias")); - assertSame("test", registry.canonicalName("testAlias2")); - assertSame("test", registry.canonicalName("testAlias3")); + assertThat(registry.hasAlias("test", "testAlias")).isTrue(); + assertThat(registry.hasAlias("test", "testAlias2")).isTrue(); + assertThat(registry.hasAlias("test", "testAlias3")).isTrue(); + assertThat(registry.canonicalName("testAlias")).isSameAs("test"); + assertThat(registry.canonicalName("testAlias2")).isSameAs("test"); + assertThat(registry.canonicalName("testAlias3")).isSameAs("test"); } @Test // SPR-17191 @@ -46,19 +45,19 @@ public class SimpleAliasRegistryTests { SimpleAliasRegistry registry = new SimpleAliasRegistry(); registry.registerAlias("name", "alias_a"); registry.registerAlias("name", "alias_b"); - assertTrue(registry.hasAlias("name", "alias_a")); - assertTrue(registry.hasAlias("name", "alias_b")); + assertThat(registry.hasAlias("name", "alias_a")).isTrue(); + assertThat(registry.hasAlias("name", "alias_b")).isTrue(); registry.registerAlias("real_name", "name"); - assertTrue(registry.hasAlias("real_name", "name")); - assertTrue(registry.hasAlias("real_name", "alias_a")); - assertTrue(registry.hasAlias("real_name", "alias_b")); + assertThat(registry.hasAlias("real_name", "name")).isTrue(); + assertThat(registry.hasAlias("real_name", "alias_a")).isTrue(); + assertThat(registry.hasAlias("real_name", "alias_b")).isTrue(); registry.registerAlias("name", "alias_c"); - assertTrue(registry.hasAlias("real_name", "name")); - assertTrue(registry.hasAlias("real_name", "alias_a")); - assertTrue(registry.hasAlias("real_name", "alias_b")); - assertTrue(registry.hasAlias("real_name", "alias_c")); + assertThat(registry.hasAlias("real_name", "name")).isTrue(); + assertThat(registry.hasAlias("real_name", "alias_a")).isTrue(); + assertThat(registry.hasAlias("real_name", "alias_b")).isTrue(); + assertThat(registry.hasAlias("real_name", "alias_c")).isTrue(); } } diff --git a/spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java b/spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java index bb0ea3c7458..503f7af4854 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java @@ -54,12 +54,6 @@ import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.springframework.core.annotation.AnnotatedElementUtils.findAllMergedAnnotations; import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation; import static org.springframework.core.annotation.AnnotatedElementUtils.getAllAnnotationAttributes; @@ -90,26 +84,26 @@ public class AnnotatedElementUtilsTests { @Test public void getMetaAnnotationTypesOnNonAnnotatedClass() { - assertTrue(getMetaAnnotationTypes(NonAnnotatedClass.class, TransactionalComponent.class).isEmpty()); - assertTrue(getMetaAnnotationTypes(NonAnnotatedClass.class, TransactionalComponent.class.getName()).isEmpty()); + assertThat(getMetaAnnotationTypes(NonAnnotatedClass.class, TransactionalComponent.class).isEmpty()).isTrue(); + assertThat(getMetaAnnotationTypes(NonAnnotatedClass.class, TransactionalComponent.class.getName()).isEmpty()).isTrue(); } @Test public void getMetaAnnotationTypesOnClassWithMetaDepth1() { Set names = getMetaAnnotationTypes(TransactionalComponentClass.class, TransactionalComponent.class); - assertEquals(names(Transactional.class, Component.class, Indexed.class), names); + assertThat(names).isEqualTo(names(Transactional.class, Component.class, Indexed.class)); names = getMetaAnnotationTypes(TransactionalComponentClass.class, TransactionalComponent.class.getName()); - assertEquals(names(Transactional.class, Component.class, Indexed.class), names); + assertThat(names).isEqualTo(names(Transactional.class, Component.class, Indexed.class)); } @Test public void getMetaAnnotationTypesOnClassWithMetaDepth2() { Set names = getMetaAnnotationTypes(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class); - assertEquals(names(TransactionalComponent.class, Transactional.class, Component.class, Indexed.class), names); + assertThat(names).isEqualTo(names(TransactionalComponent.class, Transactional.class, Component.class, Indexed.class)); names = getMetaAnnotationTypes(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName()); - assertEquals(names(TransactionalComponent.class, Transactional.class, Component.class, Indexed.class), names); + assertThat(names).isEqualTo(names(TransactionalComponent.class, Transactional.class, Component.class, Indexed.class)); } private Set names(Class... classes) { @@ -118,124 +112,122 @@ public class AnnotatedElementUtilsTests { @Test public void hasMetaAnnotationTypesOnNonAnnotatedClass() { - assertFalse(hasMetaAnnotationTypes(NonAnnotatedClass.class, TX_NAME)); + assertThat(hasMetaAnnotationTypes(NonAnnotatedClass.class, TX_NAME)).isFalse(); } @Test public void hasMetaAnnotationTypesOnClassWithMetaDepth0() { - assertFalse(hasMetaAnnotationTypes(TransactionalComponentClass.class, TransactionalComponent.class.getName())); + assertThat(hasMetaAnnotationTypes(TransactionalComponentClass.class, TransactionalComponent.class.getName())).isFalse(); } @Test public void hasMetaAnnotationTypesOnClassWithMetaDepth1() { - assertTrue(hasMetaAnnotationTypes(TransactionalComponentClass.class, TX_NAME)); - assertTrue(hasMetaAnnotationTypes(TransactionalComponentClass.class, Component.class.getName())); + assertThat(hasMetaAnnotationTypes(TransactionalComponentClass.class, TX_NAME)).isTrue(); + assertThat(hasMetaAnnotationTypes(TransactionalComponentClass.class, Component.class.getName())).isTrue(); } @Test public void hasMetaAnnotationTypesOnClassWithMetaDepth2() { - assertTrue(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, TX_NAME)); - assertTrue(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, Component.class.getName())); - assertFalse(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName())); + assertThat(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, TX_NAME)).isTrue(); + assertThat(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, Component.class.getName())).isTrue(); + assertThat(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName())).isFalse(); } @Test public void isAnnotatedOnNonAnnotatedClass() { - assertFalse(isAnnotated(NonAnnotatedClass.class, Transactional.class)); + assertThat(isAnnotated(NonAnnotatedClass.class, Transactional.class)).isFalse(); } @Test public void isAnnotatedOnClassWithMetaDepth() { - assertTrue(isAnnotated(TransactionalComponentClass.class, TransactionalComponent.class)); - assertFalse("isAnnotated() does not search the class hierarchy.", - isAnnotated(SubTransactionalComponentClass.class, TransactionalComponent.class)); - assertTrue(isAnnotated(TransactionalComponentClass.class, Transactional.class)); - assertTrue(isAnnotated(TransactionalComponentClass.class, Component.class)); - assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, Transactional.class)); - assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, Component.class)); - assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class)); + assertThat(isAnnotated(TransactionalComponentClass.class, TransactionalComponent.class)).isTrue(); + assertThat(isAnnotated(SubTransactionalComponentClass.class, TransactionalComponent.class)).as("isAnnotated() does not search the class hierarchy.").isFalse(); + assertThat(isAnnotated(TransactionalComponentClass.class, Transactional.class)).isTrue(); + assertThat(isAnnotated(TransactionalComponentClass.class, Component.class)).isTrue(); + assertThat(isAnnotated(ComposedTransactionalComponentClass.class, Transactional.class)).isTrue(); + assertThat(isAnnotated(ComposedTransactionalComponentClass.class, Component.class)).isTrue(); + assertThat(isAnnotated(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class)).isTrue(); } @Test public void isAnnotatedForPlainTypes() { - assertTrue(isAnnotated(Order.class, Documented.class)); - assertTrue(isAnnotated(NonNullApi.class, Documented.class)); - assertTrue(isAnnotated(NonNullApi.class, Nonnull.class)); - assertTrue(isAnnotated(ParametersAreNonnullByDefault.class, Nonnull.class)); + assertThat(isAnnotated(Order.class, Documented.class)).isTrue(); + assertThat(isAnnotated(NonNullApi.class, Documented.class)).isTrue(); + assertThat(isAnnotated(NonNullApi.class, Nonnull.class)).isTrue(); + assertThat(isAnnotated(ParametersAreNonnullByDefault.class, Nonnull.class)).isTrue(); } @Test public void isAnnotatedWithNameOnNonAnnotatedClass() { - assertFalse(isAnnotated(NonAnnotatedClass.class, TX_NAME)); + assertThat(isAnnotated(NonAnnotatedClass.class, TX_NAME)).isFalse(); } @Test public void isAnnotatedWithNameOnClassWithMetaDepth() { - assertTrue(isAnnotated(TransactionalComponentClass.class, TransactionalComponent.class.getName())); - assertFalse("isAnnotated() does not search the class hierarchy.", - isAnnotated(SubTransactionalComponentClass.class, TransactionalComponent.class.getName())); - assertTrue(isAnnotated(TransactionalComponentClass.class, TX_NAME)); - assertTrue(isAnnotated(TransactionalComponentClass.class, Component.class.getName())); - assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, TX_NAME)); - assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, Component.class.getName())); - assertTrue(isAnnotated(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName())); + assertThat(isAnnotated(TransactionalComponentClass.class, TransactionalComponent.class.getName())).isTrue(); + assertThat(isAnnotated(SubTransactionalComponentClass.class, TransactionalComponent.class.getName())).as("isAnnotated() does not search the class hierarchy.").isFalse(); + assertThat(isAnnotated(TransactionalComponentClass.class, TX_NAME)).isTrue(); + assertThat(isAnnotated(TransactionalComponentClass.class, Component.class.getName())).isTrue(); + assertThat(isAnnotated(ComposedTransactionalComponentClass.class, TX_NAME)).isTrue(); + assertThat(isAnnotated(ComposedTransactionalComponentClass.class, Component.class.getName())).isTrue(); + assertThat(isAnnotated(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName())).isTrue(); } @Test public void hasAnnotationOnNonAnnotatedClass() { - assertFalse(hasAnnotation(NonAnnotatedClass.class, Transactional.class)); + assertThat(hasAnnotation(NonAnnotatedClass.class, Transactional.class)).isFalse(); } @Test public void hasAnnotationOnClassWithMetaDepth() { - assertTrue(hasAnnotation(TransactionalComponentClass.class, TransactionalComponent.class)); - assertTrue(hasAnnotation(SubTransactionalComponentClass.class, TransactionalComponent.class)); - assertTrue(hasAnnotation(TransactionalComponentClass.class, Transactional.class)); - assertTrue(hasAnnotation(TransactionalComponentClass.class, Component.class)); - assertTrue(hasAnnotation(ComposedTransactionalComponentClass.class, Transactional.class)); - assertTrue(hasAnnotation(ComposedTransactionalComponentClass.class, Component.class)); - assertTrue(hasAnnotation(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class)); + assertThat(hasAnnotation(TransactionalComponentClass.class, TransactionalComponent.class)).isTrue(); + assertThat(hasAnnotation(SubTransactionalComponentClass.class, TransactionalComponent.class)).isTrue(); + assertThat(hasAnnotation(TransactionalComponentClass.class, Transactional.class)).isTrue(); + assertThat(hasAnnotation(TransactionalComponentClass.class, Component.class)).isTrue(); + assertThat(hasAnnotation(ComposedTransactionalComponentClass.class, Transactional.class)).isTrue(); + assertThat(hasAnnotation(ComposedTransactionalComponentClass.class, Component.class)).isTrue(); + assertThat(hasAnnotation(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class)).isTrue(); } @Test public void hasAnnotationForPlainTypes() { - assertTrue(hasAnnotation(Order.class, Documented.class)); - assertTrue(hasAnnotation(NonNullApi.class, Documented.class)); - assertTrue(hasAnnotation(NonNullApi.class, Nonnull.class)); - assertTrue(hasAnnotation(ParametersAreNonnullByDefault.class, Nonnull.class)); + assertThat(hasAnnotation(Order.class, Documented.class)).isTrue(); + assertThat(hasAnnotation(NonNullApi.class, Documented.class)).isTrue(); + assertThat(hasAnnotation(NonNullApi.class, Nonnull.class)).isTrue(); + assertThat(hasAnnotation(ParametersAreNonnullByDefault.class, Nonnull.class)).isTrue(); } @Test public void getAllAnnotationAttributesOnNonAnnotatedClass() { - assertNull(getAllAnnotationAttributes(NonAnnotatedClass.class, TX_NAME)); + assertThat(getAllAnnotationAttributes(NonAnnotatedClass.class, TX_NAME)).isNull(); } @Test public void getAllAnnotationAttributesOnClassWithLocalAnnotation() { MultiValueMap attributes = getAllAnnotationAttributes(TxConfig.class, TX_NAME); - assertNotNull("Annotation attributes map for @Transactional on TxConfig", attributes); - assertEquals("value for TxConfig", asList("TxConfig"), attributes.get("value")); + assertThat(attributes).as("Annotation attributes map for @Transactional on TxConfig").isNotNull(); + assertThat(attributes.get("value")).as("value for TxConfig").isEqualTo(asList("TxConfig")); } @Test public void getAllAnnotationAttributesOnClassWithLocalComposedAnnotationAndInheritedAnnotation() { MultiValueMap attributes = getAllAnnotationAttributes(SubClassWithInheritedAnnotation.class, TX_NAME); - assertNotNull("Annotation attributes map for @Transactional on SubClassWithInheritedAnnotation", attributes); - assertEquals(asList("composed2", "transactionManager"), attributes.get("qualifier")); + assertThat(attributes).as("Annotation attributes map for @Transactional on SubClassWithInheritedAnnotation").isNotNull(); + assertThat(attributes.get("qualifier")).isEqualTo(asList("composed2", "transactionManager")); } @Test public void getAllAnnotationAttributesFavorsInheritedAnnotationsOverMoreLocallyDeclaredComposedAnnotations() { MultiValueMap attributes = getAllAnnotationAttributes(SubSubClassWithInheritedAnnotation.class, TX_NAME); - assertNotNull("Annotation attributes map for @Transactional on SubSubClassWithInheritedAnnotation", attributes); - assertEquals(asList("transactionManager"), attributes.get("qualifier")); + assertThat(attributes).as("Annotation attributes map for @Transactional on SubSubClassWithInheritedAnnotation").isNotNull(); + assertThat(attributes.get("qualifier")).isEqualTo(asList("transactionManager")); } @Test public void getAllAnnotationAttributesFavorsInheritedComposedAnnotationsOverMoreLocallyDeclaredComposedAnnotations() { MultiValueMap attributes = getAllAnnotationAttributes( SubSubClassWithInheritedComposedAnnotation.class, TX_NAME); - assertNotNull("Annotation attributes map for @Transactional on SubSubClassWithInheritedComposedAnnotation", attributes); - assertEquals(asList("composed1"), attributes.get("qualifier")); + assertThat(attributes).as("Annotation attributes map for @Transactional on SubSubClassWithInheritedComposedAnnotation").isNotNull(); + assertThat(attributes.get("qualifier")).isEqualTo(asList("composed1")); } /** @@ -249,8 +241,8 @@ public class AnnotatedElementUtilsTests { public void getAllAnnotationAttributesOnClassWithLocalAnnotationThatShadowsAnnotationFromSuperclass() { // See org.springframework.core.env.EnvironmentSystemIntegrationTests#mostSpecificDerivedClassDrivesEnvironment_withDevEnvAndDerivedDevConfigClass MultiValueMap attributes = getAllAnnotationAttributes(DerivedTxConfig.class, TX_NAME); - assertNotNull("Annotation attributes map for @Transactional on DerivedTxConfig", attributes); - assertEquals("value for DerivedTxConfig", asList("DerivedTxConfig"), attributes.get("value")); + assertThat(attributes).as("Annotation attributes map for @Transactional on DerivedTxConfig").isNotNull(); + assertThat(attributes.get("value")).as("value for DerivedTxConfig").isEqualTo(asList("DerivedTxConfig")); } /** @@ -260,25 +252,24 @@ public class AnnotatedElementUtilsTests { public void getAllAnnotationAttributesOnClassWithMultipleComposedAnnotations() { // See org.springframework.core.env.EnvironmentSystemIntegrationTests MultiValueMap attributes = getAllAnnotationAttributes(TxFromMultipleComposedAnnotations.class, TX_NAME); - assertNotNull("Annotation attributes map for @Transactional on TxFromMultipleComposedAnnotations", attributes); - assertEquals("value for TxFromMultipleComposedAnnotations.", asList("TxInheritedComposed", "TxComposed"), - attributes.get("value")); + assertThat(attributes).as("Annotation attributes map for @Transactional on TxFromMultipleComposedAnnotations").isNotNull(); + assertThat(attributes.get("value")).as("value for TxFromMultipleComposedAnnotations.").isEqualTo(asList("TxInheritedComposed", "TxComposed")); } @Test public void getAllAnnotationAttributesOnLangType() { MultiValueMap attributes = getAllAnnotationAttributes( NonNullApi.class, Nonnull.class.getName()); - assertNotNull("Annotation attributes map for @Nonnull on NonNullApi", attributes); - assertEquals("value for NonNullApi", asList(When.ALWAYS), attributes.get("when")); + assertThat(attributes).as("Annotation attributes map for @Nonnull on NonNullApi").isNotNull(); + assertThat(attributes.get("when")).as("value for NonNullApi").isEqualTo(asList(When.ALWAYS)); } @Test public void getAllAnnotationAttributesOnJavaxType() { MultiValueMap attributes = getAllAnnotationAttributes( ParametersAreNonnullByDefault.class, Nonnull.class.getName()); - assertNotNull("Annotation attributes map for @Nonnull on NonNullApi", attributes); - assertEquals("value for NonNullApi", asList(When.ALWAYS), attributes.get("when")); + assertThat(attributes).as("Annotation attributes map for @Nonnull on NonNullApi").isNotNull(); + assertThat(attributes.get("when")).as("value for NonNullApi").isEqualTo(asList(When.ALWAYS)); } @Test @@ -286,10 +277,10 @@ public class AnnotatedElementUtilsTests { Class element = TxConfig.class; String name = TX_NAME; AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); - assertNotNull("Annotation attributes for @Transactional on TxConfig", attributes); - assertEquals("value for TxConfig", "TxConfig", attributes.getString("value")); + assertThat(attributes).as("Annotation attributes for @Transactional on TxConfig").isNotNull(); + assertThat(attributes.getString("value")).as("value for TxConfig").isEqualTo("TxConfig"); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); + assertThat(isAnnotated(element, name)).isTrue(); } @Test @@ -297,16 +288,16 @@ public class AnnotatedElementUtilsTests { Class element = DerivedTxConfig.class; String name = TX_NAME; AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); - assertNotNull("Annotation attributes for @Transactional on DerivedTxConfig", attributes); - assertEquals("value for DerivedTxConfig", "DerivedTxConfig", attributes.getString("value")); + assertThat(attributes).as("Annotation attributes for @Transactional on DerivedTxConfig").isNotNull(); + assertThat(attributes.getString("value")).as("value for DerivedTxConfig").isEqualTo("DerivedTxConfig"); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); + assertThat(isAnnotated(element, name)).isTrue(); } @Test public void getMergedAnnotationAttributesOnMetaCycleAnnotatedClassWithMissingTargetMetaAnnotation() { AnnotationAttributes attributes = getMergedAnnotationAttributes(MetaCycleAnnotatedClass.class, TX_NAME); - assertNull("Should not find annotation attributes for @Transactional on MetaCycleAnnotatedClass", attributes); + assertThat(attributes).as("Should not find annotation attributes for @Transactional on MetaCycleAnnotatedClass").isNull(); } @Test @@ -314,10 +305,10 @@ public class AnnotatedElementUtilsTests { Class element = SubClassWithInheritedAnnotation.class; String name = TX_NAME; AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); - assertNotNull("AnnotationAttributes for @Transactional on SubClassWithInheritedAnnotation", attributes); + assertThat(attributes).as("AnnotationAttributes for @Transactional on SubClassWithInheritedAnnotation").isNotNull(); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); - assertTrue("readOnly flag for SubClassWithInheritedAnnotation.", attributes.getBoolean("readOnly")); + assertThat(isAnnotated(element, name)).isTrue(); + assertThat(attributes.getBoolean("readOnly")).as("readOnly flag for SubClassWithInheritedAnnotation.").isTrue(); } @Test @@ -325,10 +316,10 @@ public class AnnotatedElementUtilsTests { Class element = SubSubClassWithInheritedAnnotation.class; String name = TX_NAME; AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); - assertNotNull("AnnotationAttributes for @Transactional on SubSubClassWithInheritedAnnotation", attributes); + assertThat(attributes).as("AnnotationAttributes for @Transactional on SubSubClassWithInheritedAnnotation").isNotNull(); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); - assertFalse("readOnly flag for SubSubClassWithInheritedAnnotation.", attributes.getBoolean("readOnly")); + assertThat(isAnnotated(element, name)).isTrue(); + assertThat(attributes.getBoolean("readOnly")).as("readOnly flag for SubSubClassWithInheritedAnnotation.").isFalse(); } @Test @@ -336,10 +327,10 @@ public class AnnotatedElementUtilsTests { Class element = SubSubClassWithInheritedComposedAnnotation.class; String name = TX_NAME; AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); - assertNotNull("AnnotationAttributes for @Transactional on SubSubClassWithInheritedComposedAnnotation.", attributes); + assertThat(attributes).as("AnnotationAttributes for @Transactional on SubSubClassWithInheritedComposedAnnotation.").isNotNull(); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); - assertFalse("readOnly flag for SubSubClassWithInheritedComposedAnnotation.", attributes.getBoolean("readOnly")); + assertThat(isAnnotated(element, name)).isTrue(); + assertThat(attributes.getBoolean("readOnly")).as("readOnly flag for SubSubClassWithInheritedComposedAnnotation.").isFalse(); } @Test @@ -347,9 +338,9 @@ public class AnnotatedElementUtilsTests { Class element = ConcreteClassWithInheritedAnnotation.class; String name = TX_NAME; AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); - assertNull("Should not find @Transactional on ConcreteClassWithInheritedAnnotation", attributes); + assertThat(attributes).as("Should not find @Transactional on ConcreteClassWithInheritedAnnotation").isNull(); // Verify contracts between utility methods: - assertFalse(isAnnotated(element, name)); + assertThat(isAnnotated(element, name)).isFalse(); } @Test @@ -357,9 +348,9 @@ public class AnnotatedElementUtilsTests { Class element = InheritedAnnotationInterface.class; String name = TX_NAME; AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); - assertNotNull("Should find @Transactional on InheritedAnnotationInterface", attributes); + assertThat(attributes).as("Should find @Transactional on InheritedAnnotationInterface").isNotNull(); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); + assertThat(isAnnotated(element, name)).isTrue(); } @Test @@ -367,9 +358,9 @@ public class AnnotatedElementUtilsTests { Class element = NonInheritedAnnotationInterface.class; String name = Order.class.getName(); AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); - assertNotNull("Should find @Order on NonInheritedAnnotationInterface", attributes); + assertThat(attributes).as("Should find @Order on NonInheritedAnnotationInterface").isNotNull(); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); + assertThat(isAnnotated(element, name)).isTrue(); } @Test @@ -378,12 +369,12 @@ public class AnnotatedElementUtilsTests { String name = ContextConfig.class.getName(); AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); - assertNotNull("Should find @ContextConfig on " + element.getSimpleName(), attributes); - assertArrayEquals("locations", asArray("explicitDeclaration"), attributes.getStringArray("locations")); - assertArrayEquals("value", asArray("explicitDeclaration"), attributes.getStringArray("value")); + assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull(); + assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(asArray("explicitDeclaration")); + assertThat(attributes.getStringArray("value")).as("value").isEqualTo(asArray("explicitDeclaration")); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); + assertThat(isAnnotated(element, name)).isTrue(); } /** @@ -409,12 +400,12 @@ public class AnnotatedElementUtilsTests { String simpleName = clazz.getSimpleName(); AnnotationAttributes attributes = getMergedAnnotationAttributes(clazz, name); - assertNotNull("Should find @ContextConfig on " + simpleName, attributes); - assertArrayEquals("locations for class [" + clazz.getSimpleName() + "]", expected, attributes.getStringArray("locations")); - assertArrayEquals("value for class [" + clazz.getSimpleName() + "]", expected, attributes.getStringArray("value")); + assertThat(attributes).as("Should find @ContextConfig on " + simpleName).isNotNull(); + assertThat(attributes.getStringArray("locations")).as("locations for class [" + clazz.getSimpleName() + "]").isEqualTo(expected); + assertThat(attributes.getStringArray("value")).as("value for class [" + clazz.getSimpleName() + "]").isEqualTo(expected); // Verify contracts between utility methods: - assertTrue(isAnnotated(clazz, name)); + assertThat(isAnnotated(clazz, name)).isTrue(); } @Test @@ -423,12 +414,12 @@ public class AnnotatedElementUtilsTests { String name = ContextConfig.class.getName(); AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); - assertNotNull("Should find @ContextConfig on " + element.getSimpleName(), attributes); - assertArrayEquals("value", asArray("test.xml"), attributes.getStringArray("value")); - assertArrayEquals("locations", asArray("test.xml"), attributes.getStringArray("locations")); + assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull(); + assertThat(attributes.getStringArray("value")).as("value").isEqualTo(asArray("test.xml")); + assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(asArray("test.xml")); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); + assertThat(isAnnotated(element, name)).isTrue(); } @Test @@ -437,12 +428,12 @@ public class AnnotatedElementUtilsTests { String name = ContextConfig.class.getName(); AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); - assertNotNull("Should find @ContextConfig on " + element.getSimpleName(), attributes); - assertArrayEquals("locations", asArray("test.xml"), attributes.getStringArray("locations")); - assertArrayEquals("value", asArray("test.xml"), attributes.getStringArray("value")); + assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull(); + assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(asArray("test.xml")); + assertThat(attributes.getStringArray("value")).as("value").isEqualTo(asArray("test.xml")); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); + assertThat(isAnnotated(element, name)).isTrue(); } @Test @@ -452,14 +443,14 @@ public class AnnotatedElementUtilsTests { AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name); String[] expected = asArray("A.xml", "B.xml"); - assertNotNull("Should find @ImplicitAliasesContextConfig on " + element.getSimpleName(), attributes); - assertArrayEquals("groovyScripts", expected, attributes.getStringArray("groovyScripts")); - assertArrayEquals("xmlFiles", expected, attributes.getStringArray("xmlFiles")); - assertArrayEquals("locations", expected, attributes.getStringArray("locations")); - assertArrayEquals("value", expected, attributes.getStringArray("value")); + assertThat(attributes).as("Should find @ImplicitAliasesContextConfig on " + element.getSimpleName()).isNotNull(); + assertThat(attributes.getStringArray("groovyScripts")).as("groovyScripts").isEqualTo(expected); + assertThat(attributes.getStringArray("xmlFiles")).as("xmlFiles").isEqualTo(expected); + assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(expected); + assertThat(attributes.getStringArray("value")).as("value").isEqualTo(expected); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); + assertThat(isAnnotated(element, name)).isTrue(); } @Test @@ -498,13 +489,14 @@ public class AnnotatedElementUtilsTests { String name = ContextConfig.class.getName(); ContextConfig contextConfig = getMergedAnnotation(element, ContextConfig.class); - assertNotNull("Should find @ContextConfig on " + element.getSimpleName(), contextConfig); - assertArrayEquals("locations", expected, contextConfig.locations()); - assertArrayEquals("value", expected, contextConfig.value()); - assertArrayEquals("classes", new Class[0], contextConfig.classes()); + assertThat(contextConfig).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull(); + assertThat(contextConfig.locations()).as("locations").isEqualTo(expected); + assertThat(contextConfig.value()).as("value").isEqualTo(expected); + Object[] expecteds = new Class[0]; + assertThat(contextConfig.classes()).as("classes").isEqualTo(expecteds); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); + assertThat(isAnnotated(element, name)).isTrue(); } @Test @@ -514,14 +506,14 @@ public class AnnotatedElementUtilsTests { ImplicitAliasesContextConfig config = getMergedAnnotation(element, ImplicitAliasesContextConfig.class); String[] expected = asArray("A.xml", "B.xml"); - assertNotNull("Should find @ImplicitAliasesContextConfig on " + element.getSimpleName(), config); - assertArrayEquals("groovyScripts", expected, config.groovyScripts()); - assertArrayEquals("xmlFiles", expected, config.xmlFiles()); - assertArrayEquals("locations", expected, config.locations()); - assertArrayEquals("value", expected, config.value()); + assertThat(config).as("Should find @ImplicitAliasesContextConfig on " + element.getSimpleName()).isNotNull(); + assertThat(config.groovyScripts()).as("groovyScripts").isEqualTo(expected); + assertThat(config.xmlFiles()).as("xmlFiles").isEqualTo(expected); + assertThat(config.locations()).as("locations").isEqualTo(expected); + assertThat(config.value()).as("value").isEqualTo(expected); // Verify contracts between utility methods: - assertTrue(isAnnotated(element, name)); + assertThat(isAnnotated(element, name)).isTrue(); } @Test @@ -541,66 +533,66 @@ public class AnnotatedElementUtilsTests { String[] expected = asArray("test.xml"); - assertNotNull("Should find @ContextConfig on " + element.getSimpleName(), attributes); - assertArrayEquals("locations", expected, attributes.getStringArray("locations")); - assertArrayEquals("value", expected, attributes.getStringArray("value")); + assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull(); + assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(expected); + assertThat(attributes.getStringArray("value")).as("value").isEqualTo(expected); } @Test public void findMergedAnnotationAttributesOnInheritedAnnotationInterface() { AnnotationAttributes attributes = findMergedAnnotationAttributes(InheritedAnnotationInterface.class, Transactional.class); - assertNotNull("Should find @Transactional on InheritedAnnotationInterface", attributes); + assertThat(attributes).as("Should find @Transactional on InheritedAnnotationInterface").isNotNull(); } @Test public void findMergedAnnotationAttributesOnSubInheritedAnnotationInterface() { AnnotationAttributes attributes = findMergedAnnotationAttributes(SubInheritedAnnotationInterface.class, Transactional.class); - assertNotNull("Should find @Transactional on SubInheritedAnnotationInterface", attributes); + assertThat(attributes).as("Should find @Transactional on SubInheritedAnnotationInterface").isNotNull(); } @Test public void findMergedAnnotationAttributesOnSubSubInheritedAnnotationInterface() { AnnotationAttributes attributes = findMergedAnnotationAttributes(SubSubInheritedAnnotationInterface.class, Transactional.class); - assertNotNull("Should find @Transactional on SubSubInheritedAnnotationInterface", attributes); + assertThat(attributes).as("Should find @Transactional on SubSubInheritedAnnotationInterface").isNotNull(); } @Test public void findMergedAnnotationAttributesOnNonInheritedAnnotationInterface() { AnnotationAttributes attributes = findMergedAnnotationAttributes(NonInheritedAnnotationInterface.class, Order.class); - assertNotNull("Should find @Order on NonInheritedAnnotationInterface", attributes); + assertThat(attributes).as("Should find @Order on NonInheritedAnnotationInterface").isNotNull(); } @Test public void findMergedAnnotationAttributesOnSubNonInheritedAnnotationInterface() { AnnotationAttributes attributes = findMergedAnnotationAttributes(SubNonInheritedAnnotationInterface.class, Order.class); - assertNotNull("Should find @Order on SubNonInheritedAnnotationInterface", attributes); + assertThat(attributes).as("Should find @Order on SubNonInheritedAnnotationInterface").isNotNull(); } @Test public void findMergedAnnotationAttributesOnSubSubNonInheritedAnnotationInterface() { AnnotationAttributes attributes = findMergedAnnotationAttributes(SubSubNonInheritedAnnotationInterface.class, Order.class); - assertNotNull("Should find @Order on SubSubNonInheritedAnnotationInterface", attributes); + assertThat(attributes).as("Should find @Order on SubSubNonInheritedAnnotationInterface").isNotNull(); } @Test public void findMergedAnnotationAttributesInheritedFromInterfaceMethod() throws NoSuchMethodException { Method method = ConcreteClassWithInheritedAnnotation.class.getMethod("handleFromInterface"); AnnotationAttributes attributes = findMergedAnnotationAttributes(method, Order.class); - assertNotNull("Should find @Order on ConcreteClassWithInheritedAnnotation.handleFromInterface() method", attributes); + assertThat(attributes).as("Should find @Order on ConcreteClassWithInheritedAnnotation.handleFromInterface() method").isNotNull(); } @Test public void findMergedAnnotationAttributesInheritedFromAbstractMethod() throws NoSuchMethodException { Method method = ConcreteClassWithInheritedAnnotation.class.getMethod("handle"); AnnotationAttributes attributes = findMergedAnnotationAttributes(method, Transactional.class); - assertNotNull("Should find @Transactional on ConcreteClassWithInheritedAnnotation.handle() method", attributes); + assertThat(attributes).as("Should find @Transactional on ConcreteClassWithInheritedAnnotation.handle() method").isNotNull(); } @Test public void findMergedAnnotationAttributesInheritedFromBridgedMethod() throws NoSuchMethodException { Method method = ConcreteClassWithInheritedAnnotation.class.getMethod("handleParameterized", String.class); AnnotationAttributes attributes = findMergedAnnotationAttributes(method, Transactional.class); - assertNotNull("Should find @Transactional on bridged ConcreteClassWithInheritedAnnotation.handleParameterized()", attributes); + assertThat(attributes).as("Should find @Transactional on bridged ConcreteClassWithInheritedAnnotation.handleParameterized()").isNotNull(); } /** @@ -624,18 +616,19 @@ public class AnnotatedElementUtilsTests { } } } - assertTrue(bridgeMethod != null && bridgeMethod.isBridge()); - assertTrue(bridgedMethod != null && !bridgedMethod.isBridge()); + assertThat(bridgeMethod != null && bridgeMethod.isBridge()).isTrue(); + boolean condition = bridgedMethod != null && !bridgedMethod.isBridge(); + assertThat(condition).isTrue(); AnnotationAttributes attributes = findMergedAnnotationAttributes(bridgeMethod, Order.class); - assertNotNull("Should find @Order on StringGenericParameter.getFor() bridge method", attributes); + assertThat(attributes).as("Should find @Order on StringGenericParameter.getFor() bridge method").isNotNull(); } @Test public void findMergedAnnotationAttributesOnClassWithMetaAndLocalTxConfig() { AnnotationAttributes attributes = findMergedAnnotationAttributes(MetaAndLocalTxConfigClass.class, Transactional.class); - assertNotNull("Should find @Transactional on MetaAndLocalTxConfigClass", attributes); - assertEquals("TX qualifier for MetaAndLocalTxConfigClass.", "localTxMgr", attributes.getString("qualifier")); + assertThat(attributes).as("Should find @Transactional on MetaAndLocalTxConfigClass").isNotNull(); + assertThat(attributes.getString("qualifier")).as("TX qualifier for MetaAndLocalTxConfigClass.").isEqualTo("localTxMgr"); } @Test @@ -645,18 +638,18 @@ public class AnnotatedElementUtilsTests { // 1) Find and merge AnnotationAttributes from the annotation hierarchy AnnotationAttributes attributes = findMergedAnnotationAttributes( AliasedTransactionalComponentClass.class, AliasedTransactional.class); - assertNotNull("@AliasedTransactional on AliasedTransactionalComponentClass.", attributes); + assertThat(attributes).as("@AliasedTransactional on AliasedTransactionalComponentClass.").isNotNull(); // 2) Synthesize the AnnotationAttributes back into the target annotation AliasedTransactional annotation = AnnotationUtils.synthesizeAnnotation(attributes, AliasedTransactional.class, AliasedTransactionalComponentClass.class); - assertNotNull(annotation); + assertThat(annotation).isNotNull(); // 3) Verify that the AnnotationAttributes and synthesized annotation are equivalent - assertEquals("TX value via attributes.", qualifier, attributes.getString("value")); - assertEquals("TX value via synthesized annotation.", qualifier, annotation.value()); - assertEquals("TX qualifier via attributes.", qualifier, attributes.getString("qualifier")); - assertEquals("TX qualifier via synthesized annotation.", qualifier, annotation.qualifier()); + assertThat(attributes.getString("value")).as("TX value via attributes.").isEqualTo(qualifier); + assertThat(annotation.value()).as("TX value via synthesized annotation.").isEqualTo(qualifier); + assertThat(attributes.getString("qualifier")).as("TX qualifier via attributes.").isEqualTo(qualifier); + assertThat(annotation.qualifier()).as("TX qualifier via synthesized annotation.").isEqualTo(qualifier); } @Test @@ -664,10 +657,10 @@ public class AnnotatedElementUtilsTests { AnnotationAttributes attributes = assertComponentScanAttributes(TestComponentScanClass.class, "com.example.app.test"); Filter[] excludeFilters = attributes.getAnnotationArray("excludeFilters", Filter.class); - assertNotNull(excludeFilters); + assertThat(excludeFilters).isNotNull(); List patterns = stream(excludeFilters).map(Filter::pattern).collect(toList()); - assertEquals(asList("*Test", "*Tests"), patterns); + assertThat(patterns).isEqualTo(asList("*Test", "*Tests")); } /** @@ -693,9 +686,9 @@ public class AnnotatedElementUtilsTests { private AnnotationAttributes assertComponentScanAttributes(Class element, String... expected) { AnnotationAttributes attributes = findMergedAnnotationAttributes(element, ComponentScan.class); - assertNotNull("Should find @ComponentScan on " + element, attributes); - assertArrayEquals("value: ", expected, attributes.getStringArray("value")); - assertArrayEquals("basePackages: ", expected, attributes.getStringArray("basePackages")); + assertThat(attributes).as("Should find @ComponentScan on " + element).isNotNull(); + assertThat(attributes.getStringArray("value")).as("value: ").isEqualTo(expected); + assertThat(attributes.getStringArray("basePackages")).as("basePackages: ").isEqualTo(expected); return attributes; } @@ -708,9 +701,9 @@ public class AnnotatedElementUtilsTests { public void findMergedAnnotationWithAttributeAliasesInTargetAnnotation() { Class element = AliasedTransactionalComponentClass.class; AliasedTransactional annotation = findMergedAnnotation(element, AliasedTransactional.class); - assertNotNull("@AliasedTransactional on " + element, annotation); - assertEquals("TX value via synthesized annotation.", "aliasForQualifier", annotation.value()); - assertEquals("TX qualifier via synthesized annotation.", "aliasForQualifier", annotation.qualifier()); + assertThat(annotation).as("@AliasedTransactional on " + element).isNotNull(); + assertThat(annotation.value()).as("TX value via synthesized annotation.").isEqualTo("aliasForQualifier"); + assertThat(annotation.qualifier()).as("TX qualifier via synthesized annotation.").isEqualTo("aliasForQualifier"); } @Test @@ -721,20 +714,20 @@ public class AnnotatedElementUtilsTests { Class element = AliasedComposedContextConfigAndTestPropSourceClass.class; ContextConfig contextConfig = findMergedAnnotation(element, ContextConfig.class); - assertNotNull("@ContextConfig on " + element, contextConfig); - assertArrayEquals("locations", xmlLocations, contextConfig.locations()); - assertArrayEquals("value", xmlLocations, contextConfig.value()); + assertThat(contextConfig).as("@ContextConfig on " + element).isNotNull(); + assertThat(contextConfig.locations()).as("locations").isEqualTo(xmlLocations); + assertThat(contextConfig.value()).as("value").isEqualTo(xmlLocations); // Synthesized annotation TestPropSource testPropSource = AnnotationUtils.findAnnotation(element, TestPropSource.class); - assertArrayEquals("locations", propFiles, testPropSource.locations()); - assertArrayEquals("value", propFiles, testPropSource.value()); + assertThat(testPropSource.locations()).as("locations").isEqualTo(propFiles); + assertThat(testPropSource.value()).as("value").isEqualTo(propFiles); // Merged annotation testPropSource = findMergedAnnotation(element, TestPropSource.class); - assertNotNull("@TestPropSource on " + element, testPropSource); - assertArrayEquals("locations", propFiles, testPropSource.locations()); - assertArrayEquals("value", propFiles, testPropSource.value()); + assertThat(testPropSource).as("@TestPropSource on " + element).isNotNull(); + assertThat(testPropSource.locations()).as("locations").isEqualTo(propFiles); + assertThat(testPropSource.value()).as("value").isEqualTo(propFiles); } @Test @@ -743,11 +736,11 @@ public class AnnotatedElementUtilsTests { Class element = SpringAppConfigClass.class; ContextConfig contextConfig = findMergedAnnotation(element, ContextConfig.class); - assertNotNull("Should find @ContextConfig on " + element, contextConfig); - assertArrayEquals("locations for " + element, EMPTY, contextConfig.locations()); + assertThat(contextConfig).as("Should find @ContextConfig on " + element).isNotNull(); + assertThat(contextConfig.locations()).as("locations for " + element).isEqualTo(EMPTY); // 'value' in @SpringAppConfig should not override 'value' in @ContextConfig - assertArrayEquals("value for " + element, EMPTY, contextConfig.value()); - assertArrayEquals("classes for " + element, new Class[] {Number.class}, contextConfig.classes()); + assertThat(contextConfig.value()).as("value for " + element).isEqualTo(EMPTY); + assertThat(contextConfig.classes()).as("classes for " + element).isEqualTo(new Class[] {Number.class}); } @Test @@ -763,63 +756,57 @@ public class AnnotatedElementUtilsTests { private void assertWebMapping(AnnotatedElement element) throws ArrayComparisonFailure { WebMapping webMapping = findMergedAnnotation(element, WebMapping.class); - assertNotNull(webMapping); - assertArrayEquals("value attribute: ", asArray("/test"), webMapping.value()); - assertArrayEquals("path attribute: ", asArray("/test"), webMapping.path()); + assertThat(webMapping).isNotNull(); + assertThat(webMapping.value()).as("value attribute: ").isEqualTo(asArray("/test")); + assertThat(webMapping.path()).as("path attribute: ").isEqualTo(asArray("/test")); } @Test public void javaLangAnnotationTypeViaFindMergedAnnotation() throws Exception { Constructor deprecatedCtor = Date.class.getConstructor(String.class); - assertEquals(deprecatedCtor.getAnnotation(Deprecated.class), - findMergedAnnotation(deprecatedCtor, Deprecated.class)); - assertEquals(Date.class.getAnnotation(Deprecated.class), - findMergedAnnotation(Date.class, Deprecated.class)); + assertThat(findMergedAnnotation(deprecatedCtor, Deprecated.class)).isEqualTo(deprecatedCtor.getAnnotation(Deprecated.class)); + assertThat(findMergedAnnotation(Date.class, Deprecated.class)).isEqualTo(Date.class.getAnnotation(Deprecated.class)); } @Test public void javaxAnnotationTypeViaFindMergedAnnotation() throws Exception { - assertEquals(ResourceHolder.class.getAnnotation(Resource.class), - findMergedAnnotation(ResourceHolder.class, Resource.class)); - assertEquals(SpringAppConfigClass.class.getAnnotation(Resource.class), - findMergedAnnotation(SpringAppConfigClass.class, Resource.class)); + assertThat(findMergedAnnotation(ResourceHolder.class, Resource.class)).isEqualTo(ResourceHolder.class.getAnnotation(Resource.class)); + assertThat(findMergedAnnotation(SpringAppConfigClass.class, Resource.class)).isEqualTo(SpringAppConfigClass.class.getAnnotation(Resource.class)); } @Test public void nullableAnnotationTypeViaFindMergedAnnotation() throws Exception { Method method = TransactionalServiceImpl.class.getMethod("doIt"); - assertEquals(method.getAnnotation(Resource.class), - findMergedAnnotation(method, Resource.class)); - assertEquals(method.getAnnotation(Resource.class), - findMergedAnnotation(method, Resource.class)); + assertThat(findMergedAnnotation(method, Resource.class)).isEqualTo(method.getAnnotation(Resource.class)); + assertThat(findMergedAnnotation(method, Resource.class)).isEqualTo(method.getAnnotation(Resource.class)); } @Test public void getAllMergedAnnotationsOnClassWithInterface() throws Exception { Method method = TransactionalServiceImpl.class.getMethod("doIt"); Set allMergedAnnotations = getAllMergedAnnotations(method, Transactional.class); - assertTrue(allMergedAnnotations.isEmpty()); + assertThat(allMergedAnnotations.isEmpty()).isTrue(); } @Test public void findAllMergedAnnotationsOnClassWithInterface() throws Exception { Method method = TransactionalServiceImpl.class.getMethod("doIt"); Set allMergedAnnotations = findAllMergedAnnotations(method, Transactional.class); - assertEquals(1, allMergedAnnotations.size()); + assertThat(allMergedAnnotations.size()).isEqualTo(1); } @Test // SPR-16060 public void findMethodAnnotationFromGenericInterface() throws Exception { Method method = ImplementsInterfaceWithGenericAnnotatedMethod.class.getMethod("foo", String.class); Order order = findMergedAnnotation(method, Order.class); - assertNotNull(order); + assertThat(order).isNotNull(); } @Test // SPR-17146 public void findMethodAnnotationFromGenericSuperclass() throws Exception { Method method = ExtendsBaseClassWithGenericAnnotatedMethod.class.getMethod("foo", String.class); Order order = findMergedAnnotation(method, Order.class); - assertNotNull(order); + assertThat(order).isNotNull(); } @Test // gh-22655 diff --git a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAttributesTests.java b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAttributesTests.java index 58e250fcfa4..54d286cdcd1 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAttributesTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAttributesTests.java @@ -27,10 +27,6 @@ import org.springframework.core.annotation.AnnotationUtilsTests.ImplicitAliasesC import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link AnnotationAttributes}. @@ -67,7 +63,7 @@ public class AnnotationAttributesTests { assertThat(attributes.getBoolean("bool1")).isEqualTo(true); assertThat(attributes.getBoolean("bool2")).isEqualTo(false); assertThat(attributes.getEnum("color")).isEqualTo(Color.RED); - assertTrue(attributes.getClass("class").equals(Integer.class)); + assertThat(attributes.getClass("class").equals(Integer.class)).isTrue(); assertThat(attributes.getClassArray("classes")).isEqualTo(new Class[] {Number.class, Short.class, Integer.class}); assertThat(attributes.getNumber("number")).isEqualTo(42); assertThat(attributes.getAnnotation("anno").getNumber("value")).isEqualTo(10); @@ -101,12 +97,12 @@ public class AnnotationAttributesTests { assertThat(attributes.getClassArray("classes")).isEqualTo(new Class[] {Number.class}); AnnotationAttributes[] array = attributes.getAnnotationArray("nestedAttributes"); - assertNotNull(array); + assertThat(array).isNotNull(); assertThat(array.length).isEqualTo(1); assertThat(array[0].getString("name")).isEqualTo("Dilbert"); Filter[] filters = attributes.getAnnotationArray("filters", Filter.class); - assertNotNull(filters); + assertThat(filters).isNotNull(); assertThat(filters.length).isEqualTo(1); assertThat(filters[0].pattern()).isEqualTo("foo"); } @@ -123,8 +119,8 @@ public class AnnotationAttributesTests { assertThat(retrievedFilter.pattern()).isEqualTo("foo"); Filter[] retrievedFilters = attributes.getAnnotationArray("filters", Filter.class); - assertNotNull(retrievedFilters); - assertEquals(2, retrievedFilters.length); + assertThat(retrievedFilters).isNotNull(); + assertThat(retrievedFilters.length).isEqualTo(2); assertThat(retrievedFilters[1].pattern()).isEqualTo("foo"); } @@ -165,12 +161,12 @@ public class AnnotationAttributesTests { attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class); attributes.put("value", value); AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false); - aliases.stream().forEach(alias -> assertEquals(value, attributes.getString(alias))); + aliases.stream().forEach(alias -> assertThat(attributes.getString(alias)).isEqualTo(value)); attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class); attributes.put("location1", value); AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false); - aliases.stream().forEach(alias -> assertEquals(value, attributes.getString(alias))); + aliases.stream().forEach(alias -> assertThat(attributes.getString(alias)).isEqualTo(value)); attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class); attributes.put("value", value); @@ -178,7 +174,7 @@ public class AnnotationAttributesTests { attributes.put("xmlFile", value); attributes.put("groovyScript", value); AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false); - aliases.stream().forEach(alias -> assertEquals(value, attributes.getString(alias))); + aliases.stream().forEach(alias -> assertThat(attributes.getString(alias)).isEqualTo(value)); } @Test @@ -189,35 +185,35 @@ public class AnnotationAttributesTests { attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class); attributes.put("location1", value); AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false); - aliases.stream().forEach(alias -> assertArrayEquals(value, attributes.getStringArray(alias))); + aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(value)); attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class); attributes.put("value", value); AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false); - aliases.stream().forEach(alias -> assertArrayEquals(value, attributes.getStringArray(alias))); + aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(value)); attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class); attributes.put("location1", value); attributes.put("value", value); AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false); - aliases.stream().forEach(alias -> assertArrayEquals(value, attributes.getStringArray(alias))); + aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(value)); attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class); attributes.put("location1", value); AnnotationUtils.registerDefaultValues(attributes); AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false); - aliases.stream().forEach(alias -> assertArrayEquals(value, attributes.getStringArray(alias))); + aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(value)); attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class); attributes.put("value", value); AnnotationUtils.registerDefaultValues(attributes); AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false); - aliases.stream().forEach(alias -> assertArrayEquals(value, attributes.getStringArray(alias))); + aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(value)); attributes = new AnnotationAttributes(ImplicitAliasesContextConfig.class); AnnotationUtils.registerDefaultValues(attributes); AnnotationUtils.postProcessAnnotationAttributes(null, attributes, false); - aliases.stream().forEach(alias -> assertArrayEquals(new String[] {""}, attributes.getStringArray(alias))); + aliases.stream().forEach(alias -> assertThat(attributes.getStringArray(alias)).isEqualTo(new String[] {""})); } diff --git a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAwareOrderComparatorTests.java b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAwareOrderComparatorTests.java index 5d57dee95d0..ea674b82a3f 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAwareOrderComparatorTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAwareOrderComparatorTests.java @@ -23,9 +23,6 @@ import javax.annotation.Priority; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -44,8 +41,8 @@ public class AnnotationAwareOrderComparatorTests { list.add(new B()); list.add(new A()); AnnotationAwareOrderComparator.sort(list); - assertTrue(list.get(0) instanceof A); - assertTrue(list.get(1) instanceof B); + assertThat(list.get(0) instanceof A).isTrue(); + assertThat(list.get(1) instanceof B).isTrue(); } @Test @@ -54,8 +51,8 @@ public class AnnotationAwareOrderComparatorTests { list.add(new B2()); list.add(new A2()); AnnotationAwareOrderComparator.sort(list); - assertTrue(list.get(0) instanceof A2); - assertTrue(list.get(1) instanceof B2); + assertThat(list.get(0) instanceof A2).isTrue(); + assertThat(list.get(1) instanceof B2).isTrue(); } @Test @@ -64,8 +61,8 @@ public class AnnotationAwareOrderComparatorTests { list.add(new B()); list.add(new A2()); AnnotationAwareOrderComparator.sort(list); - assertTrue(list.get(0) instanceof A2); - assertTrue(list.get(1) instanceof B); + assertThat(list.get(0) instanceof A2).isTrue(); + assertThat(list.get(1) instanceof B).isTrue(); } @Test @@ -74,8 +71,8 @@ public class AnnotationAwareOrderComparatorTests { list.add(new B()); list.add(new C()); AnnotationAwareOrderComparator.sort(list); - assertTrue(list.get(0) instanceof C); - assertTrue(list.get(1) instanceof B); + assertThat(list.get(0) instanceof C).isTrue(); + assertThat(list.get(1) instanceof B).isTrue(); } @Test @@ -84,8 +81,8 @@ public class AnnotationAwareOrderComparatorTests { list.add(B.class); list.add(A.class); AnnotationAwareOrderComparator.sort(list); - assertEquals(A.class, list.get(0)); - assertEquals(B.class, list.get(1)); + assertThat(list.get(0)).isEqualTo(A.class); + assertThat(list.get(1)).isEqualTo(B.class); } @Test @@ -94,8 +91,8 @@ public class AnnotationAwareOrderComparatorTests { list.add(B.class); list.add(C.class); AnnotationAwareOrderComparator.sort(list); - assertEquals(C.class, list.get(0)); - assertEquals(B.class, list.get(1)); + assertThat(list.get(0)).isEqualTo(C.class); + assertThat(list.get(1)).isEqualTo(B.class); } @Test @@ -106,10 +103,10 @@ public class AnnotationAwareOrderComparatorTests { list.add(null); list.add(A.class); AnnotationAwareOrderComparator.sort(list); - assertEquals(A.class, list.get(0)); - assertEquals(B.class, list.get(1)); - assertNull(list.get(2)); - assertNull(list.get(3)); + assertThat(list.get(0)).isEqualTo(A.class); + assertThat(list.get(1)).isEqualTo(B.class); + assertThat(list.get(2)).isNull(); + assertThat(list.get(3)).isNull(); } diff --git a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java index 27c9142d061..f7f54ad651c 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java @@ -46,13 +46,6 @@ import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.springframework.core.annotation.AnnotationUtils.VALUE; import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; import static org.springframework.core.annotation.AnnotationUtils.findAnnotationDeclaringClass; @@ -90,9 +83,9 @@ public class AnnotationUtilsTests { @Test public void findMethodAnnotationOnLeaf() throws Exception { Method m = Leaf.class.getMethod("annotatedOnLeaf"); - assertNotNull(m.getAnnotation(Order.class)); - assertNotNull(getAnnotation(m, Order.class)); - assertNotNull(findAnnotation(m, Order.class)); + assertThat(m.getAnnotation(Order.class)).isNotNull(); + assertThat(getAnnotation(m, Order.class)).isNotNull(); + assertThat(findAnnotation(m, Order.class)).isNotNull(); } // @since 4.2 @@ -100,70 +93,70 @@ public class AnnotationUtilsTests { public void findMethodAnnotationWithAnnotationOnMethodInInterface() throws Exception { Method m = Leaf.class.getMethod("fromInterfaceImplementedByRoot"); // @Order is not @Inherited - assertNull(m.getAnnotation(Order.class)); + assertThat(m.getAnnotation(Order.class)).isNull(); // getAnnotation() does not search on interfaces - assertNull(getAnnotation(m, Order.class)); + assertThat(getAnnotation(m, Order.class)).isNull(); // findAnnotation() does search on interfaces - assertNotNull(findAnnotation(m, Order.class)); + assertThat(findAnnotation(m, Order.class)).isNotNull(); } // @since 4.2 @Test public void findMethodAnnotationWithMetaAnnotationOnLeaf() throws Exception { Method m = Leaf.class.getMethod("metaAnnotatedOnLeaf"); - assertNull(m.getAnnotation(Order.class)); - assertNotNull(getAnnotation(m, Order.class)); - assertNotNull(findAnnotation(m, Order.class)); + assertThat(m.getAnnotation(Order.class)).isNull(); + assertThat(getAnnotation(m, Order.class)).isNotNull(); + assertThat(findAnnotation(m, Order.class)).isNotNull(); } // @since 4.2 @Test public void findMethodAnnotationWithMetaMetaAnnotationOnLeaf() throws Exception { Method m = Leaf.class.getMethod("metaMetaAnnotatedOnLeaf"); - assertNull(m.getAnnotation(Component.class)); - assertNull(getAnnotation(m, Component.class)); - assertNotNull(findAnnotation(m, Component.class)); + assertThat(m.getAnnotation(Component.class)).isNull(); + assertThat(getAnnotation(m, Component.class)).isNull(); + assertThat(findAnnotation(m, Component.class)).isNotNull(); } @Test public void findMethodAnnotationOnRoot() throws Exception { Method m = Leaf.class.getMethod("annotatedOnRoot"); - assertNotNull(m.getAnnotation(Order.class)); - assertNotNull(getAnnotation(m, Order.class)); - assertNotNull(findAnnotation(m, Order.class)); + assertThat(m.getAnnotation(Order.class)).isNotNull(); + assertThat(getAnnotation(m, Order.class)).isNotNull(); + assertThat(findAnnotation(m, Order.class)).isNotNull(); } // @since 4.2 @Test public void findMethodAnnotationWithMetaAnnotationOnRoot() throws Exception { Method m = Leaf.class.getMethod("metaAnnotatedOnRoot"); - assertNull(m.getAnnotation(Order.class)); - assertNotNull(getAnnotation(m, Order.class)); - assertNotNull(findAnnotation(m, Order.class)); + assertThat(m.getAnnotation(Order.class)).isNull(); + assertThat(getAnnotation(m, Order.class)).isNotNull(); + assertThat(findAnnotation(m, Order.class)).isNotNull(); } @Test public void findMethodAnnotationOnRootButOverridden() throws Exception { Method m = Leaf.class.getMethod("overrideWithoutNewAnnotation"); - assertNull(m.getAnnotation(Order.class)); - assertNull(getAnnotation(m, Order.class)); - assertNotNull(findAnnotation(m, Order.class)); + assertThat(m.getAnnotation(Order.class)).isNull(); + assertThat(getAnnotation(m, Order.class)).isNull(); + assertThat(findAnnotation(m, Order.class)).isNotNull(); } @Test public void findMethodAnnotationNotAnnotated() throws Exception { Method m = Leaf.class.getMethod("notAnnotated"); - assertNull(findAnnotation(m, Order.class)); + assertThat(findAnnotation(m, Order.class)).isNull(); } @Test public void findMethodAnnotationOnBridgeMethod() throws Exception { Method bridgeMethod = SimpleFoo.class.getMethod("something", Object.class); - assertTrue(bridgeMethod.isBridge()); + assertThat(bridgeMethod.isBridge()).isTrue(); - assertNull(bridgeMethod.getAnnotation(Order.class)); - assertNull(getAnnotation(bridgeMethod, Order.class)); - assertNotNull(findAnnotation(bridgeMethod, Order.class)); + assertThat(bridgeMethod.getAnnotation(Order.class)).isNull(); + assertThat(getAnnotation(bridgeMethod, Order.class)).isNull(); + assertThat(findAnnotation(bridgeMethod, Order.class)).isNotNull(); boolean runningInEclipse = Arrays.stream(new Exception().getStackTrace()) .anyMatch(element -> element.getClassName().startsWith("org.eclipse.jdt")); @@ -177,206 +170,194 @@ public class AnnotationUtilsTests { // [2] https://bugs.eclipse.org/bugs/show_bug.cgi?id=495396 // if (!runningInEclipse) { - assertNotNull(bridgeMethod.getAnnotation(Transactional.class)); + assertThat(bridgeMethod.getAnnotation(Transactional.class)).isNotNull(); } - assertNotNull(getAnnotation(bridgeMethod, Transactional.class)); - assertNotNull(findAnnotation(bridgeMethod, Transactional.class)); + assertThat(getAnnotation(bridgeMethod, Transactional.class)).isNotNull(); + assertThat(findAnnotation(bridgeMethod, Transactional.class)).isNotNull(); } @Test public void findMethodAnnotationOnBridgedMethod() throws Exception { Method bridgedMethod = SimpleFoo.class.getMethod("something", String.class); - assertFalse(bridgedMethod.isBridge()); + assertThat(bridgedMethod.isBridge()).isFalse(); - assertNull(bridgedMethod.getAnnotation(Order.class)); - assertNull(getAnnotation(bridgedMethod, Order.class)); - assertNotNull(findAnnotation(bridgedMethod, Order.class)); + assertThat(bridgedMethod.getAnnotation(Order.class)).isNull(); + assertThat(getAnnotation(bridgedMethod, Order.class)).isNull(); + assertThat(findAnnotation(bridgedMethod, Order.class)).isNotNull(); - assertNotNull(bridgedMethod.getAnnotation(Transactional.class)); - assertNotNull(getAnnotation(bridgedMethod, Transactional.class)); - assertNotNull(findAnnotation(bridgedMethod, Transactional.class)); + assertThat(bridgedMethod.getAnnotation(Transactional.class)).isNotNull(); + assertThat(getAnnotation(bridgedMethod, Transactional.class)).isNotNull(); + assertThat(findAnnotation(bridgedMethod, Transactional.class)).isNotNull(); } @Test public void findMethodAnnotationFromInterface() throws Exception { Method method = ImplementsInterfaceWithAnnotatedMethod.class.getMethod("foo"); Order order = findAnnotation(method, Order.class); - assertNotNull(order); + assertThat(order).isNotNull(); } @Test // SPR-16060 public void findMethodAnnotationFromGenericInterface() throws Exception { Method method = ImplementsInterfaceWithGenericAnnotatedMethod.class.getMethod("foo", String.class); Order order = findAnnotation(method, Order.class); - assertNotNull(order); + assertThat(order).isNotNull(); } @Test // SPR-17146 public void findMethodAnnotationFromGenericSuperclass() throws Exception { Method method = ExtendsBaseClassWithGenericAnnotatedMethod.class.getMethod("foo", String.class); Order order = findAnnotation(method, Order.class); - assertNotNull(order); + assertThat(order).isNotNull(); } @Test public void findMethodAnnotationFromInterfaceOnSuper() throws Exception { Method method = SubOfImplementsInterfaceWithAnnotatedMethod.class.getMethod("foo"); Order order = findAnnotation(method, Order.class); - assertNotNull(order); + assertThat(order).isNotNull(); } @Test public void findMethodAnnotationFromInterfaceWhenSuperDoesNotImplementMethod() throws Exception { Method method = SubOfAbstractImplementsInterfaceWithAnnotatedMethod.class.getMethod("foo"); Order order = findAnnotation(method, Order.class); - assertNotNull(order); + assertThat(order).isNotNull(); } // @since 4.1.2 @Test public void findClassAnnotationFavorsMoreLocallyDeclaredComposedAnnotationsOverAnnotationsOnInterfaces() { Component component = findAnnotation(ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface.class, Component.class); - assertNotNull(component); - assertEquals("meta2", component.value()); + assertThat(component).isNotNull(); + assertThat(component.value()).isEqualTo("meta2"); } // @since 4.0.3 @Test public void findClassAnnotationFavorsMoreLocallyDeclaredComposedAnnotationsOverInheritedAnnotations() { Transactional transactional = findAnnotation(SubSubClassWithInheritedAnnotation.class, Transactional.class); - assertNotNull(transactional); - assertTrue("readOnly flag for SubSubClassWithInheritedAnnotation", transactional.readOnly()); + assertThat(transactional).isNotNull(); + assertThat(transactional.readOnly()).as("readOnly flag for SubSubClassWithInheritedAnnotation").isTrue(); } // @since 4.0.3 @Test public void findClassAnnotationFavorsMoreLocallyDeclaredComposedAnnotationsOverInheritedComposedAnnotations() { Component component = findAnnotation(SubSubClassWithInheritedMetaAnnotation.class, Component.class); - assertNotNull(component); - assertEquals("meta2", component.value()); + assertThat(component).isNotNull(); + assertThat(component.value()).isEqualTo("meta2"); } @Test public void findClassAnnotationOnMetaMetaAnnotatedClass() { Component component = findAnnotation(MetaMetaAnnotatedClass.class, Component.class); - assertNotNull("Should find meta-annotation on composed annotation on class", component); - assertEquals("meta2", component.value()); + assertThat(component).as("Should find meta-annotation on composed annotation on class").isNotNull(); + assertThat(component.value()).isEqualTo("meta2"); } @Test public void findClassAnnotationOnMetaMetaMetaAnnotatedClass() { Component component = findAnnotation(MetaMetaMetaAnnotatedClass.class, Component.class); - assertNotNull("Should find meta-annotation on meta-annotation on composed annotation on class", component); - assertEquals("meta2", component.value()); + assertThat(component).as("Should find meta-annotation on meta-annotation on composed annotation on class").isNotNull(); + assertThat(component.value()).isEqualTo("meta2"); } @Test public void findClassAnnotationOnAnnotatedClassWithMissingTargetMetaAnnotation() { // TransactionalClass is NOT annotated or meta-annotated with @Component Component component = findAnnotation(TransactionalClass.class, Component.class); - assertNull("Should not find @Component on TransactionalClass", component); + assertThat(component).as("Should not find @Component on TransactionalClass").isNull(); } @Test public void findClassAnnotationOnMetaCycleAnnotatedClassWithMissingTargetMetaAnnotation() { Component component = findAnnotation(MetaCycleAnnotatedClass.class, Component.class); - assertNull("Should not find @Component on MetaCycleAnnotatedClass", component); + assertThat(component).as("Should not find @Component on MetaCycleAnnotatedClass").isNull(); } // @since 4.2 @Test public void findClassAnnotationOnInheritedAnnotationInterface() { Transactional tx = findAnnotation(InheritedAnnotationInterface.class, Transactional.class); - assertNotNull("Should find @Transactional on InheritedAnnotationInterface", tx); + assertThat(tx).as("Should find @Transactional on InheritedAnnotationInterface").isNotNull(); } // @since 4.2 @Test public void findClassAnnotationOnSubInheritedAnnotationInterface() { Transactional tx = findAnnotation(SubInheritedAnnotationInterface.class, Transactional.class); - assertNotNull("Should find @Transactional on SubInheritedAnnotationInterface", tx); + assertThat(tx).as("Should find @Transactional on SubInheritedAnnotationInterface").isNotNull(); } // @since 4.2 @Test public void findClassAnnotationOnSubSubInheritedAnnotationInterface() { Transactional tx = findAnnotation(SubSubInheritedAnnotationInterface.class, Transactional.class); - assertNotNull("Should find @Transactional on SubSubInheritedAnnotationInterface", tx); + assertThat(tx).as("Should find @Transactional on SubSubInheritedAnnotationInterface").isNotNull(); } // @since 4.2 @Test public void findClassAnnotationOnNonInheritedAnnotationInterface() { Order order = findAnnotation(NonInheritedAnnotationInterface.class, Order.class); - assertNotNull("Should find @Order on NonInheritedAnnotationInterface", order); + assertThat(order).as("Should find @Order on NonInheritedAnnotationInterface").isNotNull(); } // @since 4.2 @Test public void findClassAnnotationOnSubNonInheritedAnnotationInterface() { Order order = findAnnotation(SubNonInheritedAnnotationInterface.class, Order.class); - assertNotNull("Should find @Order on SubNonInheritedAnnotationInterface", order); + assertThat(order).as("Should find @Order on SubNonInheritedAnnotationInterface").isNotNull(); } // @since 4.2 @Test public void findClassAnnotationOnSubSubNonInheritedAnnotationInterface() { Order order = findAnnotation(SubSubNonInheritedAnnotationInterface.class, Order.class); - assertNotNull("Should find @Order on SubSubNonInheritedAnnotationInterface", order); + assertThat(order).as("Should find @Order on SubSubNonInheritedAnnotationInterface").isNotNull(); } @Test public void findAnnotationDeclaringClassForAllScenarios() { // no class-level annotation - assertNull(findAnnotationDeclaringClass(Transactional.class, NonAnnotatedInterface.class)); - assertNull(findAnnotationDeclaringClass(Transactional.class, NonAnnotatedClass.class)); + assertThat((Object) findAnnotationDeclaringClass(Transactional.class, NonAnnotatedInterface.class)).isNull(); + assertThat((Object) findAnnotationDeclaringClass(Transactional.class, NonAnnotatedClass.class)).isNull(); // inherited class-level annotation; note: @Transactional is inherited - assertEquals(InheritedAnnotationInterface.class, - findAnnotationDeclaringClass(Transactional.class, InheritedAnnotationInterface.class)); - assertNull(findAnnotationDeclaringClass(Transactional.class, SubInheritedAnnotationInterface.class)); - assertEquals(InheritedAnnotationClass.class, - findAnnotationDeclaringClass(Transactional.class, InheritedAnnotationClass.class)); - assertEquals(InheritedAnnotationClass.class, - findAnnotationDeclaringClass(Transactional.class, SubInheritedAnnotationClass.class)); + assertThat(findAnnotationDeclaringClass(Transactional.class, InheritedAnnotationInterface.class)).isEqualTo(InheritedAnnotationInterface.class); + assertThat(findAnnotationDeclaringClass(Transactional.class, SubInheritedAnnotationInterface.class)).isNull(); + assertThat(findAnnotationDeclaringClass(Transactional.class, InheritedAnnotationClass.class)).isEqualTo(InheritedAnnotationClass.class); + assertThat(findAnnotationDeclaringClass(Transactional.class, SubInheritedAnnotationClass.class)).isEqualTo(InheritedAnnotationClass.class); // non-inherited class-level annotation; note: @Order is not inherited, // but findAnnotationDeclaringClass() should still find it on classes. - assertEquals(NonInheritedAnnotationInterface.class, - findAnnotationDeclaringClass(Order.class, NonInheritedAnnotationInterface.class)); - assertNull(findAnnotationDeclaringClass(Order.class, SubNonInheritedAnnotationInterface.class)); - assertEquals(NonInheritedAnnotationClass.class, - findAnnotationDeclaringClass(Order.class, NonInheritedAnnotationClass.class)); - assertEquals(NonInheritedAnnotationClass.class, - findAnnotationDeclaringClass(Order.class, SubNonInheritedAnnotationClass.class)); + assertThat(findAnnotationDeclaringClass(Order.class, NonInheritedAnnotationInterface.class)).isEqualTo(NonInheritedAnnotationInterface.class); + assertThat(findAnnotationDeclaringClass(Order.class, SubNonInheritedAnnotationInterface.class)).isNull(); + assertThat(findAnnotationDeclaringClass(Order.class, NonInheritedAnnotationClass.class)).isEqualTo(NonInheritedAnnotationClass.class); + assertThat(findAnnotationDeclaringClass(Order.class, SubNonInheritedAnnotationClass.class)).isEqualTo(NonInheritedAnnotationClass.class); } @Test public void findAnnotationDeclaringClassForTypesWithSingleCandidateType() { // no class-level annotation List> transactionalCandidateList = Collections.singletonList(Transactional.class); - assertNull(findAnnotationDeclaringClassForTypes(transactionalCandidateList, NonAnnotatedInterface.class)); - assertNull(findAnnotationDeclaringClassForTypes(transactionalCandidateList, NonAnnotatedClass.class)); + assertThat((Object) findAnnotationDeclaringClassForTypes(transactionalCandidateList, NonAnnotatedInterface.class)).isNull(); + assertThat((Object) findAnnotationDeclaringClassForTypes(transactionalCandidateList, NonAnnotatedClass.class)).isNull(); // inherited class-level annotation; note: @Transactional is inherited - assertEquals(InheritedAnnotationInterface.class, - findAnnotationDeclaringClassForTypes(transactionalCandidateList, InheritedAnnotationInterface.class)); - assertNull(findAnnotationDeclaringClassForTypes(transactionalCandidateList, SubInheritedAnnotationInterface.class)); - assertEquals(InheritedAnnotationClass.class, - findAnnotationDeclaringClassForTypes(transactionalCandidateList, InheritedAnnotationClass.class)); - assertEquals(InheritedAnnotationClass.class, - findAnnotationDeclaringClassForTypes(transactionalCandidateList, SubInheritedAnnotationClass.class)); + assertThat(findAnnotationDeclaringClassForTypes(transactionalCandidateList, InheritedAnnotationInterface.class)).isEqualTo(InheritedAnnotationInterface.class); + assertThat(findAnnotationDeclaringClassForTypes(transactionalCandidateList, SubInheritedAnnotationInterface.class)).isNull(); + assertThat(findAnnotationDeclaringClassForTypes(transactionalCandidateList, InheritedAnnotationClass.class)).isEqualTo(InheritedAnnotationClass.class); + assertThat(findAnnotationDeclaringClassForTypes(transactionalCandidateList, SubInheritedAnnotationClass.class)).isEqualTo(InheritedAnnotationClass.class); // non-inherited class-level annotation; note: @Order is not inherited, // but findAnnotationDeclaringClassForTypes() should still find it on classes. List> orderCandidateList = Collections.singletonList(Order.class); - assertEquals(NonInheritedAnnotationInterface.class, - findAnnotationDeclaringClassForTypes(orderCandidateList, NonInheritedAnnotationInterface.class)); - assertNull(findAnnotationDeclaringClassForTypes(orderCandidateList, SubNonInheritedAnnotationInterface.class)); - assertEquals(NonInheritedAnnotationClass.class, - findAnnotationDeclaringClassForTypes(orderCandidateList, NonInheritedAnnotationClass.class)); - assertEquals(NonInheritedAnnotationClass.class, - findAnnotationDeclaringClassForTypes(orderCandidateList, SubNonInheritedAnnotationClass.class)); + assertThat(findAnnotationDeclaringClassForTypes(orderCandidateList, NonInheritedAnnotationInterface.class)).isEqualTo(NonInheritedAnnotationInterface.class); + assertThat(findAnnotationDeclaringClassForTypes(orderCandidateList, SubNonInheritedAnnotationInterface.class)).isNull(); + assertThat(findAnnotationDeclaringClassForTypes(orderCandidateList, NonInheritedAnnotationClass.class)).isEqualTo(NonInheritedAnnotationClass.class); + assertThat(findAnnotationDeclaringClassForTypes(orderCandidateList, SubNonInheritedAnnotationClass.class)).isEqualTo(NonInheritedAnnotationClass.class); } @Test @@ -384,110 +365,101 @@ public class AnnotationUtilsTests { List> candidates = asList(Transactional.class, Order.class); // no class-level annotation - assertNull(findAnnotationDeclaringClassForTypes(candidates, NonAnnotatedInterface.class)); - assertNull(findAnnotationDeclaringClassForTypes(candidates, NonAnnotatedClass.class)); + assertThat((Object) findAnnotationDeclaringClassForTypes(candidates, NonAnnotatedInterface.class)).isNull(); + assertThat((Object) findAnnotationDeclaringClassForTypes(candidates, NonAnnotatedClass.class)).isNull(); // inherited class-level annotation; note: @Transactional is inherited - assertEquals(InheritedAnnotationInterface.class, - findAnnotationDeclaringClassForTypes(candidates, InheritedAnnotationInterface.class)); - assertNull(findAnnotationDeclaringClassForTypes(candidates, SubInheritedAnnotationInterface.class)); - assertEquals(InheritedAnnotationClass.class, - findAnnotationDeclaringClassForTypes(candidates, InheritedAnnotationClass.class)); - assertEquals(InheritedAnnotationClass.class, - findAnnotationDeclaringClassForTypes(candidates, SubInheritedAnnotationClass.class)); + assertThat(findAnnotationDeclaringClassForTypes(candidates, InheritedAnnotationInterface.class)).isEqualTo(InheritedAnnotationInterface.class); + assertThat(findAnnotationDeclaringClassForTypes(candidates, SubInheritedAnnotationInterface.class)).isNull(); + assertThat(findAnnotationDeclaringClassForTypes(candidates, InheritedAnnotationClass.class)).isEqualTo(InheritedAnnotationClass.class); + assertThat(findAnnotationDeclaringClassForTypes(candidates, SubInheritedAnnotationClass.class)).isEqualTo(InheritedAnnotationClass.class); // non-inherited class-level annotation; note: @Order is not inherited, // but findAnnotationDeclaringClassForTypes() should still find it on classes. - assertEquals(NonInheritedAnnotationInterface.class, - findAnnotationDeclaringClassForTypes(candidates, NonInheritedAnnotationInterface.class)); - assertNull(findAnnotationDeclaringClassForTypes(candidates, SubNonInheritedAnnotationInterface.class)); - assertEquals(NonInheritedAnnotationClass.class, - findAnnotationDeclaringClassForTypes(candidates, NonInheritedAnnotationClass.class)); - assertEquals(NonInheritedAnnotationClass.class, - findAnnotationDeclaringClassForTypes(candidates, SubNonInheritedAnnotationClass.class)); + assertThat(findAnnotationDeclaringClassForTypes(candidates, NonInheritedAnnotationInterface.class)).isEqualTo(NonInheritedAnnotationInterface.class); + assertThat(findAnnotationDeclaringClassForTypes(candidates, SubNonInheritedAnnotationInterface.class)).isNull(); + assertThat(findAnnotationDeclaringClassForTypes(candidates, NonInheritedAnnotationClass.class)).isEqualTo(NonInheritedAnnotationClass.class); + assertThat(findAnnotationDeclaringClassForTypes(candidates, SubNonInheritedAnnotationClass.class)).isEqualTo(NonInheritedAnnotationClass.class); // class hierarchy mixed with @Transactional and @Order declarations - assertEquals(TransactionalClass.class, - findAnnotationDeclaringClassForTypes(candidates, TransactionalClass.class)); - assertEquals(TransactionalAndOrderedClass.class, - findAnnotationDeclaringClassForTypes(candidates, TransactionalAndOrderedClass.class)); - assertEquals(TransactionalAndOrderedClass.class, - findAnnotationDeclaringClassForTypes(candidates, SubTransactionalAndOrderedClass.class)); + assertThat(findAnnotationDeclaringClassForTypes(candidates, TransactionalClass.class)).isEqualTo(TransactionalClass.class); + assertThat(findAnnotationDeclaringClassForTypes(candidates, TransactionalAndOrderedClass.class)).isEqualTo(TransactionalAndOrderedClass.class); + assertThat(findAnnotationDeclaringClassForTypes(candidates, SubTransactionalAndOrderedClass.class)).isEqualTo(TransactionalAndOrderedClass.class); } @Test public void isAnnotationDeclaredLocallyForAllScenarios() { // no class-level annotation - assertFalse(isAnnotationDeclaredLocally(Transactional.class, NonAnnotatedInterface.class)); - assertFalse(isAnnotationDeclaredLocally(Transactional.class, NonAnnotatedClass.class)); + assertThat(isAnnotationDeclaredLocally(Transactional.class, NonAnnotatedInterface.class)).isFalse(); + assertThat(isAnnotationDeclaredLocally(Transactional.class, NonAnnotatedClass.class)).isFalse(); // inherited class-level annotation; note: @Transactional is inherited - assertTrue(isAnnotationDeclaredLocally(Transactional.class, InheritedAnnotationInterface.class)); - assertFalse(isAnnotationDeclaredLocally(Transactional.class, SubInheritedAnnotationInterface.class)); - assertTrue(isAnnotationDeclaredLocally(Transactional.class, InheritedAnnotationClass.class)); - assertFalse(isAnnotationDeclaredLocally(Transactional.class, SubInheritedAnnotationClass.class)); + assertThat(isAnnotationDeclaredLocally(Transactional.class, InheritedAnnotationInterface.class)).isTrue(); + assertThat(isAnnotationDeclaredLocally(Transactional.class, SubInheritedAnnotationInterface.class)).isFalse(); + assertThat(isAnnotationDeclaredLocally(Transactional.class, InheritedAnnotationClass.class)).isTrue(); + assertThat(isAnnotationDeclaredLocally(Transactional.class, SubInheritedAnnotationClass.class)).isFalse(); // non-inherited class-level annotation; note: @Order is not inherited - assertTrue(isAnnotationDeclaredLocally(Order.class, NonInheritedAnnotationInterface.class)); - assertFalse(isAnnotationDeclaredLocally(Order.class, SubNonInheritedAnnotationInterface.class)); - assertTrue(isAnnotationDeclaredLocally(Order.class, NonInheritedAnnotationClass.class)); - assertFalse(isAnnotationDeclaredLocally(Order.class, SubNonInheritedAnnotationClass.class)); + assertThat(isAnnotationDeclaredLocally(Order.class, NonInheritedAnnotationInterface.class)).isTrue(); + assertThat(isAnnotationDeclaredLocally(Order.class, SubNonInheritedAnnotationInterface.class)).isFalse(); + assertThat(isAnnotationDeclaredLocally(Order.class, NonInheritedAnnotationClass.class)).isTrue(); + assertThat(isAnnotationDeclaredLocally(Order.class, SubNonInheritedAnnotationClass.class)).isFalse(); } @Test public void isAnnotationInheritedForAllScenarios() { // no class-level annotation - assertFalse(isAnnotationInherited(Transactional.class, NonAnnotatedInterface.class)); - assertFalse(isAnnotationInherited(Transactional.class, NonAnnotatedClass.class)); + assertThat(isAnnotationInherited(Transactional.class, NonAnnotatedInterface.class)).isFalse(); + assertThat(isAnnotationInherited(Transactional.class, NonAnnotatedClass.class)).isFalse(); // inherited class-level annotation; note: @Transactional is inherited - assertFalse(isAnnotationInherited(Transactional.class, InheritedAnnotationInterface.class)); + assertThat(isAnnotationInherited(Transactional.class, InheritedAnnotationInterface.class)).isFalse(); // isAnnotationInherited() does not currently traverse interface hierarchies. // Thus the following, though perhaps counter intuitive, must be false: - assertFalse(isAnnotationInherited(Transactional.class, SubInheritedAnnotationInterface.class)); - assertFalse(isAnnotationInherited(Transactional.class, InheritedAnnotationClass.class)); - assertTrue(isAnnotationInherited(Transactional.class, SubInheritedAnnotationClass.class)); + assertThat(isAnnotationInherited(Transactional.class, SubInheritedAnnotationInterface.class)).isFalse(); + assertThat(isAnnotationInherited(Transactional.class, InheritedAnnotationClass.class)).isFalse(); + assertThat(isAnnotationInherited(Transactional.class, SubInheritedAnnotationClass.class)).isTrue(); // non-inherited class-level annotation; note: @Order is not inherited - assertFalse(isAnnotationInherited(Order.class, NonInheritedAnnotationInterface.class)); - assertFalse(isAnnotationInherited(Order.class, SubNonInheritedAnnotationInterface.class)); - assertFalse(isAnnotationInherited(Order.class, NonInheritedAnnotationClass.class)); - assertFalse(isAnnotationInherited(Order.class, SubNonInheritedAnnotationClass.class)); + assertThat(isAnnotationInherited(Order.class, NonInheritedAnnotationInterface.class)).isFalse(); + assertThat(isAnnotationInherited(Order.class, SubNonInheritedAnnotationInterface.class)).isFalse(); + assertThat(isAnnotationInherited(Order.class, NonInheritedAnnotationClass.class)).isFalse(); + assertThat(isAnnotationInherited(Order.class, SubNonInheritedAnnotationClass.class)).isFalse(); } @Test public void isAnnotationMetaPresentForPlainType() { - assertTrue(isAnnotationMetaPresent(Order.class, Documented.class)); - assertTrue(isAnnotationMetaPresent(NonNullApi.class, Documented.class)); - assertTrue(isAnnotationMetaPresent(NonNullApi.class, Nonnull.class)); - assertTrue(isAnnotationMetaPresent(ParametersAreNonnullByDefault.class, Nonnull.class)); + assertThat(isAnnotationMetaPresent(Order.class, Documented.class)).isTrue(); + assertThat(isAnnotationMetaPresent(NonNullApi.class, Documented.class)).isTrue(); + assertThat(isAnnotationMetaPresent(NonNullApi.class, Nonnull.class)).isTrue(); + assertThat(isAnnotationMetaPresent(ParametersAreNonnullByDefault.class, Nonnull.class)).isTrue(); } @Test public void getAnnotationAttributesWithoutAttributeAliases() { Component component = WebController.class.getAnnotation(Component.class); - assertNotNull(component); + assertThat(component).isNotNull(); AnnotationAttributes attributes = (AnnotationAttributes) getAnnotationAttributes(component); - assertNotNull(attributes); - assertEquals("value attribute: ", "webController", attributes.getString(VALUE)); - assertEquals(Component.class, attributes.annotationType()); + assertThat(attributes).isNotNull(); + assertThat(attributes.getString(VALUE)).as("value attribute: ").isEqualTo("webController"); + assertThat(attributes.annotationType()).isEqualTo(Component.class); } @Test public void getAnnotationAttributesWithNestedAnnotations() { ComponentScan componentScan = ComponentScanClass.class.getAnnotation(ComponentScan.class); - assertNotNull(componentScan); + assertThat(componentScan).isNotNull(); AnnotationAttributes attributes = getAnnotationAttributes(ComponentScanClass.class, componentScan); - assertNotNull(attributes); - assertEquals(ComponentScan.class, attributes.annotationType()); + assertThat(attributes).isNotNull(); + assertThat(attributes.annotationType()).isEqualTo(ComponentScan.class); Filter[] filters = attributes.getAnnotationArray("excludeFilters", Filter.class); - assertNotNull(filters); + assertThat(filters).isNotNull(); List patterns = stream(filters).map(Filter::pattern).collect(toList()); - assertEquals(asList("*Foo", "*Bar"), patterns); + assertThat(patterns).isEqualTo(asList("*Foo", "*Bar")); } @Test @@ -495,20 +467,20 @@ public class AnnotationUtilsTests { Method method = WebController.class.getMethod("handleMappedWithValueAttribute"); WebMapping webMapping = method.getAnnotation(WebMapping.class); AnnotationAttributes attributes = (AnnotationAttributes) getAnnotationAttributes(webMapping); - assertNotNull(attributes); - assertEquals(WebMapping.class, attributes.annotationType()); - assertEquals("name attribute: ", "foo", attributes.getString("name")); - assertArrayEquals("value attribute: ", asArray("/test"), attributes.getStringArray(VALUE)); - assertArrayEquals("path attribute: ", asArray("/test"), attributes.getStringArray("path")); + assertThat(attributes).isNotNull(); + assertThat(attributes.annotationType()).isEqualTo(WebMapping.class); + assertThat(attributes.getString("name")).as("name attribute: ").isEqualTo("foo"); + assertThat(attributes.getStringArray(VALUE)).as("value attribute: ").isEqualTo(asArray("/test")); + assertThat(attributes.getStringArray("path")).as("path attribute: ").isEqualTo(asArray("/test")); method = WebController.class.getMethod("handleMappedWithPathAttribute"); webMapping = method.getAnnotation(WebMapping.class); attributes = (AnnotationAttributes) getAnnotationAttributes(webMapping); - assertNotNull(attributes); - assertEquals(WebMapping.class, attributes.annotationType()); - assertEquals("name attribute: ", "bar", attributes.getString("name")); - assertArrayEquals("value attribute: ", asArray("/test"), attributes.getStringArray(VALUE)); - assertArrayEquals("path attribute: ", asArray("/test"), attributes.getStringArray("path")); + assertThat(attributes).isNotNull(); + assertThat(attributes.annotationType()).isEqualTo(WebMapping.class); + assertThat(attributes.getString("name")).as("name attribute: ").isEqualTo("bar"); + assertThat(attributes.getStringArray(VALUE)).as("value attribute: ").isEqualTo(asArray("/test")); + assertThat(attributes.getStringArray("path")).as("path attribute: ").isEqualTo(asArray("/test")); } @Test @@ -526,19 +498,19 @@ public class AnnotationUtilsTests { Method method = SimpleFoo.class.getMethod("something", Object.class); Order order = findAnnotation(method, Order.class); - assertEquals(1, getValue(order, VALUE)); - assertEquals(1, getValue(order)); + assertThat(getValue(order, VALUE)).isEqualTo(1); + assertThat(getValue(order)).isEqualTo(1); } @Test public void getValueFromNonPublicAnnotation() throws Exception { Annotation[] declaredAnnotations = NonPublicAnnotatedClass.class.getDeclaredAnnotations(); - assertEquals(1, declaredAnnotations.length); + assertThat(declaredAnnotations.length).isEqualTo(1); Annotation annotation = declaredAnnotations[0]; - assertNotNull(annotation); - assertEquals("NonPublicAnnotation", annotation.annotationType().getSimpleName()); - assertEquals(42, getValue(annotation, VALUE)); - assertEquals(42, getValue(annotation)); + assertThat(annotation).isNotNull(); + assertThat(annotation.annotationType().getSimpleName()).isEqualTo("NonPublicAnnotation"); + assertThat(getValue(annotation, VALUE)).isEqualTo(42); + assertThat(getValue(annotation)).isEqualTo(42); } @Test @@ -546,39 +518,39 @@ public class AnnotationUtilsTests { Method method = SimpleFoo.class.getMethod("something", Object.class); Order order = findAnnotation(method, Order.class); - assertEquals(Ordered.LOWEST_PRECEDENCE, getDefaultValue(order, VALUE)); - assertEquals(Ordered.LOWEST_PRECEDENCE, getDefaultValue(order)); + assertThat(getDefaultValue(order, VALUE)).isEqualTo(Ordered.LOWEST_PRECEDENCE); + assertThat(getDefaultValue(order)).isEqualTo(Ordered.LOWEST_PRECEDENCE); } @Test public void getDefaultValueFromNonPublicAnnotation() { Annotation[] declaredAnnotations = NonPublicAnnotatedClass.class.getDeclaredAnnotations(); - assertEquals(1, declaredAnnotations.length); + assertThat(declaredAnnotations.length).isEqualTo(1); Annotation annotation = declaredAnnotations[0]; - assertNotNull(annotation); - assertEquals("NonPublicAnnotation", annotation.annotationType().getSimpleName()); - assertEquals(-1, getDefaultValue(annotation, VALUE)); - assertEquals(-1, getDefaultValue(annotation)); + assertThat(annotation).isNotNull(); + assertThat(annotation.annotationType().getSimpleName()).isEqualTo("NonPublicAnnotation"); + assertThat(getDefaultValue(annotation, VALUE)).isEqualTo(-1); + assertThat(getDefaultValue(annotation)).isEqualTo(-1); } @Test public void getDefaultValueFromAnnotationType() { - assertEquals(Ordered.LOWEST_PRECEDENCE, getDefaultValue(Order.class, VALUE)); - assertEquals(Ordered.LOWEST_PRECEDENCE, getDefaultValue(Order.class)); + assertThat(getDefaultValue(Order.class, VALUE)).isEqualTo(Ordered.LOWEST_PRECEDENCE); + assertThat(getDefaultValue(Order.class)).isEqualTo(Ordered.LOWEST_PRECEDENCE); } @Test public void findRepeatableAnnotation() { Repeatable repeatable = findAnnotation(MyRepeatable.class, Repeatable.class); - assertNotNull(repeatable); - assertEquals(MyRepeatableContainer.class, repeatable.value()); + assertThat(repeatable).isNotNull(); + assertThat(repeatable.value()).isEqualTo(MyRepeatableContainer.class); } @Test public void getRepeatableAnnotationsDeclaredOnMethod() throws Exception { Method method = InterfaceWithRepeated.class.getMethod("foo"); Set annotations = getRepeatableAnnotations(method, MyRepeatable.class, MyRepeatableContainer.class); - assertNotNull(annotations); + assertThat(annotations).isNotNull(); List values = annotations.stream().map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(asList("A", "B", "C", "meta1")); } @@ -598,11 +570,11 @@ public class AnnotationUtilsTests { final List expectedLocations = asList("A", "B"); Set annotations = getRepeatableAnnotations(ConfigHierarchyTestCase.class, ContextConfig.class, null); - assertNotNull(annotations); - assertEquals("size if container type is omitted: ", 0, annotations.size()); + assertThat(annotations).isNotNull(); + assertThat(annotations.size()).as("size if container type is omitted: ").isEqualTo(0); annotations = getRepeatableAnnotations(ConfigHierarchyTestCase.class, ContextConfig.class, Hierarchy.class); - assertNotNull(annotations); + assertThat(annotations).isNotNull(); List locations = annotations.stream().map(ContextConfig::location).collect(toList()); assertThat(locations).isEqualTo(expectedLocations); @@ -618,19 +590,19 @@ public class AnnotationUtilsTests { // Java 8 MyRepeatable[] array = MyRepeatableClass.class.getAnnotationsByType(MyRepeatable.class); - assertNotNull(array); + assertThat(array).isNotNull(); List values = stream(array).map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesJava); // Spring Set set = getRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class, MyRepeatableContainer.class); - assertNotNull(set); + assertThat(set).isNotNull(); values = set.stream().map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesSpring); // When container type is omitted and therefore inferred from @Repeatable set = getRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class); - assertNotNull(set); + assertThat(set).isNotNull(); values = set.stream().map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesSpring); } @@ -643,19 +615,19 @@ public class AnnotationUtilsTests { // Java 8 MyRepeatable[] array = clazz.getAnnotationsByType(MyRepeatable.class); - assertNotNull(array); + assertThat(array).isNotNull(); List values = stream(array).map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesJava); // Spring Set set = getRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class); - assertNotNull(set); + assertThat(set).isNotNull(); values = set.stream().map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesSpring); // When container type is omitted and therefore inferred from @Repeatable set = getRepeatableAnnotations(clazz, MyRepeatable.class); - assertNotNull(set); + assertThat(set).isNotNull(); values = set.stream().map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesSpring); } @@ -668,19 +640,19 @@ public class AnnotationUtilsTests { // Java 8 MyRepeatable[] array = clazz.getAnnotationsByType(MyRepeatable.class); - assertNotNull(array); + assertThat(array).isNotNull(); List values = stream(array).map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesJava); // Spring Set set = getRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class); - assertNotNull(set); + assertThat(set).isNotNull(); values = set.stream().map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesSpring); // When container type is omitted and therefore inferred from @Repeatable set = getRepeatableAnnotations(clazz, MyRepeatable.class); - assertNotNull(set); + assertThat(set).isNotNull(); values = set.stream().map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesSpring); } @@ -693,19 +665,19 @@ public class AnnotationUtilsTests { // Java 8 MyRepeatable[] array = clazz.getAnnotationsByType(MyRepeatable.class); - assertNotNull(array); + assertThat(array).isNotNull(); List values = stream(array).map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesJava); // Spring Set set = getRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class); - assertNotNull(set); + assertThat(set).isNotNull(); values = set.stream().map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesSpring); // When container type is omitted and therefore inferred from @Repeatable set = getRepeatableAnnotations(clazz, MyRepeatable.class); - assertNotNull(set); + assertThat(set).isNotNull(); values = set.stream().map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesSpring); } @@ -717,19 +689,19 @@ public class AnnotationUtilsTests { // Java 8 MyRepeatable[] array = MyRepeatableClass.class.getDeclaredAnnotationsByType(MyRepeatable.class); - assertNotNull(array); + assertThat(array).isNotNull(); List values = stream(array).map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesJava); // Spring Set set = getDeclaredRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class, MyRepeatableContainer.class); - assertNotNull(set); + assertThat(set).isNotNull(); values = set.stream().map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesSpring); // When container type is omitted and therefore inferred from @Repeatable set = getDeclaredRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class); - assertNotNull(set); + assertThat(set).isNotNull(); values = set.stream().map(MyRepeatable::value).collect(toList()); assertThat(values).isEqualTo(expectedValuesSpring); } @@ -740,17 +712,17 @@ public class AnnotationUtilsTests { // Java 8 MyRepeatable[] array = clazz.getDeclaredAnnotationsByType(MyRepeatable.class); - assertNotNull(array); + assertThat(array).isNotNull(); assertThat(array.length).isEqualTo(0); // Spring Set set = getDeclaredRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class); - assertNotNull(set); + assertThat(set).isNotNull(); assertThat(set).hasSize(0); // When container type is omitted and therefore inferred from @Repeatable set = getDeclaredRepeatableAnnotations(clazz, MyRepeatable.class); - assertNotNull(set); + assertThat(set).isNotNull(); assertThat(set).hasSize(0); } @@ -759,7 +731,7 @@ public class AnnotationUtilsTests { Class clazz = ImplicitAliasesWithMissingDefaultValuesContextConfigClass.class; Class annotationType = ImplicitAliasesWithMissingDefaultValuesContextConfig.class; ImplicitAliasesWithMissingDefaultValuesContextConfig config = clazz.getAnnotation(annotationType); - assertNotNull(config); + assertThat(config).isNotNull(); assertThatExceptionOfType(AnnotationConfigurationException.class).isThrownBy(() -> synthesizeAnnotation(config, clazz)) @@ -774,7 +746,7 @@ public class AnnotationUtilsTests { Class clazz = ImplicitAliasesWithDifferentDefaultValuesContextConfigClass.class; Class annotationType = ImplicitAliasesWithDifferentDefaultValuesContextConfig.class; ImplicitAliasesWithDifferentDefaultValuesContextConfig config = clazz.getAnnotation(annotationType); - assertNotNull(config); + assertThat(config).isNotNull(); assertThatExceptionOfType(AnnotationConfigurationException.class).isThrownBy(() -> synthesizeAnnotation(config, clazz)) .withMessageStartingWith("Misconfigured aliases:") @@ -788,7 +760,7 @@ public class AnnotationUtilsTests { Class clazz = ImplicitAliasesWithDuplicateValuesContextConfigClass.class; Class annotationType = ImplicitAliasesWithDuplicateValuesContextConfig.class; ImplicitAliasesWithDuplicateValuesContextConfig config = clazz.getAnnotation(annotationType); - assertNotNull(config); + assertThat(config).isNotNull(); assertThatExceptionOfType(AnnotationConfigurationException.class).isThrownBy(() -> synthesizeAnnotation(config, clazz).location1()) @@ -803,32 +775,32 @@ public class AnnotationUtilsTests { @Test public void synthesizeAnnotationFromMapWithoutAttributeAliases() throws Exception { Component component = WebController.class.getAnnotation(Component.class); - assertNotNull(component); + assertThat(component).isNotNull(); Map map = Collections.singletonMap(VALUE, "webController"); Component synthesizedComponent = synthesizeAnnotation(map, Component.class, WebController.class); - assertNotNull(synthesizedComponent); + assertThat(synthesizedComponent).isNotNull(); - assertNotSame(component, synthesizedComponent); - assertEquals("value from component: ", "webController", component.value()); - assertEquals("value from synthesized component: ", "webController", synthesizedComponent.value()); + assertThat(synthesizedComponent).isNotSameAs(component); + assertThat(component.value()).as("value from component: ").isEqualTo("webController"); + assertThat(synthesizedComponent.value()).as("value from synthesized component: ").isEqualTo("webController"); } @Test @SuppressWarnings("unchecked") public void synthesizeAnnotationFromMapWithNestedMap() throws Exception { ComponentScanSingleFilter componentScan = ComponentScanSingleFilterClass.class.getAnnotation(ComponentScanSingleFilter.class); - assertNotNull(componentScan); - assertEquals("value from ComponentScan: ", "*Foo", componentScan.value().pattern()); + assertThat(componentScan).isNotNull(); + assertThat(componentScan.value().pattern()).as("value from ComponentScan: ").isEqualTo("*Foo"); AnnotationAttributes attributes = getAnnotationAttributes( ComponentScanSingleFilterClass.class, componentScan, false, true); - assertNotNull(attributes); - assertEquals(ComponentScanSingleFilter.class, attributes.annotationType()); + assertThat(attributes).isNotNull(); + assertThat(attributes.annotationType()).isEqualTo(ComponentScanSingleFilter.class); Map filterMap = (Map) attributes.get("value"); - assertNotNull(filterMap); - assertEquals("*Foo", filterMap.get("pattern")); + assertThat(filterMap).isNotNull(); + assertThat(filterMap.get("pattern")).isEqualTo("*Foo"); // Modify nested map filterMap.put("pattern", "newFoo"); @@ -836,27 +808,27 @@ public class AnnotationUtilsTests { ComponentScanSingleFilter synthesizedComponentScan = synthesizeAnnotation( attributes, ComponentScanSingleFilter.class, ComponentScanSingleFilterClass.class); - assertNotNull(synthesizedComponentScan); + assertThat(synthesizedComponentScan).isNotNull(); - assertNotSame(componentScan, synthesizedComponentScan); - assertEquals("value from synthesized ComponentScan: ", "newFoo", synthesizedComponentScan.value().pattern()); + assertThat(synthesizedComponentScan).isNotSameAs(componentScan); + assertThat(synthesizedComponentScan.value().pattern()).as("value from synthesized ComponentScan: ").isEqualTo("newFoo"); } @Test @SuppressWarnings("unchecked") public void synthesizeAnnotationFromMapWithNestedArrayOfMaps() throws Exception { ComponentScan componentScan = ComponentScanClass.class.getAnnotation(ComponentScan.class); - assertNotNull(componentScan); + assertThat(componentScan).isNotNull(); AnnotationAttributes attributes = getAnnotationAttributes(ComponentScanClass.class, componentScan, false, true); - assertNotNull(attributes); - assertEquals(ComponentScan.class, attributes.annotationType()); + assertThat(attributes).isNotNull(); + assertThat(attributes.annotationType()).isEqualTo(ComponentScan.class); Map[] filters = (Map[]) attributes.get("excludeFilters"); - assertNotNull(filters); + assertThat(filters).isNotNull(); List patterns = stream(filters).map(m -> (String) m.get("pattern")).collect(toList()); - assertEquals(asList("*Foo", "*Bar"), patterns); + assertThat(patterns).isEqualTo(asList("*Foo", "*Bar")); // Modify nested maps filters[0].put("pattern", "newFoo"); @@ -865,52 +837,52 @@ public class AnnotationUtilsTests { filters[1].put("enigma", 42); ComponentScan synthesizedComponentScan = synthesizeAnnotation(attributes, ComponentScan.class, ComponentScanClass.class); - assertNotNull(synthesizedComponentScan); + assertThat(synthesizedComponentScan).isNotNull(); - assertNotSame(componentScan, synthesizedComponentScan); + assertThat(synthesizedComponentScan).isNotSameAs(componentScan); patterns = stream(synthesizedComponentScan.excludeFilters()).map(Filter::pattern).collect(toList()); - assertEquals(asList("newFoo", "newBar"), patterns); + assertThat(patterns).isEqualTo(asList("newFoo", "newBar")); } @Test public void synthesizeAnnotationFromDefaultsWithoutAttributeAliases() throws Exception { AnnotationWithDefaults annotationWithDefaults = synthesizeAnnotation(AnnotationWithDefaults.class); - assertNotNull(annotationWithDefaults); - assertEquals("text: ", "enigma", annotationWithDefaults.text()); - assertTrue("predicate: ", annotationWithDefaults.predicate()); - assertArrayEquals("characters: ", new char[] { 'a', 'b', 'c' }, annotationWithDefaults.characters()); + assertThat(annotationWithDefaults).isNotNull(); + assertThat(annotationWithDefaults.text()).as("text: ").isEqualTo("enigma"); + assertThat(annotationWithDefaults.predicate()).as("predicate: ").isTrue(); + assertThat(annotationWithDefaults.characters()).as("characters: ").isEqualTo(new char[] { 'a', 'b', 'c' }); } @Test public void synthesizeAnnotationFromDefaultsWithAttributeAliases() throws Exception { ContextConfig contextConfig = synthesizeAnnotation(ContextConfig.class); - assertNotNull(contextConfig); - assertEquals("value: ", "", contextConfig.value()); - assertEquals("location: ", "", contextConfig.location()); + assertThat(contextConfig).isNotNull(); + assertThat(contextConfig.value()).as("value: ").isEqualTo(""); + assertThat(contextConfig.location()).as("location: ").isEqualTo(""); } @Test public void synthesizeAnnotationFromMapWithMinimalAttributesWithAttributeAliases() throws Exception { Map map = Collections.singletonMap("location", "test.xml"); ContextConfig contextConfig = synthesizeAnnotation(map, ContextConfig.class, null); - assertNotNull(contextConfig); - assertEquals("value: ", "test.xml", contextConfig.value()); - assertEquals("location: ", "test.xml", contextConfig.location()); + assertThat(contextConfig).isNotNull(); + assertThat(contextConfig.value()).as("value: ").isEqualTo("test.xml"); + assertThat(contextConfig.location()).as("location: ").isEqualTo("test.xml"); } @Test public void synthesizeAnnotationFromMapWithAttributeAliasesThatOverrideArraysWithSingleElements() throws Exception { Map map = Collections.singletonMap("value", "/foo"); Get get = synthesizeAnnotation(map, Get.class, null); - assertNotNull(get); - assertEquals("value: ", "/foo", get.value()); - assertEquals("path: ", "/foo", get.path()); + assertThat(get).isNotNull(); + assertThat(get.value()).as("value: ").isEqualTo("/foo"); + assertThat(get.path()).as("path: ").isEqualTo("/foo"); map = Collections.singletonMap("path", "/foo"); get = synthesizeAnnotation(map, Get.class, null); - assertNotNull(get); - assertEquals("value: ", "/foo", get.value()); - assertEquals("path: ", "/foo", get.path()); + assertThat(get).isNotNull(); + assertThat(get.value()).as("value: ").isEqualTo("/foo"); + assertThat(get.path()).as("path: ").isEqualTo("/foo"); } @Test @@ -926,13 +898,13 @@ public class AnnotationUtilsTests { private void assertAnnotationSynthesisFromMapWithImplicitAliases(String attributeNameAndValue) throws Exception { Map map = Collections.singletonMap(attributeNameAndValue, attributeNameAndValue); ImplicitAliasesContextConfig config = synthesizeAnnotation(map, ImplicitAliasesContextConfig.class, null); - assertNotNull(config); - assertEquals("value: ", attributeNameAndValue, config.value()); - assertEquals("location1: ", attributeNameAndValue, config.location1()); - assertEquals("location2: ", attributeNameAndValue, config.location2()); - assertEquals("location3: ", attributeNameAndValue, config.location3()); - assertEquals("xmlFile: ", attributeNameAndValue, config.xmlFile()); - assertEquals("groovyScript: ", attributeNameAndValue, config.groovyScript()); + assertThat(config).isNotNull(); + assertThat(config.value()).as("value: ").isEqualTo(attributeNameAndValue); + assertThat(config.location1()).as("location1: ").isEqualTo(attributeNameAndValue); + assertThat(config.location2()).as("location2: ").isEqualTo(attributeNameAndValue); + assertThat(config.location3()).as("location3: ").isEqualTo(attributeNameAndValue); + assertThat(config.xmlFile()).as("xmlFile: ").isEqualTo(attributeNameAndValue); + assertThat(config.groovyScript()).as("groovyScript: ").isEqualTo(attributeNameAndValue); } @Test @@ -943,7 +915,7 @@ public class AnnotationUtilsTests { @Test public void synthesizeAnnotationFromMapWithNullAttributeValue() throws Exception { Map map = Collections.singletonMap("text", null); - assertTrue(map.containsKey("text")); + assertThat(map.containsKey("text")).isTrue(); assertMissingTextAttribute(map); } @@ -966,29 +938,29 @@ public class AnnotationUtilsTests { public void synthesizeAnnotationFromAnnotationAttributesWithoutAttributeAliases() throws Exception { // 1) Get an annotation Component component = WebController.class.getAnnotation(Component.class); - assertNotNull(component); + assertThat(component).isNotNull(); // 2) Convert the annotation into AnnotationAttributes AnnotationAttributes attributes = getAnnotationAttributes(WebController.class, component); - assertNotNull(attributes); + assertThat(attributes).isNotNull(); // 3) Synthesize the AnnotationAttributes back into an annotation Component synthesizedComponent = synthesizeAnnotation(attributes, Component.class, WebController.class); - assertNotNull(synthesizedComponent); + assertThat(synthesizedComponent).isNotNull(); // 4) Verify that the original and synthesized annotations are equivalent - assertNotSame(component, synthesizedComponent); - assertEquals(component, synthesizedComponent); - assertEquals("value from component: ", "webController", component.value()); - assertEquals("value from synthesized component: ", "webController", synthesizedComponent.value()); + assertThat(synthesizedComponent).isNotSameAs(component); + assertThat(synthesizedComponent).isEqualTo(component); + assertThat(component.value()).as("value from component: ").isEqualTo("webController"); + assertThat(synthesizedComponent.value()).as("value from synthesized component: ").isEqualTo("webController"); } @Test // gh-22702 public void findAnnotationWithRepeatablesElements() { - assertNull(AnnotationUtils.findAnnotation(TestRepeatablesClass.class, - TestRepeatable.class)); - assertNotNull(AnnotationUtils.findAnnotation(TestRepeatablesClass.class, - TestRepeatableContainer.class)); + assertThat(AnnotationUtils.findAnnotation(TestRepeatablesClass.class, + TestRepeatable.class)).isNull(); + assertThat(AnnotationUtils.findAnnotation(TestRepeatablesClass.class, + TestRepeatableContainer.class)).isNotNull(); } @SafeVarargs diff --git a/spring-core/src/test/java/org/springframework/core/annotation/ComposedRepeatableAnnotationsTests.java b/spring-core/src/test/java/org/springframework/core/annotation/ComposedRepeatableAnnotationsTests.java index 7edafd4c115..b23952a7f2d 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/ComposedRepeatableAnnotationsTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/ComposedRepeatableAnnotationsTests.java @@ -29,10 +29,9 @@ import java.util.Set; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedRepeatableAnnotations; import static org.springframework.core.annotation.AnnotatedElementUtils.getMergedRepeatableAnnotations; @@ -112,8 +111,8 @@ public class ComposedRepeatableAnnotationsTests { public void getNoninheritedComposedRepeatableAnnotationsOnSuperclass() { Class element = SubNoninheritedRepeatableClass.class; Set annotations = getMergedRepeatableAnnotations(element, Noninherited.class); - assertNotNull(annotations); - assertEquals(0, annotations.size()); + assertThat(annotations).isNotNull(); + assertThat(annotations.size()).isEqualTo(0); } @Test @@ -213,39 +212,39 @@ public class ComposedRepeatableAnnotationsTests { } private void assertGetRepeatableAnnotations(AnnotatedElement element) { - assertNotNull(element); + assertThat(element).isNotNull(); Set peteRepeats = getMergedRepeatableAnnotations(element, PeteRepeat.class); - assertNotNull(peteRepeats); - assertEquals(3, peteRepeats.size()); + assertThat(peteRepeats).isNotNull(); + assertThat(peteRepeats.size()).isEqualTo(3); Iterator iterator = peteRepeats.iterator(); - assertEquals("A", iterator.next().value()); - assertEquals("B", iterator.next().value()); - assertEquals("C", iterator.next().value()); + assertThat(iterator.next().value()).isEqualTo("A"); + assertThat(iterator.next().value()).isEqualTo("B"); + assertThat(iterator.next().value()).isEqualTo("C"); } private void assertFindRepeatableAnnotations(AnnotatedElement element) { - assertNotNull(element); + assertThat(element).isNotNull(); Set peteRepeats = findMergedRepeatableAnnotations(element, PeteRepeat.class); - assertNotNull(peteRepeats); - assertEquals(3, peteRepeats.size()); + assertThat(peteRepeats).isNotNull(); + assertThat(peteRepeats.size()).isEqualTo(3); Iterator iterator = peteRepeats.iterator(); - assertEquals("A", iterator.next().value()); - assertEquals("B", iterator.next().value()); - assertEquals("C", iterator.next().value()); + assertThat(iterator.next().value()).isEqualTo("A"); + assertThat(iterator.next().value()).isEqualTo("B"); + assertThat(iterator.next().value()).isEqualTo("C"); } private void assertNoninheritedRepeatableAnnotations(Set annotations) { - assertNotNull(annotations); - assertEquals(3, annotations.size()); + assertThat(annotations).isNotNull(); + assertThat(annotations.size()).isEqualTo(3); Iterator iterator = annotations.iterator(); - assertEquals("A", iterator.next().value()); - assertEquals("B", iterator.next().value()); - assertEquals("C", iterator.next().value()); + assertThat(iterator.next().value()).isEqualTo("A"); + assertThat(iterator.next().value()).isEqualTo("B"); + assertThat(iterator.next().value()).isEqualTo("C"); } diff --git a/spring-core/src/test/java/org/springframework/core/annotation/MultipleComposedAnnotationsOnSingleAnnotatedElementTests.java b/spring-core/src/test/java/org/springframework/core/annotation/MultipleComposedAnnotationsOnSingleAnnotatedElementTests.java index 772047ca515..42e229845d2 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/MultipleComposedAnnotationsOnSingleAnnotatedElementTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/MultipleComposedAnnotationsOnSingleAnnotatedElementTests.java @@ -29,9 +29,7 @@ import java.util.Set; import org.junit.Ignore; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.annotation.AnnotatedElementUtils.findAllMergedAnnotations; import static org.springframework.core.annotation.AnnotatedElementUtils.getAllMergedAnnotations; @@ -63,22 +61,22 @@ public class MultipleComposedAnnotationsOnSingleAnnotatedElementTests { public void getMultipleNoninheritedComposedAnnotationsOnClass() { Class element = MultipleNoninheritedComposedCachesClass.class; Set cacheables = getAllMergedAnnotations(element, Cacheable.class); - assertNotNull(cacheables); - assertEquals(2, cacheables.size()); + assertThat(cacheables).isNotNull(); + assertThat(cacheables.size()).isEqualTo(2); Iterator iterator = cacheables.iterator(); Cacheable cacheable1 = iterator.next(); Cacheable cacheable2 = iterator.next(); - assertEquals("noninheritedCache1", cacheable1.value()); - assertEquals("noninheritedCache2", cacheable2.value()); + assertThat(cacheable1.value()).isEqualTo("noninheritedCache1"); + assertThat(cacheable2.value()).isEqualTo("noninheritedCache2"); } @Test public void getMultipleNoninheritedComposedAnnotationsOnSuperclass() { Class element = SubMultipleNoninheritedComposedCachesClass.class; Set cacheables = getAllMergedAnnotations(element, Cacheable.class); - assertNotNull(cacheables); - assertEquals(0, cacheables.size()); + assertThat(cacheables).isNotNull(); + assertThat(cacheables.size()).isEqualTo(0); } @Test @@ -90,8 +88,8 @@ public class MultipleComposedAnnotationsOnSingleAnnotatedElementTests { public void getMultipleComposedAnnotationsOnInterface() { Class element = MultipleComposedCachesOnInterfaceClass.class; Set cacheables = getAllMergedAnnotations(element, Cacheable.class); - assertNotNull(cacheables); - assertEquals(0, cacheables.size()); + assertThat(cacheables).isNotNull(); + assertThat(cacheables.size()).isEqualTo(0); } @Test @@ -110,8 +108,8 @@ public class MultipleComposedAnnotationsOnSingleAnnotatedElementTests { @Ignore("Disabled since some Java 8 updates handle the bridge method differently") public void getMultipleComposedAnnotationsOnBridgeMethod() throws Exception { Set cacheables = getAllMergedAnnotations(getBridgeMethod(), Cacheable.class); - assertNotNull(cacheables); - assertEquals(0, cacheables.size()); + assertThat(cacheables).isNotNull(); + assertThat(cacheables.size()).isEqualTo(0); } @Test @@ -128,28 +126,28 @@ public class MultipleComposedAnnotationsOnSingleAnnotatedElementTests { public void findMultipleNoninheritedComposedAnnotationsOnClass() { Class element = MultipleNoninheritedComposedCachesClass.class; Set cacheables = findAllMergedAnnotations(element, Cacheable.class); - assertNotNull(cacheables); - assertEquals(2, cacheables.size()); + assertThat(cacheables).isNotNull(); + assertThat(cacheables.size()).isEqualTo(2); Iterator iterator = cacheables.iterator(); Cacheable cacheable1 = iterator.next(); Cacheable cacheable2 = iterator.next(); - assertEquals("noninheritedCache1", cacheable1.value()); - assertEquals("noninheritedCache2", cacheable2.value()); + assertThat(cacheable1.value()).isEqualTo("noninheritedCache1"); + assertThat(cacheable2.value()).isEqualTo("noninheritedCache2"); } @Test public void findMultipleNoninheritedComposedAnnotationsOnSuperclass() { Class element = SubMultipleNoninheritedComposedCachesClass.class; Set cacheables = findAllMergedAnnotations(element, Cacheable.class); - assertNotNull(cacheables); - assertEquals(2, cacheables.size()); + assertThat(cacheables).isNotNull(); + assertThat(cacheables.size()).isEqualTo(2); Iterator iterator = cacheables.iterator(); Cacheable cacheable1 = iterator.next(); Cacheable cacheable2 = iterator.next(); - assertEquals("noninheritedCache1", cacheable1.value()); - assertEquals("noninheritedCache2", cacheable2.value()); + assertThat(cacheable1.value()).isEqualTo("noninheritedCache1"); + assertThat(cacheable2.value()).isEqualTo("noninheritedCache2"); } @Test @@ -203,42 +201,43 @@ public class MultipleComposedAnnotationsOnSingleAnnotatedElementTests { } } } - assertTrue(bridgeMethod != null && bridgeMethod.isBridge()); - assertTrue(bridgedMethod != null && !bridgedMethod.isBridge()); + assertThat(bridgeMethod != null && bridgeMethod.isBridge()).isTrue(); + boolean condition = bridgedMethod != null && !bridgedMethod.isBridge(); + assertThat(condition).isTrue(); return bridgeMethod; } private void assertGetAllMergedAnnotationsBehavior(AnnotatedElement element) { - assertNotNull(element); + assertThat(element).isNotNull(); Set cacheables = getAllMergedAnnotations(element, Cacheable.class); - assertNotNull(cacheables); - assertEquals(2, cacheables.size()); + assertThat(cacheables).isNotNull(); + assertThat(cacheables.size()).isEqualTo(2); Iterator iterator = cacheables.iterator(); Cacheable fooCacheable = iterator.next(); Cacheable barCacheable = iterator.next(); - assertEquals("fooKey", fooCacheable.key()); - assertEquals("fooCache", fooCacheable.value()); - assertEquals("barKey", barCacheable.key()); - assertEquals("barCache", barCacheable.value()); + assertThat(fooCacheable.key()).isEqualTo("fooKey"); + assertThat(fooCacheable.value()).isEqualTo("fooCache"); + assertThat(barCacheable.key()).isEqualTo("barKey"); + assertThat(barCacheable.value()).isEqualTo("barCache"); } private void assertFindAllMergedAnnotationsBehavior(AnnotatedElement element) { - assertNotNull(element); + assertThat(element).isNotNull(); Set cacheables = findAllMergedAnnotations(element, Cacheable.class); - assertNotNull(cacheables); - assertEquals(2, cacheables.size()); + assertThat(cacheables).isNotNull(); + assertThat(cacheables.size()).isEqualTo(2); Iterator iterator = cacheables.iterator(); Cacheable fooCacheable = iterator.next(); Cacheable barCacheable = iterator.next(); - assertEquals("fooKey", fooCacheable.key()); - assertEquals("fooCache", fooCacheable.value()); - assertEquals("barKey", barCacheable.key()); - assertEquals("barCache", barCacheable.value()); + assertThat(fooCacheable.key()).isEqualTo("fooKey"); + assertThat(fooCacheable.value()).isEqualTo("fooCache"); + assertThat(barCacheable.key()).isEqualTo("barKey"); + assertThat(barCacheable.value()).isEqualTo("barCache"); } diff --git a/spring-core/src/test/java/org/springframework/core/annotation/OrderSourceProviderTests.java b/spring-core/src/test/java/org/springframework/core/annotation/OrderSourceProviderTests.java index fe1f85562b1..2c1816d861b 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/OrderSourceProviderTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/OrderSourceProviderTests.java @@ -25,8 +25,7 @@ import org.junit.Test; import org.springframework.core.Ordered; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -149,16 +148,16 @@ public class OrderSourceProviderTests { private void assertOrder(List actual, Object... expected) { for (int i = 0; i < actual.size(); i++) { - assertSame("Wrong instance at index '" + i + "'", expected[i], actual.get(i)); + assertThat(actual.get(i)).as("Wrong instance at index '" + i + "'").isSameAs(expected[i]); } - assertEquals("Wrong number of items", expected.length, actual.size()); + assertThat(actual.size()).as("Wrong number of items").isEqualTo(expected.length); } private void assertOrder(Object[] actual, Object... expected) { for (int i = 0; i < actual.length; i++) { - assertSame("Wrong instance at index '" + i + "'", expected[i], actual[i]); + assertThat(actual[i]).as("Wrong instance at index '" + i + "'").isSameAs(expected[i]); } - assertEquals("Wrong number of items", expected.length, expected.length); + assertThat(expected.length).as("Wrong number of items").isEqualTo(expected.length); } diff --git a/spring-core/src/test/java/org/springframework/core/annotation/OrderUtilsTests.java b/spring-core/src/test/java/org/springframework/core/annotation/OrderUtilsTests.java index 4ad14519f5e..ae15e2de5c5 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/OrderUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/OrderUtilsTests.java @@ -20,8 +20,7 @@ import javax.annotation.Priority; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -31,38 +30,38 @@ public class OrderUtilsTests { @Test public void getSimpleOrder() { - assertEquals(Integer.valueOf(50), OrderUtils.getOrder(SimpleOrder.class, null)); - assertEquals(Integer.valueOf(50), OrderUtils.getOrder(SimpleOrder.class, null)); + assertThat(OrderUtils.getOrder(SimpleOrder.class, null)).isEqualTo(Integer.valueOf(50)); + assertThat(OrderUtils.getOrder(SimpleOrder.class, null)).isEqualTo(Integer.valueOf(50)); } @Test public void getPriorityOrder() { - assertEquals(Integer.valueOf(55), OrderUtils.getOrder(SimplePriority.class, null)); - assertEquals(Integer.valueOf(55), OrderUtils.getOrder(SimplePriority.class, null)); + assertThat(OrderUtils.getOrder(SimplePriority.class, null)).isEqualTo(Integer.valueOf(55)); + assertThat(OrderUtils.getOrder(SimplePriority.class, null)).isEqualTo(Integer.valueOf(55)); } @Test public void getOrderWithBoth() { - assertEquals(Integer.valueOf(50), OrderUtils.getOrder(OrderAndPriority.class, null)); - assertEquals(Integer.valueOf(50), OrderUtils.getOrder(OrderAndPriority.class, null)); + assertThat(OrderUtils.getOrder(OrderAndPriority.class, null)).isEqualTo(Integer.valueOf(50)); + assertThat(OrderUtils.getOrder(OrderAndPriority.class, null)).isEqualTo(Integer.valueOf(50)); } @Test public void getDefaultOrder() { - assertEquals(33, OrderUtils.getOrder(NoOrder.class, 33)); - assertEquals(33, OrderUtils.getOrder(NoOrder.class, 33)); + assertThat(OrderUtils.getOrder(NoOrder.class, 33)).isEqualTo(33); + assertThat(OrderUtils.getOrder(NoOrder.class, 33)).isEqualTo(33); } @Test public void getPriorityValueNoAnnotation() { - assertNull(OrderUtils.getPriority(SimpleOrder.class)); - assertNull(OrderUtils.getPriority(SimpleOrder.class)); + assertThat(OrderUtils.getPriority(SimpleOrder.class)).isNull(); + assertThat(OrderUtils.getPriority(SimpleOrder.class)).isNull(); } @Test public void getPriorityValue() { - assertEquals(Integer.valueOf(55), OrderUtils.getPriority(OrderAndPriority.class)); - assertEquals(Integer.valueOf(55), OrderUtils.getPriority(OrderAndPriority.class)); + assertThat(OrderUtils.getPriority(OrderAndPriority.class)).isEqualTo(Integer.valueOf(55)); + assertThat(OrderUtils.getPriority(OrderAndPriority.class)).isEqualTo(Integer.valueOf(55)); } diff --git a/spring-core/src/test/java/org/springframework/core/annotation/SynthesizingMethodParameterTests.java b/spring-core/src/test/java/org/springframework/core/annotation/SynthesizingMethodParameterTests.java index 149e7ed1385..3d63bdbc9fa 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/SynthesizingMethodParameterTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/SynthesizingMethodParameterTests.java @@ -23,10 +23,8 @@ import org.junit.Test; import org.springframework.core.MethodParameter; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotEquals; /** * @author Juergen Hoeller @@ -54,50 +52,50 @@ public class SynthesizingMethodParameterTests { @Test public void testEquals() throws NoSuchMethodException { - assertEquals(stringParameter, stringParameter); - assertEquals(longParameter, longParameter); - assertEquals(intReturnType, intReturnType); + assertThat(stringParameter).isEqualTo(stringParameter); + assertThat(longParameter).isEqualTo(longParameter); + assertThat(intReturnType).isEqualTo(intReturnType); - assertFalse(stringParameter.equals(longParameter)); - assertFalse(stringParameter.equals(intReturnType)); - assertFalse(longParameter.equals(stringParameter)); - assertFalse(longParameter.equals(intReturnType)); - assertFalse(intReturnType.equals(stringParameter)); - assertFalse(intReturnType.equals(longParameter)); + assertThat(stringParameter.equals(longParameter)).isFalse(); + assertThat(stringParameter.equals(intReturnType)).isFalse(); + assertThat(longParameter.equals(stringParameter)).isFalse(); + assertThat(longParameter.equals(intReturnType)).isFalse(); + assertThat(intReturnType.equals(stringParameter)).isFalse(); + assertThat(intReturnType.equals(longParameter)).isFalse(); Method method = getClass().getMethod("method", String.class, Long.TYPE); MethodParameter methodParameter = new SynthesizingMethodParameter(method, 0); - assertEquals(stringParameter, methodParameter); - assertEquals(methodParameter, stringParameter); - assertNotEquals(longParameter, methodParameter); - assertNotEquals(methodParameter, longParameter); + assertThat(methodParameter).isEqualTo(stringParameter); + assertThat(stringParameter).isEqualTo(methodParameter); + assertThat(methodParameter).isNotEqualTo(longParameter); + assertThat(longParameter).isNotEqualTo(methodParameter); methodParameter = new MethodParameter(method, 0); - assertEquals(stringParameter, methodParameter); - assertEquals(methodParameter, stringParameter); - assertNotEquals(longParameter, methodParameter); - assertNotEquals(methodParameter, longParameter); + assertThat(methodParameter).isEqualTo(stringParameter); + assertThat(stringParameter).isEqualTo(methodParameter); + assertThat(methodParameter).isNotEqualTo(longParameter); + assertThat(longParameter).isNotEqualTo(methodParameter); } @Test public void testHashCode() throws NoSuchMethodException { - assertEquals(stringParameter.hashCode(), stringParameter.hashCode()); - assertEquals(longParameter.hashCode(), longParameter.hashCode()); - assertEquals(intReturnType.hashCode(), intReturnType.hashCode()); + assertThat(stringParameter.hashCode()).isEqualTo(stringParameter.hashCode()); + assertThat(longParameter.hashCode()).isEqualTo(longParameter.hashCode()); + assertThat(intReturnType.hashCode()).isEqualTo(intReturnType.hashCode()); Method method = getClass().getMethod("method", String.class, Long.TYPE); SynthesizingMethodParameter methodParameter = new SynthesizingMethodParameter(method, 0); - assertEquals(stringParameter.hashCode(), methodParameter.hashCode()); - assertNotEquals(longParameter.hashCode(), methodParameter.hashCode()); + assertThat(methodParameter.hashCode()).isEqualTo(stringParameter.hashCode()); + assertThat(methodParameter.hashCode()).isNotEqualTo((long) longParameter.hashCode()); } @Test public void testFactoryMethods() { - assertEquals(stringParameter, SynthesizingMethodParameter.forExecutable(method, 0)); - assertEquals(longParameter, SynthesizingMethodParameter.forExecutable(method, 1)); + assertThat(SynthesizingMethodParameter.forExecutable(method, 0)).isEqualTo(stringParameter); + assertThat(SynthesizingMethodParameter.forExecutable(method, 1)).isEqualTo(longParameter); - assertEquals(stringParameter, SynthesizingMethodParameter.forParameter(method.getParameters()[0])); - assertEquals(longParameter, SynthesizingMethodParameter.forParameter(method.getParameters()[1])); + assertThat(SynthesizingMethodParameter.forParameter(method.getParameters()[0])).isEqualTo(stringParameter); + assertThat(SynthesizingMethodParameter.forParameter(method.getParameters()[1])).isEqualTo(longParameter); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/codec/AbstractEncoderTestCase.java b/spring-core/src/test/java/org/springframework/core/codec/AbstractEncoderTestCase.java index 6790cc727e2..34d9795d33a 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/AbstractEncoderTestCase.java +++ b/spring-core/src/test/java/org/springframework/core/codec/AbstractEncoderTestCase.java @@ -33,8 +33,7 @@ import org.springframework.util.Assert; import org.springframework.util.MimeType; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.io.buffer.DataBufferUtils.release; /** @@ -150,7 +149,6 @@ public abstract class AbstractEncoderTestCase> * @param hints the hints used for decoding. May be {@code null}. * @param the output type */ - @SuppressWarnings("unchecked") protected void testEncode(Publisher input, ResolvableType inputType, Consumer> stepConsumer, @Nullable MimeType mimeType, @Nullable Map hints) { @@ -241,7 +239,7 @@ public abstract class AbstractEncoderTestCase> byte[] resultBytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(resultBytes); release(dataBuffer); - assertArrayEquals(expected, resultBytes); + assertThat(resultBytes).isEqualTo(expected); }; } @@ -256,7 +254,7 @@ public abstract class AbstractEncoderTestCase> dataBuffer.read(resultBytes); release(dataBuffer); String actual = new String(resultBytes, UTF_8); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); }; } diff --git a/spring-core/src/test/java/org/springframework/core/codec/ByteArrayDecoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/ByteArrayDecoderTests.java index 05830bc3b89..e14cf54965e 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/ByteArrayDecoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/ByteArrayDecoderTests.java @@ -26,9 +26,7 @@ import org.springframework.core.ResolvableType; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.util.MimeTypeUtils; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -47,12 +45,12 @@ public class ByteArrayDecoderTests extends AbstractDecoderTestCase expectBytes(byte[] expected) { - return bytes -> assertArrayEquals(expected, bytes); + return bytes -> assertThat(bytes).isEqualTo(expected); } } diff --git a/spring-core/src/test/java/org/springframework/core/codec/ByteArrayEncoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/ByteArrayEncoderTests.java index 13a742ea774..4b40a62f3bb 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/ByteArrayEncoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/ByteArrayEncoderTests.java @@ -24,8 +24,7 @@ import reactor.core.publisher.Flux; import org.springframework.core.ResolvableType; import org.springframework.util.MimeTypeUtils; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -44,15 +43,15 @@ public class ByteArrayEncoderTests extends AbstractEncoderTestCase expectByteBuffer(ByteBuffer expected) { - return actual -> assertEquals(expected, actual); + return actual -> assertThat(actual).isEqualTo(expected); } } diff --git a/spring-core/src/test/java/org/springframework/core/codec/ByteBufferEncoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/ByteBufferEncoderTests.java index cd2128606d3..cd343a217f0 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/ByteBufferEncoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/ByteBufferEncoderTests.java @@ -25,8 +25,7 @@ import reactor.core.publisher.Flux; import org.springframework.core.ResolvableType; import org.springframework.util.MimeTypeUtils; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze @@ -44,15 +43,15 @@ public class ByteBufferEncoderTests extends AbstractEncoderTestCase { int capacity = this.encoder.calculateCapacity(sequence, charset); int length = sequence.length(); - assertTrue(String.format("%s has capacity %d; length %d", charset, capacity, length), - capacity >= length); + assertThat(capacity >= length).as(String.format("%s has capacity %d; length %d", charset, capacity, length)).isTrue(); }); } diff --git a/spring-core/src/test/java/org/springframework/core/codec/DataBufferDecoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/DataBufferDecoderTests.java index 670ed6d8f22..ebe6988b947 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/DataBufferDecoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/DataBufferDecoderTests.java @@ -27,9 +27,7 @@ import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.util.MimeTypeUtils; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze @@ -48,12 +46,12 @@ public class DataBufferDecoderTests extends AbstractDecoderTestCase { byte[] actualBytes = new byte[actual.readableByteCount()]; actual.read(actualBytes); - assertArrayEquals(expected, actualBytes); + assertThat(actualBytes).isEqualTo(expected); DataBufferUtils.release(actual); }; diff --git a/spring-core/src/test/java/org/springframework/core/codec/DataBufferEncoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/DataBufferEncoderTests.java index eb11fac6b08..9238478fa10 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/DataBufferEncoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/DataBufferEncoderTests.java @@ -26,8 +26,7 @@ import org.springframework.core.ResolvableType; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.util.MimeTypeUtils; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze @@ -46,15 +45,15 @@ public class DataBufferEncoderTests extends AbstractEncoderTestCase { try { byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream()); - assertEquals("foobar", new String(bytes)); + assertThat(new String(bytes)).isEqualTo("foobar"); } catch (IOException ex) { throw new AssertionError(ex.getMessage(), ex); @@ -92,8 +90,8 @@ public class ResourceDecoderTests extends AbstractDecoderTestCase { String value = DataBufferTestUtils.dumpString(dataBuffer, UTF_8); DataBufferUtils.release(dataBuffer); - assertEquals(expected, value); + assertThat(value).isEqualTo(expected); }; } diff --git a/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java index 93ec2d5616a..26833c483a5 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java @@ -34,8 +34,7 @@ import org.springframework.util.MimeTypeUtils; import static java.nio.charset.StandardCharsets.UTF_16BE; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link StringDecoder}. @@ -57,12 +56,12 @@ public class StringDecoderTests extends AbstractDecoderTestCase { @Override @Test public void canDecode() { - assertTrue(this.decoder.canDecode(TYPE, MimeTypeUtils.TEXT_PLAIN)); - assertTrue(this.decoder.canDecode(TYPE, MimeTypeUtils.TEXT_HTML)); - assertTrue(this.decoder.canDecode(TYPE, MimeTypeUtils.APPLICATION_JSON)); - assertTrue(this.decoder.canDecode(TYPE, MimeTypeUtils.parseMimeType("text/plain;charset=utf-8"))); - assertFalse(this.decoder.canDecode(ResolvableType.forClass(Integer.class), MimeTypeUtils.TEXT_PLAIN)); - assertFalse(this.decoder.canDecode(ResolvableType.forClass(Object.class), MimeTypeUtils.APPLICATION_JSON)); + assertThat(this.decoder.canDecode(TYPE, MimeTypeUtils.TEXT_PLAIN)).isTrue(); + assertThat(this.decoder.canDecode(TYPE, MimeTypeUtils.TEXT_HTML)).isTrue(); + assertThat(this.decoder.canDecode(TYPE, MimeTypeUtils.APPLICATION_JSON)).isTrue(); + assertThat(this.decoder.canDecode(TYPE, MimeTypeUtils.parseMimeType("text/plain;charset=utf-8"))).isTrue(); + assertThat(this.decoder.canDecode(ResolvableType.forClass(Integer.class), MimeTypeUtils.TEXT_PLAIN)).isFalse(); + assertThat(this.decoder.canDecode(ResolvableType.forClass(Object.class), MimeTypeUtils.APPLICATION_JSON)).isFalse(); } @Override diff --git a/spring-core/src/test/java/org/springframework/core/convert/TypeDescriptorTests.java b/spring-core/src/test/java/org/springframework/core/convert/TypeDescriptorTests.java index 9d48a8a3855..9ffbcf33cee 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/TypeDescriptorTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/TypeDescriptorTests.java @@ -44,12 +44,6 @@ import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; 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.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Tests for {@link TypeDescriptor}. @@ -66,119 +60,119 @@ public class TypeDescriptorTests { @Test public void parameterPrimitive() throws Exception { TypeDescriptor desc = new TypeDescriptor(new MethodParameter(getClass().getMethod("testParameterPrimitive", int.class), 0)); - assertEquals(int.class, desc.getType()); - assertEquals(Integer.class, desc.getObjectType()); - assertEquals("int", desc.getName()); - assertEquals("int", desc.toString()); - assertTrue(desc.isPrimitive()); - assertEquals(0, desc.getAnnotations().length); - assertFalse(desc.isCollection()); - assertFalse(desc.isMap()); + assertThat(desc.getType()).isEqualTo(int.class); + assertThat(desc.getObjectType()).isEqualTo(Integer.class); + assertThat(desc.getName()).isEqualTo("int"); + assertThat(desc.toString()).isEqualTo("int"); + assertThat(desc.isPrimitive()).isTrue(); + assertThat(desc.getAnnotations().length).isEqualTo(0); + assertThat(desc.isCollection()).isFalse(); + assertThat(desc.isMap()).isFalse(); } @Test public void parameterScalar() throws Exception { TypeDescriptor desc = new TypeDescriptor(new MethodParameter(getClass().getMethod("testParameterScalar", String.class), 0)); - assertEquals(String.class, desc.getType()); - assertEquals(String.class, desc.getObjectType()); - assertEquals("java.lang.String", desc.getName()); - assertEquals("java.lang.String", desc.toString()); - assertTrue(!desc.isPrimitive()); - assertEquals(0, desc.getAnnotations().length); - assertFalse(desc.isCollection()); - assertFalse(desc.isArray()); - assertFalse(desc.isMap()); + assertThat(desc.getType()).isEqualTo(String.class); + assertThat(desc.getObjectType()).isEqualTo(String.class); + assertThat(desc.getName()).isEqualTo("java.lang.String"); + assertThat(desc.toString()).isEqualTo("java.lang.String"); + assertThat(!desc.isPrimitive()).isTrue(); + assertThat(desc.getAnnotations().length).isEqualTo(0); + assertThat(desc.isCollection()).isFalse(); + assertThat(desc.isArray()).isFalse(); + assertThat(desc.isMap()).isFalse(); } @Test public void parameterList() throws Exception { MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterList", List.class), 0); TypeDescriptor desc = new TypeDescriptor(methodParameter); - assertEquals(List.class, desc.getType()); - assertEquals(List.class, desc.getObjectType()); - assertEquals("java.util.List", desc.getName()); - assertEquals("java.util.List>>>", desc.toString()); - assertTrue(!desc.isPrimitive()); - assertEquals(0, desc.getAnnotations().length); - assertTrue(desc.isCollection()); - assertFalse(desc.isArray()); - assertEquals(List.class, desc.getElementTypeDescriptor().getType()); - assertEquals(TypeDescriptor.nested(methodParameter, 1), desc.getElementTypeDescriptor()); - assertEquals(TypeDescriptor.nested(methodParameter, 2), desc.getElementTypeDescriptor().getElementTypeDescriptor()); - assertEquals(TypeDescriptor.nested(methodParameter, 3), desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapValueTypeDescriptor()); - assertEquals(Integer.class, desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapKeyTypeDescriptor().getType()); - assertEquals(Enum.class, desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapValueTypeDescriptor().getType()); - assertFalse(desc.isMap()); + assertThat(desc.getType()).isEqualTo(List.class); + assertThat(desc.getObjectType()).isEqualTo(List.class); + assertThat(desc.getName()).isEqualTo("java.util.List"); + assertThat(desc.toString()).isEqualTo("java.util.List>>>"); + assertThat(!desc.isPrimitive()).isTrue(); + assertThat(desc.getAnnotations().length).isEqualTo(0); + assertThat(desc.isCollection()).isTrue(); + assertThat(desc.isArray()).isFalse(); + assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(List.class); + assertThat(desc.getElementTypeDescriptor()).isEqualTo(TypeDescriptor.nested(methodParameter, 1)); + assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor()).isEqualTo(TypeDescriptor.nested(methodParameter, 2)); + assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapValueTypeDescriptor()).isEqualTo(TypeDescriptor.nested(methodParameter, 3)); + assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapKeyTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor().getMapValueTypeDescriptor().getType()).isEqualTo(Enum.class); + assertThat(desc.isMap()).isFalse(); } @Test public void parameterListNoParamTypes() throws Exception { MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterListNoParamTypes", List.class), 0); TypeDescriptor desc = new TypeDescriptor(methodParameter); - assertEquals(List.class, desc.getType()); - assertEquals(List.class, desc.getObjectType()); - assertEquals("java.util.List", desc.getName()); - assertEquals("java.util.List", desc.toString()); - assertTrue(!desc.isPrimitive()); - assertEquals(0, desc.getAnnotations().length); - assertTrue(desc.isCollection()); - assertFalse(desc.isArray()); - assertNull(desc.getElementTypeDescriptor()); - assertFalse(desc.isMap()); + assertThat(desc.getType()).isEqualTo(List.class); + assertThat(desc.getObjectType()).isEqualTo(List.class); + assertThat(desc.getName()).isEqualTo("java.util.List"); + assertThat(desc.toString()).isEqualTo("java.util.List"); + assertThat(!desc.isPrimitive()).isTrue(); + assertThat(desc.getAnnotations().length).isEqualTo(0); + assertThat(desc.isCollection()).isTrue(); + assertThat(desc.isArray()).isFalse(); + assertThat((Object) desc.getElementTypeDescriptor()).isNull(); + assertThat(desc.isMap()).isFalse(); } @Test public void parameterArray() throws Exception { MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterArray", Integer[].class), 0); TypeDescriptor desc = new TypeDescriptor(methodParameter); - assertEquals(Integer[].class, desc.getType()); - assertEquals(Integer[].class, desc.getObjectType()); - assertEquals("java.lang.Integer[]", desc.getName()); - assertEquals("java.lang.Integer[]", desc.toString()); - assertTrue(!desc.isPrimitive()); - assertEquals(0, desc.getAnnotations().length); - assertFalse(desc.isCollection()); - assertTrue(desc.isArray()); - assertEquals(Integer.class, desc.getElementTypeDescriptor().getType()); - assertEquals(TypeDescriptor.valueOf(Integer.class), desc.getElementTypeDescriptor()); - assertFalse(desc.isMap()); + assertThat(desc.getType()).isEqualTo(Integer[].class); + assertThat(desc.getObjectType()).isEqualTo(Integer[].class); + assertThat(desc.getName()).isEqualTo("java.lang.Integer[]"); + assertThat(desc.toString()).isEqualTo("java.lang.Integer[]"); + assertThat(!desc.isPrimitive()).isTrue(); + assertThat(desc.getAnnotations().length).isEqualTo(0); + assertThat(desc.isCollection()).isFalse(); + assertThat(desc.isArray()).isTrue(); + assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(desc.getElementTypeDescriptor()).isEqualTo(TypeDescriptor.valueOf(Integer.class)); + assertThat(desc.isMap()).isFalse(); } @Test public void parameterMap() throws Exception { MethodParameter methodParameter = new MethodParameter(getClass().getMethod("testParameterMap", Map.class), 0); TypeDescriptor desc = new TypeDescriptor(methodParameter); - assertEquals(Map.class, desc.getType()); - assertEquals(Map.class, desc.getObjectType()); - assertEquals("java.util.Map", desc.getName()); - assertEquals("java.util.Map>", desc.toString()); - assertTrue(!desc.isPrimitive()); - assertEquals(0, desc.getAnnotations().length); - assertFalse(desc.isCollection()); - assertFalse(desc.isArray()); - assertTrue(desc.isMap()); - assertEquals(TypeDescriptor.nested(methodParameter, 1), desc.getMapValueTypeDescriptor()); - assertEquals(TypeDescriptor.nested(methodParameter, 2), desc.getMapValueTypeDescriptor().getElementTypeDescriptor()); - assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getType()); - assertEquals(List.class, desc.getMapValueTypeDescriptor().getType()); - assertEquals(String.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()); + assertThat(desc.getType()).isEqualTo(Map.class); + assertThat(desc.getObjectType()).isEqualTo(Map.class); + assertThat(desc.getName()).isEqualTo("java.util.Map"); + assertThat(desc.toString()).isEqualTo("java.util.Map>"); + assertThat(!desc.isPrimitive()).isTrue(); + assertThat(desc.getAnnotations().length).isEqualTo(0); + assertThat(desc.isCollection()).isFalse(); + assertThat(desc.isArray()).isFalse(); + assertThat(desc.isMap()).isTrue(); + assertThat(desc.getMapValueTypeDescriptor()).isEqualTo(TypeDescriptor.nested(methodParameter, 1)); + assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor()).isEqualTo(TypeDescriptor.nested(methodParameter, 2)); + assertThat(desc.getMapKeyTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(desc.getMapValueTypeDescriptor().getType()).isEqualTo(List.class); + assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(String.class); } @Test public void parameterAnnotated() throws Exception { TypeDescriptor t1 = new TypeDescriptor(new MethodParameter(getClass().getMethod("testAnnotatedMethod", String.class), 0)); - assertEquals(String.class, t1.getType()); - assertEquals(1, t1.getAnnotations().length); - assertNotNull(t1.getAnnotation(ParameterAnnotation.class)); - assertTrue(t1.hasAnnotation(ParameterAnnotation.class)); - assertEquals(123, t1.getAnnotation(ParameterAnnotation.class).value()); + assertThat(t1.getType()).isEqualTo(String.class); + assertThat(t1.getAnnotations().length).isEqualTo(1); + assertThat(t1.getAnnotation(ParameterAnnotation.class)).isNotNull(); + assertThat(t1.hasAnnotation(ParameterAnnotation.class)).isTrue(); + assertThat(t1.getAnnotation(ParameterAnnotation.class).value()).isEqualTo(123); } @Test public void getAnnotationsReturnsClonedArray() throws Exception { TypeDescriptor t = new TypeDescriptor(new MethodParameter(getClass().getMethod("testAnnotatedMethod", String.class), 0)); t.getAnnotations()[0] = null; - assertNotNull(t.getAnnotations()[0]); + assertThat(t.getAnnotations()[0]).isNotNull(); } @Test @@ -186,8 +180,8 @@ public class TypeDescriptorTests { Property property = new Property(getClass(), getClass().getMethod("getComplexProperty"), getClass().getMethod("setComplexProperty", Map.class)); TypeDescriptor desc = new TypeDescriptor(property); - assertEquals(String.class, desc.getMapKeyTypeDescriptor().getType()); - assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getElementTypeDescriptor().getType()); + assertThat(desc.getMapKeyTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class); } @Test @@ -196,7 +190,7 @@ public class TypeDescriptorTests { Property property = new Property(getClass(), genericBean.getClass().getMethod("getProperty"), genericBean.getClass().getMethod("setProperty", Integer.class)); TypeDescriptor desc = new TypeDescriptor(property); - assertEquals(Integer.class, desc.getType()); + assertThat(desc.getType()).isEqualTo(Integer.class); } @Test @@ -205,7 +199,7 @@ public class TypeDescriptorTests { Property property = new Property(getClass(), genericBean.getClass().getMethod("getProperty"), genericBean.getClass().getMethod("setProperty", Number.class)); TypeDescriptor desc = new TypeDescriptor(property); - assertEquals(Integer.class, desc.getType()); + assertThat(desc.getType()).isEqualTo(Integer.class); } @Test @@ -214,8 +208,8 @@ public class TypeDescriptorTests { Property property = new Property(getClass(), genericBean.getClass().getMethod("getListProperty"), genericBean.getClass().getMethod("setListProperty", List.class)); TypeDescriptor desc = new TypeDescriptor(property); - assertEquals(List.class, desc.getType()); - assertEquals(Integer.class, desc.getElementTypeDescriptor().getType()); + assertThat(desc.getType()).isEqualTo(List.class); + assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class); } @Test @@ -224,10 +218,10 @@ public class TypeDescriptorTests { Property property = new Property(genericBean.getClass(), genericBean.getClass().getMethod("getListProperty"), genericBean.getClass().getMethod("setListProperty", List.class)); TypeDescriptor desc = new TypeDescriptor(property); - assertEquals(List.class, desc.getType()); - assertEquals(Integer.class, desc.getElementTypeDescriptor().getType()); - assertNotNull(desc.getAnnotation(MethodAnnotation1.class)); - assertTrue(desc.hasAnnotation(MethodAnnotation1.class)); + assertThat(desc.getType()).isEqualTo(List.class); + assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(desc.getAnnotation(MethodAnnotation1.class)).isNotNull(); + assertThat(desc.hasAnnotation(MethodAnnotation1.class)).isTrue(); } @Test @@ -235,12 +229,12 @@ public class TypeDescriptorTests { Property property = new Property( getClass(), getClass().getMethod("getProperty"), getClass().getMethod("setProperty", Map.class)); TypeDescriptor desc = new TypeDescriptor(property); - assertEquals(Map.class, desc.getType()); - assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType()); - assertEquals(Long.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()); - assertNotNull(desc.getAnnotation(MethodAnnotation1.class)); - assertNotNull(desc.getAnnotation(MethodAnnotation2.class)); - assertNotNull(desc.getAnnotation(MethodAnnotation3.class)); + assertThat(desc.getType()).isEqualTo(Map.class); + assertThat(desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Long.class); + assertThat(desc.getAnnotation(MethodAnnotation1.class)).isNotNull(); + assertThat(desc.getAnnotation(MethodAnnotation2.class)).isNotNull(); + assertThat(desc.getAnnotation(MethodAnnotation3.class)).isNotNull(); } @Test @@ -260,160 +254,159 @@ public class TypeDescriptorTests { private void assertAnnotationFoundOnMethod(Class annotationType, String methodName) throws Exception { TypeDescriptor typeDescriptor = new TypeDescriptor(new MethodParameter(getClass().getMethod(methodName), -1)); - assertNotNull("Should have found @" + annotationType.getSimpleName() + " on " + methodName + ".", - typeDescriptor.getAnnotation(annotationType)); + assertThat(typeDescriptor.getAnnotation(annotationType)).as("Should have found @" + annotationType.getSimpleName() + " on " + methodName + ".").isNotNull(); } @Test public void fieldScalar() throws Exception { TypeDescriptor typeDescriptor = new TypeDescriptor(getClass().getField("fieldScalar")); - assertFalse(typeDescriptor.isPrimitive()); - assertFalse(typeDescriptor.isArray()); - assertFalse(typeDescriptor.isCollection()); - assertFalse(typeDescriptor.isMap()); - assertEquals(Integer.class, typeDescriptor.getType()); - assertEquals(Integer.class, typeDescriptor.getObjectType()); + assertThat(typeDescriptor.isPrimitive()).isFalse(); + assertThat(typeDescriptor.isArray()).isFalse(); + assertThat(typeDescriptor.isCollection()).isFalse(); + assertThat(typeDescriptor.isMap()).isFalse(); + assertThat(typeDescriptor.getType()).isEqualTo(Integer.class); + assertThat(typeDescriptor.getObjectType()).isEqualTo(Integer.class); } @Test public void fieldList() throws Exception { TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("listOfString")); - assertFalse(typeDescriptor.isArray()); - assertEquals(List.class, typeDescriptor.getType()); - assertEquals(String.class, typeDescriptor.getElementTypeDescriptor().getType()); - assertEquals("java.util.List", typeDescriptor.toString()); + assertThat(typeDescriptor.isArray()).isFalse(); + assertThat(typeDescriptor.getType()).isEqualTo(List.class); + assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(typeDescriptor.toString()).isEqualTo("java.util.List"); } @Test public void fieldListOfListOfString() throws Exception { TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("listOfListOfString")); - assertFalse(typeDescriptor.isArray()); - assertEquals(List.class, typeDescriptor.getType()); - assertEquals(List.class, typeDescriptor.getElementTypeDescriptor().getType()); - assertEquals(String.class, typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor().getType()); - assertEquals("java.util.List>", typeDescriptor.toString()); + assertThat(typeDescriptor.isArray()).isFalse(); + assertThat(typeDescriptor.getType()).isEqualTo(List.class); + assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(List.class); + assertThat(typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(typeDescriptor.toString()).isEqualTo("java.util.List>"); } @Test public void fieldListOfListUnknown() throws Exception { TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("listOfListOfUnknown")); - assertFalse(typeDescriptor.isArray()); - assertEquals(List.class, typeDescriptor.getType()); - assertEquals(List.class, typeDescriptor.getElementTypeDescriptor().getType()); - assertNull(typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor()); - assertEquals("java.util.List>", typeDescriptor.toString()); + assertThat(typeDescriptor.isArray()).isFalse(); + assertThat(typeDescriptor.getType()).isEqualTo(List.class); + assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(List.class); + assertThat(typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor()).isNull(); + assertThat(typeDescriptor.toString()).isEqualTo("java.util.List>"); } @Test public void fieldArray() throws Exception { TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("intArray")); - assertTrue(typeDescriptor.isArray()); - assertEquals(Integer.TYPE,typeDescriptor.getElementTypeDescriptor().getType()); - assertEquals("int[]",typeDescriptor.toString()); + assertThat(typeDescriptor.isArray()).isTrue(); + assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(Integer.TYPE); + assertThat(typeDescriptor.toString()).isEqualTo("int[]"); } @Test public void fieldComplexTypeDescriptor() throws Exception { TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("arrayOfListOfString")); - assertTrue(typeDescriptor.isArray()); - assertEquals(List.class,typeDescriptor.getElementTypeDescriptor().getType()); - assertEquals(String.class, typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor().getType()); - assertEquals("java.util.List[]",typeDescriptor.toString()); + assertThat(typeDescriptor.isArray()).isTrue(); + assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(List.class); + assertThat(typeDescriptor.getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(typeDescriptor.toString()).isEqualTo("java.util.List[]"); } @Test public void fieldComplexTypeDescriptor2() throws Exception { TypeDescriptor typeDescriptor = new TypeDescriptor(TypeDescriptorTests.class.getDeclaredField("nestedMapField")); - assertTrue(typeDescriptor.isMap()); - assertEquals(String.class,typeDescriptor.getMapKeyTypeDescriptor().getType()); - assertEquals(List.class, typeDescriptor.getMapValueTypeDescriptor().getType()); - assertEquals(Integer.class, typeDescriptor.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()); - assertEquals("java.util.Map>", typeDescriptor.toString()); + assertThat(typeDescriptor.isMap()).isTrue(); + assertThat(typeDescriptor.getMapKeyTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(typeDescriptor.getMapValueTypeDescriptor().getType()).isEqualTo(List.class); + assertThat(typeDescriptor.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(typeDescriptor.toString()).isEqualTo("java.util.Map>"); } @Test public void fieldMap() throws Exception { TypeDescriptor desc = new TypeDescriptor(TypeDescriptorTests.class.getField("fieldMap")); - assertTrue(desc.isMap()); - assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType()); - assertEquals(Long.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()); + assertThat(desc.isMap()).isTrue(); + assertThat(desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Long.class); } @Test public void fieldAnnotated() throws Exception { TypeDescriptor typeDescriptor = new TypeDescriptor(getClass().getField("fieldAnnotated")); - assertEquals(1, typeDescriptor.getAnnotations().length); - assertNotNull(typeDescriptor.getAnnotation(FieldAnnotation.class)); + assertThat(typeDescriptor.getAnnotations().length).isEqualTo(1); + assertThat(typeDescriptor.getAnnotation(FieldAnnotation.class)).isNotNull(); } @Test public void valueOfScalar() { TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(Integer.class); - assertFalse(typeDescriptor.isPrimitive()); - assertFalse(typeDescriptor.isArray()); - assertFalse(typeDescriptor.isCollection()); - assertFalse(typeDescriptor.isMap()); - assertEquals(Integer.class, typeDescriptor.getType()); - assertEquals(Integer.class, typeDescriptor.getObjectType()); + assertThat(typeDescriptor.isPrimitive()).isFalse(); + assertThat(typeDescriptor.isArray()).isFalse(); + assertThat(typeDescriptor.isCollection()).isFalse(); + assertThat(typeDescriptor.isMap()).isFalse(); + assertThat(typeDescriptor.getType()).isEqualTo(Integer.class); + assertThat(typeDescriptor.getObjectType()).isEqualTo(Integer.class); } @Test public void valueOfPrimitive() { TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(int.class); - assertTrue(typeDescriptor.isPrimitive()); - assertFalse(typeDescriptor.isArray()); - assertFalse(typeDescriptor.isCollection()); - assertFalse(typeDescriptor.isMap()); - assertEquals(Integer.TYPE, typeDescriptor.getType()); - assertEquals(Integer.class, typeDescriptor.getObjectType()); + assertThat(typeDescriptor.isPrimitive()).isTrue(); + assertThat(typeDescriptor.isArray()).isFalse(); + assertThat(typeDescriptor.isCollection()).isFalse(); + assertThat(typeDescriptor.isMap()).isFalse(); + assertThat(typeDescriptor.getType()).isEqualTo(Integer.TYPE); + assertThat(typeDescriptor.getObjectType()).isEqualTo(Integer.class); } @Test public void valueOfArray() throws Exception { TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(int[].class); - assertTrue(typeDescriptor.isArray()); - assertFalse(typeDescriptor.isCollection()); - assertFalse(typeDescriptor.isMap()); - assertEquals(Integer.TYPE, typeDescriptor.getElementTypeDescriptor().getType()); + assertThat(typeDescriptor.isArray()).isTrue(); + assertThat(typeDescriptor.isCollection()).isFalse(); + assertThat(typeDescriptor.isMap()).isFalse(); + assertThat(typeDescriptor.getElementTypeDescriptor().getType()).isEqualTo(Integer.TYPE); } @Test public void valueOfCollection() throws Exception { TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(Collection.class); - assertTrue(typeDescriptor.isCollection()); - assertFalse(typeDescriptor.isArray()); - assertFalse(typeDescriptor.isMap()); - assertNull(typeDescriptor.getElementTypeDescriptor()); + assertThat(typeDescriptor.isCollection()).isTrue(); + assertThat(typeDescriptor.isArray()).isFalse(); + assertThat(typeDescriptor.isMap()).isFalse(); + assertThat((Object) typeDescriptor.getElementTypeDescriptor()).isNull(); } @Test public void forObject() { TypeDescriptor desc = TypeDescriptor.forObject("3"); - assertEquals(String.class, desc.getType()); + assertThat(desc.getType()).isEqualTo(String.class); } @Test public void forObjectNullTypeDescriptor() { TypeDescriptor desc = TypeDescriptor.forObject(null); - assertNull(desc); + assertThat((Object) desc).isNull(); } @Test public void nestedMethodParameterType2Levels() throws Exception { TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test2", List.class), 0), 2); - assertEquals(String.class, t1.getType()); + assertThat(t1.getType()).isEqualTo(String.class); } @Test public void nestedMethodParameterTypeMap() throws Exception { TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test3", Map.class), 0), 1); - assertEquals(String.class, t1.getType()); + assertThat(t1.getType()).isEqualTo(String.class); } @Test public void nestedMethodParameterTypeMapTwoLevels() throws Exception { TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test4", List.class), 0), 2); - assertEquals(String.class, t1.getType()); + assertThat(t1.getType()).isEqualTo(String.class); } @Test @@ -425,13 +418,13 @@ public class TypeDescriptorTests { @Test public void nestedTooManyLevels() throws Exception { TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test4", List.class), 0), 3); - assertNull(t1); + assertThat((Object) t1).isNull(); } @Test public void nestedMethodParameterTypeNotNestable() throws Exception { TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test5", String.class), 0), 2); - assertNull(t1); + assertThat((Object) t1).isNull(); } @Test @@ -443,89 +436,89 @@ public class TypeDescriptorTests { @Test public void nestedNotParameterized() throws Exception { TypeDescriptor t1 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test6", List.class), 0), 1); - assertEquals(List.class,t1.getType()); - assertEquals("java.util.List", t1.toString()); + assertThat(t1.getType()).isEqualTo(List.class); + assertThat(t1.toString()).isEqualTo("java.util.List"); TypeDescriptor t2 = TypeDescriptor.nested(new MethodParameter(getClass().getMethod("test6", List.class), 0), 2); - assertNull(t2); + assertThat((Object) t2).isNull(); } @Test public void nestedFieldTypeMapTwoLevels() throws Exception { TypeDescriptor t1 = TypeDescriptor.nested(getClass().getField("test4"), 2); - assertEquals(String.class, t1.getType()); + assertThat(t1.getType()).isEqualTo(String.class); } @Test public void nestedPropertyTypeMapTwoLevels() throws Exception { Property property = new Property(getClass(), getClass().getMethod("getTest4"), getClass().getMethod("setTest4", List.class)); TypeDescriptor t1 = TypeDescriptor.nested(property, 2); - assertEquals(String.class, t1.getType()); + assertThat(t1.getType()).isEqualTo(String.class); } @Test public void collection() { TypeDescriptor desc = TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Integer.class)); - assertEquals(List.class, desc.getType()); - assertEquals(List.class, desc.getObjectType()); - assertEquals("java.util.List", desc.getName()); - assertEquals("java.util.List", desc.toString()); - assertTrue(!desc.isPrimitive()); - assertEquals(0, desc.getAnnotations().length); - assertTrue(desc.isCollection()); - assertFalse(desc.isArray()); - assertEquals(Integer.class, desc.getElementTypeDescriptor().getType()); - assertEquals(TypeDescriptor.valueOf(Integer.class), desc.getElementTypeDescriptor()); - assertFalse(desc.isMap()); + assertThat(desc.getType()).isEqualTo(List.class); + assertThat(desc.getObjectType()).isEqualTo(List.class); + assertThat(desc.getName()).isEqualTo("java.util.List"); + assertThat(desc.toString()).isEqualTo("java.util.List"); + assertThat(!desc.isPrimitive()).isTrue(); + assertThat(desc.getAnnotations().length).isEqualTo(0); + assertThat(desc.isCollection()).isTrue(); + assertThat(desc.isArray()).isFalse(); + assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(desc.getElementTypeDescriptor()).isEqualTo(TypeDescriptor.valueOf(Integer.class)); + assertThat(desc.isMap()).isFalse(); } @Test public void collectionNested() { TypeDescriptor desc = TypeDescriptor.collection(List.class, TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Integer.class))); - assertEquals(List.class, desc.getType()); - assertEquals(List.class, desc.getObjectType()); - assertEquals("java.util.List", desc.getName()); - assertEquals("java.util.List>", desc.toString()); - assertTrue(!desc.isPrimitive()); - assertEquals(0, desc.getAnnotations().length); - assertTrue(desc.isCollection()); - assertFalse(desc.isArray()); - assertEquals(List.class, desc.getElementTypeDescriptor().getType()); - assertEquals(TypeDescriptor.valueOf(Integer.class), desc.getElementTypeDescriptor().getElementTypeDescriptor()); - assertFalse(desc.isMap()); + assertThat(desc.getType()).isEqualTo(List.class); + assertThat(desc.getObjectType()).isEqualTo(List.class); + assertThat(desc.getName()).isEqualTo("java.util.List"); + assertThat(desc.toString()).isEqualTo("java.util.List>"); + assertThat(!desc.isPrimitive()).isTrue(); + assertThat(desc.getAnnotations().length).isEqualTo(0); + assertThat(desc.isCollection()).isTrue(); + assertThat(desc.isArray()).isFalse(); + assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(List.class); + assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor()).isEqualTo(TypeDescriptor.valueOf(Integer.class)); + assertThat(desc.isMap()).isFalse(); } @Test public void map() { TypeDescriptor desc = TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class)); - assertEquals(Map.class, desc.getType()); - assertEquals(Map.class, desc.getObjectType()); - assertEquals("java.util.Map", desc.getName()); - assertEquals("java.util.Map", desc.toString()); - assertTrue(!desc.isPrimitive()); - assertEquals(0, desc.getAnnotations().length); - assertFalse(desc.isCollection()); - assertFalse(desc.isArray()); - assertTrue(desc.isMap()); - assertEquals(String.class, desc.getMapKeyTypeDescriptor().getType()); - assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getType()); + assertThat(desc.getType()).isEqualTo(Map.class); + assertThat(desc.getObjectType()).isEqualTo(Map.class); + assertThat(desc.getName()).isEqualTo("java.util.Map"); + assertThat(desc.toString()).isEqualTo("java.util.Map"); + assertThat(!desc.isPrimitive()).isTrue(); + assertThat(desc.getAnnotations().length).isEqualTo(0); + assertThat(desc.isCollection()).isFalse(); + assertThat(desc.isArray()).isFalse(); + assertThat(desc.isMap()).isTrue(); + assertThat(desc.getMapKeyTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(desc.getMapValueTypeDescriptor().getType()).isEqualTo(Integer.class); } @Test public void mapNested() { TypeDescriptor desc = TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class))); - assertEquals(Map.class, desc.getType()); - assertEquals(Map.class, desc.getObjectType()); - assertEquals("java.util.Map", desc.getName()); - assertEquals("java.util.Map>", desc.toString()); - assertTrue(!desc.isPrimitive()); - assertEquals(0, desc.getAnnotations().length); - assertFalse(desc.isCollection()); - assertFalse(desc.isArray()); - assertTrue(desc.isMap()); - assertEquals(String.class, desc.getMapKeyTypeDescriptor().getType()); - assertEquals(String.class, desc.getMapValueTypeDescriptor().getMapKeyTypeDescriptor().getType()); - assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getMapValueTypeDescriptor().getType()); + assertThat(desc.getType()).isEqualTo(Map.class); + assertThat(desc.getObjectType()).isEqualTo(Map.class); + assertThat(desc.getName()).isEqualTo("java.util.Map"); + assertThat(desc.toString()).isEqualTo("java.util.Map>"); + assertThat(!desc.isPrimitive()).isTrue(); + assertThat(desc.getAnnotations().length).isEqualTo(0); + assertThat(desc.isCollection()).isFalse(); + assertThat(desc.isArray()).isFalse(); + assertThat(desc.isMap()).isTrue(); + assertThat(desc.getMapKeyTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(desc.getMapValueTypeDescriptor().getMapKeyTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(desc.getMapValueTypeDescriptor().getMapValueTypeDescriptor().getType()).isEqualTo(Integer.class); } @Test @@ -533,7 +526,7 @@ public class TypeDescriptorTests { TypeDescriptor desc = TypeDescriptor.valueOf(Number.class); Integer value = Integer.valueOf(3); desc = desc.narrow(value); - assertEquals(Integer.class, desc.getType()); + assertThat(desc.getType()).isEqualTo(Integer.class); } @Test @@ -541,17 +534,17 @@ public class TypeDescriptorTests { TypeDescriptor desc = TypeDescriptor.valueOf(List.class); Integer value = Integer.valueOf(3); desc = desc.elementTypeDescriptor(value); - assertEquals(Integer.class, desc.getType()); + assertThat(desc.getType()).isEqualTo(Integer.class); } @Test public void elementTypePreserveContext() throws Exception { TypeDescriptor desc = new TypeDescriptor(getClass().getField("listPreserveContext")); - assertEquals(Integer.class, desc.getElementTypeDescriptor().getElementTypeDescriptor().getType()); + assertThat(desc.getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class); List value = new ArrayList<>(3); desc = desc.elementTypeDescriptor(value); - assertEquals(Integer.class, desc.getElementTypeDescriptor().getType()); - assertNotNull(desc.getAnnotation(FieldAnnotation.class)); + assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(desc.getAnnotation(FieldAnnotation.class)).isNotNull(); } @Test @@ -559,17 +552,17 @@ public class TypeDescriptorTests { TypeDescriptor desc = TypeDescriptor.valueOf(Map.class); Integer value = Integer.valueOf(3); desc = desc.getMapKeyTypeDescriptor(value); - assertEquals(Integer.class, desc.getType()); + assertThat(desc.getType()).isEqualTo(Integer.class); } @Test public void mapKeyTypePreserveContext() throws Exception { TypeDescriptor desc = new TypeDescriptor(getClass().getField("mapPreserveContext")); - assertEquals(Integer.class, desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType()); + assertThat(desc.getMapKeyTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class); List value = new ArrayList<>(3); desc = desc.getMapKeyTypeDescriptor(value); - assertEquals(Integer.class, desc.getElementTypeDescriptor().getType()); - assertNotNull(desc.getAnnotation(FieldAnnotation.class)); + assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(desc.getAnnotation(FieldAnnotation.class)).isNotNull(); } @Test @@ -577,17 +570,17 @@ public class TypeDescriptorTests { TypeDescriptor desc = TypeDescriptor.valueOf(Map.class); Integer value = Integer.valueOf(3); desc = desc.getMapValueTypeDescriptor(value); - assertEquals(Integer.class, desc.getType()); + assertThat(desc.getType()).isEqualTo(Integer.class); } @Test public void mapValueTypePreserveContext() throws Exception { TypeDescriptor desc = new TypeDescriptor(getClass().getField("mapPreserveContext")); - assertEquals(Integer.class, desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()); + assertThat(desc.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class); List value = new ArrayList<>(3); desc = desc.getMapValueTypeDescriptor(value); - assertEquals(Integer.class, desc.getElementTypeDescriptor().getType()); - assertNotNull(desc.getAnnotation(FieldAnnotation.class)); + assertThat(desc.getElementTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(desc.getAnnotation(FieldAnnotation.class)).isNotNull(); } @Test @@ -600,74 +593,73 @@ public class TypeDescriptorTests { TypeDescriptor t6 = TypeDescriptor.valueOf(List.class); TypeDescriptor t7 = TypeDescriptor.valueOf(Map.class); TypeDescriptor t8 = TypeDescriptor.valueOf(Map.class); - assertEquals(t1, t2); - assertEquals(t3, t4); - assertEquals(t5, t6); - assertEquals(t7, t8); + assertThat(t2).isEqualTo(t1); + assertThat(t4).isEqualTo(t3); + assertThat(t6).isEqualTo(t5); + assertThat(t8).isEqualTo(t7); TypeDescriptor t9 = new TypeDescriptor(getClass().getField("listField")); TypeDescriptor t10 = new TypeDescriptor(getClass().getField("listField")); - assertEquals(t9, t10); + assertThat(t10).isEqualTo(t9); TypeDescriptor t11 = new TypeDescriptor(getClass().getField("mapField")); TypeDescriptor t12 = new TypeDescriptor(getClass().getField("mapField")); - assertEquals(t11, t12); + assertThat(t12).isEqualTo(t11); MethodParameter testAnnotatedMethod = new MethodParameter(getClass().getMethod("testAnnotatedMethod", String.class), 0); TypeDescriptor t13 = new TypeDescriptor(testAnnotatedMethod); TypeDescriptor t14 = new TypeDescriptor(testAnnotatedMethod); - assertEquals(t13, t14); + assertThat(t14).isEqualTo(t13); TypeDescriptor t15 = new TypeDescriptor(testAnnotatedMethod); TypeDescriptor t16 = new TypeDescriptor(new MethodParameter(getClass().getMethod("testAnnotatedMethodDifferentAnnotationValue", String.class), 0)); - assertNotEquals(t15, t16); + assertThat(t16).isNotEqualTo(t15); TypeDescriptor t17 = new TypeDescriptor(testAnnotatedMethod); TypeDescriptor t18 = new TypeDescriptor(new MethodParameter(getClass().getMethod("test5", String.class), 0)); - assertNotEquals(t17, t18); + assertThat(t18).isNotEqualTo(t17); } @Test public void isAssignableTypes() { - assertTrue(TypeDescriptor.valueOf(Integer.class).isAssignableTo(TypeDescriptor.valueOf(Number.class))); - assertFalse(TypeDescriptor.valueOf(Number.class).isAssignableTo(TypeDescriptor.valueOf(Integer.class))); - assertFalse(TypeDescriptor.valueOf(String.class).isAssignableTo(TypeDescriptor.valueOf(String[].class))); + assertThat(TypeDescriptor.valueOf(Integer.class).isAssignableTo(TypeDescriptor.valueOf(Number.class))).isTrue(); + assertThat(TypeDescriptor.valueOf(Number.class).isAssignableTo(TypeDescriptor.valueOf(Integer.class))).isFalse(); + assertThat(TypeDescriptor.valueOf(String.class).isAssignableTo(TypeDescriptor.valueOf(String[].class))).isFalse(); } @Test public void isAssignableElementTypes() throws Exception { - assertTrue(new TypeDescriptor(getClass().getField("listField")).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))); - assertTrue(new TypeDescriptor(getClass().getField("notGenericList")).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))); - assertTrue(new TypeDescriptor(getClass().getField("listField")).isAssignableTo(new TypeDescriptor(getClass().getField("notGenericList")))); - assertFalse(new TypeDescriptor(getClass().getField("isAssignableElementTypes")).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))); - assertTrue(TypeDescriptor.valueOf(List.class).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))); + assertThat(new TypeDescriptor(getClass().getField("listField")).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))).isTrue(); + assertThat(new TypeDescriptor(getClass().getField("notGenericList")).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))).isTrue(); + assertThat(new TypeDescriptor(getClass().getField("listField")).isAssignableTo(new TypeDescriptor(getClass().getField("notGenericList")))).isTrue(); + assertThat(new TypeDescriptor(getClass().getField("isAssignableElementTypes")).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))).isFalse(); + assertThat(TypeDescriptor.valueOf(List.class).isAssignableTo(new TypeDescriptor(getClass().getField("listField")))).isTrue(); } @Test public void isAssignableMapKeyValueTypes() throws Exception { - assertTrue(new TypeDescriptor(getClass().getField("mapField")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))); - assertTrue(new TypeDescriptor(getClass().getField("notGenericMap")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))); - assertTrue(new TypeDescriptor(getClass().getField("mapField")).isAssignableTo(new TypeDescriptor(getClass().getField("notGenericMap")))); - assertFalse(new TypeDescriptor(getClass().getField("isAssignableMapKeyValueTypes")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))); - assertTrue(TypeDescriptor.valueOf(Map.class).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))); + assertThat(new TypeDescriptor(getClass().getField("mapField")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))).isTrue(); + assertThat(new TypeDescriptor(getClass().getField("notGenericMap")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))).isTrue(); + assertThat(new TypeDescriptor(getClass().getField("mapField")).isAssignableTo(new TypeDescriptor(getClass().getField("notGenericMap")))).isTrue(); + assertThat(new TypeDescriptor(getClass().getField("isAssignableMapKeyValueTypes")).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))).isFalse(); + assertThat(TypeDescriptor.valueOf(Map.class).isAssignableTo(new TypeDescriptor(getClass().getField("mapField")))).isTrue(); } @Test public void multiValueMap() throws Exception { TypeDescriptor td = new TypeDescriptor(getClass().getField("multiValueMap")); - assertTrue(td.isMap()); - assertEquals(String.class, td.getMapKeyTypeDescriptor().getType()); - assertEquals(List.class, td.getMapValueTypeDescriptor().getType()); - assertEquals(Integer.class, - td.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()); + assertThat(td.isMap()).isTrue(); + assertThat(td.getMapKeyTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(td.getMapValueTypeDescriptor().getType()).isEqualTo(List.class); + assertThat(td.getMapValueTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class); } @Test public void passDownGeneric() throws Exception { TypeDescriptor td = new TypeDescriptor(getClass().getField("passDownGeneric")); - assertEquals(List.class, td.getElementTypeDescriptor().getType()); - assertEquals(Set.class, td.getElementTypeDescriptor().getElementTypeDescriptor().getType()); - assertEquals(Integer.class, td.getElementTypeDescriptor().getElementTypeDescriptor().getElementTypeDescriptor().getType()); + assertThat(td.getElementTypeDescriptor().getType()).isEqualTo(List.class); + assertThat(td.getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Set.class); + assertThat(td.getElementTypeDescriptor().getElementTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class); } @Test @@ -676,7 +668,7 @@ public class TypeDescriptorTests { getClass().getMethod("setProperty", Map.class)); TypeDescriptor typeDescriptor = new TypeDescriptor(property); TypeDescriptor upCast = typeDescriptor.upcast(Object.class); - assertTrue(upCast.getAnnotation(MethodAnnotation1.class) != null); + assertThat(upCast.getAnnotation(MethodAnnotation1.class) != null).isTrue(); } @Test @@ -695,8 +687,8 @@ public class TypeDescriptorTests { class CustomSet extends HashSet { } - assertEquals(TypeDescriptor.valueOf(CustomSet.class).getElementTypeDescriptor(), TypeDescriptor.valueOf(String.class)); - assertEquals(TypeDescriptor.forObject(new CustomSet()).getElementTypeDescriptor(), TypeDescriptor.valueOf(String.class)); + assertThat(TypeDescriptor.valueOf(String.class)).isEqualTo(TypeDescriptor.valueOf(CustomSet.class).getElementTypeDescriptor()); + assertThat(TypeDescriptor.valueOf(String.class)).isEqualTo(TypeDescriptor.forObject(new CustomSet()).getElementTypeDescriptor()); } @Test @@ -705,10 +697,10 @@ public class TypeDescriptorTests { class CustomMap extends HashMap { } - assertEquals(TypeDescriptor.valueOf(CustomMap.class).getMapKeyTypeDescriptor(), TypeDescriptor.valueOf(String.class)); - assertEquals(TypeDescriptor.valueOf(CustomMap.class).getMapValueTypeDescriptor(), TypeDescriptor.valueOf(Integer.class)); - assertEquals(TypeDescriptor.forObject(new CustomMap()).getMapKeyTypeDescriptor(), TypeDescriptor.valueOf(String.class)); - assertEquals(TypeDescriptor.forObject(new CustomMap()).getMapValueTypeDescriptor(), TypeDescriptor.valueOf(Integer.class)); + assertThat(TypeDescriptor.valueOf(String.class)).isEqualTo(TypeDescriptor.valueOf(CustomMap.class).getMapKeyTypeDescriptor()); + assertThat(TypeDescriptor.valueOf(Integer.class)).isEqualTo(TypeDescriptor.valueOf(CustomMap.class).getMapValueTypeDescriptor()); + assertThat(TypeDescriptor.valueOf(String.class)).isEqualTo(TypeDescriptor.forObject(new CustomMap()).getMapKeyTypeDescriptor()); + assertThat(TypeDescriptor.valueOf(Integer.class)).isEqualTo(TypeDescriptor.forObject(new CustomMap()).getMapValueTypeDescriptor()); } @Test @@ -716,19 +708,19 @@ public class TypeDescriptorTests { TypeDescriptor mapType = TypeDescriptor.map( LinkedHashMap.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class)); TypeDescriptor arrayType = TypeDescriptor.array(mapType); - assertEquals(arrayType.getType(), LinkedHashMap[].class); - assertEquals(arrayType.getElementTypeDescriptor(), mapType); + assertThat(LinkedHashMap[].class).isEqualTo(arrayType.getType()); + assertThat(mapType).isEqualTo(arrayType.getElementTypeDescriptor()); } @Test public void createStringArray() throws Exception { TypeDescriptor arrayType = TypeDescriptor.array(TypeDescriptor.valueOf(String.class)); - assertEquals(arrayType, TypeDescriptor.valueOf(String[].class)); + assertThat(TypeDescriptor.valueOf(String[].class)).isEqualTo(arrayType); } @Test public void createNullArray() throws Exception { - assertNull(TypeDescriptor.array(null)); + assertThat((Object) TypeDescriptor.array(null)).isNull(); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/convert/converter/DefaultConversionServiceTests.java b/spring-core/src/test/java/org/springframework/core/convert/converter/DefaultConversionServiceTests.java index 0e24c037e19..b05c194f489 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/converter/DefaultConversionServiceTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/converter/DefaultConversionServiceTests.java @@ -58,13 +58,6 @@ import org.springframework.util.StopWatch; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -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 DefaultConversionService}. @@ -85,12 +78,12 @@ public class DefaultConversionServiceTests { @Test public void testStringToCharacter() { - assertEquals(Character.valueOf('1'), conversionService.convert("1", Character.class)); + assertThat(conversionService.convert("1", Character.class)).isEqualTo(Character.valueOf('1')); } @Test public void testStringToCharacterEmptyString() { - assertEquals(null, conversionService.convert("", Character.class)); + assertThat(conversionService.convert("", Character.class)).isEqualTo(null); } @Test @@ -101,34 +94,34 @@ public class DefaultConversionServiceTests { @Test public void testCharacterToString() { - assertEquals("3", conversionService.convert('3', String.class)); + assertThat(conversionService.convert('3', String.class)).isEqualTo("3"); } @Test public void testStringToBooleanTrue() { - assertEquals(true, conversionService.convert("true", Boolean.class)); - assertEquals(true, conversionService.convert("on", Boolean.class)); - assertEquals(true, conversionService.convert("yes", Boolean.class)); - assertEquals(true, conversionService.convert("1", Boolean.class)); - assertEquals(true, conversionService.convert("TRUE", Boolean.class)); - assertEquals(true, conversionService.convert("ON", Boolean.class)); - assertEquals(true, conversionService.convert("YES", Boolean.class)); + assertThat(conversionService.convert("true", Boolean.class)).isEqualTo(true); + assertThat(conversionService.convert("on", Boolean.class)).isEqualTo(true); + assertThat(conversionService.convert("yes", Boolean.class)).isEqualTo(true); + assertThat(conversionService.convert("1", Boolean.class)).isEqualTo(true); + assertThat(conversionService.convert("TRUE", Boolean.class)).isEqualTo(true); + assertThat(conversionService.convert("ON", Boolean.class)).isEqualTo(true); + assertThat(conversionService.convert("YES", Boolean.class)).isEqualTo(true); } @Test public void testStringToBooleanFalse() { - assertEquals(false, conversionService.convert("false", Boolean.class)); - assertEquals(false, conversionService.convert("off", Boolean.class)); - assertEquals(false, conversionService.convert("no", Boolean.class)); - assertEquals(false, conversionService.convert("0", Boolean.class)); - assertEquals(false, conversionService.convert("FALSE", Boolean.class)); - assertEquals(false, conversionService.convert("OFF", Boolean.class)); - assertEquals(false, conversionService.convert("NO", Boolean.class)); + assertThat(conversionService.convert("false", Boolean.class)).isEqualTo(false); + assertThat(conversionService.convert("off", Boolean.class)).isEqualTo(false); + assertThat(conversionService.convert("no", Boolean.class)).isEqualTo(false); + assertThat(conversionService.convert("0", Boolean.class)).isEqualTo(false); + assertThat(conversionService.convert("FALSE", Boolean.class)).isEqualTo(false); + assertThat(conversionService.convert("OFF", Boolean.class)).isEqualTo(false); + assertThat(conversionService.convert("NO", Boolean.class)).isEqualTo(false); } @Test public void testStringToBooleanEmptyString() { - assertEquals(null, conversionService.convert("", Boolean.class)); + assertThat(conversionService.convert("", Boolean.class)).isEqualTo(null); } @Test @@ -139,185 +132,185 @@ public class DefaultConversionServiceTests { @Test public void testBooleanToString() { - assertEquals("true", conversionService.convert(true, String.class)); + assertThat(conversionService.convert(true, String.class)).isEqualTo("true"); } @Test public void testStringToByte() { - assertEquals(Byte.valueOf("1"), conversionService.convert("1", Byte.class)); + assertThat(conversionService.convert("1", Byte.class)).isEqualTo((byte) 1); } @Test public void testByteToString() { - assertEquals("65", conversionService.convert("A".getBytes()[0], String.class)); + assertThat(conversionService.convert("A".getBytes()[0], String.class)).isEqualTo("65"); } @Test public void testStringToShort() { - assertEquals(Short.valueOf("1"), conversionService.convert("1", Short.class)); + assertThat(conversionService.convert("1", Short.class)).isEqualTo((short) 1); } @Test public void testShortToString() { short three = 3; - assertEquals("3", conversionService.convert(three, String.class)); + assertThat(conversionService.convert(three, String.class)).isEqualTo("3"); } @Test public void testStringToInteger() { - assertEquals(Integer.valueOf(1), conversionService.convert("1", Integer.class)); + assertThat(conversionService.convert("1", Integer.class)).isEqualTo((int) Integer.valueOf(1)); } @Test public void testIntegerToString() { - assertEquals("3", conversionService.convert(3, String.class)); + assertThat(conversionService.convert(3, String.class)).isEqualTo("3"); } @Test public void testStringToLong() { - assertEquals(Long.valueOf(1), conversionService.convert("1", Long.class)); + assertThat(conversionService.convert("1", Long.class)).isEqualTo(Long.valueOf(1)); } @Test public void testLongToString() { - assertEquals("3", conversionService.convert(3L, String.class)); + assertThat(conversionService.convert(3L, String.class)).isEqualTo("3"); } @Test public void testStringToFloat() { - assertEquals(Float.valueOf("1.0"), conversionService.convert("1.0", Float.class)); + assertThat(conversionService.convert("1.0", Float.class)).isEqualTo(Float.valueOf("1.0")); } @Test public void testFloatToString() { - assertEquals("1.0", conversionService.convert(Float.valueOf("1.0"), String.class)); + assertThat(conversionService.convert(Float.valueOf("1.0"), String.class)).isEqualTo("1.0"); } @Test public void testStringToDouble() { - assertEquals(Double.valueOf("1.0"), conversionService.convert("1.0", Double.class)); + assertThat(conversionService.convert("1.0", Double.class)).isEqualTo(Double.valueOf("1.0")); } @Test public void testDoubleToString() { - assertEquals("1.0", conversionService.convert(Double.valueOf("1.0"), String.class)); + assertThat(conversionService.convert(Double.valueOf("1.0"), String.class)).isEqualTo("1.0"); } @Test public void testStringToBigInteger() { - assertEquals(new BigInteger("1"), conversionService.convert("1", BigInteger.class)); + assertThat(conversionService.convert("1", BigInteger.class)).isEqualTo(new BigInteger("1")); } @Test public void testBigIntegerToString() { - assertEquals("100", conversionService.convert(new BigInteger("100"), String.class)); + assertThat(conversionService.convert(new BigInteger("100"), String.class)).isEqualTo("100"); } @Test public void testStringToBigDecimal() { - assertEquals(new BigDecimal("1.0"), conversionService.convert("1.0", BigDecimal.class)); + assertThat(conversionService.convert("1.0", BigDecimal.class)).isEqualTo(new BigDecimal("1.0")); } @Test public void testBigDecimalToString() { - assertEquals("100.00", conversionService.convert(new BigDecimal("100.00"), String.class)); + assertThat(conversionService.convert(new BigDecimal("100.00"), String.class)).isEqualTo("100.00"); } @Test public void testStringToNumber() { - assertEquals(new BigDecimal("1.0"), conversionService.convert("1.0", Number.class)); + assertThat(conversionService.convert("1.0", Number.class)).isEqualTo(new BigDecimal("1.0")); } @Test public void testStringToNumberEmptyString() { - assertEquals(null, conversionService.convert("", Number.class)); + assertThat(conversionService.convert("", Number.class)).isEqualTo(null); } @Test public void testStringToEnum() { - assertEquals(Foo.BAR, conversionService.convert("BAR", Foo.class)); + assertThat(conversionService.convert("BAR", Foo.class)).isEqualTo(Foo.BAR); } @Test public void testStringToEnumWithSubclass() { - assertEquals(SubFoo.BAZ, conversionService.convert("BAZ", SubFoo.BAR.getClass())); + assertThat(conversionService.convert("BAZ", SubFoo.BAR.getClass())).isEqualTo(SubFoo.BAZ); } @Test public void testStringToEnumEmptyString() { - assertEquals(null, conversionService.convert("", Foo.class)); + assertThat(conversionService.convert("", Foo.class)).isEqualTo(null); } @Test public void testEnumToString() { - assertEquals("BAR", conversionService.convert(Foo.BAR, String.class)); + assertThat(conversionService.convert(Foo.BAR, String.class)).isEqualTo("BAR"); } @Test public void testIntegerToEnum() { - assertEquals(Foo.BAR, conversionService.convert(0, Foo.class)); + assertThat(conversionService.convert(0, Foo.class)).isEqualTo(Foo.BAR); } @Test public void testIntegerToEnumWithSubclass() { - assertEquals(SubFoo.BAZ, conversionService.convert(1, SubFoo.BAR.getClass())); + assertThat(conversionService.convert(1, SubFoo.BAR.getClass())).isEqualTo(SubFoo.BAZ); } @Test public void testIntegerToEnumNull() { - assertEquals(null, conversionService.convert(null, Foo.class)); + assertThat(conversionService.convert(null, Foo.class)).isEqualTo(null); } @Test public void testEnumToInteger() { - assertEquals(Integer.valueOf(0), conversionService.convert(Foo.BAR, Integer.class)); + assertThat(conversionService.convert(Foo.BAR, Integer.class)).isEqualTo((int) Integer.valueOf(0)); } @Test public void testStringToEnumSet() throws Exception { - assertEquals(EnumSet.of(Foo.BAR), conversionService.convert("BAR", TypeDescriptor.valueOf(String.class), - new TypeDescriptor(getClass().getField("enumSet")))); + assertThat(conversionService.convert("BAR", TypeDescriptor.valueOf(String.class), + new TypeDescriptor(getClass().getField("enumSet")))).isEqualTo(EnumSet.of(Foo.BAR)); } @Test public void testStringToLocale() { - assertEquals(Locale.ENGLISH, conversionService.convert("en", Locale.class)); + assertThat(conversionService.convert("en", Locale.class)).isEqualTo(Locale.ENGLISH); } @Test public void testStringToLocaleWithCountry() { - assertEquals(Locale.US, conversionService.convert("en_US", Locale.class)); + assertThat(conversionService.convert("en_US", Locale.class)).isEqualTo(Locale.US); } @Test public void testStringToLocaleWithLanguageTag() { - assertEquals(Locale.US, conversionService.convert("en-US", Locale.class)); + assertThat(conversionService.convert("en-US", Locale.class)).isEqualTo(Locale.US); } @Test public void testStringToCharset() { - assertEquals(StandardCharsets.UTF_8, conversionService.convert("UTF-8", Charset.class)); + assertThat(conversionService.convert("UTF-8", Charset.class)).isEqualTo(StandardCharsets.UTF_8); } @Test public void testCharsetToString() { - assertEquals("UTF-8", conversionService.convert(StandardCharsets.UTF_8, String.class)); + assertThat(conversionService.convert(StandardCharsets.UTF_8, String.class)).isEqualTo("UTF-8"); } @Test public void testStringToCurrency() { - assertEquals(Currency.getInstance("EUR"), conversionService.convert("EUR", Currency.class)); + assertThat(conversionService.convert("EUR", Currency.class)).isEqualTo(Currency.getInstance("EUR")); } @Test public void testCurrencyToString() { - assertEquals("USD", conversionService.convert(Currency.getInstance("USD"), String.class)); + assertThat(conversionService.convert(Currency.getInstance("USD"), String.class)).isEqualTo("USD"); } @Test public void testStringToString() { String str = "test"; - assertSame(str, conversionService.convert(str, String.class)); + assertThat(conversionService.convert(str, String.class)).isSameAs(str); } @Test @@ -325,12 +318,12 @@ public class DefaultConversionServiceTests { UUID uuid = UUID.randomUUID(); String convertToString = conversionService.convert(uuid, String.class); UUID convertToUUID = conversionService.convert(convertToString, UUID.class); - assertEquals(uuid, convertToUUID); + assertThat(convertToUUID).isEqualTo(uuid); } @Test public void testNumberToNumber() { - assertEquals(Long.valueOf(1), conversionService.convert(1, Long.class)); + assertThat(conversionService.convert(1, Long.class)).isEqualTo(Long.valueOf(1)); } @Test @@ -341,12 +334,12 @@ public class DefaultConversionServiceTests { @Test public void testNumberToCharacter() { - assertEquals(Character.valueOf('A'), conversionService.convert(65, Character.class)); + assertThat(conversionService.convert(65, Character.class)).isEqualTo(Character.valueOf('A')); } @Test public void testCharacterToNumber() { - assertEquals(Integer.valueOf(65), conversionService.convert('A', Integer.class)); + assertThat(conversionService.convert('A', Integer.class)).isEqualTo(65); } // collection conversion @@ -354,9 +347,9 @@ public class DefaultConversionServiceTests { @Test public void convertArrayToCollectionInterface() { List result = conversionService.convert(new String[] {"1", "2", "3"}, List.class); - assertEquals("1", result.get(0)); - assertEquals("2", result.get(1)); - assertEquals("3", result.get(2)); + assertThat(result.get(0)).isEqualTo("1"); + assertThat(result.get(1)).isEqualTo("2"); + assertThat(result.get(2)).isEqualTo("3"); } @Test @@ -364,9 +357,9 @@ public class DefaultConversionServiceTests { @SuppressWarnings("unchecked") List result = (List) conversionService.convert(new String[] {"1", "2", "3"}, TypeDescriptor .valueOf(String[].class), new TypeDescriptor(getClass().getDeclaredField("genericList"))); - assertEquals(Integer.valueOf(1), result.get(0)); - assertEquals(Integer.valueOf(2), result.get(1)); - assertEquals(Integer.valueOf(3), result.get(2)); + assertThat((int) result.get(0)).isEqualTo((int) Integer.valueOf(1)); + assertThat((int) result.get(1)).isEqualTo((int) Integer.valueOf(2)); + assertThat((int) result.get(2)).isEqualTo((int) Integer.valueOf(3)); } @Test @@ -376,7 +369,7 @@ public class DefaultConversionServiceTests { Stream result = (Stream) this.conversionService.convert(source, TypeDescriptor.valueOf(String[].class), new TypeDescriptor(getClass().getDeclaredField("genericStream"))); - assertEquals(8, result.mapToInt(x -> x).sum()); + assertThat(result.mapToInt(x -> x).sum()).isEqualTo(8); } @Test @@ -387,17 +380,17 @@ public class DefaultConversionServiceTests { List colors = (List) conversionService.convert(new String[] {"ffffff", "#000000"}, TypeDescriptor.valueOf(String[].class), new TypeDescriptor(new MethodParameter(getClass().getMethod("handlerMethod", List.class), 0))); - assertEquals(2, colors.size()); - assertEquals(Color.WHITE, colors.get(0)); - assertEquals(Color.BLACK, colors.get(1)); + assertThat(colors.size()).isEqualTo(2); + assertThat(colors.get(0)).isEqualTo(Color.WHITE); + assertThat(colors.get(1)).isEqualTo(Color.BLACK); } @Test public void convertArrayToCollectionImpl() { LinkedList result = conversionService.convert(new String[] {"1", "2", "3"}, LinkedList.class); - assertEquals("1", result.get(0)); - assertEquals("2", result.get(1)); - assertEquals("3", result.get(2)); + assertThat(result.get(0)).isEqualTo("1"); + assertThat(result.get(1)).isEqualTo("2"); + assertThat(result.get(2)).isEqualTo("3"); } @Test @@ -409,87 +402,87 @@ public class DefaultConversionServiceTests { @Test public void convertArrayToString() { String result = conversionService.convert(new String[] {"1", "2", "3"}, String.class); - assertEquals("1,2,3", result); + assertThat(result).isEqualTo("1,2,3"); } @Test public void convertArrayToStringWithElementConversion() { String result = conversionService.convert(new Integer[] {1, 2, 3}, String.class); - assertEquals("1,2,3", result); + assertThat(result).isEqualTo("1,2,3"); } @Test public void convertEmptyArrayToString() { String result = conversionService.convert(new String[0], String.class); - assertEquals("", result); + assertThat(result).isEqualTo(""); } @Test public void convertStringToArray() { String[] result = conversionService.convert("1,2,3", String[].class); - assertEquals(3, result.length); - assertEquals("1", result[0]); - assertEquals("2", result[1]); - assertEquals("3", result[2]); + assertThat(result.length).isEqualTo(3); + assertThat(result[0]).isEqualTo("1"); + assertThat(result[1]).isEqualTo("2"); + assertThat(result[2]).isEqualTo("3"); } @Test public void convertStringToArrayWithElementConversion() { Integer[] result = conversionService.convert("1,2,3", Integer[].class); - assertEquals(3, result.length); - assertEquals(Integer.valueOf(1), result[0]); - assertEquals(Integer.valueOf(2), result[1]); - assertEquals(Integer.valueOf(3), result[2]); + assertThat(result.length).isEqualTo(3); + assertThat((int) result[0]).isEqualTo((int) Integer.valueOf(1)); + assertThat((int) result[1]).isEqualTo((int) Integer.valueOf(2)); + assertThat((int) result[2]).isEqualTo((int) Integer.valueOf(3)); } @Test public void convertStringToPrimitiveArrayWithElementConversion() { int[] result = conversionService.convert("1,2,3", int[].class); - assertEquals(3, result.length); - assertEquals(1, result[0]); - assertEquals(2, result[1]); - assertEquals(3, result[2]); + assertThat(result.length).isEqualTo(3); + assertThat(result[0]).isEqualTo(1); + assertThat(result[1]).isEqualTo(2); + assertThat(result[2]).isEqualTo(3); } @Test public void convertEmptyStringToArray() { String[] result = conversionService.convert("", String[].class); - assertEquals(0, result.length); + assertThat(result.length).isEqualTo(0); } @Test public void convertArrayToObject() { Object[] array = new Object[] {3L}; Object result = conversionService.convert(array, Long.class); - assertEquals(3L, result); + assertThat(result).isEqualTo(3L); } @Test public void convertArrayToObjectWithElementConversion() { String[] array = new String[] {"3"}; Integer result = conversionService.convert(array, Integer.class); - assertEquals(Integer.valueOf(3), result); + assertThat((int) result).isEqualTo((int) Integer.valueOf(3)); } @Test public void convertArrayToObjectAssignableTargetType() { Long[] array = new Long[] {3L}; Long[] result = (Long[]) conversionService.convert(array, Object.class); - assertArrayEquals(array, result); + assertThat(result).isEqualTo(array); } @Test public void convertObjectToArray() { Object[] result = conversionService.convert(3L, Object[].class); - assertEquals(1, result.length); - assertEquals(3L, result[0]); + assertThat(result.length).isEqualTo(1); + assertThat(result[0]).isEqualTo(3L); } @Test public void convertObjectToArrayWithElementConversion() { Integer[] result = conversionService.convert(3L, Integer[].class); - assertEquals(1, result.length); - assertEquals(Integer.valueOf(3), result[0]); + assertThat(result.length).isEqualTo(1); + assertThat((int) result[0]).isEqualTo((int) Integer.valueOf(3)); } @Test @@ -499,9 +492,9 @@ public class DefaultConversionServiceTests { list.add("2"); list.add("3"); String[] result = conversionService.convert(list, String[].class); - assertEquals("1", result[0]); - assertEquals("2", result[1]); - assertEquals("3", result[2]); + assertThat(result[0]).isEqualTo("1"); + assertThat(result[1]).isEqualTo("2"); + assertThat(result[2]).isEqualTo("3"); } @Test @@ -511,16 +504,16 @@ public class DefaultConversionServiceTests { list.add("2"); list.add("3"); Integer[] result = conversionService.convert(list, Integer[].class); - assertEquals(Integer.valueOf(1), result[0]); - assertEquals(Integer.valueOf(2), result[1]); - assertEquals(Integer.valueOf(3), result[2]); + assertThat((int) result[0]).isEqualTo((int) Integer.valueOf(1)); + assertThat((int) result[1]).isEqualTo((int) Integer.valueOf(2)); + assertThat((int) result[2]).isEqualTo((int) Integer.valueOf(3)); } @Test public void convertCollectionToString() { List list = Arrays.asList("foo", "bar"); String result = conversionService.convert(list, String.class); - assertEquals("foo,bar", result); + assertThat(result).isEqualTo("foo,bar"); } @Test @@ -528,46 +521,46 @@ public class DefaultConversionServiceTests { List list = Arrays.asList(3, 5); String result = (String) conversionService.convert(list, new TypeDescriptor(getClass().getField("genericList")), TypeDescriptor.valueOf(String.class)); - assertEquals("3,5", result); + assertThat(result).isEqualTo("3,5"); } @Test public void convertStringToCollection() { List result = conversionService.convert("1,2,3", List.class); - assertEquals(3, result.size()); - assertEquals("1", result.get(0)); - assertEquals("2", result.get(1)); - assertEquals("3", result.get(2)); + assertThat(result.size()).isEqualTo(3); + assertThat(result.get(0)).isEqualTo("1"); + assertThat(result.get(1)).isEqualTo("2"); + assertThat(result.get(2)).isEqualTo("3"); } @Test public void convertStringToCollectionWithElementConversion() throws Exception { List result = (List) conversionService.convert("1,2,3", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericList"))); - assertEquals(3, result.size()); - assertEquals(1, result.get(0)); - assertEquals(2, result.get(1)); - assertEquals(3, result.get(2)); + assertThat(result.size()).isEqualTo(3); + assertThat(result.get(0)).isEqualTo(1); + assertThat(result.get(1)).isEqualTo(2); + assertThat(result.get(2)).isEqualTo(3); } @Test public void convertEmptyStringToCollection() { Collection result = conversionService.convert("", Collection.class); - assertEquals(0, result.size()); + assertThat(result.size()).isEqualTo(0); } @Test public void convertCollectionToObject() { List list = Collections.singletonList(3L); Long result = conversionService.convert(list, Long.class); - assertEquals(Long.valueOf(3), result); + assertThat(result).isEqualTo(Long.valueOf(3)); } @Test public void convertCollectionToObjectWithElementConversion() { List list = Collections.singletonList("3"); Integer result = conversionService.convert(list, Integer.class); - assertEquals(Integer.valueOf(3), result); + assertThat((int) result).isEqualTo((int) Integer.valueOf(3)); } @Test @@ -575,7 +568,7 @@ public class DefaultConversionServiceTests { Collection source = new ArrayList<>(); source.add("foo"); Object result = conversionService.convert(source, new TypeDescriptor(getClass().getField("assignableTarget"))); - assertEquals(source, result); + assertThat(result).isEqualTo(source); } @Test @@ -585,14 +578,14 @@ public class DefaultConversionServiceTests { source.add("B"); conversionService.addConverter(List.class, ListWrapper.class, ListWrapper::new); ListWrapper result = conversionService.convert(source, ListWrapper.class); - assertSame(source, result.getList()); + assertThat(result.getList()).isSameAs(source); } @Test public void convertObjectToCollection() { List result = conversionService.convert(3L, List.class); - assertEquals(1, result.size()); - assertEquals(3L, result.get(0)); + assertThat(result.size()).isEqualTo(1); + assertThat(result.get(0)).isEqualTo(3L); } @Test @@ -600,56 +593,56 @@ public class DefaultConversionServiceTests { @SuppressWarnings("unchecked") List result = (List) conversionService.convert(3L, TypeDescriptor.valueOf(Long.class), new TypeDescriptor(getClass().getField("genericList"))); - assertEquals(1, result.size()); - assertEquals(Integer.valueOf(3), result.get(0)); + assertThat(result.size()).isEqualTo(1); + assertThat((int) result.get(0)).isEqualTo((int) Integer.valueOf(3)); } @Test public void convertStringArrayToIntegerArray() { Integer[] result = conversionService.convert(new String[] {"1", "2", "3"}, Integer[].class); - assertEquals(Integer.valueOf(1), result[0]); - assertEquals(Integer.valueOf(2), result[1]); - assertEquals(Integer.valueOf(3), result[2]); + assertThat((int) result[0]).isEqualTo((int) Integer.valueOf(1)); + assertThat((int) result[1]).isEqualTo((int) Integer.valueOf(2)); + assertThat((int) result[2]).isEqualTo((int) Integer.valueOf(3)); } @Test public void convertStringArrayToIntArray() { int[] result = conversionService.convert(new String[] {"1", "2", "3"}, int[].class); - assertEquals(1, result[0]); - assertEquals(2, result[1]); - assertEquals(3, result[2]); + assertThat(result[0]).isEqualTo(1); + assertThat(result[1]).isEqualTo(2); + assertThat(result[2]).isEqualTo(3); } @Test public void convertIntegerArrayToIntegerArray() { Integer[] result = conversionService.convert(new Integer[] {1, 2, 3}, Integer[].class); - assertEquals(Integer.valueOf(1), result[0]); - assertEquals(Integer.valueOf(2), result[1]); - assertEquals(Integer.valueOf(3), result[2]); + assertThat((int) result[0]).isEqualTo((int) Integer.valueOf(1)); + assertThat((int) result[1]).isEqualTo((int) Integer.valueOf(2)); + assertThat((int) result[2]).isEqualTo((int) Integer.valueOf(3)); } @Test public void convertIntegerArrayToIntArray() { int[] result = conversionService.convert(new Integer[] {1, 2, 3}, int[].class); - assertEquals(1, result[0]); - assertEquals(2, result[1]); - assertEquals(3, result[2]); + assertThat(result[0]).isEqualTo(1); + assertThat(result[1]).isEqualTo(2); + assertThat(result[2]).isEqualTo(3); } @Test public void convertObjectArrayToIntegerArray() { Integer[] result = conversionService.convert(new Object[] {1, 2, 3}, Integer[].class); - assertEquals(Integer.valueOf(1), result[0]); - assertEquals(Integer.valueOf(2), result[1]); - assertEquals(Integer.valueOf(3), result[2]); + assertThat((int) result[0]).isEqualTo((int) Integer.valueOf(1)); + assertThat((int) result[1]).isEqualTo((int) Integer.valueOf(2)); + assertThat((int) result[2]).isEqualTo((int) Integer.valueOf(3)); } @Test public void convertObjectArrayToIntArray() { int[] result = conversionService.convert(new Object[] {1, 2, 3}, int[].class); - assertEquals(1, result[0]); - assertEquals(2, result[1]); - assertEquals(3, result[2]); + assertThat(result[0]).isEqualTo(1); + assertThat(result[1]).isEqualTo(2); + assertThat(result[2]).isEqualTo(3); } @Test @@ -662,31 +655,31 @@ public class DefaultConversionServiceTests { @Test public void convertArrayToArrayAssignable() { int[] result = conversionService.convert(new int[] {1, 2, 3}, int[].class); - assertEquals(1, result[0]); - assertEquals(2, result[1]); - assertEquals(3, result[2]); + assertThat(result[0]).isEqualTo(1); + assertThat(result[1]).isEqualTo(2); + assertThat(result[2]).isEqualTo(3); } @Test public void convertListOfNonStringifiable() { List list = Arrays.asList(new TestEntity(1L), new TestEntity(2L)); - assertTrue(conversionService.canConvert(list.getClass(), String.class)); + assertThat(conversionService.canConvert(list.getClass(), String.class)).isTrue(); try { conversionService.convert(list, String.class); } catch (ConversionFailedException ex) { - assertTrue(ex.getMessage().contains(list.getClass().getName())); - assertTrue(ex.getCause() instanceof ConverterNotFoundException); - assertTrue(ex.getCause().getMessage().contains(TestEntity.class.getName())); + assertThat(ex.getMessage().contains(list.getClass().getName())).isTrue(); + assertThat(ex.getCause() instanceof ConverterNotFoundException).isTrue(); + assertThat(ex.getCause().getMessage().contains(TestEntity.class.getName())).isTrue(); } } @Test public void convertListOfStringToString() { List list = Arrays.asList("Foo", "Bar"); - assertTrue(conversionService.canConvert(list.getClass(), String.class)); + assertThat(conversionService.canConvert(list.getClass(), String.class)).isTrue(); String result = conversionService.convert(list, String.class); - assertEquals("Foo,Bar", result); + assertThat(result).isEqualTo("Foo,Bar"); } @Test @@ -694,9 +687,9 @@ public class DefaultConversionServiceTests { List list1 = Arrays.asList("Foo", "Bar"); List list2 = Arrays.asList("Baz", "Boop"); List> list = Arrays.asList(list1, list2); - assertTrue(conversionService.canConvert(list.getClass(), String.class)); + assertThat(conversionService.canConvert(list.getClass(), String.class)).isTrue(); String result = conversionService.convert(list, String.class); - assertEquals("Foo,Bar,Baz,Boop", result); + assertThat(result).isEqualTo("Foo,Bar,Baz,Boop"); } @Test @@ -708,9 +701,9 @@ public class DefaultConversionServiceTests { @SuppressWarnings("unchecked") List bar = (List) conversionService.convert(foo, TypeDescriptor.forObject(foo), new TypeDescriptor(getClass().getField("genericList"))); - assertEquals(Integer.valueOf(1), bar.get(0)); - assertEquals(Integer.valueOf(2), bar.get(1)); - assertEquals(Integer.valueOf(3), bar.get(2)); + assertThat((int) bar.get(0)).isEqualTo((int) Integer.valueOf(1)); + assertThat((int) bar.get(1)).isEqualTo((int) Integer.valueOf(2)); + assertThat((int) bar.get(2)).isEqualTo((int) Integer.valueOf(3)); } @Test @@ -718,7 +711,7 @@ public class DefaultConversionServiceTests { @SuppressWarnings("unchecked") List bar = (List) conversionService.convert(null, TypeDescriptor.valueOf(LinkedHashSet.class), new TypeDescriptor(getClass().getField("genericList"))); - assertNull(bar); + assertThat((Object) bar).isNull(); } @Test @@ -730,9 +723,9 @@ public class DefaultConversionServiceTests { foo.add("3"); List bar = (List) conversionService.convert(foo, TypeDescriptor.valueOf(LinkedHashSet.class), TypeDescriptor .valueOf(List.class)); - assertEquals("1", bar.get(0)); - assertEquals("2", bar.get(1)); - assertEquals("3", bar.get(2)); + assertThat(bar.get(0)).isEqualTo("1"); + assertThat(bar.get(1)).isEqualTo("2"); + assertThat(bar.get(2)).isEqualTo("3"); } @Test @@ -745,10 +738,10 @@ public class DefaultConversionServiceTests { Collection values = map.values(); List bar = (List) conversionService.convert(values, TypeDescriptor.forObject(values), new TypeDescriptor(getClass().getField("genericList"))); - assertEquals(3, bar.size()); - assertEquals(Integer.valueOf(1), bar.get(0)); - assertEquals(Integer.valueOf(2), bar.get(1)); - assertEquals(Integer.valueOf(3), bar.get(2)); + assertThat(bar.size()).isEqualTo(3); + assertThat((int) bar.get(0)).isEqualTo((int) Integer.valueOf(1)); + assertThat((int) bar.get(1)).isEqualTo((int) Integer.valueOf(2)); + assertThat((int) bar.get(2)).isEqualTo((int) Integer.valueOf(3)); } @Test @@ -759,8 +752,8 @@ public class DefaultConversionServiceTests { @SuppressWarnings("unchecked") List integers = (List) conversionService.convert(strings, TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Integer.class))); - assertEquals(Integer.valueOf(3), integers.get(0)); - assertEquals(Integer.valueOf(9), integers.get(1)); + assertThat((int) integers.get(0)).isEqualTo((int) Integer.valueOf(3)); + assertThat((int) integers.get(1)).isEqualTo((int) Integer.valueOf(9)); } @Test @@ -771,18 +764,17 @@ public class DefaultConversionServiceTests { @SuppressWarnings("unchecked") Map map = (Map) conversionService.convert(foo, TypeDescriptor.forObject(foo), new TypeDescriptor(getClass().getField("genericMap"))); - assertEquals(Foo.BAR, map.get(1)); - assertEquals(Foo.BAZ, map.get(2)); + assertThat(map.get(1)).isEqualTo(Foo.BAR); + assertThat(map.get(2)).isEqualTo(Foo.BAZ); } @Test - @SuppressWarnings("rawtypes") public void convertHashMapValuesToList() { Map hashMap = new LinkedHashMap<>(); hashMap.put("1", 1); hashMap.put("2", 2); - List converted = conversionService.convert(hashMap.values(), List.class); - assertEquals(Arrays.asList(1, 2), converted); + List converted = conversionService.convert(hashMap.values(), List.class); + assertThat(converted).isEqualTo(Arrays.asList(1, 2)); } @Test @@ -793,8 +785,8 @@ public class DefaultConversionServiceTests { @SuppressWarnings("unchecked") Map integers = (Map) conversionService.convert(strings, TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(Integer.class), TypeDescriptor.valueOf(Integer.class))); - assertEquals(Integer.valueOf(9), integers.get(3)); - assertEquals(Integer.valueOf(31), integers.get(6)); + assertThat((int) integers.get(3)).isEqualTo((int) Integer.valueOf(9)); + assertThat((int) integers.get(6)).isEqualTo((int) Integer.valueOf(31)); } @Test @@ -803,25 +795,25 @@ public class DefaultConversionServiceTests { foo.setProperty("1", "BAR"); foo.setProperty("2", "BAZ"); String result = conversionService.convert(foo, String.class); - assertTrue(result.contains("1=BAR")); - assertTrue(result.contains("2=BAZ")); + assertThat(result.contains("1=BAR")).isTrue(); + assertThat(result.contains("2=BAZ")).isTrue(); } @Test public void convertStringToProperties() { Properties result = conversionService.convert("a=b\nc=2\nd=", Properties.class); - assertEquals(3, result.size()); - assertEquals("b", result.getProperty("a")); - assertEquals("2", result.getProperty("c")); - assertEquals("", result.getProperty("d")); + assertThat(result.size()).isEqualTo(3); + assertThat(result.getProperty("a")).isEqualTo("b"); + assertThat(result.getProperty("c")).isEqualTo("2"); + assertThat(result.getProperty("d")).isEqualTo(""); } @Test public void convertStringToPropertiesWithSpaces() { Properties result = conversionService.convert(" foo=bar\n bar=baz\n baz=boop", Properties.class); - assertEquals("bar", result.get("foo")); - assertEquals("baz", result.get("bar")); - assertEquals("boop", result.get("baz")); + assertThat(result.get("foo")).isEqualTo("bar"); + assertThat(result.get("bar")).isEqualTo("baz"); + assertThat(result.get("baz")).isEqualTo("boop"); } // generic object conversion @@ -829,60 +821,60 @@ public class DefaultConversionServiceTests { @Test public void convertObjectToStringWithValueOfMethodPresentUsingToString() { ISBN.reset(); - assertEquals("123456789", conversionService.convert(new ISBN("123456789"), String.class)); + assertThat(conversionService.convert(new ISBN("123456789"), String.class)).isEqualTo("123456789"); - assertEquals("constructor invocations", 1, ISBN.constructorCount); - assertEquals("valueOf() invocations", 0, ISBN.valueOfCount); - assertEquals("toString() invocations", 1, ISBN.toStringCount); + assertThat(ISBN.constructorCount).as("constructor invocations").isEqualTo(1); + assertThat(ISBN.valueOfCount).as("valueOf() invocations").isEqualTo(0); + assertThat(ISBN.toStringCount).as("toString() invocations").isEqualTo(1); } @Test public void convertObjectToObjectUsingValueOfMethod() { ISBN.reset(); - assertEquals(new ISBN("123456789"), conversionService.convert("123456789", ISBN.class)); + assertThat(conversionService.convert("123456789", ISBN.class)).isEqualTo(new ISBN("123456789")); - assertEquals("valueOf() invocations", 1, ISBN.valueOfCount); + assertThat(ISBN.valueOfCount).as("valueOf() invocations").isEqualTo(1); // valueOf() invokes the constructor - assertEquals("constructor invocations", 2, ISBN.constructorCount); - assertEquals("toString() invocations", 0, ISBN.toStringCount); + assertThat(ISBN.constructorCount).as("constructor invocations").isEqualTo(2); + assertThat(ISBN.toStringCount).as("toString() invocations").isEqualTo(0); } @Test public void convertObjectToStringUsingToString() { SSN.reset(); - assertEquals("123456789", conversionService.convert(new SSN("123456789"), String.class)); + assertThat(conversionService.convert(new SSN("123456789"), String.class)).isEqualTo("123456789"); - assertEquals("constructor invocations", 1, SSN.constructorCount); - assertEquals("toString() invocations", 1, SSN.toStringCount); + assertThat(SSN.constructorCount).as("constructor invocations").isEqualTo(1); + assertThat(SSN.toStringCount).as("toString() invocations").isEqualTo(1); } @Test public void convertObjectToObjectUsingObjectConstructor() { SSN.reset(); - assertEquals(new SSN("123456789"), conversionService.convert("123456789", SSN.class)); + assertThat(conversionService.convert("123456789", SSN.class)).isEqualTo(new SSN("123456789")); - assertEquals("constructor invocations", 2, SSN.constructorCount); - assertEquals("toString() invocations", 0, SSN.toStringCount); + assertThat(SSN.constructorCount).as("constructor invocations").isEqualTo(2); + assertThat(SSN.toStringCount).as("toString() invocations").isEqualTo(0); } @Test public void convertStringToTimezone() { - assertEquals("GMT+02:00", conversionService.convert("GMT+2", TimeZone.class).getID()); + assertThat(conversionService.convert("GMT+2", TimeZone.class).getID()).isEqualTo("GMT+02:00"); } @Test public void convertObjectToStringWithJavaTimeOfMethodPresent() { - assertTrue(conversionService.convert(ZoneId.of("GMT+1"), String.class).startsWith("GMT+")); + assertThat(conversionService.convert(ZoneId.of("GMT+1"), String.class).startsWith("GMT+")).isTrue(); } @Test public void convertObjectToStringNotSupported() { - assertFalse(conversionService.canConvert(TestEntity.class, String.class)); + assertThat(conversionService.canConvert(TestEntity.class, String.class)).isFalse(); } @Test public void convertObjectToObjectWithJavaTimeOfMethod() { - assertEquals(ZoneId.of("GMT+1"), conversionService.convert("GMT+1", ZoneId.class)); + assertThat(conversionService.convert("GMT+1", ZoneId.class)).isEqualTo(ZoneId.of("GMT+1")); } @Test @@ -894,20 +886,20 @@ public class DefaultConversionServiceTests { @Test public void convertObjectToObjectFinderMethod() { TestEntity e = conversionService.convert(1L, TestEntity.class); - assertEquals(Long.valueOf(1), e.getId()); + assertThat(e.getId()).isEqualTo(Long.valueOf(1)); } @Test public void convertObjectToObjectFinderMethodWithNull() { TestEntity entity = (TestEntity) conversionService.convert(null, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(TestEntity.class)); - assertNull(entity); + assertThat((Object) entity).isNull(); } @Test public void convertObjectToObjectFinderMethodWithIdConversion() { TestEntity entity = conversionService.convert("1", TestEntity.class); - assertEquals(Long.valueOf(1), entity.getId()); + assertThat(entity.getId()).isEqualTo(Long.valueOf(1)); } @Test @@ -936,7 +928,7 @@ public class DefaultConversionServiceTests { new String[] {"9", "10", "11", "12"}}; List converted = conversionService.convert(grid, List.class); String[][] convertedBack = conversionService.convert(converted, String[][].class); - assertArrayEquals(grid, convertedBack); + assertThat(convertedBack).isEqualTo(grid); } @Test @@ -944,8 +936,8 @@ public class DefaultConversionServiceTests { conversionService.addConverter(Byte.class, Byte.class, source -> (byte) (source + 1)); byte[] byteArray = new byte[] {1, 2, 3}; byte[] converted = conversionService.convert(byteArray, byte[].class); - assertNotSame(byteArray, converted); - assertArrayEquals(new byte[]{2, 3, 4}, converted); + assertThat(converted).isNotSameAs(byteArray); + assertThat(converted).isEqualTo(new byte[]{2, 3, 4}); } @Test @@ -955,22 +947,22 @@ public class DefaultConversionServiceTests { MethodParameter parameter = new MethodParameter(method, 0); TypeDescriptor descriptor = new TypeDescriptor(parameter); Object actual = conversionService.convert("1,2,3", TypeDescriptor.valueOf(String.class), descriptor); - assertEquals(Optional.class, actual.getClass()); - assertEquals(Arrays.asList(1, 2, 3), ((Optional>) actual).get()); + assertThat(actual.getClass()).isEqualTo(Optional.class); + assertThat(((Optional>) actual).get()).isEqualTo(Arrays.asList(1, 2, 3)); } @Test public void convertObjectToOptionalNull() { - assertSame(Optional.empty(), conversionService.convert(null, TypeDescriptor.valueOf(Object.class), - TypeDescriptor.valueOf(Optional.class))); - assertSame(Optional.empty(), conversionService.convert(null, Optional.class)); + assertThat(conversionService.convert(null, TypeDescriptor.valueOf(Object.class), + TypeDescriptor.valueOf(Optional.class))).isSameAs(Optional.empty()); + assertThat((Object) conversionService.convert(null, Optional.class)).isSameAs(Optional.empty()); } @Test public void convertExistingOptional() { - assertSame(Optional.empty(), conversionService.convert(Optional.empty(), TypeDescriptor.valueOf(Object.class), - TypeDescriptor.valueOf(Optional.class))); - assertSame(Optional.empty(), conversionService.convert(Optional.empty(), Optional.class)); + assertThat(conversionService.convert(Optional.empty(), TypeDescriptor.valueOf(Object.class), + TypeDescriptor.valueOf(Optional.class))).isSameAs(Optional.empty()); + assertThat((Object) conversionService.convert(Optional.empty(), Optional.class)).isSameAs(Optional.empty()); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/convert/support/CollectionToCollectionConverterTests.java b/spring-core/src/test/java/org/springframework/core/convert/support/CollectionToCollectionConverterTests.java index 97c01b27f9f..ca018890494 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/support/CollectionToCollectionConverterTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/support/CollectionToCollectionConverterTests.java @@ -40,11 +40,8 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; +import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Keith Donald @@ -69,20 +66,21 @@ public class CollectionToCollectionConverterTests { list.add("37"); TypeDescriptor sourceType = TypeDescriptor.forObject(list); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarListTarget")); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); try { conversionService.convert(list, sourceType, targetType); } catch (ConversionFailedException ex) { - assertTrue(ex.getCause() instanceof ConverterNotFoundException); + boolean condition = ex.getCause() instanceof ConverterNotFoundException; + assertThat(condition).isTrue(); } conversionService.addConverterFactory(new StringToNumberConverterFactory()); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); @SuppressWarnings("unchecked") List result = (List) conversionService.convert(list, sourceType, targetType); - assertFalse(list.equals(result)); - assertEquals(9, result.get(0).intValue()); - assertEquals(37, result.get(1).intValue()); + assertThat(list.equals(result)).isFalse(); + assertThat(result.get(0).intValue()).isEqualTo(9); + assertThat(result.get(1).intValue()).isEqualTo(37); } @Test @@ -92,8 +90,8 @@ public class CollectionToCollectionConverterTests { List list = new ArrayList<>(); TypeDescriptor sourceType = TypeDescriptor.forObject(list); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("emptyListTarget")); - assertTrue(conversionService.canConvert(sourceType, targetType)); - assertEquals(list, conversionService.convert(list, sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); + assertThat(conversionService.convert(list, sourceType, targetType)).isEqualTo(list); } @Test @@ -103,11 +101,11 @@ public class CollectionToCollectionConverterTests { List list = new ArrayList<>(); TypeDescriptor sourceType = TypeDescriptor.forObject(list); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("emptyListDifferentTarget")); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); @SuppressWarnings("unchecked") LinkedList result = (LinkedList) conversionService.convert(list, sourceType, targetType); - assertEquals(LinkedList.class, result.getClass()); - assertTrue(result.isEmpty()); + assertThat(result.getClass()).isEqualTo(LinkedList.class); + assertThat(result.isEmpty()).isTrue(); } @Test @@ -116,8 +114,8 @@ public class CollectionToCollectionConverterTests { list.add(Arrays.asList("9", "12")); list.add(Arrays.asList("37", "23")); conversionService.addConverter(new CollectionToObjectConverter(conversionService)); - assertTrue(conversionService.canConvert(List.class, List.class)); - assertSame(list, conversionService.convert(list, List.class)); + assertThat(conversionService.canConvert(List.class, List.class)).isTrue(); + assertThat((Object) conversionService.convert(list, List.class)).isSameAs(list); } @Test @@ -128,8 +126,8 @@ public class CollectionToCollectionConverterTests { array[1] = Arrays.asList("37", "23"); conversionService.addConverter(new ArrayToCollectionConverter(conversionService)); conversionService.addConverter(new CollectionToObjectConverter(conversionService)); - assertTrue(conversionService.canConvert(String[].class, List.class)); - assertEquals(Arrays.asList(array), conversionService.convert(array, List.class)); + assertThat(conversionService.canConvert(String[].class, List.class)).isTrue(); + assertThat(conversionService.convert(array, List.class)).isEqualTo(Arrays.asList(array)); } @Test @@ -143,12 +141,12 @@ public class CollectionToCollectionConverterTests { conversionService.addConverter(new CollectionToObjectConverter(conversionService)); TypeDescriptor sourceType = TypeDescriptor.forObject(list); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("objectToCollection")); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); List>> result = (List>>) conversionService.convert(list, sourceType, targetType); - assertEquals((Integer) 9, result.get(0).get(0).get(0)); - assertEquals((Integer) 12, result.get(0).get(1).get(0)); - assertEquals((Integer) 37, result.get(1).get(0).get(0)); - assertEquals((Integer) 23, result.get(1).get(1).get(0)); + assertThat(result.get(0).get(0).get(0)).isEqualTo((Integer) 9); + assertThat(result.get(0).get(1).get(0)).isEqualTo((Integer) 12); + assertThat(result.get(1).get(0).get(0)).isEqualTo((Integer) 37); + assertThat(result.get(1).get(1).get(0)).isEqualTo((Integer) 23); } @Test @@ -163,12 +161,12 @@ public class CollectionToCollectionConverterTests { conversionService.addConverter(new CollectionToObjectConverter(conversionService)); TypeDescriptor sourceType = TypeDescriptor.forObject(list); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("objectToCollection")); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); List>> result = (List>>) conversionService.convert(list, sourceType, targetType); - assertEquals((Integer) 9, result.get(0).get(0).get(0)); - assertEquals((Integer) 12, result.get(0).get(0).get(1)); - assertEquals((Integer) 37, result.get(1).get(0).get(0)); - assertEquals((Integer) 23, result.get(1).get(0).get(1)); + assertThat(result.get(0).get(0).get(0)).isEqualTo((Integer) 9); + assertThat(result.get(0).get(0).get(1)).isEqualTo((Integer) 12); + assertThat(result.get(1).get(0).get(0)).isEqualTo((Integer) 37); + assertThat(result.get(1).get(0).get(1)).isEqualTo((Integer) 23); } @Test @@ -196,15 +194,16 @@ public class CollectionToCollectionConverterTests { private void testCollectionConversionToArrayList(Collection aSource) { Object myConverted = (new CollectionToCollectionConverter(new GenericConversionService())).convert( aSource, TypeDescriptor.forObject(aSource), TypeDescriptor.forObject(new ArrayList())); - assertTrue(myConverted instanceof ArrayList); - assertEquals(aSource.size(), ((ArrayList) myConverted).size()); + boolean condition = myConverted instanceof ArrayList; + assertThat(condition).isTrue(); + assertThat(((ArrayList) myConverted).size()).isEqualTo(aSource.size()); } @Test public void listToCollectionNoCopyRequired() throws NoSuchFieldException { List input = new ArrayList<>(Arrays.asList("foo", "bar")); - assertSame(input, conversionService.convert(input, TypeDescriptor.forObject(input), - new TypeDescriptor(getClass().getField("wildcardCollection")))); + assertThat(conversionService.convert(input, TypeDescriptor.forObject(input), + new TypeDescriptor(getClass().getField("wildcardCollection")))).isSameAs(input); } @Test @@ -214,7 +213,7 @@ public class CollectionToCollectionConverterTests { resources.add(new FileSystemResource("test")); resources.add(new TestResource()); TypeDescriptor sourceType = TypeDescriptor.forObject(resources); - assertSame(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); + assertThat(conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))).isSameAs(resources); } @Test @@ -225,7 +224,7 @@ public class CollectionToCollectionConverterTests { resources.add(new FileSystemResource("test")); resources.add(new TestResource()); TypeDescriptor sourceType = TypeDescriptor.forObject(resources); - assertSame(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); + assertThat(conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))).isSameAs(resources); } @Test @@ -234,7 +233,7 @@ public class CollectionToCollectionConverterTests { resources.add(null); resources.add(null); TypeDescriptor sourceType = TypeDescriptor.forObject(resources); - assertSame(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); + assertThat(conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))).isSameAs(resources); } @Test @@ -263,8 +262,7 @@ public class CollectionToCollectionConverterTests { List list = new ArrayList<>(); list.add("A"); list.add("C"); - assertEquals(EnumSet.of(MyEnum.A, MyEnum.C), - conversionService.convert(list, TypeDescriptor.forObject(list), new TypeDescriptor(getClass().getField("enumSet")))); + assertThat(conversionService.convert(list, TypeDescriptor.forObject(list), new TypeDescriptor(getClass().getField("enumSet")))).isEqualTo(EnumSet.of(MyEnum.A, MyEnum.C)); } diff --git a/spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java b/spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java index 13fca1c0bf8..9d0dc8897e2 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java @@ -55,12 +55,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link GenericConversionService}. @@ -80,17 +74,17 @@ public class GenericConversionServiceTests { @Test public void canConvert() { - assertFalse(conversionService.canConvert(String.class, Integer.class)); + assertThat(conversionService.canConvert(String.class, Integer.class)).isFalse(); conversionService.addConverterFactory(new StringToNumberConverterFactory()); - assertTrue(conversionService.canConvert(String.class, Integer.class)); + assertThat(conversionService.canConvert(String.class, Integer.class)).isTrue(); } @Test public void canConvertAssignable() { - assertTrue(conversionService.canConvert(String.class, String.class)); - assertTrue(conversionService.canConvert(Integer.class, Number.class)); - assertTrue(conversionService.canConvert(boolean.class, boolean.class)); - assertTrue(conversionService.canConvert(boolean.class, Boolean.class)); + assertThat(conversionService.canConvert(String.class, String.class)).isTrue(); + assertThat(conversionService.canConvert(Integer.class, Number.class)).isTrue(); + assertThat(conversionService.canConvert(boolean.class, boolean.class)).isTrue(); + assertThat(conversionService.canConvert(boolean.class, Boolean.class)).isTrue(); } @Test @@ -107,19 +101,19 @@ public class GenericConversionServiceTests { @Test public void canConvertNullSourceType() { - assertTrue(conversionService.canConvert(null, Integer.class)); - assertTrue(conversionService.canConvert(null, TypeDescriptor.valueOf(Integer.class))); + assertThat(conversionService.canConvert(null, Integer.class)).isTrue(); + assertThat(conversionService.canConvert(null, TypeDescriptor.valueOf(Integer.class))).isTrue(); } @Test public void convert() { conversionService.addConverterFactory(new StringToNumberConverterFactory()); - assertEquals(Integer.valueOf(3), conversionService.convert("3", Integer.class)); + assertThat(conversionService.convert("3", Integer.class)).isEqualTo((int) Integer.valueOf(3)); } @Test public void convertNullSource() { - assertEquals(null, conversionService.convert(null, Integer.class)); + assertThat(conversionService.convert(null, Integer.class)).isEqualTo(null); } @Test @@ -142,8 +136,8 @@ public class GenericConversionServiceTests { @Test public void convertAssignableSource() { - assertEquals(Boolean.FALSE, conversionService.convert(false, boolean.class)); - assertEquals(Boolean.FALSE, conversionService.convert(false, Boolean.class)); + assertThat(conversionService.convert(false, boolean.class)).isEqualTo(Boolean.FALSE); + assertThat(conversionService.convert(false, Boolean.class)).isEqualTo(Boolean.FALSE); } @Test @@ -160,17 +154,17 @@ public class GenericConversionServiceTests { @Test public void sourceTypeIsVoid() { - assertFalse(conversionService.canConvert(void.class, String.class)); + assertThat(conversionService.canConvert(void.class, String.class)).isFalse(); } @Test public void targetTypeIsVoid() { - assertFalse(conversionService.canConvert(String.class, void.class)); + assertThat(conversionService.canConvert(String.class, void.class)).isFalse(); } @Test public void convertNull() { - assertNull(conversionService.convert(null, Integer.class)); + assertThat(conversionService.convert(null, Integer.class)).isNull(); } @Test @@ -207,7 +201,7 @@ public class GenericConversionServiceTests { } }); Integer result = conversionService.convert("3", Integer.class); - assertEquals(Integer.valueOf(3), result); + assertThat((int) result).isEqualTo((int) Integer.valueOf(3)); } // SPR-8718 @@ -220,29 +214,29 @@ public class GenericConversionServiceTests { @Test public void convertObjectToPrimitive() { - assertFalse(conversionService.canConvert(String.class, boolean.class)); + assertThat(conversionService.canConvert(String.class, boolean.class)).isFalse(); conversionService.addConverter(new StringToBooleanConverter()); - assertTrue(conversionService.canConvert(String.class, boolean.class)); + assertThat(conversionService.canConvert(String.class, boolean.class)).isTrue(); Boolean b = conversionService.convert("true", boolean.class); - assertTrue(b); - assertTrue(conversionService.canConvert(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(boolean.class))); + assertThat(b).isTrue(); + assertThat(conversionService.canConvert(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(boolean.class))).isTrue(); b = (Boolean) conversionService.convert("true", TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(boolean.class)); - assertTrue(b); + assertThat(b).isTrue(); } @Test public void convertObjectToPrimitiveViaConverterFactory() { - assertFalse(conversionService.canConvert(String.class, int.class)); + assertThat(conversionService.canConvert(String.class, int.class)).isFalse(); conversionService.addConverterFactory(new StringToNumberConverterFactory()); - assertTrue(conversionService.canConvert(String.class, int.class)); + assertThat(conversionService.canConvert(String.class, int.class)).isTrue(); Integer three = conversionService.convert("3", int.class); - assertEquals(3, three.intValue()); + assertThat(three.intValue()).isEqualTo(3); } @Test public void genericConverterDelegatingBackToConversionServiceConverterNotFound() { conversionService.addConverter(new ObjectToArrayConverter(conversionService)); - assertFalse(conversionService.canConvert(String.class, Integer[].class)); + assertThat(conversionService.canConvert(String.class, Integer[].class)).isFalse(); assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() -> conversionService.convert("3,4,5", Integer[].class)); } @@ -253,7 +247,7 @@ public class GenericConversionServiceTests { raw.add("one"); raw.add("two"); Object converted = conversionService.convert(raw, Iterable.class); - assertSame(raw, converted); + assertThat(converted).isSameAs(raw); } @Test @@ -262,7 +256,7 @@ public class GenericConversionServiceTests { raw.add("one"); raw.add("two"); Object converted = conversionService.convert(raw, Object.class); - assertSame(raw, converted); + assertThat(converted).isSameAs(raw); } @Test @@ -270,7 +264,7 @@ public class GenericConversionServiceTests { Map raw = new HashMap<>(); raw.put("key", "value"); Object converted = conversionService.convert(raw, Object.class); - assertSame(raw, converted); + assertThat(converted).isSameAs(raw); } @Test @@ -278,7 +272,7 @@ public class GenericConversionServiceTests { conversionService.addConverter(new MyBaseInterfaceToStringConverter()); conversionService.addConverter(new ObjectToStringConverter()); Object converted = conversionService.convert(new MyInterfaceImplementer(), String.class); - assertEquals("RESULT", converted); + assertThat(converted).isEqualTo("RESULT"); } @Test @@ -286,7 +280,7 @@ public class GenericConversionServiceTests { conversionService.addConverter(new MyBaseInterfaceToStringConverter()); conversionService.addConverter(new ArrayToArrayConverter(conversionService)); String[] converted = conversionService.convert(new MyInterface[] {new MyInterfaceImplementer()}, String[].class); - assertEquals("RESULT", converted[0]); + assertThat(converted[0]).isEqualTo("RESULT"); } @Test @@ -294,7 +288,7 @@ public class GenericConversionServiceTests { conversionService.addConverter(new MyBaseInterfaceToStringConverter()); conversionService.addConverter(new ArrayToArrayConverter(conversionService)); String[] converted = conversionService.convert(new MyInterfaceImplementer[] {new MyInterfaceImplementer()}, String[].class); - assertEquals("RESULT", converted[0]); + assertThat(converted[0]).isEqualTo("RESULT"); } @Test @@ -302,21 +296,21 @@ public class GenericConversionServiceTests { conversionService.addConverter(new MyStringArrayToResourceArrayConverter()); Resource[] converted = conversionService.convert(new String[] { "x1", "z3" }, Resource[].class); List descriptions = Arrays.stream(converted).map(Resource::getDescription).sorted(naturalOrder()).collect(toList()); - assertEquals(Arrays.asList("1", "3"), descriptions); + assertThat(descriptions).isEqualTo(Arrays.asList("1", "3")); } @Test public void testStringArrayToIntegerArray() { conversionService.addConverter(new MyStringArrayToIntegerArrayConverter()); Integer[] converted = conversionService.convert(new String[] {"x1", "z3"}, Integer[].class); - assertArrayEquals(new Integer[] { 1, 3 }, converted); + assertThat(converted).isEqualTo(new Integer[] { 1, 3 }); } @Test public void testStringToIntegerArray() { conversionService.addConverter(new MyStringToIntegerArrayConverter()); Integer[] converted = conversionService.convert("x1,z3", Integer[].class); - assertArrayEquals(new Integer[] { 1, 3 }, converted); + assertThat(converted).isEqualTo(new Integer[] { 1, 3 }); } @Test @@ -324,28 +318,28 @@ public class GenericConversionServiceTests { Map input = new LinkedHashMap<>(); input.put("key", "value"); Object converted = conversionService.convert(input, TypeDescriptor.forObject(input), new TypeDescriptor(getClass().getField("wildcardMap"))); - assertEquals(input, converted); + assertThat(converted).isEqualTo(input); } @Test public void testStringToString() { String value = "myValue"; String result = conversionService.convert(value, String.class); - assertSame(value, result); + assertThat(result).isSameAs(value); } @Test public void testStringToObject() { String value = "myValue"; Object result = conversionService.convert(value, Object.class); - assertSame(value, result); + assertThat(result).isSameAs(value); } @Test public void testIgnoreCopyConstructor() { WithCopyConstructor value = new WithCopyConstructor(); Object result = conversionService.convert(value, WithCopyConstructor.class); - assertSame(value, result); + assertThat(result).isSameAs(value); } @Test @@ -403,8 +397,8 @@ public class GenericConversionServiceTests { List list = new ArrayList<>(); TypeDescriptor sourceType = TypeDescriptor.forObject(list); TypeDescriptor targetType = TypeDescriptor.valueOf(String[].class); - assertTrue(conversionService.canConvert(sourceType, targetType)); - assertEquals(0, ((String[]) conversionService.convert(list, sourceType, targetType)).length); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); + assertThat(((String[]) conversionService.convert(list, sourceType, targetType)).length).isEqualTo(0); } @Test @@ -414,26 +408,26 @@ public class GenericConversionServiceTests { List list = new ArrayList<>(); TypeDescriptor sourceType = TypeDescriptor.forObject(list); TypeDescriptor targetType = TypeDescriptor.valueOf(Integer.class); - assertTrue(conversionService.canConvert(sourceType, targetType)); - assertNull(conversionService.convert(list, sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); + assertThat(conversionService.convert(list, sourceType, targetType)).isNull(); } @Test public void stringToArrayCanConvert() { conversionService.addConverter(new StringToArrayConverter(conversionService)); - assertFalse(conversionService.canConvert(String.class, Integer[].class)); + assertThat(conversionService.canConvert(String.class, Integer[].class)).isFalse(); conversionService.addConverterFactory(new StringToNumberConverterFactory()); - assertTrue(conversionService.canConvert(String.class, Integer[].class)); + assertThat(conversionService.canConvert(String.class, Integer[].class)).isTrue(); } @Test public void stringToCollectionCanConvert() throws Exception { conversionService.addConverter(new StringToCollectionConverter(conversionService)); - assertTrue(conversionService.canConvert(String.class, Collection.class)); + assertThat(conversionService.canConvert(String.class, Collection.class)).isTrue(); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("integerCollection")); - assertFalse(conversionService.canConvert(TypeDescriptor.valueOf(String.class), targetType)); + assertThat(conversionService.canConvert(TypeDescriptor.valueOf(String.class), targetType)).isFalse(); conversionService.addConverterFactory(new StringToNumberConverterFactory()); - assertTrue(conversionService.canConvert(TypeDescriptor.valueOf(String.class), targetType)); + assertThat(conversionService.canConvert(TypeDescriptor.valueOf(String.class), targetType)).isTrue(); } @Test @@ -447,16 +441,16 @@ public class GenericConversionServiceTests { public void testConvertiblePairEqualsAndHash() { GenericConverter.ConvertiblePair pair = new GenericConverter.ConvertiblePair(Number.class, String.class); GenericConverter.ConvertiblePair pairEqual = new GenericConverter.ConvertiblePair(Number.class, String.class); - assertEquals(pair, pairEqual); - assertEquals(pair.hashCode(), pairEqual.hashCode()); + assertThat(pairEqual).isEqualTo(pair); + assertThat(pairEqual.hashCode()).isEqualTo(pair.hashCode()); } @Test public void testConvertiblePairDifferentEqualsAndHash() { GenericConverter.ConvertiblePair pair = new GenericConverter.ConvertiblePair(Number.class, String.class); GenericConverter.ConvertiblePair pairOpposite = new GenericConverter.ConvertiblePair(String.class, Number.class); - assertFalse(pair.equals(pairOpposite)); - assertFalse(pair.hashCode() == pairOpposite.hashCode()); + assertThat(pair.equals(pairOpposite)).isFalse(); + assertThat(pair.hashCode() == pairOpposite.hashCode()).isFalse(); } @Test @@ -474,9 +468,9 @@ public class GenericConversionServiceTests { @Test public void removeConvertible() { conversionService.addConverter(new ColorConverter()); - assertTrue(conversionService.canConvert(String.class, Color.class)); + assertThat(conversionService.canConvert(String.class, Color.class)).isTrue(); conversionService.removeConvertible(String.class, Color.class); - assertFalse(conversionService.canConvert(String.class, Color.class)); + assertThat(conversionService.canConvert(String.class, Color.class)).isFalse(); } @Test @@ -484,8 +478,8 @@ public class GenericConversionServiceTests { MyConditionalConverter converter = new MyConditionalConverter(); conversionService.addConverter(new ColorConverter()); conversionService.addConverter(converter); - assertEquals(Color.BLACK, conversionService.convert("#000000", Color.class)); - assertTrue(converter.getMatchAttempts() > 0); + assertThat(conversionService.convert("#000000", Color.class)).isEqualTo(Color.BLACK); + assertThat(converter.getMatchAttempts() > 0).isTrue(); } @Test @@ -493,9 +487,9 @@ public class GenericConversionServiceTests { MyConditionalConverterFactory converter = new MyConditionalConverterFactory(); conversionService.addConverter(new ColorConverter()); conversionService.addConverterFactory(converter); - assertEquals(Color.BLACK, conversionService.convert("#000000", Color.class)); - assertTrue(converter.getMatchAttempts() > 0); - assertTrue(converter.getNestedMatchAttempts() > 0); + assertThat(conversionService.convert("#000000", Color.class)).isEqualTo(Color.BLACK); + assertThat(converter.getMatchAttempts() > 0).isTrue(); + assertThat(converter.getNestedMatchAttempts() > 0).isTrue(); } @Test @@ -503,14 +497,14 @@ public class GenericConversionServiceTests { conversionService.addConverter(new ColorConverter()); conversionService.addConverter(new MyConditionalColorConverter()); - assertEquals(Color.BLACK, conversionService.convert("000000xxxx", - new TypeDescriptor(getClass().getField("activeColor")))); - assertEquals(Color.BLACK, conversionService.convert(" #000000 ", - new TypeDescriptor(getClass().getField("inactiveColor")))); - assertEquals(Color.BLACK, conversionService.convert("000000yyyy", - new TypeDescriptor(getClass().getField("activeColor")))); - assertEquals(Color.BLACK, conversionService.convert(" #000000 ", - new TypeDescriptor(getClass().getField("inactiveColor")))); + assertThat(conversionService.convert("000000xxxx", + new TypeDescriptor(getClass().getField("activeColor")))).isEqualTo(Color.BLACK); + assertThat(conversionService.convert(" #000000 ", + new TypeDescriptor(getClass().getField("inactiveColor")))).isEqualTo(Color.BLACK); + assertThat(conversionService.convert("000000yyyy", + new TypeDescriptor(getClass().getField("activeColor")))).isEqualTo(Color.BLACK); + assertThat(conversionService.convert(" #000000 ", + new TypeDescriptor(getClass().getField("inactiveColor")))).isEqualTo(Color.BLACK); } @Test @@ -525,9 +519,9 @@ public class GenericConversionServiceTests { public void conditionalConversionForAllTypes() { MyConditionalGenericConverter converter = new MyConditionalGenericConverter(); conversionService.addConverter(converter); - assertEquals((Integer) 3, conversionService.convert(3, Integer.class)); + assertThat(conversionService.convert(3, Integer.class)).isEqualTo(3); assertThat(converter.getSourceTypes().size()).isGreaterThan(2); - assertTrue(converter.getSourceTypes().stream().allMatch(td -> Integer.class.equals(td.getType()))); + assertThat(converter.getSourceTypes().stream().allMatch(td -> Integer.class.equals(td.getType()))).isTrue(); } @Test @@ -535,19 +529,19 @@ public class GenericConversionServiceTests { // SPR-9566 byte[] byteArray = new byte[] { 1, 2, 3 }; byte[] converted = conversionService.convert(byteArray, byte[].class); - assertSame(byteArray, converted); + assertThat(converted).isSameAs(byteArray); } @Test public void testEnumToStringConversion() { conversionService.addConverter(new EnumToStringConverter(conversionService)); - assertEquals("A", conversionService.convert(MyEnum.A, String.class)); + assertThat(conversionService.convert(MyEnum.A, String.class)).isEqualTo("A"); } @Test public void testSubclassOfEnumToString() throws Exception { conversionService.addConverter(new EnumToStringConverter(conversionService)); - assertEquals("FIRST", conversionService.convert(EnumWithSubclass.FIRST, String.class)); + assertThat(conversionService.convert(EnumWithSubclass.FIRST, String.class)).isEqualTo("FIRST"); } @Test @@ -555,21 +549,21 @@ public class GenericConversionServiceTests { // SPR-9692 conversionService.addConverter(new EnumToStringConverter(conversionService)); conversionService.addConverter(new MyEnumInterfaceToStringConverter()); - assertEquals("1", conversionService.convert(MyEnum.A, String.class)); + assertThat(conversionService.convert(MyEnum.A, String.class)).isEqualTo("1"); } @Test public void testStringToEnumWithInterfaceConversion() { conversionService.addConverterFactory(new StringToEnumConverterFactory()); conversionService.addConverterFactory(new StringToMyEnumInterfaceConverterFactory()); - assertEquals(MyEnum.A, conversionService.convert("1", MyEnum.class)); + assertThat(conversionService.convert("1", MyEnum.class)).isEqualTo(MyEnum.A); } @Test public void testStringToEnumWithBaseInterfaceConversion() { conversionService.addConverterFactory(new StringToEnumConverterFactory()); conversionService.addConverterFactory(new StringToMyEnumBaseInterfaceConverterFactory()); - assertEquals(MyEnum.A, conversionService.convert("base1", MyEnum.class)); + assertThat(conversionService.convert("base1", MyEnum.class)).isEqualTo(MyEnum.A); } @Test @@ -587,36 +581,24 @@ public class GenericConversionServiceTests { conversionService.addConverter(new MyStringToStringCollectionConverter()); conversionService.addConverter(new MyStringToIntegerCollectionConverter()); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))); - assertEquals(Collections.singleton(4), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")))); - assertEquals(Collections.singleton(4), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))); - assertEquals(Collections.singleton(4), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))); - assertEquals(Collections.singleton(4), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX")); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")))).isEqualTo(Collections.singleton(4)); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton(4)); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))).isEqualTo(Collections.singleton(4)); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton(4)); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX")); } @Test public void adaptedCollectionTypesFromSameSourceType() throws Exception { conversionService.addConverter(new MyStringToStringCollectionConverter()); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX")); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))).isEqualTo(Collections.singleton("testX")); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton("testX")); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))).isEqualTo(Collections.singleton("testX")); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX")); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton("testX")); assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() -> conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")))); @@ -626,32 +608,24 @@ public class GenericConversionServiceTests { public void genericCollectionAsSource() throws Exception { conversionService.addConverter(new MyStringToGenericCollectionConverter()); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX")); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))).isEqualTo(Collections.singleton("testX")); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton("testX")); // The following is unpleasant but a consequence of the generic collection converter above... - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")))); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")))).isEqualTo(Collections.singleton("testX")); } @Test public void rawCollectionAsSource() throws Exception { conversionService.addConverter(new MyStringToRawCollectionConverter()); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))); - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("stringCollection")))).isEqualTo(Collections.singleton("testX")); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("genericCollection")))).isEqualTo(Collections.singleton("testX")); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("rawCollection")))).isEqualTo(Collections.singleton("testX")); // The following is unpleasant but a consequence of the raw collection converter above... - assertEquals(Collections.singleton("testX"), - conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")))); + assertThat(conversionService.convert("test", TypeDescriptor.valueOf(String.class), new TypeDescriptor(getClass().getField("integerCollection")))).isEqualTo(Collections.singleton("testX")); } diff --git a/spring-core/src/test/java/org/springframework/core/convert/support/MapToMapConverterTests.java b/spring-core/src/test/java/org/springframework/core/convert/support/MapToMapConverterTests.java index f7af7d354dc..c6f3a4ffa21 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/support/MapToMapConverterTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/support/MapToMapConverterTests.java @@ -35,10 +35,6 @@ import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Keith Donald @@ -64,21 +60,21 @@ public class MapToMapConverterTests { TypeDescriptor sourceType = TypeDescriptor.forObject(map); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget")); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); try { conversionService.convert(map, sourceType, targetType); } catch (ConversionFailedException ex) { - assertTrue(ex.getCause() instanceof ConverterNotFoundException); + assertThat(ex.getCause() instanceof ConverterNotFoundException).isTrue(); } conversionService.addConverterFactory(new StringToNumberConverterFactory()); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); @SuppressWarnings("unchecked") Map result = (Map) conversionService.convert(map, sourceType, targetType); - assertFalse(map.equals(result)); - assertEquals((Integer) 9, result.get(1)); - assertEquals((Integer) 37, result.get(2)); + assertThat(map.equals(result)).isFalse(); + assertThat((int) result.get(1)).isEqualTo(9); + assertThat((int) result.get(2)).isEqualTo(37); } @Test @@ -87,8 +83,8 @@ public class MapToMapConverterTests { map.put("1", "9"); map.put("2", "37"); - assertTrue(conversionService.canConvert(Map.class, Map.class)); - assertSame(map, conversionService.convert(map, Map.class)); + assertThat(conversionService.canConvert(Map.class, Map.class)).isTrue(); + assertThat((Map) conversionService.convert(map, Map.class)).isSameAs(map); } @Test @@ -99,21 +95,21 @@ public class MapToMapConverterTests { TypeDescriptor sourceType = new TypeDescriptor(getClass().getField("notGenericMapSource")); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("scalarMapTarget")); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); try { conversionService.convert(map, sourceType, targetType); } catch (ConversionFailedException ex) { - assertTrue(ex.getCause() instanceof ConverterNotFoundException); + assertThat(ex.getCause() instanceof ConverterNotFoundException).isTrue(); } conversionService.addConverterFactory(new StringToNumberConverterFactory()); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); @SuppressWarnings("unchecked") Map result = (Map) conversionService.convert(map, sourceType, targetType); - assertFalse(map.equals(result)); - assertEquals((Integer) 9, result.get(1)); - assertEquals((Integer) 37, result.get(2)); + assertThat(map.equals(result)).isFalse(); + assertThat((int) result.get(1)).isEqualTo(9); + assertThat((int) result.get(2)).isEqualTo(37); } @Test @@ -124,22 +120,22 @@ public class MapToMapConverterTests { TypeDescriptor sourceType = TypeDescriptor.forObject(map); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("collectionMapTarget")); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); try { conversionService.convert(map, sourceType, targetType); } catch (ConversionFailedException ex) { - assertTrue(ex.getCause() instanceof ConverterNotFoundException); + assertThat(ex.getCause() instanceof ConverterNotFoundException).isTrue(); } conversionService.addConverter(new CollectionToCollectionConverter(conversionService)); conversionService.addConverterFactory(new StringToNumberConverterFactory()); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); @SuppressWarnings("unchecked") Map> result = (Map>) conversionService.convert(map, sourceType, targetType); - assertFalse(map.equals(result)); - assertEquals(Arrays.asList(9, 12), result.get(1)); - assertEquals(Arrays.asList(37, 23), result.get(2)); + assertThat(map.equals(result)).isFalse(); + assertThat(result.get(1)).isEqualTo(Arrays.asList(9, 12)); + assertThat(result.get(2)).isEqualTo(Arrays.asList(37, 23)); } @Test @@ -150,18 +146,18 @@ public class MapToMapConverterTests { TypeDescriptor sourceType = new TypeDescriptor(getClass().getField("sourceCollectionMapTarget")); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("collectionMapTarget")); - assertFalse(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isFalse(); assertThatExceptionOfType(ConverterNotFoundException.class).isThrownBy(() -> conversionService.convert(map, sourceType, targetType)); conversionService.addConverter(new CollectionToCollectionConverter(conversionService)); conversionService.addConverterFactory(new StringToNumberConverterFactory()); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); @SuppressWarnings("unchecked") Map> result = (Map>) conversionService.convert(map, sourceType, targetType); - assertFalse(map.equals(result)); - assertEquals(Arrays.asList(9, 12), result.get(1)); - assertEquals(Arrays.asList(37, 23), result.get(2)); + assertThat(map.equals(result)).isFalse(); + assertThat(result.get(1)).isEqualTo(Arrays.asList(9, 12)); + assertThat(result.get(2)).isEqualTo(Arrays.asList(37, 23)); } @Test @@ -170,8 +166,8 @@ public class MapToMapConverterTests { map.put("1", Arrays.asList("9", "12")); map.put("2", Arrays.asList("37", "23")); - assertTrue(conversionService.canConvert(Map.class, Map.class)); - assertSame(map, conversionService.convert(map, Map.class)); + assertThat(conversionService.canConvert(Map.class, Map.class)).isTrue(); + assertThat((Map) conversionService.convert(map, Map.class)).isSameAs(map); } @Test @@ -182,8 +178,8 @@ public class MapToMapConverterTests { conversionService.addConverter(new CollectionToCollectionConverter(conversionService)); conversionService.addConverter(new CollectionToObjectConverter(conversionService)); - assertTrue(conversionService.canConvert(Map.class, Map.class)); - assertSame(map, conversionService.convert(map, Map.class)); + assertThat(conversionService.canConvert(Map.class, Map.class)).isTrue(); + assertThat((Map) conversionService.convert(map, Map.class)).isSameAs(map); } @Test @@ -192,16 +188,16 @@ public class MapToMapConverterTests { TypeDescriptor sourceType = TypeDescriptor.forObject(map); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("emptyMapTarget")); - assertTrue(conversionService.canConvert(sourceType, targetType)); - assertSame(map, conversionService.convert(map, sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); + assertThat(conversionService.convert(map, sourceType, targetType)).isSameAs(map); } @Test public void emptyMapNoTargetGenericInfo() throws Exception { Map map = new HashMap<>(); - assertTrue(conversionService.canConvert(Map.class, Map.class)); - assertSame(map, conversionService.convert(map, Map.class)); + assertThat(conversionService.canConvert(Map.class, Map.class)).isTrue(); + assertThat((Map) conversionService.convert(map, Map.class)).isSameAs(map); } @Test @@ -210,11 +206,11 @@ public class MapToMapConverterTests { TypeDescriptor sourceType = TypeDescriptor.forObject(map); TypeDescriptor targetType = new TypeDescriptor(getClass().getField("emptyMapDifferentTarget")); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); @SuppressWarnings("unchecked") LinkedHashMap result = (LinkedHashMap) conversionService.convert(map, sourceType, targetType); - assertEquals(map, result); - assertEquals(LinkedHashMap.class, result.getClass()); + assertThat(result).isEqualTo(map); + assertThat(result.getClass()).isEqualTo(LinkedHashMap.class); } @Test @@ -227,11 +223,11 @@ public class MapToMapConverterTests { TypeDescriptor targetType = TypeDescriptor.map(NoDefaultConstructorMap.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class)); - assertTrue(conversionService.canConvert(sourceType, targetType)); + assertThat(conversionService.canConvert(sourceType, targetType)).isTrue(); @SuppressWarnings("unchecked") Map result = (Map) conversionService.convert(map, sourceType, targetType); - assertEquals(map, result); - assertEquals(NoDefaultConstructorMap.class, result.getClass()); + assertThat(result).isEqualTo(map); + assertThat(result.getClass()).isEqualTo(NoDefaultConstructorMap.class); } @Test @@ -274,8 +270,8 @@ public class MapToMapConverterTests { result.put(MyEnum.A, 1); result.put(MyEnum.C, 2); - assertEquals(result, conversionService.convert(source, - TypeDescriptor.forObject(source), new TypeDescriptor(getClass().getField("enumMap")))); + assertThat(conversionService.convert(source, + TypeDescriptor.forObject(source), new TypeDescriptor(getClass().getField("enumMap")))).isEqualTo(result); } diff --git a/spring-core/src/test/java/org/springframework/core/convert/support/StreamConverterTests.java b/spring-core/src/test/java/org/springframework/core/convert/support/StreamConverterTests.java index a74703a9ec1..51c0f91ef80 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/support/StreamConverterTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/support/StreamConverterTests.java @@ -28,12 +28,9 @@ import org.springframework.core.convert.ConverterNotFoundException; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.Converter; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertNotNull; -import static org.junit.Assert.assertTrue; /** * Tests for {@link StreamConverter}. @@ -64,14 +61,15 @@ public class StreamConverterTests { TypeDescriptor listOfStrings = new TypeDescriptor(Types.class.getField("listOfStrings")); Object result = this.conversionService.convert(stream, listOfStrings); - assertNotNull("Converted object must not be null", result); - assertTrue("Converted object must be a list", result instanceof List); + assertThat(result).as("Converted object must not be null").isNotNull(); + boolean condition = result instanceof List; + assertThat(condition).as("Converted object must be a list").isTrue(); @SuppressWarnings("unchecked") List content = (List) result; - assertEquals("1", content.get(0)); - assertEquals("2", content.get(1)); - assertEquals("3", content.get(2)); - assertEquals("Wrong number of elements", 3, content.size()); + assertThat(content.get(0)).isEqualTo("1"); + assertThat(content.get(1)).isEqualTo("2"); + assertThat(content.get(2)).isEqualTo("3"); + assertThat(content.size()).as("Wrong number of elements").isEqualTo(3); } @Test @@ -81,13 +79,13 @@ public class StreamConverterTests { TypeDescriptor arrayOfLongs = new TypeDescriptor(Types.class.getField("arrayOfLongs")); Object result = this.conversionService.convert(stream, arrayOfLongs); - assertNotNull("Converted object must not be null", result); - assertTrue("Converted object must be an array", result.getClass().isArray()); + assertThat(result).as("Converted object must not be null").isNotNull(); + assertThat(result.getClass().isArray()).as("Converted object must be an array").isTrue(); Long[] content = (Long[]) result; - assertEquals(Long.valueOf(1L), content[0]); - assertEquals(Long.valueOf(2L), content[1]); - assertEquals(Long.valueOf(3L), content[2]); - assertEquals("Wrong number of elements", 3, content.length); + assertThat(content[0]).isEqualTo(Long.valueOf(1L)); + assertThat(content[1]).isEqualTo(Long.valueOf(2L)); + assertThat(content[2]).isEqualTo(Long.valueOf(3L)); + assertThat(content.length).as("Wrong number of elements").isEqualTo(3); } @Test @@ -96,14 +94,15 @@ public class StreamConverterTests { TypeDescriptor listOfStrings = new TypeDescriptor(Types.class.getField("rawList")); Object result = this.conversionService.convert(stream, listOfStrings); - assertNotNull("Converted object must not be null", result); - assertTrue("Converted object must be a list", result instanceof List); + assertThat(result).as("Converted object must not be null").isNotNull(); + boolean condition = result instanceof List; + assertThat(condition).as("Converted object must be a list").isTrue(); @SuppressWarnings("unchecked") List content = (List) result; - assertEquals(1, content.get(0)); - assertEquals(2, content.get(1)); - assertEquals(3, content.get(2)); - assertEquals("Wrong number of elements", 3, content.size()); + assertThat(content.get(0)).isEqualTo(1); + assertThat(content.get(1)).isEqualTo(2); + assertThat(content.get(2)).isEqualTo(3); + assertThat(content.size()).as("Wrong number of elements").isEqualTo(3); } @Test @@ -123,11 +122,12 @@ public class StreamConverterTests { TypeDescriptor streamOfInteger = new TypeDescriptor(Types.class.getField("streamOfIntegers")); Object result = this.conversionService.convert(stream, streamOfInteger); - assertNotNull("Converted object must not be null", result); - assertTrue("Converted object must be a stream", result instanceof Stream); + assertThat(result).as("Converted object must not be null").isNotNull(); + boolean condition = result instanceof Stream; + assertThat(condition).as("Converted object must be a stream").isTrue(); @SuppressWarnings("unchecked") Stream content = (Stream) result; - assertEquals(6, content.mapToInt(x -> x).sum()); + assertThat(content.mapToInt(x -> x).sum()).isEqualTo(6); } @Test @@ -143,11 +143,12 @@ public class StreamConverterTests { TypeDescriptor streamOfBoolean = new TypeDescriptor(Types.class.getField("streamOfBooleans")); Object result = this.conversionService.convert(stream, streamOfBoolean); - assertNotNull("Converted object must not be null", result); - assertTrue("Converted object must be a stream", result instanceof Stream); + assertThat(result).as("Converted object must not be null").isNotNull(); + boolean condition = result instanceof Stream; + assertThat(condition).as("Converted object must be a stream").isTrue(); @SuppressWarnings("unchecked") Stream content = (Stream) result; - assertEquals(2, content.filter(x -> x).count()); + assertThat(content.filter(x -> x).count()).isEqualTo(2); } @Test @@ -157,20 +158,21 @@ public class StreamConverterTests { TypeDescriptor streamOfInteger = new TypeDescriptor(Types.class.getField("rawStream")); Object result = this.conversionService.convert(stream, streamOfInteger); - assertNotNull("Converted object must not be null", result); - assertTrue("Converted object must be a stream", result instanceof Stream); + assertThat(result).as("Converted object must not be null").isNotNull(); + boolean condition = result instanceof Stream; + assertThat(condition).as("Converted object must be a stream").isTrue(); @SuppressWarnings("unchecked") Stream content = (Stream) result; StringBuilder sb = new StringBuilder(); content.forEach(sb::append); - assertEquals("123", sb.toString()); + assertThat(sb.toString()).isEqualTo("123"); } @Test public void doesNotMatchIfNoStream() throws NoSuchFieldException { - assertFalse("Should not match non stream type", this.streamConverter.matches( + assertThat(this.streamConverter.matches( new TypeDescriptor(Types.class.getField("listOfStrings")), - new TypeDescriptor(Types.class.getField("arrayOfLongs")))); + new TypeDescriptor(Types.class.getField("arrayOfLongs")))).as("Should not match non stream type").isFalse(); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/env/CompositePropertySourceTests.java b/spring-core/src/test/java/org/springframework/core/env/CompositePropertySourceTests.java index 78d4c4e2c07..d8bf59477a9 100644 --- a/spring-core/src/test/java/org/springframework/core/env/CompositePropertySourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/CompositePropertySourceTests.java @@ -20,7 +20,7 @@ import java.util.Collections; import org.junit.Test; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CompositePropertySource}. @@ -43,7 +43,7 @@ public class CompositePropertySourceTests { int i1 = s.indexOf("name='p1'"); int i2 = s.indexOf("name='p2'"); int i3 = s.indexOf("name='p3'"); - assertTrue("Bad order: " + s, ((i1 < i2) && (i2 < i3))); + assertThat(((i1 < i2) && (i2 < i3))).as("Bad order: " + s).isTrue(); } } diff --git a/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java b/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java index cea64244cf9..4fd3e34ba1c 100644 --- a/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java @@ -23,7 +23,6 @@ import joptsimple.OptionSet; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link JOptCommandLinePropertySource}. @@ -75,7 +74,7 @@ public class JOptCommandLinePropertySourceTests { OptionSet options = parser.parse("--foo=bar,baz,biz"); CommandLinePropertySource ps = new JOptCommandLinePropertySource(options); - assertEquals(Arrays.asList("bar","baz","biz"), ps.getOptionValues("foo")); + assertThat(ps.getOptionValues("foo")).isEqualTo(Arrays.asList("bar","baz","biz")); assertThat(ps.getProperty("foo")).isEqualTo("bar,baz,biz"); } @@ -86,7 +85,7 @@ public class JOptCommandLinePropertySourceTests { OptionSet options = parser.parse("--foo=bar", "--foo=baz", "--foo=biz"); CommandLinePropertySource ps = new JOptCommandLinePropertySource(options); - assertEquals(Arrays.asList("bar","baz","biz"), ps.getOptionValues("foo")); + assertThat(ps.getOptionValues("foo")).isEqualTo(Arrays.asList("bar","baz","biz")); assertThat(ps.getProperty("foo")).isEqualTo("bar,baz,biz"); } diff --git a/spring-core/src/test/java/org/springframework/core/env/MutablePropertySourcesTests.java b/spring-core/src/test/java/org/springframework/core/env/MutablePropertySourcesTests.java index bee1a02a0db..b0e9bd30945 100644 --- a/spring-core/src/test/java/org/springframework/core/env/MutablePropertySourcesTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/MutablePropertySourcesTests.java @@ -25,10 +25,6 @@ import org.springframework.mock.env.MockPropertySource; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Chris Beams @@ -99,11 +95,11 @@ public class MutablePropertySourcesTests { assertThat(sources.precedenceOf(PropertySource.named("f"))).isEqualTo(5); assertThat(sources.precedenceOf(PropertySource.named("g"))).isEqualTo(6); - assertEquals(sources.remove("a"), PropertySource.named("a")); + assertThat(PropertySource.named("a")).isEqualTo(sources.remove("a")); assertThat(sources.size()).isEqualTo(6); assertThat(sources.contains("a")).isFalse(); - assertNull(sources.remove("a")); + assertThat((Object) sources.remove("a")).isNull(); assertThat(sources.size()).isEqualTo(6); String bogusPS = "bogus"; @@ -150,19 +146,19 @@ public class MutablePropertySourcesTests { sources.addLast(new MockPropertySource("test")); Iterator> it = sources.iterator(); - assertTrue(it.hasNext()); - assertEquals("test", it.next().getName()); + assertThat(it.hasNext()).isTrue(); + assertThat(it.next().getName()).isEqualTo("test"); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy( it::remove); - assertFalse(it.hasNext()); + assertThat(it.hasNext()).isFalse(); } @Test public void iteratorIsEmptyForEmptySources() { MutablePropertySources sources = new MutablePropertySources(); Iterator> it = sources.iterator(); - assertFalse(it.hasNext()); + assertThat(it.hasNext()).isFalse(); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/env/ProfilesTests.java b/spring-core/src/test/java/org/springframework/core/env/ProfilesTests.java index 809d0572e9d..6e6c39b80bd 100644 --- a/spring-core/src/test/java/org/springframework/core/env/ProfilesTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/ProfilesTests.java @@ -25,10 +25,8 @@ import org.junit.Test; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Tests for {@link Profiles}. @@ -71,63 +69,63 @@ public class ProfilesTests { @Test public void ofSingleElement() { Profiles profiles = Profiles.of("spring"); - assertTrue(profiles.matches(activeProfiles("spring"))); - assertFalse(profiles.matches(activeProfiles("framework"))); + assertThat(profiles.matches(activeProfiles("spring"))).isTrue(); + assertThat(profiles.matches(activeProfiles("framework"))).isFalse(); } @Test public void ofSingleInvertedElement() { Profiles profiles = Profiles.of("!spring"); - assertFalse(profiles.matches(activeProfiles("spring"))); - assertTrue(profiles.matches(activeProfiles("framework"))); + assertThat(profiles.matches(activeProfiles("spring"))).isFalse(); + assertThat(profiles.matches(activeProfiles("framework"))).isTrue(); } @Test public void ofMultipleElements() { Profiles profiles = Profiles.of("spring", "framework"); - assertTrue(profiles.matches(activeProfiles("spring"))); - assertTrue(profiles.matches(activeProfiles("framework"))); - assertFalse(profiles.matches(activeProfiles("java"))); + assertThat(profiles.matches(activeProfiles("spring"))).isTrue(); + assertThat(profiles.matches(activeProfiles("framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("java"))).isFalse(); } @Test public void ofMultipleElementsWithInverted() { Profiles profiles = Profiles.of("!spring", "framework"); - assertFalse(profiles.matches(activeProfiles("spring"))); - assertTrue(profiles.matches(activeProfiles("spring", "framework"))); - assertTrue(profiles.matches(activeProfiles("framework"))); - assertTrue(profiles.matches(activeProfiles("java"))); + assertThat(profiles.matches(activeProfiles("spring"))).isFalse(); + assertThat(profiles.matches(activeProfiles("spring", "framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("java"))).isTrue(); } @Test public void ofMultipleElementsAllInverted() { Profiles profiles = Profiles.of("!spring", "!framework"); - assertTrue(profiles.matches(activeProfiles("spring"))); - assertTrue(profiles.matches(activeProfiles("framework"))); - assertTrue(profiles.matches(activeProfiles("java"))); - assertFalse(profiles.matches(activeProfiles("spring", "framework"))); - assertFalse(profiles.matches(activeProfiles("spring", "framework", "java"))); + assertThat(profiles.matches(activeProfiles("spring"))).isTrue(); + assertThat(profiles.matches(activeProfiles("framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("java"))).isTrue(); + assertThat(profiles.matches(activeProfiles("spring", "framework"))).isFalse(); + assertThat(profiles.matches(activeProfiles("spring", "framework", "java"))).isFalse(); } @Test public void ofSingleExpression() { Profiles profiles = Profiles.of("(spring)"); - assertTrue(profiles.matches(activeProfiles("spring"))); - assertFalse(profiles.matches(activeProfiles("framework"))); + assertThat(profiles.matches(activeProfiles("spring"))).isTrue(); + assertThat(profiles.matches(activeProfiles("framework"))).isFalse(); } @Test public void ofSingleExpressionInverted() { Profiles profiles = Profiles.of("!(spring)"); - assertFalse(profiles.matches(activeProfiles("spring"))); - assertTrue(profiles.matches(activeProfiles("framework"))); + assertThat(profiles.matches(activeProfiles("spring"))).isFalse(); + assertThat(profiles.matches(activeProfiles("framework"))).isTrue(); } @Test public void ofSingleInvertedExpression() { Profiles profiles = Profiles.of("(!spring)"); - assertFalse(profiles.matches(activeProfiles("spring"))); - assertTrue(profiles.matches(activeProfiles("framework"))); + assertThat(profiles.matches(activeProfiles("spring"))).isFalse(); + assertThat(profiles.matches(activeProfiles("framework"))).isTrue(); } @Test @@ -143,10 +141,10 @@ public class ProfilesTests { } private void assertOrExpression(Profiles profiles) { - assertTrue(profiles.matches(activeProfiles("spring"))); - assertTrue(profiles.matches(activeProfiles("framework"))); - assertTrue(profiles.matches(activeProfiles("spring", "framework"))); - assertFalse(profiles.matches(activeProfiles("java"))); + assertThat(profiles.matches(activeProfiles("spring"))).isTrue(); + assertThat(profiles.matches(activeProfiles("framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("spring", "framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("java"))).isFalse(); } @Test @@ -168,10 +166,10 @@ public class ProfilesTests { } private void assertAndExpression(Profiles profiles) { - assertFalse(profiles.matches(activeProfiles("spring"))); - assertFalse(profiles.matches(activeProfiles("framework"))); - assertTrue(profiles.matches(activeProfiles("spring", "framework"))); - assertFalse(profiles.matches(activeProfiles("java"))); + assertThat(profiles.matches(activeProfiles("spring"))).isFalse(); + assertThat(profiles.matches(activeProfiles("framework"))).isFalse(); + assertThat(profiles.matches(activeProfiles("spring", "framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("java"))).isFalse(); } @Test @@ -187,10 +185,10 @@ public class ProfilesTests { } private void assertOfNotAndExpression(Profiles profiles) { - assertTrue(profiles.matches(activeProfiles("spring"))); - assertTrue(profiles.matches(activeProfiles("framework"))); - assertFalse(profiles.matches(activeProfiles("spring", "framework"))); - assertTrue(profiles.matches(activeProfiles("java"))); + assertThat(profiles.matches(activeProfiles("spring"))).isTrue(); + assertThat(profiles.matches(activeProfiles("framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("spring", "framework"))).isFalse(); + assertThat(profiles.matches(activeProfiles("java"))).isTrue(); } @Test @@ -224,10 +222,10 @@ public class ProfilesTests { } private void assertOfAndExpressionWithInvertedSingleElement(Profiles profiles) { - assertTrue(profiles.matches(activeProfiles("framework"))); - assertFalse(profiles.matches(activeProfiles("java"))); - assertFalse(profiles.matches(activeProfiles("spring", "framework"))); - assertFalse(profiles.matches(activeProfiles("spring"))); + assertThat(profiles.matches(activeProfiles("framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("java"))).isFalse(); + assertThat(profiles.matches(activeProfiles("spring", "framework"))).isFalse(); + assertThat(profiles.matches(activeProfiles("spring"))).isFalse(); } @Test @@ -237,10 +235,10 @@ public class ProfilesTests { } private void assertOfOrExpressionWithInvertedSingleElement(Profiles profiles) { - assertTrue(profiles.matches(activeProfiles("framework"))); - assertTrue(profiles.matches(activeProfiles("java"))); - assertTrue(profiles.matches(activeProfiles("spring", "framework"))); - assertFalse(profiles.matches(activeProfiles("spring"))); + assertThat(profiles.matches(activeProfiles("framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("java"))).isTrue(); + assertThat(profiles.matches(activeProfiles("spring", "framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("spring"))).isFalse(); } @Test @@ -256,10 +254,10 @@ public class ProfilesTests { } private void assertOfNotOrExpression(Profiles profiles) { - assertFalse(profiles.matches(activeProfiles("spring"))); - assertFalse(profiles.matches(activeProfiles("framework"))); - assertFalse(profiles.matches(activeProfiles("spring", "framework"))); - assertTrue(profiles.matches(activeProfiles("java"))); + assertThat(profiles.matches(activeProfiles("spring"))).isFalse(); + assertThat(profiles.matches(activeProfiles("framework"))).isFalse(); + assertThat(profiles.matches(activeProfiles("spring", "framework"))).isFalse(); + assertThat(profiles.matches(activeProfiles("java"))).isTrue(); } @Test @@ -275,10 +273,10 @@ public class ProfilesTests { } private void assertComplexExpression(Profiles profiles) { - assertFalse(profiles.matches(activeProfiles("spring"))); - assertTrue(profiles.matches(activeProfiles("spring", "framework"))); - assertTrue(profiles.matches(activeProfiles("spring", "java"))); - assertFalse(profiles.matches(activeProfiles("java", "framework"))); + assertThat(profiles.matches(activeProfiles("spring"))).isFalse(); + assertThat(profiles.matches(activeProfiles("spring", "framework"))).isTrue(); + assertThat(profiles.matches(activeProfiles("spring", "java"))).isTrue(); + assertThat(profiles.matches(activeProfiles("java", "framework"))).isFalse(); } @Test @@ -290,8 +288,7 @@ public class ProfilesTests { @Test public void sensibleToString() { - assertEquals("spring & framework or java | kotlin", - Profiles.of("spring & framework", "java | kotlin").toString()); + assertThat(Profiles.of("spring & framework", "java | kotlin").toString()).isEqualTo("spring & framework or java | kotlin"); } private void assertMalformed(Supplier supplier) { diff --git a/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java b/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java index bdca5523617..2bb709a3043 100644 --- a/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java @@ -30,8 +30,6 @@ import org.springframework.mock.env.MockPropertySource; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.springframework.core.env.AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME; import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME; import static org.springframework.core.env.AbstractEnvironment.RESERVED_DEFAULT_PROFILE_NAME; @@ -377,21 +375,21 @@ public class StandardEnvironmentTests { @Test public void suppressGetenvAccessThroughSystemProperty() { System.setProperty("spring.getenv.ignore", "true"); - assertTrue(environment.getSystemEnvironment().isEmpty()); + assertThat(environment.getSystemEnvironment().isEmpty()).isTrue(); System.clearProperty("spring.getenv.ignore"); } @Test public void suppressGetenvAccessThroughSpringProperty() { SpringProperties.setProperty("spring.getenv.ignore", "true"); - assertTrue(environment.getSystemEnvironment().isEmpty()); + assertThat(environment.getSystemEnvironment().isEmpty()).isTrue(); SpringProperties.setProperty("spring.getenv.ignore", null); } @Test public void suppressGetenvAccessThroughSpringFlag() { SpringProperties.setFlag("spring.getenv.ignore"); - assertTrue(environment.getSystemEnvironment().isEmpty()); + assertThat(environment.getSystemEnvironment().isEmpty()).isTrue(); SpringProperties.setProperty("spring.getenv.ignore", null); } @@ -405,7 +403,7 @@ public class StandardEnvironmentTests { { Map systemProperties = environment.getSystemProperties(); assertThat(systemProperties).isNotNull(); - assertSame(systemProperties, System.getProperties()); + assertThat(System.getProperties()).isSameAs(systemProperties); assertThat(systemProperties.get(ALLOWED_PROPERTY_NAME)).isEqualTo(ALLOWED_PROPERTY_VALUE); assertThat(systemProperties.get(DISALLOWED_PROPERTY_NAME)).isEqualTo(DISALLOWED_PROPERTY_VALUE); @@ -473,7 +471,7 @@ public class StandardEnvironmentTests { { Map systemEnvironment = environment.getSystemEnvironment(); assertThat(systemEnvironment).isNotNull(); - assertSame(systemEnvironment, System.getenv()); + assertThat(System.getenv()).isSameAs(systemEnvironment); } SecurityManager oldSecurityManager = System.getSecurityManager(); diff --git a/spring-core/src/test/java/org/springframework/core/env/SystemEnvironmentPropertySourceTests.java b/spring-core/src/test/java/org/springframework/core/env/SystemEnvironmentPropertySourceTests.java index 9c411e8e515..51a35f7dda0 100644 --- a/spring-core/src/test/java/org/springframework/core/env/SystemEnvironmentPropertySourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/SystemEnvironmentPropertySourceTests.java @@ -59,7 +59,7 @@ public class SystemEnvironmentPropertySourceTests { envMap.put("akey", "avalue"); assertThat(ps.containsProperty("akey")).isEqualTo(true); - assertThat(ps.getProperty("akey")).isEqualTo((Object)"avalue"); + assertThat(ps.getProperty("akey")).isEqualTo("avalue"); } @Test @@ -67,7 +67,7 @@ public class SystemEnvironmentPropertySourceTests { envMap.put("a.key", "a.value"); assertThat(ps.containsProperty("a.key")).isEqualTo(true); - assertThat(ps.getProperty("a.key")).isEqualTo((Object)"a.value"); + assertThat(ps.getProperty("a.key")).isEqualTo("a.value"); } @Test @@ -77,8 +77,8 @@ public class SystemEnvironmentPropertySourceTests { assertThat(ps.containsProperty("a_key")).isEqualTo(true); assertThat(ps.containsProperty("a.key")).isEqualTo(true); - assertThat(ps.getProperty("a_key")).isEqualTo((Object)"a_value"); - assertThat( ps.getProperty("a.key")).isEqualTo((Object)"a_value"); + assertThat(ps.getProperty("a_key")).isEqualTo("a_value"); + assertThat( ps.getProperty("a.key")).isEqualTo("a_value"); } @Test @@ -86,8 +86,8 @@ public class SystemEnvironmentPropertySourceTests { envMap.put("a_key", "a_value"); envMap.put("a.key", "a.value"); - assertThat(ps.getProperty("a_key")).isEqualTo((Object)"a_value"); - assertThat( ps.getProperty("a.key")).isEqualTo((Object)"a.value"); + assertThat(ps.getProperty("a_key")).isEqualTo("a_value"); + assertThat( ps.getProperty("a.key")).isEqualTo("a.value"); } @Test @@ -171,7 +171,7 @@ public class SystemEnvironmentPropertySourceTests { }; assertThat(ps.containsProperty("A_KEY")).isEqualTo(true); - assertThat(ps.getProperty("A_KEY")).isEqualTo((Object)"a_value"); + assertThat(ps.getProperty("A_KEY")).isEqualTo("a_value"); } } diff --git a/spring-core/src/test/java/org/springframework/core/io/ClassPathResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/ClassPathResourceTests.java index dda86815e51..d81b5efcece 100644 --- a/spring-core/src/test/java/org/springframework/core/io/ClassPathResourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/ClassPathResourceTests.java @@ -22,10 +22,8 @@ import java.util.regex.Pattern; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests that serve as regression tests for the bugs described in SPR-6888 @@ -100,35 +98,35 @@ public class ClassPathResourceTests { @Test public void dropLeadingSlashForClassLoaderAccess() { - assertEquals("test.html", new ClassPathResource("/test.html").getPath()); - assertEquals("test.html", ((ClassPathResource) new ClassPathResource("").createRelative("/test.html")).getPath()); + assertThat(new ClassPathResource("/test.html").getPath()).isEqualTo("test.html"); + assertThat(((ClassPathResource) new ClassPathResource("").createRelative("/test.html")).getPath()).isEqualTo("test.html"); } @Test public void preserveLeadingSlashForClassRelativeAccess() { - assertEquals("/test.html", new ClassPathResource("/test.html", getClass()).getPath()); - assertEquals("/test.html", ((ClassPathResource) new ClassPathResource("", getClass()).createRelative("/test.html")).getPath()); + assertThat(new ClassPathResource("/test.html", getClass()).getPath()).isEqualTo("/test.html"); + assertThat(((ClassPathResource) new ClassPathResource("", getClass()).createRelative("/test.html")).getPath()).isEqualTo("/test.html"); } @Test public void directoryNotReadable() { Resource fileDir = new ClassPathResource("org/springframework/core"); - assertTrue(fileDir.exists()); - assertFalse(fileDir.isReadable()); + assertThat(fileDir.exists()).isTrue(); + assertThat(fileDir.isReadable()).isFalse(); Resource jarDir = new ClassPathResource("reactor/core"); - assertTrue(jarDir.exists()); - assertFalse(jarDir.isReadable()); + assertThat(jarDir.exists()).isTrue(); + assertThat(jarDir.isReadable()).isFalse(); } private void assertDescriptionContainsExpectedPath(ClassPathResource resource, String expectedPath) { Matcher matcher = DESCRIPTION_PATTERN.matcher(resource.getDescription()); - assertTrue(matcher.matches()); - assertEquals(1, matcher.groupCount()); + assertThat(matcher.matches()).isTrue(); + assertThat(matcher.groupCount()).isEqualTo(1); String match = matcher.group(1); - assertEquals(expectedPath, match); + assertThat(match).isEqualTo(expectedPath); } private void assertExceptionContainsFullyQualifiedPath(ClassPathResource resource) { diff --git a/spring-core/src/test/java/org/springframework/core/io/ResourceEditorTests.java b/spring-core/src/test/java/org/springframework/core/io/ResourceEditorTests.java index 9ddbd4a04d5..14d17940551 100644 --- a/spring-core/src/test/java/org/springframework/core/io/ResourceEditorTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/ResourceEditorTests.java @@ -22,10 +22,8 @@ import org.junit.Test; import org.springframework.core.env.StandardEnvironment; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * Unit tests for the {@link ResourceEditor} class. @@ -41,8 +39,8 @@ public class ResourceEditorTests { PropertyEditor editor = new ResourceEditor(); editor.setAsText("classpath:org/springframework/core/io/ResourceEditorTests.class"); Resource resource = (Resource) editor.getValue(); - assertNotNull(resource); - assertTrue(resource.exists()); + assertThat(resource).isNotNull(); + assertThat(resource.exists()).isTrue(); } @Test @@ -55,14 +53,14 @@ public class ResourceEditorTests { public void setAndGetAsTextWithNull() { PropertyEditor editor = new ResourceEditor(); editor.setAsText(null); - assertEquals("", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(""); } @Test public void setAndGetAsTextWithWhitespaceResource() { PropertyEditor editor = new ResourceEditor(); editor.setAsText(" "); - assertEquals("", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(""); } @Test @@ -72,7 +70,7 @@ public class ResourceEditorTests { try { editor.setAsText("${test.prop}"); Resource resolved = (Resource) editor.getValue(); - assertEquals("foo", resolved.getFilename()); + assertThat(resolved.getFilename()).isEqualTo("foo"); } finally { System.getProperties().remove("test.prop"); @@ -86,7 +84,7 @@ public class ResourceEditorTests { try { editor.setAsText("${test.prop}-${bar}"); Resource resolved = (Resource) editor.getValue(); - assertEquals("foo-${bar}", resolved.getFilename()); + assertThat(resolved.getFilename()).isEqualTo("foo-${bar}"); } finally { System.getProperties().remove("test.prop"); diff --git a/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java index 2fabfd5b601..9af391bfbfc 100644 --- a/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java @@ -34,9 +34,6 @@ import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for various {@link Resource} implementations. @@ -51,45 +48,45 @@ public class ResourceTests { @Test public void testByteArrayResource() throws IOException { Resource resource = new ByteArrayResource("testString".getBytes()); - assertTrue(resource.exists()); - assertFalse(resource.isOpen()); + assertThat(resource.exists()).isTrue(); + assertThat(resource.isOpen()).isFalse(); String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream())); - assertEquals("testString", content); - assertEquals(resource, new ByteArrayResource("testString".getBytes())); + assertThat(content).isEqualTo("testString"); + assertThat(new ByteArrayResource("testString".getBytes())).isEqualTo(resource); } @Test public void testByteArrayResourceWithDescription() throws IOException { Resource resource = new ByteArrayResource("testString".getBytes(), "my description"); - assertTrue(resource.exists()); - assertFalse(resource.isOpen()); + assertThat(resource.exists()).isTrue(); + assertThat(resource.isOpen()).isFalse(); String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream())); - assertEquals("testString", content); - assertTrue(resource.getDescription().contains("my description")); - assertEquals(resource, new ByteArrayResource("testString".getBytes())); + assertThat(content).isEqualTo("testString"); + assertThat(resource.getDescription().contains("my description")).isTrue(); + assertThat(new ByteArrayResource("testString".getBytes())).isEqualTo(resource); } @Test public void testInputStreamResource() throws IOException { InputStream is = new ByteArrayInputStream("testString".getBytes()); Resource resource = new InputStreamResource(is); - assertTrue(resource.exists()); - assertTrue(resource.isOpen()); + assertThat(resource.exists()).isTrue(); + assertThat(resource.isOpen()).isTrue(); String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream())); - assertEquals("testString", content); - assertEquals(resource, new InputStreamResource(is)); + assertThat(content).isEqualTo("testString"); + assertThat(new InputStreamResource(is)).isEqualTo(resource); } @Test public void testInputStreamResourceWithDescription() throws IOException { InputStream is = new ByteArrayInputStream("testString".getBytes()); Resource resource = new InputStreamResource(is, "my description"); - assertTrue(resource.exists()); - assertTrue(resource.isOpen()); + assertThat(resource.exists()).isTrue(); + assertThat(resource.isOpen()).isTrue(); String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream())); - assertEquals("testString", content); - assertTrue(resource.getDescription().contains("my description")); - assertEquals(resource, new InputStreamResource(is)); + assertThat(content).isEqualTo("testString"); + assertThat(resource.getDescription().contains("my description")).isTrue(); + assertThat(new InputStreamResource(is)).isEqualTo(resource); } @Test @@ -97,15 +94,15 @@ public class ResourceTests { Resource resource = new ClassPathResource("org/springframework/core/io/Resource.class"); doTestResource(resource); Resource resource2 = new ClassPathResource("org/springframework/core/../core/io/./Resource.class"); - assertEquals(resource, resource2); + assertThat(resource2).isEqualTo(resource); Resource resource3 = new ClassPathResource("org/springframework/core/").createRelative("../core/io/./Resource.class"); - assertEquals(resource, resource3); + assertThat(resource3).isEqualTo(resource); // Check whether equal/hashCode works in a HashSet. HashSet resources = new HashSet<>(); resources.add(resource); resources.add(resource2); - assertEquals(1, resources.size()); + assertThat(resources.size()).isEqualTo(1); } @Test @@ -113,15 +110,14 @@ public class ResourceTests { Resource resource = new ClassPathResource("org/springframework/core/io/Resource.class", getClass().getClassLoader()); doTestResource(resource); - assertEquals(resource, - new ClassPathResource("org/springframework/core/../core/io/./Resource.class", getClass().getClassLoader())); + assertThat(new ClassPathResource("org/springframework/core/../core/io/./Resource.class", getClass().getClassLoader())).isEqualTo(resource); } @Test public void testClassPathResourceWithClass() throws IOException { Resource resource = new ClassPathResource("Resource.class", getClass()); doTestResource(resource); - assertEquals(resource, new ClassPathResource("Resource.class", getClass())); + assertThat(new ClassPathResource("Resource.class", getClass())).isEqualTo(resource); } @Test @@ -129,7 +125,7 @@ public class ResourceTests { String file = getClass().getResource("Resource.class").getFile(); Resource resource = new FileSystemResource(file); doTestResource(resource); - assertEquals(new FileSystemResource(file), resource); + assertThat(resource).isEqualTo(new FileSystemResource(file)); } @Test @@ -137,64 +133,64 @@ public class ResourceTests { Path filePath = Paths.get(getClass().getResource("Resource.class").toURI()); Resource resource = new FileSystemResource(filePath); doTestResource(resource); - assertEquals(new FileSystemResource(filePath), resource); + assertThat(resource).isEqualTo(new FileSystemResource(filePath)); } @Test public void testFileSystemResourceWithPlainPath() { Resource resource = new FileSystemResource("core/io/Resource.class"); - assertEquals(resource, new FileSystemResource("core/../core/io/./Resource.class")); + assertThat(new FileSystemResource("core/../core/io/./Resource.class")).isEqualTo(resource); } @Test public void testUrlResource() throws IOException { Resource resource = new UrlResource(getClass().getResource("Resource.class")); doTestResource(resource); - assertEquals(new UrlResource(getClass().getResource("Resource.class")), resource); + assertThat(resource).isEqualTo(new UrlResource(getClass().getResource("Resource.class"))); Resource resource2 = new UrlResource("file:core/io/Resource.class"); - assertEquals(resource2, new UrlResource("file:core/../core/io/./Resource.class")); + assertThat(new UrlResource("file:core/../core/io/./Resource.class")).isEqualTo(resource2); - assertEquals("test.txt", new UrlResource("file:/dir/test.txt?argh").getFilename()); - assertEquals("test.txt", new UrlResource("file:\\dir\\test.txt?argh").getFilename()); - assertEquals("test.txt", new UrlResource("file:\\dir/test.txt?argh").getFilename()); + assertThat(new UrlResource("file:/dir/test.txt?argh").getFilename()).isEqualTo("test.txt"); + assertThat(new UrlResource("file:\\dir\\test.txt?argh").getFilename()).isEqualTo("test.txt"); + assertThat(new UrlResource("file:\\dir/test.txt?argh").getFilename()).isEqualTo("test.txt"); } private void doTestResource(Resource resource) throws IOException { - assertEquals("Resource.class", resource.getFilename()); - assertTrue(resource.getURL().getFile().endsWith("Resource.class")); - assertTrue(resource.exists()); - assertTrue(resource.isReadable()); - assertTrue(resource.contentLength() > 0); - assertTrue(resource.lastModified() > 0); + assertThat(resource.getFilename()).isEqualTo("Resource.class"); + assertThat(resource.getURL().getFile().endsWith("Resource.class")).isTrue(); + assertThat(resource.exists()).isTrue(); + assertThat(resource.isReadable()).isTrue(); + assertThat(resource.contentLength() > 0).isTrue(); + assertThat(resource.lastModified() > 0).isTrue(); Resource relative1 = resource.createRelative("ClassPathResource.class"); - assertEquals("ClassPathResource.class", relative1.getFilename()); - assertTrue(relative1.getURL().getFile().endsWith("ClassPathResource.class")); - assertTrue(relative1.exists()); - assertTrue(relative1.isReadable()); - assertTrue(relative1.contentLength() > 0); - assertTrue(relative1.lastModified() > 0); + assertThat(relative1.getFilename()).isEqualTo("ClassPathResource.class"); + assertThat(relative1.getURL().getFile().endsWith("ClassPathResource.class")).isTrue(); + assertThat(relative1.exists()).isTrue(); + assertThat(relative1.isReadable()).isTrue(); + assertThat(relative1.contentLength() > 0).isTrue(); + assertThat(relative1.lastModified() > 0).isTrue(); Resource relative2 = resource.createRelative("support/ResourcePatternResolver.class"); - assertEquals("ResourcePatternResolver.class", relative2.getFilename()); - assertTrue(relative2.getURL().getFile().endsWith("ResourcePatternResolver.class")); - assertTrue(relative2.exists()); - assertTrue(relative2.isReadable()); - assertTrue(relative2.contentLength() > 0); - assertTrue(relative2.lastModified() > 0); + assertThat(relative2.getFilename()).isEqualTo("ResourcePatternResolver.class"); + assertThat(relative2.getURL().getFile().endsWith("ResourcePatternResolver.class")).isTrue(); + assertThat(relative2.exists()).isTrue(); + assertThat(relative2.isReadable()).isTrue(); + assertThat(relative2.contentLength() > 0).isTrue(); + assertThat(relative2.lastModified() > 0).isTrue(); Resource relative3 = resource.createRelative("../SpringVersion.class"); - assertEquals("SpringVersion.class", relative3.getFilename()); - assertTrue(relative3.getURL().getFile().endsWith("SpringVersion.class")); - assertTrue(relative3.exists()); - assertTrue(relative3.isReadable()); - assertTrue(relative3.contentLength() > 0); - assertTrue(relative3.lastModified() > 0); + assertThat(relative3.getFilename()).isEqualTo("SpringVersion.class"); + assertThat(relative3.getURL().getFile().endsWith("SpringVersion.class")).isTrue(); + assertThat(relative3.exists()).isTrue(); + assertThat(relative3.isReadable()).isTrue(); + assertThat(relative3.contentLength() > 0).isTrue(); + assertThat(relative3.lastModified() > 0).isTrue(); Resource relative4 = resource.createRelative("X.class"); - assertFalse(relative4.exists()); - assertFalse(relative4.isReadable()); + assertThat(relative4.exists()).isFalse(); + assertThat(relative4.isReadable()).isFalse(); assertThatExceptionOfType(FileNotFoundException.class).isThrownBy( relative4::contentLength); assertThatExceptionOfType(FileNotFoundException.class).isThrownBy( @@ -205,27 +201,27 @@ public class ResourceTests { public void testClassPathResourceWithRelativePath() throws IOException { Resource resource = new ClassPathResource("dir/"); Resource relative = resource.createRelative("subdir"); - assertEquals(new ClassPathResource("dir/subdir"), relative); + assertThat(relative).isEqualTo(new ClassPathResource("dir/subdir")); } @Test public void testFileSystemResourceWithRelativePath() throws IOException { Resource resource = new FileSystemResource("dir/"); Resource relative = resource.createRelative("subdir"); - assertEquals(new FileSystemResource("dir/subdir"), relative); + assertThat(relative).isEqualTo(new FileSystemResource("dir/subdir")); } @Test public void testUrlResourceWithRelativePath() throws IOException { Resource resource = new UrlResource("file:dir/"); Resource relative = resource.createRelative("subdir"); - assertEquals(new UrlResource("file:dir/subdir"), relative); + assertThat(relative).isEqualTo(new UrlResource("file:dir/subdir")); } @Ignore @Test // this test is quite slow. TODO: re-enable with JUnit categories public void testNonFileResourceExists() throws Exception { Resource resource = new UrlResource("https://www.springframework.org"); - assertTrue(resource.exists()); + assertThat(resource.exists()).isTrue(); } @Test @@ -280,7 +276,7 @@ public class ResourceTests { ByteBuffer buffer = ByteBuffer.allocate((int) resource.contentLength()); channel.read(buffer); buffer.rewind(); - assertTrue(buffer.limit() > 0); + assertThat(buffer.limit() > 0).isTrue(); } finally { if (channel != null) { diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/AbstractDataBufferAllocatingTestCase.java b/spring-core/src/test/java/org/springframework/core/io/buffer/AbstractDataBufferAllocatingTestCase.java index c795dc29dae..595c34859d2 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/AbstractDataBufferAllocatingTestCase.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/AbstractDataBufferAllocatingTestCase.java @@ -36,7 +36,7 @@ import reactor.core.publisher.Mono; import org.springframework.core.io.buffer.support.DataBufferTestUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Base class for tests that read or write data buffers with a rule to check @@ -96,7 +96,7 @@ public abstract class AbstractDataBufferAllocatingTestCase { String value = DataBufferTestUtils.dumpString(dataBuffer, StandardCharsets.UTF_8); DataBufferUtils.release(dataBuffer); - assertEquals(expected, value); + assertThat(value).isEqualTo(expected); }; } @@ -139,7 +139,7 @@ public abstract class AbstractDataBufferAllocatingTestCase { } continue; } - assertEquals("ByteBuf Leak: " + total + " unreleased allocations", 0, total); + assertThat(total).as("ByteBuf Leak: " + total + " unreleased allocations").isEqualTo(0); } } } diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java index 3baeb23e2bf..e2a3107bc9b 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java @@ -25,11 +25,9 @@ import java.util.Arrays; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Arjen Poutsma @@ -40,39 +38,39 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { public void byteCountsAndPositions() { DataBuffer buffer = createDataBuffer(2); - assertEquals(0, buffer.readPosition()); - assertEquals(0, buffer.writePosition()); - assertEquals(0, buffer.readableByteCount()); - assertEquals(2, buffer.writableByteCount()); - assertEquals(2, buffer.capacity()); + assertThat(buffer.readPosition()).isEqualTo(0); + assertThat(buffer.writePosition()).isEqualTo(0); + assertThat(buffer.readableByteCount()).isEqualTo(0); + assertThat(buffer.writableByteCount()).isEqualTo(2); + assertThat(buffer.capacity()).isEqualTo(2); buffer.write((byte) 'a'); - assertEquals(0, buffer.readPosition()); - assertEquals(1, buffer.writePosition()); - assertEquals(1, buffer.readableByteCount()); - assertEquals(1, buffer.writableByteCount()); - assertEquals(2, buffer.capacity()); + assertThat(buffer.readPosition()).isEqualTo(0); + assertThat(buffer.writePosition()).isEqualTo(1); + assertThat(buffer.readableByteCount()).isEqualTo(1); + assertThat(buffer.writableByteCount()).isEqualTo(1); + assertThat(buffer.capacity()).isEqualTo(2); buffer.write((byte) 'b'); - assertEquals(0, buffer.readPosition()); - assertEquals(2, buffer.writePosition()); - assertEquals(2, buffer.readableByteCount()); - assertEquals(0, buffer.writableByteCount()); - assertEquals(2, buffer.capacity()); + assertThat(buffer.readPosition()).isEqualTo(0); + assertThat(buffer.writePosition()).isEqualTo(2); + assertThat(buffer.readableByteCount()).isEqualTo(2); + assertThat(buffer.writableByteCount()).isEqualTo(0); + assertThat(buffer.capacity()).isEqualTo(2); buffer.read(); - assertEquals(1, buffer.readPosition()); - assertEquals(2, buffer.writePosition()); - assertEquals(1, buffer.readableByteCount()); - assertEquals(0, buffer.writableByteCount()); - assertEquals(2, buffer.capacity()); + assertThat(buffer.readPosition()).isEqualTo(1); + assertThat(buffer.writePosition()).isEqualTo(2); + assertThat(buffer.readableByteCount()).isEqualTo(1); + assertThat(buffer.writableByteCount()).isEqualTo(0); + assertThat(buffer.capacity()).isEqualTo(2); buffer.read(); - assertEquals(2, buffer.readPosition()); - assertEquals(2, buffer.writePosition()); - assertEquals(0, buffer.readableByteCount()); - assertEquals(0, buffer.writableByteCount()); - assertEquals(2, buffer.capacity()); + assertThat(buffer.readPosition()).isEqualTo(2); + assertThat(buffer.writePosition()).isEqualTo(2); + assertThat(buffer.readableByteCount()).isEqualTo(0); + assertThat(buffer.writableByteCount()).isEqualTo(0); + assertThat(buffer.capacity()).isEqualTo(2); release(buffer); } @@ -133,7 +131,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { buffer.write(new byte[]{'a', 'b', 'c'}); int ch = buffer.read(); - assertEquals('a', ch); + assertThat(ch).isEqualTo((byte) 'a'); buffer.write((byte) 'd'); buffer.write((byte) 'e'); @@ -141,7 +139,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { byte[] result = new byte[4]; buffer.read(result); - assertArrayEquals(new byte[]{'b', 'c', 'd', 'e'}, result); + assertThat(result).isEqualTo(new byte[]{'b', 'c', 'd', 'e'}); release(buffer); } @@ -175,7 +173,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { DataBuffer buffer = createDataBuffer(1); buffer.write("", StandardCharsets.UTF_8); - assertEquals(0, buffer.readableByteCount()); + assertThat(buffer.readableByteCount()).isEqualTo(0); release(buffer); } @@ -188,7 +186,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { byte[] result = new byte[6]; buffer.read(result); - assertArrayEquals("Spring".getBytes(StandardCharsets.UTF_8), result); + assertThat(result).isEqualTo("Spring".getBytes(StandardCharsets.UTF_8)); release(buffer); } @@ -200,7 +198,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { byte[] result = new byte[10]; buffer.read(result); - assertArrayEquals("Spring €".getBytes(StandardCharsets.UTF_8), result); + assertThat(result).isEqualTo("Spring €".getBytes(StandardCharsets.UTF_8)); release(buffer); } @@ -212,7 +210,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { byte[] result = new byte[1]; buffer.read(result); - assertArrayEquals("\u00A3".getBytes(StandardCharsets.ISO_8859_1), result); + assertThat(result).isEqualTo("\u00A3".getBytes(StandardCharsets.ISO_8859_1)); release(buffer); } @@ -221,18 +219,18 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { DataBuffer buffer = createDataBuffer(1); buffer.write("abc", StandardCharsets.UTF_8); - assertEquals(3, buffer.readableByteCount()); + assertThat(buffer.readableByteCount()).isEqualTo(3); buffer.write("def", StandardCharsets.UTF_8); - assertEquals(6, buffer.readableByteCount()); + assertThat(buffer.readableByteCount()).isEqualTo(6); buffer.write("ghi", StandardCharsets.UTF_8); - assertEquals(9, buffer.readableByteCount()); + assertThat(buffer.readableByteCount()).isEqualTo(9); byte[] result = new byte[9]; buffer.read(result); - assertArrayEquals("abcdefghi".getBytes(), result); + assertThat(result).isEqualTo("abcdefghi".getBytes()); release(buffer); } @@ -245,26 +243,26 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { InputStream inputStream = buffer.asInputStream(); - assertEquals(4, inputStream.available()); + assertThat(inputStream.available()).isEqualTo(4); int result = inputStream.read(); - assertEquals('b', result); - assertEquals(3, inputStream.available()); + assertThat(result).isEqualTo((byte) 'b'); + assertThat(inputStream.available()).isEqualTo(3); byte[] bytes = new byte[2]; int len = inputStream.read(bytes); - assertEquals(2, len); - assertArrayEquals(new byte[]{'c', 'd'}, bytes); - assertEquals(1, inputStream.available()); + assertThat(len).isEqualTo(2); + assertThat(bytes).isEqualTo(new byte[]{'c', 'd'}); + assertThat(inputStream.available()).isEqualTo(1); Arrays.fill(bytes, (byte) 0); len = inputStream.read(bytes); - assertEquals(1, len); - assertArrayEquals(new byte[]{'e', (byte) 0}, bytes); - assertEquals(0, inputStream.available()); + assertThat(len).isEqualTo(1); + assertThat(bytes).isEqualTo(new byte[]{'e', (byte) 0}); + assertThat(inputStream.available()).isEqualTo(0); - assertEquals(-1, inputStream.read()); - assertEquals(-1, inputStream.read(bytes)); + assertThat(inputStream.read()).isEqualTo(-1); + assertThat(inputStream.read(bytes)).isEqualTo(-1); release(buffer); } @@ -280,8 +278,8 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { try { byte[] result = new byte[3]; int len = inputStream.read(result); - assertEquals(3, len); - assertArrayEquals(bytes, result); + assertThat(len).isEqualTo(3); + assertThat(result).isEqualTo(bytes); } finally { inputStream.close(); @@ -304,7 +302,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { byte[] bytes = new byte[5]; buffer.read(bytes); - assertArrayEquals(new byte[]{'a', 'b', 'c', 'd', 'e'}, bytes); + assertThat(bytes).isEqualTo(new byte[]{'a', 'b', 'c', 'd', 'e'}); release(buffer); } @@ -313,10 +311,10 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { public void expand() { DataBuffer buffer = createDataBuffer(1); buffer.write((byte) 'a'); - assertEquals(1, buffer.capacity()); + assertThat(buffer.capacity()).isEqualTo(1); buffer.write((byte) 'b'); - assertTrue(buffer.capacity() > 1); + assertThat(buffer.capacity() > 1).isTrue(); release(buffer); } @@ -324,10 +322,10 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { @Test public void increaseCapacity() { DataBuffer buffer = createDataBuffer(1); - assertEquals(1, buffer.capacity()); + assertThat(buffer.capacity()).isEqualTo(1); buffer.capacity(2); - assertEquals(2, buffer.capacity()); + assertThat(buffer.capacity()).isEqualTo(2); release(buffer); } @@ -337,7 +335,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { DataBuffer buffer = createDataBuffer(2); buffer.writePosition(2); buffer.capacity(1); - assertEquals(1, buffer.capacity()); + assertThat(buffer.capacity()).isEqualTo(1); release(buffer); } @@ -348,7 +346,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { buffer.writePosition(2); buffer.readPosition(2); buffer.capacity(1); - assertEquals(1, buffer.capacity()); + assertThat(buffer.capacity()).isEqualTo(1); release(buffer); } @@ -379,11 +377,11 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { buffer1.write(buffer2, buffer3); buffer1.write((byte) 'd'); // make sure the write index is correctly set - assertEquals(4, buffer1.readableByteCount()); + assertThat(buffer1.readableByteCount()).isEqualTo(4); byte[] result = new byte[4]; buffer1.read(result); - assertArrayEquals(new byte[]{'a', 'b', 'c', 'd'}, result); + assertThat(result).isEqualTo(new byte[]{'a', 'b', 'c', 'd'}); release(buffer1); } @@ -404,11 +402,11 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { buffer1.write(buffer2, buffer3); buffer1.write((byte) 'd'); // make sure the write index is correctly set - assertEquals(4, buffer1.readableByteCount()); + assertThat(buffer1.readableByteCount()).isEqualTo(4); byte[] result = new byte[4]; buffer1.read(result); - assertArrayEquals(new byte[]{'a', 'b', 'c', 'd'}, result); + assertThat(result).isEqualTo(new byte[]{'a', 'b', 'c', 'd'}); release(buffer1, buffer2, buffer3); } @@ -420,14 +418,14 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { buffer.read(); // skip a ByteBuffer result = buffer.asByteBuffer(); - assertEquals(2, result.capacity()); + assertThat(result.capacity()).isEqualTo(2); buffer.write((byte) 'd'); - assertEquals(2, result.remaining()); + assertThat(result.remaining()).isEqualTo(2); byte[] resultBytes = new byte[2]; result.get(resultBytes); - assertArrayEquals(new byte[]{'b', 'c'}, resultBytes); + assertThat(resultBytes).isEqualTo(new byte[]{'b', 'c'}); release(buffer); } @@ -438,14 +436,14 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { buffer.write(new byte[]{'a', 'b'}); ByteBuffer result = buffer.asByteBuffer(1, 2); - assertEquals(2, result.capacity()); + assertThat(result.capacity()).isEqualTo(2); buffer.write((byte) 'c'); - assertEquals(2, result.remaining()); + assertThat(result.remaining()).isEqualTo(2); byte[] resultBytes = new byte[2]; result.get(resultBytes); - assertArrayEquals(new byte[]{'b', 'c'}, resultBytes); + assertThat(resultBytes).isEqualTo(new byte[]{'b', 'c'}); release(buffer); } @@ -457,9 +455,9 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { dataBuffer.write((byte) 'a'); - assertEquals(1, byteBuffer.limit()); + assertThat(byteBuffer.limit()).isEqualTo(1); byte b = byteBuffer.get(); - assertEquals('a', b); + assertThat(b).isEqualTo((byte) 'a'); release(dataBuffer); } @@ -473,7 +471,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { dataBuffer.writePosition(1); byte b = dataBuffer.read(); - assertEquals('a', b); + assertThat(b).isEqualTo((byte) 'a'); release(dataBuffer); } @@ -483,7 +481,7 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { DataBuffer buffer = createDataBuffer(1); ByteBuffer result = buffer.asByteBuffer(); - assertEquals(0, result.capacity()); + assertThat(result.capacity()).isEqualTo(0); release(buffer); } @@ -494,16 +492,16 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { buffer.write(new byte[]{'a', 'b', 'c'}); int result = buffer.indexOf(b -> b == 'c', 0); - assertEquals(2, result); + assertThat(result).isEqualTo(2); result = buffer.indexOf(b -> b == 'c', Integer.MIN_VALUE); - assertEquals(2, result); + assertThat(result).isEqualTo(2); result = buffer.indexOf(b -> b == 'c', Integer.MAX_VALUE); - assertEquals(-1, result); + assertThat(result).isEqualTo(-1); result = buffer.indexOf(b -> b == 'z', 0); - assertEquals(-1, result); + assertThat(result).isEqualTo(-1); release(buffer); } @@ -514,25 +512,25 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { buffer.write(new byte[]{'a', 'b', 'c'}); int result = buffer.lastIndexOf(b -> b == 'b', 2); - assertEquals(1, result); + assertThat(result).isEqualTo(1); result = buffer.lastIndexOf(b -> b == 'c', 2); - assertEquals(2, result); + assertThat(result).isEqualTo(2); result = buffer.lastIndexOf(b -> b == 'b', Integer.MAX_VALUE); - assertEquals(1, result); + assertThat(result).isEqualTo(1); result = buffer.lastIndexOf(b -> b == 'c', Integer.MAX_VALUE); - assertEquals(2, result); + assertThat(result).isEqualTo(2); result = buffer.lastIndexOf(b -> b == 'b', Integer.MIN_VALUE); - assertEquals(-1, result); + assertThat(result).isEqualTo(-1); result = buffer.lastIndexOf(b -> b == 'c', Integer.MIN_VALUE); - assertEquals(-1, result); + assertThat(result).isEqualTo(-1); result = buffer.lastIndexOf(b -> b == 'z', 0); - assertEquals(-1, result); + assertThat(result).isEqualTo(-1); release(buffer); } @@ -543,22 +541,22 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { buffer.write(new byte[]{'a', 'b'}); DataBuffer slice = buffer.slice(1, 2); - assertEquals(2, slice.readableByteCount()); + assertThat(slice.readableByteCount()).isEqualTo(2); assertThatExceptionOfType(Exception.class).isThrownBy(() -> slice.write((byte) 0)); buffer.write((byte) 'c'); - assertEquals(3, buffer.readableByteCount()); + assertThat(buffer.readableByteCount()).isEqualTo(3); byte[] result = new byte[3]; buffer.read(result); - assertArrayEquals(new byte[]{'a', 'b', 'c'}, result); + assertThat(result).isEqualTo(new byte[]{'a', 'b', 'c'}); - assertEquals(2, slice.readableByteCount()); + assertThat(slice.readableByteCount()).isEqualTo(2); result = new byte[2]; slice.read(result); - assertArrayEquals(new byte[]{'b', 'c'}, result); + assertThat(result).isEqualTo(new byte[]{'b', 'c'}); release(buffer); @@ -570,22 +568,22 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { buffer.write(new byte[]{'a', 'b'}); DataBuffer slice = buffer.retainedSlice(1, 2); - assertEquals(2, slice.readableByteCount()); + assertThat(slice.readableByteCount()).isEqualTo(2); assertThatExceptionOfType(Exception.class).isThrownBy(() -> slice.write((byte) 0)); buffer.write((byte) 'c'); - assertEquals(3, buffer.readableByteCount()); + assertThat(buffer.readableByteCount()).isEqualTo(3); byte[] result = new byte[3]; buffer.read(result); - assertArrayEquals(new byte[]{'a', 'b', 'c'}, result); + assertThat(result).isEqualTo(new byte[]{'a', 'b', 'c'}); - assertEquals(2, slice.readableByteCount()); + assertThat(slice.readableByteCount()).isEqualTo(2); result = new byte[2]; slice.read(result); - assertArrayEquals(new byte[]{'b', 'c'}, result); + assertThat(result).isEqualTo(new byte[]{'b', 'c'}); release(buffer, slice); @@ -600,11 +598,11 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { buffer.writePosition(3); buffer.write(slice); - assertEquals(6, buffer.readableByteCount()); + assertThat(buffer.readableByteCount()).isEqualTo(6); byte[] result = new byte[6]; buffer.read(result); - assertArrayEquals(bytes, result); + assertThat(result).isEqualTo(bytes); release(buffer); } @@ -613,11 +611,11 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { public void join() { DataBuffer composite = this.bufferFactory.join(Arrays.asList(stringBuffer("a"), stringBuffer("b"), stringBuffer("c"))); - assertEquals(3, composite.readableByteCount()); + assertThat(composite.readableByteCount()).isEqualTo(3); byte[] bytes = new byte[3]; composite.read(bytes); - assertArrayEquals(new byte[] {'a','b','c'}, bytes); + assertThat(bytes).isEqualTo(new byte[] {'a','b','c'}); release(composite); } @@ -626,9 +624,9 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase { public void getByte() { DataBuffer buffer = stringBuffer("abc"); - assertEquals('a', buffer.getByte(0)); - assertEquals('b', buffer.getByte(1)); - assertEquals('c', buffer.getByte(2)); + assertThat(buffer.getByte(0)).isEqualTo((byte) 'a'); + assertThat(buffer.getByte(1)).isEqualTo((byte) 'b'); + assertThat(buffer.getByte(2)).isEqualTo((byte) 'c'); assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> buffer.getByte(-1)); diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java index ed943c0c934..f1e0162c438 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferUtilsTests.java @@ -48,7 +48,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.buffer.support.DataBufferTestUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.isA; @@ -155,7 +155,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { byteBuffer.put("foo".getBytes(StandardCharsets.UTF_8)); byteBuffer.flip(); long pos = invocation.getArgument(1); - assertEquals(0, pos); + assertThat(pos).isEqualTo(0); DataBuffer dataBuffer = invocation.getArgument(2); CompletionHandler completionHandler = invocation.getArgument(3); completionHandler.completed(3, dataBuffer); @@ -306,7 +306,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { String result = String.join("", Files.readAllLines(tempFile)); - assertEquals("foobar", result); + assertThat(result).isEqualTo("foobar"); channel.close(); } @@ -352,7 +352,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { String result = String.join("", Files.readAllLines(tempFile)); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); channel.close(); flux.subscribe(DataBufferUtils::release); @@ -385,7 +385,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { String result = String.join("", Files.readAllLines(tempFile)); - assertEquals("foobarbazqux", result); + assertThat(result).isEqualTo("foobarbazqux"); } @Test @@ -407,7 +407,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { String result = String.join("", Files.readAllLines(tempFile)); - assertEquals("foobar", result); + assertThat(result).isEqualTo("foobar"); channel.close(); } @@ -424,7 +424,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { long pos = invocation.getArgument(1); CompletionHandler completionHandler = invocation.getArgument(3); - assertEquals(0, pos); + assertThat(pos).isEqualTo(0); int written = buffer.remaining(); buffer.position(buffer.limit()); @@ -468,7 +468,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { String result = String.join("", Files.readAllLines(tempFile)); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); channel.close(); flux.subscribe(DataBufferUtils::release); @@ -495,7 +495,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { try { String expected = String.join("", Files.readAllLines(source)); String result = String.join("", Files.readAllLines(destination)); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); } catch (IOException e) { throw new AssertionError(e.getMessage(), e); @@ -530,7 +530,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { String expected = String.join("", Files.readAllLines(source)); String result = String.join("", Files.readAllLines(destination)); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); latch.countDown(); } @@ -677,7 +677,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { private static void assertReleased(DataBuffer dataBuffer) { if (dataBuffer instanceof NettyDataBuffer) { ByteBuf byteBuf = ((NettyDataBuffer) dataBuffer).getNativeBuffer(); - assertEquals(0, byteBuf.refCnt()); + assertThat(byteBuf.refCnt()).isEqualTo(0); } } @@ -720,8 +720,7 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { StepVerifier.create(result) .consumeNextWith(dataBuffer -> { - assertEquals("foobarbaz", - DataBufferTestUtils.dumpString(dataBuffer, StandardCharsets.UTF_8)); + assertThat(DataBufferTestUtils.dumpString(dataBuffer, StandardCharsets.UTF_8)).isEqualTo("foobarbaz"); release(dataBuffer); }) .verifyComplete(); @@ -761,9 +760,9 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { byte[] delims = "ooba".getBytes(StandardCharsets.UTF_8); DataBufferUtils.Matcher matcher = DataBufferUtils.matcher(delims); int result = matcher.match(foo); - assertEquals(-1, result); + assertThat(result).isEqualTo(-1); result = matcher.match(bar); - assertEquals(1, result); + assertThat(result).isEqualTo(1); release(foo, bar); @@ -776,13 +775,13 @@ public class DataBufferUtilsTests extends AbstractDataBufferAllocatingTestCase { byte[] delims = "oo".getBytes(StandardCharsets.UTF_8); DataBufferUtils.Matcher matcher = DataBufferUtils.matcher(delims); int result = matcher.match(foo); - assertEquals(2, result); + assertThat(result).isEqualTo(2); foo.readPosition(2); result = matcher.match(foo); - assertEquals(3, result); + assertThat(result).isEqualTo(3); foo.readPosition(3); result = matcher.match(foo); - assertEquals(-1, result); + assertThat(result).isEqualTo(-1); release(foo); } diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/PooledDataBufferTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/PooledDataBufferTests.java index f24005d7af7..71fe1f46299 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/PooledDataBufferTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/PooledDataBufferTests.java @@ -22,9 +22,8 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Arjen Poutsma @@ -56,9 +55,9 @@ public class PooledDataBufferTests { buffer.retain(); boolean result = buffer.release(); - assertFalse(result); + assertThat(result).isFalse(); result = buffer.release(); - assertTrue(result); + assertThat(result).isTrue(); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/support/DataBufferTestUtilsTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/support/DataBufferTestUtilsTests.java index 46b26007804..89dcb20fe2a 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/support/DataBufferTestUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/support/DataBufferTestUtilsTests.java @@ -23,8 +23,7 @@ import org.junit.Test; import org.springframework.core.io.buffer.AbstractDataBufferAllocatingTestCase; import org.springframework.core.io.buffer.DataBuffer; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -39,7 +38,7 @@ public class DataBufferTestUtilsTests extends AbstractDataBufferAllocatingTestCa byte[] result = DataBufferTestUtils.dumpBytes(buffer); - assertArrayEquals(source, result); + assertThat(result).isEqualTo(source); release(buffer); } @@ -52,7 +51,7 @@ public class DataBufferTestUtilsTests extends AbstractDataBufferAllocatingTestCa String result = DataBufferTestUtils.dumpString(buffer, StandardCharsets.UTF_8); - assertEquals(source, result); + assertThat(result).isEqualTo(source); release(buffer); } diff --git a/spring-core/src/test/java/org/springframework/core/io/support/EncodedResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/support/EncodedResourceTests.java index f2ed4ee49ad..cc50b0a031d 100644 --- a/spring-core/src/test/java/org/springframework/core/io/support/EncodedResourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/support/EncodedResourceTests.java @@ -23,9 +23,7 @@ import org.junit.Test; import org.springframework.core.io.DescriptiveResource; import org.springframework.core.io.Resource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link EncodedResource}. @@ -45,42 +43,42 @@ public class EncodedResourceTests { @Test public void equalsWithNullOtherObject() { - assertFalse(new EncodedResource(resource).equals(null)); + assertThat(new EncodedResource(resource).equals(null)).isFalse(); } @Test public void equalsWithSameEncoding() { EncodedResource er1 = new EncodedResource(resource, UTF8); EncodedResource er2 = new EncodedResource(resource, UTF8); - assertEquals(er1, er2); + assertThat(er2).isEqualTo(er1); } @Test public void equalsWithDifferentEncoding() { EncodedResource er1 = new EncodedResource(resource, UTF8); EncodedResource er2 = new EncodedResource(resource, UTF16); - assertNotEquals(er1, er2); + assertThat(er2).isNotEqualTo(er1); } @Test public void equalsWithSameCharset() { EncodedResource er1 = new EncodedResource(resource, UTF8_CS); EncodedResource er2 = new EncodedResource(resource, UTF8_CS); - assertEquals(er1, er2); + assertThat(er2).isEqualTo(er1); } @Test public void equalsWithDifferentCharset() { EncodedResource er1 = new EncodedResource(resource, UTF8_CS); EncodedResource er2 = new EncodedResource(resource, UTF16_CS); - assertNotEquals(er1, er2); + assertThat(er2).isNotEqualTo(er1); } @Test public void equalsWithEncodingAndCharset() { EncodedResource er1 = new EncodedResource(resource, UTF8); EncodedResource er2 = new EncodedResource(resource, UTF8_CS); - assertNotEquals(er1, er2); + assertThat(er2).isNotEqualTo(er1); } } diff --git a/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java b/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java index c02123bad94..2a1c7073d39 100644 --- a/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java @@ -28,9 +28,8 @@ import org.junit.Test; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * If this test case fails, uncomment diagnostics in the @@ -69,14 +68,14 @@ public class PathMatchingResourcePatternResolverTests { public void singleResourceOnFileSystem() throws IOException { Resource[] resources = resolver.getResources("org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.class"); - assertEquals(1, resources.length); + assertThat(resources.length).isEqualTo(1); assertProtocolAndFilenames(resources, "file", "PathMatchingResourcePatternResolverTests.class"); } @Test public void singleResourceInJar() throws IOException { Resource[] resources = resolver.getResources("org/reactivestreams/Publisher.class"); - assertEquals(1, resources.length); + assertThat(resources.length).isEqualTo(1); assertProtocolAndFilenames(resources, "jar", "Publisher.class"); } @@ -119,7 +118,7 @@ public class PathMatchingResourcePatternResolverTests { break; } } - assertTrue("Could not find aspectj_1_5_0.dtd in the root of the aspectjweaver jar", found); + assertThat(found).as("Could not find aspectj_1_5_0.dtd in the root of the aspectjweaver jar").isTrue(); } @@ -144,18 +143,17 @@ public class PathMatchingResourcePatternResolverTests { // System.out.println(resources[i]); // } - assertEquals("Correct number of files found", filenames.length, resources.length); + assertThat(resources.length).as("Correct number of files found").isEqualTo(filenames.length); for (Resource resource : resources) { String actualProtocol = resource.getURL().getProtocol(); - assertEquals(protocol, actualProtocol); + assertThat(actualProtocol).isEqualTo(protocol); assertFilenameIn(resource, filenames); } } private void assertFilenameIn(Resource resource, String... filenames) { String filename = resource.getFilename(); - assertTrue(resource + " does not have a filename that matches any of the specified names", - Arrays.stream(filenames).anyMatch(filename::endsWith)); + assertThat(Arrays.stream(filenames).anyMatch(filename::endsWith)).as(resource + " does not have a filename that matches any of the specified names").isTrue(); } } diff --git a/spring-core/src/test/java/org/springframework/core/io/support/ResourceArrayPropertyEditorTests.java b/spring-core/src/test/java/org/springframework/core/io/support/ResourceArrayPropertyEditorTests.java index ffdcc1fef45..0402bbd0ccf 100644 --- a/spring-core/src/test/java/org/springframework/core/io/support/ResourceArrayPropertyEditorTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/support/ResourceArrayPropertyEditorTests.java @@ -23,10 +23,8 @@ import org.junit.Test; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.Resource; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * @author Dave Syer @@ -39,8 +37,8 @@ public class ResourceArrayPropertyEditorTests { PropertyEditor editor = new ResourceArrayPropertyEditor(); editor.setAsText("classpath:org/springframework/core/io/support/ResourceArrayPropertyEditor.class"); Resource[] resources = (Resource[]) editor.getValue(); - assertNotNull(resources); - assertTrue(resources[0].exists()); + assertThat(resources).isNotNull(); + assertThat(resources[0].exists()).isTrue(); } @Test @@ -52,8 +50,8 @@ public class ResourceArrayPropertyEditorTests { PropertyEditor editor = new ResourceArrayPropertyEditor(); editor.setAsText("classpath*:org/springframework/core/io/support/Resource*Editor.class"); Resource[] resources = (Resource[]) editor.getValue(); - assertNotNull(resources); - assertTrue(resources[0].exists()); + assertThat(resources).isNotNull(); + assertThat(resources[0].exists()).isTrue(); } @Test @@ -63,7 +61,7 @@ public class ResourceArrayPropertyEditorTests { try { editor.setAsText("${test.prop}"); Resource[] resources = (Resource[]) editor.getValue(); - assertEquals("foo", resources[0].getFilename()); + assertThat(resources[0].getFilename()).isEqualTo("foo"); } finally { System.getProperties().remove("test.prop"); diff --git a/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java b/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java index 4248fb9782e..d7592047efd 100644 --- a/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java @@ -25,7 +25,6 @@ import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ClassPathResource; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link ResourcePropertySource}. @@ -47,57 +46,57 @@ public class ResourcePropertySourceTests { @Test public void withLocationAndGeneratedName() throws IOException { PropertySource ps = new ResourcePropertySource(PROPERTIES_LOCATION); - assertEquals("bar", ps.getProperty("foo")); + assertThat(ps.getProperty("foo")).isEqualTo("bar"); assertThat(ps.getName()).isEqualTo(PROPERTIES_RESOURCE_DESCRIPTION); } @Test public void xmlWithLocationAndGeneratedName() throws IOException { PropertySource ps = new ResourcePropertySource(XML_PROPERTIES_LOCATION); - assertEquals("bar", ps.getProperty("foo")); + assertThat(ps.getProperty("foo")).isEqualTo("bar"); assertThat(ps.getName()).isEqualTo(XML_PROPERTIES_RESOURCE_DESCRIPTION); } @Test public void withLocationAndExplicitName() throws IOException { PropertySource ps = new ResourcePropertySource("ps1", PROPERTIES_LOCATION); - assertEquals("bar", ps.getProperty("foo")); + assertThat(ps.getProperty("foo")).isEqualTo("bar"); assertThat(ps.getName()).isEqualTo("ps1"); } @Test public void withLocationAndExplicitNameAndExplicitClassLoader() throws IOException { PropertySource ps = new ResourcePropertySource("ps1", PROPERTIES_LOCATION, getClass().getClassLoader()); - assertEquals("bar", ps.getProperty("foo")); + assertThat(ps.getProperty("foo")).isEqualTo("bar"); assertThat(ps.getName()).isEqualTo("ps1"); } @Test public void withLocationAndGeneratedNameAndExplicitClassLoader() throws IOException { PropertySource ps = new ResourcePropertySource(PROPERTIES_LOCATION, getClass().getClassLoader()); - assertEquals("bar", ps.getProperty("foo")); + assertThat(ps.getProperty("foo")).isEqualTo("bar"); assertThat(ps.getName()).isEqualTo(PROPERTIES_RESOURCE_DESCRIPTION); } @Test public void withResourceAndGeneratedName() throws IOException { PropertySource ps = new ResourcePropertySource(new ClassPathResource(PROPERTIES_PATH)); - assertEquals("bar", ps.getProperty("foo")); + assertThat(ps.getProperty("foo")).isEqualTo("bar"); assertThat(ps.getName()).isEqualTo(PROPERTIES_RESOURCE_DESCRIPTION); } @Test public void withResourceAndExplicitName() throws IOException { PropertySource ps = new ResourcePropertySource("ps1", new ClassPathResource(PROPERTIES_PATH)); - assertEquals("bar", ps.getProperty("foo")); + assertThat(ps.getProperty("foo")).isEqualTo("bar"); assertThat(ps.getName()).isEqualTo("ps1"); } @Test public void withResourceHavingNoDescription() throws IOException { PropertySource ps = new ResourcePropertySource(new ByteArrayResource("foo=bar".getBytes(), "")); - assertEquals("bar", ps.getProperty("foo")); - assertEquals("Byte array resource []", ps.getName()); + assertThat(ps.getProperty("foo")).isEqualTo("bar"); + assertThat(ps.getName()).isEqualTo("Byte array resource []"); } } diff --git a/spring-core/src/test/java/org/springframework/core/io/support/SpringFactoriesLoaderTests.java b/spring-core/src/test/java/org/springframework/core/io/support/SpringFactoriesLoaderTests.java index 18c8aff340d..c8a023701f1 100644 --- a/spring-core/src/test/java/org/springframework/core/io/support/SpringFactoriesLoaderTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/support/SpringFactoriesLoaderTests.java @@ -21,10 +21,8 @@ import java.util.List; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Tests for {@link SpringFactoriesLoader}. @@ -38,17 +36,19 @@ public class SpringFactoriesLoaderTests { @Test public void loadFactoriesInCorrectOrder() { List factories = SpringFactoriesLoader.loadFactories(DummyFactory.class, null); - assertEquals(2, factories.size()); - assertTrue(factories.get(0) instanceof MyDummyFactory1); - assertTrue(factories.get(1) instanceof MyDummyFactory2); + assertThat(factories.size()).isEqualTo(2); + boolean condition1 = factories.get(0) instanceof MyDummyFactory1; + assertThat(condition1).isTrue(); + boolean condition = factories.get(1) instanceof MyDummyFactory2; + assertThat(condition).isTrue(); } @Test public void loadPackagePrivateFactory() { List factories = SpringFactoriesLoader.loadFactories(DummyPackagePrivateFactory.class, null); - assertEquals(1, factories.size()); - assertFalse(Modifier.isPublic(factories.get(0).getClass().getModifiers())); + assertThat(factories.size()).isEqualTo(1); + assertThat(Modifier.isPublic(factories.get(0).getClass().getModifiers())).isFalse(); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/log/LogSupportTests.java b/spring-core/src/test/java/org/springframework/core/log/LogSupportTests.java index f52d16df5f5..aa9908b08b0 100644 --- a/spring-core/src/test/java/org/springframework/core/log/LogSupportTests.java +++ b/spring-core/src/test/java/org/springframework/core/log/LogSupportTests.java @@ -18,8 +18,7 @@ package org.springframework.core.log; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -30,43 +29,43 @@ public class LogSupportTests { @Test public void testLogMessageWithSupplier() { LogMessage msg = LogMessage.of(() -> new StringBuilder("a").append(" b")); - assertEquals("a b", msg.toString()); - assertSame(msg.toString(), msg.toString()); + assertThat(msg.toString()).isEqualTo("a b"); + assertThat(msg.toString()).isSameAs(msg.toString()); } @Test public void testLogMessageWithFormat1() { LogMessage msg = LogMessage.format("a %s", "b"); - assertEquals("a b", msg.toString()); - assertSame(msg.toString(), msg.toString()); + assertThat(msg.toString()).isEqualTo("a b"); + assertThat(msg.toString()).isSameAs(msg.toString()); } @Test public void testLogMessageWithFormat2() { LogMessage msg = LogMessage.format("a %s %s", "b", "c"); - assertEquals("a b c", msg.toString()); - assertSame(msg.toString(), msg.toString()); + assertThat(msg.toString()).isEqualTo("a b c"); + assertThat(msg.toString()).isSameAs(msg.toString()); } @Test public void testLogMessageWithFormat3() { LogMessage msg = LogMessage.format("a %s %s %s", "b", "c", "d"); - assertEquals("a b c d", msg.toString()); - assertSame(msg.toString(), msg.toString()); + assertThat(msg.toString()).isEqualTo("a b c d"); + assertThat(msg.toString()).isSameAs(msg.toString()); } @Test public void testLogMessageWithFormat4() { LogMessage msg = LogMessage.format("a %s %s %s %s", "b", "c", "d", "e"); - assertEquals("a b c d e", msg.toString()); - assertSame(msg.toString(), msg.toString()); + assertThat(msg.toString()).isEqualTo("a b c d e"); + assertThat(msg.toString()).isSameAs(msg.toString()); } @Test public void testLogMessageWithFormatX() { LogMessage msg = LogMessage.format("a %s %s %s %s %s", "b", "c", "d", "e", "f"); - assertEquals("a b c d e f", msg.toString()); - assertSame(msg.toString(), msg.toString()); + assertThat(msg.toString()).isEqualTo("a b c d e f"); + assertThat(msg.toString()).isSameAs(msg.toString()); } } diff --git a/spring-core/src/test/java/org/springframework/core/serializer/SerializationConverterTests.java b/spring-core/src/test/java/org/springframework/core/serializer/SerializationConverterTests.java index 49b534b55f7..392b37bd315 100644 --- a/spring-core/src/test/java/org/springframework/core/serializer/SerializationConverterTests.java +++ b/spring-core/src/test/java/org/springframework/core/serializer/SerializationConverterTests.java @@ -25,8 +25,8 @@ import org.springframework.core.serializer.support.DeserializingConverter; import org.springframework.core.serializer.support.SerializationFailedException; import org.springframework.core.serializer.support.SerializingConverter; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Gary Russell @@ -40,7 +40,7 @@ public class SerializationConverterTests { SerializingConverter toBytes = new SerializingConverter(); byte[] bytes = toBytes.convert("Testing"); DeserializingConverter fromBytes = new DeserializingConverter(); - assertEquals("Testing", fromBytes.convert(bytes)); + assertThat(fromBytes.convert(bytes)).isEqualTo("Testing"); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/style/ToStringCreatorTests.java b/spring-core/src/test/java/org/springframework/core/style/ToStringCreatorTests.java index 9daa03102ed..21a8450d27e 100644 --- a/spring-core/src/test/java/org/springframework/core/style/ToStringCreatorTests.java +++ b/spring-core/src/test/java/org/springframework/core/style/ToStringCreatorTests.java @@ -28,7 +28,7 @@ import org.junit.Test; import org.springframework.util.ObjectUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Keith Donald @@ -69,9 +69,8 @@ public class ToStringCreatorTests { return new ToStringCreator(this).append("familyFavoriteSport", map).toString(); } }; - assertEquals("[ToStringCreatorTests.4@" + ObjectUtils.getIdentityHexString(stringy) + - " familyFavoriteSport = map['Keri' -> 'Softball', 'Scot' -> 'Fishing', 'Keith' -> 'Flag Football']]", - stringy.toString()); + assertThat(stringy.toString()).isEqualTo(("[ToStringCreatorTests.4@" + ObjectUtils.getIdentityHexString(stringy) + + " familyFavoriteSport = map['Keri' -> 'Softball', 'Scot' -> 'Fishing', 'Keith' -> 'Flag Football']]")); } private Map getMap() { @@ -86,15 +85,15 @@ public class ToStringCreatorTests { public void defaultStyleArray() { SomeObject[] array = new SomeObject[] {s1, s2, s3}; String str = new ToStringCreator(array).toString(); - assertEquals("[@" + ObjectUtils.getIdentityHexString(array) + - " array[A, B, C]]", str); + assertThat(str).isEqualTo(("[@" + ObjectUtils.getIdentityHexString(array) + + " array[A, B, C]]")); } @Test public void primitiveArrays() { int[] integers = new int[] {0, 1, 2, 3, 4}; String str = new ToStringCreator(integers).toString(); - assertEquals("[@" + ObjectUtils.getIdentityHexString(integers) + " array[0, 1, 2, 3, 4]]", str); + assertThat(str).isEqualTo(("[@" + ObjectUtils.getIdentityHexString(integers) + " array[0, 1, 2, 3, 4]]")); } @Test @@ -104,8 +103,7 @@ public class ToStringCreatorTests { list.add(s2); list.add(s3); String str = new ToStringCreator(this).append("myLetters", list).toString(); - assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + " myLetters = list[A, B, C]]", - str); + assertThat(str).isEqualTo(("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + " myLetters = list[A, B, C]]")); } @Test @@ -115,21 +113,21 @@ public class ToStringCreatorTests { set.add(s2); set.add(s3); String str = new ToStringCreator(this).append("myLetters", set).toString(); - assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + " myLetters = set[A, B, C]]", str); + assertThat(str).isEqualTo(("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + " myLetters = set[A, B, C]]")); } @Test public void appendClass() { String str = new ToStringCreator(this).append("myClass", this.getClass()).toString(); - assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + - " myClass = ToStringCreatorTests]", str); + assertThat(str).isEqualTo(("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + + " myClass = ToStringCreatorTests]")); } @Test public void appendMethod() throws Exception { String str = new ToStringCreator(this).append("myMethod", this.getClass().getMethod("appendMethod")).toString(); - assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + - " myMethod = appendMethod@ToStringCreatorTests]", str); + assertThat(str).isEqualTo(("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + + " myMethod = appendMethod@ToStringCreatorTests]")); } diff --git a/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java b/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java index 7b45335713b..ebaf6d8abd8 100644 --- a/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java +++ b/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java @@ -25,9 +25,6 @@ import org.springframework.util.ConcurrencyThrottleSupport; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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 Rick Evans @@ -40,7 +37,7 @@ public class SimpleAsyncTaskExecutorTests { public void cannotExecuteWhenConcurrencyIsSwitchedOff() throws Exception { SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(); executor.setConcurrencyLimit(ConcurrencyThrottleSupport.NO_CONCURRENCY); - assertTrue(executor.isThrottleActive()); + assertThat(executor.isThrottleActive()).isTrue(); assertThatIllegalStateException().isThrownBy(() -> executor.execute(new NoOpRunnable())); } @@ -48,7 +45,7 @@ public class SimpleAsyncTaskExecutorTests { @Test public void throttleIsNotActiveByDefault() throws Exception { SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(); - assertFalse("Concurrency throttle must not default to being active (on)", executor.isThrottleActive()); + assertThat(executor.isThrottleActive()).as("Concurrency throttle must not default to being active (on)").isFalse(); } @Test @@ -72,7 +69,7 @@ public class SimpleAsyncTaskExecutorTests { }); ThreadNameHarvester task = new ThreadNameHarvester(monitor); executeAndWait(executor, task, monitor); - assertEquals("test", task.getThreadName()); + assertThat(task.getThreadName()).isEqualTo("test"); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/type/AnnotationMetadataTests.java b/spring-core/src/test/java/org/springframework/core/type/AnnotationMetadataTests.java index f360bd94266..b34ae869c05 100644 --- a/spring-core/src/test/java/org/springframework/core/type/AnnotationMetadataTests.java +++ b/spring-core/src/test/java/org/springframework/core/type/AnnotationMetadataTests.java @@ -39,10 +39,6 @@ import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; import org.springframework.stereotype.Component; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Unit tests demonstrating that the reflection-based {@link StandardAnnotationMetadata} @@ -238,7 +234,7 @@ public class AnnotationMetadataTests { @Test public void inheritedAnnotationWithMetaAnnotationsWithIdenticalAttributeNamesUsingStandardAnnotationMetadata() { AnnotationMetadata metadata = AnnotationMetadata.introspect(NamedComposedAnnotationExtended.class); - assertFalse(metadata.hasAnnotation(NamedComposedAnnotation.class.getName())); + assertThat(metadata.hasAnnotation(NamedComposedAnnotation.class.getName())).isFalse(); } @Test @@ -246,7 +242,7 @@ public class AnnotationMetadataTests { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(NamedComposedAnnotationExtended.class.getName()); AnnotationMetadata metadata = metadataReader.getAnnotationMetadata(); - assertFalse(metadata.hasAnnotation(NamedComposedAnnotation.class.getName())); + assertThat(metadata.hasAnnotation(NamedComposedAnnotation.class.getName())).isFalse(); } @@ -295,56 +291,56 @@ public class AnnotationMetadataTests { Set methods = metadata.getAnnotatedMethods(DirectAnnotation.class.getName()); MethodMetadata method = methods.iterator().next(); - assertEquals("direct", method.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")); - assertEquals("direct", method.getAnnotationAttributes(DirectAnnotation.class.getName()).get("myValue")); + assertThat(method.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")).isEqualTo("direct"); + assertThat(method.getAnnotationAttributes(DirectAnnotation.class.getName()).get("myValue")).isEqualTo("direct"); List allMeta = method.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value"); assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet(Arrays.asList("direct", "meta"))); allMeta = method.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("additional"); assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet(Arrays.asList("direct"))); - assertTrue(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName())); + assertThat(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName())).isTrue(); { // perform tests with classValuesAsString = false (the default) AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes(SpecialAttr.class.getName()); assertThat(specialAttrs).hasSize(6); - assertTrue(String.class.isAssignableFrom(specialAttrs.getClass("clazz"))); - assertTrue(specialAttrs.getEnum("state").equals(Thread.State.NEW)); + assertThat(String.class.isAssignableFrom(specialAttrs.getClass("clazz"))).isTrue(); + assertThat(specialAttrs.getEnum("state").equals(Thread.State.NEW)).isTrue(); AnnotationAttributes nestedAnno = specialAttrs.getAnnotation("nestedAnno"); assertThat("na").isEqualTo(nestedAnno.getString("value")); - assertTrue(nestedAnno.getEnum("anEnum").equals(SomeEnum.LABEL1)); - assertArrayEquals(new Class[] {String.class}, (Class[]) nestedAnno.get("classArray")); + assertThat(nestedAnno.getEnum("anEnum").equals(SomeEnum.LABEL1)).isTrue(); + assertThat((Class[]) nestedAnno.get("classArray")).isEqualTo(new Class[] {String.class}); AnnotationAttributes[] nestedAnnoArray = specialAttrs.getAnnotationArray("nestedAnnoArray"); assertThat(nestedAnnoArray.length).isEqualTo(2); assertThat(nestedAnnoArray[0].getString("value")).isEqualTo("default"); - assertTrue(nestedAnnoArray[0].getEnum("anEnum").equals(SomeEnum.DEFAULT)); - assertArrayEquals(new Class[] {Void.class}, (Class[]) nestedAnnoArray[0].get("classArray")); + assertThat(nestedAnnoArray[0].getEnum("anEnum").equals(SomeEnum.DEFAULT)).isTrue(); + assertThat((Class[]) nestedAnnoArray[0].get("classArray")).isEqualTo(new Class[] {Void.class}); assertThat(nestedAnnoArray[1].getString("value")).isEqualTo("na1"); - assertTrue(nestedAnnoArray[1].getEnum("anEnum").equals(SomeEnum.LABEL2)); - assertArrayEquals(new Class[] {Number.class}, (Class[]) nestedAnnoArray[1].get("classArray")); - assertArrayEquals(new Class[] {Number.class}, nestedAnnoArray[1].getClassArray("classArray")); + assertThat(nestedAnnoArray[1].getEnum("anEnum").equals(SomeEnum.LABEL2)).isTrue(); + assertThat((Class[]) nestedAnnoArray[1].get("classArray")).isEqualTo(new Class[] {Number.class}); + assertThat(nestedAnnoArray[1].getClassArray("classArray")).isEqualTo(new Class[] {Number.class}); AnnotationAttributes optional = specialAttrs.getAnnotation("optional"); assertThat(optional.getString("value")).isEqualTo("optional"); - assertTrue(optional.getEnum("anEnum").equals(SomeEnum.DEFAULT)); - assertArrayEquals(new Class[] {Void.class}, (Class[]) optional.get("classArray")); - assertArrayEquals(new Class[] {Void.class}, optional.getClassArray("classArray")); + assertThat(optional.getEnum("anEnum").equals(SomeEnum.DEFAULT)).isTrue(); + assertThat((Class[]) optional.get("classArray")).isEqualTo(new Class[] {Void.class}); + assertThat(optional.getClassArray("classArray")).isEqualTo(new Class[] {Void.class}); AnnotationAttributes[] optionalArray = specialAttrs.getAnnotationArray("optionalArray"); assertThat(optionalArray.length).isEqualTo(1); assertThat(optionalArray[0].getString("value")).isEqualTo("optional"); - assertTrue(optionalArray[0].getEnum("anEnum").equals(SomeEnum.DEFAULT)); - assertArrayEquals(new Class[] {Void.class}, (Class[]) optionalArray[0].get("classArray")); - assertArrayEquals(new Class[] {Void.class}, optionalArray[0].getClassArray("classArray")); + assertThat(optionalArray[0].getEnum("anEnum").equals(SomeEnum.DEFAULT)).isTrue(); + assertThat((Class[]) optionalArray[0].get("classArray")).isEqualTo(new Class[] {Void.class}); + assertThat(optionalArray[0].getClassArray("classArray")).isEqualTo(new Class[] {Void.class}); - assertEquals("direct", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")); + assertThat(metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")).isEqualTo("direct"); allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value"); assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet(Arrays.asList("direct", "meta"))); allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("additional"); assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet(Arrays.asList("direct", ""))); - assertEquals("", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("additional")); - assertEquals(0, ((String[]) metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("additionalArray")).length); + assertThat(metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("additional")).isEqualTo(""); + assertThat(((String[]) metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("additionalArray")).length).isEqualTo(0); } { // perform tests with classValuesAsString = true AnnotationAttributes specialAttrs = (AnnotationAttributes) metadata.getAnnotationAttributes( @@ -354,24 +350,24 @@ public class AnnotationMetadataTests { assertThat(specialAttrs.getString("clazz")).isEqualTo(String.class.getName()); AnnotationAttributes nestedAnno = specialAttrs.getAnnotation("nestedAnno"); - assertArrayEquals(new String[] { String.class.getName() }, nestedAnno.getStringArray("classArray")); - assertArrayEquals(new String[] { String.class.getName() }, nestedAnno.getStringArray("classArray")); + assertThat(nestedAnno.getStringArray("classArray")).isEqualTo(new String[] { String.class.getName() }); + assertThat(nestedAnno.getStringArray("classArray")).isEqualTo(new String[] { String.class.getName() }); AnnotationAttributes[] nestedAnnoArray = specialAttrs.getAnnotationArray("nestedAnnoArray"); - assertArrayEquals(new String[] { Void.class.getName() }, (String[]) nestedAnnoArray[0].get("classArray")); - assertArrayEquals(new String[] { Void.class.getName() }, nestedAnnoArray[0].getStringArray("classArray")); - assertArrayEquals(new String[] { Number.class.getName() }, (String[]) nestedAnnoArray[1].get("classArray")); - assertArrayEquals(new String[] { Number.class.getName() }, nestedAnnoArray[1].getStringArray("classArray")); + assertThat((String[]) nestedAnnoArray[0].get("classArray")).isEqualTo(new String[] { Void.class.getName() }); + assertThat(nestedAnnoArray[0].getStringArray("classArray")).isEqualTo(new String[] { Void.class.getName() }); + assertThat((String[]) nestedAnnoArray[1].get("classArray")).isEqualTo(new String[] { Number.class.getName() }); + assertThat(nestedAnnoArray[1].getStringArray("classArray")).isEqualTo(new String[] { Number.class.getName() }); AnnotationAttributes optional = specialAttrs.getAnnotation("optional"); - assertArrayEquals(new String[] { Void.class.getName() }, (String[]) optional.get("classArray")); - assertArrayEquals(new String[] { Void.class.getName() }, optional.getStringArray("classArray")); + assertThat((String[]) optional.get("classArray")).isEqualTo(new String[] { Void.class.getName() }); + assertThat(optional.getStringArray("classArray")).isEqualTo(new String[] { Void.class.getName() }); AnnotationAttributes[] optionalArray = specialAttrs.getAnnotationArray("optionalArray"); - assertArrayEquals(new String[] { Void.class.getName() }, (String[]) optionalArray[0].get("classArray")); - assertArrayEquals(new String[] { Void.class.getName() }, optionalArray[0].getStringArray("classArray")); + assertThat((String[]) optionalArray[0].get("classArray")).isEqualTo(new String[] { Void.class.getName() }); + assertThat(optionalArray[0].getStringArray("classArray")).isEqualTo(new String[] { Void.class.getName() }); - assertEquals("direct", metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")); + assertThat(metadata.getAnnotationAttributes(DirectAnnotation.class.getName()).get("value")).isEqualTo("direct"); allMeta = metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()).get("value"); assertThat(new HashSet<>(allMeta)).isEqualTo(new HashSet(Arrays.asList("direct", "meta"))); } diff --git a/spring-core/src/test/java/org/springframework/core/type/AnnotationTypeFilterTests.java b/spring-core/src/test/java/org/springframework/core/type/AnnotationTypeFilterTests.java index 2a682bb89d6..53dcf5e4242 100644 --- a/spring-core/src/test/java/org/springframework/core/type/AnnotationTypeFilterTests.java +++ b/spring-core/src/test/java/org/springframework/core/type/AnnotationTypeFilterTests.java @@ -28,8 +28,7 @@ import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.stereotype.Component; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ramnivas Laddad @@ -45,7 +44,7 @@ public class AnnotationTypeFilterTests { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class); - assertTrue(filter.match(metadataReader, metadataReaderFactory)); + assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); } @@ -57,7 +56,7 @@ public class AnnotationTypeFilterTests { AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class); // Must fail as annotation on interfaces should not be considered a match - assertFalse(filter.match(metadataReader, metadataReaderFactory)); + assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse(); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); } @@ -68,7 +67,7 @@ public class AnnotationTypeFilterTests { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class); - assertTrue(filter.match(metadataReader, metadataReaderFactory)); + assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); } @@ -80,7 +79,7 @@ public class AnnotationTypeFilterTests { AnnotationTypeFilter filter = new AnnotationTypeFilter(NonInheritedAnnotation.class); // Must fail as annotation isn't inherited - assertFalse(filter.match(metadataReader, metadataReaderFactory)); + assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse(); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); } @@ -91,7 +90,7 @@ public class AnnotationTypeFilterTests { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); AnnotationTypeFilter filter = new AnnotationTypeFilter(Component.class); - assertFalse(filter.match(metadataReader, metadataReaderFactory)); + assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse(); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); } @@ -102,7 +101,7 @@ public class AnnotationTypeFilterTests { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); AnnotationTypeFilter filter = new AnnotationTypeFilter(InheritedAnnotation.class, false, true); - assertTrue(filter.match(metadataReader, metadataReaderFactory)); + assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); } diff --git a/spring-core/src/test/java/org/springframework/core/type/AspectJTypeFilterTests.java b/spring-core/src/test/java/org/springframework/core/type/AspectJTypeFilterTests.java index e2e13591ae7..0e32d6315a7 100644 --- a/spring-core/src/test/java/org/springframework/core/type/AspectJTypeFilterTests.java +++ b/spring-core/src/test/java/org/springframework/core/type/AspectJTypeFilterTests.java @@ -24,8 +24,7 @@ import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; import org.springframework.core.type.filter.AspectJTypeFilter; import org.springframework.stereotype.Component; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ramnivas Laddad @@ -131,7 +130,7 @@ public class AspectJTypeFilterTests { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(type); AspectJTypeFilter filter = new AspectJTypeFilter(typePattern, getClass().getClassLoader()); - assertTrue(filter.match(metadataReader, metadataReaderFactory)); + assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); ClassloadingAssertions.assertClassNotLoaded(type); } @@ -140,7 +139,7 @@ public class AspectJTypeFilterTests { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(type); AspectJTypeFilter filter = new AspectJTypeFilter(typePattern, getClass().getClassLoader()); - assertFalse(filter.match(metadataReader, metadataReaderFactory)); + assertThat(filter.match(metadataReader, metadataReaderFactory)).isFalse(); ClassloadingAssertions.assertClassNotLoaded(type); } diff --git a/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java b/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java index 771687ccbf4..5518ebf9e94 100644 --- a/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java +++ b/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java @@ -23,8 +23,7 @@ import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; import org.springframework.core.type.filter.AssignableTypeFilter; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ramnivas Laddad @@ -40,8 +39,8 @@ public class AssignableTypeFilterTests { AssignableTypeFilter matchingFilter = new AssignableTypeFilter(TestNonInheritingClass.class); AssignableTypeFilter notMatchingFilter = new AssignableTypeFilter(TestInterface.class); - assertFalse(notMatchingFilter.match(metadataReader, metadataReaderFactory)); - assertTrue(matchingFilter.match(metadataReader, metadataReaderFactory)); + assertThat(notMatchingFilter.match(metadataReader, metadataReaderFactory)).isFalse(); + assertThat(matchingFilter.match(metadataReader, metadataReaderFactory)).isTrue(); } @Test @@ -51,7 +50,7 @@ public class AssignableTypeFilterTests { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); AssignableTypeFilter filter = new AssignableTypeFilter(TestInterface.class); - assertTrue(filter.match(metadataReader, metadataReaderFactory)); + assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); } @@ -62,7 +61,7 @@ public class AssignableTypeFilterTests { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); AssignableTypeFilter filter = new AssignableTypeFilter(SimpleJdbcDaoSupport.class); - assertTrue(filter.match(metadataReader, metadataReaderFactory)); + assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); } @@ -73,7 +72,7 @@ public class AssignableTypeFilterTests { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); AssignableTypeFilter filter = new AssignableTypeFilter(JdbcDaoSupport.class); - assertTrue(filter.match(metadataReader, metadataReaderFactory)); + assertThat(filter.match(metadataReader, metadataReaderFactory)).isTrue(); ClassloadingAssertions.assertClassNotLoaded(classUnderTest); } diff --git a/spring-core/src/test/java/org/springframework/core/type/ClassloadingAssertions.java b/spring-core/src/test/java/org/springframework/core/type/ClassloadingAssertions.java index 284c8908af3..8c26fbcf01c 100644 --- a/spring-core/src/test/java/org/springframework/core/type/ClassloadingAssertions.java +++ b/spring-core/src/test/java/org/springframework/core/type/ClassloadingAssertions.java @@ -21,7 +21,7 @@ import java.lang.reflect.Method; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Ramnivas Laddad @@ -38,7 +38,7 @@ abstract class ClassloadingAssertions { } public static void assertClassNotLoaded(String className) { - assertFalse("Class [" + className + "] should not have been loaded", isClassLoaded(className)); + assertThat(isClassLoaded(className)).as("Class [" + className + "] should not have been loaded").isFalse(); } } diff --git a/spring-core/src/test/java/org/springframework/tests/AssumeTests.java b/spring-core/src/test/java/org/springframework/tests/AssumeTests.java index ea9ca66138e..23567407b23 100644 --- a/spring-core/src/test/java/org/springframework/tests/AssumeTests.java +++ b/spring-core/src/test/java/org/springframework/tests/AssumeTests.java @@ -25,7 +25,7 @@ import org.junit.Test; import static java.util.stream.Collectors.joining; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.springframework.tests.Assume.TEST_GROUPS_SYSTEM_PROPERTY; import static org.springframework.tests.TestGroup.CI; import static org.springframework.tests.TestGroup.LONG_RUNNING; diff --git a/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java b/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java index 79dc19d2c2a..1e9c53865cf 100644 --- a/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java +++ b/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java @@ -25,11 +25,8 @@ import java.util.Map; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link AntPathMatcher}. @@ -49,89 +46,90 @@ public class AntPathMatcherTests { @Test public void match() { // test exact matching - assertTrue(pathMatcher.match("test", "test")); - assertTrue(pathMatcher.match("/test", "/test")); - assertTrue(pathMatcher.match("https://example.org", "https://example.org")); // SPR-14141 - assertFalse(pathMatcher.match("/test.jpg", "test.jpg")); - assertFalse(pathMatcher.match("test", "/test")); - assertFalse(pathMatcher.match("/test", "test")); + assertThat(pathMatcher.match("test", "test")).isTrue(); + assertThat(pathMatcher.match("/test", "/test")).isTrue(); + // SPR-14141 + assertThat(pathMatcher.match("https://example.org", "https://example.org")).isTrue(); + assertThat(pathMatcher.match("/test.jpg", "test.jpg")).isFalse(); + assertThat(pathMatcher.match("test", "/test")).isFalse(); + assertThat(pathMatcher.match("/test", "test")).isFalse(); // test matching with ?'s - assertTrue(pathMatcher.match("t?st", "test")); - assertTrue(pathMatcher.match("??st", "test")); - assertTrue(pathMatcher.match("tes?", "test")); - assertTrue(pathMatcher.match("te??", "test")); - assertTrue(pathMatcher.match("?es?", "test")); - assertFalse(pathMatcher.match("tes?", "tes")); - assertFalse(pathMatcher.match("tes?", "testt")); - assertFalse(pathMatcher.match("tes?", "tsst")); + assertThat(pathMatcher.match("t?st", "test")).isTrue(); + assertThat(pathMatcher.match("??st", "test")).isTrue(); + assertThat(pathMatcher.match("tes?", "test")).isTrue(); + assertThat(pathMatcher.match("te??", "test")).isTrue(); + assertThat(pathMatcher.match("?es?", "test")).isTrue(); + assertThat(pathMatcher.match("tes?", "tes")).isFalse(); + assertThat(pathMatcher.match("tes?", "testt")).isFalse(); + assertThat(pathMatcher.match("tes?", "tsst")).isFalse(); // test matching with *'s - assertTrue(pathMatcher.match("*", "test")); - assertTrue(pathMatcher.match("test*", "test")); - assertTrue(pathMatcher.match("test*", "testTest")); - assertTrue(pathMatcher.match("test/*", "test/Test")); - assertTrue(pathMatcher.match("test/*", "test/t")); - assertTrue(pathMatcher.match("test/*", "test/")); - assertTrue(pathMatcher.match("*test*", "AnothertestTest")); - assertTrue(pathMatcher.match("*test", "Anothertest")); - assertTrue(pathMatcher.match("*.*", "test.")); - assertTrue(pathMatcher.match("*.*", "test.test")); - assertTrue(pathMatcher.match("*.*", "test.test.test")); - assertTrue(pathMatcher.match("test*aaa", "testblaaaa")); - assertFalse(pathMatcher.match("test*", "tst")); - assertFalse(pathMatcher.match("test*", "tsttest")); - assertFalse(pathMatcher.match("test*", "test/")); - assertFalse(pathMatcher.match("test*", "test/t")); - assertFalse(pathMatcher.match("test/*", "test")); - assertFalse(pathMatcher.match("*test*", "tsttst")); - assertFalse(pathMatcher.match("*test", "tsttst")); - assertFalse(pathMatcher.match("*.*", "tsttst")); - assertFalse(pathMatcher.match("test*aaa", "test")); - assertFalse(pathMatcher.match("test*aaa", "testblaaab")); + assertThat(pathMatcher.match("*", "test")).isTrue(); + assertThat(pathMatcher.match("test*", "test")).isTrue(); + assertThat(pathMatcher.match("test*", "testTest")).isTrue(); + assertThat(pathMatcher.match("test/*", "test/Test")).isTrue(); + assertThat(pathMatcher.match("test/*", "test/t")).isTrue(); + assertThat(pathMatcher.match("test/*", "test/")).isTrue(); + assertThat(pathMatcher.match("*test*", "AnothertestTest")).isTrue(); + assertThat(pathMatcher.match("*test", "Anothertest")).isTrue(); + assertThat(pathMatcher.match("*.*", "test.")).isTrue(); + assertThat(pathMatcher.match("*.*", "test.test")).isTrue(); + assertThat(pathMatcher.match("*.*", "test.test.test")).isTrue(); + assertThat(pathMatcher.match("test*aaa", "testblaaaa")).isTrue(); + assertThat(pathMatcher.match("test*", "tst")).isFalse(); + assertThat(pathMatcher.match("test*", "tsttest")).isFalse(); + assertThat(pathMatcher.match("test*", "test/")).isFalse(); + assertThat(pathMatcher.match("test*", "test/t")).isFalse(); + assertThat(pathMatcher.match("test/*", "test")).isFalse(); + assertThat(pathMatcher.match("*test*", "tsttst")).isFalse(); + assertThat(pathMatcher.match("*test", "tsttst")).isFalse(); + assertThat(pathMatcher.match("*.*", "tsttst")).isFalse(); + assertThat(pathMatcher.match("test*aaa", "test")).isFalse(); + assertThat(pathMatcher.match("test*aaa", "testblaaab")).isFalse(); // test matching with ?'s and /'s - assertTrue(pathMatcher.match("/?", "/a")); - assertTrue(pathMatcher.match("/?/a", "/a/a")); - assertTrue(pathMatcher.match("/a/?", "/a/b")); - assertTrue(pathMatcher.match("/??/a", "/aa/a")); - assertTrue(pathMatcher.match("/a/??", "/a/bb")); - assertTrue(pathMatcher.match("/?", "/a")); + assertThat(pathMatcher.match("/?", "/a")).isTrue(); + assertThat(pathMatcher.match("/?/a", "/a/a")).isTrue(); + assertThat(pathMatcher.match("/a/?", "/a/b")).isTrue(); + assertThat(pathMatcher.match("/??/a", "/aa/a")).isTrue(); + assertThat(pathMatcher.match("/a/??", "/a/bb")).isTrue(); + assertThat(pathMatcher.match("/?", "/a")).isTrue(); // test matching with **'s - assertTrue(pathMatcher.match("/**", "/testing/testing")); - assertTrue(pathMatcher.match("/*/**", "/testing/testing")); - assertTrue(pathMatcher.match("/**/*", "/testing/testing")); - assertTrue(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla")); - assertTrue(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla/bla")); - assertTrue(pathMatcher.match("/**/test", "/bla/bla/test")); - assertTrue(pathMatcher.match("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla")); - assertTrue(pathMatcher.match("/bla*bla/test", "/blaXXXbla/test")); - assertTrue(pathMatcher.match("/*bla/test", "/XXXbla/test")); - assertFalse(pathMatcher.match("/bla*bla/test", "/blaXXXbl/test")); - assertFalse(pathMatcher.match("/*bla/test", "XXXblab/test")); - assertFalse(pathMatcher.match("/*bla/test", "XXXbl/test")); + assertThat(pathMatcher.match("/**", "/testing/testing")).isTrue(); + assertThat(pathMatcher.match("/*/**", "/testing/testing")).isTrue(); + assertThat(pathMatcher.match("/**/*", "/testing/testing")).isTrue(); + assertThat(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla")).isTrue(); + assertThat(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla/bla")).isTrue(); + assertThat(pathMatcher.match("/**/test", "/bla/bla/test")).isTrue(); + assertThat(pathMatcher.match("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla")).isTrue(); + assertThat(pathMatcher.match("/bla*bla/test", "/blaXXXbla/test")).isTrue(); + assertThat(pathMatcher.match("/*bla/test", "/XXXbla/test")).isTrue(); + assertThat(pathMatcher.match("/bla*bla/test", "/blaXXXbl/test")).isFalse(); + assertThat(pathMatcher.match("/*bla/test", "XXXblab/test")).isFalse(); + assertThat(pathMatcher.match("/*bla/test", "XXXbl/test")).isFalse(); - assertFalse(pathMatcher.match("/????", "/bala/bla")); - assertFalse(pathMatcher.match("/**/*bla", "/bla/bla/bla/bbb")); + assertThat(pathMatcher.match("/????", "/bala/bla")).isFalse(); + assertThat(pathMatcher.match("/**/*bla", "/bla/bla/bla/bbb")).isFalse(); - assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/")); - assertTrue(pathMatcher.match("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing")); - assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing")); - assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg")); + assertThat(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue(); + assertThat(pathMatcher.match("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing")).isTrue(); + assertThat(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue(); + assertThat(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg")).isTrue(); - assertTrue(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/")); - assertTrue(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing")); - assertTrue(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing")); - assertFalse(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing")); + assertThat(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue(); + assertThat(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing")).isTrue(); + assertThat(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue(); + assertThat(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing")).isFalse(); - assertFalse(pathMatcher.match("/x/x/**/bla", "/x/x/x/")); + assertThat(pathMatcher.match("/x/x/**/bla", "/x/x/x/")).isFalse(); - assertTrue(pathMatcher.match("/foo/bar/**", "/foo/bar")) ; + assertThat(pathMatcher.match("/foo/bar/**", "/foo/bar")).isTrue(); - assertTrue(pathMatcher.match("", "")); + assertThat(pathMatcher.match("", "")).isTrue(); - assertTrue(pathMatcher.match("/{bla}.*", "/testing.html")); + assertThat(pathMatcher.match("/{bla}.*", "/testing.html")).isTrue(); } // SPR-14247 @@ -139,94 +137,94 @@ public class AntPathMatcherTests { public void matchWithTrimTokensEnabled() throws Exception { pathMatcher.setTrimTokens(true); - assertTrue(pathMatcher.match("/foo/bar", "/foo /bar")); + assertThat(pathMatcher.match("/foo/bar", "/foo /bar")).isTrue(); } @Test public void withMatchStart() { // test exact matching - assertTrue(pathMatcher.matchStart("test", "test")); - assertTrue(pathMatcher.matchStart("/test", "/test")); - assertFalse(pathMatcher.matchStart("/test.jpg", "test.jpg")); - assertFalse(pathMatcher.matchStart("test", "/test")); - assertFalse(pathMatcher.matchStart("/test", "test")); + assertThat(pathMatcher.matchStart("test", "test")).isTrue(); + assertThat(pathMatcher.matchStart("/test", "/test")).isTrue(); + assertThat(pathMatcher.matchStart("/test.jpg", "test.jpg")).isFalse(); + assertThat(pathMatcher.matchStart("test", "/test")).isFalse(); + assertThat(pathMatcher.matchStart("/test", "test")).isFalse(); // test matching with ?'s - assertTrue(pathMatcher.matchStart("t?st", "test")); - assertTrue(pathMatcher.matchStart("??st", "test")); - assertTrue(pathMatcher.matchStart("tes?", "test")); - assertTrue(pathMatcher.matchStart("te??", "test")); - assertTrue(pathMatcher.matchStart("?es?", "test")); - assertFalse(pathMatcher.matchStart("tes?", "tes")); - assertFalse(pathMatcher.matchStart("tes?", "testt")); - assertFalse(pathMatcher.matchStart("tes?", "tsst")); + assertThat(pathMatcher.matchStart("t?st", "test")).isTrue(); + assertThat(pathMatcher.matchStart("??st", "test")).isTrue(); + assertThat(pathMatcher.matchStart("tes?", "test")).isTrue(); + assertThat(pathMatcher.matchStart("te??", "test")).isTrue(); + assertThat(pathMatcher.matchStart("?es?", "test")).isTrue(); + assertThat(pathMatcher.matchStart("tes?", "tes")).isFalse(); + assertThat(pathMatcher.matchStart("tes?", "testt")).isFalse(); + assertThat(pathMatcher.matchStart("tes?", "tsst")).isFalse(); // test matching with *'s - assertTrue(pathMatcher.matchStart("*", "test")); - assertTrue(pathMatcher.matchStart("test*", "test")); - assertTrue(pathMatcher.matchStart("test*", "testTest")); - assertTrue(pathMatcher.matchStart("test/*", "test/Test")); - assertTrue(pathMatcher.matchStart("test/*", "test/t")); - assertTrue(pathMatcher.matchStart("test/*", "test/")); - assertTrue(pathMatcher.matchStart("*test*", "AnothertestTest")); - assertTrue(pathMatcher.matchStart("*test", "Anothertest")); - assertTrue(pathMatcher.matchStart("*.*", "test.")); - assertTrue(pathMatcher.matchStart("*.*", "test.test")); - assertTrue(pathMatcher.matchStart("*.*", "test.test.test")); - assertTrue(pathMatcher.matchStart("test*aaa", "testblaaaa")); - assertFalse(pathMatcher.matchStart("test*", "tst")); - assertFalse(pathMatcher.matchStart("test*", "test/")); - assertFalse(pathMatcher.matchStart("test*", "tsttest")); - assertFalse(pathMatcher.matchStart("test*", "test/")); - assertFalse(pathMatcher.matchStart("test*", "test/t")); - assertTrue(pathMatcher.matchStart("test/*", "test")); - assertTrue(pathMatcher.matchStart("test/t*.txt", "test")); - assertFalse(pathMatcher.matchStart("*test*", "tsttst")); - assertFalse(pathMatcher.matchStart("*test", "tsttst")); - assertFalse(pathMatcher.matchStart("*.*", "tsttst")); - assertFalse(pathMatcher.matchStart("test*aaa", "test")); - assertFalse(pathMatcher.matchStart("test*aaa", "testblaaab")); + assertThat(pathMatcher.matchStart("*", "test")).isTrue(); + assertThat(pathMatcher.matchStart("test*", "test")).isTrue(); + assertThat(pathMatcher.matchStart("test*", "testTest")).isTrue(); + assertThat(pathMatcher.matchStart("test/*", "test/Test")).isTrue(); + assertThat(pathMatcher.matchStart("test/*", "test/t")).isTrue(); + assertThat(pathMatcher.matchStart("test/*", "test/")).isTrue(); + assertThat(pathMatcher.matchStart("*test*", "AnothertestTest")).isTrue(); + assertThat(pathMatcher.matchStart("*test", "Anothertest")).isTrue(); + assertThat(pathMatcher.matchStart("*.*", "test.")).isTrue(); + assertThat(pathMatcher.matchStart("*.*", "test.test")).isTrue(); + assertThat(pathMatcher.matchStart("*.*", "test.test.test")).isTrue(); + assertThat(pathMatcher.matchStart("test*aaa", "testblaaaa")).isTrue(); + assertThat(pathMatcher.matchStart("test*", "tst")).isFalse(); + assertThat(pathMatcher.matchStart("test*", "test/")).isFalse(); + assertThat(pathMatcher.matchStart("test*", "tsttest")).isFalse(); + assertThat(pathMatcher.matchStart("test*", "test/")).isFalse(); + assertThat(pathMatcher.matchStart("test*", "test/t")).isFalse(); + assertThat(pathMatcher.matchStart("test/*", "test")).isTrue(); + assertThat(pathMatcher.matchStart("test/t*.txt", "test")).isTrue(); + assertThat(pathMatcher.matchStart("*test*", "tsttst")).isFalse(); + assertThat(pathMatcher.matchStart("*test", "tsttst")).isFalse(); + assertThat(pathMatcher.matchStart("*.*", "tsttst")).isFalse(); + assertThat(pathMatcher.matchStart("test*aaa", "test")).isFalse(); + assertThat(pathMatcher.matchStart("test*aaa", "testblaaab")).isFalse(); // test matching with ?'s and /'s - assertTrue(pathMatcher.matchStart("/?", "/a")); - assertTrue(pathMatcher.matchStart("/?/a", "/a/a")); - assertTrue(pathMatcher.matchStart("/a/?", "/a/b")); - assertTrue(pathMatcher.matchStart("/??/a", "/aa/a")); - assertTrue(pathMatcher.matchStart("/a/??", "/a/bb")); - assertTrue(pathMatcher.matchStart("/?", "/a")); + assertThat(pathMatcher.matchStart("/?", "/a")).isTrue(); + assertThat(pathMatcher.matchStart("/?/a", "/a/a")).isTrue(); + assertThat(pathMatcher.matchStart("/a/?", "/a/b")).isTrue(); + assertThat(pathMatcher.matchStart("/??/a", "/aa/a")).isTrue(); + assertThat(pathMatcher.matchStart("/a/??", "/a/bb")).isTrue(); + assertThat(pathMatcher.matchStart("/?", "/a")).isTrue(); // test matching with **'s - assertTrue(pathMatcher.matchStart("/**", "/testing/testing")); - assertTrue(pathMatcher.matchStart("/*/**", "/testing/testing")); - assertTrue(pathMatcher.matchStart("/**/*", "/testing/testing")); - assertTrue(pathMatcher.matchStart("test*/**", "test/")); - assertTrue(pathMatcher.matchStart("test*/**", "test/t")); - assertTrue(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla")); - assertTrue(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla/bla")); - assertTrue(pathMatcher.matchStart("/**/test", "/bla/bla/test")); - assertTrue(pathMatcher.matchStart("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla")); - assertTrue(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbla/test")); - assertTrue(pathMatcher.matchStart("/*bla/test", "/XXXbla/test")); - assertFalse(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbl/test")); - assertFalse(pathMatcher.matchStart("/*bla/test", "XXXblab/test")); - assertFalse(pathMatcher.matchStart("/*bla/test", "XXXbl/test")); + assertThat(pathMatcher.matchStart("/**", "/testing/testing")).isTrue(); + assertThat(pathMatcher.matchStart("/*/**", "/testing/testing")).isTrue(); + assertThat(pathMatcher.matchStart("/**/*", "/testing/testing")).isTrue(); + assertThat(pathMatcher.matchStart("test*/**", "test/")).isTrue(); + assertThat(pathMatcher.matchStart("test*/**", "test/t")).isTrue(); + assertThat(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla")).isTrue(); + assertThat(pathMatcher.matchStart("/bla/**/bla", "/bla/testing/testing/bla/bla")).isTrue(); + assertThat(pathMatcher.matchStart("/**/test", "/bla/bla/test")).isTrue(); + assertThat(pathMatcher.matchStart("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla")).isTrue(); + assertThat(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbla/test")).isTrue(); + assertThat(pathMatcher.matchStart("/*bla/test", "/XXXbla/test")).isTrue(); + assertThat(pathMatcher.matchStart("/bla*bla/test", "/blaXXXbl/test")).isFalse(); + assertThat(pathMatcher.matchStart("/*bla/test", "XXXblab/test")).isFalse(); + assertThat(pathMatcher.matchStart("/*bla/test", "XXXbl/test")).isFalse(); - assertFalse(pathMatcher.matchStart("/????", "/bala/bla")); - assertTrue(pathMatcher.matchStart("/**/*bla", "/bla/bla/bla/bbb")); + assertThat(pathMatcher.matchStart("/????", "/bala/bla")).isFalse(); + assertThat(pathMatcher.matchStart("/**/*bla", "/bla/bla/bla/bbb")).isTrue(); - assertTrue(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/")); - assertTrue(pathMatcher.matchStart("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing")); - assertTrue(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing")); - assertTrue(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg")); + assertThat(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue(); + assertThat(pathMatcher.matchStart("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing")).isTrue(); + assertThat(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue(); + assertThat(pathMatcher.matchStart("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg")).isTrue(); - assertTrue(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/")); - assertTrue(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing")); - assertTrue(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing")); - assertTrue(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing")); + assertThat(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/")).isTrue(); + assertThat(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing")).isTrue(); + assertThat(pathMatcher.matchStart("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue(); + assertThat(pathMatcher.matchStart("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing")).isTrue(); - assertTrue(pathMatcher.matchStart("/x/x/**/bla", "/x/x/x/")); + assertThat(pathMatcher.matchStart("/x/x/**/bla", "/x/x/x/")).isTrue(); - assertTrue(pathMatcher.matchStart("", "")); + assertThat(pathMatcher.matchStart("", "")).isTrue(); } @Test @@ -234,123 +232,120 @@ public class AntPathMatcherTests { pathMatcher.setPathSeparator("."); // test exact matching - assertTrue(pathMatcher.match("test", "test")); - assertTrue(pathMatcher.match(".test", ".test")); - assertFalse(pathMatcher.match(".test/jpg", "test/jpg")); - assertFalse(pathMatcher.match("test", ".test")); - assertFalse(pathMatcher.match(".test", "test")); + assertThat(pathMatcher.match("test", "test")).isTrue(); + assertThat(pathMatcher.match(".test", ".test")).isTrue(); + assertThat(pathMatcher.match(".test/jpg", "test/jpg")).isFalse(); + assertThat(pathMatcher.match("test", ".test")).isFalse(); + assertThat(pathMatcher.match(".test", "test")).isFalse(); // test matching with ?'s - assertTrue(pathMatcher.match("t?st", "test")); - assertTrue(pathMatcher.match("??st", "test")); - assertTrue(pathMatcher.match("tes?", "test")); - assertTrue(pathMatcher.match("te??", "test")); - assertTrue(pathMatcher.match("?es?", "test")); - assertFalse(pathMatcher.match("tes?", "tes")); - assertFalse(pathMatcher.match("tes?", "testt")); - assertFalse(pathMatcher.match("tes?", "tsst")); + assertThat(pathMatcher.match("t?st", "test")).isTrue(); + assertThat(pathMatcher.match("??st", "test")).isTrue(); + assertThat(pathMatcher.match("tes?", "test")).isTrue(); + assertThat(pathMatcher.match("te??", "test")).isTrue(); + assertThat(pathMatcher.match("?es?", "test")).isTrue(); + assertThat(pathMatcher.match("tes?", "tes")).isFalse(); + assertThat(pathMatcher.match("tes?", "testt")).isFalse(); + assertThat(pathMatcher.match("tes?", "tsst")).isFalse(); // test matching with *'s - assertTrue(pathMatcher.match("*", "test")); - assertTrue(pathMatcher.match("test*", "test")); - assertTrue(pathMatcher.match("test*", "testTest")); - assertTrue(pathMatcher.match("*test*", "AnothertestTest")); - assertTrue(pathMatcher.match("*test", "Anothertest")); - assertTrue(pathMatcher.match("*/*", "test/")); - assertTrue(pathMatcher.match("*/*", "test/test")); - assertTrue(pathMatcher.match("*/*", "test/test/test")); - assertTrue(pathMatcher.match("test*aaa", "testblaaaa")); - assertFalse(pathMatcher.match("test*", "tst")); - assertFalse(pathMatcher.match("test*", "tsttest")); - assertFalse(pathMatcher.match("*test*", "tsttst")); - assertFalse(pathMatcher.match("*test", "tsttst")); - assertFalse(pathMatcher.match("*/*", "tsttst")); - assertFalse(pathMatcher.match("test*aaa", "test")); - assertFalse(pathMatcher.match("test*aaa", "testblaaab")); + assertThat(pathMatcher.match("*", "test")).isTrue(); + assertThat(pathMatcher.match("test*", "test")).isTrue(); + assertThat(pathMatcher.match("test*", "testTest")).isTrue(); + assertThat(pathMatcher.match("*test*", "AnothertestTest")).isTrue(); + assertThat(pathMatcher.match("*test", "Anothertest")).isTrue(); + assertThat(pathMatcher.match("*/*", "test/")).isTrue(); + assertThat(pathMatcher.match("*/*", "test/test")).isTrue(); + assertThat(pathMatcher.match("*/*", "test/test/test")).isTrue(); + assertThat(pathMatcher.match("test*aaa", "testblaaaa")).isTrue(); + assertThat(pathMatcher.match("test*", "tst")).isFalse(); + assertThat(pathMatcher.match("test*", "tsttest")).isFalse(); + assertThat(pathMatcher.match("*test*", "tsttst")).isFalse(); + assertThat(pathMatcher.match("*test", "tsttst")).isFalse(); + assertThat(pathMatcher.match("*/*", "tsttst")).isFalse(); + assertThat(pathMatcher.match("test*aaa", "test")).isFalse(); + assertThat(pathMatcher.match("test*aaa", "testblaaab")).isFalse(); // test matching with ?'s and .'s - assertTrue(pathMatcher.match(".?", ".a")); - assertTrue(pathMatcher.match(".?.a", ".a.a")); - assertTrue(pathMatcher.match(".a.?", ".a.b")); - assertTrue(pathMatcher.match(".??.a", ".aa.a")); - assertTrue(pathMatcher.match(".a.??", ".a.bb")); - assertTrue(pathMatcher.match(".?", ".a")); + assertThat(pathMatcher.match(".?", ".a")).isTrue(); + assertThat(pathMatcher.match(".?.a", ".a.a")).isTrue(); + assertThat(pathMatcher.match(".a.?", ".a.b")).isTrue(); + assertThat(pathMatcher.match(".??.a", ".aa.a")).isTrue(); + assertThat(pathMatcher.match(".a.??", ".a.bb")).isTrue(); + assertThat(pathMatcher.match(".?", ".a")).isTrue(); // test matching with **'s - assertTrue(pathMatcher.match(".**", ".testing.testing")); - assertTrue(pathMatcher.match(".*.**", ".testing.testing")); - assertTrue(pathMatcher.match(".**.*", ".testing.testing")); - assertTrue(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla")); - assertTrue(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla.bla")); - assertTrue(pathMatcher.match(".**.test", ".bla.bla.test")); - assertTrue(pathMatcher.match(".bla.**.**.bla", ".bla.bla.bla.bla.bla.bla")); - assertTrue(pathMatcher.match(".bla*bla.test", ".blaXXXbla.test")); - assertTrue(pathMatcher.match(".*bla.test", ".XXXbla.test")); - assertFalse(pathMatcher.match(".bla*bla.test", ".blaXXXbl.test")); - assertFalse(pathMatcher.match(".*bla.test", "XXXblab.test")); - assertFalse(pathMatcher.match(".*bla.test", "XXXbl.test")); + assertThat(pathMatcher.match(".**", ".testing.testing")).isTrue(); + assertThat(pathMatcher.match(".*.**", ".testing.testing")).isTrue(); + assertThat(pathMatcher.match(".**.*", ".testing.testing")).isTrue(); + assertThat(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla")).isTrue(); + assertThat(pathMatcher.match(".bla.**.bla", ".bla.testing.testing.bla.bla")).isTrue(); + assertThat(pathMatcher.match(".**.test", ".bla.bla.test")).isTrue(); + assertThat(pathMatcher.match(".bla.**.**.bla", ".bla.bla.bla.bla.bla.bla")).isTrue(); + assertThat(pathMatcher.match(".bla*bla.test", ".blaXXXbla.test")).isTrue(); + assertThat(pathMatcher.match(".*bla.test", ".XXXbla.test")).isTrue(); + assertThat(pathMatcher.match(".bla*bla.test", ".blaXXXbl.test")).isFalse(); + assertThat(pathMatcher.match(".*bla.test", "XXXblab.test")).isFalse(); + assertThat(pathMatcher.match(".*bla.test", "XXXbl.test")).isFalse(); } @Test public void extractPathWithinPattern() throws Exception { - assertEquals("", pathMatcher.extractPathWithinPattern("/docs/commit.html", "/docs/commit.html")); + assertThat(pathMatcher.extractPathWithinPattern("/docs/commit.html", "/docs/commit.html")).isEqualTo(""); - assertEquals("cvs/commit", pathMatcher.extractPathWithinPattern("/docs/*", "/docs/cvs/commit")); - assertEquals("commit.html", pathMatcher.extractPathWithinPattern("/docs/cvs/*.html", "/docs/cvs/commit.html")); - assertEquals("cvs/commit", pathMatcher.extractPathWithinPattern("/docs/**", "/docs/cvs/commit")); - assertEquals("cvs/commit.html", - pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/cvs/commit.html")); - assertEquals("commit.html", pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/commit.html")); - assertEquals("commit.html", pathMatcher.extractPathWithinPattern("/*.html", "/commit.html")); - assertEquals("docs/commit.html", pathMatcher.extractPathWithinPattern("/*.html", "/docs/commit.html")); - assertEquals("/commit.html", pathMatcher.extractPathWithinPattern("*.html", "/commit.html")); - assertEquals("/docs/commit.html", pathMatcher.extractPathWithinPattern("*.html", "/docs/commit.html")); - assertEquals("/docs/commit.html", pathMatcher.extractPathWithinPattern("**/*.*", "/docs/commit.html")); - assertEquals("/docs/commit.html", pathMatcher.extractPathWithinPattern("*", "/docs/commit.html")); + assertThat(pathMatcher.extractPathWithinPattern("/docs/*", "/docs/cvs/commit")).isEqualTo("cvs/commit"); + assertThat(pathMatcher.extractPathWithinPattern("/docs/cvs/*.html", "/docs/cvs/commit.html")).isEqualTo("commit.html"); + assertThat(pathMatcher.extractPathWithinPattern("/docs/**", "/docs/cvs/commit")).isEqualTo("cvs/commit"); + assertThat(pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/cvs/commit.html")).isEqualTo("cvs/commit.html"); + assertThat(pathMatcher.extractPathWithinPattern("/docs/**/*.html", "/docs/commit.html")).isEqualTo("commit.html"); + assertThat(pathMatcher.extractPathWithinPattern("/*.html", "/commit.html")).isEqualTo("commit.html"); + assertThat(pathMatcher.extractPathWithinPattern("/*.html", "/docs/commit.html")).isEqualTo("docs/commit.html"); + assertThat(pathMatcher.extractPathWithinPattern("*.html", "/commit.html")).isEqualTo("/commit.html"); + assertThat(pathMatcher.extractPathWithinPattern("*.html", "/docs/commit.html")).isEqualTo("/docs/commit.html"); + assertThat(pathMatcher.extractPathWithinPattern("**/*.*", "/docs/commit.html")).isEqualTo("/docs/commit.html"); + assertThat(pathMatcher.extractPathWithinPattern("*", "/docs/commit.html")).isEqualTo("/docs/commit.html"); // SPR-10515 - assertEquals("/docs/cvs/other/commit.html", pathMatcher.extractPathWithinPattern("**/commit.html", "/docs/cvs/other/commit.html")); - assertEquals("cvs/other/commit.html", pathMatcher.extractPathWithinPattern("/docs/**/commit.html", "/docs/cvs/other/commit.html")); - assertEquals("cvs/other/commit.html", pathMatcher.extractPathWithinPattern("/docs/**/**/**/**", "/docs/cvs/other/commit.html")); + assertThat(pathMatcher.extractPathWithinPattern("**/commit.html", "/docs/cvs/other/commit.html")).isEqualTo("/docs/cvs/other/commit.html"); + assertThat(pathMatcher.extractPathWithinPattern("/docs/**/commit.html", "/docs/cvs/other/commit.html")).isEqualTo("cvs/other/commit.html"); + assertThat(pathMatcher.extractPathWithinPattern("/docs/**/**/**/**", "/docs/cvs/other/commit.html")).isEqualTo("cvs/other/commit.html"); - assertEquals("docs/cvs/commit", pathMatcher.extractPathWithinPattern("/d?cs/*", "/docs/cvs/commit")); - assertEquals("cvs/commit.html", - pathMatcher.extractPathWithinPattern("/docs/c?s/*.html", "/docs/cvs/commit.html")); - assertEquals("docs/cvs/commit", pathMatcher.extractPathWithinPattern("/d?cs/**", "/docs/cvs/commit")); - assertEquals("docs/cvs/commit.html", - pathMatcher.extractPathWithinPattern("/d?cs/**/*.html", "/docs/cvs/commit.html")); + assertThat(pathMatcher.extractPathWithinPattern("/d?cs/*", "/docs/cvs/commit")).isEqualTo("docs/cvs/commit"); + assertThat(pathMatcher.extractPathWithinPattern("/docs/c?s/*.html", "/docs/cvs/commit.html")).isEqualTo("cvs/commit.html"); + assertThat(pathMatcher.extractPathWithinPattern("/d?cs/**", "/docs/cvs/commit")).isEqualTo("docs/cvs/commit"); + assertThat(pathMatcher.extractPathWithinPattern("/d?cs/**/*.html", "/docs/cvs/commit.html")).isEqualTo("docs/cvs/commit.html"); } @Test public void extractUriTemplateVariables() throws Exception { Map result = pathMatcher.extractUriTemplateVariables("/hotels/{hotel}", "/hotels/1"); - assertEquals(Collections.singletonMap("hotel", "1"), result); + assertThat(result).isEqualTo(Collections.singletonMap("hotel", "1")); result = pathMatcher.extractUriTemplateVariables("/h?tels/{hotel}", "/hotels/1"); - assertEquals(Collections.singletonMap("hotel", "1"), result); + assertThat(result).isEqualTo(Collections.singletonMap("hotel", "1")); result = pathMatcher.extractUriTemplateVariables("/hotels/{hotel}/bookings/{booking}", "/hotels/1/bookings/2"); Map expected = new LinkedHashMap<>(); expected.put("hotel", "1"); expected.put("booking", "2"); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); result = pathMatcher.extractUriTemplateVariables("/**/hotels/**/{hotel}", "/foo/hotels/bar/1"); - assertEquals(Collections.singletonMap("hotel", "1"), result); + assertThat(result).isEqualTo(Collections.singletonMap("hotel", "1")); result = pathMatcher.extractUriTemplateVariables("/{page}.html", "/42.html"); - assertEquals(Collections.singletonMap("page", "42"), result); + assertThat(result).isEqualTo(Collections.singletonMap("page", "42")); result = pathMatcher.extractUriTemplateVariables("/{page}.*", "/42.html"); - assertEquals(Collections.singletonMap("page", "42"), result); + assertThat(result).isEqualTo(Collections.singletonMap("page", "42")); result = pathMatcher.extractUriTemplateVariables("/A-{B}-C", "/A-b-C"); - assertEquals(Collections.singletonMap("B", "b"), result); + assertThat(result).isEqualTo(Collections.singletonMap("B", "b")); result = pathMatcher.extractUriTemplateVariables("/{name}.{extension}", "/test.html"); expected = new LinkedHashMap<>(); expected.put("name", "test"); expected.put("extension", "html"); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); } @Test @@ -358,13 +353,13 @@ public class AntPathMatcherTests { Map result = pathMatcher .extractUriTemplateVariables("{symbolicName:[\\w\\.]+}-{version:[\\w\\.]+}.jar", "com.example-1.0.0.jar"); - assertEquals("com.example", result.get("symbolicName")); - assertEquals("1.0.0", result.get("version")); + assertThat(result.get("symbolicName")).isEqualTo("com.example"); + assertThat(result.get("version")).isEqualTo("1.0.0"); result = pathMatcher.extractUriTemplateVariables("{symbolicName:[\\w\\.]+}-sources-{version:[\\w\\.]+}.jar", "com.example-sources-1.0.0.jar"); - assertEquals("com.example", result.get("symbolicName")); - assertEquals("1.0.0", result.get("version")); + assertThat(result.get("symbolicName")).isEqualTo("com.example"); + assertThat(result.get("version")).isEqualTo("1.0.0"); } /** @@ -375,23 +370,23 @@ public class AntPathMatcherTests { Map result = pathMatcher.extractUriTemplateVariables( "{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.]+}.jar", "com.example-sources-1.0.0.jar"); - assertEquals("com.example", result.get("symbolicName")); - assertEquals("1.0.0", result.get("version")); + assertThat(result.get("symbolicName")).isEqualTo("com.example"); + assertThat(result.get("version")).isEqualTo("1.0.0"); result = pathMatcher.extractUriTemplateVariables( "{symbolicName:[\\w\\.]+}-sources-{version:[\\d\\.]+}-{year:\\d{4}}{month:\\d{2}}{day:\\d{2}}.jar", "com.example-sources-1.0.0-20100220.jar"); - assertEquals("com.example", result.get("symbolicName")); - assertEquals("1.0.0", result.get("version")); - assertEquals("2010", result.get("year")); - assertEquals("02", result.get("month")); - assertEquals("20", result.get("day")); + assertThat(result.get("symbolicName")).isEqualTo("com.example"); + assertThat(result.get("version")).isEqualTo("1.0.0"); + assertThat(result.get("year")).isEqualTo("2010"); + assertThat(result.get("month")).isEqualTo("02"); + assertThat(result.get("day")).isEqualTo("20"); result = pathMatcher.extractUriTemplateVariables( "{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.\\{\\}]+}.jar", "com.example-sources-1.0.0.{12}.jar"); - assertEquals("com.example", result.get("symbolicName")); - assertEquals("1.0.0.{12}", result.get("version")); + assertThat(result.get("symbolicName")).isEqualTo("com.example"); + assertThat(result.get("version")).isEqualTo("1.0.0.{12}"); } /** @@ -406,33 +401,39 @@ public class AntPathMatcherTests { @Test public void combine() { - assertEquals("", pathMatcher.combine(null, null)); - assertEquals("/hotels", pathMatcher.combine("/hotels", null)); - assertEquals("/hotels", pathMatcher.combine(null, "/hotels")); - assertEquals("/hotels/booking", pathMatcher.combine("/hotels/*", "booking")); - assertEquals("/hotels/booking", pathMatcher.combine("/hotels/*", "/booking")); - assertEquals("/hotels/**/booking", pathMatcher.combine("/hotels/**", "booking")); - assertEquals("/hotels/**/booking", pathMatcher.combine("/hotels/**", "/booking")); - assertEquals("/hotels/booking", pathMatcher.combine("/hotels", "/booking")); - assertEquals("/hotels/booking", pathMatcher.combine("/hotels", "booking")); - assertEquals("/hotels/booking", pathMatcher.combine("/hotels/", "booking")); - assertEquals("/hotels/{hotel}", pathMatcher.combine("/hotels/*", "{hotel}")); - assertEquals("/hotels/**/{hotel}", pathMatcher.combine("/hotels/**", "{hotel}")); - assertEquals("/hotels/{hotel}", pathMatcher.combine("/hotels", "{hotel}")); - assertEquals("/hotels/{hotel}.*", pathMatcher.combine("/hotels", "{hotel}.*")); - assertEquals("/hotels/*/booking/{booking}", pathMatcher.combine("/hotels/*/booking", "{booking}")); - assertEquals("/hotel.html", pathMatcher.combine("/*.html", "/hotel.html")); - assertEquals("/hotel.html", pathMatcher.combine("/*.html", "/hotel")); - assertEquals("/hotel.html", pathMatcher.combine("/*.html", "/hotel.*")); - assertEquals("/*.html", pathMatcher.combine("/**", "/*.html")); - assertEquals("/*.html", pathMatcher.combine("/*", "/*.html")); - assertEquals("/*.html", pathMatcher.combine("/*.*", "/*.html")); - assertEquals("/{foo}/bar", pathMatcher.combine("/{foo}", "/bar")); // SPR-8858 - assertEquals("/user/user", pathMatcher.combine("/user", "/user")); // SPR-7970 - assertEquals("/{foo:.*[^0-9].*}/edit/", pathMatcher.combine("/{foo:.*[^0-9].*}", "/edit/")); // SPR-10062 - assertEquals("/1.0/foo/test", pathMatcher.combine("/1.0", "/foo/test")); // SPR-10554 - assertEquals("/hotel", pathMatcher.combine("/", "/hotel")); // SPR-12975 - assertEquals("/hotel/booking", pathMatcher.combine("/hotel/", "/booking")); // SPR-12975 + assertThat(pathMatcher.combine(null, null)).isEqualTo(""); + assertThat(pathMatcher.combine("/hotels", null)).isEqualTo("/hotels"); + assertThat(pathMatcher.combine(null, "/hotels")).isEqualTo("/hotels"); + assertThat(pathMatcher.combine("/hotels/*", "booking")).isEqualTo("/hotels/booking"); + assertThat(pathMatcher.combine("/hotels/*", "/booking")).isEqualTo("/hotels/booking"); + assertThat(pathMatcher.combine("/hotels/**", "booking")).isEqualTo("/hotels/**/booking"); + assertThat(pathMatcher.combine("/hotels/**", "/booking")).isEqualTo("/hotels/**/booking"); + assertThat(pathMatcher.combine("/hotels", "/booking")).isEqualTo("/hotels/booking"); + assertThat(pathMatcher.combine("/hotels", "booking")).isEqualTo("/hotels/booking"); + assertThat(pathMatcher.combine("/hotels/", "booking")).isEqualTo("/hotels/booking"); + assertThat(pathMatcher.combine("/hotels/*", "{hotel}")).isEqualTo("/hotels/{hotel}"); + assertThat(pathMatcher.combine("/hotels/**", "{hotel}")).isEqualTo("/hotels/**/{hotel}"); + assertThat(pathMatcher.combine("/hotels", "{hotel}")).isEqualTo("/hotels/{hotel}"); + assertThat(pathMatcher.combine("/hotels", "{hotel}.*")).isEqualTo("/hotels/{hotel}.*"); + assertThat(pathMatcher.combine("/hotels/*/booking", "{booking}")).isEqualTo("/hotels/*/booking/{booking}"); + assertThat(pathMatcher.combine("/*.html", "/hotel.html")).isEqualTo("/hotel.html"); + assertThat(pathMatcher.combine("/*.html", "/hotel")).isEqualTo("/hotel.html"); + assertThat(pathMatcher.combine("/*.html", "/hotel.*")).isEqualTo("/hotel.html"); + assertThat(pathMatcher.combine("/**", "/*.html")).isEqualTo("/*.html"); + assertThat(pathMatcher.combine("/*", "/*.html")).isEqualTo("/*.html"); + assertThat(pathMatcher.combine("/*.*", "/*.html")).isEqualTo("/*.html"); + // SPR-8858 + assertThat(pathMatcher.combine("/{foo}", "/bar")).isEqualTo("/{foo}/bar"); + // SPR-7970 + assertThat(pathMatcher.combine("/user", "/user")).isEqualTo("/user/user"); + // SPR-10062 + assertThat(pathMatcher.combine("/{foo:.*[^0-9].*}", "/edit/")).isEqualTo("/{foo:.*[^0-9].*}/edit/"); + // SPR-10554 + assertThat(pathMatcher.combine("/1.0", "/foo/test")).isEqualTo("/1.0/foo/test"); + // SPR-12975 + assertThat(pathMatcher.combine("/", "/hotel")).isEqualTo("/hotel"); + // SPR-12975 + assertThat(pathMatcher.combine("/hotel/", "/booking")).isEqualTo("/hotel/booking"); } @Test @@ -445,53 +446,53 @@ public class AntPathMatcherTests { public void patternComparator() { Comparator comparator = pathMatcher.getPatternComparator("/hotels/new"); - assertEquals(0, comparator.compare(null, null)); - assertEquals(1, comparator.compare(null, "/hotels/new")); - assertEquals(-1, comparator.compare("/hotels/new", null)); + assertThat(comparator.compare(null, null)).isEqualTo(0); + assertThat(comparator.compare(null, "/hotels/new")).isEqualTo(1); + assertThat(comparator.compare("/hotels/new", null)).isEqualTo(-1); - assertEquals(0, comparator.compare("/hotels/new", "/hotels/new")); + assertThat(comparator.compare("/hotels/new", "/hotels/new")).isEqualTo(0); - assertEquals(-1, comparator.compare("/hotels/new", "/hotels/*")); - assertEquals(1, comparator.compare("/hotels/*", "/hotels/new")); - assertEquals(0, comparator.compare("/hotels/*", "/hotels/*")); + assertThat(comparator.compare("/hotels/new", "/hotels/*")).isEqualTo(-1); + assertThat(comparator.compare("/hotels/*", "/hotels/new")).isEqualTo(1); + assertThat(comparator.compare("/hotels/*", "/hotels/*")).isEqualTo(0); - assertEquals(-1, comparator.compare("/hotels/new", "/hotels/{hotel}")); - assertEquals(1, comparator.compare("/hotels/{hotel}", "/hotels/new")); - assertEquals(0, comparator.compare("/hotels/{hotel}", "/hotels/{hotel}")); - assertEquals(-1, comparator.compare("/hotels/{hotel}/booking", "/hotels/{hotel}/bookings/{booking}")); - assertEquals(1, comparator.compare("/hotels/{hotel}/bookings/{booking}", "/hotels/{hotel}/booking")); + assertThat(comparator.compare("/hotels/new", "/hotels/{hotel}")).isEqualTo(-1); + assertThat(comparator.compare("/hotels/{hotel}", "/hotels/new")).isEqualTo(1); + assertThat(comparator.compare("/hotels/{hotel}", "/hotels/{hotel}")).isEqualTo(0); + assertThat(comparator.compare("/hotels/{hotel}/booking", "/hotels/{hotel}/bookings/{booking}")).isEqualTo(-1); + assertThat(comparator.compare("/hotels/{hotel}/bookings/{booking}", "/hotels/{hotel}/booking")).isEqualTo(1); // SPR-10550 - assertEquals(-1, comparator.compare("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}", "/**")); - assertEquals(1, comparator.compare("/**", "/hotels/{hotel}/bookings/{booking}/cutomers/{customer}")); - assertEquals(0, comparator.compare("/**", "/**")); + assertThat(comparator.compare("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}", "/**")).isEqualTo(-1); + assertThat(comparator.compare("/**", "/hotels/{hotel}/bookings/{booking}/cutomers/{customer}")).isEqualTo(1); + assertThat(comparator.compare("/**", "/**")).isEqualTo(0); - assertEquals(-1, comparator.compare("/hotels/{hotel}", "/hotels/*")); - assertEquals(1, comparator.compare("/hotels/*", "/hotels/{hotel}")); + assertThat(comparator.compare("/hotels/{hotel}", "/hotels/*")).isEqualTo(-1); + assertThat(comparator.compare("/hotels/*", "/hotels/{hotel}")).isEqualTo(1); - assertEquals(-1, comparator.compare("/hotels/*", "/hotels/*/**")); - assertEquals(1, comparator.compare("/hotels/*/**", "/hotels/*")); + assertThat(comparator.compare("/hotels/*", "/hotels/*/**")).isEqualTo(-1); + assertThat(comparator.compare("/hotels/*/**", "/hotels/*")).isEqualTo(1); - assertEquals(-1, comparator.compare("/hotels/new", "/hotels/new.*")); - assertEquals(2, comparator.compare("/hotels/{hotel}", "/hotels/{hotel}.*")); + assertThat(comparator.compare("/hotels/new", "/hotels/new.*")).isEqualTo(-1); + assertThat(comparator.compare("/hotels/{hotel}", "/hotels/{hotel}.*")).isEqualTo(2); // SPR-6741 - assertEquals(-1, comparator.compare("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}", "/hotels/**")); - assertEquals(1, comparator.compare("/hotels/**", "/hotels/{hotel}/bookings/{booking}/cutomers/{customer}")); - assertEquals(1, comparator.compare("/hotels/foo/bar/**", "/hotels/{hotel}")); - assertEquals(-1, comparator.compare("/hotels/{hotel}", "/hotels/foo/bar/**")); - assertEquals(2, comparator.compare("/hotels/**/bookings/**", "/hotels/**")); - assertEquals(-2, comparator.compare("/hotels/**", "/hotels/**/bookings/**")); + assertThat(comparator.compare("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}", "/hotels/**")).isEqualTo(-1); + assertThat(comparator.compare("/hotels/**", "/hotels/{hotel}/bookings/{booking}/cutomers/{customer}")).isEqualTo(1); + assertThat(comparator.compare("/hotels/foo/bar/**", "/hotels/{hotel}")).isEqualTo(1); + assertThat(comparator.compare("/hotels/{hotel}", "/hotels/foo/bar/**")).isEqualTo(-1); + assertThat(comparator.compare("/hotels/**/bookings/**", "/hotels/**")).isEqualTo(2); + assertThat(comparator.compare("/hotels/**", "/hotels/**/bookings/**")).isEqualTo(-2); // SPR-8683 - assertEquals(1, comparator.compare("/**", "/hotels/{hotel}")); + assertThat(comparator.compare("/**", "/hotels/{hotel}")).isEqualTo(1); // longer is better - assertEquals(1, comparator.compare("/hotels", "/hotels2")); + assertThat(comparator.compare("/hotels", "/hotels2")).isEqualTo(1); // SPR-13139 - assertEquals(-1, comparator.compare("*", "*/**")); - assertEquals(1, comparator.compare("*/**", "*")); + assertThat(comparator.compare("*", "*/**")).isEqualTo(-1); + assertThat(comparator.compare("*/**", "*")).isEqualTo(1); } @Test @@ -502,74 +503,74 @@ public class AntPathMatcherTests { paths.add(null); paths.add("/hotels/new"); Collections.sort(paths, comparator); - assertEquals("/hotels/new", paths.get(0)); - assertNull(paths.get(1)); + assertThat(paths.get(0)).isEqualTo("/hotels/new"); + assertThat(paths.get(1)).isNull(); paths.clear(); paths.add("/hotels/new"); paths.add(null); Collections.sort(paths, comparator); - assertEquals("/hotels/new", paths.get(0)); - assertNull(paths.get(1)); + assertThat(paths.get(0)).isEqualTo("/hotels/new"); + assertThat(paths.get(1)).isNull(); paths.clear(); paths.add("/hotels/*"); paths.add("/hotels/new"); Collections.sort(paths, comparator); - assertEquals("/hotels/new", paths.get(0)); - assertEquals("/hotels/*", paths.get(1)); + assertThat(paths.get(0)).isEqualTo("/hotels/new"); + assertThat(paths.get(1)).isEqualTo("/hotels/*"); paths.clear(); paths.add("/hotels/new"); paths.add("/hotels/*"); Collections.sort(paths, comparator); - assertEquals("/hotels/new", paths.get(0)); - assertEquals("/hotels/*", paths.get(1)); + assertThat(paths.get(0)).isEqualTo("/hotels/new"); + assertThat(paths.get(1)).isEqualTo("/hotels/*"); paths.clear(); paths.add("/hotels/**"); paths.add("/hotels/*"); Collections.sort(paths, comparator); - assertEquals("/hotels/*", paths.get(0)); - assertEquals("/hotels/**", paths.get(1)); + assertThat(paths.get(0)).isEqualTo("/hotels/*"); + assertThat(paths.get(1)).isEqualTo("/hotels/**"); paths.clear(); paths.add("/hotels/*"); paths.add("/hotels/**"); Collections.sort(paths, comparator); - assertEquals("/hotels/*", paths.get(0)); - assertEquals("/hotels/**", paths.get(1)); + assertThat(paths.get(0)).isEqualTo("/hotels/*"); + assertThat(paths.get(1)).isEqualTo("/hotels/**"); paths.clear(); paths.add("/hotels/{hotel}"); paths.add("/hotels/new"); Collections.sort(paths, comparator); - assertEquals("/hotels/new", paths.get(0)); - assertEquals("/hotels/{hotel}", paths.get(1)); + assertThat(paths.get(0)).isEqualTo("/hotels/new"); + assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}"); paths.clear(); paths.add("/hotels/new"); paths.add("/hotels/{hotel}"); Collections.sort(paths, comparator); - assertEquals("/hotels/new", paths.get(0)); - assertEquals("/hotels/{hotel}", paths.get(1)); + assertThat(paths.get(0)).isEqualTo("/hotels/new"); + assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}"); paths.clear(); paths.add("/hotels/*"); paths.add("/hotels/{hotel}"); paths.add("/hotels/new"); Collections.sort(paths, comparator); - assertEquals("/hotels/new", paths.get(0)); - assertEquals("/hotels/{hotel}", paths.get(1)); - assertEquals("/hotels/*", paths.get(2)); + assertThat(paths.get(0)).isEqualTo("/hotels/new"); + assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}"); + assertThat(paths.get(2)).isEqualTo("/hotels/*"); paths.clear(); paths.add("/hotels/ne*"); paths.add("/hotels/n*"); Collections.shuffle(paths); Collections.sort(paths, comparator); - assertEquals("/hotels/ne*", paths.get(0)); - assertEquals("/hotels/n*", paths.get(1)); + assertThat(paths.get(0)).isEqualTo("/hotels/ne*"); + assertThat(paths.get(1)).isEqualTo("/hotels/n*"); paths.clear(); comparator = pathMatcher.getPatternComparator("/hotels/new.html"); @@ -577,16 +578,16 @@ public class AntPathMatcherTests { paths.add("/hotels/{hotel}"); Collections.shuffle(paths); Collections.sort(paths, comparator); - assertEquals("/hotels/new.*", paths.get(0)); - assertEquals("/hotels/{hotel}", paths.get(1)); + assertThat(paths.get(0)).isEqualTo("/hotels/new.*"); + assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}"); paths.clear(); comparator = pathMatcher.getPatternComparator("/web/endUser/action/login.html"); paths.add("/**/login.*"); paths.add("/**/endUser/action/login.*"); Collections.sort(paths, comparator); - assertEquals("/**/endUser/action/login.*", paths.get(0)); - assertEquals("/**/login.*", paths.get(1)); + assertThat(paths.get(0)).isEqualTo("/**/endUser/action/login.*"); + assertThat(paths.get(1)).isEqualTo("/**/login.*"); paths.clear(); } @@ -594,64 +595,64 @@ public class AntPathMatcherTests { public void trimTokensOff() { pathMatcher.setTrimTokens(false); - assertTrue(pathMatcher.match("/group/{groupName}/members", "/group/sales/members")); - assertTrue(pathMatcher.match("/group/{groupName}/members", "/group/ sales/members")); - assertFalse(pathMatcher.match("/group/{groupName}/members", "/Group/ Sales/Members")); + assertThat(pathMatcher.match("/group/{groupName}/members", "/group/sales/members")).isTrue(); + assertThat(pathMatcher.match("/group/{groupName}/members", "/group/ sales/members")).isTrue(); + assertThat(pathMatcher.match("/group/{groupName}/members", "/Group/ Sales/Members")).isFalse(); } @Test // SPR-13286 public void caseInsensitive() { pathMatcher.setCaseSensitive(false); - assertTrue(pathMatcher.match("/group/{groupName}/members", "/group/sales/members")); - assertTrue(pathMatcher.match("/group/{groupName}/members", "/Group/Sales/Members")); - assertTrue(pathMatcher.match("/Group/{groupName}/Members", "/group/Sales/members")); + assertThat(pathMatcher.match("/group/{groupName}/members", "/group/sales/members")).isTrue(); + assertThat(pathMatcher.match("/group/{groupName}/members", "/Group/Sales/Members")).isTrue(); + assertThat(pathMatcher.match("/Group/{groupName}/Members", "/group/Sales/members")).isTrue(); } @Test public void defaultCacheSetting() { match(); - assertTrue(pathMatcher.stringMatcherCache.size() > 20); + assertThat(pathMatcher.stringMatcherCache.size() > 20).isTrue(); for (int i = 0; i < 65536; i++) { pathMatcher.match("test" + i, "test"); } // Cache turned off because it went beyond the threshold - assertTrue(pathMatcher.stringMatcherCache.isEmpty()); + assertThat(pathMatcher.stringMatcherCache.isEmpty()).isTrue(); } @Test public void cachePatternsSetToTrue() { pathMatcher.setCachePatterns(true); match(); - assertTrue(pathMatcher.stringMatcherCache.size() > 20); + assertThat(pathMatcher.stringMatcherCache.size() > 20).isTrue(); for (int i = 0; i < 65536; i++) { pathMatcher.match("test" + i, "test" + i); } // Cache keeps being alive due to the explicit cache setting - assertTrue(pathMatcher.stringMatcherCache.size() > 65536); + assertThat(pathMatcher.stringMatcherCache.size() > 65536).isTrue(); } @Test public void preventCreatingStringMatchersIfPathDoesNotStartsWithPatternPrefix() { pathMatcher.setCachePatterns(true); - assertEquals(0, pathMatcher.stringMatcherCache.size()); + assertThat(pathMatcher.stringMatcherCache.size()).isEqualTo(0); pathMatcher.match("test?", "test"); - assertEquals(1, pathMatcher.stringMatcherCache.size()); + assertThat(pathMatcher.stringMatcherCache.size()).isEqualTo(1); pathMatcher.match("test?", "best"); pathMatcher.match("test/*", "view/test.jpg"); pathMatcher.match("test/**/test.jpg", "view/test.jpg"); pathMatcher.match("test/{name}.jpg", "view/test.jpg"); - assertEquals(1, pathMatcher.stringMatcherCache.size()); + assertThat(pathMatcher.stringMatcherCache.size()).isEqualTo(1); } @Test public void creatingStringMatchersIfPatternPrefixCannotDetermineIfPathMatch() { pathMatcher.setCachePatterns(true); - assertEquals(0, pathMatcher.stringMatcherCache.size()); + assertThat(pathMatcher.stringMatcherCache.size()).isEqualTo(0); pathMatcher.match("test", "testian"); pathMatcher.match("test?", "testFf"); @@ -662,31 +663,30 @@ public class AntPathMatcherTests { pathMatcher.match("/**/{name}.jpg", "/test/lorem.jpg"); pathMatcher.match("/*/dir/{name}.jpg", "/*/dir/lorem.jpg"); - assertEquals(7, pathMatcher.stringMatcherCache.size()); + assertThat(pathMatcher.stringMatcherCache.size()).isEqualTo(7); } @Test public void cachePatternsSetToFalse() { pathMatcher.setCachePatterns(false); match(); - assertTrue(pathMatcher.stringMatcherCache.isEmpty()); + assertThat(pathMatcher.stringMatcherCache.isEmpty()).isTrue(); } @Test public void extensionMappingWithDotPathSeparator() { pathMatcher.setPathSeparator("."); - assertEquals("Extension mapping should be disabled with \".\" as path separator", - "/*.html.hotel.*", pathMatcher.combine("/*.html", "hotel.*")); + assertThat(pathMatcher.combine("/*.html", "hotel.*")).as("Extension mapping should be disabled with \".\" as path separator").isEqualTo("/*.html.hotel.*"); } @Test // gh-22959 public void isPattern() { - assertTrue(pathMatcher.isPattern("/test/*")); - assertTrue(pathMatcher.isPattern("/test/**/name")); - assertTrue(pathMatcher.isPattern("/test?")); - assertTrue(pathMatcher.isPattern("/test/{name}")); - assertFalse(pathMatcher.isPattern("/test/name")); - assertFalse(pathMatcher.isPattern("/test/foo{bar")); + assertThat(pathMatcher.isPattern("/test/*")).isTrue(); + assertThat(pathMatcher.isPattern("/test/**/name")).isTrue(); + assertThat(pathMatcher.isPattern("/test?")).isTrue(); + assertThat(pathMatcher.isPattern("/test/{name}")).isTrue(); + assertThat(pathMatcher.isPattern("/test/name")).isFalse(); + assertThat(pathMatcher.isPattern("/test/foo{bar")).isFalse(); } } diff --git a/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java b/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java index 3bd1448722e..3dafedcc82c 100644 --- a/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java +++ b/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java @@ -22,10 +22,7 @@ import org.junit.Test; import org.springframework.tests.sample.objects.TestObject; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -57,21 +54,26 @@ public class AutoPopulatingListTests { Object lastElement = null; for (int x = 0; x < 10; x++) { Object element = list.get(x); - assertNotNull("Element is null", list.get(x)); - assertTrue("Element is incorrect type", element instanceof TestObject); - assertNotSame(lastElement, element); + assertThat(list.get(x)).as("Element is null").isNotNull(); + boolean condition = element instanceof TestObject; + assertThat(condition).as("Element is incorrect type").isTrue(); + assertThat(element).isNotSameAs(lastElement); lastElement = element; } String helloWorld = "Hello World!"; list.add(10, null); list.add(11, helloWorld); - assertEquals(helloWorld, list.get(11)); + assertThat(list.get(11)).isEqualTo(helloWorld); - assertTrue(list.get(10) instanceof TestObject); - assertTrue(list.get(12) instanceof TestObject); - assertTrue(list.get(13) instanceof TestObject); - assertTrue(list.get(20) instanceof TestObject); + boolean condition3 = list.get(10) instanceof TestObject; + assertThat(condition3).isTrue(); + boolean condition2 = list.get(12) instanceof TestObject; + assertThat(condition2).isTrue(); + boolean condition1 = list.get(13) instanceof TestObject; + assertThat(condition1).isTrue(); + boolean condition = list.get(20) instanceof TestObject; + assertThat(condition).isTrue(); } private void doTestWithElementFactory(AutoPopulatingList list) { @@ -80,7 +82,7 @@ public class AutoPopulatingListTests { for (int x = 0; x < list.size(); x++) { Object element = list.get(x); if (element instanceof TestObject) { - assertEquals(x, ((TestObject) element).getAge()); + assertThat(((TestObject) element).getAge()).isEqualTo(x); } } } @@ -88,7 +90,7 @@ public class AutoPopulatingListTests { @Test public void serialization() throws Exception { AutoPopulatingList list = new AutoPopulatingList(TestObject.class); - assertEquals(list, SerializationTestUtils.serializeAndDeserialize(list)); + assertThat(SerializationTestUtils.serializeAndDeserialize(list)).isEqualTo(list); } diff --git a/spring-core/src/test/java/org/springframework/util/Base64UtilsTests.java b/spring-core/src/test/java/org/springframework/util/Base64UtilsTests.java index c6fc3fdc3f2..836e8eff116 100644 --- a/spring-core/src/test/java/org/springframework/util/Base64UtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/Base64UtilsTests.java @@ -21,8 +21,7 @@ import javax.xml.bind.DatatypeConverter; import org.junit.Test; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -34,57 +33,57 @@ public class Base64UtilsTests { public void encode() throws UnsupportedEncodingException { byte[] bytes = new byte[] {-0x4f, 0xa, -0x73, -0x4f, 0x64, -0x20, 0x75, 0x41, 0x5, -0x49, -0x57, -0x65, -0x19, 0x2e, 0x3f, -0x1b}; - assertArrayEquals(bytes, Base64Utils.decode(Base64Utils.encode(bytes))); + assertThat(Base64Utils.decode(Base64Utils.encode(bytes))).isEqualTo(bytes); bytes = "Hello World".getBytes("UTF-8"); - assertArrayEquals(bytes, Base64Utils.decode(Base64Utils.encode(bytes))); + assertThat(Base64Utils.decode(Base64Utils.encode(bytes))).isEqualTo(bytes); bytes = "Hello World\r\nSecond Line".getBytes("UTF-8"); - assertArrayEquals(bytes, Base64Utils.decode(Base64Utils.encode(bytes))); + assertThat(Base64Utils.decode(Base64Utils.encode(bytes))).isEqualTo(bytes); bytes = "Hello World\r\nSecond Line\r\n".getBytes("UTF-8"); - assertArrayEquals(bytes, Base64Utils.decode(Base64Utils.encode(bytes))); + assertThat(Base64Utils.decode(Base64Utils.encode(bytes))).isEqualTo(bytes); bytes = new byte[] { (byte) 0xfb, (byte) 0xf0 }; - assertArrayEquals("+/A=".getBytes(), Base64Utils.encode(bytes)); - assertArrayEquals(bytes, Base64Utils.decode(Base64Utils.encode(bytes))); + assertThat(Base64Utils.encode(bytes)).isEqualTo("+/A=".getBytes()); + assertThat(Base64Utils.decode(Base64Utils.encode(bytes))).isEqualTo(bytes); - assertArrayEquals("-_A=".getBytes(), Base64Utils.encodeUrlSafe(bytes)); - assertArrayEquals(bytes, Base64Utils.decodeUrlSafe(Base64Utils.encodeUrlSafe(bytes))); + assertThat(Base64Utils.encodeUrlSafe(bytes)).isEqualTo("-_A=".getBytes()); + assertThat(Base64Utils.decodeUrlSafe(Base64Utils.encodeUrlSafe(bytes))).isEqualTo(bytes); } @Test public void encodeToStringWithJdk8VsJaxb() throws UnsupportedEncodingException { byte[] bytes = new byte[] {-0x4f, 0xa, -0x73, -0x4f, 0x64, -0x20, 0x75, 0x41, 0x5, -0x49, -0x57, -0x65, -0x19, 0x2e, 0x3f, -0x1b}; - assertEquals(Base64Utils.encodeToString(bytes), DatatypeConverter.printBase64Binary(bytes)); - assertArrayEquals(bytes, Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))); - assertArrayEquals(bytes, DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))); + assertThat(DatatypeConverter.printBase64Binary(bytes)).isEqualTo(Base64Utils.encodeToString(bytes)); + assertThat(Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))).isEqualTo(bytes); + assertThat(DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))).isEqualTo(bytes); bytes = "Hello World".getBytes("UTF-8"); - assertEquals(Base64Utils.encodeToString(bytes), DatatypeConverter.printBase64Binary(bytes)); - assertArrayEquals(bytes, Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))); - assertArrayEquals(bytes, DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))); + assertThat(DatatypeConverter.printBase64Binary(bytes)).isEqualTo(Base64Utils.encodeToString(bytes)); + assertThat(Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))).isEqualTo(bytes); + assertThat(DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))).isEqualTo(bytes); bytes = "Hello World\r\nSecond Line".getBytes("UTF-8"); - assertEquals(Base64Utils.encodeToString(bytes), DatatypeConverter.printBase64Binary(bytes)); - assertArrayEquals(bytes, Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))); - assertArrayEquals(bytes, DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))); + assertThat(DatatypeConverter.printBase64Binary(bytes)).isEqualTo(Base64Utils.encodeToString(bytes)); + assertThat(Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))).isEqualTo(bytes); + assertThat(DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))).isEqualTo(bytes); bytes = "Hello World\r\nSecond Line\r\n".getBytes("UTF-8"); - assertEquals(Base64Utils.encodeToString(bytes), DatatypeConverter.printBase64Binary(bytes)); - assertArrayEquals(bytes, Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))); - assertArrayEquals(bytes, DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))); + assertThat(DatatypeConverter.printBase64Binary(bytes)).isEqualTo(Base64Utils.encodeToString(bytes)); + assertThat(Base64Utils.decodeFromString(Base64Utils.encodeToString(bytes))).isEqualTo(bytes); + assertThat(DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(bytes))).isEqualTo(bytes); } @Test public void encodeDecodeUrlSafe() { byte[] bytes = new byte[] { (byte) 0xfb, (byte) 0xf0 }; - assertArrayEquals("-_A=".getBytes(), Base64Utils.encodeUrlSafe(bytes)); - assertArrayEquals(bytes, Base64Utils.decodeUrlSafe(Base64Utils.encodeUrlSafe(bytes))); + assertThat(Base64Utils.encodeUrlSafe(bytes)).isEqualTo("-_A=".getBytes()); + assertThat(Base64Utils.decodeUrlSafe(Base64Utils.encodeUrlSafe(bytes))).isEqualTo(bytes); - assertEquals("-_A=", Base64Utils.encodeToUrlSafeString(bytes)); - assertArrayEquals(bytes, Base64Utils.decodeFromUrlSafeString(Base64Utils.encodeToUrlSafeString(bytes))); + assertThat(Base64Utils.encodeToUrlSafeString(bytes)).isEqualTo("-_A="); + assertThat(Base64Utils.decodeFromUrlSafeString(Base64Utils.encodeToUrlSafeString(bytes))).isEqualTo(bytes); } } diff --git a/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java index edb4ec5c18d..a5d35b26923 100644 --- a/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java @@ -37,11 +37,7 @@ import org.springframework.tests.sample.objects.ITestInterface; import org.springframework.tests.sample.objects.ITestObject; import org.springframework.tests.sample.objects.TestObject; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Colin Sampaleanu @@ -64,60 +60,60 @@ public class ClassUtilsTests { @Test public void testIsPresent() { - assertTrue(ClassUtils.isPresent("java.lang.String", classLoader)); - assertFalse(ClassUtils.isPresent("java.lang.MySpecialString", classLoader)); + assertThat(ClassUtils.isPresent("java.lang.String", classLoader)).isTrue(); + assertThat(ClassUtils.isPresent("java.lang.MySpecialString", classLoader)).isFalse(); } @Test public void testForName() throws ClassNotFoundException { - assertEquals(String.class, ClassUtils.forName("java.lang.String", classLoader)); - assertEquals(String[].class, ClassUtils.forName("java.lang.String[]", classLoader)); - assertEquals(String[].class, ClassUtils.forName(String[].class.getName(), classLoader)); - assertEquals(String[][].class, ClassUtils.forName(String[][].class.getName(), classLoader)); - assertEquals(String[][][].class, ClassUtils.forName(String[][][].class.getName(), classLoader)); - assertEquals(TestObject.class, ClassUtils.forName("org.springframework.tests.sample.objects.TestObject", classLoader)); - assertEquals(TestObject[].class, ClassUtils.forName("org.springframework.tests.sample.objects.TestObject[]", classLoader)); - assertEquals(TestObject[].class, ClassUtils.forName(TestObject[].class.getName(), classLoader)); - assertEquals(TestObject[][].class, ClassUtils.forName("org.springframework.tests.sample.objects.TestObject[][]", classLoader)); - assertEquals(TestObject[][].class, ClassUtils.forName(TestObject[][].class.getName(), classLoader)); - assertEquals(short[][][].class, ClassUtils.forName("[[[S", classLoader)); + assertThat(ClassUtils.forName("java.lang.String", classLoader)).isEqualTo(String.class); + assertThat(ClassUtils.forName("java.lang.String[]", classLoader)).isEqualTo(String[].class); + assertThat(ClassUtils.forName(String[].class.getName(), classLoader)).isEqualTo(String[].class); + assertThat(ClassUtils.forName(String[][].class.getName(), classLoader)).isEqualTo(String[][].class); + assertThat(ClassUtils.forName(String[][][].class.getName(), classLoader)).isEqualTo(String[][][].class); + assertThat(ClassUtils.forName("org.springframework.tests.sample.objects.TestObject", classLoader)).isEqualTo(TestObject.class); + assertThat(ClassUtils.forName("org.springframework.tests.sample.objects.TestObject[]", classLoader)).isEqualTo(TestObject[].class); + assertThat(ClassUtils.forName(TestObject[].class.getName(), classLoader)).isEqualTo(TestObject[].class); + assertThat(ClassUtils.forName("org.springframework.tests.sample.objects.TestObject[][]", classLoader)).isEqualTo(TestObject[][].class); + assertThat(ClassUtils.forName(TestObject[][].class.getName(), classLoader)).isEqualTo(TestObject[][].class); + assertThat(ClassUtils.forName("[[[S", classLoader)).isEqualTo(short[][][].class); } @Test public void testForNameWithPrimitiveClasses() throws ClassNotFoundException { - assertEquals(boolean.class, ClassUtils.forName("boolean", classLoader)); - assertEquals(byte.class, ClassUtils.forName("byte", classLoader)); - assertEquals(char.class, ClassUtils.forName("char", classLoader)); - assertEquals(short.class, ClassUtils.forName("short", classLoader)); - assertEquals(int.class, ClassUtils.forName("int", classLoader)); - assertEquals(long.class, ClassUtils.forName("long", classLoader)); - assertEquals(float.class, ClassUtils.forName("float", classLoader)); - assertEquals(double.class, ClassUtils.forName("double", classLoader)); - assertEquals(void.class, ClassUtils.forName("void", classLoader)); + assertThat(ClassUtils.forName("boolean", classLoader)).isEqualTo(boolean.class); + assertThat(ClassUtils.forName("byte", classLoader)).isEqualTo(byte.class); + assertThat(ClassUtils.forName("char", classLoader)).isEqualTo(char.class); + assertThat(ClassUtils.forName("short", classLoader)).isEqualTo(short.class); + assertThat(ClassUtils.forName("int", classLoader)).isEqualTo(int.class); + assertThat(ClassUtils.forName("long", classLoader)).isEqualTo(long.class); + assertThat(ClassUtils.forName("float", classLoader)).isEqualTo(float.class); + assertThat(ClassUtils.forName("double", classLoader)).isEqualTo(double.class); + assertThat(ClassUtils.forName("void", classLoader)).isEqualTo(void.class); } @Test public void testForNameWithPrimitiveArrays() throws ClassNotFoundException { - assertEquals(boolean[].class, ClassUtils.forName("boolean[]", classLoader)); - assertEquals(byte[].class, ClassUtils.forName("byte[]", classLoader)); - assertEquals(char[].class, ClassUtils.forName("char[]", classLoader)); - assertEquals(short[].class, ClassUtils.forName("short[]", classLoader)); - assertEquals(int[].class, ClassUtils.forName("int[]", classLoader)); - assertEquals(long[].class, ClassUtils.forName("long[]", classLoader)); - assertEquals(float[].class, ClassUtils.forName("float[]", classLoader)); - assertEquals(double[].class, ClassUtils.forName("double[]", classLoader)); + assertThat(ClassUtils.forName("boolean[]", classLoader)).isEqualTo(boolean[].class); + assertThat(ClassUtils.forName("byte[]", classLoader)).isEqualTo(byte[].class); + assertThat(ClassUtils.forName("char[]", classLoader)).isEqualTo(char[].class); + assertThat(ClassUtils.forName("short[]", classLoader)).isEqualTo(short[].class); + assertThat(ClassUtils.forName("int[]", classLoader)).isEqualTo(int[].class); + assertThat(ClassUtils.forName("long[]", classLoader)).isEqualTo(long[].class); + assertThat(ClassUtils.forName("float[]", classLoader)).isEqualTo(float[].class); + assertThat(ClassUtils.forName("double[]", classLoader)).isEqualTo(double[].class); } @Test public void testForNameWithPrimitiveArraysInternalName() throws ClassNotFoundException { - assertEquals(boolean[].class, ClassUtils.forName(boolean[].class.getName(), classLoader)); - assertEquals(byte[].class, ClassUtils.forName(byte[].class.getName(), classLoader)); - assertEquals(char[].class, ClassUtils.forName(char[].class.getName(), classLoader)); - assertEquals(short[].class, ClassUtils.forName(short[].class.getName(), classLoader)); - assertEquals(int[].class, ClassUtils.forName(int[].class.getName(), classLoader)); - assertEquals(long[].class, ClassUtils.forName(long[].class.getName(), classLoader)); - assertEquals(float[].class, ClassUtils.forName(float[].class.getName(), classLoader)); - assertEquals(double[].class, ClassUtils.forName(double[].class.getName(), classLoader)); + assertThat(ClassUtils.forName(boolean[].class.getName(), classLoader)).isEqualTo(boolean[].class); + assertThat(ClassUtils.forName(byte[].class.getName(), classLoader)).isEqualTo(byte[].class); + assertThat(ClassUtils.forName(char[].class.getName(), classLoader)).isEqualTo(char[].class); + assertThat(ClassUtils.forName(short[].class.getName(), classLoader)).isEqualTo(short[].class); + assertThat(ClassUtils.forName(int[].class.getName(), classLoader)).isEqualTo(int[].class); + assertThat(ClassUtils.forName(long[].class.getName(), classLoader)).isEqualTo(long[].class); + assertThat(ClassUtils.forName(float[].class.getName(), classLoader)).isEqualTo(float[].class); + assertThat(ClassUtils.forName(double[].class.getName(), classLoader)).isEqualTo(double[].class); } @Test @@ -133,208 +129,204 @@ public class ClassUtilsTests { Class composite = ClassUtils.createCompositeInterface( new Class[] {Serializable.class, Externalizable.class}, childLoader1); - assertTrue(ClassUtils.isCacheSafe(String.class, null)); - assertTrue(ClassUtils.isCacheSafe(String.class, classLoader)); - assertTrue(ClassUtils.isCacheSafe(String.class, childLoader1)); - assertTrue(ClassUtils.isCacheSafe(String.class, childLoader2)); - assertTrue(ClassUtils.isCacheSafe(String.class, childLoader3)); - assertFalse(ClassUtils.isCacheSafe(InnerClass.class, null)); - assertTrue(ClassUtils.isCacheSafe(InnerClass.class, classLoader)); - assertTrue(ClassUtils.isCacheSafe(InnerClass.class, childLoader1)); - assertTrue(ClassUtils.isCacheSafe(InnerClass.class, childLoader2)); - assertTrue(ClassUtils.isCacheSafe(InnerClass.class, childLoader3)); - assertFalse(ClassUtils.isCacheSafe(composite, null)); - assertFalse(ClassUtils.isCacheSafe(composite, classLoader)); - assertTrue(ClassUtils.isCacheSafe(composite, childLoader1)); - assertFalse(ClassUtils.isCacheSafe(composite, childLoader2)); - assertTrue(ClassUtils.isCacheSafe(composite, childLoader3)); + assertThat(ClassUtils.isCacheSafe(String.class, null)).isTrue(); + assertThat(ClassUtils.isCacheSafe(String.class, classLoader)).isTrue(); + assertThat(ClassUtils.isCacheSafe(String.class, childLoader1)).isTrue(); + assertThat(ClassUtils.isCacheSafe(String.class, childLoader2)).isTrue(); + assertThat(ClassUtils.isCacheSafe(String.class, childLoader3)).isTrue(); + assertThat(ClassUtils.isCacheSafe(InnerClass.class, null)).isFalse(); + assertThat(ClassUtils.isCacheSafe(InnerClass.class, classLoader)).isTrue(); + assertThat(ClassUtils.isCacheSafe(InnerClass.class, childLoader1)).isTrue(); + assertThat(ClassUtils.isCacheSafe(InnerClass.class, childLoader2)).isTrue(); + assertThat(ClassUtils.isCacheSafe(InnerClass.class, childLoader3)).isTrue(); + assertThat(ClassUtils.isCacheSafe(composite, null)).isFalse(); + assertThat(ClassUtils.isCacheSafe(composite, classLoader)).isFalse(); + assertThat(ClassUtils.isCacheSafe(composite, childLoader1)).isTrue(); + assertThat(ClassUtils.isCacheSafe(composite, childLoader2)).isFalse(); + assertThat(ClassUtils.isCacheSafe(composite, childLoader3)).isTrue(); } @Test public void testGetShortName() { String className = ClassUtils.getShortName(getClass()); - assertEquals("Class name did not match", "ClassUtilsTests", className); + assertThat(className).as("Class name did not match").isEqualTo("ClassUtilsTests"); } @Test public void testGetShortNameForObjectArrayClass() { String className = ClassUtils.getShortName(Object[].class); - assertEquals("Class name did not match", "Object[]", className); + assertThat(className).as("Class name did not match").isEqualTo("Object[]"); } @Test public void testGetShortNameForMultiDimensionalObjectArrayClass() { String className = ClassUtils.getShortName(Object[][].class); - assertEquals("Class name did not match", "Object[][]", className); + assertThat(className).as("Class name did not match").isEqualTo("Object[][]"); } @Test public void testGetShortNameForPrimitiveArrayClass() { String className = ClassUtils.getShortName(byte[].class); - assertEquals("Class name did not match", "byte[]", className); + assertThat(className).as("Class name did not match").isEqualTo("byte[]"); } @Test public void testGetShortNameForMultiDimensionalPrimitiveArrayClass() { String className = ClassUtils.getShortName(byte[][][].class); - assertEquals("Class name did not match", "byte[][][]", className); + assertThat(className).as("Class name did not match").isEqualTo("byte[][][]"); } @Test public void testGetShortNameForInnerClass() { String className = ClassUtils.getShortName(InnerClass.class); - assertEquals("Class name did not match", "ClassUtilsTests.InnerClass", className); + assertThat(className).as("Class name did not match").isEqualTo("ClassUtilsTests.InnerClass"); } @Test public void testGetShortNameAsProperty() { String shortName = ClassUtils.getShortNameAsProperty(this.getClass()); - assertEquals("Class name did not match", "classUtilsTests", shortName); + assertThat(shortName).as("Class name did not match").isEqualTo("classUtilsTests"); } @Test public void testGetClassFileName() { - assertEquals("String.class", ClassUtils.getClassFileName(String.class)); - assertEquals("ClassUtilsTests.class", ClassUtils.getClassFileName(getClass())); + assertThat(ClassUtils.getClassFileName(String.class)).isEqualTo("String.class"); + assertThat(ClassUtils.getClassFileName(getClass())).isEqualTo("ClassUtilsTests.class"); } @Test public void testGetPackageName() { - assertEquals("java.lang", ClassUtils.getPackageName(String.class)); - assertEquals(getClass().getPackage().getName(), ClassUtils.getPackageName(getClass())); + assertThat(ClassUtils.getPackageName(String.class)).isEqualTo("java.lang"); + assertThat(ClassUtils.getPackageName(getClass())).isEqualTo(getClass().getPackage().getName()); } @Test public void testGetQualifiedName() { String className = ClassUtils.getQualifiedName(getClass()); - assertEquals("Class name did not match", "org.springframework.util.ClassUtilsTests", className); + assertThat(className).as("Class name did not match").isEqualTo("org.springframework.util.ClassUtilsTests"); } @Test public void testGetQualifiedNameForObjectArrayClass() { String className = ClassUtils.getQualifiedName(Object[].class); - assertEquals("Class name did not match", "java.lang.Object[]", className); + assertThat(className).as("Class name did not match").isEqualTo("java.lang.Object[]"); } @Test public void testGetQualifiedNameForMultiDimensionalObjectArrayClass() { String className = ClassUtils.getQualifiedName(Object[][].class); - assertEquals("Class name did not match", "java.lang.Object[][]", className); + assertThat(className).as("Class name did not match").isEqualTo("java.lang.Object[][]"); } @Test public void testGetQualifiedNameForPrimitiveArrayClass() { String className = ClassUtils.getQualifiedName(byte[].class); - assertEquals("Class name did not match", "byte[]", className); + assertThat(className).as("Class name did not match").isEqualTo("byte[]"); } @Test public void testGetQualifiedNameForMultiDimensionalPrimitiveArrayClass() { String className = ClassUtils.getQualifiedName(byte[][].class); - assertEquals("Class name did not match", "byte[][]", className); + assertThat(className).as("Class name did not match").isEqualTo("byte[][]"); } @Test public void testHasMethod() { - assertTrue(ClassUtils.hasMethod(Collection.class, "size")); - assertTrue(ClassUtils.hasMethod(Collection.class, "remove", Object.class)); - assertFalse(ClassUtils.hasMethod(Collection.class, "remove")); - assertFalse(ClassUtils.hasMethod(Collection.class, "someOtherMethod")); + assertThat(ClassUtils.hasMethod(Collection.class, "size")).isTrue(); + assertThat(ClassUtils.hasMethod(Collection.class, "remove", Object.class)).isTrue(); + assertThat(ClassUtils.hasMethod(Collection.class, "remove")).isFalse(); + assertThat(ClassUtils.hasMethod(Collection.class, "someOtherMethod")).isFalse(); } @Test public void testGetMethodIfAvailable() { Method method = ClassUtils.getMethodIfAvailable(Collection.class, "size"); - assertNotNull(method); - assertEquals("size", method.getName()); + assertThat(method).isNotNull(); + assertThat(method.getName()).isEqualTo("size"); method = ClassUtils.getMethodIfAvailable(Collection.class, "remove", Object.class); - assertNotNull(method); - assertEquals("remove", method.getName()); + assertThat(method).isNotNull(); + assertThat(method.getName()).isEqualTo("remove"); - assertNull(ClassUtils.getMethodIfAvailable(Collection.class, "remove")); - assertNull(ClassUtils.getMethodIfAvailable(Collection.class, "someOtherMethod")); + assertThat(ClassUtils.getMethodIfAvailable(Collection.class, "remove")).isNull(); + assertThat(ClassUtils.getMethodIfAvailable(Collection.class, "someOtherMethod")).isNull(); } @Test public void testGetMethodCountForName() { - assertEquals("Verifying number of overloaded 'print' methods for OverloadedMethodsClass.", 2, - ClassUtils.getMethodCountForName(OverloadedMethodsClass.class, "print")); - assertEquals("Verifying number of overloaded 'print' methods for SubOverloadedMethodsClass.", 4, - ClassUtils.getMethodCountForName(SubOverloadedMethodsClass.class, "print")); + assertThat(ClassUtils.getMethodCountForName(OverloadedMethodsClass.class, "print")).as("Verifying number of overloaded 'print' methods for OverloadedMethodsClass.").isEqualTo(2); + assertThat(ClassUtils.getMethodCountForName(SubOverloadedMethodsClass.class, "print")).as("Verifying number of overloaded 'print' methods for SubOverloadedMethodsClass.").isEqualTo(4); } @Test public void testCountOverloadedMethods() { - assertFalse(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "foobar")); + assertThat(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "foobar")).isFalse(); // no args - assertTrue(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "hashCode")); + assertThat(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "hashCode")).isTrue(); // matches although it takes an arg - assertTrue(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "setAge")); + assertThat(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "setAge")).isTrue(); } @Test public void testNoArgsStaticMethod() throws IllegalAccessException, InvocationTargetException { Method method = ClassUtils.getStaticMethod(InnerClass.class, "staticMethod"); method.invoke(null, (Object[]) null); - assertTrue("no argument method was not invoked.", - InnerClass.noArgCalled); + assertThat(InnerClass.noArgCalled).as("no argument method was not invoked.").isTrue(); } @Test public void testArgsStaticMethod() throws IllegalAccessException, InvocationTargetException { Method method = ClassUtils.getStaticMethod(InnerClass.class, "argStaticMethod", String.class); method.invoke(null, "test"); - assertTrue("argument method was not invoked.", InnerClass.argCalled); + assertThat(InnerClass.argCalled).as("argument method was not invoked.").isTrue(); } @Test public void testOverloadedStaticMethod() throws IllegalAccessException, InvocationTargetException { Method method = ClassUtils.getStaticMethod(InnerClass.class, "staticMethod", String.class); method.invoke(null, "test"); - assertTrue("argument method was not invoked.", InnerClass.overloadedCalled); + assertThat(InnerClass.overloadedCalled).as("argument method was not invoked.").isTrue(); } @Test public void testIsAssignable() { - assertTrue(ClassUtils.isAssignable(Object.class, Object.class)); - assertTrue(ClassUtils.isAssignable(String.class, String.class)); - assertTrue(ClassUtils.isAssignable(Object.class, String.class)); - assertTrue(ClassUtils.isAssignable(Object.class, Integer.class)); - assertTrue(ClassUtils.isAssignable(Number.class, Integer.class)); - assertTrue(ClassUtils.isAssignable(Number.class, int.class)); - assertTrue(ClassUtils.isAssignable(Integer.class, int.class)); - assertTrue(ClassUtils.isAssignable(int.class, Integer.class)); - assertFalse(ClassUtils.isAssignable(String.class, Object.class)); - assertFalse(ClassUtils.isAssignable(Integer.class, Number.class)); - assertFalse(ClassUtils.isAssignable(Integer.class, double.class)); - assertFalse(ClassUtils.isAssignable(double.class, Integer.class)); + assertThat(ClassUtils.isAssignable(Object.class, Object.class)).isTrue(); + assertThat(ClassUtils.isAssignable(String.class, String.class)).isTrue(); + assertThat(ClassUtils.isAssignable(Object.class, String.class)).isTrue(); + assertThat(ClassUtils.isAssignable(Object.class, Integer.class)).isTrue(); + assertThat(ClassUtils.isAssignable(Number.class, Integer.class)).isTrue(); + assertThat(ClassUtils.isAssignable(Number.class, int.class)).isTrue(); + assertThat(ClassUtils.isAssignable(Integer.class, int.class)).isTrue(); + assertThat(ClassUtils.isAssignable(int.class, Integer.class)).isTrue(); + assertThat(ClassUtils.isAssignable(String.class, Object.class)).isFalse(); + assertThat(ClassUtils.isAssignable(Integer.class, Number.class)).isFalse(); + assertThat(ClassUtils.isAssignable(Integer.class, double.class)).isFalse(); + assertThat(ClassUtils.isAssignable(double.class, Integer.class)).isFalse(); } @Test public void testClassPackageAsResourcePath() { String result = ClassUtils.classPackageAsResourcePath(Proxy.class); - assertEquals("java/lang/reflect", result); + assertThat(result).isEqualTo("java/lang/reflect"); } @Test public void testAddResourcePathToPackagePath() { String result = "java/lang/reflect/xyzabc.xml"; - assertEquals(result, ClassUtils.addResourcePathToPackagePath(Proxy.class, "xyzabc.xml")); - assertEquals(result, ClassUtils.addResourcePathToPackagePath(Proxy.class, "/xyzabc.xml")); + assertThat(ClassUtils.addResourcePathToPackagePath(Proxy.class, "xyzabc.xml")).isEqualTo(result); + assertThat(ClassUtils.addResourcePathToPackagePath(Proxy.class, "/xyzabc.xml")).isEqualTo(result); - assertEquals("java/lang/reflect/a/b/c/d.xml", - ClassUtils.addResourcePathToPackagePath(Proxy.class, "a/b/c/d.xml")); + assertThat(ClassUtils.addResourcePathToPackagePath(Proxy.class, "a/b/c/d.xml")).isEqualTo("java/lang/reflect/a/b/c/d.xml"); } @Test public void testGetAllInterfaces() { DerivedTestObject testBean = new DerivedTestObject(); List> ifcs = Arrays.asList(ClassUtils.getAllInterfaces(testBean)); - assertEquals("Correct number of interfaces", 4, ifcs.size()); - assertTrue("Contains Serializable", ifcs.contains(Serializable.class)); - assertTrue("Contains ITestBean", ifcs.contains(ITestObject.class)); - assertTrue("Contains IOther", ifcs.contains(ITestInterface.class)); + assertThat(ifcs.size()).as("Correct number of interfaces").isEqualTo(4); + assertThat(ifcs.contains(Serializable.class)).as("Contains Serializable").isTrue(); + assertThat(ifcs.contains(ITestObject.class)).as("Contains ITestBean").isTrue(); + assertThat(ifcs.contains(ITestInterface.class)).as("Contains IOther").isTrue(); } @Test @@ -342,50 +334,50 @@ public class ClassUtilsTests { List> ifcs = new LinkedList<>(); ifcs.add(Serializable.class); ifcs.add(Runnable.class); - assertEquals("[interface java.io.Serializable, interface java.lang.Runnable]", ifcs.toString()); - assertEquals("[java.io.Serializable, java.lang.Runnable]", ClassUtils.classNamesToString(ifcs)); + assertThat(ifcs.toString()).isEqualTo("[interface java.io.Serializable, interface java.lang.Runnable]"); + assertThat(ClassUtils.classNamesToString(ifcs)).isEqualTo("[java.io.Serializable, java.lang.Runnable]"); List> classes = new LinkedList<>(); classes.add(LinkedList.class); classes.add(Integer.class); - assertEquals("[class java.util.LinkedList, class java.lang.Integer]", classes.toString()); - assertEquals("[java.util.LinkedList, java.lang.Integer]", ClassUtils.classNamesToString(classes)); + assertThat(classes.toString()).isEqualTo("[class java.util.LinkedList, class java.lang.Integer]"); + assertThat(ClassUtils.classNamesToString(classes)).isEqualTo("[java.util.LinkedList, java.lang.Integer]"); - assertEquals("[interface java.util.List]", Collections.singletonList(List.class).toString()); - assertEquals("[java.util.List]", ClassUtils.classNamesToString(List.class)); + assertThat(Collections.singletonList(List.class).toString()).isEqualTo("[interface java.util.List]"); + assertThat(ClassUtils.classNamesToString(List.class)).isEqualTo("[java.util.List]"); - assertEquals("[]", Collections.EMPTY_LIST.toString()); - assertEquals("[]", ClassUtils.classNamesToString(Collections.emptyList())); + assertThat(Collections.EMPTY_LIST.toString()).isEqualTo("[]"); + assertThat(ClassUtils.classNamesToString(Collections.emptyList())).isEqualTo("[]"); } @Test public void testDetermineCommonAncestor() { - assertEquals(Number.class, ClassUtils.determineCommonAncestor(Integer.class, Number.class)); - assertEquals(Number.class, ClassUtils.determineCommonAncestor(Number.class, Integer.class)); - assertEquals(Number.class, ClassUtils.determineCommonAncestor(Number.class, null)); - assertEquals(Integer.class, ClassUtils.determineCommonAncestor(null, Integer.class)); - assertEquals(Integer.class, ClassUtils.determineCommonAncestor(Integer.class, Integer.class)); + assertThat(ClassUtils.determineCommonAncestor(Integer.class, Number.class)).isEqualTo(Number.class); + assertThat(ClassUtils.determineCommonAncestor(Number.class, Integer.class)).isEqualTo(Number.class); + assertThat(ClassUtils.determineCommonAncestor(Number.class, null)).isEqualTo(Number.class); + assertThat(ClassUtils.determineCommonAncestor(null, Integer.class)).isEqualTo(Integer.class); + assertThat(ClassUtils.determineCommonAncestor(Integer.class, Integer.class)).isEqualTo(Integer.class); - assertEquals(Number.class, ClassUtils.determineCommonAncestor(Integer.class, Float.class)); - assertEquals(Number.class, ClassUtils.determineCommonAncestor(Float.class, Integer.class)); - assertNull(ClassUtils.determineCommonAncestor(Integer.class, String.class)); - assertNull(ClassUtils.determineCommonAncestor(String.class, Integer.class)); + assertThat(ClassUtils.determineCommonAncestor(Integer.class, Float.class)).isEqualTo(Number.class); + assertThat(ClassUtils.determineCommonAncestor(Float.class, Integer.class)).isEqualTo(Number.class); + assertThat(ClassUtils.determineCommonAncestor(Integer.class, String.class)).isNull(); + assertThat(ClassUtils.determineCommonAncestor(String.class, Integer.class)).isNull(); - assertEquals(Collection.class, ClassUtils.determineCommonAncestor(List.class, Collection.class)); - assertEquals(Collection.class, ClassUtils.determineCommonAncestor(Collection.class, List.class)); - assertEquals(Collection.class, ClassUtils.determineCommonAncestor(Collection.class, null)); - assertEquals(List.class, ClassUtils.determineCommonAncestor(null, List.class)); - assertEquals(List.class, ClassUtils.determineCommonAncestor(List.class, List.class)); + assertThat(ClassUtils.determineCommonAncestor(List.class, Collection.class)).isEqualTo(Collection.class); + assertThat(ClassUtils.determineCommonAncestor(Collection.class, List.class)).isEqualTo(Collection.class); + assertThat(ClassUtils.determineCommonAncestor(Collection.class, null)).isEqualTo(Collection.class); + assertThat(ClassUtils.determineCommonAncestor(null, List.class)).isEqualTo(List.class); + assertThat(ClassUtils.determineCommonAncestor(List.class, List.class)).isEqualTo(List.class); - assertNull(ClassUtils.determineCommonAncestor(List.class, Set.class)); - assertNull(ClassUtils.determineCommonAncestor(Set.class, List.class)); - assertNull(ClassUtils.determineCommonAncestor(List.class, Runnable.class)); - assertNull(ClassUtils.determineCommonAncestor(Runnable.class, List.class)); + assertThat(ClassUtils.determineCommonAncestor(List.class, Set.class)).isNull(); + assertThat(ClassUtils.determineCommonAncestor(Set.class, List.class)).isNull(); + assertThat(ClassUtils.determineCommonAncestor(List.class, Runnable.class)).isNull(); + assertThat(ClassUtils.determineCommonAncestor(Runnable.class, List.class)).isNull(); - assertEquals(List.class, ClassUtils.determineCommonAncestor(List.class, ArrayList.class)); - assertEquals(List.class, ClassUtils.determineCommonAncestor(ArrayList.class, List.class)); - assertNull(ClassUtils.determineCommonAncestor(List.class, String.class)); - assertNull(ClassUtils.determineCommonAncestor(String.class, List.class)); + assertThat(ClassUtils.determineCommonAncestor(List.class, ArrayList.class)).isEqualTo(List.class); + assertThat(ClassUtils.determineCommonAncestor(ArrayList.class, List.class)).isEqualTo(List.class); + assertThat(ClassUtils.determineCommonAncestor(List.class, String.class)).isNull(); + assertThat(ClassUtils.determineCommonAncestor(String.class, List.class)).isNull(); } diff --git a/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java b/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java index 5c858569562..d80f15a236a 100644 --- a/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/CollectionUtilsTests.java @@ -30,9 +30,7 @@ import java.util.Set; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -43,18 +41,18 @@ public class CollectionUtilsTests { @Test public void testIsEmpty() { - assertTrue(CollectionUtils.isEmpty((Set) null)); - assertTrue(CollectionUtils.isEmpty((Map) null)); - assertTrue(CollectionUtils.isEmpty(new HashMap())); - assertTrue(CollectionUtils.isEmpty(new HashSet<>())); + assertThat(CollectionUtils.isEmpty((Set) null)).isTrue(); + assertThat(CollectionUtils.isEmpty((Map) null)).isTrue(); + assertThat(CollectionUtils.isEmpty(new HashMap())).isTrue(); + assertThat(CollectionUtils.isEmpty(new HashSet<>())).isTrue(); List list = new LinkedList<>(); list.add(new Object()); - assertFalse(CollectionUtils.isEmpty(list)); + assertThat(CollectionUtils.isEmpty(list)).isFalse(); Map map = new HashMap<>(); map.put("foo", "bar"); - assertFalse(CollectionUtils.isEmpty(map)); + assertThat(CollectionUtils.isEmpty(map)).isFalse(); } @Test @@ -64,9 +62,9 @@ public class CollectionUtilsTests { list.add("value3"); CollectionUtils.mergeArrayIntoCollection(arr, list); - assertEquals("value3", list.get(0)); - assertEquals("value1", list.get(1)); - assertEquals("value2", list.get(2)); + assertThat(list.get(0)).isEqualTo("value3"); + assertThat(list.get(1)).isEqualTo("value1"); + assertThat(list.get(2)).isEqualTo("value2"); } @Test @@ -76,9 +74,9 @@ public class CollectionUtilsTests { list.add(Integer.valueOf(3)); CollectionUtils.mergeArrayIntoCollection(arr, list); - assertEquals(Integer.valueOf(3), list.get(0)); - assertEquals(Integer.valueOf(1), list.get(1)); - assertEquals(Integer.valueOf(2), list.get(2)); + assertThat(list.get(0)).isEqualTo(Integer.valueOf(3)); + assertThat(list.get(1)).isEqualTo(Integer.valueOf(1)); + assertThat(list.get(2)).isEqualTo(Integer.valueOf(2)); } @Test @@ -89,30 +87,30 @@ public class CollectionUtilsTests { props.setProperty("prop2", "value2"); props.put("prop3", Integer.valueOf(3)); - Map map = new HashMap<>(); + Map map = new HashMap<>(); map.put("prop4", "value4"); CollectionUtils.mergePropertiesIntoMap(props, map); - assertEquals("value1", map.get("prop1")); - assertEquals("value2", map.get("prop2")); - assertEquals(Integer.valueOf(3), map.get("prop3")); - assertEquals("value4", map.get("prop4")); + assertThat(map.get("prop1")).isEqualTo("value1"); + assertThat(map.get("prop2")).isEqualTo("value2"); + assertThat(map.get("prop3")).isEqualTo(Integer.valueOf(3)); + assertThat(map.get("prop4")).isEqualTo("value4"); } @Test public void testContains() { - assertFalse(CollectionUtils.contains((Iterator) null, "myElement")); - assertFalse(CollectionUtils.contains((Enumeration) null, "myElement")); - assertFalse(CollectionUtils.contains(new LinkedList().iterator(), "myElement")); - assertFalse(CollectionUtils.contains(new Hashtable().keys(), "myElement")); + assertThat(CollectionUtils.contains((Iterator) null, "myElement")).isFalse(); + assertThat(CollectionUtils.contains((Enumeration) null, "myElement")).isFalse(); + assertThat(CollectionUtils.contains(new LinkedList().iterator(), "myElement")).isFalse(); + assertThat(CollectionUtils.contains(new Hashtable().keys(), "myElement")).isFalse(); List list = new LinkedList<>(); list.add("myElement"); - assertTrue(CollectionUtils.contains(list.iterator(), "myElement")); + assertThat(CollectionUtils.contains(list.iterator(), "myElement")).isTrue(); Hashtable ht = new Hashtable<>(); ht.put("myElement", "myValue"); - assertTrue(CollectionUtils.contains(ht.keys(), "myElement")); + assertThat(CollectionUtils.contains(ht.keys(), "myElement")).isTrue(); } @Test @@ -127,25 +125,23 @@ public class CollectionUtilsTests { candidates.add("def"); candidates.add("abc"); - assertTrue(CollectionUtils.containsAny(source, candidates)); + assertThat(CollectionUtils.containsAny(source, candidates)).isTrue(); candidates.remove("def"); - assertTrue(CollectionUtils.containsAny(source, candidates)); + assertThat(CollectionUtils.containsAny(source, candidates)).isTrue(); candidates.remove("abc"); - assertFalse(CollectionUtils.containsAny(source, candidates)); + assertThat(CollectionUtils.containsAny(source, candidates)).isFalse(); } @Test public void testContainsInstanceWithNullCollection() throws Exception { - assertFalse("Must return false if supplied Collection argument is null", - CollectionUtils.containsInstance(null, this)); + assertThat(CollectionUtils.containsInstance(null, this)).as("Must return false if supplied Collection argument is null").isFalse(); } @Test public void testContainsInstanceWithInstancesThatAreEqualButDistinct() throws Exception { List list = new ArrayList<>(); list.add(new Instance("fiona")); - assertFalse("Must return false if instance is not in the supplied Collection argument", - CollectionUtils.containsInstance(list, new Instance("fiona"))); + assertThat(CollectionUtils.containsInstance(list, new Instance("fiona"))).as("Must return false if instance is not in the supplied Collection argument").isFalse(); } @Test @@ -154,8 +150,7 @@ public class CollectionUtilsTests { list.add(new Instance("apple")); Instance instance = new Instance("fiona"); list.add(instance); - assertTrue("Must return true if instance is in the supplied Collection argument", - CollectionUtils.containsInstance(list, instance)); + assertThat(CollectionUtils.containsInstance(list, instance)).as("Must return true if instance is in the supplied Collection argument").isTrue(); } @Test @@ -163,8 +158,7 @@ public class CollectionUtilsTests { List list = new ArrayList<>(); list.add(new Instance("apple")); list.add(new Instance("fiona")); - assertFalse("Must return false if null instance is supplied", - CollectionUtils.containsInstance(list, null)); + assertThat(CollectionUtils.containsInstance(list, null)).as("Must return false if null instance is supplied").isFalse(); } @Test @@ -179,7 +173,7 @@ public class CollectionUtilsTests { candidates.add("def"); candidates.add("abc"); - assertEquals("def", CollectionUtils.findFirstMatch(source, candidates)); + assertThat(CollectionUtils.findFirstMatch(source, candidates)).isEqualTo("def"); } @Test @@ -187,33 +181,33 @@ public class CollectionUtilsTests { List list = new LinkedList<>(); list.add("myElement"); list.add("myOtherElement"); - assertFalse(CollectionUtils.hasUniqueObject(list)); + assertThat(CollectionUtils.hasUniqueObject(list)).isFalse(); list = new LinkedList<>(); list.add("myElement"); - assertTrue(CollectionUtils.hasUniqueObject(list)); + assertThat(CollectionUtils.hasUniqueObject(list)).isTrue(); list = new LinkedList<>(); list.add("myElement"); list.add(null); - assertFalse(CollectionUtils.hasUniqueObject(list)); + assertThat(CollectionUtils.hasUniqueObject(list)).isFalse(); list = new LinkedList<>(); list.add(null); list.add("myElement"); - assertFalse(CollectionUtils.hasUniqueObject(list)); + assertThat(CollectionUtils.hasUniqueObject(list)).isFalse(); list = new LinkedList<>(); list.add(null); list.add(null); - assertTrue(CollectionUtils.hasUniqueObject(list)); + assertThat(CollectionUtils.hasUniqueObject(list)).isTrue(); list = new LinkedList<>(); list.add(null); - assertTrue(CollectionUtils.hasUniqueObject(list)); + assertThat(CollectionUtils.hasUniqueObject(list)).isTrue(); list = new LinkedList<>(); - assertFalse(CollectionUtils.hasUniqueObject(list)); + assertThat(CollectionUtils.hasUniqueObject(list)).isFalse(); } diff --git a/spring-core/src/test/java/org/springframework/util/CompositeIteratorTests.java b/spring-core/src/test/java/org/springframework/util/CompositeIteratorTests.java index 6f519579d77..bf65e2e1936 100644 --- a/spring-core/src/test/java/org/springframework/util/CompositeIteratorTests.java +++ b/spring-core/src/test/java/org/springframework/util/CompositeIteratorTests.java @@ -23,12 +23,10 @@ import java.util.NoSuchElementException; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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; /** @@ -42,7 +40,7 @@ public class CompositeIteratorTests { @Test public void testNoIterators() { CompositeIterator it = new CompositeIterator<>(); - assertFalse(it.hasNext()); + assertThat(it.hasNext()).isFalse(); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy( it::next); } @@ -52,10 +50,10 @@ public class CompositeIteratorTests { CompositeIterator it = new CompositeIterator<>(); it.add(Arrays.asList("0", "1").iterator()); for (int i = 0; i < 2; i++) { - assertTrue(it.hasNext()); - assertEquals(String.valueOf(i), it.next()); + assertThat(it.hasNext()).isTrue(); + assertThat(it.next()).isEqualTo(String.valueOf(i)); } - assertFalse(it.hasNext()); + assertThat(it.hasNext()).isFalse(); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy( it::next); } @@ -67,10 +65,10 @@ public class CompositeIteratorTests { it.add(Arrays.asList("2").iterator()); it.add(Arrays.asList("3", "4").iterator()); for (int i = 0; i < 5; i++) { - assertTrue(it.hasNext()); - assertEquals(String.valueOf(i), it.next()); + assertThat(it.hasNext()).isTrue(); + assertThat(it.next()).isEqualTo(String.valueOf(i)); } - assertFalse(it.hasNext()); + assertThat(it.hasNext()).isFalse(); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy( it::next); diff --git a/spring-core/src/test/java/org/springframework/util/ConcurrentReferenceHashMapTests.java b/spring-core/src/test/java/org/springframework/util/ConcurrentReferenceHashMapTests.java index 76e4e9f6990..b1d47e895f5 100644 --- a/spring-core/src/test/java/org/springframework/util/ConcurrentReferenceHashMapTests.java +++ b/spring-core/src/test/java/org/springframework/util/ConcurrentReferenceHashMapTests.java @@ -41,7 +41,6 @@ import org.springframework.util.comparator.NullSafeComparator; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertFalse; /** * Tests for {@link ConcurrentReferenceHashMap}. @@ -278,7 +277,7 @@ public class ConcurrentReferenceHashMapTests { assertThat(this.map.remove(123, "456")).isFalse(); assertThat(this.map.get(123)).isEqualTo("123"); assertThat(this.map.remove(123, "123")).isTrue(); - assertFalse(this.map.containsKey(123)); + assertThat(this.map.containsKey(123)).isFalse(); assertThat(this.map.isEmpty()).isTrue(); } @@ -288,7 +287,7 @@ public class ConcurrentReferenceHashMapTests { assertThat(this.map.remove(123, "456")).isFalse(); assertThat(this.map.get(123)).isNull(); assertThat(this.map.remove(123, null)).isTrue(); - assertFalse(this.map.containsKey(123)); + assertThat(this.map.containsKey(123)).isFalse(); assertThat(this.map.isEmpty()).isTrue(); } diff --git a/spring-core/src/test/java/org/springframework/util/DigestUtilsTests.java b/spring-core/src/test/java/org/springframework/util/DigestUtilsTests.java index 12a84504abf..dfede80ce95 100644 --- a/spring-core/src/test/java/org/springframework/util/DigestUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/DigestUtilsTests.java @@ -23,8 +23,7 @@ import java.io.UnsupportedEncodingException; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -47,10 +46,10 @@ public class DigestUtilsTests { {-0x4f, 0xa, -0x73, -0x4f, 0x64, -0x20, 0x75, 0x41, 0x5, -0x49, -0x57, -0x65, -0x19, 0x2e, 0x3f, -0x1b}; byte[] result = DigestUtils.md5Digest(bytes); - assertArrayEquals("Invalid hash", expected, result); + assertThat(result).as("Invalid hash").isEqualTo(expected); result = DigestUtils.md5Digest(new ByteArrayInputStream(bytes)); - assertArrayEquals("Invalid hash", expected, result); + assertThat(result).as("Invalid hash").isEqualTo(expected); } @Test @@ -58,10 +57,10 @@ public class DigestUtilsTests { String expected = "b10a8db164e0754105b7a99be72e3fe5"; String hash = DigestUtils.md5DigestAsHex(bytes); - assertEquals("Invalid hash", expected, hash); + assertThat(hash).as("Invalid hash").isEqualTo(expected); hash = DigestUtils.md5DigestAsHex(new ByteArrayInputStream(bytes)); - assertEquals("Invalid hash", expected, hash); + assertThat(hash).as("Invalid hash").isEqualTo(expected); } @Test @@ -70,11 +69,11 @@ public class DigestUtilsTests { StringBuilder builder = new StringBuilder(); DigestUtils.appendMd5DigestAsHex(bytes, builder); - assertEquals("Invalid hash", expected, builder.toString()); + assertThat(builder.toString()).as("Invalid hash").isEqualTo(expected); builder = new StringBuilder(); DigestUtils.appendMd5DigestAsHex(new ByteArrayInputStream(bytes), builder); - assertEquals("Invalid hash", expected, builder.toString()); + assertThat(builder.toString()).as("Invalid hash").isEqualTo(expected); } } diff --git a/spring-core/src/test/java/org/springframework/util/ExceptionTypeFilterTests.java b/spring-core/src/test/java/org/springframework/util/ExceptionTypeFilterTests.java index dfc5dab7aff..815eb60dc20 100644 --- a/spring-core/src/test/java/org/springframework/util/ExceptionTypeFilterTests.java +++ b/spring-core/src/test/java/org/springframework/util/ExceptionTypeFilterTests.java @@ -19,7 +19,7 @@ package org.springframework.util; import org.junit.Test; import static java.util.Arrays.asList; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -30,8 +30,8 @@ public class ExceptionTypeFilterTests { public void subClassMatch() { ExceptionTypeFilter filter = new ExceptionTypeFilter( asList(RuntimeException.class), null, true); - assertTrue(filter.match(RuntimeException.class)); - assertTrue(filter.match(IllegalStateException.class)); + assertThat(filter.match(RuntimeException.class)).isTrue(); + assertThat(filter.match(IllegalStateException.class)).isTrue(); } } diff --git a/spring-core/src/test/java/org/springframework/util/ExponentialBackOffTests.java b/spring-core/src/test/java/org/springframework/util/ExponentialBackOffTests.java index ef2597f6596..3d6455180c5 100644 --- a/spring-core/src/test/java/org/springframework/util/ExponentialBackOffTests.java +++ b/spring-core/src/test/java/org/springframework/util/ExponentialBackOffTests.java @@ -21,8 +21,8 @@ import org.junit.Test; import org.springframework.util.backoff.BackOffExecution; import org.springframework.util.backoff.ExponentialBackOff; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @@ -34,19 +34,19 @@ public class ExponentialBackOffTests { public void defaultInstance() { ExponentialBackOff backOff = new ExponentialBackOff(); BackOffExecution execution = backOff.start(); - assertEquals(2000L, execution.nextBackOff()); - assertEquals(3000L, execution.nextBackOff()); - assertEquals(4500L, execution.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(2000L); + assertThat(execution.nextBackOff()).isEqualTo(3000L); + assertThat(execution.nextBackOff()).isEqualTo(4500L); } @Test public void simpleIncrease() { ExponentialBackOff backOff = new ExponentialBackOff(100L, 2.0); BackOffExecution execution = backOff.start(); - assertEquals(100L, execution.nextBackOff()); - assertEquals(200L, execution.nextBackOff()); - assertEquals(400L, execution.nextBackOff()); - assertEquals(800L, execution.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(100L); + assertThat(execution.nextBackOff()).isEqualTo(200L); + assertThat(execution.nextBackOff()).isEqualTo(400L); + assertThat(execution.nextBackOff()).isEqualTo(800L); } @Test @@ -55,10 +55,10 @@ public class ExponentialBackOffTests { backOff.setMaxElapsedTime(300L); BackOffExecution execution = backOff.start(); - assertEquals(100L, execution.nextBackOff()); - assertEquals(100L, execution.nextBackOff()); - assertEquals(100L, execution.nextBackOff()); - assertEquals(BackOffExecution.STOP, execution.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(100L); + assertThat(execution.nextBackOff()).isEqualTo(100L); + assertThat(execution.nextBackOff()).isEqualTo(100L); + assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP); } @Test @@ -67,10 +67,11 @@ public class ExponentialBackOffTests { backOff.setMaxInterval(4000L); BackOffExecution execution = backOff.start(); - assertEquals(2000L, execution.nextBackOff()); - assertEquals(4000L, execution.nextBackOff()); - assertEquals(4000L, execution.nextBackOff()); // max reached - assertEquals(4000L, execution.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(2000L); + assertThat(execution.nextBackOff()).isEqualTo(4000L); + // max reached + assertThat(execution.nextBackOff()).isEqualTo(4000L); + assertThat(execution.nextBackOff()).isEqualTo(4000L); } @Test @@ -79,9 +80,10 @@ public class ExponentialBackOffTests { backOff.setMaxElapsedTime(4000L); BackOffExecution execution = backOff.start(); - assertEquals(2000L, execution.nextBackOff()); - assertEquals(4000L, execution.nextBackOff()); - assertEquals(BackOffExecution.STOP, execution.nextBackOff()); // > 4 sec wait in total + assertThat(execution.nextBackOff()).isEqualTo(2000L); + assertThat(execution.nextBackOff()).isEqualTo(4000L); + // > 4 sec wait in total + assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP); } @Test @@ -94,12 +96,12 @@ public class ExponentialBackOffTests { BackOffExecution execution = backOff.start(); BackOffExecution execution2 = backOff.start(); - assertEquals(2000L, execution.nextBackOff()); - assertEquals(2000L, execution2.nextBackOff()); - assertEquals(4000L, execution.nextBackOff()); - assertEquals(4000L, execution2.nextBackOff()); - assertEquals(BackOffExecution.STOP, execution.nextBackOff()); - assertEquals(BackOffExecution.STOP, execution2.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(2000L); + assertThat(execution2.nextBackOff()).isEqualTo(2000L); + assertThat(execution.nextBackOff()).isEqualTo(4000L); + assertThat(execution2.nextBackOff()).isEqualTo(4000L); + assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP); + assertThat(execution2.nextBackOff()).isEqualTo(BackOffExecution.STOP); } @Test @@ -115,19 +117,19 @@ public class ExponentialBackOffTests { backOff.setMaxInterval(50L); BackOffExecution execution = backOff.start(); - assertEquals(50L, execution.nextBackOff()); - assertEquals(50L, execution.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(50L); + assertThat(execution.nextBackOff()).isEqualTo(50L); } @Test public void toStringContent() { ExponentialBackOff backOff = new ExponentialBackOff(2000L, 2.0); BackOffExecution execution = backOff.start(); - assertEquals("ExponentialBackOff{currentInterval=n/a, multiplier=2.0}", execution.toString()); + assertThat(execution.toString()).isEqualTo("ExponentialBackOff{currentInterval=n/a, multiplier=2.0}"); execution.nextBackOff(); - assertEquals("ExponentialBackOff{currentInterval=2000ms, multiplier=2.0}", execution.toString()); + assertThat(execution.toString()).isEqualTo("ExponentialBackOff{currentInterval=2000ms, multiplier=2.0}"); execution.nextBackOff(); - assertEquals("ExponentialBackOff{currentInterval=4000ms, multiplier=2.0}", execution.toString()); + assertThat(execution.toString()).isEqualTo("ExponentialBackOff{currentInterval=4000ms, multiplier=2.0}"); } } diff --git a/spring-core/src/test/java/org/springframework/util/FastByteArrayOutputStreamTests.java b/spring-core/src/test/java/org/springframework/util/FastByteArrayOutputStreamTests.java index 295d0e4e2cc..4b3a0192ab6 100644 --- a/spring-core/src/test/java/org/springframework/util/FastByteArrayOutputStreamTests.java +++ b/spring-core/src/test/java/org/springframework/util/FastByteArrayOutputStreamTests.java @@ -24,12 +24,9 @@ import java.nio.charset.StandardCharsets; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIOException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; /** * Test suite for {@link FastByteArrayOutputStream}. @@ -48,7 +45,7 @@ public class FastByteArrayOutputStreamTests { @Test public void size() throws Exception { this.os.write(this.helloBytes); - assertEquals(this.os.size(), this.helloBytes.length); + assertThat(this.helloBytes.length).isEqualTo(this.os.size()); } @Test @@ -57,7 +54,7 @@ public class FastByteArrayOutputStreamTests { int sizeBefore = this.os.size(); this.os.resize(64); assertByteArrayEqualsString(this.os); - assertEquals(sizeBefore, this.os.size()); + assertThat(this.os.size()).isEqualTo(sizeBefore); } @Test @@ -66,8 +63,8 @@ public class FastByteArrayOutputStreamTests { for (int i = 0; i < 10; i++) { this.os.write(1); } - assertEquals(10, this.os.size()); - assertArrayEquals(this.os.toByteArray(), new byte[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}); + assertThat(this.os.size()).isEqualTo(10); + assertThat(new byte[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}).isEqualTo(this.os.toByteArray()); } @Test @@ -81,7 +78,7 @@ public class FastByteArrayOutputStreamTests { this.os.write(this.helloBytes); assertByteArrayEqualsString(this.os); this.os.reset(); - assertEquals(0, this.os.size()); + assertThat(this.os.size()).isEqualTo(0); this.os.write(this.helloBytes); assertByteArrayEqualsString(this.os); } @@ -97,8 +94,8 @@ public class FastByteArrayOutputStreamTests { public void toByteArrayUnsafe() throws Exception { this.os.write(this.helloBytes); assertByteArrayEqualsString(this.os); - assertSame(this.os.toByteArrayUnsafe(), this.os.toByteArrayUnsafe()); - assertArrayEquals(this.os.toByteArray(), this.helloBytes); + assertThat(this.os.toByteArrayUnsafe()).isSameAs(this.os.toByteArrayUnsafe()); + assertThat(this.helloBytes).isEqualTo(this.os.toByteArray()); } @Test @@ -107,7 +104,7 @@ public class FastByteArrayOutputStreamTests { assertByteArrayEqualsString(this.os); ByteArrayOutputStream baos = new ByteArrayOutputStream(); this.os.writeTo(baos); - assertArrayEquals(baos.toByteArray(), this.helloBytes); + assertThat(this.helloBytes).isEqualTo(baos.toByteArray()); } @Test @@ -120,23 +117,23 @@ public class FastByteArrayOutputStreamTests { @Test public void getInputStream() throws Exception { this.os.write(this.helloBytes); - assertNotNull(this.os.getInputStream()); + assertThat(this.os.getInputStream()).isNotNull(); } @Test public void getInputStreamAvailable() throws Exception { this.os.write(this.helloBytes); - assertEquals(this.os.getInputStream().available(), this.helloBytes.length); + assertThat(this.helloBytes.length).isEqualTo(this.os.getInputStream().available()); } @Test public void getInputStreamRead() throws Exception { this.os.write(this.helloBytes); InputStream inputStream = this.os.getInputStream(); - assertEquals(inputStream.read(), this.helloBytes[0]); - assertEquals(inputStream.read(), this.helloBytes[1]); - assertEquals(inputStream.read(), this.helloBytes[2]); - assertEquals(inputStream.read(), this.helloBytes[3]); + assertThat(this.helloBytes[0]).isEqualTo((byte) inputStream.read()); + assertThat(this.helloBytes[1]).isEqualTo((byte) inputStream.read()); + assertThat(this.helloBytes[2]).isEqualTo((byte) inputStream.read()); + assertThat(this.helloBytes[3]).isEqualTo((byte) inputStream.read()); } @Test @@ -145,7 +142,7 @@ public class FastByteArrayOutputStreamTests { this.os.write(bytes); InputStream inputStream = this.os.getInputStream(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - assertEquals(bais.read(), inputStream.read()); + assertThat(inputStream.read()).isEqualTo(bais.read()); } @Test @@ -154,9 +151,9 @@ public class FastByteArrayOutputStreamTests { InputStream inputStream = this.os.getInputStream(); byte[] actual = new byte[inputStream.available()]; int bytesRead = inputStream.read(actual); - assertEquals(this.helloBytes.length, bytesRead); - assertArrayEquals(this.helloBytes, actual); - assertEquals(0, inputStream.available()); + assertThat(bytesRead).isEqualTo(this.helloBytes.length); + assertThat(actual).isEqualTo(this.helloBytes); + assertThat(inputStream.available()).isEqualTo(0); } @Test @@ -165,30 +162,30 @@ public class FastByteArrayOutputStreamTests { InputStream inputStream = os.getInputStream(); byte[] actual = new byte[inputStream.available() + 1]; int bytesRead = inputStream.read(actual); - assertEquals(this.helloBytes.length, bytesRead); + assertThat(bytesRead).isEqualTo(this.helloBytes.length); for (int i = 0; i < bytesRead; i++) { - assertEquals(this.helloBytes[i], actual[i]); + assertThat(actual[i]).isEqualTo(this.helloBytes[i]); } - assertEquals(0, actual[this.helloBytes.length]); - assertEquals(0, inputStream.available()); + assertThat(actual[this.helloBytes.length]).isEqualTo((byte) 0); + assertThat(inputStream.available()).isEqualTo(0); } @Test public void getInputStreamSkip() throws Exception { this.os.write(this.helloBytes); InputStream inputStream = this.os.getInputStream(); - assertEquals(inputStream.read(), this.helloBytes[0]); - assertEquals(1, inputStream.skip(1)); - assertEquals(inputStream.read(), this.helloBytes[2]); - assertEquals(this.helloBytes.length - 3, inputStream.available()); + assertThat(this.helloBytes[0]).isEqualTo((byte) inputStream.read()); + assertThat(inputStream.skip(1)).isEqualTo(1); + assertThat(this.helloBytes[2]).isEqualTo((byte) inputStream.read()); + assertThat(inputStream.available()).isEqualTo((this.helloBytes.length - 3)); } @Test public void getInputStreamSkipAll() throws Exception { this.os.write(this.helloBytes); InputStream inputStream = this.os.getInputStream(); - assertEquals(inputStream.skip(1000), this.helloBytes.length); - assertEquals(0, inputStream.available()); + assertThat(this.helloBytes.length).isEqualTo(inputStream.skip(1000)); + assertThat(inputStream.available()).isEqualTo(0); } @Test @@ -199,7 +196,7 @@ public class FastByteArrayOutputStreamTests { DigestUtils.appendMd5DigestAsHex(inputStream, builder); builder.append("\""); String actual = builder.toString(); - assertEquals("\"0b10a8db164e0754105b7a99be72e3fe5\"", actual); + assertThat(actual).isEqualTo("\"0b10a8db164e0754105b7a99be72e3fe5\""); } @Test @@ -213,12 +210,12 @@ public class FastByteArrayOutputStreamTests { DigestUtils.appendMd5DigestAsHex(inputStream, builder); builder.append("\""); String actual = builder.toString(); - assertEquals("\"06225ca1e4533354c516e74512065331d\"", actual); + assertThat(actual).isEqualTo("\"06225ca1e4533354c516e74512065331d\""); } private void assertByteArrayEqualsString(FastByteArrayOutputStream actual) { - assertArrayEquals(this.helloBytes, actual.toByteArray()); + assertThat(actual.toByteArray()).isEqualTo(this.helloBytes); } } diff --git a/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java b/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java index 85f58222f1a..5a0e5e317cc 100644 --- a/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java @@ -25,8 +25,7 @@ import java.util.Arrays; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for the FileCopyUtils class. @@ -42,8 +41,8 @@ public class FileCopyUtilsTests { ByteArrayInputStream in = new ByteArrayInputStream(content); ByteArrayOutputStream out = new ByteArrayOutputStream(content.length); int count = FileCopyUtils.copy(in, out); - assertEquals(content.length, count); - assertTrue(Arrays.equals(content, out.toByteArray())); + assertThat(count).isEqualTo(content.length); + assertThat(Arrays.equals(content, out.toByteArray())).isTrue(); } @Test @@ -51,7 +50,7 @@ public class FileCopyUtilsTests { byte[] content = "content".getBytes(); ByteArrayOutputStream out = new ByteArrayOutputStream(content.length); FileCopyUtils.copy(content, out); - assertTrue(Arrays.equals(content, out.toByteArray())); + assertThat(Arrays.equals(content, out.toByteArray())).isTrue(); } @Test @@ -59,7 +58,7 @@ public class FileCopyUtilsTests { byte[] content = "content".getBytes(); ByteArrayInputStream in = new ByteArrayInputStream(content); byte[] result = FileCopyUtils.copyToByteArray(in); - assertTrue(Arrays.equals(content, result)); + assertThat(Arrays.equals(content, result)).isTrue(); } @Test @@ -68,8 +67,8 @@ public class FileCopyUtilsTests { StringReader in = new StringReader(content); StringWriter out = new StringWriter(); int count = FileCopyUtils.copy(in, out); - assertEquals(content.length(), count); - assertEquals(content, out.toString()); + assertThat(count).isEqualTo(content.length()); + assertThat(out.toString()).isEqualTo(content); } @Test @@ -77,7 +76,7 @@ public class FileCopyUtilsTests { String content = "content"; StringWriter out = new StringWriter(); FileCopyUtils.copy(content, out); - assertEquals(content, out.toString()); + assertThat(out.toString()).isEqualTo(content); } @Test @@ -85,7 +84,7 @@ public class FileCopyUtilsTests { String content = "content"; StringReader in = new StringReader(content); String result = FileCopyUtils.copyToString(in); - assertEquals(content, result); + assertThat(result).isEqualTo(content); } } diff --git a/spring-core/src/test/java/org/springframework/util/FileSystemUtilsTests.java b/spring-core/src/test/java/org/springframework/util/FileSystemUtilsTests.java index 49f69e5584b..7b5707755db 100644 --- a/spring-core/src/test/java/org/springframework/util/FileSystemUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/FileSystemUtilsTests.java @@ -21,8 +21,7 @@ import java.io.File; import org.junit.After; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -40,17 +39,17 @@ public class FileSystemUtilsTests { File bar = new File(child, "bar.txt"); bar.createNewFile(); - assertTrue(root.exists()); - assertTrue(child.exists()); - assertTrue(grandchild.exists()); - assertTrue(bar.exists()); + assertThat(root.exists()).isTrue(); + assertThat(child.exists()).isTrue(); + assertThat(grandchild.exists()).isTrue(); + assertThat(bar.exists()).isTrue(); FileSystemUtils.deleteRecursively(root); - assertFalse(root.exists()); - assertFalse(child.exists()); - assertFalse(grandchild.exists()); - assertFalse(bar.exists()); + assertThat(root.exists()).isFalse(); + assertThat(child.exists()).isFalse(); + assertThat(grandchild.exists()).isFalse(); + assertThat(bar.exists()).isFalse(); } @Test @@ -64,19 +63,19 @@ public class FileSystemUtilsTests { File bar = new File(child, "bar.txt"); bar.createNewFile(); - assertTrue(src.exists()); - assertTrue(child.exists()); - assertTrue(grandchild.exists()); - assertTrue(bar.exists()); + assertThat(src.exists()).isTrue(); + assertThat(child.exists()).isTrue(); + assertThat(grandchild.exists()).isTrue(); + assertThat(bar.exists()).isTrue(); File dest = new File("./dest"); FileSystemUtils.copyRecursively(src, dest); - assertTrue(dest.exists()); - assertTrue(new File(dest, child.getName()).exists()); + assertThat(dest.exists()).isTrue(); + assertThat(new File(dest, child.getName()).exists()).isTrue(); FileSystemUtils.deleteRecursively(src); - assertFalse(src.exists()); + assertThat(src.exists()).isFalse(); } diff --git a/spring-core/src/test/java/org/springframework/util/FixedBackOffTests.java b/spring-core/src/test/java/org/springframework/util/FixedBackOffTests.java index b9e0aab6d5a..85f12ff40de 100644 --- a/spring-core/src/test/java/org/springframework/util/FixedBackOffTests.java +++ b/spring-core/src/test/java/org/springframework/util/FixedBackOffTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.util.backoff.BackOffExecution; import org.springframework.util.backoff.FixedBackOff; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -33,7 +33,7 @@ public class FixedBackOffTests { FixedBackOff backOff = new FixedBackOff(); BackOffExecution execution = backOff.start(); for (int i = 0; i < 100; i++) { - assertEquals(FixedBackOff.DEFAULT_INTERVAL, execution.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(FixedBackOff.DEFAULT_INTERVAL); } } @@ -41,16 +41,16 @@ public class FixedBackOffTests { public void noAttemptAtAll() { FixedBackOff backOff = new FixedBackOff(100L, 0L); BackOffExecution execution = backOff.start(); - assertEquals(BackOffExecution.STOP, execution.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP); } @Test public void maxAttemptsReached() { FixedBackOff backOff = new FixedBackOff(200L, 2); BackOffExecution execution = backOff.start(); - assertEquals(200L, execution.nextBackOff()); - assertEquals(200L, execution.nextBackOff()); - assertEquals(BackOffExecution.STOP, execution.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(200L); + assertThat(execution.nextBackOff()).isEqualTo(200L); + assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP); } @Test @@ -59,34 +59,34 @@ public class FixedBackOffTests { BackOffExecution execution = backOff.start(); BackOffExecution execution2 = backOff.start(); - assertEquals(100L, execution.nextBackOff()); - assertEquals(100L, execution2.nextBackOff()); - assertEquals(BackOffExecution.STOP, execution.nextBackOff()); - assertEquals(BackOffExecution.STOP, execution2.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(100L); + assertThat(execution2.nextBackOff()).isEqualTo(100L); + assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP); + assertThat(execution2.nextBackOff()).isEqualTo(BackOffExecution.STOP); } @Test public void liveUpdate() { FixedBackOff backOff = new FixedBackOff(100L, 1); BackOffExecution execution = backOff.start(); - assertEquals(100L, execution.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(100L); backOff.setInterval(200L); backOff.setMaxAttempts(2); - assertEquals(200L, execution.nextBackOff()); - assertEquals(BackOffExecution.STOP, execution.nextBackOff()); + assertThat(execution.nextBackOff()).isEqualTo(200L); + assertThat(execution.nextBackOff()).isEqualTo(BackOffExecution.STOP); } @Test public void toStringContent() { FixedBackOff backOff = new FixedBackOff(200L, 10); BackOffExecution execution = backOff.start(); - assertEquals("FixedBackOff{interval=200, currentAttempts=0, maxAttempts=10}", execution.toString()); + assertThat(execution.toString()).isEqualTo("FixedBackOff{interval=200, currentAttempts=0, maxAttempts=10}"); execution.nextBackOff(); - assertEquals("FixedBackOff{interval=200, currentAttempts=1, maxAttempts=10}", execution.toString()); + assertThat(execution.toString()).isEqualTo("FixedBackOff{interval=200, currentAttempts=1, maxAttempts=10}"); execution.nextBackOff(); - assertEquals("FixedBackOff{interval=200, currentAttempts=2, maxAttempts=10}", execution.toString()); + assertThat(execution.toString()).isEqualTo("FixedBackOff{interval=200, currentAttempts=2, maxAttempts=10}"); } } diff --git a/spring-core/src/test/java/org/springframework/util/InstanceFilterTests.java b/spring-core/src/test/java/org/springframework/util/InstanceFilterTests.java index 076919f4dc7..112670672f3 100644 --- a/spring-core/src/test/java/org/springframework/util/InstanceFilterTests.java +++ b/spring-core/src/test/java/org/springframework/util/InstanceFilterTests.java @@ -19,8 +19,7 @@ package org.springframework.util; import org.junit.Test; import static java.util.Arrays.asList; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -66,11 +65,11 @@ public class InstanceFilterTests { } private void match(InstanceFilter filter, T candidate) { - assertTrue("filter '" + filter + "' should match " + candidate, filter.match(candidate)); + assertThat(filter.match(candidate)).as("filter '" + filter + "' should match " + candidate).isTrue(); } private void doNotMatch(InstanceFilter filter, T candidate) { - assertFalse("filter '" + filter + "' should not match " + candidate, filter.match(candidate)); + assertThat(filter.match(candidate)).as("filter '" + filter + "' should not match " + candidate).isFalse(); } } diff --git a/spring-core/src/test/java/org/springframework/util/LinkedCaseInsensitiveMapTests.java b/spring-core/src/test/java/org/springframework/util/LinkedCaseInsensitiveMapTests.java index 7a49f75ae0f..092142b34ef 100644 --- a/spring-core/src/test/java/org/springframework/util/LinkedCaseInsensitiveMapTests.java +++ b/spring-core/src/test/java/org/springframework/util/LinkedCaseInsensitiveMapTests.java @@ -20,9 +20,7 @@ import java.util.Iterator; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link LinkedCaseInsensitiveMap}. @@ -37,101 +35,101 @@ public class LinkedCaseInsensitiveMapTests { @Test public void putAndGet() { - assertNull(map.put("key", "value1")); - assertEquals("value1", map.put("key", "value2")); - assertEquals("value2", map.put("key", "value3")); - assertEquals(1, map.size()); - assertEquals("value3", map.get("key")); - assertEquals("value3", map.get("KEY")); - assertEquals("value3", map.get("Key")); - assertTrue(map.containsKey("key")); - assertTrue(map.containsKey("KEY")); - assertTrue(map.containsKey("Key")); - assertTrue(map.keySet().contains("key")); - assertTrue(map.keySet().contains("KEY")); - assertTrue(map.keySet().contains("Key")); + assertThat(map.put("key", "value1")).isNull(); + assertThat(map.put("key", "value2")).isEqualTo("value1"); + assertThat(map.put("key", "value3")).isEqualTo("value2"); + assertThat(map.size()).isEqualTo(1); + assertThat(map.get("key")).isEqualTo("value3"); + assertThat(map.get("KEY")).isEqualTo("value3"); + assertThat(map.get("Key")).isEqualTo("value3"); + assertThat(map.containsKey("key")).isTrue(); + assertThat(map.containsKey("KEY")).isTrue(); + assertThat(map.containsKey("Key")).isTrue(); + assertThat(map.keySet().contains("key")).isTrue(); + assertThat(map.keySet().contains("KEY")).isTrue(); + assertThat(map.keySet().contains("Key")).isTrue(); } @Test public void putWithOverlappingKeys() { - assertNull(map.put("key", "value1")); - assertEquals("value1", map.put("KEY", "value2")); - assertEquals("value2", map.put("Key", "value3")); - assertEquals(1, map.size()); - assertEquals("value3", map.get("key")); - assertEquals("value3", map.get("KEY")); - assertEquals("value3", map.get("Key")); - assertTrue(map.containsKey("key")); - assertTrue(map.containsKey("KEY")); - assertTrue(map.containsKey("Key")); - assertTrue(map.keySet().contains("key")); - assertTrue(map.keySet().contains("KEY")); - assertTrue(map.keySet().contains("Key")); + assertThat(map.put("key", "value1")).isNull(); + assertThat(map.put("KEY", "value2")).isEqualTo("value1"); + assertThat(map.put("Key", "value3")).isEqualTo("value2"); + assertThat(map.size()).isEqualTo(1); + assertThat(map.get("key")).isEqualTo("value3"); + assertThat(map.get("KEY")).isEqualTo("value3"); + assertThat(map.get("Key")).isEqualTo("value3"); + assertThat(map.containsKey("key")).isTrue(); + assertThat(map.containsKey("KEY")).isTrue(); + assertThat(map.containsKey("Key")).isTrue(); + assertThat(map.keySet().contains("key")).isTrue(); + assertThat(map.keySet().contains("KEY")).isTrue(); + assertThat(map.keySet().contains("Key")).isTrue(); } @Test public void getOrDefault() { - assertNull(map.put("key", "value1")); - assertEquals("value1", map.put("KEY", "value2")); - assertEquals("value2", map.put("Key", "value3")); - assertEquals("value3", map.getOrDefault("key", "N")); - assertEquals("value3", map.getOrDefault("KEY", "N")); - assertEquals("value3", map.getOrDefault("Key", "N")); - assertEquals("N", map.getOrDefault("keeeey", "N")); - assertEquals("N", map.getOrDefault(new Object(), "N")); + assertThat(map.put("key", "value1")).isNull(); + assertThat(map.put("KEY", "value2")).isEqualTo("value1"); + assertThat(map.put("Key", "value3")).isEqualTo("value2"); + assertThat(map.getOrDefault("key", "N")).isEqualTo("value3"); + assertThat(map.getOrDefault("KEY", "N")).isEqualTo("value3"); + assertThat(map.getOrDefault("Key", "N")).isEqualTo("value3"); + assertThat(map.getOrDefault("keeeey", "N")).isEqualTo("N"); + assertThat(map.getOrDefault(new Object(), "N")).isEqualTo("N"); } @Test public void getOrDefaultWithNullValue() { - assertNull(map.put("key", null)); - assertNull(map.put("KEY", null)); - assertNull(map.put("Key", null)); - assertNull(map.getOrDefault("key", "N")); - assertNull(map.getOrDefault("KEY", "N")); - assertNull(map.getOrDefault("Key", "N")); - assertEquals("N", map.getOrDefault("keeeey", "N")); - assertEquals("N", map.getOrDefault(new Object(), "N")); + assertThat(map.put("key", null)).isNull(); + assertThat(map.put("KEY", null)).isNull(); + assertThat(map.put("Key", null)).isNull(); + assertThat(map.getOrDefault("key", "N")).isNull(); + assertThat(map.getOrDefault("KEY", "N")).isNull(); + assertThat(map.getOrDefault("Key", "N")).isNull(); + assertThat(map.getOrDefault("keeeey", "N")).isEqualTo("N"); + assertThat(map.getOrDefault(new Object(), "N")).isEqualTo("N"); } @Test public void computeIfAbsentWithExistingValue() { - assertNull(map.putIfAbsent("key", "value1")); - assertEquals("value1", map.putIfAbsent("KEY", "value2")); - assertEquals("value1", map.put("Key", "value3")); - assertEquals("value3", map.computeIfAbsent("key", key -> "value1")); - assertEquals("value3", map.computeIfAbsent("KEY", key -> "value2")); - assertEquals("value3", map.computeIfAbsent("Key", key -> "value3")); + assertThat(map.putIfAbsent("key", "value1")).isNull(); + assertThat(map.putIfAbsent("KEY", "value2")).isEqualTo("value1"); + assertThat(map.put("Key", "value3")).isEqualTo("value1"); + assertThat(map.computeIfAbsent("key", key2 -> "value1")).isEqualTo("value3"); + assertThat(map.computeIfAbsent("KEY", key1 -> "value2")).isEqualTo("value3"); + assertThat(map.computeIfAbsent("Key", key -> "value3")).isEqualTo("value3"); } @Test public void computeIfAbsentWithComputedValue() { - assertEquals("value1", map.computeIfAbsent("key", key -> "value1")); - assertEquals("value1", map.computeIfAbsent("KEY", key -> "value2")); - assertEquals("value1", map.computeIfAbsent("Key", key -> "value3")); + assertThat(map.computeIfAbsent("key", key2 -> "value1")).isEqualTo("value1"); + assertThat(map.computeIfAbsent("KEY", key1 -> "value2")).isEqualTo("value1"); + assertThat(map.computeIfAbsent("Key", key -> "value3")).isEqualTo("value1"); } @Test public void mapClone() { - assertNull(map.put("key", "value1")); + assertThat(map.put("key", "value1")).isNull(); LinkedCaseInsensitiveMap copy = map.clone(); - assertEquals(map.getLocale(), copy.getLocale()); - assertEquals("value1", map.get("key")); - assertEquals("value1", map.get("KEY")); - assertEquals("value1", map.get("Key")); - assertEquals("value1", copy.get("key")); - assertEquals("value1", copy.get("KEY")); - assertEquals("value1", copy.get("Key")); + assertThat(copy.getLocale()).isEqualTo(map.getLocale()); + assertThat(map.get("key")).isEqualTo("value1"); + assertThat(map.get("KEY")).isEqualTo("value1"); + assertThat(map.get("Key")).isEqualTo("value1"); + assertThat(copy.get("key")).isEqualTo("value1"); + assertThat(copy.get("KEY")).isEqualTo("value1"); + assertThat(copy.get("Key")).isEqualTo("value1"); copy.put("Key", "value2"); - assertEquals(1, map.size()); - assertEquals(1, copy.size()); - assertEquals("value1", map.get("key")); - assertEquals("value1", map.get("KEY")); - assertEquals("value1", map.get("Key")); - assertEquals("value2", copy.get("key")); - assertEquals("value2", copy.get("KEY")); - assertEquals("value2", copy.get("Key")); + assertThat(map.size()).isEqualTo(1); + assertThat(copy.size()).isEqualTo(1); + assertThat(map.get("key")).isEqualTo("value1"); + assertThat(map.get("KEY")).isEqualTo("value1"); + assertThat(map.get("Key")).isEqualTo("value1"); + assertThat(copy.get("key")).isEqualTo("value2"); + assertThat(copy.get("KEY")).isEqualTo("value2"); + assertThat(copy.get("Key")).isEqualTo("value2"); } @@ -140,7 +138,7 @@ public class LinkedCaseInsensitiveMapTests { map.put("key", "value"); map.keySet().clear(); map.computeIfAbsent("key", k -> "newvalue"); - assertEquals("newvalue", map.get("key")); + assertThat(map.get("key")).isEqualTo("newvalue"); } @Test @@ -148,70 +146,70 @@ public class LinkedCaseInsensitiveMapTests { map.put("key", "value"); map.keySet().remove("key"); map.computeIfAbsent("key", k -> "newvalue"); - assertEquals("newvalue", map.get("key")); + assertThat(map.get("key")).isEqualTo("newvalue"); } @Test public void removeFromKeySetViaIterator() { map.put("key", "value"); nextAndRemove(map.keySet().iterator()); - assertEquals(0, map.size()); + assertThat(map.size()).isEqualTo(0); map.computeIfAbsent("key", k -> "newvalue"); - assertEquals("newvalue", map.get("key")); + assertThat(map.get("key")).isEqualTo("newvalue"); } @Test public void clearFromValues() { map.put("key", "value"); map.values().clear(); - assertEquals(0, map.size()); + assertThat(map.size()).isEqualTo(0); map.computeIfAbsent("key", k -> "newvalue"); - assertEquals("newvalue", map.get("key")); + assertThat(map.get("key")).isEqualTo("newvalue"); } @Test public void removeFromValues() { map.put("key", "value"); map.values().remove("value"); - assertEquals(0, map.size()); + assertThat(map.size()).isEqualTo(0); map.computeIfAbsent("key", k -> "newvalue"); - assertEquals("newvalue", map.get("key")); + assertThat(map.get("key")).isEqualTo("newvalue"); } @Test public void removeFromValuesViaIterator() { map.put("key", "value"); nextAndRemove(map.values().iterator()); - assertEquals(0, map.size()); + assertThat(map.size()).isEqualTo(0); map.computeIfAbsent("key", k -> "newvalue"); - assertEquals("newvalue", map.get("key")); + assertThat(map.get("key")).isEqualTo("newvalue"); } @Test public void clearFromEntrySet() { map.put("key", "value"); map.entrySet().clear(); - assertEquals(0, map.size()); + assertThat(map.size()).isEqualTo(0); map.computeIfAbsent("key", k -> "newvalue"); - assertEquals("newvalue", map.get("key")); + assertThat(map.get("key")).isEqualTo("newvalue"); } @Test public void removeFromEntrySet() { map.put("key", "value"); map.entrySet().remove(map.entrySet().iterator().next()); - assertEquals(0, map.size()); + assertThat(map.size()).isEqualTo(0); map.computeIfAbsent("key", k -> "newvalue"); - assertEquals("newvalue", map.get("key")); + assertThat(map.get("key")).isEqualTo("newvalue"); } @Test public void removeFromEntrySetViaIterator() { map.put("key", "value"); nextAndRemove(map.entrySet().iterator()); - assertEquals(0, map.size()); + assertThat(map.size()).isEqualTo(0); map.computeIfAbsent("key", k -> "newvalue"); - assertEquals("newvalue", map.get("key")); + assertThat(map.get("key")).isEqualTo("newvalue"); } private void nextAndRemove(Iterator iterator) { diff --git a/spring-core/src/test/java/org/springframework/util/LinkedMultiValueMapTests.java b/spring-core/src/test/java/org/springframework/util/LinkedMultiValueMapTests.java index e8adbe03363..97c484835fd 100644 --- a/spring-core/src/test/java/org/springframework/util/LinkedMultiValueMapTests.java +++ b/spring-core/src/test/java/org/springframework/util/LinkedMultiValueMapTests.java @@ -25,8 +25,7 @@ import java.util.Map; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -41,39 +40,39 @@ public class LinkedMultiValueMapTests { public void add() { map.add("key", "value1"); map.add("key", "value2"); - assertEquals(1, map.size()); + assertThat(map.size()).isEqualTo(1); List expected = new ArrayList<>(2); expected.add("value1"); expected.add("value2"); - assertEquals(expected, map.get("key")); + assertThat(map.get("key")).isEqualTo(expected); } @Test public void set() { map.set("key", "value1"); map.set("key", "value2"); - assertEquals(1, map.size()); - assertEquals(Collections.singletonList("value2"), map.get("key")); + assertThat(map.size()).isEqualTo(1); + assertThat(map.get("key")).isEqualTo(Collections.singletonList("value2")); } @Test public void addAll() { map.add("key", "value1"); map.addAll("key", Arrays.asList("value2", "value3")); - assertEquals(1, map.size()); + assertThat(map.size()).isEqualTo(1); List expected = new ArrayList<>(2); expected.add("value1"); expected.add("value2"); expected.add("value3"); - assertEquals(expected, map.get("key")); + assertThat(map.get("key")).isEqualTo(expected); } @Test public void addAllWithEmptyList() { map.addAll("key", Collections.emptyList()); - assertEquals(1, map.size()); - assertEquals(Collections.emptyList(), map.get("key")); - assertNull(map.getFirst("key")); + assertThat(map.size()).isEqualTo(1); + assertThat(map.get("key")).isEqualTo(Collections.emptyList()); + assertThat(map.getFirst("key")).isNull(); } @Test @@ -82,15 +81,15 @@ public class LinkedMultiValueMapTests { values.add("value1"); values.add("value2"); map.put("key", values); - assertEquals("value1", map.getFirst("key")); - assertNull(map.getFirst("other")); + assertThat(map.getFirst("key")).isEqualTo("value1"); + assertThat(map.getFirst("other")).isNull(); } @Test public void getFirstWithEmptyList() { map.put("key", Collections.emptyList()); - assertNull(map.getFirst("key")); - assertNull(map.getFirst("other")); + assertThat(map.getFirst("key")).isNull(); + assertThat(map.getFirst("other")).isNull(); } @Test @@ -100,30 +99,30 @@ public class LinkedMultiValueMapTests { values.add("value2"); map.put("key", values); Map svm = map.toSingleValueMap(); - assertEquals(1, svm.size()); - assertEquals("value1", svm.get("key")); + assertThat(svm.size()).isEqualTo(1); + assertThat(svm.get("key")).isEqualTo("value1"); } @Test public void toSingleValueMapWithEmptyList() { map.put("key", Collections.emptyList()); Map svm = map.toSingleValueMap(); - assertEquals(0, svm.size()); - assertNull(svm.get("key")); + assertThat(svm.size()).isEqualTo(0); + assertThat(svm.get("key")).isNull(); } @Test public void equals() { map.set("key1", "value1"); - assertEquals(map, map); + assertThat(map).isEqualTo(map); MultiValueMap o1 = new LinkedMultiValueMap<>(); o1.set("key1", "value1"); - assertEquals(map, o1); - assertEquals(o1, map); + assertThat(o1).isEqualTo(map); + assertThat(map).isEqualTo(o1); Map> o2 = new HashMap<>(); o2.put("key1", Collections.singletonList("value1")); - assertEquals(map, o2); - assertEquals(o2, map); + assertThat(o2).isEqualTo(map); + assertThat(map).isEqualTo(o2); } } diff --git a/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java b/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java index 3e72f8b94c5..463b968a1b5 100644 --- a/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java +++ b/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java @@ -22,8 +22,8 @@ import java.util.List; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Colin Sampaleanu @@ -42,7 +42,7 @@ public class MethodInvokerTests { mi.setTargetMethod("method1"); mi.prepare(); Integer i = (Integer) mi.invoke(); - assertEquals(1, i.intValue()); + assertThat(i.intValue()).isEqualTo(1); // defensive check: singleton, non-static should work with null array tc1 = new TestClass1(); @@ -52,7 +52,7 @@ public class MethodInvokerTests { mi.setArguments((Object[]) null); mi.prepare(); i = (Integer) mi.invoke(); - assertEquals(1, i.intValue()); + assertThat(i.intValue()).isEqualTo(1); // sanity check: check that argument count matching works mi = new MethodInvoker(); @@ -60,14 +60,14 @@ public class MethodInvokerTests { mi.setTargetMethod("supertypes"); mi.setArguments(new ArrayList<>(), new ArrayList<>(), "hello"); mi.prepare(); - assertEquals("hello", mi.invoke()); + assertThat(mi.invoke()).isEqualTo("hello"); mi = new MethodInvoker(); mi.setTargetClass(TestClass1.class); mi.setTargetMethod("supertypes2"); mi.setArguments(new ArrayList<>(), new ArrayList<>(), "hello", "bogus"); mi.prepare(); - assertEquals("hello", mi.invoke()); + assertThat(mi.invoke()).isEqualTo("hello"); // Sanity check: check that argument conversion doesn't work with plain MethodInvoker mi = new MethodInvoker(); @@ -98,7 +98,7 @@ public class MethodInvokerTests { methodInvoker.setArguments(new Purchaser()); methodInvoker.prepare(); String greeting = (String) methodInvoker.invoke(); - assertEquals("purchaser: hello", greeting); + assertThat(greeting).isEqualTo("purchaser: hello"); } @Test @@ -109,7 +109,7 @@ public class MethodInvokerTests { methodInvoker.setArguments(new Shopper()); methodInvoker.prepare(); String greeting = (String) methodInvoker.invoke(); - assertEquals("purchaser: may I help you?", greeting); + assertThat(greeting).isEqualTo("purchaser: may I help you?"); } @Test @@ -120,7 +120,7 @@ public class MethodInvokerTests { methodInvoker.setArguments(new Salesman()); methodInvoker.prepare(); String greeting = (String) methodInvoker.invoke(); - assertEquals("greetable: how are sales?", greeting); + assertThat(greeting).isEqualTo("greetable: how are sales?"); } @Test @@ -131,7 +131,7 @@ public class MethodInvokerTests { methodInvoker.setArguments(new Customer()); methodInvoker.prepare(); String greeting = (String) methodInvoker.invoke(); - assertEquals("customer: good day", greeting); + assertThat(greeting).isEqualTo("customer: good day"); } @Test @@ -142,7 +142,7 @@ public class MethodInvokerTests { methodInvoker.setArguments(new Regular("Kotter")); methodInvoker.prepare(); String greeting = (String) methodInvoker.invoke(); - assertEquals("regular: welcome back Kotter", greeting); + assertThat(greeting).isEqualTo("regular: welcome back Kotter"); } @Test @@ -153,7 +153,7 @@ public class MethodInvokerTests { methodInvoker.setArguments(new VIP("Fonzie")); methodInvoker.prepare(); String greeting = (String) methodInvoker.invoke(); - assertEquals("regular: whassup dude?", greeting); + assertThat(greeting).isEqualTo("regular: whassup dude?"); } diff --git a/spring-core/src/test/java/org/springframework/util/MimeTypeTests.java b/spring-core/src/test/java/org/springframework/util/MimeTypeTests.java index f6bd6a770fb..80c60fa1e0f 100644 --- a/spring-core/src/test/java/org/springframework/util/MimeTypeTests.java +++ b/spring-core/src/test/java/org/springframework/util/MimeTypeTests.java @@ -28,13 +28,9 @@ import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.support.DefaultConversionService; import static java.util.Collections.singletonMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertSame; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link MimeType}. @@ -86,111 +82,111 @@ public class MimeTypeTests { public void parseCharset() { String s = "text/html; charset=iso-8859-1"; MimeType mimeType = MimeType.valueOf(s); - assertEquals("Invalid type", "text", mimeType.getType()); - assertEquals("Invalid subtype", "html", mimeType.getSubtype()); - assertEquals("Invalid charset", StandardCharsets.ISO_8859_1, mimeType.getCharset()); + assertThat(mimeType.getType()).as("Invalid type").isEqualTo("text"); + assertThat(mimeType.getSubtype()).as("Invalid subtype").isEqualTo("html"); + assertThat(mimeType.getCharset()).as("Invalid charset").isEqualTo(StandardCharsets.ISO_8859_1); } @Test public void parseQuotedCharset() { String s = "application/xml;charset=\"utf-8\""; MimeType mimeType = MimeType.valueOf(s); - assertEquals("Invalid type", "application", mimeType.getType()); - assertEquals("Invalid subtype", "xml", mimeType.getSubtype()); - assertEquals("Invalid charset", StandardCharsets.UTF_8, mimeType.getCharset()); + assertThat(mimeType.getType()).as("Invalid type").isEqualTo("application"); + assertThat(mimeType.getSubtype()).as("Invalid subtype").isEqualTo("xml"); + assertThat(mimeType.getCharset()).as("Invalid charset").isEqualTo(StandardCharsets.UTF_8); } @Test public void parseQuotedSeparator() { String s = "application/xop+xml;charset=utf-8;type=\"application/soap+xml;action=\\\"https://x.y.z\\\"\""; MimeType mimeType = MimeType.valueOf(s); - assertEquals("Invalid type", "application", mimeType.getType()); - assertEquals("Invalid subtype", "xop+xml", mimeType.getSubtype()); - assertEquals("Invalid charset", StandardCharsets.UTF_8, mimeType.getCharset()); - assertEquals("\"application/soap+xml;action=\\\"https://x.y.z\\\"\"", mimeType.getParameter("type")); + assertThat(mimeType.getType()).as("Invalid type").isEqualTo("application"); + assertThat(mimeType.getSubtype()).as("Invalid subtype").isEqualTo("xop+xml"); + assertThat(mimeType.getCharset()).as("Invalid charset").isEqualTo(StandardCharsets.UTF_8); + assertThat(mimeType.getParameter("type")).isEqualTo("\"application/soap+xml;action=\\\"https://x.y.z\\\"\""); } @Test public void withConversionService() { ConversionService conversionService = new DefaultConversionService(); - assertTrue(conversionService.canConvert(String.class, MimeType.class)); + assertThat(conversionService.canConvert(String.class, MimeType.class)).isTrue(); MimeType mimeType = MimeType.valueOf("application/xml"); - assertEquals(mimeType, conversionService.convert("application/xml", MimeType.class)); + assertThat(conversionService.convert("application/xml", MimeType.class)).isEqualTo(mimeType); } @Test public void includes() { MimeType textPlain = MimeTypeUtils.TEXT_PLAIN; - assertTrue("Equal types is not inclusive", textPlain.includes(textPlain)); + assertThat(textPlain.includes(textPlain)).as("Equal types is not inclusive").isTrue(); MimeType allText = new MimeType("text"); - assertTrue("All subtypes is not inclusive", allText.includes(textPlain)); - assertFalse("All subtypes is inclusive", textPlain.includes(allText)); + assertThat(allText.includes(textPlain)).as("All subtypes is not inclusive").isTrue(); + assertThat(textPlain.includes(allText)).as("All subtypes is inclusive").isFalse(); - assertTrue("All types is not inclusive", MimeTypeUtils.ALL.includes(textPlain)); - assertFalse("All types is inclusive", textPlain.includes(MimeTypeUtils.ALL)); + assertThat(MimeTypeUtils.ALL.includes(textPlain)).as("All types is not inclusive").isTrue(); + assertThat(textPlain.includes(MimeTypeUtils.ALL)).as("All types is inclusive").isFalse(); - assertTrue("All types is not inclusive", MimeTypeUtils.ALL.includes(textPlain)); - assertFalse("All types is inclusive", textPlain.includes(MimeTypeUtils.ALL)); + assertThat(MimeTypeUtils.ALL.includes(textPlain)).as("All types is not inclusive").isTrue(); + assertThat(textPlain.includes(MimeTypeUtils.ALL)).as("All types is inclusive").isFalse(); MimeType applicationSoapXml = new MimeType("application", "soap+xml"); MimeType applicationWildcardXml = new MimeType("application", "*+xml"); MimeType suffixXml = new MimeType("application", "x.y+z+xml"); // SPR-15795 - assertTrue(applicationSoapXml.includes(applicationSoapXml)); - assertTrue(applicationWildcardXml.includes(applicationWildcardXml)); - assertTrue(applicationWildcardXml.includes(suffixXml)); + assertThat(applicationSoapXml.includes(applicationSoapXml)).isTrue(); + assertThat(applicationWildcardXml.includes(applicationWildcardXml)).isTrue(); + assertThat(applicationWildcardXml.includes(suffixXml)).isTrue(); - assertTrue(applicationWildcardXml.includes(applicationSoapXml)); - assertFalse(applicationSoapXml.includes(applicationWildcardXml)); - assertFalse(suffixXml.includes(applicationWildcardXml)); + assertThat(applicationWildcardXml.includes(applicationSoapXml)).isTrue(); + assertThat(applicationSoapXml.includes(applicationWildcardXml)).isFalse(); + assertThat(suffixXml.includes(applicationWildcardXml)).isFalse(); - assertFalse(applicationWildcardXml.includes(MimeTypeUtils.APPLICATION_JSON)); + assertThat(applicationWildcardXml.includes(MimeTypeUtils.APPLICATION_JSON)).isFalse(); } @Test public void isCompatible() { MimeType textPlain = MimeTypeUtils.TEXT_PLAIN; - assertTrue("Equal types is not compatible", textPlain.isCompatibleWith(textPlain)); + assertThat(textPlain.isCompatibleWith(textPlain)).as("Equal types is not compatible").isTrue(); MimeType allText = new MimeType("text"); - assertTrue("All subtypes is not compatible", allText.isCompatibleWith(textPlain)); - assertTrue("All subtypes is not compatible", textPlain.isCompatibleWith(allText)); + assertThat(allText.isCompatibleWith(textPlain)).as("All subtypes is not compatible").isTrue(); + assertThat(textPlain.isCompatibleWith(allText)).as("All subtypes is not compatible").isTrue(); - assertTrue("All types is not compatible", MimeTypeUtils.ALL.isCompatibleWith(textPlain)); - assertTrue("All types is not compatible", textPlain.isCompatibleWith(MimeTypeUtils.ALL)); + assertThat(MimeTypeUtils.ALL.isCompatibleWith(textPlain)).as("All types is not compatible").isTrue(); + assertThat(textPlain.isCompatibleWith(MimeTypeUtils.ALL)).as("All types is not compatible").isTrue(); - assertTrue("All types is not compatible", MimeTypeUtils.ALL.isCompatibleWith(textPlain)); - assertTrue("All types is compatible", textPlain.isCompatibleWith(MimeTypeUtils.ALL)); + assertThat(MimeTypeUtils.ALL.isCompatibleWith(textPlain)).as("All types is not compatible").isTrue(); + assertThat(textPlain.isCompatibleWith(MimeTypeUtils.ALL)).as("All types is compatible").isTrue(); MimeType applicationSoapXml = new MimeType("application", "soap+xml"); MimeType applicationWildcardXml = new MimeType("application", "*+xml"); MimeType suffixXml = new MimeType("application", "x.y+z+xml"); // SPR-15795 - assertTrue(applicationSoapXml.isCompatibleWith(applicationSoapXml)); - assertTrue(applicationWildcardXml.isCompatibleWith(applicationWildcardXml)); - assertTrue(applicationWildcardXml.isCompatibleWith(suffixXml)); + assertThat(applicationSoapXml.isCompatibleWith(applicationSoapXml)).isTrue(); + assertThat(applicationWildcardXml.isCompatibleWith(applicationWildcardXml)).isTrue(); + assertThat(applicationWildcardXml.isCompatibleWith(suffixXml)).isTrue(); - assertTrue(applicationWildcardXml.isCompatibleWith(applicationSoapXml)); - assertTrue(applicationSoapXml.isCompatibleWith(applicationWildcardXml)); - assertTrue(suffixXml.isCompatibleWith(applicationWildcardXml)); + assertThat(applicationWildcardXml.isCompatibleWith(applicationSoapXml)).isTrue(); + assertThat(applicationSoapXml.isCompatibleWith(applicationWildcardXml)).isTrue(); + assertThat(suffixXml.isCompatibleWith(applicationWildcardXml)).isTrue(); - assertFalse(applicationWildcardXml.isCompatibleWith(MimeTypeUtils.APPLICATION_JSON)); + assertThat(applicationWildcardXml.isCompatibleWith(MimeTypeUtils.APPLICATION_JSON)).isFalse(); } @Test public void testToString() { MimeType mimeType = new MimeType("text", "plain"); String result = mimeType.toString(); - assertEquals("Invalid toString() returned", "text/plain", result); + assertThat(result).as("Invalid toString() returned").isEqualTo("text/plain"); } @Test public void parseMimeType() { String s = "audio/*"; MimeType mimeType = MimeTypeUtils.parseMimeType(s); - assertEquals("Invalid type", "audio", mimeType.getType()); - assertEquals("Invalid subtype", "*", mimeType.getSubtype()); + assertThat(mimeType.getType()).as("Invalid type").isEqualTo("audio"); + assertThat(mimeType.getSubtype()).as("Invalid subtype").isEqualTo("*"); } @Test @@ -262,25 +258,25 @@ public class MimeTypeTests { @Test // SPR-8917 public void parseMimeTypeQuotedParameterValue() { MimeType mimeType = MimeTypeUtils.parseMimeType("audio/*;attr=\"v>alue\""); - assertEquals("\"v>alue\"", mimeType.getParameter("attr")); + assertThat(mimeType.getParameter("attr")).isEqualTo("\"v>alue\""); } @Test // SPR-8917 public void parseMimeTypeSingleQuotedParameterValue() { MimeType mimeType = MimeTypeUtils.parseMimeType("audio/*;attr='v>alue'"); - assertEquals("'v>alue'", mimeType.getParameter("attr")); + assertThat(mimeType.getParameter("attr")).isEqualTo("'v>alue'"); } @Test // SPR-16630 public void parseMimeTypeWithSpacesAroundEquals() { MimeType mimeType = MimeTypeUtils.parseMimeType("multipart/x-mixed-replace;boundary = --myboundary"); - assertEquals("--myboundary", mimeType.getParameter("boundary")); + assertThat(mimeType.getParameter("boundary")).isEqualTo("--myboundary"); } @Test // SPR-16630 public void parseMimeTypeWithSpacesAroundEqualsAndQuotedValue() { MimeType mimeType = MimeTypeUtils.parseMimeType("text/plain; foo = \" bar \" "); - assertEquals("\" bar \"", mimeType.getParameter("foo")); + assertThat(mimeType.getParameter("foo")).isEqualTo("\" bar \""); } @Test @@ -293,12 +289,12 @@ public class MimeTypeTests { public void parseMimeTypes() { String s = "text/plain, text/html, text/x-dvi, text/x-c"; List mimeTypes = MimeTypeUtils.parseMimeTypes(s); - assertNotNull("No mime types returned", mimeTypes); - assertEquals("Invalid amount of mime types", 4, mimeTypes.size()); + assertThat(mimeTypes).as("No mime types returned").isNotNull(); + assertThat(mimeTypes.size()).as("Invalid amount of mime types").isEqualTo(4); mimeTypes = MimeTypeUtils.parseMimeTypes(null); - assertNotNull("No mime types returned", mimeTypes); - assertEquals("Invalid amount of mime types", 0, mimeTypes.size()); + assertThat(mimeTypes).as("No mime types returned").isNotNull(); + assertThat(mimeTypes.size()).as("Invalid amount of mime types").isEqualTo(0); } @Test // SPR-17459 @@ -314,9 +310,9 @@ public class MimeTypeTests { private void testWithQuotedParameters(String... mimeTypes) { String s = String.join(",", mimeTypes); List actual = MimeTypeUtils.parseMimeTypes(s); - assertEquals(mimeTypes.length, actual.size()); + assertThat(actual.size()).isEqualTo(mimeTypes.length); for (int i=0; i < mimeTypes.length; i++) { - assertEquals(mimeTypes[i], actual.get(i).toString()); + assertThat(actual.get(i).toString()).isEqualTo(mimeTypes[i]); } } @@ -328,11 +324,11 @@ public class MimeTypeTests { MimeType audioBasicLevel = new MimeType("audio", "basic", singletonMap("level", "1")); // equal - assertEquals("Invalid comparison result", 0, audioBasic.compareTo(audioBasic)); - assertEquals("Invalid comparison result", 0, audio.compareTo(audio)); - assertEquals("Invalid comparison result", 0, audioBasicLevel.compareTo(audioBasicLevel)); + assertThat(audioBasic.compareTo(audioBasic)).as("Invalid comparison result").isEqualTo(0); + assertThat(audio.compareTo(audio)).as("Invalid comparison result").isEqualTo(0); + assertThat(audioBasicLevel.compareTo(audioBasicLevel)).as("Invalid comparison result").isEqualTo(0); - assertTrue("Invalid comparison result", audioBasicLevel.compareTo(audio) > 0); + assertThat(audioBasicLevel.compareTo(audio) > 0).as("Invalid comparison result").isTrue(); List expected = new ArrayList<>(); expected.add(audio); @@ -348,7 +344,7 @@ public class MimeTypeTests { Collections.sort(result); for (int j = 0; j < result.size(); j++) { - assertSame("Invalid media type at " + j + ", run " + i, expected.get(j), result.get(j)); + assertThat(result.get(j)).as("Invalid media type at " + j + ", run " + i).isSameAs(expected.get(j)); } } } @@ -357,18 +353,18 @@ public class MimeTypeTests { public void compareToCaseSensitivity() { MimeType m1 = new MimeType("audio", "basic"); MimeType m2 = new MimeType("Audio", "Basic"); - assertEquals("Invalid comparison result", 0, m1.compareTo(m2)); - assertEquals("Invalid comparison result", 0, m2.compareTo(m1)); + assertThat(m1.compareTo(m2)).as("Invalid comparison result").isEqualTo(0); + assertThat(m2.compareTo(m1)).as("Invalid comparison result").isEqualTo(0); m1 = new MimeType("audio", "basic", singletonMap("foo", "bar")); m2 = new MimeType("audio", "basic", singletonMap("Foo", "bar")); - assertEquals("Invalid comparison result", 0, m1.compareTo(m2)); - assertEquals("Invalid comparison result", 0, m2.compareTo(m1)); + assertThat(m1.compareTo(m2)).as("Invalid comparison result").isEqualTo(0); + assertThat(m2.compareTo(m1)).as("Invalid comparison result").isEqualTo(0); m1 = new MimeType("audio", "basic", singletonMap("foo", "bar")); m2 = new MimeType("audio", "basic", singletonMap("foo", "Bar")); - assertTrue("Invalid comparison result", m1.compareTo(m2) != 0); - assertTrue("Invalid comparison result", m2.compareTo(m1) != 0); + assertThat(m1.compareTo(m2) != 0).as("Invalid comparison result").isTrue(); + assertThat(m2.compareTo(m1) != 0).as("Invalid comparison result").isTrue(); } /** @@ -379,10 +375,10 @@ public class MimeTypeTests { public void equalsIsCaseInsensitiveForCharsets() { MimeType m1 = new MimeType("text", "plain", singletonMap("charset", "UTF-8")); MimeType m2 = new MimeType("text", "plain", singletonMap("charset", "utf-8")); - assertEquals(m1, m2); - assertEquals(m2, m1); - assertEquals(0, m1.compareTo(m2)); - assertEquals(0, m2.compareTo(m1)); + assertThat(m2).isEqualTo(m1); + assertThat(m1).isEqualTo(m2); + assertThat(m1.compareTo(m2)).isEqualTo(0); + assertThat(m2.compareTo(m1)).isEqualTo(0); } } diff --git a/spring-core/src/test/java/org/springframework/util/NumberUtilsTests.java b/spring-core/src/test/java/org/springframework/util/NumberUtilsTests.java index 4baf587b2e4..aff5593b883 100644 --- a/spring-core/src/test/java/org/springframework/util/NumberUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/NumberUtilsTests.java @@ -23,8 +23,8 @@ import java.util.Locale; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @author Rob Harrop @@ -41,12 +41,12 @@ public class NumberUtilsTests { String aFloat = "" + Float.MAX_VALUE; String aDouble = "" + Double.MAX_VALUE; - assertEquals("Byte did not parse", Byte.valueOf(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class)); - assertEquals("Short did not parse", Short.valueOf(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class)); - assertEquals("Integer did not parse", Integer.valueOf(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class)); - assertEquals("Long did not parse", Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class)); - assertEquals("Float did not parse", Float.valueOf(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class)); - assertEquals("Double did not parse", Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class)); + assertThat(NumberUtils.parseNumber(aByte, Byte.class)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aShort, Short.class)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(anInteger, Integer.class)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aLong, Long.class)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aFloat, Float.class)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aDouble, Double.class)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test @@ -59,12 +59,12 @@ public class NumberUtilsTests { String aFloat = "" + Float.MAX_VALUE; String aDouble = "" + Double.MAX_VALUE; - assertEquals("Byte did not parse", Byte.valueOf(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class, nf)); - assertEquals("Short did not parse", Short.valueOf(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class, nf)); - assertEquals("Integer did not parse", Integer.valueOf(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class, nf)); - assertEquals("Long did not parse", Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf)); - assertEquals("Float did not parse", Float.valueOf(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class, nf)); - assertEquals("Double did not parse", Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf)); + assertThat(NumberUtils.parseNumber(aByte, Byte.class, nf)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aShort, Short.class, nf)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(anInteger, Integer.class, nf)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aFloat, Float.class, nf)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test @@ -76,12 +76,12 @@ public class NumberUtilsTests { String aFloat = " " + Float.MAX_VALUE + " "; String aDouble = " " + Double.MAX_VALUE + " "; - assertEquals("Byte did not parse", Byte.valueOf(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class)); - assertEquals("Short did not parse", Short.valueOf(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class)); - assertEquals("Integer did not parse", Integer.valueOf(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class)); - assertEquals("Long did not parse", Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class)); - assertEquals("Float did not parse", Float.valueOf(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class)); - assertEquals("Double did not parse", Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class)); + assertThat(NumberUtils.parseNumber(aByte, Byte.class)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aShort, Short.class)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(anInteger, Integer.class)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aLong, Long.class)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aFloat, Float.class)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aDouble, Double.class)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test @@ -94,12 +94,12 @@ public class NumberUtilsTests { String aFloat = " " + Float.MAX_VALUE + " "; String aDouble = " " + Double.MAX_VALUE + " "; - assertEquals("Byte did not parse", Byte.valueOf(Byte.MAX_VALUE), NumberUtils.parseNumber(aByte, Byte.class, nf)); - assertEquals("Short did not parse", Short.valueOf(Short.MAX_VALUE), NumberUtils.parseNumber(aShort, Short.class, nf)); - assertEquals("Integer did not parse", Integer.valueOf(Integer.MAX_VALUE), NumberUtils.parseNumber(anInteger, Integer.class, nf)); - assertEquals("Long did not parse", Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf)); - assertEquals("Float did not parse", Float.valueOf(Float.MAX_VALUE), NumberUtils.parseNumber(aFloat, Float.class, nf)); - assertEquals("Double did not parse", Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf)); + assertThat(NumberUtils.parseNumber(aByte, Byte.class, nf)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aShort, Short.class, nf)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(anInteger, Integer.class, nf)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aFloat, Float.class, nf)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test @@ -114,8 +114,7 @@ public class NumberUtilsTests { assertShortEquals(aShort); assertIntegerEquals(anInteger); assertLongEquals(aLong); - assertEquals("BigInteger did not parse", - new BigInteger(aReallyBigInt, 16), NumberUtils.parseNumber("0x" + aReallyBigInt, BigInteger.class)); + assertThat(NumberUtils.parseNumber("0x" + aReallyBigInt, BigInteger.class)).as("BigInteger did not parse").isEqualTo(new BigInteger(aReallyBigInt, 16)); } @Test @@ -130,48 +129,47 @@ public class NumberUtilsTests { assertNegativeShortEquals(aShort); assertNegativeIntegerEquals(anInteger); assertNegativeLongEquals(aLong); - assertEquals("BigInteger did not parse", - new BigInteger(aReallyBigInt, 16).negate(), NumberUtils.parseNumber("-0x" + aReallyBigInt, BigInteger.class)); + assertThat(NumberUtils.parseNumber("-0x" + aReallyBigInt, BigInteger.class)).as("BigInteger did not parse").isEqualTo(new BigInteger(aReallyBigInt, 16).negate()); } @Test public void convertDoubleToBigInteger() { Double decimal = Double.valueOf(3.14d); - assertEquals(new BigInteger("3"), NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)); + assertThat(NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)).isEqualTo(new BigInteger("3")); } @Test public void convertBigDecimalToBigInteger() { String number = "987459837583750387355346"; BigDecimal decimal = new BigDecimal(number); - assertEquals(new BigInteger(number), NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)); + assertThat(NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)).isEqualTo(new BigInteger(number)); } @Test public void convertNonExactBigDecimalToBigInteger() { BigDecimal decimal = new BigDecimal("987459837583750387355346.14"); - assertEquals(new BigInteger("987459837583750387355346"), NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)); + assertThat(NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)).isEqualTo(new BigInteger("987459837583750387355346")); } @Test public void parseBigDecimalNumber1() { String bigDecimalAsString = "0.10"; Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class); - assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal); + assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test public void parseBigDecimalNumber2() { String bigDecimalAsString = "0.001"; Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class); - assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal); + assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test public void parseBigDecimalNumber3() { String bigDecimalAsString = "3.14159265358979323846"; Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class); - assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal); + assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test @@ -179,7 +177,7 @@ public class NumberUtilsTests { String bigDecimalAsString = "0.10"; NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH); Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat); - assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal); + assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test @@ -187,7 +185,7 @@ public class NumberUtilsTests { String bigDecimalAsString = "0.001"; NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH); Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat); - assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal); + assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test @@ -195,7 +193,7 @@ public class NumberUtilsTests { String bigDecimalAsString = "3.14159265358979323846"; NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH); Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat); - assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal); + assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test @@ -212,8 +210,8 @@ public class NumberUtilsTests { assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Integer.class)); - assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class)); - assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class)); + assertThat(NumberUtils.parseNumber(aLong, Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aDouble, Double.class)).isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test @@ -230,8 +228,8 @@ public class NumberUtilsTests { assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Integer.class)); - assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.parseNumber(aLong, Long.class)); - assertEquals(Double.valueOf(Double.MIN_VALUE), NumberUtils.parseNumber(aDouble, Double.class)); + assertThat(NumberUtils.parseNumber(aLong, Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); + assertThat(NumberUtils.parseNumber(aDouble, Double.class)).isEqualTo(Double.valueOf(Double.MIN_VALUE)); } @Test @@ -249,8 +247,8 @@ public class NumberUtilsTests { assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Integer.class, nf)); - assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf)); - assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf)); + assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); + assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test @@ -268,51 +266,51 @@ public class NumberUtilsTests { assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Integer.class, nf)); - assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.parseNumber(aLong, Long.class, nf)); - assertEquals(Double.valueOf(Double.MIN_VALUE), NumberUtils.parseNumber(aDouble, Double.class, nf)); + assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); + assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).isEqualTo(Double.valueOf(Double.MIN_VALUE)); } @Test public void convertToInteger() { - assertEquals(Integer.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(-1), Integer.class)); - assertEquals(Integer.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(0), Integer.class)); - assertEquals(Integer.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(1), Integer.class)); - assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MAX_VALUE), Integer.class)); - assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MAX_VALUE + 1), Integer.class)); - assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MIN_VALUE), Integer.class)); - assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MIN_VALUE - 1), Integer.class)); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(-1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(-1))); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(0), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(0))); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(1))); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MAX_VALUE + 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MIN_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MIN_VALUE - 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); - assertEquals(Integer.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Long.valueOf(-1), Integer.class)); - assertEquals(Integer.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Long.valueOf(0), Integer.class)); - assertEquals(Integer.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Long.valueOf(1), Integer.class)); - assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MAX_VALUE), Integer.class)); - assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MAX_VALUE + 1), Integer.class)); - assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MIN_VALUE), Integer.class)); - assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MIN_VALUE - 1), Integer.class)); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(-1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(-1))); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(0), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(0))); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(1))); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MAX_VALUE + 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MIN_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MIN_VALUE - 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); - assertEquals(Integer.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(-1), Integer.class)); - assertEquals(Integer.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(0), Integer.class)); - assertEquals(Integer.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(1), Integer.class)); - assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE), Integer.class)); - assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE + 1), Integer.class)); - assertEquals(Integer.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE), Integer.class)); - assertEquals(Integer.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE - 1), Integer.class)); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(-1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(-1))); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(0), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(0))); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(1))); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE + 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE - 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); - assertEquals(Integer.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) -1), Integer.class)); - assertEquals(Integer.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 0), Integer.class)); - assertEquals(Integer.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 1), Integer.class)); - assertEquals(Integer.valueOf(Short.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MAX_VALUE), Integer.class)); - assertEquals(Integer.valueOf(Short.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MAX_VALUE + 1)), Integer.class)); - assertEquals(Integer.valueOf(Short.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MIN_VALUE), Integer.class)); - assertEquals(Integer.valueOf(Short.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MIN_VALUE - 1)), Integer.class)); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) -1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(-1))); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 0), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(0))); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(1))); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Short.MAX_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MAX_VALUE + 1)), Integer.class)).isEqualTo(Integer.valueOf(Short.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MIN_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Short.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MIN_VALUE - 1)), Integer.class)).isEqualTo(Integer.valueOf(Short.MAX_VALUE)); - assertEquals(Integer.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) -1), Integer.class)); - assertEquals(Integer.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 0), Integer.class)); - assertEquals(Integer.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 1), Integer.class)); - assertEquals(Integer.valueOf(Byte.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MAX_VALUE), Integer.class)); - assertEquals(Integer.valueOf(Byte.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MAX_VALUE + 1)), Integer.class)); - assertEquals(Integer.valueOf(Byte.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MIN_VALUE), Integer.class)); - assertEquals(Integer.valueOf(Byte.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MIN_VALUE - 1)), Integer.class)); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) -1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(-1))); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 0), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(0))); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.valueOf(1))); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Byte.MAX_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MAX_VALUE + 1)), Integer.class)).isEqualTo(Integer.valueOf(Byte.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MIN_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Byte.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MIN_VALUE - 1)), Integer.class)).isEqualTo(Integer.valueOf(Byte.MAX_VALUE)); assertToNumberOverflow(Long.valueOf(Long.MAX_VALUE + 1), Integer.class); assertToNumberOverflow(Long.valueOf(Long.MIN_VALUE - 1), Integer.class); @@ -323,45 +321,45 @@ public class NumberUtilsTests { @Test public void convertToLong() { - assertEquals(Long.valueOf(Long.valueOf(-1)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(-1), Long.class)); - assertEquals(Long.valueOf(Long.valueOf(0)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(0), Long.class)); - assertEquals(Long.valueOf(Long.valueOf(1)), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(1), Long.class)); - assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MAX_VALUE), Long.class)); - assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MAX_VALUE + 1), Long.class)); - assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MIN_VALUE), Long.class)); - assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MIN_VALUE - 1), Long.class)); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(-1), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(-1))); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(0), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(0))); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(1), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(1))); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MAX_VALUE), Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MAX_VALUE + 1), Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MIN_VALUE), Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MIN_VALUE - 1), Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); - assertEquals(Long.valueOf(Long.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Long.valueOf(-1), Long.class)); - assertEquals(Long.valueOf(Long.valueOf(0)), NumberUtils.convertNumberToTargetClass(Long.valueOf(0), Long.class)); - assertEquals(Long.valueOf(Long.valueOf(1)), NumberUtils.convertNumberToTargetClass(Long.valueOf(1), Long.class)); - assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MAX_VALUE), Long.class)); - assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MAX_VALUE + 1), Long.class)); - assertEquals(Long.valueOf(Long.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MIN_VALUE), Long.class)); - assertEquals(Long.valueOf(Long.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MIN_VALUE - 1), Long.class)); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(-1), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(-1))); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(0), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(0))); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(1), Long.class)).isEqualTo(Long.valueOf(Long.valueOf(1))); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MAX_VALUE), Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MAX_VALUE + 1), Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MIN_VALUE), Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Long.MIN_VALUE - 1), Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); - assertEquals(Long.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(-1), Long.class)); - assertEquals(Long.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(0), Long.class)); - assertEquals(Long.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Integer.valueOf(1), Long.class)); - assertEquals(Long.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE), Long.class)); - assertEquals(Long.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE + 1), Long.class)); - assertEquals(Long.valueOf(Integer.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE), Long.class)); - assertEquals(Long.valueOf(Integer.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE - 1), Long.class)); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(-1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(-1))); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(0), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(0))); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(1))); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE), Long.class)).isEqualTo(Long.valueOf(Integer.MAX_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MAX_VALUE + 1), Long.class)).isEqualTo(Long.valueOf(Integer.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE), Long.class)).isEqualTo(Long.valueOf(Integer.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Integer.valueOf(Integer.MIN_VALUE - 1), Long.class)).isEqualTo(Long.valueOf(Integer.MAX_VALUE)); - assertEquals(Long.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) -1), Long.class)); - assertEquals(Long.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 0), Long.class)); - assertEquals(Long.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 1), Long.class)); - assertEquals(Long.valueOf(Short.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MAX_VALUE), Long.class)); - assertEquals(Long.valueOf(Short.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MAX_VALUE + 1)), Long.class)); - assertEquals(Long.valueOf(Short.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MIN_VALUE), Long.class)); - assertEquals(Long.valueOf(Short.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MIN_VALUE - 1)), Long.class)); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) -1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(-1))); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 0), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(0))); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) 1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(1))); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MAX_VALUE), Long.class)).isEqualTo(Long.valueOf(Short.MAX_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MAX_VALUE + 1)), Long.class)).isEqualTo(Long.valueOf(Short.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf(Short.MIN_VALUE), Long.class)).isEqualTo(Long.valueOf(Short.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Short.valueOf((short) (Short.MIN_VALUE - 1)), Long.class)).isEqualTo(Long.valueOf(Short.MAX_VALUE)); - assertEquals(Long.valueOf(Integer.valueOf(-1)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) -1), Long.class)); - assertEquals(Long.valueOf(Integer.valueOf(0)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 0), Long.class)); - assertEquals(Long.valueOf(Integer.valueOf(1)), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 1), Long.class)); - assertEquals(Long.valueOf(Byte.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MAX_VALUE), Long.class)); - assertEquals(Long.valueOf(Byte.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MAX_VALUE + 1)), Long.class)); - assertEquals(Long.valueOf(Byte.MIN_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MIN_VALUE), Long.class)); - assertEquals(Long.valueOf(Byte.MAX_VALUE), NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MIN_VALUE - 1)), Long.class)); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) -1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(-1))); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 0), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(0))); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) 1), Long.class)).isEqualTo(Long.valueOf(Integer.valueOf(1))); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MAX_VALUE), Long.class)).isEqualTo(Long.valueOf(Byte.MAX_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MAX_VALUE + 1)), Long.class)).isEqualTo(Long.valueOf(Byte.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf(Byte.MIN_VALUE), Long.class)).isEqualTo(Long.valueOf(Byte.MIN_VALUE)); + assertThat(NumberUtils.convertNumberToTargetClass(Byte.valueOf((byte) (Byte.MIN_VALUE - 1)), Long.class)).isEqualTo(Long.valueOf(Byte.MAX_VALUE)); assertToNumberOverflow(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE), Long.class); assertToNumberOverflow(BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE), Long.class); @@ -370,35 +368,35 @@ public class NumberUtilsTests { private void assertLongEquals(String aLong) { - assertEquals("Long did not parse", Long.MAX_VALUE, NumberUtils.parseNumber(aLong, Long.class).longValue()); + assertThat(NumberUtils.parseNumber(aLong, Long.class).longValue()).as("Long did not parse").isEqualTo(Long.MAX_VALUE); } private void assertIntegerEquals(String anInteger) { - assertEquals("Integer did not parse", Integer.MAX_VALUE, NumberUtils.parseNumber(anInteger, Integer.class).intValue()); + assertThat(NumberUtils.parseNumber(anInteger, Integer.class).intValue()).as("Integer did not parse").isEqualTo(Integer.MAX_VALUE); } private void assertShortEquals(String aShort) { - assertEquals("Short did not parse", Short.MAX_VALUE, NumberUtils.parseNumber(aShort, Short.class).shortValue()); + assertThat(NumberUtils.parseNumber(aShort, Short.class).shortValue()).as("Short did not parse").isEqualTo(Short.MAX_VALUE); } private void assertByteEquals(String aByte) { - assertEquals("Byte did not parse", Byte.MAX_VALUE, NumberUtils.parseNumber(aByte, Byte.class).byteValue()); + assertThat(NumberUtils.parseNumber(aByte, Byte.class).byteValue()).as("Byte did not parse").isEqualTo(Byte.MAX_VALUE); } private void assertNegativeLongEquals(String aLong) { - assertEquals("Long did not parse", Long.MIN_VALUE, NumberUtils.parseNumber(aLong, Long.class).longValue()); + assertThat(NumberUtils.parseNumber(aLong, Long.class).longValue()).as("Long did not parse").isEqualTo(Long.MIN_VALUE); } private void assertNegativeIntegerEquals(String anInteger) { - assertEquals("Integer did not parse", Integer.MIN_VALUE, NumberUtils.parseNumber(anInteger, Integer.class).intValue()); + assertThat(NumberUtils.parseNumber(anInteger, Integer.class).intValue()).as("Integer did not parse").isEqualTo(Integer.MIN_VALUE); } private void assertNegativeShortEquals(String aShort) { - assertEquals("Short did not parse", Short.MIN_VALUE, NumberUtils.parseNumber(aShort, Short.class).shortValue()); + assertThat(NumberUtils.parseNumber(aShort, Short.class).shortValue()).as("Short did not parse").isEqualTo(Short.MIN_VALUE); } private void assertNegativeByteEquals(String aByte) { - assertEquals("Byte did not parse", Byte.MIN_VALUE, NumberUtils.parseNumber(aByte, Byte.class).byteValue()); + assertThat(NumberUtils.parseNumber(aByte, Byte.class).byteValue()).as("Byte did not parse").isEqualTo(Byte.MIN_VALUE); } private void assertToNumberOverflow(Number number, Class targetClass) { diff --git a/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java index a26a762d856..fb54e1a8241 100644 --- a/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java @@ -28,11 +28,6 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import static org.springframework.util.ObjectUtils.isEmpty; /** @@ -47,15 +42,15 @@ public class ObjectUtilsTests { @Test public void isCheckedException() { - assertTrue(ObjectUtils.isCheckedException(new Exception())); - assertTrue(ObjectUtils.isCheckedException(new SQLException())); + assertThat(ObjectUtils.isCheckedException(new Exception())).isTrue(); + assertThat(ObjectUtils.isCheckedException(new SQLException())).isTrue(); - assertFalse(ObjectUtils.isCheckedException(new RuntimeException())); - assertFalse(ObjectUtils.isCheckedException(new IllegalArgumentException(""))); + assertThat(ObjectUtils.isCheckedException(new RuntimeException())).isFalse(); + assertThat(ObjectUtils.isCheckedException(new IllegalArgumentException(""))).isFalse(); // Any Throwable other than RuntimeException and Error // has to be considered checked according to the JLS. - assertTrue(ObjectUtils.isCheckedException(new Throwable())); + assertThat(ObjectUtils.isCheckedException(new Throwable())).isTrue(); } @Test @@ -65,105 +60,105 @@ public class ObjectUtilsTests { Class[] sqlAndIO = new Class[] {SQLException.class, IOException.class}; Class[] throwable = new Class[] {Throwable.class}; - assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException())); - assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), empty)); - assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), exception)); - assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), sqlAndIO)); - assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), throwable)); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException())).isTrue(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), empty)).isTrue(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), exception)).isTrue(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), sqlAndIO)).isTrue(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), throwable)).isTrue(); - assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Exception())); - assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), empty)); - assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), exception)); - assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), sqlAndIO)); - assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), throwable)); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Exception())).isFalse(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), empty)).isFalse(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), exception)).isTrue(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), sqlAndIO)).isFalse(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Exception(), throwable)).isTrue(); - assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new SQLException())); - assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), empty)); - assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), exception)); - assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), sqlAndIO)); - assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), throwable)); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new SQLException())).isFalse(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), empty)).isFalse(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), exception)).isTrue(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), sqlAndIO)).isTrue(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new SQLException(), throwable)).isTrue(); - assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable())); - assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), empty)); - assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), exception)); - assertFalse(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), sqlAndIO)); - assertTrue(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), throwable)); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Throwable())).isFalse(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), empty)).isFalse(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), exception)).isFalse(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), sqlAndIO)).isFalse(); + assertThat(ObjectUtils.isCompatibleWithThrowsClause(new Throwable(), throwable)).isTrue(); } @Test public void isEmptyNull() { - assertTrue(isEmpty(null)); + assertThat(isEmpty(null)).isTrue(); } @Test public void isEmptyArray() { - assertTrue(isEmpty(new char[0])); - assertTrue(isEmpty(new Object[0])); - assertTrue(isEmpty(new Integer[0])); + assertThat(isEmpty(new char[0])).isTrue(); + assertThat(isEmpty(new Object[0])).isTrue(); + assertThat(isEmpty(new Integer[0])).isTrue(); - assertFalse(isEmpty(new int[] {42})); - assertFalse(isEmpty(new Integer[] {42})); + assertThat(isEmpty(new int[] {42})).isFalse(); + assertThat(isEmpty(new Integer[] {42})).isFalse(); } @Test public void isEmptyCollection() { - assertTrue(isEmpty(Collections.emptyList())); - assertTrue(isEmpty(Collections.emptySet())); + assertThat(isEmpty(Collections.emptyList())).isTrue(); + assertThat(isEmpty(Collections.emptySet())).isTrue(); Set set = new HashSet<>(); set.add("foo"); - assertFalse(isEmpty(set)); - assertFalse(isEmpty(Arrays.asList("foo"))); + assertThat(isEmpty(set)).isFalse(); + assertThat(isEmpty(Arrays.asList("foo"))).isFalse(); } @Test public void isEmptyMap() { - assertTrue(isEmpty(Collections.emptyMap())); + assertThat(isEmpty(Collections.emptyMap())).isTrue(); HashMap map = new HashMap<>(); map.put("foo", 42L); - assertFalse(isEmpty(map)); + assertThat(isEmpty(map)).isFalse(); } @Test public void isEmptyCharSequence() { - assertTrue(isEmpty(new StringBuilder())); - assertTrue(isEmpty("")); + assertThat(isEmpty(new StringBuilder())).isTrue(); + assertThat(isEmpty("")).isTrue(); - assertFalse(isEmpty(new StringBuilder("foo"))); - assertFalse(isEmpty(" ")); - assertFalse(isEmpty("\t")); - assertFalse(isEmpty("foo")); + assertThat(isEmpty(new StringBuilder("foo"))).isFalse(); + assertThat(isEmpty(" ")).isFalse(); + assertThat(isEmpty("\t")).isFalse(); + assertThat(isEmpty("foo")).isFalse(); } @Test public void isEmptyUnsupportedObjectType() { - assertFalse(isEmpty(42L)); - assertFalse(isEmpty(new Object())); + assertThat(isEmpty(42L)).isFalse(); + assertThat(isEmpty(new Object())).isFalse(); } @Test public void toObjectArray() { int[] a = new int[] {1, 2, 3, 4, 5}; Integer[] wrapper = (Integer[]) ObjectUtils.toObjectArray(a); - assertTrue(wrapper.length == 5); + assertThat(wrapper.length == 5).isTrue(); for (int i = 0; i < wrapper.length; i++) { - assertEquals(a[i], wrapper[i].intValue()); + assertThat(wrapper[i].intValue()).isEqualTo(a[i]); } } @Test public void toObjectArrayWithNull() { Object[] objects = ObjectUtils.toObjectArray(null); - assertNotNull(objects); - assertEquals(0, objects.length); + assertThat(objects).isNotNull(); + assertThat(objects.length).isEqualTo(0); } @Test public void toObjectArrayWithEmptyPrimitiveArray() { Object[] objects = ObjectUtils.toObjectArray(new byte[] {}); - assertNotNull(objects); - assertEquals(0, objects.length); + assertThat(objects).isNotNull(); + assertThat(objects.length).isEqualTo(0); } @Test @@ -175,7 +170,7 @@ public class ObjectUtilsTests { @Test public void toObjectArrayWithNonPrimitiveArray() { String[] source = new String[] {"Bingo"}; - assertArrayEquals(source, ObjectUtils.toObjectArray(source)); + assertThat(ObjectUtils.toObjectArray(source)).isEqualTo(source); } @Test @@ -183,8 +178,8 @@ public class ObjectUtilsTests { String[] array = new String[] {"foo", "bar"}; String newElement = "baz"; Object[] newArray = ObjectUtils.addObjectToArray(array, newElement); - assertEquals(3, newArray.length); - assertEquals(newElement, newArray[2]); + assertThat(newArray.length).isEqualTo(3); + assertThat(newArray[2]).isEqualTo(newElement); } @Test @@ -192,8 +187,8 @@ public class ObjectUtilsTests { String[] array = new String[0]; String newElement = "foo"; String[] newArray = ObjectUtils.addObjectToArray(array, newElement); - assertEquals(1, newArray.length); - assertEquals(newElement, newArray[0]); + assertThat(newArray.length).isEqualTo(1); + assertThat(newArray[0]).isEqualTo(newElement); } @Test @@ -202,9 +197,9 @@ public class ObjectUtilsTests { String[] array = new String[] {existingElement}; String newElement = "bar"; String[] newArray = ObjectUtils.addObjectToArray(array, newElement); - assertEquals(2, newArray.length); - assertEquals(existingElement, newArray[0]); - assertEquals(newElement, newArray[1]); + assertThat(newArray.length).isEqualTo(2); + assertThat(newArray[0]).isEqualTo(existingElement); + assertThat(newArray[1]).isEqualTo(newElement); } @Test @@ -212,44 +207,44 @@ public class ObjectUtilsTests { String[] array = new String[] {null}; String newElement = "bar"; String[] newArray = ObjectUtils.addObjectToArray(array, newElement); - assertEquals(2, newArray.length); - assertEquals(null, newArray[0]); - assertEquals(newElement, newArray[1]); + assertThat(newArray.length).isEqualTo(2); + assertThat(newArray[0]).isEqualTo(null); + assertThat(newArray[1]).isEqualTo(newElement); } @Test public void addObjectToNullArray() throws Exception { String newElement = "foo"; String[] newArray = ObjectUtils.addObjectToArray(null, newElement); - assertEquals(1, newArray.length); - assertEquals(newElement, newArray[0]); + assertThat(newArray.length).isEqualTo(1); + assertThat(newArray[0]).isEqualTo(newElement); } @Test public void addNullObjectToNullArray() throws Exception { Object[] newArray = ObjectUtils.addObjectToArray(null, null); - assertEquals(1, newArray.length); - assertEquals(null, newArray[0]); + assertThat(newArray.length).isEqualTo(1); + assertThat(newArray[0]).isEqualTo(null); } @Test public void nullSafeEqualsWithArrays() throws Exception { - assertTrue(ObjectUtils.nullSafeEquals(new String[] {"a", "b", "c"}, new String[] {"a", "b", "c"})); - assertTrue(ObjectUtils.nullSafeEquals(new int[] {1, 2, 3}, new int[] {1, 2, 3})); + assertThat(ObjectUtils.nullSafeEquals(new String[] {"a", "b", "c"}, new String[] {"a", "b", "c"})).isTrue(); + assertThat(ObjectUtils.nullSafeEquals(new int[] {1, 2, 3}, new int[] {1, 2, 3})).isTrue(); } @Test @Deprecated public void hashCodeWithBooleanFalse() { int expected = Boolean.FALSE.hashCode(); - assertEquals(expected, ObjectUtils.hashCode(false)); + assertThat(ObjectUtils.hashCode(false)).isEqualTo(expected); } @Test @Deprecated public void hashCodeWithBooleanTrue() { int expected = Boolean.TRUE.hashCode(); - assertEquals(expected, ObjectUtils.hashCode(true)); + assertThat(ObjectUtils.hashCode(true)).isEqualTo(expected); } @Test @@ -257,7 +252,7 @@ public class ObjectUtilsTests { public void hashCodeWithDouble() { double dbl = 9830.43; int expected = (new Double(dbl)).hashCode(); - assertEquals(expected, ObjectUtils.hashCode(dbl)); + assertThat(ObjectUtils.hashCode(dbl)).isEqualTo(expected); } @Test @@ -265,7 +260,7 @@ public class ObjectUtilsTests { public void hashCodeWithFloat() { float flt = 34.8f; int expected = (new Float(flt)).hashCode(); - assertEquals(expected, ObjectUtils.hashCode(flt)); + assertThat(ObjectUtils.hashCode(flt)).isEqualTo(expected); } @Test @@ -273,7 +268,7 @@ public class ObjectUtilsTests { public void hashCodeWithLong() { long lng = 883L; int expected = (new Long(lng)).hashCode(); - assertEquals(expected, ObjectUtils.hashCode(lng)); + assertThat(ObjectUtils.hashCode(lng)).isEqualTo(expected); } @Test @@ -281,112 +276,112 @@ public class ObjectUtilsTests { Object obj = new Object(); String expected = obj.getClass().getName() + "@" + ObjectUtils.getIdentityHexString(obj); String actual = ObjectUtils.identityToString(obj); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void identityToStringWithNullObject() { - assertEquals("", ObjectUtils.identityToString(null)); + assertThat(ObjectUtils.identityToString(null)).isEqualTo(""); } @Test public void isArrayOfPrimitivesWithBooleanArray() { - assertTrue(ClassUtils.isPrimitiveArray(boolean[].class)); + assertThat(ClassUtils.isPrimitiveArray(boolean[].class)).isTrue(); } @Test public void isArrayOfPrimitivesWithObjectArray() { - assertFalse(ClassUtils.isPrimitiveArray(Object[].class)); + assertThat(ClassUtils.isPrimitiveArray(Object[].class)).isFalse(); } @Test public void isArrayOfPrimitivesWithNonArray() { - assertFalse(ClassUtils.isPrimitiveArray(String.class)); + assertThat(ClassUtils.isPrimitiveArray(String.class)).isFalse(); } @Test public void isPrimitiveOrWrapperWithBooleanPrimitiveClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(boolean.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(boolean.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithBooleanWrapperClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(Boolean.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(Boolean.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithBytePrimitiveClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(byte.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(byte.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithByteWrapperClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(Byte.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(Byte.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithCharacterClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(Character.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(Character.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithCharClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(char.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(char.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithDoublePrimitiveClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(double.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(double.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithDoubleWrapperClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(Double.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(Double.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithFloatPrimitiveClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(float.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(float.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithFloatWrapperClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(Float.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(Float.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithIntClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(int.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(int.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithIntegerClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(Integer.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(Integer.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithLongPrimitiveClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(long.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(long.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithLongWrapperClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(Long.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(Long.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithNonPrimitiveOrWrapperClass() { - assertFalse(ClassUtils.isPrimitiveOrWrapper(Object.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(Object.class)).isFalse(); } @Test public void isPrimitiveOrWrapperWithShortPrimitiveClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(short.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(short.class)).isTrue(); } @Test public void isPrimitiveOrWrapperWithShortWrapperClass() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(Short.class)); + assertThat(ClassUtils.isPrimitiveOrWrapper(Short.class)).isTrue(); } @Test @@ -397,12 +392,12 @@ public class ObjectUtilsTests { boolean[] array = {true, false}; int actual = ObjectUtils.nullSafeHashCode(array); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void nullSafeHashCodeWithBooleanArrayEqualToNull() { - assertEquals(0, ObjectUtils.nullSafeHashCode((boolean[]) null)); + assertThat(ObjectUtils.nullSafeHashCode((boolean[]) null)).isEqualTo(0); } @Test @@ -413,12 +408,12 @@ public class ObjectUtilsTests { byte[] array = {8, 10}; int actual = ObjectUtils.nullSafeHashCode(array); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void nullSafeHashCodeWithByteArrayEqualToNull() { - assertEquals(0, ObjectUtils.nullSafeHashCode((byte[]) null)); + assertThat(ObjectUtils.nullSafeHashCode((byte[]) null)).isEqualTo(0); } @Test @@ -429,12 +424,12 @@ public class ObjectUtilsTests { char[] array = {'a', 'E'}; int actual = ObjectUtils.nullSafeHashCode(array); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void nullSafeHashCodeWithCharArrayEqualToNull() { - assertEquals(0, ObjectUtils.nullSafeHashCode((char[]) null)); + assertThat(ObjectUtils.nullSafeHashCode((char[]) null)).isEqualTo(0); } @Test @@ -447,12 +442,12 @@ public class ObjectUtilsTests { double[] array = {8449.65, 9944.923}; int actual = ObjectUtils.nullSafeHashCode(array); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void nullSafeHashCodeWithDoubleArrayEqualToNull() { - assertEquals(0, ObjectUtils.nullSafeHashCode((double[]) null)); + assertThat(ObjectUtils.nullSafeHashCode((double[]) null)).isEqualTo(0); } @Test @@ -463,12 +458,12 @@ public class ObjectUtilsTests { float[] array = {9.6f, 7.4f}; int actual = ObjectUtils.nullSafeHashCode(array); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void nullSafeHashCodeWithFloatArrayEqualToNull() { - assertEquals(0, ObjectUtils.nullSafeHashCode((float[]) null)); + assertThat(ObjectUtils.nullSafeHashCode((float[]) null)).isEqualTo(0); } @Test @@ -479,12 +474,12 @@ public class ObjectUtilsTests { int[] array = {884, 340}; int actual = ObjectUtils.nullSafeHashCode(array); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void nullSafeHashCodeWithIntArrayEqualToNull() { - assertEquals(0, ObjectUtils.nullSafeHashCode((int[]) null)); + assertThat(ObjectUtils.nullSafeHashCode((int[]) null)).isEqualTo(0); } @Test @@ -497,18 +492,18 @@ public class ObjectUtilsTests { long[] array = {7993L, 84320L}; int actual = ObjectUtils.nullSafeHashCode(array); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void nullSafeHashCodeWithLongArrayEqualToNull() { - assertEquals(0, ObjectUtils.nullSafeHashCode((long[]) null)); + assertThat(ObjectUtils.nullSafeHashCode((long[]) null)).isEqualTo(0); } @Test public void nullSafeHashCodeWithObject() { String str = "Luke"; - assertEquals(str.hashCode(), ObjectUtils.nullSafeHashCode(str)); + assertThat(ObjectUtils.nullSafeHashCode(str)).isEqualTo(str.hashCode()); } @Test @@ -519,12 +514,12 @@ public class ObjectUtilsTests { Object[] array = {"Leia", "Han"}; int actual = ObjectUtils.nullSafeHashCode(array); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void nullSafeHashCodeWithObjectArrayEqualToNull() { - assertEquals(0, ObjectUtils.nullSafeHashCode((Object[]) null)); + assertThat(ObjectUtils.nullSafeHashCode((Object[]) null)).isEqualTo(0); } @Test @@ -592,7 +587,7 @@ public class ObjectUtilsTests { @Test public void nullSafeHashCodeWithObjectEqualToNull() { - assertEquals(0, ObjectUtils.nullSafeHashCode((Object) null)); + assertThat(ObjectUtils.nullSafeHashCode((Object) null)).isEqualTo(0); } @Test @@ -603,187 +598,187 @@ public class ObjectUtilsTests { short[] array = {70, 8}; int actual = ObjectUtils.nullSafeHashCode(array); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void nullSafeHashCodeWithShortArrayEqualToNull() { - assertEquals(0, ObjectUtils.nullSafeHashCode((short[]) null)); + assertThat(ObjectUtils.nullSafeHashCode((short[]) null)).isEqualTo(0); } @Test public void nullSafeToStringWithBooleanArray() { boolean[] array = {true, false}; - assertEquals("{true, false}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{true, false}"); } @Test public void nullSafeToStringWithBooleanArrayBeingEmpty() { boolean[] array = {}; - assertEquals("{}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}"); } @Test public void nullSafeToStringWithBooleanArrayEqualToNull() { - assertEquals("null", ObjectUtils.nullSafeToString((boolean[]) null)); + assertThat(ObjectUtils.nullSafeToString((boolean[]) null)).isEqualTo("null"); } @Test public void nullSafeToStringWithByteArray() { byte[] array = {5, 8}; - assertEquals("{5, 8}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{5, 8}"); } @Test public void nullSafeToStringWithByteArrayBeingEmpty() { byte[] array = {}; - assertEquals("{}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}"); } @Test public void nullSafeToStringWithByteArrayEqualToNull() { - assertEquals("null", ObjectUtils.nullSafeToString((byte[]) null)); + assertThat(ObjectUtils.nullSafeToString((byte[]) null)).isEqualTo("null"); } @Test public void nullSafeToStringWithCharArray() { char[] array = {'A', 'B'}; - assertEquals("{'A', 'B'}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{'A', 'B'}"); } @Test public void nullSafeToStringWithCharArrayBeingEmpty() { char[] array = {}; - assertEquals("{}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}"); } @Test public void nullSafeToStringWithCharArrayEqualToNull() { - assertEquals("null", ObjectUtils.nullSafeToString((char[]) null)); + assertThat(ObjectUtils.nullSafeToString((char[]) null)).isEqualTo("null"); } @Test public void nullSafeToStringWithDoubleArray() { double[] array = {8594.93, 8594023.95}; - assertEquals("{8594.93, 8594023.95}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{8594.93, 8594023.95}"); } @Test public void nullSafeToStringWithDoubleArrayBeingEmpty() { double[] array = {}; - assertEquals("{}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}"); } @Test public void nullSafeToStringWithDoubleArrayEqualToNull() { - assertEquals("null", ObjectUtils.nullSafeToString((double[]) null)); + assertThat(ObjectUtils.nullSafeToString((double[]) null)).isEqualTo("null"); } @Test public void nullSafeToStringWithFloatArray() { float[] array = {8.6f, 43.8f}; - assertEquals("{8.6, 43.8}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{8.6, 43.8}"); } @Test public void nullSafeToStringWithFloatArrayBeingEmpty() { float[] array = {}; - assertEquals("{}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}"); } @Test public void nullSafeToStringWithFloatArrayEqualToNull() { - assertEquals("null", ObjectUtils.nullSafeToString((float[]) null)); + assertThat(ObjectUtils.nullSafeToString((float[]) null)).isEqualTo("null"); } @Test public void nullSafeToStringWithIntArray() { int[] array = {9, 64}; - assertEquals("{9, 64}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{9, 64}"); } @Test public void nullSafeToStringWithIntArrayBeingEmpty() { int[] array = {}; - assertEquals("{}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}"); } @Test public void nullSafeToStringWithIntArrayEqualToNull() { - assertEquals("null", ObjectUtils.nullSafeToString((int[]) null)); + assertThat(ObjectUtils.nullSafeToString((int[]) null)).isEqualTo("null"); } @Test public void nullSafeToStringWithLongArray() { long[] array = {434L, 23423L}; - assertEquals("{434, 23423}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{434, 23423}"); } @Test public void nullSafeToStringWithLongArrayBeingEmpty() { long[] array = {}; - assertEquals("{}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}"); } @Test public void nullSafeToStringWithLongArrayEqualToNull() { - assertEquals("null", ObjectUtils.nullSafeToString((long[]) null)); + assertThat(ObjectUtils.nullSafeToString((long[]) null)).isEqualTo("null"); } @Test public void nullSafeToStringWithPlainOldString() { - assertEquals("I shoh love tha taste of mangoes", ObjectUtils.nullSafeToString("I shoh love tha taste of mangoes")); + assertThat(ObjectUtils.nullSafeToString("I shoh love tha taste of mangoes")).isEqualTo("I shoh love tha taste of mangoes"); } @Test public void nullSafeToStringWithObjectArray() { Object[] array = {"Han", Long.valueOf(43)}; - assertEquals("{Han, 43}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{Han, 43}"); } @Test public void nullSafeToStringWithObjectArrayBeingEmpty() { Object[] array = {}; - assertEquals("{}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}"); } @Test public void nullSafeToStringWithObjectArrayEqualToNull() { - assertEquals("null", ObjectUtils.nullSafeToString((Object[]) null)); + assertThat(ObjectUtils.nullSafeToString((Object[]) null)).isEqualTo("null"); } @Test public void nullSafeToStringWithShortArray() { short[] array = {7, 9}; - assertEquals("{7, 9}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{7, 9}"); } @Test public void nullSafeToStringWithShortArrayBeingEmpty() { short[] array = {}; - assertEquals("{}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}"); } @Test public void nullSafeToStringWithShortArrayEqualToNull() { - assertEquals("null", ObjectUtils.nullSafeToString((short[]) null)); + assertThat(ObjectUtils.nullSafeToString((short[]) null)).isEqualTo("null"); } @Test public void nullSafeToStringWithStringArray() { String[] array = {"Luke", "Anakin"}; - assertEquals("{Luke, Anakin}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{Luke, Anakin}"); } @Test public void nullSafeToStringWithStringArrayBeingEmpty() { String[] array = {}; - assertEquals("{}", ObjectUtils.nullSafeToString(array)); + assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo("{}"); } @Test public void nullSafeToStringWithStringArrayEqualToNull() { - assertEquals("null", ObjectUtils.nullSafeToString((String[]) null)); + assertThat(ObjectUtils.nullSafeToString((String[]) null)).isEqualTo("null"); } @Test @@ -813,8 +808,8 @@ public class ObjectUtilsTests { private void assertEqualHashCodes(int expected, Object array) { int actual = ObjectUtils.nullSafeHashCode(array); - assertEquals(expected, actual); - assertTrue(array.hashCode() != actual); + assertThat(actual).isEqualTo(expected); + assertThat(array.hashCode() != actual).isTrue(); } diff --git a/spring-core/src/test/java/org/springframework/util/PatternMatchUtilsTests.java b/spring-core/src/test/java/org/springframework/util/PatternMatchUtilsTests.java index c130afc684a..a3aa5b4c6fc 100644 --- a/spring-core/src/test/java/org/springframework/util/PatternMatchUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/PatternMatchUtilsTests.java @@ -18,7 +18,7 @@ package org.springframework.util; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -28,8 +28,8 @@ public class PatternMatchUtilsTests { @Test public void testTrivial() { - assertEquals(false, PatternMatchUtils.simpleMatch((String) null, "")); - assertEquals(false, PatternMatchUtils.simpleMatch("1", null)); + assertThat(PatternMatchUtils.simpleMatch((String) null, "")).isEqualTo(false); + assertThat(PatternMatchUtils.simpleMatch("1", null)).isEqualTo(false); doTest("*", "123", true); doTest("123", "123", true); } @@ -100,7 +100,7 @@ public class PatternMatchUtilsTests { } private void doTest(String pattern, String str, boolean shouldMatch) { - assertEquals(shouldMatch, PatternMatchUtils.simpleMatch(pattern, str)); + assertThat(PatternMatchUtils.simpleMatch(pattern, str)).isEqualTo(shouldMatch); } } diff --git a/spring-core/src/test/java/org/springframework/util/PropertiesPersisterTests.java b/spring-core/src/test/java/org/springframework/util/PropertiesPersisterTests.java index 592c646d752..a55b45565ce 100644 --- a/spring-core/src/test/java/org/springframework/util/PropertiesPersisterTests.java +++ b/spring-core/src/test/java/org/springframework/util/PropertiesPersisterTests.java @@ -25,8 +25,7 @@ import java.util.Properties; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -107,8 +106,8 @@ public class PropertiesPersisterTests { else { persister.load(props, new ByteArrayInputStream(propString.getBytes())); } - assertEquals("message1", props.getProperty("code1")); - assertEquals("message2", props.getProperty("code2")); + assertThat(props.getProperty("code1")).isEqualTo("message1"); + assertThat(props.getProperty("code2")).isEqualTo("message2"); return props; } @@ -126,10 +125,10 @@ public class PropertiesPersisterTests { propCopy = new String(propOut.toByteArray()); } if (header != null) { - assertTrue(propCopy.contains(header)); + assertThat(propCopy.contains(header)).isTrue(); } - assertTrue(propCopy.contains("\ncode1=message1")); - assertTrue(propCopy.contains("\ncode2=message2")); + assertThat(propCopy.contains("\ncode1=message1")).isTrue(); + assertThat(propCopy.contains("\ncode2=message2")).isTrue(); return propCopy; } diff --git a/spring-core/src/test/java/org/springframework/util/PropertyPlaceholderHelperTests.java b/spring-core/src/test/java/org/springframework/util/PropertyPlaceholderHelperTests.java index 9c59596695a..58951b8a98b 100644 --- a/spring-core/src/test/java/org/springframework/util/PropertyPlaceholderHelperTests.java +++ b/spring-core/src/test/java/org/springframework/util/PropertyPlaceholderHelperTests.java @@ -20,8 +20,10 @@ import java.util.Properties; import org.junit.Test; +import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver; + +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @author Rob Harrop @@ -36,7 +38,7 @@ public class PropertyPlaceholderHelperTests { Properties props = new Properties(); props.setProperty("foo", "bar"); - assertEquals("foo=bar", this.helper.replacePlaceholders(text, props)); + assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar"); } @Test @@ -46,7 +48,7 @@ public class PropertyPlaceholderHelperTests { props.setProperty("foo", "bar"); props.setProperty("bar", "baz"); - assertEquals("foo=bar,bar=baz", this.helper.replacePlaceholders(text, props)); + assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar,bar=baz"); } @Test @@ -56,7 +58,7 @@ public class PropertyPlaceholderHelperTests { props.setProperty("bar", "${baz}"); props.setProperty("baz", "bar"); - assertEquals("foo=bar", this.helper.replacePlaceholders(text, props)); + assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar"); } @Test @@ -66,7 +68,7 @@ public class PropertyPlaceholderHelperTests { props.setProperty("bar", "bar"); props.setProperty("inner", "ar"); - assertEquals("foo=bar", this.helper.replacePlaceholders(text, props)); + assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar"); text = "${top}"; props = new Properties(); @@ -75,25 +77,21 @@ public class PropertyPlaceholderHelperTests { props.setProperty("differentiator", "first"); props.setProperty("first.grandchild", "actualValue"); - assertEquals("actualValue+actualValue", this.helper.replacePlaceholders(text, props)); + assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("actualValue+actualValue"); } @Test public void testWithResolver() { String text = "foo=${foo}"; + PlaceholderResolver resolver = new PlaceholderResolver() { - assertEquals("foo=bar", - this.helper.replacePlaceholders(text, new PropertyPlaceholderHelper.PlaceholderResolver() { - @Override - public String resolvePlaceholder(String placeholderName) { - if ("foo".equals(placeholderName)) { - return "bar"; - } - else { - return null; - } - } - })); + @Override + public String resolvePlaceholder(String placeholderName) { + return "foo".equals(placeholderName) ? "bar" : null; + } + + }; + assertThat(this.helper.replacePlaceholders(text, resolver)).isEqualTo("foo=bar"); } @Test @@ -102,7 +100,7 @@ public class PropertyPlaceholderHelperTests { Properties props = new Properties(); props.setProperty("foo", "bar"); - assertEquals("foo=bar,bar=${bar}", this.helper.replacePlaceholders(text, props)); + assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar,bar=${bar}"); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java index ba18adc9fdf..38e2d9ed1a8 100644 --- a/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java @@ -33,11 +33,6 @@ import org.springframework.tests.sample.objects.TestObject; import static org.assertj.core.api.Assertions.assertThat; 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; -import static org.junit.Assert.assertTrue; /** * @author Rob Harrop @@ -50,22 +45,22 @@ public class ReflectionUtilsTests { @Test public void findField() { Field field = ReflectionUtils.findField(TestObjectSubclassWithPublicField.class, "publicField", String.class); - assertNotNull(field); - assertEquals("publicField", field.getName()); - assertEquals(String.class, field.getType()); - assertTrue("Field should be public.", Modifier.isPublic(field.getModifiers())); + assertThat(field).isNotNull(); + assertThat(field.getName()).isEqualTo("publicField"); + assertThat(field.getType()).isEqualTo(String.class); + assertThat(Modifier.isPublic(field.getModifiers())).as("Field should be public.").isTrue(); field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "prot", String.class); - assertNotNull(field); - assertEquals("prot", field.getName()); - assertEquals(String.class, field.getType()); - assertTrue("Field should be protected.", Modifier.isProtected(field.getModifiers())); + assertThat(field).isNotNull(); + assertThat(field.getName()).isEqualTo("prot"); + assertThat(field.getType()).isEqualTo(String.class); + assertThat(Modifier.isProtected(field.getModifiers())).as("Field should be protected.").isTrue(); field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class); - assertNotNull(field); - assertEquals("name", field.getName()); - assertEquals(String.class, field.getType()); - assertTrue("Field should be private.", Modifier.isPrivate(field.getModifiers())); + assertThat(field).isNotNull(); + assertThat(field.getName()).isEqualTo("name"); + assertThat(field.getType()).isEqualTo(String.class); + assertThat(Modifier.isPrivate(field.getModifiers())).as("Field should be private.").isTrue(); } @Test @@ -76,11 +71,11 @@ public class ReflectionUtilsTests { ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, testBean, "FooBar"); - assertNotNull(testBean.getName()); - assertEquals("FooBar", testBean.getName()); + assertThat(testBean.getName()).isNotNull(); + assertThat(testBean.getName()).isEqualTo("FooBar"); ReflectionUtils.setField(field, testBean, null); - assertNull(testBean.getName()); + assertThat((Object) testBean.getName()).isNull(); } @Test @@ -94,26 +89,26 @@ public class ReflectionUtilsTests { Method setName = TestObject.class.getMethod("setName", String.class); Object name = ReflectionUtils.invokeMethod(getName, bean); - assertEquals("Incorrect name returned", rob, name); + assertThat(name).as("Incorrect name returned").isEqualTo(rob); String juergen = "Juergen Hoeller"; ReflectionUtils.invokeMethod(setName, bean, juergen); - assertEquals("Incorrect name set", juergen, bean.getName()); + assertThat(bean.getName()).as("Incorrect name set").isEqualTo(juergen); } @Test public void declaresException() throws Exception { Method remoteExMethod = A.class.getDeclaredMethod("foo", Integer.class); - assertTrue(ReflectionUtils.declaresException(remoteExMethod, RemoteException.class)); - assertTrue(ReflectionUtils.declaresException(remoteExMethod, ConnectException.class)); - assertFalse(ReflectionUtils.declaresException(remoteExMethod, NoSuchMethodException.class)); - assertFalse(ReflectionUtils.declaresException(remoteExMethod, Exception.class)); + assertThat(ReflectionUtils.declaresException(remoteExMethod, RemoteException.class)).isTrue(); + assertThat(ReflectionUtils.declaresException(remoteExMethod, ConnectException.class)).isTrue(); + assertThat(ReflectionUtils.declaresException(remoteExMethod, NoSuchMethodException.class)).isFalse(); + assertThat(ReflectionUtils.declaresException(remoteExMethod, Exception.class)).isFalse(); Method illegalExMethod = B.class.getDeclaredMethod("bar", String.class); - assertTrue(ReflectionUtils.declaresException(illegalExMethod, IllegalArgumentException.class)); - assertTrue(ReflectionUtils.declaresException(illegalExMethod, NumberFormatException.class)); - assertFalse(ReflectionUtils.declaresException(illegalExMethod, IllegalStateException.class)); - assertFalse(ReflectionUtils.declaresException(illegalExMethod, Exception.class)); + assertThat(ReflectionUtils.declaresException(illegalExMethod, IllegalArgumentException.class)).isTrue(); + assertThat(ReflectionUtils.declaresException(illegalExMethod, NumberFormatException.class)).isTrue(); + assertThat(ReflectionUtils.declaresException(illegalExMethod, IllegalStateException.class)).isFalse(); + assertThat(ReflectionUtils.declaresException(illegalExMethod, Exception.class)).isFalse(); } @Test @@ -157,8 +152,8 @@ public class ReflectionUtilsTests { testValidCopy(src, dest); // Check subclass fields were copied - assertEquals(src.magic, dest.magic); - assertEquals(src.prot, dest.prot); + assertThat(dest.magic).isEqualTo(src.magic); + assertThat(dest.prot).isEqualTo(src.prot); } @Test @@ -168,7 +163,7 @@ public class ReflectionUtilsTests { dest.magic = 11; testValidCopy(src, dest); // Should have left this one alone - assertEquals(11, dest.magic); + assertThat(dest.magic).isEqualTo(11); } @Test @@ -183,11 +178,11 @@ public class ReflectionUtilsTests { src.setName("freddie"); src.setAge(15); src.setSpouse(new TestObject()); - assertFalse(src.getAge() == dest.getAge()); + assertThat(src.getAge() == dest.getAge()).isFalse(); ReflectionUtils.shallowCopyFieldState(src, dest); - assertEquals(src.getAge(), dest.getAge()); - assertEquals(src.getSpouse(), dest.getSpouse()); + assertThat(dest.getAge()).isEqualTo(src.getAge()); + assertThat(dest.getSpouse()).isEqualTo(src.getSpouse()); } @Test @@ -199,11 +194,11 @@ public class ReflectionUtilsTests { return Modifier.isProtected(m.getModifiers()); } }); - assertFalse(mc.getMethodNames().isEmpty()); - assertTrue("Must find protected method on Object", mc.getMethodNames().contains("clone")); - assertTrue("Must find protected method on Object", mc.getMethodNames().contains("finalize")); - assertFalse("Public, not protected", mc.getMethodNames().contains("hashCode")); - assertFalse("Public, not protected", mc.getMethodNames().contains("absquatulate")); + assertThat(mc.getMethodNames().isEmpty()).isFalse(); + assertThat(mc.getMethodNames().contains("clone")).as("Must find protected method on Object").isTrue(); + assertThat(mc.getMethodNames().contains("finalize")).as("Must find protected method on Object").isTrue(); + assertThat(mc.getMethodNames().contains("hashCode")).as("Public, not protected").isFalse(); + assertThat(mc.getMethodNames().contains("absquatulate")).as("Public, not protected").isFalse(); } @Test @@ -216,20 +211,20 @@ public class ReflectionUtilsTests { ++absquatulateCount; } } - assertEquals("Found 2 absquatulates", 2, absquatulateCount); + assertThat(absquatulateCount).as("Found 2 absquatulates").isEqualTo(2); } @Test public void findMethod() throws Exception { - assertNotNull(ReflectionUtils.findMethod(B.class, "bar", String.class)); - assertNotNull(ReflectionUtils.findMethod(B.class, "foo", Integer.class)); - assertNotNull(ReflectionUtils.findMethod(B.class, "getClass")); + assertThat(ReflectionUtils.findMethod(B.class, "bar", String.class)).isNotNull(); + assertThat(ReflectionUtils.findMethod(B.class, "foo", Integer.class)).isNotNull(); + assertThat(ReflectionUtils.findMethod(B.class, "getClass")).isNotNull(); } @Ignore("[SPR-8644] findMethod() does not currently support var-args") @Test public void findMethodWithVarArgs() throws Exception { - assertNotNull(ReflectionUtils.findMethod(B.class, "add", int.class, int.class, int.class)); + assertThat(ReflectionUtils.findMethod(B.class, "add", int.class, int.class, int.class)).isNotNull(); } @Test @@ -260,14 +255,14 @@ public class ReflectionUtilsTests { public void m1$1() { } } - assertTrue(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$123"))); - assertTrue(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$0"))); - assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$$0"))); - assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$"))); - assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1"))); - assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1"))); - assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$"))); - assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$1"))); + assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$123"))).isTrue(); + assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$0"))).isTrue(); + assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$$0"))).isFalse(); + assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$"))).isFalse(); + assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1"))).isFalse(); + assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1"))).isFalse(); + assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$"))).isFalse(); + assertThat(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$1"))).isFalse(); } @Test @@ -326,8 +321,8 @@ public class ReflectionUtilsTests { } } assertThat(m1MethodCount).isEqualTo(1); - assertTrue(ObjectUtils.containsElement(methods, Leaf.class.getMethod("m1"))); - assertFalse(ObjectUtils.containsElement(methods, Parent.class.getMethod("m1"))); + assertThat(ObjectUtils.containsElement(methods, Leaf.class.getMethod("m1"))).isTrue(); + assertThat(ObjectUtils.containsElement(methods, Parent.class.getMethod("m1"))).isFalse(); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/ResizableByteArrayOutputStreamTests.java b/spring-core/src/test/java/org/springframework/util/ResizableByteArrayOutputStreamTests.java index 34349f93e47..e6ed79a4d4f 100644 --- a/spring-core/src/test/java/org/springframework/util/ResizableByteArrayOutputStreamTests.java +++ b/spring-core/src/test/java/org/springframework/util/ResizableByteArrayOutputStreamTests.java @@ -19,9 +19,8 @@ package org.springframework.util; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; /** * @author Brian Clozel @@ -45,29 +44,29 @@ public class ResizableByteArrayOutputStreamTests { @Test public void resize() throws Exception { - assertEquals(INITIAL_CAPACITY, this.baos.capacity()); + assertThat(this.baos.capacity()).isEqualTo(INITIAL_CAPACITY); this.baos.write(helloBytes); int size = 64; this.baos.resize(size); - assertEquals(size, this.baos.capacity()); + assertThat(this.baos.capacity()).isEqualTo(size); assertByteArrayEqualsString(this.baos); } @Test public void autoGrow() { - assertEquals(INITIAL_CAPACITY, this.baos.capacity()); + assertThat(this.baos.capacity()).isEqualTo(INITIAL_CAPACITY); for (int i = 0; i < 129; i++) { this.baos.write(0); } - assertEquals(256, this.baos.capacity()); + assertThat(this.baos.capacity()).isEqualTo(256); } @Test public void grow() throws Exception { - assertEquals(INITIAL_CAPACITY, this.baos.capacity()); + assertThat(this.baos.capacity()).isEqualTo(INITIAL_CAPACITY); this.baos.write(helloBytes); this.baos.grow(1000); - assertEquals(this.helloBytes.length + 1000, this.baos.capacity()); + assertThat(this.baos.capacity()).isEqualTo((this.helloBytes.length + 1000)); assertByteArrayEqualsString(this.baos); } @@ -86,7 +85,7 @@ public class ResizableByteArrayOutputStreamTests { private void assertByteArrayEqualsString(ResizableByteArrayOutputStream actual) { - assertArrayEquals(helloBytes, actual.toByteArray()); + assertThat(actual.toByteArray()).isEqualTo(helloBytes); } } diff --git a/spring-core/src/test/java/org/springframework/util/ResourceUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ResourceUtilsTests.java index af060de1391..daccbf6ef24 100644 --- a/spring-core/src/test/java/org/springframework/util/ResourceUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ResourceUtilsTests.java @@ -23,9 +23,7 @@ import java.net.URLStreamHandler; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -34,58 +32,40 @@ public class ResourceUtilsTests { @Test public void isJarURL() throws Exception { - assertTrue(ResourceUtils.isJarURL(new URL("jar:file:myjar.jar!/mypath"))); - assertTrue(ResourceUtils.isJarURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler()))); - assertTrue(ResourceUtils.isJarURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler()))); - assertTrue(ResourceUtils.isJarURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/mypath", new DummyURLStreamHandler()))); - assertFalse(ResourceUtils.isJarURL(new URL("file:myjar.jar"))); - assertFalse(ResourceUtils.isJarURL(new URL("http:myserver/myjar.jar"))); + assertThat(ResourceUtils.isJarURL(new URL("jar:file:myjar.jar!/mypath"))).isTrue(); + assertThat(ResourceUtils.isJarURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isTrue(); + assertThat(ResourceUtils.isJarURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isTrue(); + assertThat(ResourceUtils.isJarURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/mypath", new DummyURLStreamHandler()))).isTrue(); + assertThat(ResourceUtils.isJarURL(new URL("file:myjar.jar"))).isFalse(); + assertThat(ResourceUtils.isJarURL(new URL("http:myserver/myjar.jar"))).isFalse(); } @Test public void extractJarFileURL() throws Exception { - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractJarFileURL(new URL("jar:file:myjar.jar!/mypath"))); - assertEquals(new URL("file:/myjar.jar"), - ResourceUtils.extractJarFileURL(new URL(null, "jar:myjar.jar!/mypath", new DummyURLStreamHandler()))); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractJarFileURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler()))); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractJarFileURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler()))); + assertThat(ResourceUtils.extractJarFileURL(new URL("jar:file:myjar.jar!/mypath"))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractJarFileURL(new URL(null, "jar:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:/myjar.jar")); + assertThat(ResourceUtils.extractJarFileURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractJarFileURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar")); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractJarFileURL(new URL("file:myjar.jar"))); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractJarFileURL(new URL("jar:file:myjar.jar!/"))); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractJarFileURL(new URL(null, "zip:file:myjar.jar!/", new DummyURLStreamHandler()))); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractJarFileURL(new URL(null, "wsjar:file:myjar.jar!/", new DummyURLStreamHandler()))); + assertThat(ResourceUtils.extractJarFileURL(new URL("file:myjar.jar"))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractJarFileURL(new URL("jar:file:myjar.jar!/"))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractJarFileURL(new URL(null, "zip:file:myjar.jar!/", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractJarFileURL(new URL(null, "wsjar:file:myjar.jar!/", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar")); } @Test public void extractArchiveURL() throws Exception { - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractArchiveURL(new URL("jar:file:myjar.jar!/mypath"))); - assertEquals(new URL("file:/myjar.jar"), - ResourceUtils.extractArchiveURL(new URL(null, "jar:myjar.jar!/mypath", new DummyURLStreamHandler()))); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractArchiveURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler()))); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractArchiveURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler()))); - assertEquals(new URL("file:mywar.war"), - ResourceUtils.extractArchiveURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/mypath", new DummyURLStreamHandler()))); + assertThat(ResourceUtils.extractArchiveURL(new URL("jar:file:myjar.jar!/mypath"))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractArchiveURL(new URL(null, "jar:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:/myjar.jar")); + assertThat(ResourceUtils.extractArchiveURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractArchiveURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractArchiveURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/mypath", new DummyURLStreamHandler()))).isEqualTo(new URL("file:mywar.war")); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractArchiveURL(new URL("file:myjar.jar"))); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractArchiveURL(new URL("jar:file:myjar.jar!/"))); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractArchiveURL(new URL(null, "zip:file:myjar.jar!/", new DummyURLStreamHandler()))); - assertEquals(new URL("file:myjar.jar"), - ResourceUtils.extractArchiveURL(new URL(null, "wsjar:file:myjar.jar!/", new DummyURLStreamHandler()))); - assertEquals(new URL("file:mywar.war"), - ResourceUtils.extractArchiveURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/", new DummyURLStreamHandler()))); + assertThat(ResourceUtils.extractArchiveURL(new URL("file:myjar.jar"))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractArchiveURL(new URL("jar:file:myjar.jar!/"))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractArchiveURL(new URL(null, "zip:file:myjar.jar!/", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractArchiveURL(new URL(null, "wsjar:file:myjar.jar!/", new DummyURLStreamHandler()))).isEqualTo(new URL("file:myjar.jar")); + assertThat(ResourceUtils.extractArchiveURL(new URL(null, "jar:war:file:mywar.war*/myjar.jar!/", new DummyURLStreamHandler()))).isEqualTo(new URL("file:mywar.war")); } diff --git a/spring-core/src/test/java/org/springframework/util/SerializationUtilsTests.java b/spring-core/src/test/java/org/springframework/util/SerializationUtilsTests.java index 35b2399f8fe..158f97ada2e 100644 --- a/spring-core/src/test/java/org/springframework/util/SerializationUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/SerializationUtilsTests.java @@ -20,10 +20,9 @@ import java.math.BigInteger; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * Test for static utility to help with serialization. @@ -40,7 +39,7 @@ public class SerializationUtilsTests { @Test public void serializeCycleSunnyDay() throws Exception { - assertEquals("foo", SerializationUtils.deserialize(SerializationUtils.serialize("foo"))); + assertThat(SerializationUtils.deserialize(SerializationUtils.serialize("foo"))).isEqualTo("foo"); } @Test @@ -64,12 +63,12 @@ public class SerializationUtilsTests { @Test public void serializeNull() throws Exception { - assertNull(SerializationUtils.serialize(null)); + assertThat(SerializationUtils.serialize(null)).isNull(); } @Test public void deserializeNull() throws Exception { - assertNull(SerializationUtils.deserialize(null)); + assertThat(SerializationUtils.deserialize(null)).isNull(); } } diff --git a/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java b/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java index 2b0a5fc44aa..23c30d43869 100644 --- a/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java @@ -24,10 +24,9 @@ import javax.net.ServerSocketFactory; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.springframework.util.SocketUtils.PORT_RANGE_MAX; import static org.springframework.util.SocketUtils.PORT_RANGE_MIN; @@ -71,7 +70,7 @@ public class SocketUtilsTests { public void findAvailableTcpPortWithMinPortEqualToMaxPort() { int minMaxPort = SocketUtils.findAvailableTcpPort(); int port = SocketUtils.findAvailableTcpPort(minMaxPort, minMaxPort); - assertEquals(minMaxPort, port); + assertThat(port).isEqualTo(minMaxPort); } @Test @@ -230,12 +229,12 @@ public class SocketUtilsTests { assertAvailablePorts(ports, numRequested, minPort, maxPort); } private void assertPortInRange(int port, int minPort, int maxPort) { - assertTrue("port [" + port + "] >= " + minPort, port >= minPort); - assertTrue("port [" + port + "] <= " + maxPort, port <= maxPort); + assertThat(port >= minPort).as("port [" + port + "] >= " + minPort).isTrue(); + assertThat(port <= maxPort).as("port [" + port + "] <= " + maxPort).isTrue(); } private void assertAvailablePorts(SortedSet ports, int numRequested, int minPort, int maxPort) { - assertEquals("number of ports requested", numRequested, ports.size()); + assertThat(ports.size()).as("number of ports requested").isEqualTo(numRequested); for (int port : ports) { assertPortInRange(port, minPort, maxPort); } diff --git a/spring-core/src/test/java/org/springframework/util/StopWatchTests.java b/spring-core/src/test/java/org/springframework/util/StopWatchTests.java index 074a44107d5..dbe14bd8f65 100644 --- a/spring-core/src/test/java/org/springframework/util/StopWatchTests.java +++ b/spring-core/src/test/java/org/springframework/util/StopWatchTests.java @@ -18,11 +18,9 @@ package org.springframework.util; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -42,11 +40,11 @@ public class StopWatchTests { String name1 = "Task 1"; String name2 = "Task 2"; - assertFalse(sw.isRunning()); + assertThat(sw.isRunning()).isFalse(); sw.start(name1); Thread.sleep(int1); - assertTrue(sw.isRunning()); - assertEquals(name1, sw.currentTaskName()); + assertThat(sw.isRunning()).isTrue(); + assertThat(sw.currentTaskName()).isEqualTo(name1); sw.stop(); // TODO are timings off in JUnit? Why do these assertions sometimes fail @@ -65,22 +63,22 @@ public class StopWatchTests { // assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 // + int2 + fudgeFactor); - assertTrue(sw.getTaskCount() == 2); + assertThat(sw.getTaskCount() == 2).isTrue(); String pp = sw.prettyPrint(); - assertTrue(pp.contains(name1)); - assertTrue(pp.contains(name2)); + assertThat(pp.contains(name1)).isTrue(); + assertThat(pp.contains(name2)).isTrue(); StopWatch.TaskInfo[] tasks = sw.getTaskInfo(); - assertTrue(tasks.length == 2); - assertTrue(tasks[0].getTaskName().equals(name1)); - assertTrue(tasks[1].getTaskName().equals(name2)); + assertThat(tasks.length == 2).isTrue(); + assertThat(tasks[0].getTaskName().equals(name1)).isTrue(); + assertThat(tasks[1].getTaskName().equals(name2)).isTrue(); String toString = sw.toString(); - assertTrue(toString.contains(id)); - assertTrue(toString.contains(name1)); - assertTrue(toString.contains(name2)); + assertThat(toString.contains(id)).isTrue(); + assertThat(toString.contains(name1)).isTrue(); + assertThat(toString.contains(name2)).isTrue(); - assertEquals(id, sw.getId()); + assertThat(sw.getId()).isEqualTo(id); } @Test @@ -91,10 +89,10 @@ public class StopWatchTests { String name1 = "Task 1"; String name2 = "Task 2"; - assertFalse(sw.isRunning()); + assertThat(sw.isRunning()).isFalse(); sw.start(name1); Thread.sleep(int1); - assertTrue(sw.isRunning()); + assertThat(sw.isRunning()).isTrue(); sw.stop(); // TODO are timings off in JUnit? Why do these assertions sometimes fail @@ -113,13 +111,13 @@ public class StopWatchTests { // assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 // + int2 + fudgeFactor); - assertTrue(sw.getTaskCount() == 2); + assertThat(sw.getTaskCount() == 2).isTrue(); String pp = sw.prettyPrint(); - assertTrue(pp.contains("kept")); + assertThat(pp.contains("kept")).isTrue(); String toString = sw.toString(); - assertFalse(toString.contains(name1)); - assertFalse(toString.contains(name2)); + assertThat(toString.contains(name1)).isFalse(); + assertThat(toString.contains(name2)).isFalse(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy( sw::getTaskInfo); @@ -142,7 +140,7 @@ public class StopWatchTests { sw.start(""); sw.stop(); sw.start(""); - assertTrue(sw.isRunning()); + assertThat(sw.isRunning()).isTrue(); assertThatIllegalStateException().isThrownBy(() -> sw.start("")); } diff --git a/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java b/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java index 387d35dde7e..fadb7542ff7 100644 --- a/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java @@ -22,14 +22,8 @@ import java.util.Properties; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -41,189 +35,179 @@ public class StringUtilsTests { @Test public void testHasTextBlank() { String blank = " "; - assertEquals(false, StringUtils.hasText(blank)); + assertThat(StringUtils.hasText(blank)).isEqualTo(false); } @Test public void testHasTextNullEmpty() { - assertEquals(false, StringUtils.hasText(null)); - assertEquals(false, StringUtils.hasText("")); + assertThat(StringUtils.hasText(null)).isEqualTo(false); + assertThat(StringUtils.hasText("")).isEqualTo(false); } @Test public void testHasTextValid() { - assertEquals(true, StringUtils.hasText("t")); + assertThat(StringUtils.hasText("t")).isEqualTo(true); } @Test public void testContainsWhitespace() { - assertFalse(StringUtils.containsWhitespace(null)); - assertFalse(StringUtils.containsWhitespace("")); - assertFalse(StringUtils.containsWhitespace("a")); - assertFalse(StringUtils.containsWhitespace("abc")); - assertTrue(StringUtils.containsWhitespace(" ")); - assertTrue(StringUtils.containsWhitespace(" a")); - assertTrue(StringUtils.containsWhitespace("abc ")); - assertTrue(StringUtils.containsWhitespace("a b")); - assertTrue(StringUtils.containsWhitespace("a b")); + assertThat(StringUtils.containsWhitespace(null)).isFalse(); + assertThat(StringUtils.containsWhitespace("")).isFalse(); + assertThat(StringUtils.containsWhitespace("a")).isFalse(); + assertThat(StringUtils.containsWhitespace("abc")).isFalse(); + assertThat(StringUtils.containsWhitespace(" ")).isTrue(); + assertThat(StringUtils.containsWhitespace(" a")).isTrue(); + assertThat(StringUtils.containsWhitespace("abc ")).isTrue(); + assertThat(StringUtils.containsWhitespace("a b")).isTrue(); + assertThat(StringUtils.containsWhitespace("a b")).isTrue(); } @Test public void testTrimWhitespace() { - assertEquals(null, StringUtils.trimWhitespace(null)); - assertEquals("", StringUtils.trimWhitespace("")); - assertEquals("", StringUtils.trimWhitespace(" ")); - assertEquals("", StringUtils.trimWhitespace("\t")); - assertEquals("a", StringUtils.trimWhitespace(" a")); - assertEquals("a", StringUtils.trimWhitespace("a ")); - assertEquals("a", StringUtils.trimWhitespace(" a ")); - assertEquals("a b", StringUtils.trimWhitespace(" a b ")); - assertEquals("a b c", StringUtils.trimWhitespace(" a b c ")); + assertThat(StringUtils.trimWhitespace(null)).isEqualTo(null); + assertThat(StringUtils.trimWhitespace("")).isEqualTo(""); + assertThat(StringUtils.trimWhitespace(" ")).isEqualTo(""); + assertThat(StringUtils.trimWhitespace("\t")).isEqualTo(""); + assertThat(StringUtils.trimWhitespace(" a")).isEqualTo("a"); + assertThat(StringUtils.trimWhitespace("a ")).isEqualTo("a"); + assertThat(StringUtils.trimWhitespace(" a ")).isEqualTo("a"); + assertThat(StringUtils.trimWhitespace(" a b ")).isEqualTo("a b"); + assertThat(StringUtils.trimWhitespace(" a b c ")).isEqualTo("a b c"); } @Test public void testTrimAllWhitespace() { - assertEquals("", StringUtils.trimAllWhitespace("")); - assertEquals("", StringUtils.trimAllWhitespace(" ")); - assertEquals("", StringUtils.trimAllWhitespace("\t")); - assertEquals("a", StringUtils.trimAllWhitespace(" a")); - assertEquals("a", StringUtils.trimAllWhitespace("a ")); - assertEquals("a", StringUtils.trimAllWhitespace(" a ")); - assertEquals("ab", StringUtils.trimAllWhitespace(" a b ")); - assertEquals("abc", StringUtils.trimAllWhitespace(" a b c ")); + assertThat(StringUtils.trimAllWhitespace("")).isEqualTo(""); + assertThat(StringUtils.trimAllWhitespace(" ")).isEqualTo(""); + assertThat(StringUtils.trimAllWhitespace("\t")).isEqualTo(""); + assertThat(StringUtils.trimAllWhitespace(" a")).isEqualTo("a"); + assertThat(StringUtils.trimAllWhitespace("a ")).isEqualTo("a"); + assertThat(StringUtils.trimAllWhitespace(" a ")).isEqualTo("a"); + assertThat(StringUtils.trimAllWhitespace(" a b ")).isEqualTo("ab"); + assertThat(StringUtils.trimAllWhitespace(" a b c ")).isEqualTo("abc"); } @Test public void testTrimLeadingWhitespace() { - assertEquals(null, StringUtils.trimLeadingWhitespace(null)); - assertEquals("", StringUtils.trimLeadingWhitespace("")); - assertEquals("", StringUtils.trimLeadingWhitespace(" ")); - assertEquals("", StringUtils.trimLeadingWhitespace("\t")); - assertEquals("a", StringUtils.trimLeadingWhitespace(" a")); - assertEquals("a ", StringUtils.trimLeadingWhitespace("a ")); - assertEquals("a ", StringUtils.trimLeadingWhitespace(" a ")); - assertEquals("a b ", StringUtils.trimLeadingWhitespace(" a b ")); - assertEquals("a b c ", StringUtils.trimLeadingWhitespace(" a b c ")); + assertThat(StringUtils.trimLeadingWhitespace(null)).isEqualTo(null); + assertThat(StringUtils.trimLeadingWhitespace("")).isEqualTo(""); + assertThat(StringUtils.trimLeadingWhitespace(" ")).isEqualTo(""); + assertThat(StringUtils.trimLeadingWhitespace("\t")).isEqualTo(""); + assertThat(StringUtils.trimLeadingWhitespace(" a")).isEqualTo("a"); + assertThat(StringUtils.trimLeadingWhitespace("a ")).isEqualTo("a "); + assertThat(StringUtils.trimLeadingWhitespace(" a ")).isEqualTo("a "); + assertThat(StringUtils.trimLeadingWhitespace(" a b ")).isEqualTo("a b "); + assertThat(StringUtils.trimLeadingWhitespace(" a b c ")).isEqualTo("a b c "); } @Test public void testTrimTrailingWhitespace() { - assertEquals(null, StringUtils.trimTrailingWhitespace(null)); - assertEquals("", StringUtils.trimTrailingWhitespace("")); - assertEquals("", StringUtils.trimTrailingWhitespace(" ")); - assertEquals("", StringUtils.trimTrailingWhitespace("\t")); - assertEquals("a", StringUtils.trimTrailingWhitespace("a ")); - assertEquals(" a", StringUtils.trimTrailingWhitespace(" a")); - assertEquals(" a", StringUtils.trimTrailingWhitespace(" a ")); - assertEquals(" a b", StringUtils.trimTrailingWhitespace(" a b ")); - assertEquals(" a b c", StringUtils.trimTrailingWhitespace(" a b c ")); + assertThat(StringUtils.trimTrailingWhitespace(null)).isEqualTo(null); + assertThat(StringUtils.trimTrailingWhitespace("")).isEqualTo(""); + assertThat(StringUtils.trimTrailingWhitespace(" ")).isEqualTo(""); + assertThat(StringUtils.trimTrailingWhitespace("\t")).isEqualTo(""); + assertThat(StringUtils.trimTrailingWhitespace("a ")).isEqualTo("a"); + assertThat(StringUtils.trimTrailingWhitespace(" a")).isEqualTo(" a"); + assertThat(StringUtils.trimTrailingWhitespace(" a ")).isEqualTo(" a"); + assertThat(StringUtils.trimTrailingWhitespace(" a b ")).isEqualTo(" a b"); + assertThat(StringUtils.trimTrailingWhitespace(" a b c ")).isEqualTo(" a b c"); } @Test public void testTrimLeadingCharacter() { - assertEquals(null, StringUtils.trimLeadingCharacter(null, ' ')); - assertEquals("", StringUtils.trimLeadingCharacter("", ' ')); - assertEquals("", StringUtils.trimLeadingCharacter(" ", ' ')); - assertEquals("\t", StringUtils.trimLeadingCharacter("\t", ' ')); - assertEquals("a", StringUtils.trimLeadingCharacter(" a", ' ')); - assertEquals("a ", StringUtils.trimLeadingCharacter("a ", ' ')); - assertEquals("a ", StringUtils.trimLeadingCharacter(" a ", ' ')); - assertEquals("a b ", StringUtils.trimLeadingCharacter(" a b ", ' ')); - assertEquals("a b c ", StringUtils.trimLeadingCharacter(" a b c ", ' ')); + assertThat(StringUtils.trimLeadingCharacter(null, ' ')).isEqualTo(null); + assertThat(StringUtils.trimLeadingCharacter("", ' ')).isEqualTo(""); + assertThat(StringUtils.trimLeadingCharacter(" ", ' ')).isEqualTo(""); + assertThat(StringUtils.trimLeadingCharacter("\t", ' ')).isEqualTo("\t"); + assertThat(StringUtils.trimLeadingCharacter(" a", ' ')).isEqualTo("a"); + assertThat(StringUtils.trimLeadingCharacter("a ", ' ')).isEqualTo("a "); + assertThat(StringUtils.trimLeadingCharacter(" a ", ' ')).isEqualTo("a "); + assertThat(StringUtils.trimLeadingCharacter(" a b ", ' ')).isEqualTo("a b "); + assertThat(StringUtils.trimLeadingCharacter(" a b c ", ' ')).isEqualTo("a b c "); } @Test public void testTrimTrailingCharacter() { - assertEquals(null, StringUtils.trimTrailingCharacter(null, ' ')); - assertEquals("", StringUtils.trimTrailingCharacter("", ' ')); - assertEquals("", StringUtils.trimTrailingCharacter(" ", ' ')); - assertEquals("\t", StringUtils.trimTrailingCharacter("\t", ' ')); - assertEquals("a", StringUtils.trimTrailingCharacter("a ", ' ')); - assertEquals(" a", StringUtils.trimTrailingCharacter(" a", ' ')); - assertEquals(" a", StringUtils.trimTrailingCharacter(" a ", ' ')); - assertEquals(" a b", StringUtils.trimTrailingCharacter(" a b ", ' ')); - assertEquals(" a b c", StringUtils.trimTrailingCharacter(" a b c ", ' ')); + assertThat(StringUtils.trimTrailingCharacter(null, ' ')).isEqualTo(null); + assertThat(StringUtils.trimTrailingCharacter("", ' ')).isEqualTo(""); + assertThat(StringUtils.trimTrailingCharacter(" ", ' ')).isEqualTo(""); + assertThat(StringUtils.trimTrailingCharacter("\t", ' ')).isEqualTo("\t"); + assertThat(StringUtils.trimTrailingCharacter("a ", ' ')).isEqualTo("a"); + assertThat(StringUtils.trimTrailingCharacter(" a", ' ')).isEqualTo(" a"); + assertThat(StringUtils.trimTrailingCharacter(" a ", ' ')).isEqualTo(" a"); + assertThat(StringUtils.trimTrailingCharacter(" a b ", ' ')).isEqualTo(" a b"); + assertThat(StringUtils.trimTrailingCharacter(" a b c ", ' ')).isEqualTo(" a b c"); } @Test public void testStartsWithIgnoreCase() { String prefix = "fOo"; - assertTrue(StringUtils.startsWithIgnoreCase("foo", prefix)); - assertTrue(StringUtils.startsWithIgnoreCase("Foo", prefix)); - assertTrue(StringUtils.startsWithIgnoreCase("foobar", prefix)); - assertTrue(StringUtils.startsWithIgnoreCase("foobarbar", prefix)); - assertTrue(StringUtils.startsWithIgnoreCase("Foobar", prefix)); - assertTrue(StringUtils.startsWithIgnoreCase("FoobarBar", prefix)); - assertTrue(StringUtils.startsWithIgnoreCase("foObar", prefix)); - assertTrue(StringUtils.startsWithIgnoreCase("FOObar", prefix)); - assertTrue(StringUtils.startsWithIgnoreCase("fOobar", prefix)); - assertFalse(StringUtils.startsWithIgnoreCase(null, prefix)); - assertFalse(StringUtils.startsWithIgnoreCase("fOobar", null)); - assertFalse(StringUtils.startsWithIgnoreCase("b", prefix)); - assertFalse(StringUtils.startsWithIgnoreCase("barfoo", prefix)); - assertFalse(StringUtils.startsWithIgnoreCase("barfoobar", prefix)); + assertThat(StringUtils.startsWithIgnoreCase("foo", prefix)).isTrue(); + assertThat(StringUtils.startsWithIgnoreCase("Foo", prefix)).isTrue(); + assertThat(StringUtils.startsWithIgnoreCase("foobar", prefix)).isTrue(); + assertThat(StringUtils.startsWithIgnoreCase("foobarbar", prefix)).isTrue(); + assertThat(StringUtils.startsWithIgnoreCase("Foobar", prefix)).isTrue(); + assertThat(StringUtils.startsWithIgnoreCase("FoobarBar", prefix)).isTrue(); + assertThat(StringUtils.startsWithIgnoreCase("foObar", prefix)).isTrue(); + assertThat(StringUtils.startsWithIgnoreCase("FOObar", prefix)).isTrue(); + assertThat(StringUtils.startsWithIgnoreCase("fOobar", prefix)).isTrue(); + assertThat(StringUtils.startsWithIgnoreCase(null, prefix)).isFalse(); + assertThat(StringUtils.startsWithIgnoreCase("fOobar", null)).isFalse(); + assertThat(StringUtils.startsWithIgnoreCase("b", prefix)).isFalse(); + assertThat(StringUtils.startsWithIgnoreCase("barfoo", prefix)).isFalse(); + assertThat(StringUtils.startsWithIgnoreCase("barfoobar", prefix)).isFalse(); } @Test public void testEndsWithIgnoreCase() { String suffix = "fOo"; - assertTrue(StringUtils.endsWithIgnoreCase("foo", suffix)); - assertTrue(StringUtils.endsWithIgnoreCase("Foo", suffix)); - assertTrue(StringUtils.endsWithIgnoreCase("barfoo", suffix)); - assertTrue(StringUtils.endsWithIgnoreCase("barbarfoo", suffix)); - assertTrue(StringUtils.endsWithIgnoreCase("barFoo", suffix)); - assertTrue(StringUtils.endsWithIgnoreCase("barBarFoo", suffix)); - assertTrue(StringUtils.endsWithIgnoreCase("barfoO", suffix)); - assertTrue(StringUtils.endsWithIgnoreCase("barFOO", suffix)); - assertTrue(StringUtils.endsWithIgnoreCase("barfOo", suffix)); - assertFalse(StringUtils.endsWithIgnoreCase(null, suffix)); - assertFalse(StringUtils.endsWithIgnoreCase("barfOo", null)); - assertFalse(StringUtils.endsWithIgnoreCase("b", suffix)); - assertFalse(StringUtils.endsWithIgnoreCase("foobar", suffix)); - assertFalse(StringUtils.endsWithIgnoreCase("barfoobar", suffix)); + assertThat(StringUtils.endsWithIgnoreCase("foo", suffix)).isTrue(); + assertThat(StringUtils.endsWithIgnoreCase("Foo", suffix)).isTrue(); + assertThat(StringUtils.endsWithIgnoreCase("barfoo", suffix)).isTrue(); + assertThat(StringUtils.endsWithIgnoreCase("barbarfoo", suffix)).isTrue(); + assertThat(StringUtils.endsWithIgnoreCase("barFoo", suffix)).isTrue(); + assertThat(StringUtils.endsWithIgnoreCase("barBarFoo", suffix)).isTrue(); + assertThat(StringUtils.endsWithIgnoreCase("barfoO", suffix)).isTrue(); + assertThat(StringUtils.endsWithIgnoreCase("barFOO", suffix)).isTrue(); + assertThat(StringUtils.endsWithIgnoreCase("barfOo", suffix)).isTrue(); + assertThat(StringUtils.endsWithIgnoreCase(null, suffix)).isFalse(); + assertThat(StringUtils.endsWithIgnoreCase("barfOo", null)).isFalse(); + assertThat(StringUtils.endsWithIgnoreCase("b", suffix)).isFalse(); + assertThat(StringUtils.endsWithIgnoreCase("foobar", suffix)).isFalse(); + assertThat(StringUtils.endsWithIgnoreCase("barfoobar", suffix)).isFalse(); } @Test public void testSubstringMatch() { - assertTrue(StringUtils.substringMatch("foo", 0, "foo")); - assertTrue(StringUtils.substringMatch("foo", 1, "oo")); - assertTrue(StringUtils.substringMatch("foo", 2, "o")); - assertFalse(StringUtils.substringMatch("foo", 0, "fOo")); - assertFalse(StringUtils.substringMatch("foo", 1, "fOo")); - assertFalse(StringUtils.substringMatch("foo", 2, "fOo")); - assertFalse(StringUtils.substringMatch("foo", 3, "fOo")); - assertFalse(StringUtils.substringMatch("foo", 1, "Oo")); - assertFalse(StringUtils.substringMatch("foo", 2, "Oo")); - assertFalse(StringUtils.substringMatch("foo", 3, "Oo")); - assertFalse(StringUtils.substringMatch("foo", 2, "O")); - assertFalse(StringUtils.substringMatch("foo", 3, "O")); + assertThat(StringUtils.substringMatch("foo", 0, "foo")).isTrue(); + assertThat(StringUtils.substringMatch("foo", 1, "oo")).isTrue(); + assertThat(StringUtils.substringMatch("foo", 2, "o")).isTrue(); + assertThat(StringUtils.substringMatch("foo", 0, "fOo")).isFalse(); + assertThat(StringUtils.substringMatch("foo", 1, "fOo")).isFalse(); + assertThat(StringUtils.substringMatch("foo", 2, "fOo")).isFalse(); + assertThat(StringUtils.substringMatch("foo", 3, "fOo")).isFalse(); + assertThat(StringUtils.substringMatch("foo", 1, "Oo")).isFalse(); + assertThat(StringUtils.substringMatch("foo", 2, "Oo")).isFalse(); + assertThat(StringUtils.substringMatch("foo", 3, "Oo")).isFalse(); + assertThat(StringUtils.substringMatch("foo", 2, "O")).isFalse(); + assertThat(StringUtils.substringMatch("foo", 3, "O")).isFalse(); } @Test public void testCountOccurrencesOf() { - assertTrue("nullx2 = 0", - StringUtils.countOccurrencesOf(null, null) == 0); - assertTrue("null string = 0", - StringUtils.countOccurrencesOf("s", null) == 0); - assertTrue("null substring = 0", - StringUtils.countOccurrencesOf(null, "s") == 0); + assertThat(StringUtils.countOccurrencesOf(null, null) == 0).as("nullx2 = 0").isTrue(); + assertThat(StringUtils.countOccurrencesOf("s", null) == 0).as("null string = 0").isTrue(); + assertThat(StringUtils.countOccurrencesOf(null, "s") == 0).as("null substring = 0").isTrue(); String s = "erowoiueoiur"; - assertTrue("not found = 0", - StringUtils.countOccurrencesOf(s, "WERWER") == 0); - assertTrue("not found char = 0", - StringUtils.countOccurrencesOf(s, "x") == 0); - assertTrue("not found ws = 0", - StringUtils.countOccurrencesOf(s, " ") == 0); - assertTrue("not found empty string = 0", - StringUtils.countOccurrencesOf(s, "") == 0); - assertTrue("found char=2", StringUtils.countOccurrencesOf(s, "e") == 2); - assertTrue("found substring=2", - StringUtils.countOccurrencesOf(s, "oi") == 2); - assertTrue("found substring=2", - StringUtils.countOccurrencesOf(s, "oiu") == 2); - assertTrue("found substring=3", - StringUtils.countOccurrencesOf(s, "oiur") == 1); - assertTrue("test last", StringUtils.countOccurrencesOf(s, "r") == 2); + assertThat(StringUtils.countOccurrencesOf(s, "WERWER") == 0).as("not found = 0").isTrue(); + assertThat(StringUtils.countOccurrencesOf(s, "x") == 0).as("not found char = 0").isTrue(); + assertThat(StringUtils.countOccurrencesOf(s, " ") == 0).as("not found ws = 0").isTrue(); + assertThat(StringUtils.countOccurrencesOf(s, "") == 0).as("not found empty string = 0").isTrue(); + assertThat(StringUtils.countOccurrencesOf(s, "e") == 2).as("found char=2").isTrue(); + assertThat(StringUtils.countOccurrencesOf(s, "oi") == 2).as("found substring=2").isTrue(); + assertThat(StringUtils.countOccurrencesOf(s, "oiu") == 2).as("found substring=2").isTrue(); + assertThat(StringUtils.countOccurrencesOf(s, "oiur") == 1).as("found substring=3").isTrue(); + assertThat(StringUtils.countOccurrencesOf(s, "r") == 2).as("test last").isTrue(); } @Test @@ -234,19 +218,19 @@ public class StringUtilsTests { // Simple replace String s = StringUtils.replace(inString, oldPattern, newPattern); - assertTrue("Replace 1 worked", s.equals("a6AazAfoo77abfoo")); + assertThat(s.equals("a6AazAfoo77abfoo")).as("Replace 1 worked").isTrue(); // Non match: no change s = StringUtils.replace(inString, "qwoeiruqopwieurpoqwieur", newPattern); - assertSame("Replace non-matched is returned as-is", inString, s); + assertThat(s).as("Replace non-matched is returned as-is").isSameAs(inString); // Null new pattern: should ignore s = StringUtils.replace(inString, oldPattern, null); - assertSame("Replace non-matched is returned as-is", inString, s); + assertThat(s).as("Replace non-matched is returned as-is").isSameAs(inString); // Null old pattern: should ignore s = StringUtils.replace(inString, null, newPattern); - assertSame("Replace non-matched is returned as-is", inString, s); + assertThat(s).as("Replace non-matched is returned as-is").isSameAs(inString); } @Test @@ -254,26 +238,22 @@ public class StringUtilsTests { String inString = "The quick brown fox jumped over the lazy dog"; String noThe = StringUtils.delete(inString, "the"); - assertTrue("Result has no the [" + noThe + "]", - noThe.equals("The quick brown fox jumped over lazy dog")); + assertThat(noThe.equals("The quick brown fox jumped over lazy dog")).as("Result has no the [" + noThe + "]").isTrue(); String nohe = StringUtils.delete(inString, "he"); - assertTrue("Result has no he [" + nohe + "]", - nohe.equals("T quick brown fox jumped over t lazy dog")); + assertThat(nohe.equals("T quick brown fox jumped over t lazy dog")).as("Result has no he [" + nohe + "]").isTrue(); String nosp = StringUtils.delete(inString, " "); - assertTrue("Result has no spaces", - nosp.equals("Thequickbrownfoxjumpedoverthelazydog")); + assertThat(nosp.equals("Thequickbrownfoxjumpedoverthelazydog")).as("Result has no spaces").isTrue(); String killEnd = StringUtils.delete(inString, "dog"); - assertTrue("Result has no dog", - killEnd.equals("The quick brown fox jumped over the lazy ")); + assertThat(killEnd.equals("The quick brown fox jumped over the lazy ")).as("Result has no dog").isTrue(); String mismatch = StringUtils.delete(inString, "dxxcxcxog"); - assertTrue("Result is unchanged", mismatch.equals(inString)); + assertThat(mismatch.equals(inString)).as("Result is unchanged").isTrue(); String nochange = StringUtils.delete(inString, ""); - assertTrue("Result is unchanged", nochange.equals(inString)); + assertThat(nochange.equals(inString)).as("Result is unchanged").isTrue(); } @Test @@ -281,163 +261,152 @@ public class StringUtilsTests { String inString = "Able was I ere I saw Elba"; String res = StringUtils.deleteAny(inString, "I"); - assertTrue("Result has no Is [" + res + "]", res.equals("Able was ere saw Elba")); + assertThat(res.equals("Able was ere saw Elba")).as("Result has no Is [" + res + "]").isTrue(); res = StringUtils.deleteAny(inString, "AeEba!"); - assertTrue("Result has no Is [" + res + "]", res.equals("l ws I r I sw l")); + assertThat(res.equals("l ws I r I sw l")).as("Result has no Is [" + res + "]").isTrue(); String mismatch = StringUtils.deleteAny(inString, "#@$#$^"); - assertTrue("Result is unchanged", mismatch.equals(inString)); + assertThat(mismatch.equals(inString)).as("Result is unchanged").isTrue(); String whitespace = "This is\n\n\n \t a messagy string with whitespace\n"; - assertTrue("Has CR", whitespace.contains("\n")); - assertTrue("Has tab", whitespace.contains("\t")); - assertTrue("Has sp", whitespace.contains(" ")); + assertThat(whitespace.contains("\n")).as("Has CR").isTrue(); + assertThat(whitespace.contains("\t")).as("Has tab").isTrue(); + assertThat(whitespace.contains(" ")).as("Has sp").isTrue(); String cleaned = StringUtils.deleteAny(whitespace, "\n\t "); - assertTrue("Has no CR", !cleaned.contains("\n")); - assertTrue("Has no tab", !cleaned.contains("\t")); - assertTrue("Has no sp", !cleaned.contains(" ")); - assertTrue("Still has chars", cleaned.length() > 10); + boolean condition2 = !cleaned.contains("\n"); + assertThat(condition2).as("Has no CR").isTrue(); + boolean condition1 = !cleaned.contains("\t"); + assertThat(condition1).as("Has no tab").isTrue(); + boolean condition = !cleaned.contains(" "); + assertThat(condition).as("Has no sp").isTrue(); + assertThat(cleaned.length() > 10).as("Still has chars").isTrue(); } @Test public void testQuote() { - assertEquals("'myString'", StringUtils.quote("myString")); - assertEquals("''", StringUtils.quote("")); - assertNull(StringUtils.quote(null)); + assertThat(StringUtils.quote("myString")).isEqualTo("'myString'"); + assertThat(StringUtils.quote("")).isEqualTo("''"); + assertThat(StringUtils.quote(null)).isNull(); } @Test public void testQuoteIfString() { - assertEquals("'myString'", StringUtils.quoteIfString("myString")); - assertEquals("''", StringUtils.quoteIfString("")); - assertEquals(Integer.valueOf(5), StringUtils.quoteIfString(5)); - assertNull(StringUtils.quoteIfString(null)); + assertThat(StringUtils.quoteIfString("myString")).isEqualTo("'myString'"); + assertThat(StringUtils.quoteIfString("")).isEqualTo("''"); + assertThat(StringUtils.quoteIfString(5)).isEqualTo(Integer.valueOf(5)); + assertThat(StringUtils.quoteIfString(null)).isNull(); } @Test public void testUnqualify() { String qualified = "i.am.not.unqualified"; - assertEquals("unqualified", StringUtils.unqualify(qualified)); + assertThat(StringUtils.unqualify(qualified)).isEqualTo("unqualified"); } @Test public void testCapitalize() { String capitalized = "i am not capitalized"; - assertEquals("I am not capitalized", StringUtils.capitalize(capitalized)); + assertThat(StringUtils.capitalize(capitalized)).isEqualTo("I am not capitalized"); } @Test public void testUncapitalize() { String capitalized = "I am capitalized"; - assertEquals("i am capitalized", StringUtils.uncapitalize(capitalized)); + assertThat(StringUtils.uncapitalize(capitalized)).isEqualTo("i am capitalized"); } @Test public void testGetFilename() { - assertEquals(null, StringUtils.getFilename(null)); - assertEquals("", StringUtils.getFilename("")); - assertEquals("myfile", StringUtils.getFilename("myfile")); - assertEquals("myfile", StringUtils.getFilename("mypath/myfile")); - assertEquals("myfile.", StringUtils.getFilename("myfile.")); - assertEquals("myfile.", StringUtils.getFilename("mypath/myfile.")); - assertEquals("myfile.txt", StringUtils.getFilename("myfile.txt")); - assertEquals("myfile.txt", StringUtils.getFilename("mypath/myfile.txt")); + assertThat(StringUtils.getFilename(null)).isEqualTo(null); + assertThat(StringUtils.getFilename("")).isEqualTo(""); + assertThat(StringUtils.getFilename("myfile")).isEqualTo("myfile"); + assertThat(StringUtils.getFilename("mypath/myfile")).isEqualTo("myfile"); + assertThat(StringUtils.getFilename("myfile.")).isEqualTo("myfile."); + assertThat(StringUtils.getFilename("mypath/myfile.")).isEqualTo("myfile."); + assertThat(StringUtils.getFilename("myfile.txt")).isEqualTo("myfile.txt"); + assertThat(StringUtils.getFilename("mypath/myfile.txt")).isEqualTo("myfile.txt"); } @Test public void testGetFilenameExtension() { - assertEquals(null, StringUtils.getFilenameExtension(null)); - assertEquals(null, StringUtils.getFilenameExtension("")); - assertEquals(null, StringUtils.getFilenameExtension("myfile")); - assertEquals(null, StringUtils.getFilenameExtension("myPath/myfile")); - assertEquals(null, StringUtils.getFilenameExtension("/home/user/.m2/settings/myfile")); - assertEquals("", StringUtils.getFilenameExtension("myfile.")); - assertEquals("", StringUtils.getFilenameExtension("myPath/myfile.")); - assertEquals("txt", StringUtils.getFilenameExtension("myfile.txt")); - assertEquals("txt", StringUtils.getFilenameExtension("mypath/myfile.txt")); - assertEquals("txt", StringUtils.getFilenameExtension("/home/user/.m2/settings/myfile.txt")); + assertThat(StringUtils.getFilenameExtension(null)).isEqualTo(null); + assertThat(StringUtils.getFilenameExtension("")).isEqualTo(null); + assertThat(StringUtils.getFilenameExtension("myfile")).isEqualTo(null); + assertThat(StringUtils.getFilenameExtension("myPath/myfile")).isEqualTo(null); + assertThat(StringUtils.getFilenameExtension("/home/user/.m2/settings/myfile")).isEqualTo(null); + assertThat(StringUtils.getFilenameExtension("myfile.")).isEqualTo(""); + assertThat(StringUtils.getFilenameExtension("myPath/myfile.")).isEqualTo(""); + assertThat(StringUtils.getFilenameExtension("myfile.txt")).isEqualTo("txt"); + assertThat(StringUtils.getFilenameExtension("mypath/myfile.txt")).isEqualTo("txt"); + assertThat(StringUtils.getFilenameExtension("/home/user/.m2/settings/myfile.txt")).isEqualTo("txt"); } @Test public void testStripFilenameExtension() { - assertEquals("", StringUtils.stripFilenameExtension("")); - assertEquals("myfile", StringUtils.stripFilenameExtension("myfile")); - assertEquals("myfile", StringUtils.stripFilenameExtension("myfile.")); - assertEquals("myfile", StringUtils.stripFilenameExtension("myfile.txt")); - assertEquals("mypath/myfile", StringUtils.stripFilenameExtension("mypath/myfile")); - assertEquals("mypath/myfile", StringUtils.stripFilenameExtension("mypath/myfile.")); - assertEquals("mypath/myfile", StringUtils.stripFilenameExtension("mypath/myfile.txt")); - assertEquals("/home/user/.m2/settings/myfile", StringUtils.stripFilenameExtension("/home/user/.m2/settings/myfile")); - assertEquals("/home/user/.m2/settings/myfile", StringUtils.stripFilenameExtension("/home/user/.m2/settings/myfile.")); - assertEquals("/home/user/.m2/settings/myfile", StringUtils.stripFilenameExtension("/home/user/.m2/settings/myfile.txt")); + assertThat(StringUtils.stripFilenameExtension("")).isEqualTo(""); + assertThat(StringUtils.stripFilenameExtension("myfile")).isEqualTo("myfile"); + assertThat(StringUtils.stripFilenameExtension("myfile.")).isEqualTo("myfile"); + assertThat(StringUtils.stripFilenameExtension("myfile.txt")).isEqualTo("myfile"); + assertThat(StringUtils.stripFilenameExtension("mypath/myfile")).isEqualTo("mypath/myfile"); + assertThat(StringUtils.stripFilenameExtension("mypath/myfile.")).isEqualTo("mypath/myfile"); + assertThat(StringUtils.stripFilenameExtension("mypath/myfile.txt")).isEqualTo("mypath/myfile"); + assertThat(StringUtils.stripFilenameExtension("/home/user/.m2/settings/myfile")).isEqualTo("/home/user/.m2/settings/myfile"); + assertThat(StringUtils.stripFilenameExtension("/home/user/.m2/settings/myfile.")).isEqualTo("/home/user/.m2/settings/myfile"); + assertThat(StringUtils.stripFilenameExtension("/home/user/.m2/settings/myfile.txt")).isEqualTo("/home/user/.m2/settings/myfile"); } @Test public void testCleanPath() { - assertEquals("mypath/myfile", StringUtils.cleanPath("mypath/myfile")); - assertEquals("mypath/myfile", StringUtils.cleanPath("mypath\\myfile")); - assertEquals("mypath/myfile", StringUtils.cleanPath("mypath/../mypath/myfile")); - assertEquals("mypath/myfile", StringUtils.cleanPath("mypath/myfile/../../mypath/myfile")); - assertEquals("../mypath/myfile", StringUtils.cleanPath("../mypath/myfile")); - assertEquals("../mypath/myfile", StringUtils.cleanPath("../mypath/../mypath/myfile")); - assertEquals("../mypath/myfile", StringUtils.cleanPath("mypath/../../mypath/myfile")); - assertEquals("/../mypath/myfile", StringUtils.cleanPath("/../mypath/myfile")); - assertEquals("/mypath/myfile", StringUtils.cleanPath("/a/:b/../../mypath/myfile")); - assertEquals("/", StringUtils.cleanPath("/")); - assertEquals("/", StringUtils.cleanPath("/mypath/../")); - assertEquals("", StringUtils.cleanPath("mypath/..")); - assertEquals("", StringUtils.cleanPath("mypath/../.")); - assertEquals("./", StringUtils.cleanPath("mypath/../")); - assertEquals("./", StringUtils.cleanPath("././")); - assertEquals("./", StringUtils.cleanPath("./")); - assertEquals("../", StringUtils.cleanPath("../")); - assertEquals("../", StringUtils.cleanPath("./../")); - assertEquals("../", StringUtils.cleanPath(".././")); - assertEquals("file:/", StringUtils.cleanPath("file:/")); - assertEquals("file:/", StringUtils.cleanPath("file:/mypath/../")); - assertEquals("file:", StringUtils.cleanPath("file:mypath/..")); - assertEquals("file:", StringUtils.cleanPath("file:mypath/../.")); - assertEquals("file:./", StringUtils.cleanPath("file:mypath/../")); - assertEquals("file:./", StringUtils.cleanPath("file:././")); - assertEquals("file:./", StringUtils.cleanPath("file:./")); - assertEquals("file:../", StringUtils.cleanPath("file:../")); - assertEquals("file:../", StringUtils.cleanPath("file:./../")); - assertEquals("file:../", StringUtils.cleanPath("file:.././")); - assertEquals("file:///c:/path/the%20file.txt", StringUtils.cleanPath("file:///c:/some/../path/the%20file.txt")); + assertThat(StringUtils.cleanPath("mypath/myfile")).isEqualTo("mypath/myfile"); + assertThat(StringUtils.cleanPath("mypath\\myfile")).isEqualTo("mypath/myfile"); + assertThat(StringUtils.cleanPath("mypath/../mypath/myfile")).isEqualTo("mypath/myfile"); + assertThat(StringUtils.cleanPath("mypath/myfile/../../mypath/myfile")).isEqualTo("mypath/myfile"); + assertThat(StringUtils.cleanPath("../mypath/myfile")).isEqualTo("../mypath/myfile"); + assertThat(StringUtils.cleanPath("../mypath/../mypath/myfile")).isEqualTo("../mypath/myfile"); + assertThat(StringUtils.cleanPath("mypath/../../mypath/myfile")).isEqualTo("../mypath/myfile"); + assertThat(StringUtils.cleanPath("/../mypath/myfile")).isEqualTo("/../mypath/myfile"); + assertThat(StringUtils.cleanPath("/a/:b/../../mypath/myfile")).isEqualTo("/mypath/myfile"); + assertThat(StringUtils.cleanPath("/")).isEqualTo("/"); + assertThat(StringUtils.cleanPath("/mypath/../")).isEqualTo("/"); + assertThat(StringUtils.cleanPath("mypath/..")).isEqualTo(""); + assertThat(StringUtils.cleanPath("mypath/../.")).isEqualTo(""); + assertThat(StringUtils.cleanPath("mypath/../")).isEqualTo("./"); + assertThat(StringUtils.cleanPath("././")).isEqualTo("./"); + assertThat(StringUtils.cleanPath("./")).isEqualTo("./"); + assertThat(StringUtils.cleanPath("../")).isEqualTo("../"); + assertThat(StringUtils.cleanPath("./../")).isEqualTo("../"); + assertThat(StringUtils.cleanPath(".././")).isEqualTo("../"); + assertThat(StringUtils.cleanPath("file:/")).isEqualTo("file:/"); + assertThat(StringUtils.cleanPath("file:/mypath/../")).isEqualTo("file:/"); + assertThat(StringUtils.cleanPath("file:mypath/..")).isEqualTo("file:"); + assertThat(StringUtils.cleanPath("file:mypath/../.")).isEqualTo("file:"); + assertThat(StringUtils.cleanPath("file:mypath/../")).isEqualTo("file:./"); + assertThat(StringUtils.cleanPath("file:././")).isEqualTo("file:./"); + assertThat(StringUtils.cleanPath("file:./")).isEqualTo("file:./"); + assertThat(StringUtils.cleanPath("file:../")).isEqualTo("file:../"); + assertThat(StringUtils.cleanPath("file:./../")).isEqualTo("file:../"); + assertThat(StringUtils.cleanPath("file:.././")).isEqualTo("file:../"); + assertThat(StringUtils.cleanPath("file:///c:/some/../path/the%20file.txt")).isEqualTo("file:///c:/path/the%20file.txt"); } @Test public void testPathEquals() { - assertTrue("Must be true for the same strings", - StringUtils.pathEquals("/dummy1/dummy2/dummy3", "/dummy1/dummy2/dummy3")); - assertTrue("Must be true for the same win strings", - StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3", "C:\\dummy1\\dummy2\\dummy3")); - assertTrue("Must be true for one top path on 1", - StringUtils.pathEquals("/dummy1/bin/../dummy2/dummy3", "/dummy1/dummy2/dummy3")); - assertTrue("Must be true for one win top path on 2", - StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3", "C:\\dummy1\\bin\\..\\dummy2\\dummy3")); - assertTrue("Must be true for two top paths on 1", - StringUtils.pathEquals("/dummy1/bin/../dummy2/bin/../dummy3", "/dummy1/dummy2/dummy3")); - assertTrue("Must be true for two win top paths on 2", - StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3", "C:\\dummy1\\bin\\..\\dummy2\\bin\\..\\dummy3")); - assertTrue("Must be true for double top paths on 1", - StringUtils.pathEquals("/dummy1/bin/tmp/../../dummy2/dummy3", "/dummy1/dummy2/dummy3")); - assertTrue("Must be true for double top paths on 2 with similarity", - StringUtils.pathEquals("/dummy1/dummy2/dummy3", "/dummy1/dum/dum/../../dummy2/dummy3")); - assertTrue("Must be true for current paths", - StringUtils.pathEquals("./dummy1/dummy2/dummy3", "dummy1/dum/./dum/../../dummy2/dummy3")); - assertFalse("Must be false for relative/absolute paths", - StringUtils.pathEquals("./dummy1/dummy2/dummy3", "/dummy1/dum/./dum/../../dummy2/dummy3")); - assertFalse("Must be false for different strings", - StringUtils.pathEquals("/dummy1/dummy2/dummy3", "/dummy1/dummy4/dummy3")); - assertFalse("Must be false for one false path on 1", - StringUtils.pathEquals("/dummy1/bin/tmp/../dummy2/dummy3", "/dummy1/dummy2/dummy3")); - assertFalse("Must be false for one false win top path on 2", - StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3", "C:\\dummy1\\bin\\tmp\\..\\dummy2\\dummy3")); - assertFalse("Must be false for top path on 1 + difference", - StringUtils.pathEquals("/dummy1/bin/../dummy2/dummy3", "/dummy1/dummy2/dummy4")); + assertThat(StringUtils.pathEquals("/dummy1/dummy2/dummy3", "/dummy1/dummy2/dummy3")).as("Must be true for the same strings").isTrue(); + assertThat(StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3", "C:\\dummy1\\dummy2\\dummy3")).as("Must be true for the same win strings").isTrue(); + assertThat(StringUtils.pathEquals("/dummy1/bin/../dummy2/dummy3", "/dummy1/dummy2/dummy3")).as("Must be true for one top path on 1").isTrue(); + assertThat(StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3", "C:\\dummy1\\bin\\..\\dummy2\\dummy3")).as("Must be true for one win top path on 2").isTrue(); + assertThat(StringUtils.pathEquals("/dummy1/bin/../dummy2/bin/../dummy3", "/dummy1/dummy2/dummy3")).as("Must be true for two top paths on 1").isTrue(); + assertThat(StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3", "C:\\dummy1\\bin\\..\\dummy2\\bin\\..\\dummy3")).as("Must be true for two win top paths on 2").isTrue(); + assertThat(StringUtils.pathEquals("/dummy1/bin/tmp/../../dummy2/dummy3", "/dummy1/dummy2/dummy3")).as("Must be true for double top paths on 1").isTrue(); + assertThat(StringUtils.pathEquals("/dummy1/dummy2/dummy3", "/dummy1/dum/dum/../../dummy2/dummy3")).as("Must be true for double top paths on 2 with similarity").isTrue(); + assertThat(StringUtils.pathEquals("./dummy1/dummy2/dummy3", "dummy1/dum/./dum/../../dummy2/dummy3")).as("Must be true for current paths").isTrue(); + assertThat(StringUtils.pathEquals("./dummy1/dummy2/dummy3", "/dummy1/dum/./dum/../../dummy2/dummy3")).as("Must be false for relative/absolute paths").isFalse(); + assertThat(StringUtils.pathEquals("/dummy1/dummy2/dummy3", "/dummy1/dummy4/dummy3")).as("Must be false for different strings").isFalse(); + assertThat(StringUtils.pathEquals("/dummy1/bin/tmp/../dummy2/dummy3", "/dummy1/dummy2/dummy3")).as("Must be false for one false path on 1").isFalse(); + assertThat(StringUtils.pathEquals("C:\\dummy1\\dummy2\\dummy3", "C:\\dummy1\\bin\\tmp\\..\\dummy2\\dummy3")).as("Must be false for one false win top path on 2").isFalse(); + assertThat(StringUtils.pathEquals("/dummy1/bin/../dummy2/dummy3", "/dummy1/dummy2/dummy4")).as("Must be false for top path on 1 + difference").isFalse(); } @Test @@ -445,14 +414,14 @@ public class StringUtilsTests { String[] input1 = new String[] {"myString2"}; String[] input2 = new String[] {"myString1", "myString2"}; String[] result = StringUtils.concatenateStringArrays(input1, input2); - assertEquals(3, result.length); - assertEquals("myString2", result[0]); - assertEquals("myString1", result[1]); - assertEquals("myString2", result[2]); + assertThat(result.length).isEqualTo(3); + assertThat(result[0]).isEqualTo("myString2"); + assertThat(result[1]).isEqualTo("myString1"); + assertThat(result[2]).isEqualTo("myString2"); - assertArrayEquals(input1, StringUtils.concatenateStringArrays(input1, null)); - assertArrayEquals(input2, StringUtils.concatenateStringArrays(null, input2)); - assertNull(StringUtils.concatenateStringArrays(null, null)); + assertThat(StringUtils.concatenateStringArrays(input1, null)).isEqualTo(input1); + assertThat(StringUtils.concatenateStringArrays(null, input2)).isEqualTo(input2); + assertThat(StringUtils.concatenateStringArrays(null, null)).isNull(); } @Test @@ -461,119 +430,116 @@ public class StringUtilsTests { String[] input1 = new String[] {"myString2"}; String[] input2 = new String[] {"myString1", "myString2"}; String[] result = StringUtils.mergeStringArrays(input1, input2); - assertEquals(2, result.length); - assertEquals("myString2", result[0]); - assertEquals("myString1", result[1]); + assertThat(result.length).isEqualTo(2); + assertThat(result[0]).isEqualTo("myString2"); + assertThat(result[1]).isEqualTo("myString1"); - assertArrayEquals(input1, StringUtils.mergeStringArrays(input1, null)); - assertArrayEquals(input2, StringUtils.mergeStringArrays(null, input2)); - assertNull(StringUtils.mergeStringArrays(null, null)); + assertThat(StringUtils.mergeStringArrays(input1, null)).isEqualTo(input1); + assertThat(StringUtils.mergeStringArrays(null, input2)).isEqualTo(input2); + assertThat(StringUtils.mergeStringArrays(null, null)).isNull(); } @Test public void testSortStringArray() { String[] input = new String[] {"myString2"}; input = StringUtils.addStringToArray(input, "myString1"); - assertEquals("myString2", input[0]); - assertEquals("myString1", input[1]); + assertThat(input[0]).isEqualTo("myString2"); + assertThat(input[1]).isEqualTo("myString1"); StringUtils.sortStringArray(input); - assertEquals("myString1", input[0]); - assertEquals("myString2", input[1]); + assertThat(input[0]).isEqualTo("myString1"); + assertThat(input[1]).isEqualTo("myString2"); } @Test public void testRemoveDuplicateStrings() { String[] input = new String[] {"myString2", "myString1", "myString2"}; input = StringUtils.removeDuplicateStrings(input); - assertEquals("myString2", input[0]); - assertEquals("myString1", input[1]); + assertThat(input[0]).isEqualTo("myString2"); + assertThat(input[1]).isEqualTo("myString1"); } @Test public void testSplitArrayElementsIntoProperties() { String[] input = new String[] {"key1=value1 ", "key2 =\"value2\""}; Properties result = StringUtils.splitArrayElementsIntoProperties(input, "="); - assertEquals("value1", result.getProperty("key1")); - assertEquals("\"value2\"", result.getProperty("key2")); + assertThat(result.getProperty("key1")).isEqualTo("value1"); + assertThat(result.getProperty("key2")).isEqualTo("\"value2\""); } @Test public void testSplitArrayElementsIntoPropertiesAndDeletedChars() { String[] input = new String[] {"key1=value1 ", "key2 =\"value2\""}; Properties result = StringUtils.splitArrayElementsIntoProperties(input, "=", "\""); - assertEquals("value1", result.getProperty("key1")); - assertEquals("value2", result.getProperty("key2")); + assertThat(result.getProperty("key1")).isEqualTo("value1"); + assertThat(result.getProperty("key2")).isEqualTo("value2"); } @Test public void testTokenizeToStringArray() { String[] sa = StringUtils.tokenizeToStringArray("a,b , ,c", ","); - assertEquals(3, sa.length); - assertTrue("components are correct", - sa[0].equals("a") && sa[1].equals("b") && sa[2].equals("c")); + assertThat(sa.length).isEqualTo(3); + assertThat(sa[0].equals("a") && sa[1].equals("b") && sa[2].equals("c")).as("components are correct").isTrue(); } @Test public void testTokenizeToStringArrayWithNotIgnoreEmptyTokens() { String[] sa = StringUtils.tokenizeToStringArray("a,b , ,c", ",", true, false); - assertEquals(4, sa.length); - assertTrue("components are correct", - sa[0].equals("a") && sa[1].equals("b") && sa[2].equals("") && sa[3].equals("c")); + assertThat(sa.length).isEqualTo(4); + assertThat(sa[0].equals("a") && sa[1].equals("b") && sa[2].equals("") && sa[3].equals("c")).as("components are correct").isTrue(); } @Test public void testTokenizeToStringArrayWithNotTrimTokens() { String[] sa = StringUtils.tokenizeToStringArray("a,b ,c", ",", false, true); - assertEquals(3, sa.length); - assertTrue("components are correct", - sa[0].equals("a") && sa[1].equals("b ") && sa[2].equals("c")); + assertThat(sa.length).isEqualTo(3); + assertThat(sa[0].equals("a") && sa[1].equals("b ") && sa[2].equals("c")).as("components are correct").isTrue(); } @Test public void testCommaDelimitedListToStringArrayWithNullProducesEmptyArray() { String[] sa = StringUtils.commaDelimitedListToStringArray(null); - assertTrue("String array isn't null with null input", sa != null); - assertTrue("String array length == 0 with null input", sa.length == 0); + assertThat(sa != null).as("String array isn't null with null input").isTrue(); + assertThat(sa.length == 0).as("String array length == 0 with null input").isTrue(); } @Test public void testCommaDelimitedListToStringArrayWithEmptyStringProducesEmptyArray() { String[] sa = StringUtils.commaDelimitedListToStringArray(""); - assertTrue("String array isn't null with null input", sa != null); - assertTrue("String array length == 0 with null input", sa.length == 0); + assertThat(sa != null).as("String array isn't null with null input").isTrue(); + assertThat(sa.length == 0).as("String array length == 0 with null input").isTrue(); } @Test public void testDelimitedListToStringArrayWithComma() { String[] sa = StringUtils.delimitedListToStringArray("a,b", ","); - assertEquals(2, sa.length); - assertEquals("a", sa[0]); - assertEquals("b", sa[1]); + assertThat(sa.length).isEqualTo(2); + assertThat(sa[0]).isEqualTo("a"); + assertThat(sa[1]).isEqualTo("b"); } @Test public void testDelimitedListToStringArrayWithSemicolon() { String[] sa = StringUtils.delimitedListToStringArray("a;b", ";"); - assertEquals(2, sa.length); - assertEquals("a", sa[0]); - assertEquals("b", sa[1]); + assertThat(sa.length).isEqualTo(2); + assertThat(sa[0]).isEqualTo("a"); + assertThat(sa[1]).isEqualTo("b"); } @Test public void testDelimitedListToStringArrayWithEmptyString() { String[] sa = StringUtils.delimitedListToStringArray("a,b", ""); - assertEquals(3, sa.length); - assertEquals("a", sa[0]); - assertEquals(",", sa[1]); - assertEquals("b", sa[2]); + assertThat(sa.length).isEqualTo(3); + assertThat(sa[0]).isEqualTo("a"); + assertThat(sa[1]).isEqualTo(","); + assertThat(sa[2]).isEqualTo("b"); } @Test public void testDelimitedListToStringArrayWithNullDelimiter() { String[] sa = StringUtils.delimitedListToStringArray("a,b", null); - assertEquals(1, sa.length); - assertEquals("a,b", sa[0]); + assertThat(sa.length).isEqualTo(1); + assertThat(sa[0]).isEqualTo("a,b"); } @Test @@ -596,9 +562,7 @@ public class StringUtilsTests { private void doTestStringArrayReverseTransformationMatches(String[] sa) { String[] reverse = StringUtils.commaDelimitedListToStringArray(StringUtils.arrayToCommaDelimitedString(sa)); - assertEquals("Reverse transformation is equal", - Arrays.asList(sa), - Arrays.asList(reverse)); + assertThat(Arrays.asList(reverse)).as("Reverse transformation is equal").isEqualTo(Arrays.asList(sa)); } @Test @@ -606,9 +570,8 @@ public class StringUtilsTests { // Could read these from files String s = "woeirqupoiewuropqiewuorpqiwueopriquwopeiurqopwieur"; String[] sa = StringUtils.commaDelimitedListToStringArray(s); - assertTrue("Found one String with no delimiters", sa.length == 1); - assertTrue("Single array entry matches input String with no delimiters", - sa[0].equals(s)); + assertThat(sa.length == 1).as("Found one String with no delimiters").isTrue(); + assertThat(sa[0].equals(s)).as("Single array entry matches input String with no delimiters").isTrue(); } @Test @@ -625,9 +588,8 @@ public class StringUtilsTests { public void testCommaDelimitedListToStringArrayEmptyStrings() { // Could read these from files String[] sa = StringUtils.commaDelimitedListToStringArray("a,,b"); - assertEquals("a,,b produces array length 3", 3, sa.length); - assertTrue("components are correct", - sa[0].equals("a") && sa[1].equals("") && sa[2].equals("b")); + assertThat(sa.length).as("a,,b produces array length 3").isEqualTo(3); + assertThat(sa[0].equals("a") && sa[1].equals("") && sa[2].equals("b")).as("components are correct").isTrue(); sa = new String[] {"", "", "a", ""}; doTestCommaDelimitedListToStringArrayLegalMatch(sa); @@ -642,9 +604,9 @@ public class StringUtilsTests { sb.append(components[i]); } String[] sa = StringUtils.commaDelimitedListToStringArray(sb.toString()); - assertTrue("String array isn't null with legal match", sa != null); - assertEquals("String array length is correct with legal match", components.length, sa.length); - assertTrue("Output equals input", Arrays.equals(sa, components)); + assertThat(sa != null).as("String array isn't null with legal match").isTrue(); + assertThat(sa.length).as("String array length is correct with legal match").isEqualTo(components.length); + assertThat(Arrays.equals(sa, components)).as("Output equals input").isTrue(); } @@ -652,20 +614,20 @@ public class StringUtilsTests { public void testParseLocaleStringSunnyDay() { Locale expectedLocale = Locale.UK; Locale locale = StringUtils.parseLocaleString(expectedLocale.toString()); - assertNotNull("When given a bona-fide Locale string, must not return null.", locale); - assertEquals(expectedLocale, locale); + assertThat(locale).as("When given a bona-fide Locale string, must not return null.").isNotNull(); + assertThat(locale).isEqualTo(expectedLocale); } @Test public void testParseLocaleStringWithMalformedLocaleString() { Locale locale = StringUtils.parseLocaleString("_banjo_on_my_knee"); - assertNotNull("When given a malformed Locale string, must not return null.", locale); + assertThat(locale).as("When given a malformed Locale string, must not return null.").isNotNull(); } @Test public void testParseLocaleStringWithEmptyLocaleStringYieldsNullLocale() { Locale locale = StringUtils.parseLocaleString(""); - assertNull("When given an empty Locale string, must return null.", locale); + assertThat(locale).as("When given an empty Locale string, must return null.").isNull(); } @Test // SPR-8637 @@ -673,7 +635,7 @@ public class StringUtilsTests { String variant = "proper-northern"; String localeString = "en_GB_" + variant; Locale locale = StringUtils.parseLocaleString(localeString); - assertEquals("Multi-valued variant portion of the Locale not extracted correctly.", variant, locale.getVariant()); + assertThat(locale.getVariant()).as("Multi-valued variant portion of the Locale not extracted correctly.").isEqualTo(variant); } @Test // SPR-3671 @@ -681,7 +643,7 @@ public class StringUtilsTests { String variant = "proper_northern"; String localeString = "en_GB_" + variant; Locale locale = StringUtils.parseLocaleString(localeString); - assertEquals("Multi-valued variant portion of the Locale not extracted correctly.", variant, locale.getVariant()); + assertThat(locale.getVariant()).as("Multi-valued variant portion of the Locale not extracted correctly.").isEqualTo(variant); } @Test // SPR-3671 @@ -689,7 +651,7 @@ public class StringUtilsTests { String variant = "proper northern"; String localeString = "en GB " + variant; Locale locale = StringUtils.parseLocaleString(localeString); - assertEquals("Multi-valued variant portion of the Locale not extracted correctly.", variant, locale.getVariant()); + assertThat(locale.getVariant()).as("Multi-valued variant portion of the Locale not extracted correctly.").isEqualTo(variant); } @Test // SPR-3671 @@ -697,7 +659,7 @@ public class StringUtilsTests { String variant = "proper northern"; String localeString = "en_GB_" + variant; Locale locale = StringUtils.parseLocaleString(localeString); - assertEquals("Multi-valued variant portion of the Locale not extracted correctly.", variant, locale.getVariant()); + assertThat(locale.getVariant()).as("Multi-valued variant portion of the Locale not extracted correctly.").isEqualTo(variant); } @Test // SPR-3671 @@ -705,7 +667,7 @@ public class StringUtilsTests { String variant = "proper northern"; String localeString = "en GB " + variant; // lots of whitespace Locale locale = StringUtils.parseLocaleString(localeString); - assertEquals("Multi-valued variant portion of the Locale not extracted correctly.", variant, locale.getVariant()); + assertThat(locale.getVariant()).as("Multi-valued variant portion of the Locale not extracted correctly.").isEqualTo(variant); } @Test // SPR-3671 @@ -713,7 +675,7 @@ public class StringUtilsTests { String variant = "proper_northern"; String localeString = "en_GB_____" + variant; // lots of underscores Locale locale = StringUtils.parseLocaleString(localeString); - assertEquals("Multi-valued variant portion of the Locale not extracted correctly.", variant, locale.getVariant()); + assertThat(locale.getVariant()).as("Multi-valued variant portion of the Locale not extracted correctly.").isEqualTo(variant); } @Test // SPR-7779 @@ -724,8 +686,8 @@ public class StringUtilsTests { @Test // SPR-9420 public void testParseLocaleWithSameLowercaseTokenForLanguageAndCountry() { - assertEquals("tr_TR", StringUtils.parseLocaleString("tr_tr").toString()); - assertEquals("bg_BG_vnt", StringUtils.parseLocaleString("bg_bg_vnt").toString()); + assertThat(StringUtils.parseLocaleString("tr_tr").toString()).isEqualTo("tr_TR"); + assertThat(StringUtils.parseLocaleString("bg_bg_vnt").toString()).isEqualTo("bg_BG_vnt"); } @Test // SPR-11806 @@ -733,12 +695,12 @@ public class StringUtilsTests { String variant = "GBtest"; String localeString = "en_GB_" + variant; Locale locale = StringUtils.parseLocaleString(localeString); - assertEquals("Variant containing country code not extracted correctly", variant, locale.getVariant()); + assertThat(locale.getVariant()).as("Variant containing country code not extracted correctly").isEqualTo(variant); } @Test // SPR-14718, SPR-7598 public void testParseJava7Variant() { - assertEquals("sr__#LATN", StringUtils.parseLocaleString("sr__#LATN").toString()); + assertThat(StringUtils.parseLocaleString("sr__#LATN").toString()).isEqualTo("sr__#LATN"); } @Test // SPR-16651 @@ -746,10 +708,10 @@ public class StringUtilsTests { for (Locale locale : Locale.getAvailableLocales()) { Locale parsedLocale = StringUtils.parseLocaleString(locale.toString()); if (parsedLocale == null) { - assertEquals("", locale.getLanguage()); + assertThat(locale.getLanguage()).isEqualTo(""); } else { - assertEquals(parsedLocale.toString(), locale.toString()); + assertThat(locale.toString()).isEqualTo(parsedLocale.toString()); } } } @@ -759,28 +721,28 @@ public class StringUtilsTests { for (Locale locale : Locale.getAvailableLocales()) { Locale parsedLocale = StringUtils.parseLocale(locale.toLanguageTag()); if (parsedLocale == null) { - assertEquals("", locale.getLanguage()); + assertThat(locale.getLanguage()).isEqualTo(""); } else { - assertEquals(parsedLocale.toLanguageTag(), locale.toLanguageTag()); + assertThat(locale.toLanguageTag()).isEqualTo(parsedLocale.toLanguageTag()); } } } @Test public void testInvalidLocaleWithLocaleString() { - assertEquals(new Locale("invalid"), StringUtils.parseLocaleString("invalid")); - assertEquals(new Locale("invalidvalue"), StringUtils.parseLocaleString("invalidvalue")); - assertEquals(new Locale("invalidvalue", "foo"), StringUtils.parseLocaleString("invalidvalue_foo")); - assertNull(StringUtils.parseLocaleString("")); + assertThat(StringUtils.parseLocaleString("invalid")).isEqualTo(new Locale("invalid")); + assertThat(StringUtils.parseLocaleString("invalidvalue")).isEqualTo(new Locale("invalidvalue")); + assertThat(StringUtils.parseLocaleString("invalidvalue_foo")).isEqualTo(new Locale("invalidvalue", "foo")); + assertThat(StringUtils.parseLocaleString("")).isNull(); } @Test public void testInvalidLocaleWithLanguageTag() { - assertEquals(new Locale("invalid"), StringUtils.parseLocale("invalid")); - assertEquals(new Locale("invalidvalue"), StringUtils.parseLocale("invalidvalue")); - assertEquals(new Locale("invalidvalue", "foo"), StringUtils.parseLocale("invalidvalue_foo")); - assertNull(StringUtils.parseLocale("")); + assertThat(StringUtils.parseLocale("invalid")).isEqualTo(new Locale("invalid")); + assertThat(StringUtils.parseLocale("invalidvalue")).isEqualTo(new Locale("invalidvalue")); + assertThat(StringUtils.parseLocale("invalidvalue_foo")).isEqualTo(new Locale("invalidvalue", "foo")); + assertThat(StringUtils.parseLocale("")).isNull(); } } diff --git a/spring-core/src/test/java/org/springframework/util/SystemPropertyUtilsTests.java b/spring-core/src/test/java/org/springframework/util/SystemPropertyUtilsTests.java index 3bc89ab1171..089eaf4275f 100644 --- a/spring-core/src/test/java/org/springframework/util/SystemPropertyUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/SystemPropertyUtilsTests.java @@ -20,8 +20,8 @@ import java.util.Map; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @author Rob Harrop @@ -34,7 +34,7 @@ public class SystemPropertyUtilsTests { System.setProperty("test.prop", "bar"); try { String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop}"); - assertEquals("bar", resolved); + assertThat(resolved).isEqualTo("bar"); } finally { System.getProperties().remove("test.prop"); @@ -46,7 +46,7 @@ public class SystemPropertyUtilsTests { System.setProperty("test.prop", "bar"); try { String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop:foo}"); - assertEquals("bar", resolved); + assertThat(resolved).isEqualTo("bar"); } finally { System.getProperties().remove("test.prop"); @@ -58,7 +58,7 @@ public class SystemPropertyUtilsTests { System.setProperty("test.prop", "bar"); try { String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop:#{foo.bar}}"); - assertEquals("bar", resolved); + assertThat(resolved).isEqualTo("bar"); } finally { System.getProperties().remove("test.prop"); @@ -70,7 +70,7 @@ public class SystemPropertyUtilsTests { System.setProperty("test.prop", "bar"); try { String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop:Y#{foo.bar}X}"); - assertEquals("bar", resolved); + assertThat(resolved).isEqualTo("bar"); } finally { System.getProperties().remove("test.prop"); @@ -80,19 +80,19 @@ public class SystemPropertyUtilsTests { @Test public void testReplaceWithDefault() { String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop:foo}"); - assertEquals("foo", resolved); + assertThat(resolved).isEqualTo("foo"); } @Test public void testReplaceWithExpressionDefault() { String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop:#{foo.bar}}"); - assertEquals("#{foo.bar}", resolved); + assertThat(resolved).isEqualTo("#{foo.bar}"); } @Test public void testReplaceWithExpressionContainingDefault() { String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop:Y#{foo.bar}X}"); - assertEquals("Y#{foo.bar}X", resolved); + assertThat(resolved).isEqualTo("Y#{foo.bar}X"); } @Test @@ -104,13 +104,13 @@ public class SystemPropertyUtilsTests { @Test public void testReplaceWithNoDefaultIgnored() { String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop}", true); - assertEquals("${test.prop}", resolved); + assertThat(resolved).isEqualTo("${test.prop}"); } @Test public void testReplaceWithEmptyDefault() { String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop:}"); - assertEquals("", resolved); + assertThat(resolved).isEqualTo(""); } @Test @@ -119,7 +119,7 @@ public class SystemPropertyUtilsTests { System.setProperty("bar", "baz"); try { String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop}"); - assertEquals("foo=baz", resolved); + assertThat(resolved).isEqualTo("foo=baz"); } finally { System.getProperties().remove("test.prop"); @@ -132,7 +132,7 @@ public class SystemPropertyUtilsTests { Map env = System.getenv(); if (env.containsKey("PATH")) { String text = "${PATH}"; - assertEquals(env.get("PATH"), SystemPropertyUtils.resolvePlaceholders(text)); + assertThat(SystemPropertyUtils.resolvePlaceholders(text)).isEqualTo(env.get("PATH")); } } diff --git a/spring-core/src/test/java/org/springframework/util/TypeUtilsTests.java b/spring-core/src/test/java/org/springframework/util/TypeUtilsTests.java index 21c3ca93f41..e4ecc6f3f49 100644 --- a/spring-core/src/test/java/org/springframework/util/TypeUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/TypeUtilsTests.java @@ -25,8 +25,7 @@ import java.util.List; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link TypeUtils}. @@ -59,13 +58,13 @@ public class TypeUtilsTests { @Test public void withClasses() { - assertTrue(TypeUtils.isAssignable(Object.class, Object.class)); - assertTrue(TypeUtils.isAssignable(Object.class, String.class)); - assertFalse(TypeUtils.isAssignable(String.class, Object.class)); - assertTrue(TypeUtils.isAssignable(List.class, List.class)); - assertTrue(TypeUtils.isAssignable(List.class, LinkedList.class)); - assertFalse(TypeUtils.isAssignable(List.class, Collection.class)); - assertFalse(TypeUtils.isAssignable(List.class, HashSet.class)); + assertThat(TypeUtils.isAssignable(Object.class, Object.class)).isTrue(); + assertThat(TypeUtils.isAssignable(Object.class, String.class)).isTrue(); + assertThat(TypeUtils.isAssignable(String.class, Object.class)).isFalse(); + assertThat(TypeUtils.isAssignable(List.class, List.class)).isTrue(); + assertThat(TypeUtils.isAssignable(List.class, LinkedList.class)).isTrue(); + assertThat(TypeUtils.isAssignable(List.class, Collection.class)).isFalse(); + assertThat(TypeUtils.isAssignable(List.class, HashSet.class)).isFalse(); } @Test @@ -73,22 +72,22 @@ public class TypeUtilsTests { Type objectsType = getClass().getField("objects").getGenericType(); Type openObjectsType = getClass().getField("openObjects").getGenericType(); Type stringsType = getClass().getField("strings").getGenericType(); - assertTrue(TypeUtils.isAssignable(Object.class, objectsType)); - assertTrue(TypeUtils.isAssignable(Object.class, openObjectsType)); - assertTrue(TypeUtils.isAssignable(Object.class, stringsType)); - assertTrue(TypeUtils.isAssignable(List.class, objectsType)); - assertTrue(TypeUtils.isAssignable(List.class, openObjectsType)); - assertTrue(TypeUtils.isAssignable(List.class, stringsType)); - assertTrue(TypeUtils.isAssignable(objectsType, List.class)); - assertTrue(TypeUtils.isAssignable(openObjectsType, List.class)); - assertTrue(TypeUtils.isAssignable(stringsType, List.class)); - assertTrue(TypeUtils.isAssignable(objectsType, objectsType)); - assertTrue(TypeUtils.isAssignable(openObjectsType, openObjectsType)); - assertTrue(TypeUtils.isAssignable(stringsType, stringsType)); - assertTrue(TypeUtils.isAssignable(openObjectsType, objectsType)); - assertTrue(TypeUtils.isAssignable(openObjectsType, stringsType)); - assertFalse(TypeUtils.isAssignable(stringsType, objectsType)); - assertFalse(TypeUtils.isAssignable(objectsType, stringsType)); + assertThat(TypeUtils.isAssignable(Object.class, objectsType)).isTrue(); + assertThat(TypeUtils.isAssignable(Object.class, openObjectsType)).isTrue(); + assertThat(TypeUtils.isAssignable(Object.class, stringsType)).isTrue(); + assertThat(TypeUtils.isAssignable(List.class, objectsType)).isTrue(); + assertThat(TypeUtils.isAssignable(List.class, openObjectsType)).isTrue(); + assertThat(TypeUtils.isAssignable(List.class, stringsType)).isTrue(); + assertThat(TypeUtils.isAssignable(objectsType, List.class)).isTrue(); + assertThat(TypeUtils.isAssignable(openObjectsType, List.class)).isTrue(); + assertThat(TypeUtils.isAssignable(stringsType, List.class)).isTrue(); + assertThat(TypeUtils.isAssignable(objectsType, objectsType)).isTrue(); + assertThat(TypeUtils.isAssignable(openObjectsType, openObjectsType)).isTrue(); + assertThat(TypeUtils.isAssignable(stringsType, stringsType)).isTrue(); + assertThat(TypeUtils.isAssignable(openObjectsType, objectsType)).isTrue(); + assertThat(TypeUtils.isAssignable(openObjectsType, stringsType)).isTrue(); + assertThat(TypeUtils.isAssignable(stringsType, objectsType)).isFalse(); + assertThat(TypeUtils.isAssignable(objectsType, stringsType)).isFalse(); } @Test @@ -104,25 +103,25 @@ public class TypeUtilsTests { Type openWildcard = openObjectsType.getActualTypeArguments()[0]; // '?' Type openNumbersWildcard = openNumbersType.getActualTypeArguments()[0]; // '? extends number' - assertTrue(TypeUtils.isAssignable(openWildcard, objectType)); - assertTrue(TypeUtils.isAssignable(openNumbersWildcard, numberType)); - assertFalse(TypeUtils.isAssignable(openNumbersWildcard, stringType)); - assertFalse(TypeUtils.isAssignable(storableObjectListType, openObjectsType)); + assertThat(TypeUtils.isAssignable(openWildcard, objectType)).isTrue(); + assertThat(TypeUtils.isAssignable(openNumbersWildcard, numberType)).isTrue(); + assertThat(TypeUtils.isAssignable(openNumbersWildcard, stringType)).isFalse(); + assertThat(TypeUtils.isAssignable(storableObjectListType, openObjectsType)).isFalse(); } @Test public void withGenericArrayTypes() throws Exception { Type arrayType = getClass().getField("array").getGenericType(); Type openArrayType = getClass().getField("openArray").getGenericType(); - assertTrue(TypeUtils.isAssignable(Object.class, arrayType)); - assertTrue(TypeUtils.isAssignable(Object.class, openArrayType)); - assertTrue(TypeUtils.isAssignable(List[].class, arrayType)); - assertTrue(TypeUtils.isAssignable(List[].class, openArrayType)); - assertTrue(TypeUtils.isAssignable(arrayType, List[].class)); - assertTrue(TypeUtils.isAssignable(openArrayType, List[].class)); - assertTrue(TypeUtils.isAssignable(arrayType, arrayType)); - assertTrue(TypeUtils.isAssignable(openArrayType, openArrayType)); - assertTrue(TypeUtils.isAssignable(openArrayType, arrayType)); + assertThat(TypeUtils.isAssignable(Object.class, arrayType)).isTrue(); + assertThat(TypeUtils.isAssignable(Object.class, openArrayType)).isTrue(); + assertThat(TypeUtils.isAssignable(List[].class, arrayType)).isTrue(); + assertThat(TypeUtils.isAssignable(List[].class, openArrayType)).isTrue(); + assertThat(TypeUtils.isAssignable(arrayType, List[].class)).isTrue(); + assertThat(TypeUtils.isAssignable(openArrayType, List[].class)).isTrue(); + assertThat(TypeUtils.isAssignable(arrayType, arrayType)).isTrue(); + assertThat(TypeUtils.isAssignable(openArrayType, openArrayType)).isTrue(); + assertThat(TypeUtils.isAssignable(openArrayType, arrayType)).isTrue(); } } diff --git a/spring-core/src/test/java/org/springframework/util/comparator/ComparableComparatorTests.java b/spring-core/src/test/java/org/springframework/util/comparator/ComparableComparatorTests.java index ea87ebf49da..b2c87637a8d 100644 --- a/spring-core/src/test/java/org/springframework/util/comparator/ComparableComparatorTests.java +++ b/spring-core/src/test/java/org/springframework/util/comparator/ComparableComparatorTests.java @@ -20,8 +20,8 @@ import java.util.Comparator; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertTrue; /** * Tests for {@link ComparableComparator}. @@ -37,7 +37,7 @@ public class ComparableComparatorTests { Comparator c = new ComparableComparator<>(); String s1 = "abc"; String s2 = "cde"; - assertTrue(c.compare(s1, s2) < 0); + assertThat(c.compare(s1, s2) < 0).isTrue(); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/spring-core/src/test/java/org/springframework/util/comparator/NullSafeComparatorTests.java b/spring-core/src/test/java/org/springframework/util/comparator/NullSafeComparatorTests.java index c5c536c5846..c5840bf99fb 100644 --- a/spring-core/src/test/java/org/springframework/util/comparator/NullSafeComparatorTests.java +++ b/spring-core/src/test/java/org/springframework/util/comparator/NullSafeComparatorTests.java @@ -20,7 +20,7 @@ import java.util.Comparator; import org.junit.Test; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link NullSafeComparator}. @@ -35,15 +35,15 @@ public class NullSafeComparatorTests { @Test public void shouldCompareWithNullsLow() { Comparator c = NullSafeComparator.NULLS_LOW; - assertTrue(c.compare(null, "boo") < 0); + assertThat(c.compare(null, "boo") < 0).isTrue(); } @SuppressWarnings("unchecked") @Test public void shouldCompareWithNullsHigh() { Comparator c = NullSafeComparator.NULLS_HIGH; - assertTrue(c.compare(null, "boo") > 0); - assertTrue(c.compare(null, null) == 0); + assertThat(c.compare(null, "boo") > 0).isTrue(); + assertThat(c.compare(null, null) == 0).isTrue(); } } diff --git a/spring-core/src/test/java/org/springframework/util/concurrent/FutureAdapterTests.java b/spring-core/src/test/java/org/springframework/util/concurrent/FutureAdapterTests.java index c14e303fcee..187af398621 100644 --- a/spring-core/src/test/java/org/springframework/util/concurrent/FutureAdapterTests.java +++ b/spring-core/src/test/java/org/springframework/util/concurrent/FutureAdapterTests.java @@ -23,8 +23,7 @@ import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -54,35 +53,35 @@ public class FutureAdapterTests { public void cancel() throws Exception { given(adaptee.cancel(true)).willReturn(true); boolean result = adapter.cancel(true); - assertTrue(result); + assertThat(result).isTrue(); } @Test public void isCancelled() { given(adaptee.isCancelled()).willReturn(true); boolean result = adapter.isCancelled(); - assertTrue(result); + assertThat(result).isTrue(); } @Test public void isDone() { given(adaptee.isDone()).willReturn(true); boolean result = adapter.isDone(); - assertTrue(result); + assertThat(result).isTrue(); } @Test public void get() throws Exception { given(adaptee.get()).willReturn(42); String result = adapter.get(); - assertEquals("42", result); + assertThat(result).isEqualTo("42"); } @Test public void getTimeOut() throws Exception { given(adaptee.get(1, TimeUnit.SECONDS)).willReturn(42); String result = adapter.get(1, TimeUnit.SECONDS); - assertEquals("42", result); + assertThat(result).isEqualTo("42"); } diff --git a/spring-core/src/test/java/org/springframework/util/concurrent/ListenableFutureTaskTests.java b/spring-core/src/test/java/org/springframework/util/concurrent/ListenableFutureTaskTests.java index cfb263754c8..aef4f186a20 100644 --- a/spring-core/src/test/java/org/springframework/util/concurrent/ListenableFutureTaskTests.java +++ b/spring-core/src/test/java/org/springframework/util/concurrent/ListenableFutureTaskTests.java @@ -24,9 +24,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -47,7 +45,7 @@ public class ListenableFutureTaskTests { task.addCallback(new ListenableFutureCallback() { @Override public void onSuccess(String result) { - assertEquals(s, result); + assertThat(result).isEqualTo(s); } @Override public void onFailure(Throwable ex) { @@ -56,9 +54,9 @@ public class ListenableFutureTaskTests { }); task.run(); - assertSame(s, task.get()); - assertSame(s, task.completable().get()); - task.completable().thenAccept(v -> assertSame(s, v)); + assertThat(task.get()).isSameAs(s); + assertThat(task.completable().get()).isSameAs(s); + task.completable().thenAccept(v -> assertThat(v).isSameAs(s)); } @Test @@ -76,7 +74,7 @@ public class ListenableFutureTaskTests { } @Override public void onFailure(Throwable ex) { - assertEquals(s, ex.getMessage()); + assertThat(ex.getMessage()).isEqualTo(s); } }); task.run(); @@ -102,9 +100,9 @@ public class ListenableFutureTaskTests { verify(successCallback).onSuccess(s); verifyZeroInteractions(failureCallback); - assertSame(s, task.get()); - assertSame(s, task.completable().get()); - task.completable().thenAccept(v -> assertSame(s, v)); + assertThat(task.get()).isSameAs(s); + assertThat(task.completable().get()).isSameAs(s); + task.completable().thenAccept(v -> assertThat(v).isSameAs(s)); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/concurrent/MonoToListenableFutureAdapterTests.java b/spring-core/src/test/java/org/springframework/util/concurrent/MonoToListenableFutureAdapterTests.java index c006e0d27df..509d4e49249 100644 --- a/spring-core/src/test/java/org/springframework/util/concurrent/MonoToListenableFutureAdapterTests.java +++ b/spring-core/src/test/java/org/springframework/util/concurrent/MonoToListenableFutureAdapterTests.java @@ -22,9 +22,7 @@ import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; import reactor.core.publisher.Mono; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link MonoToListenableFutureAdapter}. @@ -39,7 +37,7 @@ public class MonoToListenableFutureAdapterTests { ListenableFuture future = new MonoToListenableFutureAdapter<>(Mono.just(expected)); future.addCallback(actual::set, actual::set); - assertEquals(expected, actual.get()); + assertThat(actual.get()).isEqualTo(expected); } @Test @@ -49,7 +47,7 @@ public class MonoToListenableFutureAdapterTests { ListenableFuture future = new MonoToListenableFutureAdapter<>(Mono.error(expected)); future.addCallback(actual::set, actual::set); - assertEquals(expected, actual.get()); + assertThat(actual.get()).isEqualTo(expected); } @Test @@ -57,16 +55,16 @@ public class MonoToListenableFutureAdapterTests { Mono mono = Mono.delay(Duration.ofSeconds(60)); Future future = new MonoToListenableFutureAdapter<>(mono); - assertTrue(future.cancel(true)); - assertTrue(future.isCancelled()); + assertThat(future.cancel(true)).isTrue(); + assertThat(future.isCancelled()).isTrue(); } @Test public void cancellationAfterTerminated() { Future future = new MonoToListenableFutureAdapter<>(Mono.empty()); - assertFalse("Should return false if task already completed", future.cancel(true)); - assertFalse(future.isCancelled()); + assertThat(future.cancel(true)).as("Should return false if task already completed").isFalse(); + assertThat(future.isCancelled()).isFalse(); } } diff --git a/spring-core/src/test/java/org/springframework/util/concurrent/SettableListenableFutureTests.java b/spring-core/src/test/java/org/springframework/util/concurrent/SettableListenableFutureTests.java index 709c8e1427c..425973ec644 100644 --- a/spring-core/src/test/java/org/springframework/util/concurrent/SettableListenableFutureTests.java +++ b/spring-core/src/test/java/org/springframework/util/concurrent/SettableListenableFutureTests.java @@ -26,10 +26,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -46,88 +43,88 @@ public class SettableListenableFutureTests { @Test public void validateInitialValues() { - assertFalse(settableListenableFuture.isCancelled()); - assertFalse(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isFalse(); } @Test public void returnsSetValue() throws ExecutionException, InterruptedException { String string = "hello"; - assertTrue(settableListenableFuture.set(string)); + assertThat(settableListenableFuture.set(string)).isTrue(); assertThat(settableListenableFuture.get()).isEqualTo(string); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test public void returnsSetValueFromCompletable() throws ExecutionException, InterruptedException { String string = "hello"; - assertTrue(settableListenableFuture.set(string)); + assertThat(settableListenableFuture.set(string)).isTrue(); Future completable = settableListenableFuture.completable(); assertThat(completable.get()).isEqualTo(string); - assertFalse(completable.isCancelled()); - assertTrue(completable.isDone()); + assertThat(completable.isCancelled()).isFalse(); + assertThat(completable.isDone()).isTrue(); } @Test public void setValueUpdatesDoneStatus() { settableListenableFuture.set("hello"); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test public void throwsSetExceptionWrappedInExecutionException() throws Exception { Throwable exception = new RuntimeException(); - assertTrue(settableListenableFuture.setException(exception)); + assertThat(settableListenableFuture.setException(exception)).isTrue(); assertThatExceptionOfType(ExecutionException.class).isThrownBy( settableListenableFuture::get) .withCause(exception); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test public void throwsSetExceptionWrappedInExecutionExceptionFromCompletable() throws Exception { Throwable exception = new RuntimeException(); - assertTrue(settableListenableFuture.setException(exception)); + assertThat(settableListenableFuture.setException(exception)).isTrue(); Future completable = settableListenableFuture.completable(); assertThatExceptionOfType(ExecutionException.class).isThrownBy( completable::get) .withCause(exception); - assertFalse(completable.isCancelled()); - assertTrue(completable.isDone()); + assertThat(completable.isCancelled()).isFalse(); + assertThat(completable.isDone()).isTrue(); } @Test public void throwsSetErrorWrappedInExecutionException() throws Exception { Throwable exception = new OutOfMemoryError(); - assertTrue(settableListenableFuture.setException(exception)); + assertThat(settableListenableFuture.setException(exception)).isTrue(); assertThatExceptionOfType(ExecutionException.class).isThrownBy( settableListenableFuture::get) .withCause(exception); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test public void throwsSetErrorWrappedInExecutionExceptionFromCompletable() throws Exception { Throwable exception = new OutOfMemoryError(); - assertTrue(settableListenableFuture.setException(exception)); + assertThat(settableListenableFuture.setException(exception)).isTrue(); Future completable = settableListenableFuture.completable(); assertThatExceptionOfType(ExecutionException.class).isThrownBy( completable::get) .withCause(exception); - assertFalse(completable.isCancelled()); - assertTrue(completable.isDone()); + assertThat(completable.isCancelled()).isFalse(); + assertThat(completable.isDone()).isTrue(); } @Test @@ -148,8 +145,8 @@ public class SettableListenableFutureTests { settableListenableFuture.set(string); assertThat(callbackHolder[0]).isEqualTo(string); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test @@ -169,10 +166,10 @@ public class SettableListenableFutureTests { }); settableListenableFuture.set(string); - assertFalse(settableListenableFuture.set("good bye")); + assertThat(settableListenableFuture.set("good bye")).isFalse(); assertThat(callbackHolder[0]).isEqualTo(string); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test @@ -193,8 +190,8 @@ public class SettableListenableFutureTests { settableListenableFuture.setException(exception); assertThat(callbackHolder[0]).isEqualTo(exception); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test @@ -214,18 +211,18 @@ public class SettableListenableFutureTests { }); settableListenableFuture.setException(exception); - assertFalse(settableListenableFuture.setException(new IllegalArgumentException())); + assertThat(settableListenableFuture.setException(new IllegalArgumentException())).isFalse(); assertThat(callbackHolder[0]).isEqualTo(exception); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test public void nullIsAcceptedAsValueToSet() throws ExecutionException, InterruptedException { settableListenableFuture.set(null); - assertNull(settableListenableFuture.get()); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat((Object) settableListenableFuture.get()).isNull(); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test @@ -247,8 +244,8 @@ public class SettableListenableFutureTests { String value = settableListenableFuture.get(); assertThat(value).isEqualTo(string); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test @@ -276,65 +273,65 @@ public class SettableListenableFutureTests { String value = settableListenableFuture.get(500L, TimeUnit.MILLISECONDS); assertThat(value).isEqualTo(string); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test public void cancelPreventsValueFromBeingSet() { - assertTrue(settableListenableFuture.cancel(true)); - assertFalse(settableListenableFuture.set("hello")); - assertTrue(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.cancel(true)).isTrue(); + assertThat(settableListenableFuture.set("hello")).isFalse(); + assertThat(settableListenableFuture.isCancelled()).isTrue(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test public void cancelSetsFutureToDone() { settableListenableFuture.cancel(true); - assertTrue(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isTrue(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test public void cancelWithMayInterruptIfRunningTrueCallsOverriddenMethod() { InterruptibleSettableListenableFuture interruptibleFuture = new InterruptibleSettableListenableFuture(); - assertTrue(interruptibleFuture.cancel(true)); - assertTrue(interruptibleFuture.calledInterruptTask()); - assertTrue(interruptibleFuture.isCancelled()); - assertTrue(interruptibleFuture.isDone()); + assertThat(interruptibleFuture.cancel(true)).isTrue(); + assertThat(interruptibleFuture.calledInterruptTask()).isTrue(); + assertThat(interruptibleFuture.isCancelled()).isTrue(); + assertThat(interruptibleFuture.isDone()).isTrue(); } @Test public void cancelWithMayInterruptIfRunningFalseDoesNotCallOverriddenMethod() { InterruptibleSettableListenableFuture interruptibleFuture = new InterruptibleSettableListenableFuture(); - assertTrue(interruptibleFuture.cancel(false)); - assertFalse(interruptibleFuture.calledInterruptTask()); - assertTrue(interruptibleFuture.isCancelled()); - assertTrue(interruptibleFuture.isDone()); + assertThat(interruptibleFuture.cancel(false)).isTrue(); + assertThat(interruptibleFuture.calledInterruptTask()).isFalse(); + assertThat(interruptibleFuture.isCancelled()).isTrue(); + assertThat(interruptibleFuture.isDone()).isTrue(); } @Test public void setPreventsCancel() { - assertTrue(settableListenableFuture.set("hello")); - assertFalse(settableListenableFuture.cancel(true)); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.set("hello")).isTrue(); + assertThat(settableListenableFuture.cancel(true)).isFalse(); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test public void cancelPreventsExceptionFromBeingSet() { - assertTrue(settableListenableFuture.cancel(true)); - assertFalse(settableListenableFuture.setException(new RuntimeException())); - assertTrue(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.cancel(true)).isTrue(); + assertThat(settableListenableFuture.setException(new RuntimeException())).isFalse(); + assertThat(settableListenableFuture.isCancelled()).isTrue(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test public void setExceptionPreventsCancel() { - assertTrue(settableListenableFuture.setException(new RuntimeException())); - assertFalse(settableListenableFuture.cancel(true)); - assertFalse(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.setException(new RuntimeException())).isTrue(); + assertThat(settableListenableFuture.cancel(true)).isFalse(); + assertThat(settableListenableFuture.isCancelled()).isFalse(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test @@ -344,8 +341,8 @@ public class SettableListenableFutureTests { assertThatExceptionOfType(CancellationException.class).isThrownBy(() -> settableListenableFuture.get()); - assertTrue(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isTrue(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test @@ -366,8 +363,8 @@ public class SettableListenableFutureTests { assertThatExceptionOfType(CancellationException.class).isThrownBy(() -> settableListenableFuture.get(500L, TimeUnit.MILLISECONDS)); - assertTrue(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isTrue(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test @@ -383,8 +380,8 @@ public class SettableListenableFutureTests { settableListenableFuture.set("hello"); verifyNoMoreInteractions(callback); - assertTrue(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isTrue(); + assertThat(settableListenableFuture.isDone()).isTrue(); } @Test @@ -400,8 +397,8 @@ public class SettableListenableFutureTests { settableListenableFuture.setException(new RuntimeException()); verifyNoMoreInteractions(callback); - assertTrue(settableListenableFuture.isCancelled()); - assertTrue(settableListenableFuture.isDone()); + assertThat(settableListenableFuture.isCancelled()).isTrue(); + assertThat(settableListenableFuture.isDone()).isTrue(); } diff --git a/spring-core/src/test/java/org/springframework/util/unit/DataSizeTests.java b/spring-core/src/test/java/org/springframework/util/unit/DataSizeTests.java index 6e3236e8496..65998214147 100644 --- a/spring-core/src/test/java/org/springframework/util/unit/DataSizeTests.java +++ b/spring-core/src/test/java/org/springframework/util/unit/DataSizeTests.java @@ -18,10 +18,8 @@ package org.springframework.util.unit; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Tests for {@link DataSize}. @@ -32,182 +30,182 @@ public class DataSizeTests { @Test public void ofBytesToBytes() { - assertEquals(1024, DataSize.ofBytes(1024).toBytes()); + assertThat(DataSize.ofBytes(1024).toBytes()).isEqualTo(1024); } @Test public void ofBytesToKilobytes() { - assertEquals(1, DataSize.ofBytes(1024).toKilobytes()); + assertThat(DataSize.ofBytes(1024).toKilobytes()).isEqualTo(1); } @Test public void ofKilobytesToKilobytes() { - assertEquals(1024, DataSize.ofKilobytes(1024).toKilobytes()); + assertThat(DataSize.ofKilobytes(1024).toKilobytes()).isEqualTo(1024); } @Test public void ofKilobytesToMegabytes() { - assertEquals(1, DataSize.ofKilobytes(1024).toMegabytes()); + assertThat(DataSize.ofKilobytes(1024).toMegabytes()).isEqualTo(1); } @Test public void ofMegabytesToMegabytes() { - assertEquals(1024, DataSize.ofMegabytes(1024).toMegabytes()); + assertThat(DataSize.ofMegabytes(1024).toMegabytes()).isEqualTo(1024); } @Test public void ofMegabytesToGigabytes() { - assertEquals(2, DataSize.ofMegabytes(2048).toGigabytes()); + assertThat(DataSize.ofMegabytes(2048).toGigabytes()).isEqualTo(2); } @Test public void ofGigabytesToGigabytes() { - assertEquals(4096, DataSize.ofGigabytes(4096).toGigabytes()); + assertThat(DataSize.ofGigabytes(4096).toGigabytes()).isEqualTo(4096); } @Test public void ofGigabytesToTerabytes() { - assertEquals(4, DataSize.ofGigabytes(4096).toTerabytes()); + assertThat(DataSize.ofGigabytes(4096).toTerabytes()).isEqualTo(4); } @Test public void ofTerabytesToGigabytes() { - assertEquals(1024, DataSize.ofTerabytes(1).toGigabytes()); + assertThat(DataSize.ofTerabytes(1).toGigabytes()).isEqualTo(1024); } @Test public void ofWithBytesUnit() { - assertEquals(DataSize.ofBytes(10), DataSize.of(10, DataUnit.BYTES)); + assertThat(DataSize.of(10, DataUnit.BYTES)).isEqualTo(DataSize.ofBytes(10)); } @Test public void ofWithKilobytesUnit() { - assertEquals(DataSize.ofKilobytes(20), DataSize.of(20, DataUnit.KILOBYTES)); + assertThat(DataSize.of(20, DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(20)); } @Test public void ofWithMegabytesUnit() { - assertEquals(DataSize.ofMegabytes(30), DataSize.of(30, DataUnit.MEGABYTES)); + assertThat(DataSize.of(30, DataUnit.MEGABYTES)).isEqualTo(DataSize.ofMegabytes(30)); } @Test public void ofWithGigabytesUnit() { - assertEquals(DataSize.ofGigabytes(40), DataSize.of(40, DataUnit.GIGABYTES)); + assertThat(DataSize.of(40, DataUnit.GIGABYTES)).isEqualTo(DataSize.ofGigabytes(40)); } @Test public void ofWithTerabytesUnit() { - assertEquals(DataSize.ofTerabytes(50), DataSize.of(50, DataUnit.TERABYTES)); + assertThat(DataSize.of(50, DataUnit.TERABYTES)).isEqualTo(DataSize.ofTerabytes(50)); } @Test public void parseWithDefaultUnitUsesBytes() { - assertEquals(DataSize.ofKilobytes(1), DataSize.parse("1024")); + assertThat(DataSize.parse("1024")).isEqualTo(DataSize.ofKilobytes(1)); } @Test public void parseNegativeNumberWithDefaultUnitUsesBytes() { - assertEquals(DataSize.ofBytes(-1), DataSize.parse("-1")); + assertThat(DataSize.parse("-1")).isEqualTo(DataSize.ofBytes(-1)); } @Test public void parseWithNullDefaultUnitUsesBytes() { - assertEquals(DataSize.ofKilobytes(1), DataSize.parse("1024", null)); + assertThat(DataSize.parse("1024", null)).isEqualTo(DataSize.ofKilobytes(1)); } @Test public void parseNegativeNumberWithNullDefaultUnitUsesBytes() { - assertEquals(DataSize.ofKilobytes(-1), DataSize.parse("-1024", null)); + assertThat(DataSize.parse("-1024", null)).isEqualTo(DataSize.ofKilobytes(-1)); } @Test public void parseWithCustomDefaultUnit() { - assertEquals(DataSize.ofKilobytes(1), DataSize.parse("1", DataUnit.KILOBYTES)); + assertThat(DataSize.parse("1", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(1)); } @Test public void parseNegativeNumberWithCustomDefaultUnit() { - assertEquals(DataSize.ofKilobytes(-1), DataSize.parse("-1", DataUnit.KILOBYTES)); + assertThat(DataSize.parse("-1", DataUnit.KILOBYTES)).isEqualTo(DataSize.ofKilobytes(-1)); } @Test public void parseWithBytes() { - assertEquals(DataSize.ofKilobytes(1), DataSize.parse("1024B")); + assertThat(DataSize.parse("1024B")).isEqualTo(DataSize.ofKilobytes(1)); } @Test public void parseWithNegativeBytes() { - assertEquals(DataSize.ofKilobytes(-1), DataSize.parse("-1024B")); + assertThat(DataSize.parse("-1024B")).isEqualTo(DataSize.ofKilobytes(-1)); } @Test public void parseWithPositiveBytes() { - assertEquals(DataSize.ofKilobytes(1), DataSize.parse("+1024B")); + assertThat(DataSize.parse("+1024B")).isEqualTo(DataSize.ofKilobytes(1)); } @Test public void parseWithKilobytes() { - assertEquals(DataSize.ofBytes(1024), DataSize.parse("1KB")); + assertThat(DataSize.parse("1KB")).isEqualTo(DataSize.ofBytes(1024)); } @Test public void parseWithNegativeKilobytes() { - assertEquals(DataSize.ofBytes(-1024), DataSize.parse("-1KB")); + assertThat(DataSize.parse("-1KB")).isEqualTo(DataSize.ofBytes(-1024)); } @Test public void parseWithMegabytes() { - assertEquals(DataSize.ofMegabytes(4), DataSize.parse("4MB")); + assertThat(DataSize.parse("4MB")).isEqualTo(DataSize.ofMegabytes(4)); } @Test public void parseWithNegativeMegabytes() { - assertEquals(DataSize.ofMegabytes(-4), DataSize.parse("-4MB")); + assertThat(DataSize.parse("-4MB")).isEqualTo(DataSize.ofMegabytes(-4)); } @Test public void parseWithGigabytes() { - assertEquals(DataSize.ofMegabytes(1024), DataSize.parse("1GB")); + assertThat(DataSize.parse("1GB")).isEqualTo(DataSize.ofMegabytes(1024)); } @Test public void parseWithNegativeGigabytes() { - assertEquals(DataSize.ofMegabytes(-1024), DataSize.parse("-1GB")); + assertThat(DataSize.parse("-1GB")).isEqualTo(DataSize.ofMegabytes(-1024)); } @Test public void parseWithTerabytes() { - assertEquals(DataSize.ofTerabytes(1), DataSize.parse("1TB")); + assertThat(DataSize.parse("1TB")).isEqualTo(DataSize.ofTerabytes(1)); } @Test public void parseWithNegativeTerabytes() { - assertEquals(DataSize.ofTerabytes(-1), DataSize.parse("-1TB")); + assertThat(DataSize.parse("-1TB")).isEqualTo(DataSize.ofTerabytes(-1)); } @Test public void isNegativeWithPositive() { - assertFalse(DataSize.ofBytes(50).isNegative()); + assertThat(DataSize.ofBytes(50).isNegative()).isFalse(); } @Test public void isNegativeWithZero() { - assertFalse(DataSize.ofBytes(0).isNegative()); + assertThat(DataSize.ofBytes(0).isNegative()).isFalse(); } @Test public void isNegativeWithNegative() { - assertTrue(DataSize.ofBytes(-1).isNegative()); + assertThat(DataSize.ofBytes(-1).isNegative()).isTrue(); } @Test public void toStringUsesBytes() { - assertEquals("1024B", DataSize.ofKilobytes(1).toString()); + assertThat(DataSize.ofKilobytes(1).toString()).isEqualTo("1024B"); } @Test public void toStringWithNegativeBytes() { - assertEquals("-1024B", DataSize.ofKilobytes(-1).toString()); + assertThat(DataSize.ofKilobytes(-1).toString()).isEqualTo("-1024B"); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java b/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java index 47f4ab18590..4c2bec5e496 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java +++ b/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java @@ -43,7 +43,7 @@ import org.springframework.core.io.Resource; import org.springframework.tests.MockitoUtils; import org.springframework.tests.MockitoUtils.InvocationArgumentsAdapter; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; @@ -135,8 +135,8 @@ public abstract class AbstractStaxXMLReaderTestCase { transformer.transform(source, result); Node node1 = result.getNode().getFirstChild().getFirstChild(); - assertEquals(" ", node1.getTextContent()); - assertEquals(" Some text ", node1.getNextSibling().getTextContent()); + assertThat(node1.getTextContent()).isEqualTo(" "); + assertThat(node1.getNextSibling().getTextContent()).isEqualTo(" Some text "); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/xml/ListBasedXMLEventReaderTests.java b/spring-core/src/test/java/org/springframework/util/xml/ListBasedXMLEventReaderTests.java index 9dc2c1acd0d..c4e9b84e27d 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/ListBasedXMLEventReaderTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/ListBasedXMLEventReaderTests.java @@ -37,7 +37,6 @@ import static javax.xml.stream.XMLStreamConstants.START_DOCUMENT; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Arjen Poutsma @@ -71,12 +70,12 @@ public class ListBasedXMLEventReaderTests { ListBasedXMLEventReader reader = new ListBasedXMLEventReader(events); - assertEquals(START_DOCUMENT, reader.nextEvent().getEventType()); - assertEquals(START_ELEMENT, reader.nextEvent().getEventType()); - assertEquals(START_ELEMENT, reader.nextEvent().getEventType()); - assertEquals("baz", reader.getElementText()); - assertEquals(END_ELEMENT, reader.nextEvent().getEventType()); - assertEquals(END_DOCUMENT, reader.nextEvent().getEventType()); + assertThat(reader.nextEvent().getEventType()).isEqualTo(START_DOCUMENT); + assertThat(reader.nextEvent().getEventType()).isEqualTo(START_ELEMENT); + assertThat(reader.nextEvent().getEventType()).isEqualTo(START_ELEMENT); + assertThat(reader.getElementText()).isEqualTo("baz"); + assertThat(reader.nextEvent().getEventType()).isEqualTo(END_ELEMENT); + assertThat(reader.nextEvent().getEventType()).isEqualTo(END_DOCUMENT); } @Test @@ -86,7 +85,7 @@ public class ListBasedXMLEventReaderTests { ListBasedXMLEventReader reader = new ListBasedXMLEventReader(events); - assertEquals(START_DOCUMENT, reader.nextEvent().getEventType()); + assertThat(reader.nextEvent().getEventType()).isEqualTo(START_DOCUMENT); assertThatExceptionOfType(XMLStreamException.class).isThrownBy( reader::getElementText) diff --git a/spring-core/src/test/java/org/springframework/util/xml/StaxResultTests.java b/spring-core/src/test/java/org/springframework/util/xml/StaxResultTests.java index bdf7daf4256..1896199fea4 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/StaxResultTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/StaxResultTests.java @@ -33,8 +33,6 @@ import org.junit.Test; import org.springframework.tests.XmlContent; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * @author Arjen Poutsma @@ -61,8 +59,8 @@ public class StaxResultTests { Reader reader = new StringReader(XML); Source source = new StreamSource(reader); StaxResult result = new StaxResult(streamWriter); - assertEquals("Invalid streamWriter returned", streamWriter, result.getXMLStreamWriter()); - assertNull("EventWriter returned", result.getXMLEventWriter()); + assertThat(result.getXMLStreamWriter()).as("Invalid streamWriter returned").isEqualTo(streamWriter); + assertThat(result.getXMLEventWriter()).as("EventWriter returned").isNull(); transformer.transform(source, result); assertThat(XmlContent.from(stringWriter)).as("Invalid result").isSimilarTo(XML); } @@ -74,8 +72,8 @@ public class StaxResultTests { Reader reader = new StringReader(XML); Source source = new StreamSource(reader); StaxResult result = new StaxResult(eventWriter); - assertEquals("Invalid eventWriter returned", eventWriter, result.getXMLEventWriter()); - assertNull("StreamWriter returned", result.getXMLStreamWriter()); + assertThat(result.getXMLEventWriter()).as("Invalid eventWriter returned").isEqualTo(eventWriter); + assertThat(result.getXMLStreamWriter()).as("StreamWriter returned").isNull(); transformer.transform(source, result); assertThat(XmlContent.from(stringWriter)).as("Invalid result").isSimilarTo(XML); } diff --git a/spring-core/src/test/java/org/springframework/util/xml/StaxSourceTests.java b/spring-core/src/test/java/org/springframework/util/xml/StaxSourceTests.java index fbe840bdc02..c2cc48de8b9 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/StaxSourceTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/StaxSourceTests.java @@ -36,8 +36,6 @@ import org.xml.sax.InputSource; import org.springframework.tests.XmlContent; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * @author Arjen Poutsma @@ -66,8 +64,8 @@ public class StaxSourceTests { public void streamReaderSourceToStreamResult() throws Exception { XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(XML)); StaxSource source = new StaxSource(streamReader); - assertEquals("Invalid streamReader returned", streamReader, source.getXMLStreamReader()); - assertNull("EventReader returned", source.getXMLEventReader()); + assertThat(source.getXMLStreamReader()).as("Invalid streamReader returned").isEqualTo(streamReader); + assertThat((Object) source.getXMLEventReader()).as("EventReader returned").isNull(); StringWriter writer = new StringWriter(); transformer.transform(source, new StreamResult(writer)); assertThat(XmlContent.from(writer)).as("Invalid result").isSimilarTo(XML); @@ -77,8 +75,8 @@ public class StaxSourceTests { public void streamReaderSourceToDOMResult() throws Exception { XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(XML)); StaxSource source = new StaxSource(streamReader); - assertEquals("Invalid streamReader returned", streamReader, source.getXMLStreamReader()); - assertNull("EventReader returned", source.getXMLEventReader()); + assertThat(source.getXMLStreamReader()).as("Invalid streamReader returned").isEqualTo(streamReader); + assertThat((Object) source.getXMLEventReader()).as("EventReader returned").isNull(); Document expected = documentBuilder.parse(new InputSource(new StringReader(XML))); Document result = documentBuilder.newDocument(); @@ -90,8 +88,8 @@ public class StaxSourceTests { public void eventReaderSourceToStreamResult() throws Exception { XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(XML)); StaxSource source = new StaxSource(eventReader); - assertEquals("Invalid eventReader returned", eventReader, source.getXMLEventReader()); - assertNull("StreamReader returned", source.getXMLStreamReader()); + assertThat((Object) source.getXMLEventReader()).as("Invalid eventReader returned").isEqualTo(eventReader); + assertThat(source.getXMLStreamReader()).as("StreamReader returned").isNull(); StringWriter writer = new StringWriter(); transformer.transform(source, new StreamResult(writer)); assertThat(XmlContent.from(writer)).as("Invalid result").isSimilarTo(XML); @@ -101,8 +99,8 @@ public class StaxSourceTests { public void eventReaderSourceToDOMResult() throws Exception { XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(XML)); StaxSource source = new StaxSource(eventReader); - assertEquals("Invalid eventReader returned", eventReader, source.getXMLEventReader()); - assertNull("StreamReader returned", source.getXMLStreamReader()); + assertThat((Object) source.getXMLEventReader()).as("Invalid eventReader returned").isEqualTo(eventReader); + assertThat(source.getXMLStreamReader()).as("StreamReader returned").isNull(); Document expected = documentBuilder.parse(new InputSource(new StringReader(XML))); Document result = documentBuilder.newDocument(); diff --git a/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java b/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java index f2c5bb79353..d70c616665c 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java @@ -29,7 +29,7 @@ import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -49,11 +49,9 @@ public class StaxStreamXMLReaderTests extends AbstractStaxXMLReaderTestCase { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(CONTENT)); streamReader.nextTag(); // skip to root - assertEquals("Invalid element", new QName("http://springframework.org/spring-ws", "root"), - streamReader.getName()); + assertThat(streamReader.getName()).as("Invalid element").isEqualTo(new QName("http://springframework.org/spring-ws", "root")); streamReader.nextTag(); // skip to child - assertEquals("Invalid element", new QName("http://springframework.org/spring-ws", "child"), - streamReader.getName()); + assertThat(streamReader.getName()).as("Invalid element").isEqualTo(new QName("http://springframework.org/spring-ws", "child")); StaxStreamXMLReader xmlReader = new StaxStreamXMLReader(streamReader); ContentHandler contentHandler = mock(ContentHandler.class); diff --git a/spring-core/src/test/java/org/springframework/util/xml/StaxUtilsTests.java b/spring-core/src/test/java/org/springframework/util/xml/StaxUtilsTests.java index 3f25fba1937..7fe97af318e 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/StaxUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/StaxUtilsTests.java @@ -35,8 +35,7 @@ import javax.xml.transform.stream.StreamSource; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -45,9 +44,9 @@ public class StaxUtilsTests { @Test public void isStaxSourceInvalid() throws Exception { - assertFalse("A StAX Source", StaxUtils.isStaxSource(new DOMSource())); - assertFalse("A StAX Source", StaxUtils.isStaxSource(new SAXSource())); - assertFalse("A StAX Source", StaxUtils.isStaxSource(new StreamSource())); + assertThat(StaxUtils.isStaxSource(new DOMSource())).as("A StAX Source").isFalse(); + assertThat(StaxUtils.isStaxSource(new SAXSource())).as("A StAX Source").isFalse(); + assertThat(StaxUtils.isStaxSource(new StreamSource())).as("A StAX Source").isFalse(); } @Test @@ -57,7 +56,7 @@ public class StaxUtilsTests { XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(expected)); Source source = StaxUtils.createCustomStaxSource(streamReader); - assertTrue("Not a StAX Source", StaxUtils.isStaxSource(source)); + assertThat(StaxUtils.isStaxSource(source)).as("Not a StAX Source").isTrue(); } @Test @@ -67,14 +66,14 @@ public class StaxUtilsTests { XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(expected)); StAXSource source = new StAXSource(streamReader); - assertTrue("Not a StAX Source", StaxUtils.isStaxSource(source)); + assertThat(StaxUtils.isStaxSource(source)).as("Not a StAX Source").isTrue(); } @Test public void isStaxResultInvalid() throws Exception { - assertFalse("A StAX Result", StaxUtils.isStaxResult(new DOMResult())); - assertFalse("A StAX Result", StaxUtils.isStaxResult(new SAXResult())); - assertFalse("A StAX Result", StaxUtils.isStaxResult(new StreamResult())); + assertThat(StaxUtils.isStaxResult(new DOMResult())).as("A StAX Result").isFalse(); + assertThat(StaxUtils.isStaxResult(new SAXResult())).as("A StAX Result").isFalse(); + assertThat(StaxUtils.isStaxResult(new StreamResult())).as("A StAX Result").isFalse(); } @Test @@ -83,7 +82,7 @@ public class StaxUtilsTests { XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(new StringWriter()); Result result = StaxUtils.createCustomStaxResult(streamWriter); - assertTrue("Not a StAX Result", StaxUtils.isStaxResult(result)); + assertThat(StaxUtils.isStaxResult(result)).as("Not a StAX Result").isTrue(); } @Test @@ -92,7 +91,7 @@ public class StaxUtilsTests { XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(new StringWriter()); StAXResult result = new StAXResult(streamWriter); - assertTrue("Not a StAX Result", StaxUtils.isStaxResult(result)); + assertThat(StaxUtils.isStaxResult(result)).as("Not a StAX Result").isTrue(); } } diff --git a/spring-core/src/test/java/org/springframework/util/xml/TransformerUtilsTests.java b/spring-core/src/test/java/org/springframework/util/xml/TransformerUtilsTests.java index 5364ece36b1..df39bd1a66e 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/TransformerUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/TransformerUtilsTests.java @@ -27,9 +27,8 @@ import javax.xml.transform.URIResolver; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Unit tests for {@link TransformerUtils}. @@ -44,11 +43,11 @@ public class TransformerUtilsTests { Transformer transformer = new StubTransformer(); TransformerUtils.enableIndenting(transformer); String indent = transformer.getOutputProperty(OutputKeys.INDENT); - assertNotNull(indent); - assertEquals("yes", indent); + assertThat(indent).isNotNull(); + assertThat(indent).isEqualTo("yes"); String indentAmount = transformer.getOutputProperty("{http://xml.apache.org/xalan}indent-amount"); - assertNotNull(indentAmount); - assertEquals(String.valueOf(TransformerUtils.DEFAULT_INDENT_AMOUNT), indentAmount); + assertThat(indentAmount).isNotNull(); + assertThat(indentAmount).isEqualTo(String.valueOf(TransformerUtils.DEFAULT_INDENT_AMOUNT)); } @Test @@ -57,11 +56,11 @@ public class TransformerUtilsTests { Transformer transformer = new StubTransformer(); TransformerUtils.enableIndenting(transformer, Integer.valueOf(indentAmountProperty)); String indent = transformer.getOutputProperty(OutputKeys.INDENT); - assertNotNull(indent); - assertEquals("yes", indent); + assertThat(indent).isNotNull(); + assertThat(indent).isEqualTo("yes"); String indentAmount = transformer.getOutputProperty("{http://xml.apache.org/xalan}indent-amount"); - assertNotNull(indentAmount); - assertEquals(indentAmountProperty, indentAmount); + assertThat(indentAmount).isNotNull(); + assertThat(indentAmount).isEqualTo(indentAmountProperty); } @Test @@ -69,8 +68,8 @@ public class TransformerUtilsTests { Transformer transformer = new StubTransformer(); TransformerUtils.disableIndenting(transformer); String indent = transformer.getOutputProperty(OutputKeys.INDENT); - assertNotNull(indent); - assertEquals("no", indent); + assertThat(indent).isNotNull(); + assertThat(indent).isEqualTo("no"); } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/AbstractExpressionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/AbstractExpressionTests.java index 553efa42d34..7a682dbd4e5 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/AbstractExpressionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/AbstractExpressionTests.java @@ -27,9 +27,6 @@ import org.springframework.util.ObjectUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Common superclass for expression tests. @@ -71,19 +68,18 @@ public abstract class AbstractExpressionTests { if (expectedValue == null) { return; // no point doing other checks } - assertNull("Expression returned null value, but expected '" + expectedValue + "'", expectedValue); + assertThat(expectedValue).as("Expression returned null value, but expected '" + expectedValue + "'").isNull(); } Class resultType = value.getClass(); - assertEquals("Type of the actual result was not as expected. Expected '" + expectedResultType + - "' but result was of type '" + resultType + "'", expectedResultType, resultType); + assertThat(resultType).as("Type of the actual result was not as expected. Expected '" + expectedResultType + + "' but result was of type '" + resultType + "'").isEqualTo(expectedResultType); if (expectedValue instanceof String) { - assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, - AbstractExpressionTests.stringValueOf(value)); + assertThat(AbstractExpressionTests.stringValueOf(value)).as("Did not get expected value for expression '" + expression + "'.").isEqualTo(expectedValue); } else { - assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value); + assertThat(value).as("Did not get expected value for expression '" + expression + "'.").isEqualTo(expectedValue); } } @@ -99,13 +95,13 @@ public abstract class AbstractExpressionTests { if (expectedValue == null) { return; // no point doing other checks } - assertNull("Expression returned null value, but expected '" + expectedValue + "'", expectedValue); + assertThat(expectedValue).as("Expression returned null value, but expected '" + expectedValue + "'").isNull(); } Class resultType = value.getClass(); - assertEquals("Type of the actual result was not as expected. Expected '" + expectedResultType + - "' but result was of type '" + resultType + "'", expectedResultType, resultType); - assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value); + assertThat(resultType).as("Type of the actual result was not as expected. Expected '" + expectedResultType + + "' but result was of type '" + resultType + "'").isEqualTo(expectedResultType); + assertThat(value).as("Did not get expected value for expression '" + expression + "'.").isEqualTo(expectedValue); } /** @@ -129,18 +125,17 @@ public abstract class AbstractExpressionTests { if (expectedValue == null) { return; // no point doing other checks } - assertNull("Expression returned null value, but expected '" + expectedValue + "'", expectedValue); + assertThat(expectedValue).as("Expression returned null value, but expected '" + expectedValue + "'").isNull(); } Class resultType = value.getClass(); if (expectedValue instanceof String) { - assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, - AbstractExpressionTests.stringValueOf(value)); + assertThat(AbstractExpressionTests.stringValueOf(value)).as("Did not get expected value for expression '" + expression + "'.").isEqualTo(expectedValue); } else { - assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value); + assertThat(value).as("Did not get expected value for expression '" + expression + "'.").isEqualTo(expectedValue); } - assertTrue("Type of the result was not as expected. Expected '" + expectedClassOfResult + - "' but result was of type '" + resultType + "'", expectedClassOfResult.equals(resultType)); + assertThat(expectedClassOfResult.equals(resultType)).as("Type of the result was not as expected. Expected '" + expectedClassOfResult + + "' but result was of type '" + resultType + "'").isTrue(); assertThat(expr.isWritable(context)).as("isWritable").isEqualTo(shouldBeWritable); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java index 61080756e42..f58ff537c4c 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java @@ -21,9 +21,7 @@ import org.junit.Test; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test construction of arrays. @@ -121,8 +119,8 @@ public class ArrayConstructorTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); Expression e = parser.parseExpression(expression); Object o = e.getValue(); - assertNotNull(o); - assertTrue(o.getClass().isArray()); + assertThat(o).isNotNull(); + assertThat(o.getClass().isArray()).isTrue(); StringBuilder s = new StringBuilder(); s.append('['); if (o instanceof int[]) { @@ -201,7 +199,7 @@ public class ArrayConstructorTests extends AbstractExpressionTests { throw new IllegalStateException("Not supported " + o.getClass()); } s.append(']'); - assertEquals(expectedToString, s.toString()); + assertThat(s.toString()).isEqualTo(expectedToString); return s.toString(); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/CachedMethodExecutorTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/CachedMethodExecutorTests.java index 65ef1be3fb9..62459ffdb2f 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/CachedMethodExecutorTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/CachedMethodExecutorTests.java @@ -24,7 +24,7 @@ import org.springframework.expression.spel.ast.MethodReference; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Test for caching in {@link MethodReference} (SPR-10657). @@ -60,7 +60,7 @@ public class CachedMethodExecutorTests { private void assertMethodExecution(Expression expression, Object var, String expected) { this.context.setVariable("var", var); - assertEquals(expected, expression.getValue(this.context)); + assertThat(expression.getValue(this.context)).isEqualTo(expected); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java index f94749c22df..36e1ef40186 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java @@ -34,9 +34,6 @@ import org.springframework.expression.spel.testresources.PlaceOfBirth; import static org.assertj.core.api.Assertions.assertThat; 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 invocation of constructors. @@ -107,15 +104,15 @@ public class ConstructorInvocationTests extends AbstractExpressionTests { eContext.setRootObject(new Tester()); eContext.setVariable("bar", 3); Object o = expr.getValue(eContext); - assertEquals(3, o); - assertEquals(1, parser.parseExpression("counter").getValue(eContext)); + assertThat(o).isEqualTo(3); + assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(1); // Now the expression has cached that throwException(int) is the right thing to // call. Let's change 'bar' to be a PlaceOfBirth which indicates the cached // reference is out of date. eContext.setVariable("bar", new PlaceOfBirth("London")); o = expr.getValue(eContext); - assertEquals(0, o); + assertThat(o).isEqualTo(0); // That confirms the logic to mark the cached reference stale and retry is working // Now let's cause the method to exit via exception and ensure it doesn't cause @@ -124,8 +121,8 @@ public class ConstructorInvocationTests extends AbstractExpressionTests { // First, switch back to throwException(int) eContext.setVariable("bar", 3); o = expr.getValue(eContext); - assertEquals(3, o); - assertEquals(2, parser.parseExpression("counter").getValue(eContext)); + assertThat(o).isEqualTo(3); + assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(2); // 4 will make it throw a checked exception - this will be wrapped by spel on the // way out @@ -138,7 +135,7 @@ public class ConstructorInvocationTests extends AbstractExpressionTests { // using arguments '(java.lang.Integer)' // If counter is 4 then the method got called twice! - assertEquals(3, parser.parseExpression("counter").getValue(eContext)); + assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(3); // 1 will make it throw a RuntimeException - SpEL will let this through eContext.setVariable("bar", 1); @@ -150,7 +147,7 @@ public class ConstructorInvocationTests extends AbstractExpressionTests { // using arguments '(java.lang.Integer)' // If counter is 5 then the method got called twice! - assertEquals(4, parser.parseExpression("counter").getValue(eContext)); + assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(4); } @Test @@ -159,20 +156,20 @@ public class ConstructorInvocationTests extends AbstractExpressionTests { // reflective constructor accessor is the only one by default List constructorResolvers = ctx.getConstructorResolvers(); - assertEquals(1, constructorResolvers.size()); + assertThat(constructorResolvers.size()).isEqualTo(1); ConstructorResolver dummy = new DummyConstructorResolver(); ctx.addConstructorResolver(dummy); - assertEquals(2, ctx.getConstructorResolvers().size()); + assertThat(ctx.getConstructorResolvers().size()).isEqualTo(2); List copy = new ArrayList<>(); copy.addAll(ctx.getConstructorResolvers()); - assertTrue(ctx.removeConstructorResolver(dummy)); - assertFalse(ctx.removeConstructorResolver(dummy)); - assertEquals(1, ctx.getConstructorResolvers().size()); + assertThat(ctx.removeConstructorResolver(dummy)).isTrue(); + assertThat(ctx.removeConstructorResolver(dummy)).isFalse(); + assertThat(ctx.getConstructorResolvers().size()).isEqualTo(1); ctx.setConstructorResolvers(copy); - assertEquals(2, ctx.getConstructorResolvers().size()); + assertThat(ctx.getConstructorResolvers().size()).isEqualTo(2); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/DefaultComparatorUnitTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/DefaultComparatorUnitTests.java index 8d646a9c216..0afdb577ce4 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/DefaultComparatorUnitTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/DefaultComparatorUnitTests.java @@ -23,8 +23,7 @@ import org.springframework.expression.EvaluationException; import org.springframework.expression.TypeComparator; import org.springframework.expression.spel.support.StandardTypeComparator; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for type comparison @@ -38,29 +37,29 @@ public class DefaultComparatorUnitTests { public void testPrimitives() throws EvaluationException { TypeComparator comparator = new StandardTypeComparator(); // primitive int - assertTrue(comparator.compare(1, 2) < 0); - assertTrue(comparator.compare(1, 1) == 0); - assertTrue(comparator.compare(2, 1) > 0); + assertThat(comparator.compare(1, 2) < 0).isTrue(); + assertThat(comparator.compare(1, 1) == 0).isTrue(); + assertThat(comparator.compare(2, 1) > 0).isTrue(); - assertTrue(comparator.compare(1.0d, 2) < 0); - assertTrue(comparator.compare(1.0d, 1) == 0); - assertTrue(comparator.compare(2.0d, 1) > 0); + assertThat(comparator.compare(1.0d, 2) < 0).isTrue(); + assertThat(comparator.compare(1.0d, 1) == 0).isTrue(); + assertThat(comparator.compare(2.0d, 1) > 0).isTrue(); - assertTrue(comparator.compare(1.0f, 2) < 0); - assertTrue(comparator.compare(1.0f, 1) == 0); - assertTrue(comparator.compare(2.0f, 1) > 0); + assertThat(comparator.compare(1.0f, 2) < 0).isTrue(); + assertThat(comparator.compare(1.0f, 1) == 0).isTrue(); + assertThat(comparator.compare(2.0f, 1) > 0).isTrue(); - assertTrue(comparator.compare(1L, 2) < 0); - assertTrue(comparator.compare(1L, 1) == 0); - assertTrue(comparator.compare(2L, 1) > 0); + assertThat(comparator.compare(1L, 2) < 0).isTrue(); + assertThat(comparator.compare(1L, 1) == 0).isTrue(); + assertThat(comparator.compare(2L, 1) > 0).isTrue(); - assertTrue(comparator.compare(1, 2L) < 0); - assertTrue(comparator.compare(1, 1L) == 0); - assertTrue(comparator.compare(2, 1L) > 0); + assertThat(comparator.compare(1, 2L) < 0).isTrue(); + assertThat(comparator.compare(1, 1L) == 0).isTrue(); + assertThat(comparator.compare(2, 1L) > 0).isTrue(); - assertTrue(comparator.compare(1L, 2L) < 0); - assertTrue(comparator.compare(1L, 1L) == 0); - assertTrue(comparator.compare(2L, 1L) > 0); + assertThat(comparator.compare(1L, 2L) < 0).isTrue(); + assertThat(comparator.compare(1L, 1L) == 0).isTrue(); + assertThat(comparator.compare(2L, 1L) > 0).isTrue(); } @Test @@ -70,54 +69,54 @@ public class DefaultComparatorUnitTests { BigDecimal bdOne = new BigDecimal("1"); BigDecimal bdTwo = new BigDecimal("2"); - assertTrue(comparator.compare(bdOne, bdTwo) < 0); - assertTrue(comparator.compare(bdOne, new BigDecimal("1")) == 0); - assertTrue(comparator.compare(bdTwo, bdOne) > 0); + assertThat(comparator.compare(bdOne, bdTwo) < 0).isTrue(); + assertThat(comparator.compare(bdOne, new BigDecimal("1")) == 0).isTrue(); + assertThat(comparator.compare(bdTwo, bdOne) > 0).isTrue(); - assertTrue(comparator.compare(1, bdTwo) < 0); - assertTrue(comparator.compare(1, bdOne) == 0); - assertTrue(comparator.compare(2, bdOne) > 0); + assertThat(comparator.compare(1, bdTwo) < 0).isTrue(); + assertThat(comparator.compare(1, bdOne) == 0).isTrue(); + assertThat(comparator.compare(2, bdOne) > 0).isTrue(); - assertTrue(comparator.compare(1.0d, bdTwo) < 0); - assertTrue(comparator.compare(1.0d, bdOne) == 0); - assertTrue(comparator.compare(2.0d, bdOne) > 0); + assertThat(comparator.compare(1.0d, bdTwo) < 0).isTrue(); + assertThat(comparator.compare(1.0d, bdOne) == 0).isTrue(); + assertThat(comparator.compare(2.0d, bdOne) > 0).isTrue(); - assertTrue(comparator.compare(1.0f, bdTwo) < 0); - assertTrue(comparator.compare(1.0f, bdOne) == 0); - assertTrue(comparator.compare(2.0f, bdOne) > 0); + assertThat(comparator.compare(1.0f, bdTwo) < 0).isTrue(); + assertThat(comparator.compare(1.0f, bdOne) == 0).isTrue(); + assertThat(comparator.compare(2.0f, bdOne) > 0).isTrue(); - assertTrue(comparator.compare(1L, bdTwo) < 0); - assertTrue(comparator.compare(1L, bdOne) == 0); - assertTrue(comparator.compare(2L, bdOne) > 0); + assertThat(comparator.compare(1L, bdTwo) < 0).isTrue(); + assertThat(comparator.compare(1L, bdOne) == 0).isTrue(); + assertThat(comparator.compare(2L, bdOne) > 0).isTrue(); } @Test public void testNulls() throws EvaluationException { TypeComparator comparator = new StandardTypeComparator(); - assertTrue(comparator.compare(null,"abc")<0); - assertTrue(comparator.compare(null,null)==0); - assertTrue(comparator.compare("abc",null)>0); + assertThat(comparator.compare(null,"abc")<0).isTrue(); + assertThat(comparator.compare(null,null)==0).isTrue(); + assertThat(comparator.compare("abc",null)>0).isTrue(); } @Test public void testObjects() throws EvaluationException { TypeComparator comparator = new StandardTypeComparator(); - assertTrue(comparator.compare("a","a")==0); - assertTrue(comparator.compare("a","b")<0); - assertTrue(comparator.compare("b","a")>0); + assertThat(comparator.compare("a","a")==0).isTrue(); + assertThat(comparator.compare("a","b")<0).isTrue(); + assertThat(comparator.compare("b","a")>0).isTrue(); } @Test public void testCanCompare() throws EvaluationException { TypeComparator comparator = new StandardTypeComparator(); - assertTrue(comparator.canCompare(null,1)); - assertTrue(comparator.canCompare(1,null)); + assertThat(comparator.canCompare(null,1)).isTrue(); + assertThat(comparator.canCompare(1,null)).isTrue(); - assertTrue(comparator.canCompare(2,1)); - assertTrue(comparator.canCompare("abc","def")); - assertTrue(comparator.canCompare("abc",3)); - assertFalse(comparator.canCompare(String.class,3)); + assertThat(comparator.canCompare(2,1)).isTrue(); + assertThat(comparator.canCompare("abc","def")).isTrue(); + assertThat(comparator.canCompare("abc",3)).isTrue(); + assertThat(comparator.canCompare(String.class,3)).isFalse(); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java index 2077e6628bc..c310ccbda59 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java @@ -45,11 +45,7 @@ import org.springframework.expression.spel.testresources.TestPerson; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.within; /** * Tests the evaluation of real expressions in a real context. @@ -70,17 +66,17 @@ public class EvaluationTests extends AbstractExpressionTests { TestClass testClass = new TestClass(); Object o = e.getValue(new StandardEvaluationContext(testClass)); - assertEquals("", o); + assertThat(o).isEqualTo(""); o = parser.parseExpression("list[3]").getValue(new StandardEvaluationContext(testClass)); - assertEquals("", o); - assertEquals(4, testClass.list.size()); + assertThat(o).isEqualTo(""); + assertThat(testClass.list.size()).isEqualTo(4); assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> parser.parseExpression("list2[3]").getValue(new StandardEvaluationContext(testClass))); o = parser.parseExpression("foo[3]").getValue(new StandardEvaluationContext(testClass)); - assertEquals("", o); - assertEquals(4, testClass.getFoo().size()); + assertThat(o).isEqualTo(""); + assertThat(testClass.getFoo().size()).isEqualTo(4); } @Test @@ -90,9 +86,9 @@ public class EvaluationTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Object o = parser.parseExpression("map['a']").getValue(ctx); - assertNull(o); + assertThat(o).isNull(); o = parser.parseExpression("map").getValue(ctx); - assertNotNull(o); + assertThat(o).isNotNull(); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> parser.parseExpression("map2['a']").getValue(ctx)); @@ -107,9 +103,9 @@ public class EvaluationTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Object o = parser.parseExpression("wibble.bar").getValue(ctx); - assertEquals("hello", o); + assertThat(o).isEqualTo("hello"); o = parser.parseExpression("wibble").getValue(ctx); - assertNotNull(o); + assertThat(o).isNotNull(); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> parser.parseExpression("wibble2.bar").getValue(ctx)); @@ -286,15 +282,15 @@ public class EvaluationTests extends AbstractExpressionTests { // repeated evaluation to drive use of cached executor SpelExpression e = (SpelExpression) parser.parseExpression("new String('wibble')"); String newString = e.getValue(String.class); - assertEquals("wibble", newString); + assertThat(newString).isEqualTo("wibble"); newString = e.getValue(String.class); - assertEquals("wibble", newString); + assertThat(newString).isEqualTo("wibble"); // not writable - assertFalse(e.isWritable(new StandardEvaluationContext())); + assertThat(e.isWritable(new StandardEvaluationContext())).isFalse(); // ast - assertEquals("new String('wibble')", e.toStringAST()); + assertThat(e.toStringAST()).isEqualTo("new String('wibble')"); } // unary expressions @@ -373,7 +369,7 @@ public class EvaluationTests extends AbstractExpressionTests { @Test public void testTernaryOperator04() { Expression e = parser.parseExpression("1>2?3:4"); - assertFalse(e.isWritable(context)); + assertThat(e.isWritable(context)).isFalse(); } @Test @@ -452,12 +448,12 @@ public class EvaluationTests extends AbstractExpressionTests { @Test public void testTypeReferencesAndQualifiedIdentifierCaching() { SpelExpression e = (SpelExpression) parser.parseExpression("T(java.lang.String)"); - assertFalse(e.isWritable(new StandardEvaluationContext())); - assertEquals("T(java.lang.String)", e.toStringAST()); - assertEquals(String.class, e.getValue(Class.class)); + assertThat(e.isWritable(new StandardEvaluationContext())).isFalse(); + assertThat(e.toStringAST()).isEqualTo("T(java.lang.String)"); + assertThat(e.getValue(Class.class)).isEqualTo(String.class); // use cached QualifiedIdentifier: - assertEquals("T(java.lang.String)", e.toStringAST()); - assertEquals(String.class, e.getValue(Class.class)); + assertThat(e.toStringAST()).isEqualTo("T(java.lang.String)"); + assertThat(e.getValue(Class.class)).isEqualTo(String.class); } @Test @@ -466,27 +462,27 @@ public class EvaluationTests extends AbstractExpressionTests { EvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariable("a", (short) 3); ctx.setVariable("b", (short) 6); - assertTrue(e.getValue(ctx, Boolean.class)); + assertThat(e.getValue(ctx, Boolean.class)).isTrue(); ctx.setVariable("b", (byte) 6); - assertTrue(e.getValue(ctx, Boolean.class)); + assertThat(e.getValue(ctx, Boolean.class)).isTrue(); ctx.setVariable("a", (byte) 9); ctx.setVariable("b", (byte) 6); - assertFalse(e.getValue(ctx, Boolean.class)); + assertThat(e.getValue(ctx, Boolean.class)).isFalse(); ctx.setVariable("a", 10L); ctx.setVariable("b", (short) 30); - assertTrue(e.getValue(ctx, Boolean.class)); + assertThat(e.getValue(ctx, Boolean.class)).isTrue(); ctx.setVariable("a", (byte) 3); ctx.setVariable("b", (short) 30); - assertTrue(e.getValue(ctx, Boolean.class)); + assertThat(e.getValue(ctx, Boolean.class)).isTrue(); ctx.setVariable("a", (byte) 3); ctx.setVariable("b", 30L); - assertTrue(e.getValue(ctx, Boolean.class)); + assertThat(e.getValue(ctx, Boolean.class)).isTrue(); ctx.setVariable("a", (byte) 3); ctx.setVariable("b", 30f); - assertTrue(e.getValue(ctx, Boolean.class)); + assertThat(e.getValue(ctx, Boolean.class)).isTrue(); ctx.setVariable("a", new BigInteger("10")); ctx.setVariable("b", new BigInteger("20")); - assertTrue(e.getValue(ctx, Boolean.class)); + assertThat(e.getValue(ctx, Boolean.class)).isTrue(); } @Test @@ -523,15 +519,15 @@ public class EvaluationTests extends AbstractExpressionTests { @Test public void testAdvancedNumerics() { int twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Integer.class); - assertEquals(24, twentyFour); + assertThat(twentyFour).isEqualTo(24); double one = parser.parseExpression("8.0 / 5e0 % 2").getValue(Double.class); - assertEquals(1.6d, one, 0d); + assertThat((float) one).isCloseTo((float) 1.6d, within((float) 0d)); int o = parser.parseExpression("8.0 / 5e0 % 2").getValue(Integer.class); - assertEquals(1, o); + assertThat(o).isEqualTo(1); int sixteen = parser.parseExpression("-2 ^ 4").getValue(Integer.class); - assertEquals(16, sixteen); + assertThat(sixteen).isEqualTo(16); int minusFortyFive = parser.parseExpression("1+2-3*8^2/2/2").getValue(Integer.class); - assertEquals(-45, minusFortyFive); + assertThat(minusFortyFive).isEqualTo(-45); } @Test @@ -539,7 +535,7 @@ public class EvaluationTests extends AbstractExpressionTests { EvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); boolean trueValue = parser.parseExpression("T(java.util.Date) == Birthdate.Class").getValue( context, Boolean.class); - assertTrue(trueValue); + assertThat(trueValue).isTrue(); } @Test @@ -548,13 +544,13 @@ public class EvaluationTests extends AbstractExpressionTests { assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> parser.parseExpression("T(List)!=null").getValue(context, Boolean.class)); ((StandardTypeLocator) context.getTypeLocator()).registerImport("java.util"); - assertTrue(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class)); + assertThat(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class)).isTrue(); } @Test public void testResolvingString() { Class stringClass = parser.parseExpression("T(String)").getValue(Class.class); - assertEquals(String.class, stringClass); + assertThat(stringClass).isEqualTo(String.class); } /** @@ -569,20 +565,20 @@ public class EvaluationTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(config); Expression e = parser.parseExpression("name"); e.setValue(context, "Oleg"); - assertEquals("Oleg", person.getName()); + assertThat(person.getName()).isEqualTo("Oleg"); e = parser.parseExpression("address.street"); e.setValue(context, "123 High St"); - assertEquals("123 High St", person.getAddress().getStreet()); + assertThat(person.getAddress().getStreet()).isEqualTo("123 High St"); e = parser.parseExpression("address.crossStreets[0]"); e.setValue(context, "Blah"); - assertEquals("Blah", person.getAddress().getCrossStreets().get(0)); + assertThat(person.getAddress().getCrossStreets().get(0)).isEqualTo("Blah"); e = parser.parseExpression("address.crossStreets[3]"); e.setValue(context, "Wibble"); - assertEquals("Blah", person.getAddress().getCrossStreets().get(0)); - assertEquals("Wibble", person.getAddress().getCrossStreets().get(3)); + assertThat(person.getAddress().getCrossStreets().get(0)).isEqualTo("Blah"); + assertThat(person.getAddress().getCrossStreets().get(3)).isEqualTo("Wibble"); } /** @@ -593,13 +589,13 @@ public class EvaluationTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(); Expression e = parser.parseExpression("null"); - assertNull(e.getValue()); + assertThat(e.getValue()).isNull(); e = parser.parseExpression("NULL"); - assertNull(e.getValue()); + assertThat(e.getValue()).isNull(); e = parser.parseExpression("NuLl"); - assertNull(e.getValue()); + assertThat(e.getValue()).isNull(); } /** @@ -637,21 +633,21 @@ public class EvaluationTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Expression e = parser.parseExpression("listOfStrings[++index3]='def'"); e.getValue(ctx); - assertEquals(2,instance.listOfStrings.size()); - assertEquals("def",instance.listOfStrings.get(1)); + assertThat(instance.listOfStrings.size()).isEqualTo(2); + assertThat(instance.listOfStrings.get(1)).isEqualTo("def"); // Check reference beyond end of collection ctx = new StandardEvaluationContext(instance); parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); e = parser.parseExpression("listOfStrings[0]"); String value = e.getValue(ctx, String.class); - assertEquals("abc",value); + assertThat(value).isEqualTo("abc"); e = parser.parseExpression("listOfStrings[1]"); value = e.getValue(ctx, String.class); - assertEquals("def",value); + assertThat(value).isEqualTo("def"); e = parser.parseExpression("listOfStrings[2]"); value = e.getValue(ctx, String.class); - assertEquals("",value); + assertThat(value).isEqualTo(""); // Now turn off growing and reference off the end StandardEvaluationContext failCtx = new StandardEvaluationContext(instance); @@ -675,7 +671,7 @@ public class EvaluationTests extends AbstractExpressionTests { e.setValue(ctx, "3"); } catch (SpelEvaluationException see) { - assertEquals(SpelMessage.UNABLE_TO_GROW_COLLECTION, see.getMessageCode()); + assertThat(see.getMessageCode()).isEqualTo(SpelMessage.UNABLE_TO_GROW_COLLECTION); assertThat(instance.getFoo().size()).isEqualTo(3); } } @@ -687,7 +683,7 @@ public class EvaluationTests extends AbstractExpressionTests { StandardEvaluationContext ctx = new StandardEvaluationContext(i); ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Expression e = parser.parseExpression("#this++"); - assertEquals(42,i.intValue()); + assertThat(i.intValue()).isEqualTo(42); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> e.getValue(ctx, Integer.class)) .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE)); @@ -702,48 +698,48 @@ public class EvaluationTests extends AbstractExpressionTests { // BigDecimal e = parser.parseExpression("bd++"); - assertTrue(new BigDecimal("2").equals(helper.bd)); + assertThat(new BigDecimal("2").equals(helper.bd)).isTrue(); BigDecimal return_bd = e.getValue(ctx, BigDecimal.class); - assertTrue(new BigDecimal("2").equals(return_bd)); - assertTrue(new BigDecimal("3").equals(helper.bd)); + assertThat(new BigDecimal("2").equals(return_bd)).isTrue(); + assertThat(new BigDecimal("3").equals(helper.bd)).isTrue(); // double e = parser.parseExpression("ddd++"); - assertEquals(2.0d, helper.ddd,0d); + assertThat((float) helper.ddd).isCloseTo((float) 2.0d, within((float) 0d)); double return_ddd = e.getValue(ctx, Double.TYPE); - assertEquals(2.0d, return_ddd,0d); - assertEquals(3.0d, helper.ddd,0d); + assertThat((float) return_ddd).isCloseTo((float) 2.0d, within((float) 0d)); + assertThat((float) helper.ddd).isCloseTo((float) 3.0d, within((float) 0d)); // float e = parser.parseExpression("fff++"); - assertEquals(3.0f, helper.fff,0d); + assertThat(helper.fff).isCloseTo(3.0f, within((float) 0d)); float return_fff = e.getValue(ctx, Float.TYPE); - assertEquals(3.0f, return_fff,0d); - assertEquals(4.0f, helper.fff,0d); + assertThat(return_fff).isCloseTo(3.0f, within((float) 0d)); + assertThat(helper.fff).isCloseTo(4.0f, within((float) 0d)); // long e = parser.parseExpression("lll++"); - assertEquals(66666L, helper.lll); + assertThat(helper.lll).isEqualTo(66666L); long return_lll = e.getValue(ctx, Long.TYPE); - assertEquals(66666L, return_lll); - assertEquals(66667L, helper.lll); + assertThat(return_lll).isEqualTo(66666L); + assertThat(helper.lll).isEqualTo(66667L); // int e = parser.parseExpression("iii++"); - assertEquals(42, helper.iii); + assertThat(helper.iii).isEqualTo(42); int return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(42, return_iii); - assertEquals(43, helper.iii); + assertThat(return_iii).isEqualTo(42); + assertThat(helper.iii).isEqualTo(43); return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(43, return_iii); - assertEquals(44, helper.iii); + assertThat(return_iii).isEqualTo(43); + assertThat(helper.iii).isEqualTo(44); // short e = parser.parseExpression("sss++"); - assertEquals(15, helper.sss); + assertThat(helper.sss).isEqualTo((short) 15); short return_sss = e.getValue(ctx, Short.TYPE); - assertEquals(15, return_sss); - assertEquals(16, helper.sss); + assertThat(return_sss).isEqualTo((short) 15); + assertThat(helper.sss).isEqualTo((short) 16); } @Test @@ -756,48 +752,48 @@ public class EvaluationTests extends AbstractExpressionTests { // BigDecimal e = parser.parseExpression("++bd"); - assertTrue(new BigDecimal("2").equals(helper.bd)); + assertThat(new BigDecimal("2").equals(helper.bd)).isTrue(); BigDecimal return_bd = e.getValue(ctx, BigDecimal.class); - assertTrue(new BigDecimal("3").equals(return_bd)); - assertTrue(new BigDecimal("3").equals(helper.bd)); + assertThat(new BigDecimal("3").equals(return_bd)).isTrue(); + assertThat(new BigDecimal("3").equals(helper.bd)).isTrue(); // double e = parser.parseExpression("++ddd"); - assertEquals(2.0d, helper.ddd ,0d); + assertThat((float) helper.ddd).isCloseTo((float) 2.0d, within((float) 0d)); double return_ddd = e.getValue(ctx, Double.TYPE); - assertEquals(3.0d, return_ddd, 0d); - assertEquals(3.0d, helper.ddd, 0d); + assertThat((float) return_ddd).isCloseTo((float) 3.0d, within((float) 0d)); + assertThat((float) helper.ddd).isCloseTo((float) 3.0d, within((float) 0d)); // float e = parser.parseExpression("++fff"); - assertEquals(3.0f, helper.fff, 0d); + assertThat(helper.fff).isCloseTo(3.0f, within((float) 0d)); float return_fff = e.getValue(ctx, Float.TYPE); - assertEquals(4.0f, return_fff, 0d); - assertEquals(4.0f, helper.fff, 0d); + assertThat(return_fff).isCloseTo(4.0f, within((float) 0d)); + assertThat(helper.fff).isCloseTo(4.0f, within((float) 0d)); // long e = parser.parseExpression("++lll"); - assertEquals(66666L, helper.lll); + assertThat(helper.lll).isEqualTo(66666L); long return_lll = e.getValue(ctx, Long.TYPE); - assertEquals(66667L, return_lll); - assertEquals(66667L, helper.lll); + assertThat(return_lll).isEqualTo(66667L); + assertThat(helper.lll).isEqualTo(66667L); // int e = parser.parseExpression("++iii"); - assertEquals(42, helper.iii); + assertThat(helper.iii).isEqualTo(42); int return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(43, return_iii); - assertEquals(43, helper.iii); + assertThat(return_iii).isEqualTo(43); + assertThat(helper.iii).isEqualTo(43); return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(44, return_iii); - assertEquals(44, helper.iii); + assertThat(return_iii).isEqualTo(44); + assertThat(helper.iii).isEqualTo(44); // short e = parser.parseExpression("++sss"); - assertEquals(15, helper.sss); + assertThat(helper.sss).isEqualTo((short) 15); int return_sss = (Integer) e.getValue(ctx); - assertEquals(16, return_sss); - assertEquals(16, helper.sss); + assertThat(return_sss).isEqualTo((short) 16); + assertThat(helper.sss).isEqualTo((short) 16); } @Test @@ -838,7 +834,7 @@ public class EvaluationTests extends AbstractExpressionTests { StandardEvaluationContext ctx = new StandardEvaluationContext(i); ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Expression e = parser.parseExpression("#this--"); - assertEquals(42, i.intValue()); + assertThat(i.intValue()).isEqualTo(42); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> e.getValue(ctx, Integer.class)) .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE)); @@ -853,48 +849,48 @@ public class EvaluationTests extends AbstractExpressionTests { // BigDecimal e = parser.parseExpression("bd--"); - assertTrue(new BigDecimal("2").equals(helper.bd)); + assertThat(new BigDecimal("2").equals(helper.bd)).isTrue(); BigDecimal return_bd = e.getValue(ctx,BigDecimal.class); - assertTrue(new BigDecimal("2").equals(return_bd)); - assertTrue(new BigDecimal("1").equals(helper.bd)); + assertThat(new BigDecimal("2").equals(return_bd)).isTrue(); + assertThat(new BigDecimal("1").equals(helper.bd)).isTrue(); // double e = parser.parseExpression("ddd--"); - assertEquals(2.0d, helper.ddd,0d); + assertThat((float) helper.ddd).isCloseTo((float) 2.0d, within((float) 0d)); double return_ddd = e.getValue(ctx, Double.TYPE); - assertEquals(2.0d, return_ddd,0d); - assertEquals(1.0d, helper.ddd,0d); + assertThat((float) return_ddd).isCloseTo((float) 2.0d, within((float) 0d)); + assertThat((float) helper.ddd).isCloseTo((float) 1.0d, within((float) 0d)); // float e = parser.parseExpression("fff--"); - assertEquals(3.0f, helper.fff,0d); + assertThat(helper.fff).isCloseTo(3.0f, within((float) 0d)); float return_fff = e.getValue(ctx, Float.TYPE); - assertEquals(3.0f, return_fff,0d); - assertEquals(2.0f, helper.fff,0d); + assertThat(return_fff).isCloseTo(3.0f, within((float) 0d)); + assertThat(helper.fff).isCloseTo(2.0f, within((float) 0d)); // long e = parser.parseExpression("lll--"); - assertEquals(66666L, helper.lll); + assertThat(helper.lll).isEqualTo(66666L); long return_lll = e.getValue(ctx, Long.TYPE); - assertEquals(66666L, return_lll); - assertEquals(66665L, helper.lll); + assertThat(return_lll).isEqualTo(66666L); + assertThat(helper.lll).isEqualTo(66665L); // int e = parser.parseExpression("iii--"); - assertEquals(42, helper.iii); + assertThat(helper.iii).isEqualTo(42); int return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(42, return_iii); - assertEquals(41, helper.iii); + assertThat(return_iii).isEqualTo(42); + assertThat(helper.iii).isEqualTo(41); return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(41, return_iii); - assertEquals(40, helper.iii); + assertThat(return_iii).isEqualTo(41); + assertThat(helper.iii).isEqualTo(40); // short e = parser.parseExpression("sss--"); - assertEquals(15, helper.sss); + assertThat(helper.sss).isEqualTo((short) 15); short return_sss = e.getValue(ctx, Short.TYPE); - assertEquals(15, return_sss); - assertEquals(14, helper.sss); + assertThat(return_sss).isEqualTo((short) 15); + assertThat(helper.sss).isEqualTo((short) 14); } @Test @@ -906,48 +902,48 @@ public class EvaluationTests extends AbstractExpressionTests { // BigDecimal e = parser.parseExpression("--bd"); - assertTrue(new BigDecimal("2").equals(helper.bd)); + assertThat(new BigDecimal("2").equals(helper.bd)).isTrue(); BigDecimal return_bd = e.getValue(ctx,BigDecimal.class); - assertTrue(new BigDecimal("1").equals(return_bd)); - assertTrue(new BigDecimal("1").equals(helper.bd)); + assertThat(new BigDecimal("1").equals(return_bd)).isTrue(); + assertThat(new BigDecimal("1").equals(helper.bd)).isTrue(); // double e = parser.parseExpression("--ddd"); - assertEquals(2.0d, helper.ddd,0d); + assertThat((float) helper.ddd).isCloseTo((float) 2.0d, within((float) 0d)); double return_ddd = e.getValue(ctx, Double.TYPE); - assertEquals(1.0d, return_ddd,0d); - assertEquals(1.0d, helper.ddd,0d); + assertThat((float) return_ddd).isCloseTo((float) 1.0d, within((float) 0d)); + assertThat((float) helper.ddd).isCloseTo((float) 1.0d, within((float) 0d)); // float e = parser.parseExpression("--fff"); - assertEquals(3.0f, helper.fff,0d); + assertThat(helper.fff).isCloseTo(3.0f, within((float) 0d)); float return_fff = e.getValue(ctx, Float.TYPE); - assertEquals(2.0f, return_fff,0d); - assertEquals(2.0f, helper.fff,0d); + assertThat(return_fff).isCloseTo(2.0f, within((float) 0d)); + assertThat(helper.fff).isCloseTo(2.0f, within((float) 0d)); // long e = parser.parseExpression("--lll"); - assertEquals(66666L, helper.lll); + assertThat(helper.lll).isEqualTo(66666L); long return_lll = e.getValue(ctx, Long.TYPE); - assertEquals(66665L, return_lll); - assertEquals(66665L, helper.lll); + assertThat(return_lll).isEqualTo(66665L); + assertThat(helper.lll).isEqualTo(66665L); // int e = parser.parseExpression("--iii"); - assertEquals(42, helper.iii); + assertThat(helper.iii).isEqualTo(42); int return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(41, return_iii); - assertEquals(41, helper.iii); + assertThat(return_iii).isEqualTo(41); + assertThat(helper.iii).isEqualTo(41); return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(40, return_iii); - assertEquals(40, helper.iii); + assertThat(return_iii).isEqualTo(40); + assertThat(helper.iii).isEqualTo(40); // short e = parser.parseExpression("--sss"); - assertEquals(15, helper.sss); + assertThat(helper.sss).isEqualTo((short) 15); int return_sss = (Integer)e.getValue(ctx); - assertEquals(14, return_sss); - assertEquals(14, helper.sss); + assertThat(return_sss).isEqualTo(14); + assertThat(helper.sss).isEqualTo((short) 14); } @Test @@ -995,20 +991,20 @@ public class EvaluationTests extends AbstractExpressionTests { // intArray[2] is 3 e = parser.parseExpression("intArray[#root.index1++]++"); e.getValue(ctx, Integer.class); - assertEquals(3, helper.index1); - assertEquals(4, helper.intArray[2]); + assertThat(helper.index1).isEqualTo(3); + assertThat(helper.intArray[2]).isEqualTo(4); // index1 is 3 intArray[3] is 4 e = parser.parseExpression("intArray[#root.index1++]--"); - assertEquals(4, e.getValue(ctx, Integer.class).intValue()); - assertEquals(4, helper.index1); - assertEquals(3, helper.intArray[3]); + assertThat(e.getValue(ctx, Integer.class).intValue()).isEqualTo(4); + assertThat(helper.index1).isEqualTo(4); + assertThat(helper.intArray[3]).isEqualTo(3); // index1 is 4, intArray[3] is 3 e = parser.parseExpression("intArray[--#root.index1]++"); - assertEquals(3, e.getValue(ctx, Integer.class).intValue()); - assertEquals(3, helper.index1); - assertEquals(4, helper.intArray[3]); + assertThat(e.getValue(ctx, Integer.class).intValue()).isEqualTo(3); + assertThat(helper.index1).isEqualTo(3); + assertThat(helper.intArray[3]).isEqualTo(4); } @@ -1167,49 +1163,49 @@ public class EvaluationTests extends AbstractExpressionTests { // Assign // iii=42 e = parser.parseExpression("iii=iii++"); - assertEquals(42, helper.iii); + assertThat(helper.iii).isEqualTo(42); int return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(42, helper.iii); - assertEquals(42, return_iii); + assertThat(helper.iii).isEqualTo(42); + assertThat(return_iii).isEqualTo(42); // Identifier e = parser.parseExpression("iii++"); - assertEquals(42, helper.iii); + assertThat(helper.iii).isEqualTo(42); return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(42, return_iii); - assertEquals(43, helper.iii); + assertThat(return_iii).isEqualTo(42); + assertThat(helper.iii).isEqualTo(43); e = parser.parseExpression("--iii"); - assertEquals(43, helper.iii); + assertThat(helper.iii).isEqualTo(43); return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(42, return_iii); - assertEquals(42, helper.iii); + assertThat(return_iii).isEqualTo(42); + assertThat(helper.iii).isEqualTo(42); e = parser.parseExpression("iii=99"); - assertEquals(42, helper.iii); + assertThat(helper.iii).isEqualTo(42); return_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(99, return_iii); - assertEquals(99, helper.iii); + assertThat(return_iii).isEqualTo(99); + assertThat(helper.iii).isEqualTo(99); // CompoundExpression // foo.iii == 99 e = parser.parseExpression("foo.iii++"); - assertEquals(99, helper.foo.iii); + assertThat(helper.foo.iii).isEqualTo(99); int return_foo_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(99, return_foo_iii); - assertEquals(100, helper.foo.iii); + assertThat(return_foo_iii).isEqualTo(99); + assertThat(helper.foo.iii).isEqualTo(100); e = parser.parseExpression("--foo.iii"); - assertEquals(100, helper.foo.iii); + assertThat(helper.foo.iii).isEqualTo(100); return_foo_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(99, return_foo_iii); - assertEquals(99, helper.foo.iii); + assertThat(return_foo_iii).isEqualTo(99); + assertThat(helper.foo.iii).isEqualTo(99); e = parser.parseExpression("foo.iii=999"); - assertEquals(99, helper.foo.iii); + assertThat(helper.foo.iii).isEqualTo(99); return_foo_iii = e.getValue(ctx, Integer.TYPE); - assertEquals(999, return_foo_iii); - assertEquals(999, helper.foo.iii); + assertThat(return_foo_iii).isEqualTo(999); + assertThat(helper.foo.iii).isEqualTo(999); // ConstructorReference expectFailNotAssignable(parser, ctx, "(new String('abc'))++"); @@ -1253,27 +1249,27 @@ public class EvaluationTests extends AbstractExpressionTests { expectFailNotDecrementable(parser, ctx, "--#wibble"); e = parser.parseExpression("#wibble=#wibble+#wibble"); String s = e.getValue(ctx, String.class); - assertEquals("hello worldhello world", s); - assertEquals("hello worldhello world",ctx.lookupVariable("wibble")); + assertThat(s).isEqualTo("hello worldhello world"); + assertThat(ctx.lookupVariable("wibble")).isEqualTo("hello worldhello world"); ctx.setVariable("wobble", 3); e = parser.parseExpression("#wobble++"); - assertEquals(3, ((Integer) ctx.lookupVariable("wobble")).intValue()); + assertThat(((Integer) ctx.lookupVariable("wobble")).intValue()).isEqualTo(3); int r = e.getValue(ctx, Integer.TYPE); - assertEquals(3, r); - assertEquals(4, ((Integer) ctx.lookupVariable("wobble")).intValue()); + assertThat(r).isEqualTo(3); + assertThat(((Integer) ctx.lookupVariable("wobble")).intValue()).isEqualTo(4); e = parser.parseExpression("--#wobble"); - assertEquals(4, ((Integer) ctx.lookupVariable("wobble")).intValue()); + assertThat(((Integer) ctx.lookupVariable("wobble")).intValue()).isEqualTo(4); r = e.getValue(ctx, Integer.TYPE); - assertEquals(3, r); - assertEquals(3, ((Integer) ctx.lookupVariable("wobble")).intValue()); + assertThat(r).isEqualTo(3); + assertThat(((Integer) ctx.lookupVariable("wobble")).intValue()).isEqualTo(3); e = parser.parseExpression("#wobble=34"); - assertEquals(3, ((Integer) ctx.lookupVariable("wobble")).intValue()); + assertThat(((Integer) ctx.lookupVariable("wobble")).intValue()).isEqualTo(3); r = e.getValue(ctx, Integer.TYPE); - assertEquals(34, r); - assertEquals(34, ((Integer) ctx.lookupVariable("wobble")).intValue()); + assertThat(r).isEqualTo(34); + assertThat(((Integer) ctx.lookupVariable("wobble")).intValue()).isEqualTo(34); // Projection expectFailNotIncrementable(parser, ctx, "({1,2,3}.![#isEven(#this)])++"); // projection would be {false,true,false} @@ -1299,22 +1295,22 @@ public class EvaluationTests extends AbstractExpressionTests { // PropertyOrFieldReference helper.iii = 42; e = parser.parseExpression("iii++"); - assertEquals(42, helper.iii); + assertThat(helper.iii).isEqualTo(42); r = e.getValue(ctx, Integer.TYPE); - assertEquals(42, r); - assertEquals(43, helper.iii); + assertThat(r).isEqualTo(42); + assertThat(helper.iii).isEqualTo(43); e = parser.parseExpression("--iii"); - assertEquals(43, helper.iii); + assertThat(helper.iii).isEqualTo(43); r = e.getValue(ctx, Integer.TYPE); - assertEquals(42, r); - assertEquals(42, helper.iii); + assertThat(r).isEqualTo(42); + assertThat(helper.iii).isEqualTo(42); e = parser.parseExpression("iii=100"); - assertEquals(42, helper.iii); + assertThat(helper.iii).isEqualTo(42); r = e.getValue(ctx, Integer.TYPE); - assertEquals(100, r); - assertEquals(100, helper.iii); + assertThat(r).isEqualTo(100); + assertThat(helper.iii).isEqualTo(100); } private void expectFailNotAssignable(ExpressionParser parser, EvaluationContext eContext, String expressionString) { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java index fd0df8814c5..2396b17f0d9 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java @@ -37,7 +37,6 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; ///CLOVER:OFF @@ -79,8 +78,8 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests { // They are reusable value = expr.getValue(); - assertEquals("hello world", value); - assertEquals(String.class, value.getClass()); + assertThat(value).isEqualTo("hello world"); + assertThat(value.getClass()).isEqualTo(String.class); } catch (EvaluationException | ParseException ex) { throw new AssertionError(ex.getMessage(), ex); @@ -103,16 +102,16 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests { Expression expr = parser.parseRaw("#favouriteColour"); Object value = expr.getValue(ctx); - assertEquals("blue", value); + assertThat(value).isEqualTo("blue"); expr = parser.parseRaw("#primes.get(1)"); value = expr.getValue(ctx); - assertEquals(3, value); + assertThat(value).isEqualTo(3); // all prime numbers > 10 from the list (using selection ?{...}) expr = parser.parseRaw("#primes.?[#this>10]"); value = expr.getValue(ctx); - assertEquals("[11, 13, 17]", value.toString()); + assertThat(value.toString()).isEqualTo("[11, 13, 17]"); } @@ -141,30 +140,30 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests { // read it, set it, read it again Expression expr = parser.parseRaw("str"); Object value = expr.getValue(ctx); - assertEquals("wibble", value); + assertThat(value).isEqualTo("wibble"); expr = parser.parseRaw("str"); expr.setValue(ctx, "wobble"); expr = parser.parseRaw("str"); value = expr.getValue(ctx); - assertEquals("wobble", value); + assertThat(value).isEqualTo("wobble"); // or using assignment within the expression expr = parser.parseRaw("str='wabble'"); value = expr.getValue(ctx); expr = parser.parseRaw("str"); value = expr.getValue(ctx); - assertEquals("wabble", value); + assertThat(value).isEqualTo("wabble"); // private property will be accessed through getter() expr = parser.parseRaw("property"); value = expr.getValue(ctx); - assertEquals(42, value); + assertThat(value).isEqualTo(42); // ... and set through setter expr = parser.parseRaw("property=4"); value = expr.getValue(ctx); expr = parser.parseRaw("property"); value = expr.getValue(ctx); - assertEquals(4,value); + assertThat(value).isEqualTo(4); } public static String repeat(String s) { return s+s; } @@ -183,7 +182,7 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests { Expression expr = parser.parseRaw("#repeat('hello')"); Object value = expr.getValue(ctx); - assertEquals("hellohello", value); + assertThat(value).isEqualTo("hellohello"); } catch (EvaluationException | ParseException ex) { @@ -204,7 +203,7 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests { ctx.addPropertyAccessor(new FruitColourAccessor()); Expression expr = parser.parseRaw("orange"); Object value = expr.getValue(ctx); - assertEquals(Color.orange, value); + assertThat(value).isEqualTo(Color.orange); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> expr.setValue(ctx, Color.blue)) .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL)); @@ -220,7 +219,7 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests { ctx.addPropertyAccessor(new VegetableColourAccessor()); Expression expr = parser.parseRaw("pea"); Object value = expr.getValue(ctx); - assertEquals(Color.green, value); + assertThat(value).isEqualTo(Color.green); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> expr.setValue(ctx, Color.blue)) diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java index dbaf3bc82a8..63e835ee07f 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java @@ -32,9 +32,6 @@ import org.springframework.expression.spel.testresources.Inventor; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; /** * Tests for the expression state object - some features are not yet exploited in the language (eg nested scopes) @@ -48,7 +45,7 @@ public class ExpressionStateTests extends AbstractExpressionTests { public void testConstruction() { EvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); ExpressionState state = new ExpressionState(context); - assertEquals(context, state.getEvaluationContext()); + assertThat(state.getEvaluationContext()).isEqualTo(context); } // Local variables are in variable scopes which come and go during evaluation. Normal variables are @@ -59,125 +56,128 @@ public class ExpressionStateTests extends AbstractExpressionTests { ExpressionState state = getState(); Object value = state.lookupLocalVariable("foo"); - assertNull(value); + assertThat(value).isNull(); state.setLocalVariable("foo",34); value = state.lookupLocalVariable("foo"); - assertEquals(34, value); + assertThat(value).isEqualTo(34); state.setLocalVariable("foo", null); value = state.lookupLocalVariable("foo"); - assertEquals(null, value); + assertThat(value).isEqualTo(null); } @Test public void testVariables() { ExpressionState state = getState(); TypedValue typedValue = state.lookupVariable("foo"); - assertEquals(TypedValue.NULL, typedValue); + assertThat(typedValue).isEqualTo(TypedValue.NULL); state.setVariable("foo",34); typedValue = state.lookupVariable("foo"); - assertEquals(34, typedValue.getValue()); - assertEquals(Integer.class, typedValue.getTypeDescriptor().getType()); + assertThat(typedValue.getValue()).isEqualTo(34); + assertThat(typedValue.getTypeDescriptor().getType()).isEqualTo(Integer.class); state.setVariable("foo","abc"); typedValue = state.lookupVariable("foo"); - assertEquals("abc", typedValue.getValue()); - assertEquals(String.class, typedValue.getTypeDescriptor().getType()); + assertThat(typedValue.getValue()).isEqualTo("abc"); + assertThat(typedValue.getTypeDescriptor().getType()).isEqualTo(String.class); } @Test public void testNoVariableInterference() { ExpressionState state = getState(); TypedValue typedValue = state.lookupVariable("foo"); - assertEquals(TypedValue.NULL, typedValue); + assertThat(typedValue).isEqualTo(TypedValue.NULL); state.setLocalVariable("foo",34); typedValue = state.lookupVariable("foo"); - assertEquals(TypedValue.NULL, typedValue); + assertThat(typedValue).isEqualTo(TypedValue.NULL); state.setVariable("goo", "hello"); - assertNull(state.lookupLocalVariable("goo")); + assertThat(state.lookupLocalVariable("goo")).isNull(); } @Test public void testLocalVariableNestedScopes() { ExpressionState state = getState(); - assertEquals(null, state.lookupLocalVariable("foo")); + assertThat(state.lookupLocalVariable("foo")).isEqualTo(null); state.setLocalVariable("foo",12); - assertEquals(12, state.lookupLocalVariable("foo")); + assertThat(state.lookupLocalVariable("foo")).isEqualTo(12); state.enterScope(null); - assertEquals(12, state.lookupLocalVariable("foo")); // found in upper scope + // found in upper scope + assertThat(state.lookupLocalVariable("foo")).isEqualTo(12); state.setLocalVariable("foo","abc"); - assertEquals("abc", state.lookupLocalVariable("foo")); // found in nested scope + // found in nested scope + assertThat(state.lookupLocalVariable("foo")).isEqualTo("abc"); state.exitScope(); - assertEquals(12, state.lookupLocalVariable("foo")); // found in nested scope + // found in nested scope + assertThat(state.lookupLocalVariable("foo")).isEqualTo(12); } @Test public void testRootContextObject() { ExpressionState state = getState(); - assertEquals(Inventor.class, state.getRootContextObject().getValue().getClass()); + assertThat(state.getRootContextObject().getValue().getClass()).isEqualTo(Inventor.class); // although the root object is being set on the evaluation context, the value in the 'state' remains what it was when constructed ((StandardEvaluationContext) state.getEvaluationContext()).setRootObject(null); - assertEquals(Inventor.class, state.getRootContextObject().getValue().getClass()); + assertThat(state.getRootContextObject().getValue().getClass()).isEqualTo(Inventor.class); // assertEquals(null, state.getRootContextObject().getValue()); state = new ExpressionState(new StandardEvaluationContext()); - assertEquals(TypedValue.NULL, state.getRootContextObject()); + assertThat(state.getRootContextObject()).isEqualTo(TypedValue.NULL); ((StandardEvaluationContext) state.getEvaluationContext()).setRootObject(null); - assertEquals(null, state.getRootContextObject().getValue()); + assertThat(state.getRootContextObject().getValue()).isEqualTo(null); } @Test public void testActiveContextObject() { ExpressionState state = getState(); - assertEquals(state.getRootContextObject().getValue(), state.getActiveContextObject().getValue()); + assertThat(state.getActiveContextObject().getValue()).isEqualTo(state.getRootContextObject().getValue()); assertThatIllegalStateException().isThrownBy( state::popActiveContextObject); state.pushActiveContextObject(new TypedValue(34)); - assertEquals(34, state.getActiveContextObject().getValue()); + assertThat(state.getActiveContextObject().getValue()).isEqualTo(34); state.pushActiveContextObject(new TypedValue("hello")); - assertEquals("hello", state.getActiveContextObject().getValue()); + assertThat(state.getActiveContextObject().getValue()).isEqualTo("hello"); state.popActiveContextObject(); - assertEquals(34, state.getActiveContextObject().getValue()); + assertThat(state.getActiveContextObject().getValue()).isEqualTo(34); state.popActiveContextObject(); - assertEquals(state.getRootContextObject().getValue(), state.getActiveContextObject().getValue()); + assertThat(state.getActiveContextObject().getValue()).isEqualTo(state.getRootContextObject().getValue()); state = new ExpressionState(new StandardEvaluationContext()); - assertEquals(TypedValue.NULL, state.getActiveContextObject()); + assertThat(state.getActiveContextObject()).isEqualTo(TypedValue.NULL); } @Test public void testPopulatedNestedScopes() { ExpressionState state = getState(); - assertNull(state.lookupLocalVariable("foo")); + assertThat(state.lookupLocalVariable("foo")).isNull(); state.enterScope("foo",34); - assertEquals(34, state.lookupLocalVariable("foo")); + assertThat(state.lookupLocalVariable("foo")).isEqualTo(34); state.enterScope(null); state.setLocalVariable("foo", 12); - assertEquals(12, state.lookupLocalVariable("foo")); + assertThat(state.lookupLocalVariable("foo")).isEqualTo(12); state.exitScope(); - assertEquals(34, state.lookupLocalVariable("foo")); + assertThat(state.lookupLocalVariable("foo")).isEqualTo(34); state.exitScope(); - assertNull(state.lookupLocalVariable("goo")); + assertThat(state.lookupLocalVariable("goo")).isNull(); } @Test @@ -187,33 +187,33 @@ public class ExpressionStateTests extends AbstractExpressionTests { // supplied should override root on context ExpressionState state = new ExpressionState(ctx,new TypedValue("i am a string")); TypedValue stateRoot = state.getRootContextObject(); - assertEquals(String.class, stateRoot.getTypeDescriptor().getType()); - assertEquals("i am a string", stateRoot.getValue()); + assertThat(stateRoot.getTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(stateRoot.getValue()).isEqualTo("i am a string"); } @Test public void testPopulatedNestedScopesMap() { ExpressionState state = getState(); - assertNull(state.lookupLocalVariable("foo")); - assertNull(state.lookupLocalVariable("goo")); + assertThat(state.lookupLocalVariable("foo")).isNull(); + assertThat(state.lookupLocalVariable("goo")).isNull(); Map m = new HashMap<>(); m.put("foo", 34); m.put("goo", "abc"); state.enterScope(m); - assertEquals(34, state.lookupLocalVariable("foo")); - assertEquals("abc", state.lookupLocalVariable("goo")); + assertThat(state.lookupLocalVariable("foo")).isEqualTo(34); + assertThat(state.lookupLocalVariable("goo")).isEqualTo("abc"); state.enterScope(null); state.setLocalVariable("foo",12); - assertEquals(12, state.lookupLocalVariable("foo")); - assertEquals("abc", state.lookupLocalVariable("goo")); + assertThat(state.lookupLocalVariable("foo")).isEqualTo(12); + assertThat(state.lookupLocalVariable("goo")).isEqualTo("abc"); state.exitScope(); state.exitScope(); - assertNull(state.lookupLocalVariable("foo")); - assertNull(state.lookupLocalVariable("goo")); + assertThat(state.lookupLocalVariable("foo")).isNull(); + assertThat(state.lookupLocalVariable("goo")).isNull(); } @Test @@ -231,14 +231,14 @@ public class ExpressionStateTests extends AbstractExpressionTests { @Test public void testComparator() { ExpressionState state = getState(); - assertEquals(state.getEvaluationContext().getTypeComparator(), state.getTypeComparator()); + assertThat(state.getTypeComparator()).isEqualTo(state.getEvaluationContext().getTypeComparator()); } @Test public void testTypeLocator() throws EvaluationException { ExpressionState state = getState(); - assertNotNull(state.getEvaluationContext().getTypeLocator()); - assertEquals(Integer.class, state.findType("java.lang.Integer")); + assertThat(state.getEvaluationContext().getTypeLocator()).isNotNull(); + assertThat(state.findType("java.lang.Integer")).isEqualTo(Integer.class); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> state.findType("someMadeUpName")) .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.TYPE_NOT_FOUND)); @@ -249,16 +249,16 @@ public class ExpressionStateTests extends AbstractExpressionTests { public void testTypeConversion() throws EvaluationException { ExpressionState state = getState(); String s = (String) state.convertValue(34, TypeDescriptor.valueOf(String.class)); - assertEquals("34", s); + assertThat(s).isEqualTo("34"); s = (String)state.convertValue(new TypedValue(34), TypeDescriptor.valueOf(String.class)); - assertEquals("34", s); + assertThat(s).isEqualTo("34"); } @Test public void testPropertyAccessors() { ExpressionState state = getState(); - assertEquals(state.getEvaluationContext().getPropertyAccessors(), state.getPropertyAccessors()); + assertThat(state.getPropertyAccessors()).isEqualTo(state.getEvaluationContext().getPropertyAccessors()); } /** diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java index cc00e850150..d67ec475293 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java @@ -33,9 +33,7 @@ import org.springframework.expression.Expression; import org.springframework.expression.TypeConverter; import org.springframework.expression.spel.support.StandardEvaluationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Expression evaluation where the TypeConverter plugged in is the @@ -76,29 +74,30 @@ public class ExpressionWithConversionTests extends AbstractExpressionTests { // ArrayList containing List to List Class clazz = typeDescriptorForListOfString.getElementTypeDescriptor().getType(); - assertEquals(String.class,clazz); + assertThat(clazz).isEqualTo(String.class); List l = (List) tcs.convertValue(listOfInteger, TypeDescriptor.forObject(listOfInteger), typeDescriptorForListOfString); - assertNotNull(l); + assertThat(l).isNotNull(); // ArrayList containing List to List clazz = typeDescriptorForListOfInteger.getElementTypeDescriptor().getType(); - assertEquals(Integer.class,clazz); + assertThat(clazz).isEqualTo(Integer.class); l = (List) tcs.convertValue(listOfString, TypeDescriptor.forObject(listOfString), typeDescriptorForListOfString); - assertNotNull(l); + assertThat(l).isNotNull(); } @Test public void testSetParameterizedList() throws Exception { StandardEvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); Expression e = parser.parseExpression("listOfInteger.size()"); - assertEquals(0,e.getValue(context,Integer.class).intValue()); + assertThat(e.getValue(context, Integer.class).intValue()).isEqualTo(0); context.setTypeConverter(new TypeConvertorUsingConversionService()); // Assign a List to the List field - the component elements should be converted parser.parseExpression("listOfInteger").setValue(context,listOfString); - assertEquals(3,e.getValue(context,Integer.class).intValue()); // size now 3 + // size now 3 + assertThat(e.getValue(context, Integer.class).intValue()).isEqualTo(3); Class clazz = parser.parseExpression("listOfInteger[1].getClass()").getValue(context, Class.class); // element type correctly Integer - assertEquals(Integer.class,clazz); + assertThat(clazz).isEqualTo(Integer.class); } @Test @@ -120,17 +119,17 @@ public class ExpressionWithConversionTests extends AbstractExpressionTests { TypeDescriptor collectionType = new TypeDescriptor(new MethodParameter(TestTarget.class.getDeclaredMethod( "sum", Collection.class), 0)); // The type conversion is possible - assertTrue(evaluationContext.getTypeConverter() - .canConvert(TypeDescriptor.valueOf(String.class), collectionType)); + assertThat(evaluationContext.getTypeConverter() + .canConvert(TypeDescriptor.valueOf(String.class), collectionType)).isTrue(); // ... and it can be done successfully - assertEquals("[1, 2, 3, 4]", evaluationContext.getTypeConverter().convertValue("1,2,3,4", TypeDescriptor.valueOf(String.class), collectionType).toString()); + assertThat(evaluationContext.getTypeConverter().convertValue("1,2,3,4", TypeDescriptor.valueOf(String.class), collectionType).toString()).isEqualTo("[1, 2, 3, 4]"); evaluationContext.setVariable("target", new TestTarget()); // OK up to here, so the evaluation should be fine... // ... but this fails int result = (Integer) parser.parseExpression("#target.sum(#root)").getValue(evaluationContext, "1,2,3,4"); - assertEquals("Wrong result: " + result, 10, result); + assertThat(result).as("Wrong result: " + result).isEqualTo(10); } @@ -145,26 +144,26 @@ public class ExpressionWithConversionTests extends AbstractExpressionTests { Expression expression = parser.parseExpression("foos"); expression.setValue(context, foos); Foo baz = root.getFoos().iterator().next(); - assertEquals("baz", baz.value); + assertThat(baz.value).isEqualTo("baz"); // method call expression = parser.parseExpression("setFoos(#foos)"); context.setVariable("foos", foos); expression.getValue(context); baz = root.getFoos().iterator().next(); - assertEquals("baz", baz.value); + assertThat(baz.value).isEqualTo("baz"); // method call with result from method call expression = parser.parseExpression("setFoos(getFoosAsStrings())"); expression.getValue(context); baz = root.getFoos().iterator().next(); - assertEquals("baz", baz.value); + assertThat(baz.value).isEqualTo("baz"); // method call with result from method call expression = parser.parseExpression("setFoos(getFoosAsObjects())"); expression.getValue(context); baz = root.getFoos().iterator().next(); - assertEquals("baz", baz.value); + assertThat(baz.value).isEqualTo("baz"); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/InProgressTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/InProgressTests.java index e5f708559fd..4238440be8a 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/InProgressTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/InProgressTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.expression.spel.standard.SpelExpression; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * These are tests for language features that are not yet considered 'live'. Either missing implementation or @@ -79,7 +79,7 @@ public class InProgressTests extends AbstractExpressionTests { @Test public void testProjection06() throws Exception { SpelExpression expr = (SpelExpression) parser.parseExpression("'abc'.![true]"); - assertEquals("'abc'.![true]", expr.toStringAST()); + assertThat(expr.toStringAST()).isEqualTo("'abc'.![true]"); } // SELECTION @@ -142,11 +142,11 @@ public class InProgressTests extends AbstractExpressionTests { @Test public void testSelectionAST() throws Exception { SpelExpression expr = (SpelExpression) parser.parseExpression("'abc'.^[true]"); - assertEquals("'abc'.^[true]", expr.toStringAST()); + assertThat(expr.toStringAST()).isEqualTo("'abc'.^[true]"); expr = (SpelExpression) parser.parseExpression("'abc'.?[true]"); - assertEquals("'abc'.?[true]", expr.toStringAST()); + assertThat(expr.toStringAST()).isEqualTo("'abc'.?[true]"); expr = (SpelExpression) parser.parseExpression("'abc'.$[true]"); - assertEquals("'abc'.$[true]", expr.toStringAST()); + assertThat(expr.toStringAST()).isEqualTo("'abc'.$[true]"); } // Constructor invocation diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java index 7a5f4d71e14..1df09488242 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java @@ -37,8 +37,7 @@ import org.springframework.expression.TypedValue; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("rawtypes") public class IndexingTests { @@ -50,11 +49,11 @@ public class IndexingTests { this.property = property; SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("property"); - assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.HashMap", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); - assertEquals(property, expression.getValue(this, Map.class)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.HashMap"); + assertThat(expression.getValue(this)).isEqualTo(property); + assertThat(expression.getValue(this, Map.class)).isEqualTo(property); expression = parser.parseExpression("property['foo']"); - assertEquals("bar", expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo("bar"); } @FieldAnnotation @@ -71,11 +70,11 @@ public class IndexingTests { context.addPropertyAccessor(new MapAccessor()); context.setRootObject(property); Expression expression = parser.parseExpression("property"); - assertEquals("java.util.HashMap", expression.getValueTypeDescriptor(context).toString()); - assertEquals(map, expression.getValue(context)); - assertEquals(map, expression.getValue(context, Map.class)); + assertThat(expression.getValueTypeDescriptor(context).toString()).isEqualTo("java.util.HashMap"); + assertThat(expression.getValue(context)).isEqualTo(map); + assertThat(expression.getValue(context, Map.class)).isEqualTo(map); expression = parser.parseExpression("property['foo']"); - assertEquals("bar", expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("bar"); } public static class MapAccessor implements PropertyAccessor { @@ -116,12 +115,12 @@ public class IndexingTests { this.property = property; SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("property"); - assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.HashMap", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.HashMap"); + assertThat(expression.getValue(this)).isEqualTo(property); expression = parser.parseExpression("property['foo']"); - assertEquals("bar", expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo("bar"); expression.setValue(this, "baz"); - assertEquals("baz", expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo("baz"); } @Test @@ -131,12 +130,12 @@ public class IndexingTests { this.parameterizedMap = property; SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("parameterizedMap"); - assertEquals("java.util.HashMap", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("java.util.HashMap"); + assertThat(expression.getValue(this)).isEqualTo(property); expression = parser.parseExpression("parameterizedMap['9']"); - assertEquals(3, expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo(3); expression.setValue(this, "37"); - assertEquals(37, expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo(37); } public Map parameterizedMap; @@ -145,12 +144,12 @@ public class IndexingTests { public void setPropertyContainingMapAutoGrow() { SpelExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, false)); Expression expression = parser.parseExpression("parameterizedMap"); - assertEquals("java.util.Map", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("java.util.Map"); + assertThat(expression.getValue(this)).isEqualTo(property); expression = parser.parseExpression("parameterizedMap['9']"); - assertEquals(null, expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo(null); expression.setValue(this, "37"); - assertEquals(37, expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo(37); } @Test @@ -160,10 +159,10 @@ public class IndexingTests { this.property = property; SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("property"); - assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList"); + assertThat(expression.getValue(this)).isEqualTo(property); expression = parser.parseExpression("property[0]"); - assertEquals("bar", expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo("bar"); } @Test @@ -173,12 +172,12 @@ public class IndexingTests { this.property = property; SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("property"); - assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList"); + assertThat(expression.getValue(this)).isEqualTo(property); expression = parser.parseExpression("property[0]"); - assertEquals(3, expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo(3); expression.setValue(this, "4"); - assertEquals("4", expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo("4"); } @Test @@ -187,14 +186,14 @@ public class IndexingTests { this.property = property; SpelExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Expression expression = parser.parseExpression("property"); - assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList"); + assertThat(expression.getValue(this)).isEqualTo(property); expression = parser.parseExpression("property[0]"); try { expression.setValue(this, "4"); } catch (EvaluationException ex) { - assertTrue(ex.getMessage().startsWith("EL1053E")); + assertThat(ex.getMessage().startsWith("EL1053E")).isTrue(); } } @@ -205,10 +204,10 @@ public class IndexingTests { this.parameterizedList = property; SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("parameterizedList"); - assertEquals("java.util.ArrayList", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("java.util.ArrayList"); + assertThat(expression.getValue(this)).isEqualTo(property); expression = parser.parseExpression("parameterizedList[0]"); - assertEquals(3, expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo(3); } public List parameterizedList; @@ -220,10 +219,10 @@ public class IndexingTests { this.parameterizedListOfList = property; SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("parameterizedListOfList[0]"); - assertEquals("java.util.Arrays$ArrayList", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property.get(0), expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("java.util.Arrays$ArrayList"); + assertThat(expression.getValue(this)).isEqualTo(property.get(0)); expression = parser.parseExpression("parameterizedListOfList[0][0]"); - assertEquals(3, expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo(3); } public List> parameterizedListOfList; @@ -235,12 +234,12 @@ public class IndexingTests { this.parameterizedList = property; SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("parameterizedList"); - assertEquals("java.util.ArrayList", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("java.util.ArrayList"); + assertThat(expression.getValue(this)).isEqualTo(property); expression = parser.parseExpression("parameterizedList[0]"); - assertEquals(3, expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo(3); expression.setValue(this, "4"); - assertEquals(4, expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo(4); } @Test @@ -248,14 +247,14 @@ public class IndexingTests { SpelParserConfiguration configuration = new SpelParserConfiguration(true, true); SpelExpressionParser parser = new SpelExpressionParser(configuration); Expression expression = parser.parseExpression("property"); - assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.lang.Object", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.lang.Object"); + assertThat(expression.getValue(this)).isEqualTo(property); expression = parser.parseExpression("property[0]"); try { - assertEquals("bar", expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo("bar"); } catch (EvaluationException ex) { - assertTrue(ex.getMessage().startsWith("EL1027E")); + assertThat(ex.getMessage().startsWith("EL1027E")).isTrue(); } } @@ -266,14 +265,14 @@ public class IndexingTests { SpelParserConfiguration configuration = new SpelParserConfiguration(true, true); SpelExpressionParser parser = new SpelExpressionParser(configuration); Expression expression = parser.parseExpression("property"); - assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList"); + assertThat(expression.getValue(this)).isEqualTo(property); expression = parser.parseExpression("property[0]"); try { - assertEquals("bar", expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo("bar"); } catch (EvaluationException ex) { - assertTrue(ex.getMessage().startsWith("EL1053E")); + assertThat(ex.getMessage().startsWith("EL1053E")).isTrue(); } } @@ -284,14 +283,14 @@ public class IndexingTests { SpelParserConfiguration configuration = new SpelParserConfiguration(true, true); SpelExpressionParser parser = new SpelExpressionParser(configuration); Expression expression = parser.parseExpression("property2"); - assertEquals("java.util.ArrayList", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property2, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("java.util.ArrayList"); + assertThat(expression.getValue(this)).isEqualTo(property2); expression = parser.parseExpression("property2[0]"); try { - assertEquals("bar", expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo("bar"); } catch (EvaluationException ex) { - assertTrue(ex.getMessage().startsWith("EL1053E")); + assertThat(ex.getMessage().startsWith("EL1053E")).isTrue(); } } @@ -303,10 +302,10 @@ public class IndexingTests { this.property = property; SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("property"); - assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.lang.String[]", expression.getValueTypeDescriptor(this).toString()); - assertEquals(property, expression.getValue(this)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.lang.String[]"); + assertThat(expression.getValue(this)).isEqualTo(property); expression = parser.parseExpression("property[0]"); - assertEquals("bar", expression.getValue(this)); + assertThat(expression.getValue(this)).isEqualTo("bar"); } @Test @@ -314,8 +313,8 @@ public class IndexingTests { listOfScalarNotGeneric = new ArrayList(); SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("listOfScalarNotGeneric"); - assertEquals("java.util.ArrayList", expression.getValueTypeDescriptor(this).toString()); - assertEquals("", expression.getValue(this, String.class)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("java.util.ArrayList"); + assertThat(expression.getValue(this, String.class)).isEqualTo(""); } @SuppressWarnings("unchecked") @@ -326,15 +325,15 @@ public class IndexingTests { listNotGeneric.add(6); SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("listNotGeneric"); - assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList", expression.getValueTypeDescriptor(this).toString()); - assertEquals("5,6", expression.getValue(this, String.class)); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList"); + assertThat(expression.getValue(this, String.class)).isEqualTo("5,6"); } @Test public void resolveCollectionElementTypeNull() { SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("listNotGeneric"); - assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.List", expression.getValueTypeDescriptor(this).toString()); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.List"); } @FieldAnnotation @@ -354,7 +353,7 @@ public class IndexingTests { mapNotGeneric.put("bonusAmount", 7.17); SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("mapNotGeneric"); - assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.HashMap", expression.getValueTypeDescriptor(this).toString()); + assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.HashMap"); } @FieldAnnotation @@ -367,7 +366,7 @@ public class IndexingTests { listOfScalarNotGeneric.add("5"); SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("listOfScalarNotGeneric[0]"); - assertEquals(new Integer(5), expression.getValue(this, Integer.class)); + assertThat(expression.getValue(this, Integer.class)).isEqualTo(new Integer(5)); } public List listOfScalarNotGeneric; @@ -382,7 +381,7 @@ public class IndexingTests { listOfMapsNotGeneric.add(map); SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("listOfMapsNotGeneric[0]['fruit']"); - assertEquals("apple", expression.getValue(this, String.class)); + assertThat(expression.getValue(this, String.class)).isEqualTo("apple"); } public List listOfMapsNotGeneric; diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java index 0969b8fa16d..08c1e88c0aa 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java @@ -25,9 +25,8 @@ import org.springframework.expression.spel.ast.InlineList; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Test usage of inline lists. @@ -147,13 +146,14 @@ public class ListTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expression = (SpelExpression) parser.parseExpression(expressionText); SpelNode node = expression.getAST(); - assertTrue(node instanceof InlineList); + boolean condition = node instanceof InlineList; + assertThat(condition).isTrue(); InlineList inlineList = (InlineList) node; if (expectedToBeConstant) { - assertTrue(inlineList.isConstant()); + assertThat(inlineList.isConstant()).isTrue(); } else { - assertFalse(inlineList.isConstant()); + assertThat(inlineList.isConstant()).isFalse(); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/LiteralExpressionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/LiteralExpressionTests.java index 9e127204eb3..6acbce3dcc5 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/LiteralExpressionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/LiteralExpressionTests.java @@ -25,8 +25,6 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; /** * @author Andy Clement @@ -45,10 +43,10 @@ public class LiteralExpressionTests { assertThat(lEx.getValue(new Rooty(), String.class)).isInstanceOf(String.class).isEqualTo("somevalue"); assertThat(lEx.getValue(ctx, new Rooty())).isInstanceOf(String.class).isEqualTo("somevalue"); assertThat(lEx.getValue(ctx, new Rooty(),String.class)).isInstanceOf(String.class).isEqualTo("somevalue"); - assertEquals("somevalue", lEx.getExpressionString()); - assertFalse(lEx.isWritable(new StandardEvaluationContext())); - assertFalse(lEx.isWritable(new Rooty())); - assertFalse(lEx.isWritable(new StandardEvaluationContext(), new Rooty())); + assertThat(lEx.getExpressionString()).isEqualTo("somevalue"); + assertThat(lEx.isWritable(new StandardEvaluationContext())).isFalse(); + assertThat(lEx.isWritable(new Rooty())).isFalse(); + assertThat(lEx.isWritable(new StandardEvaluationContext(), new Rooty())).isFalse(); } static class Rooty {} @@ -69,14 +67,14 @@ public class LiteralExpressionTests { @Test public void testGetValueType() throws Exception { LiteralExpression lEx = new LiteralExpression("somevalue"); - assertEquals(String.class, lEx.getValueType()); - assertEquals(String.class, lEx.getValueType(new StandardEvaluationContext())); - assertEquals(String.class, lEx.getValueType(new Rooty())); - assertEquals(String.class, lEx.getValueType(new StandardEvaluationContext(), new Rooty())); - assertEquals(String.class, lEx.getValueTypeDescriptor().getType()); - assertEquals(String.class, lEx.getValueTypeDescriptor(new StandardEvaluationContext()).getType()); - assertEquals(String.class, lEx.getValueTypeDescriptor(new Rooty()).getType()); - assertEquals(String.class, lEx.getValueTypeDescriptor(new StandardEvaluationContext(), new Rooty()).getType()); + assertThat(lEx.getValueType()).isEqualTo(String.class); + assertThat(lEx.getValueType(new StandardEvaluationContext())).isEqualTo(String.class); + assertThat(lEx.getValueType(new Rooty())).isEqualTo(String.class); + assertThat(lEx.getValueType(new StandardEvaluationContext(), new Rooty())).isEqualTo(String.class); + assertThat(lEx.getValueTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(lEx.getValueTypeDescriptor(new StandardEvaluationContext()).getType()).isEqualTo(String.class); + assertThat(lEx.getValueTypeDescriptor(new Rooty()).getType()).isEqualTo(String.class); + assertThat(lEx.getValueTypeDescriptor(new StandardEvaluationContext(), new Rooty()).getType()).isEqualTo(String.class); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/LiteralTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/LiteralTests.java index 4e80ba5a367..16c38a63979 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/LiteralTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/LiteralTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.support.StandardEvaluationContext; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests the evaluation of basic literals: boolean, integer, hex integer, long, real, null, date @@ -165,10 +165,10 @@ public class LiteralTests extends AbstractExpressionTests { @Test public void testNotWritable() throws Exception { SpelExpression expr = (SpelExpression)parser.parseExpression("37"); - assertFalse(expr.isWritable(new StandardEvaluationContext())); + assertThat(expr.isWritable(new StandardEvaluationContext())).isFalse(); expr = (SpelExpression)parser.parseExpression("37L"); - assertFalse(expr.isWritable(new StandardEvaluationContext())); + assertThat(expr.isWritable(new StandardEvaluationContext())).isFalse(); expr = (SpelExpression)parser.parseExpression("true"); - assertFalse(expr.isWritable(new StandardEvaluationContext())); + assertThat(expr.isWritable(new StandardEvaluationContext())).isFalse(); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java index 89aab2f844e..6cb5e83bc85 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java @@ -34,7 +34,6 @@ import org.springframework.tests.TestGroup; import org.springframework.util.StopWatch; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Testing variations on map access. @@ -61,7 +60,7 @@ public class MapAccessTests extends AbstractExpressionTests { Expression expr = parser.parseExpression("testMap.monday"); Object value = expr.getValue(ctx, String.class); - assertEquals("montag", value); + assertThat(value).isEqualTo("montag"); } @Test @@ -72,7 +71,7 @@ public class MapAccessTests extends AbstractExpressionTests { Expression expr = parser.parseExpression("testMap[#day]"); Object value = expr.getValue(ctx, String.class); - assertEquals("samstag", value); + assertThat(value).isEqualTo("samstag"); } @Test @@ -86,7 +85,7 @@ public class MapAccessTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("testBean.properties['key2']"); - assertEquals("value2", expr.getValue(bean)); + assertThat(expr.getValue(bean)).isEqualTo("value2"); } @Test @@ -96,7 +95,7 @@ public class MapAccessTests extends AbstractExpressionTests { ExpressionParser spelExpressionParser = new SpelExpressionParser(); Expression expr = spelExpressionParser.parseExpression("#root['key']"); - assertEquals("value", expr.getValue(map)); + assertThat(expr.getValue(map)).isEqualTo("value"); } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java index 5cf3292433a..40270a74372 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java @@ -28,10 +28,8 @@ import org.springframework.expression.spel.ast.InlineMap; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Test usage of inline maps. @@ -125,13 +123,14 @@ public class MapTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expression = (SpelExpression) parser.parseExpression(expressionText); SpelNode node = expression.getAST(); - assertTrue(node instanceof InlineMap); + boolean condition = node instanceof InlineMap; + assertThat(condition).isTrue(); InlineMap inlineMap = (InlineMap) node; if (expectedToBeConstant) { - assertTrue(inlineMap.isConstant()); + assertThat(inlineMap.isConstant()).isTrue(); } else { - assertFalse(inlineMap.isConstant()); + assertThat(inlineMap.isConstant()).isFalse(); } } @@ -154,35 +153,35 @@ public class MapTests extends AbstractExpressionTests { expression = (SpelExpression) parser.parseExpression("foo[T]"); o = expression.getValue(new MapHolder()); - assertEquals("TV", o); + assertThat(o).isEqualTo("TV"); expression = (SpelExpression) parser.parseExpression("foo[t]"); o = expression.getValue(new MapHolder()); - assertEquals("tv", o); + assertThat(o).isEqualTo("tv"); expression = (SpelExpression) parser.parseExpression("foo[NEW]"); o = expression.getValue(new MapHolder()); - assertEquals("VALUE", o); + assertThat(o).isEqualTo("VALUE"); expression = (SpelExpression) parser.parseExpression("foo[new]"); o = expression.getValue(new MapHolder()); - assertEquals("value", o); + assertThat(o).isEqualTo("value"); expression = (SpelExpression) parser.parseExpression("foo['abc.def']"); o = expression.getValue(new MapHolder()); - assertEquals("value", o); + assertThat(o).isEqualTo("value"); expression = (SpelExpression)parser.parseExpression("foo[foo[NEW]]"); o = expression.getValue(new MapHolder()); - assertEquals("37",o); + assertThat(o).isEqualTo("37"); expression = (SpelExpression)parser.parseExpression("foo[foo[new]]"); o = expression.getValue(new MapHolder()); - assertEquals("38",o); + assertThat(o).isEqualTo("38"); expression = (SpelExpression)parser.parseExpression("foo[foo[foo[T]]]"); o = expression.getValue(new MapHolder()); - assertEquals("value",o); + assertThat(o).isEqualTo("value"); } @SuppressWarnings({ "rawtypes", "unchecked" }) diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java index 9c7e25d33ac..69d08965681 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java @@ -41,10 +41,6 @@ import org.springframework.expression.spel.testresources.PlaceOfBirth; import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; /** * Tests invocation of methods. @@ -103,15 +99,15 @@ public class MethodInvocationTests extends AbstractExpressionTests { StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext(); eContext.setVariable("bar", 3); Object o = expr.getValue(eContext); - assertEquals(3, o); - assertEquals(1, parser.parseExpression("counter").getValue(eContext)); + assertThat(o).isEqualTo(3); + assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(1); // Now the expression has cached that throwException(int) is the right thing to call // Let's change 'bar' to be a PlaceOfBirth which indicates the cached reference is // out of date. eContext.setVariable("bar", new PlaceOfBirth("London")); o = expr.getValue(eContext); - assertEquals("London", o); + assertThat(o).isEqualTo("London"); // That confirms the logic to mark the cached reference stale and retry is working // Now let's cause the method to exit via exception and ensure it doesn't cause a retry. @@ -119,8 +115,8 @@ public class MethodInvocationTests extends AbstractExpressionTests { // First, switch back to throwException(int) eContext.setVariable("bar", 3); o = expr.getValue(eContext); - assertEquals(3, o); - assertEquals(2, parser.parseExpression("counter").getValue(eContext)); + assertThat(o).isEqualTo(3); + assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(2); // Now cause it to throw an exception: @@ -130,14 +126,14 @@ public class MethodInvocationTests extends AbstractExpressionTests { .isNotInstanceOf(SpelEvaluationException.class); // If counter is 4 then the method got called twice! - assertEquals(3, parser.parseExpression("counter").getValue(eContext)); + assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(3); eContext.setVariable("bar", 4); assertThatExceptionOfType(ExpressionInvocationTargetException.class).isThrownBy(() -> expr.getValue(eContext)); // If counter is 5 then the method got called twice! - assertEquals(4, parser.parseExpression("counter").getValue(eContext)); + assertThat(parser.parseExpression("counter").getValue(eContext)).isEqualTo(4); } /** @@ -189,24 +185,24 @@ public class MethodInvocationTests extends AbstractExpressionTests { // Filter will be called but not do anything, so first doit() will be invoked SpelExpression expr = (SpelExpression) parser.parseExpression("doit(1)"); String result = expr.getValue(context, String.class); - assertEquals("1", result); - assertTrue(filter.filterCalled); + assertThat(result).isEqualTo("1"); + assertThat(filter.filterCalled).isTrue(); // Filter will now remove non @Anno annotated methods filter.removeIfNotAnnotated = true; filter.filterCalled = false; expr = (SpelExpression) parser.parseExpression("doit(1)"); result = expr.getValue(context, String.class); - assertEquals("double 1.0", result); - assertTrue(filter.filterCalled); + assertThat(result).isEqualTo("double 1.0"); + assertThat(filter.filterCalled).isTrue(); // check not called for other types filter.filterCalled = false; context.setRootObject(new String("abc")); expr = (SpelExpression) parser.parseExpression("charAt(0)"); result = expr.getValue(context, String.class); - assertEquals("a", result); - assertFalse(filter.filterCalled); + assertThat(result).isEqualTo("a"); + assertThat(filter.filterCalled).isFalse(); // check de-registration works filter.filterCalled = false; @@ -214,8 +210,8 @@ public class MethodInvocationTests extends AbstractExpressionTests { context.setRootObject(new TestObject()); expr = (SpelExpression) parser.parseExpression("doit(1)"); result = expr.getValue(context, String.class); - assertEquals("1", result); - assertFalse(filter.filterCalled); + assertThat(result).isEqualTo("1"); + assertThat(filter.filterCalled).isFalse(); } @Test @@ -224,20 +220,20 @@ public class MethodInvocationTests extends AbstractExpressionTests { // reflective method accessor is the only one by default List methodResolvers = ctx.getMethodResolvers(); - assertEquals(1, methodResolvers.size()); + assertThat(methodResolvers.size()).isEqualTo(1); MethodResolver dummy = new DummyMethodResolver(); ctx.addMethodResolver(dummy); - assertEquals(2, ctx.getMethodResolvers().size()); + assertThat(ctx.getMethodResolvers().size()).isEqualTo(2); List copy = new ArrayList<>(); copy.addAll(ctx.getMethodResolvers()); - assertTrue(ctx.removeMethodResolver(dummy)); - assertFalse(ctx.removeMethodResolver(dummy)); - assertEquals(1, ctx.getMethodResolvers().size()); + assertThat(ctx.removeMethodResolver(dummy)).isTrue(); + assertThat(ctx.removeMethodResolver(dummy)).isFalse(); + assertThat(ctx.getMethodResolvers().size()).isEqualTo(1); ctx.setMethodResolvers(copy); - assertEquals(2, ctx.getMethodResolvers().size()); + assertThat(ctx.getMethodResolvers().size()).isEqualTo(2); } @Test @@ -273,7 +269,7 @@ public class MethodInvocationTests extends AbstractExpressionTests { public void testMethodOfClass() throws Exception { Expression expression = parser.parseExpression("getName()"); Object value = expression.getValue(new StandardEvaluationContext(String.class)); - assertEquals("java.lang.String", value); + assertThat(value).isEqualTo("java.lang.String"); } @Test @@ -292,7 +288,7 @@ public class MethodInvocationTests extends AbstractExpressionTests { }); Expression expression = parser.parseExpression("@service.handleBytes(#root)"); byte[] outBytes = expression.getValue(context, byte[].class); - assertSame(bytes, outBytes); + assertThat(outBytes).isSameAs(bytes); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/OperatorOverloaderTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/OperatorOverloaderTests.java index efad67acbef..f6bc255c16f 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/OperatorOverloaderTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/OperatorOverloaderTests.java @@ -24,7 +24,7 @@ import org.springframework.expression.OperatorOverloader; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.support.StandardEvaluationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Test providing operator support @@ -42,13 +42,13 @@ public class OperatorOverloaderTests extends AbstractExpressionTests { eContext.setOperatorOverloader(new StringAndBooleanAddition()); SpelExpression expr = (SpelExpression)parser.parseExpression("'abc'+true"); - assertEquals("abctrue",expr.getValue(eContext)); + assertThat(expr.getValue(eContext)).isEqualTo("abctrue"); expr = (SpelExpression)parser.parseExpression("'abc'-true"); - assertEquals("abc",expr.getValue(eContext)); + assertThat(expr.getValue(eContext)).isEqualTo("abc"); expr = (SpelExpression)parser.parseExpression("'abc'+null"); - assertEquals("abcnull",expr.getValue(eContext)); + assertThat(expr.getValue(eContext)).isEqualTo("abcnull"); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java index 77f4c87ec1a..511e40d9178 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.springframework.expression.spel.ast.Operator; import org.springframework.expression.spel.standard.SpelExpression; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests the evaluation of expressions using relational operators. @@ -401,9 +401,9 @@ public class OperatorTests extends AbstractExpressionTests { // AST: SpelExpression expr = (SpelExpression)parser.parseExpression("+3"); - assertEquals("+3",expr.toStringAST()); + assertThat(expr.toStringAST()).isEqualTo("+3"); expr = (SpelExpression)parser.parseExpression("2+3"); - assertEquals("(2 + 3)",expr.toStringAST()); + assertThat(expr.toStringAST()).isEqualTo("(2 + 3)"); // use as a unary operator evaluate("+5d",5d,Double.class); @@ -425,9 +425,9 @@ public class OperatorTests extends AbstractExpressionTests { evaluateAndCheckError("'ab' - 2", SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES); evaluateAndCheckError("2-'ab'", SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES); SpelExpression expr = (SpelExpression)parser.parseExpression("-3"); - assertEquals("-3", expr.toStringAST()); + assertThat(expr.toStringAST()).isEqualTo("-3"); expr = (SpelExpression)parser.parseExpression("2-3"); - assertEquals("(2 - 3)", expr.toStringAST()); + assertThat(expr.toStringAST()).isEqualTo("(2 - 3)"); evaluate("-5d",-5d,Double.class); evaluate("-5L",-5L,Long.class); @@ -497,40 +497,40 @@ public class OperatorTests extends AbstractExpressionTests { @Test public void testOperatorNames() throws Exception { Operator node = getOperatorNode((SpelExpression)parser.parseExpression("1==3")); - assertEquals("==",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo("=="); node = getOperatorNode((SpelExpression)parser.parseExpression("1!=3")); - assertEquals("!=",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo("!="); node = getOperatorNode((SpelExpression)parser.parseExpression("3/3")); - assertEquals("/",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo("/"); node = getOperatorNode((SpelExpression)parser.parseExpression("3+3")); - assertEquals("+",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo("+"); node = getOperatorNode((SpelExpression)parser.parseExpression("3-3")); - assertEquals("-",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo("-"); node = getOperatorNode((SpelExpression)parser.parseExpression("3<4")); - assertEquals("<",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo("<"); node = getOperatorNode((SpelExpression)parser.parseExpression("3<=4")); - assertEquals("<=",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo("<="); node = getOperatorNode((SpelExpression)parser.parseExpression("3*4")); - assertEquals("*",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo("*"); node = getOperatorNode((SpelExpression)parser.parseExpression("3%4")); - assertEquals("%",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo("%"); node = getOperatorNode((SpelExpression)parser.parseExpression("3>=4")); - assertEquals(">=",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo(">="); node = getOperatorNode((SpelExpression)parser.parseExpression("3 between 4")); - assertEquals("between",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo("between"); node = getOperatorNode((SpelExpression)parser.parseExpression("3 ^ 4")); - assertEquals("^",node.getOperatorName()); + assertThat(node.getOperatorName()).isEqualTo("^"); } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java index 8ab29bfd765..815d8ec18ab 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/PerformanceTests.java @@ -26,7 +26,7 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; ///CLOVER:OFF diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java index 3f1418940c5..6434f280e94 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java @@ -38,11 +38,6 @@ import org.springframework.expression.spel.testresources.Person; import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; /** * Tests accessing of properties. @@ -87,7 +82,7 @@ public class PropertyAccessTests extends AbstractExpressionTests { assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> expr.getValue(context)) .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL)); - assertFalse(expr.isWritable(context)); + assertThat(expr.isWritable(context)).isFalse(); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> expr.setValue(context, "abc")) .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL)); @@ -105,17 +100,17 @@ public class PropertyAccessTests extends AbstractExpressionTests { ctx.addPropertyAccessor(new StringyPropertyAccessor()); Expression expr = parser.parseRaw("new String('hello').flibbles"); Integer i = expr.getValue(ctx, Integer.class); - assertEquals(7, (int) i); + assertThat((int) i).isEqualTo(7); // The reflection one will be used for other properties... expr = parser.parseRaw("new String('hello').CASE_INSENSITIVE_ORDER"); Object o = expr.getValue(ctx); - assertNotNull(o); + assertThat(o).isNotNull(); SpelExpression flibbleexpr = parser.parseRaw("new String('hello').flibbles"); flibbleexpr.setValue(ctx, 99); i = flibbleexpr.getValue(ctx, Integer.class); - assertEquals(99, (int) i); + assertThat((int) i).isEqualTo(99); // Cannot set it to a string value assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> @@ -131,27 +126,27 @@ public class PropertyAccessTests extends AbstractExpressionTests { // reflective property accessor is the only one by default List propertyAccessors = ctx.getPropertyAccessors(); - assertEquals(1,propertyAccessors.size()); + assertThat(propertyAccessors.size()).isEqualTo(1); StringyPropertyAccessor spa = new StringyPropertyAccessor(); ctx.addPropertyAccessor(spa); - assertEquals(2,ctx.getPropertyAccessors().size()); + assertThat(ctx.getPropertyAccessors().size()).isEqualTo(2); List copy = new ArrayList<>(); copy.addAll(ctx.getPropertyAccessors()); - assertTrue(ctx.removePropertyAccessor(spa)); - assertFalse(ctx.removePropertyAccessor(spa)); - assertEquals(1,ctx.getPropertyAccessors().size()); + assertThat(ctx.removePropertyAccessor(spa)).isTrue(); + assertThat(ctx.removePropertyAccessor(spa)).isFalse(); + assertThat(ctx.getPropertyAccessors().size()).isEqualTo(1); ctx.setPropertyAccessors(copy); - assertEquals(2,ctx.getPropertyAccessors().size()); + assertThat(ctx.getPropertyAccessors().size()).isEqualTo(2); } @Test public void testAccessingPropertyOfClass() { Expression expression = parser.parseExpression("name"); Object value = expression.getValue(new StandardEvaluationContext(String.class)); - assertEquals("java.lang.String", value); + assertThat(value).isEqualTo("java.lang.String"); } @Test @@ -161,16 +156,16 @@ public class PropertyAccessTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); context.addPropertyAccessor(new ConfigurablePropertyAccessor(Collections.singletonMap("name", "Ollie"))); - assertEquals("Ollie", expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("Ollie"); context = new StandardEvaluationContext(); context.addPropertyAccessor(new ConfigurablePropertyAccessor(Collections.singletonMap("name", "Jens"))); - assertEquals("Jens", expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("Jens"); } @Test public void standardGetClassAccess() { - assertEquals(String.class.getName(), parser.parseExpression("'a'.class.name").getValue()); + assertThat(parser.parseExpression("'a'.class.name").getValue()).isEqualTo(String.class.getName()); } @Test @@ -186,9 +181,9 @@ public class PropertyAccessTests extends AbstractExpressionTests { Expression expr = parser.parseExpression("name"); Person target = new Person("p1"); - assertEquals("p1", expr.getValue(context, target)); + assertThat(expr.getValue(context, target)).isEqualTo("p1"); target.setName("p2"); - assertEquals("p2", expr.getValue(context, target)); + assertThat(expr.getValue(context, target)).isEqualTo("p2"); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> parser.parseExpression("name='p3'").getValue(context, target)); @@ -200,37 +195,37 @@ public class PropertyAccessTests extends AbstractExpressionTests { Expression expr = parser.parseExpression("name"); Person target = new Person("p1"); - assertEquals("p1", expr.getValue(context, target)); + assertThat(expr.getValue(context, target)).isEqualTo("p1"); target.setName("p2"); - assertEquals("p2", expr.getValue(context, target)); + assertThat(expr.getValue(context, target)).isEqualTo("p2"); parser.parseExpression("name='p3'").getValue(context, target); - assertEquals("p3", target.getName()); - assertEquals("p3", expr.getValue(context, target)); + assertThat(target.getName()).isEqualTo("p3"); + assertThat(expr.getValue(context, target)).isEqualTo("p3"); expr.setValue(context, target, "p4"); - assertEquals("p4", target.getName()); - assertEquals("p4", expr.getValue(context, target)); + assertThat(target.getName()).isEqualTo("p4"); + assertThat(expr.getValue(context, target)).isEqualTo("p4"); } @Test public void propertyReadWriteWithRootObject() { Person target = new Person("p1"); EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().withRootObject(target).build(); - assertSame(target, context.getRootObject().getValue()); + assertThat(context.getRootObject().getValue()).isSameAs(target); Expression expr = parser.parseExpression("name"); - assertEquals("p1", expr.getValue(context, target)); + assertThat(expr.getValue(context, target)).isEqualTo("p1"); target.setName("p2"); - assertEquals("p2", expr.getValue(context, target)); + assertThat(expr.getValue(context, target)).isEqualTo("p2"); parser.parseExpression("name='p3'").getValue(context, target); - assertEquals("p3", target.getName()); - assertEquals("p3", expr.getValue(context, target)); + assertThat(target.getName()).isEqualTo("p3"); + assertThat(expr.getValue(context, target)).isEqualTo("p3"); expr.setValue(context, target, "p4"); - assertEquals("p4", target.getName()); - assertEquals("p4", expr.getValue(context, target)); + assertThat(target.getName()).isEqualTo("p4"); + assertThat(expr.getValue(context, target)).isEqualTo("p4"); } @Test @@ -245,7 +240,7 @@ public class PropertyAccessTests extends AbstractExpressionTests { public void propertyAccessWithInstanceMethodResolver() { EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().withInstanceMethods().build(); Person target = new Person("p1"); - assertEquals("1", parser.parseExpression("name.substring(1)").getValue(context, target)); + assertThat(parser.parseExpression("name.substring(1)").getValue(context, target)).isEqualTo("1"); } @Test @@ -254,9 +249,9 @@ public class PropertyAccessTests extends AbstractExpressionTests { EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding(). withInstanceMethods().withTypedRootObject(target, TypeDescriptor.valueOf(Object.class)).build(); - assertEquals("1", parser.parseExpression("name.substring(1)").getValue(context, target)); - assertSame(target, context.getRootObject().getValue()); - assertSame(Object.class, context.getRootObject().getTypeDescriptor().getType()); + assertThat(parser.parseExpression("name.substring(1)").getValue(context, target)).isEqualTo("1"); + assertThat(context.getRootObject().getValue()).isSameAs(target); + assertThat(context.getRootObject().getTypeDescriptor().getType()).isSameAs(Object.class); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java b/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java index 66adb1fc15f..ce8d90c65d7 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java @@ -35,8 +35,7 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.ReflectionHelper; import org.springframework.expression.spel.support.StandardEvaluationContext; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; ///CLOVER:OFF /** @@ -54,11 +53,11 @@ public class ScenariosForSpringSecurity extends AbstractExpressionTests { ctx.setRootObject(new Person("Ben")); Boolean value = expr.getValue(ctx,Boolean.class); - assertFalse(value); + assertThat((boolean) value).isFalse(); ctx.setRootObject(new Manager("Luke")); value = expr.getValue(ctx,Boolean.class); - assertTrue(value); + assertThat((boolean) value).isTrue(); } @Test @@ -74,11 +73,11 @@ public class ScenariosForSpringSecurity extends AbstractExpressionTests { ctx.setRootObject(new Person("Andy")); Boolean value = expr.getValue(ctx,Boolean.class); - assertTrue(value); + assertThat((boolean) value).isTrue(); ctx.setRootObject(new Person("Christian")); value = expr.getValue(ctx,Boolean.class); - assertFalse(value); + assertThat((boolean) value).isFalse(); // (2) Or register an accessor that can understand 'p' and return the right person expr = parser.parseRaw("p.name == principal.name"); @@ -89,11 +88,11 @@ public class ScenariosForSpringSecurity extends AbstractExpressionTests { pAccessor.setPerson(new Person("Andy")); value = expr.getValue(ctx,Boolean.class); - assertTrue(value); + assertThat((boolean) value).isTrue(); pAccessor.setPerson(new Person("Christian")); value = expr.getValue(ctx,Boolean.class); - assertFalse(value); + assertThat((boolean) value).isFalse(); } @Test @@ -110,12 +109,12 @@ public class ScenariosForSpringSecurity extends AbstractExpressionTests { ctx.setVariable("a",1.0d); // referenced as #a in the expression ctx.setRootObject(new Supervisor("Ben")); // so non-qualified references 'hasRole()' 'hasIpAddress()' are invoked against it value = expr.getValue(ctx,Boolean.class); - assertTrue(value); + assertThat((boolean) value).isTrue(); ctx.setRootObject(new Manager("Luke")); ctx.setVariable("a",1.043d); value = expr.getValue(ctx,Boolean.class); - assertFalse(value); + assertThat((boolean) value).isFalse(); } // Here i'm going to change which hasRole() executes and make it one of my own Java methods @@ -136,7 +135,7 @@ public class ScenariosForSpringSecurity extends AbstractExpressionTests { ctx.setVariable("a",1.0d); // referenced as #a in the expression value = expr.getValue(ctx,Boolean.class); - assertTrue(value); + assertThat((boolean) value).isTrue(); // ctx.setRootObject(new Manager("Luke")); // ctx.setVariable("a",1.043d); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SelectionAndProjectionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SelectionAndProjectionTests.java index 12e373a344f..eac74c4153e 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SelectionAndProjectionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SelectionAndProjectionTests.java @@ -33,8 +33,7 @@ import org.springframework.expression.TypedValue; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -48,14 +47,15 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("integers.?[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new ListTestBean()); Object value = expression.getValue(context); - assertTrue(value instanceof List); + boolean condition = value instanceof List; + assertThat(condition).isTrue(); List list = (List) value; - assertEquals(5, list.size()); - assertEquals(0, list.get(0)); - assertEquals(1, list.get(1)); - assertEquals(2, list.get(2)); - assertEquals(3, list.get(3)); - assertEquals(4, list.get(4)); + assertThat(list.size()).isEqualTo(5); + assertThat(list.get(0)).isEqualTo(0); + assertThat(list.get(1)).isEqualTo(1); + assertThat(list.get(2)).isEqualTo(2); + assertThat(list.get(3)).isEqualTo(3); + assertThat(list.get(4)).isEqualTo(4); } @Test @@ -63,8 +63,9 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("integers.^[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new ListTestBean()); Object value = expression.getValue(context); - assertTrue(value instanceof Integer); - assertEquals(0, value); + boolean condition = value instanceof Integer; + assertThat(condition).isTrue(); + assertThat(value).isEqualTo(0); } @Test @@ -72,8 +73,9 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("integers.$[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new ListTestBean()); Object value = expression.getValue(context); - assertTrue(value instanceof Integer); - assertEquals(4, value); + boolean condition = value instanceof Integer; + assertThat(condition).isTrue(); + assertThat(value).isEqualTo(4); } @Test @@ -81,14 +83,15 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("integers.?[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new SetTestBean()); Object value = expression.getValue(context); - assertTrue(value instanceof List); + boolean condition = value instanceof List; + assertThat(condition).isTrue(); List list = (List) value; - assertEquals(5, list.size()); - assertEquals(0, list.get(0)); - assertEquals(1, list.get(1)); - assertEquals(2, list.get(2)); - assertEquals(3, list.get(3)); - assertEquals(4, list.get(4)); + assertThat(list.size()).isEqualTo(5); + assertThat(list.get(0)).isEqualTo(0); + assertThat(list.get(1)).isEqualTo(1); + assertThat(list.get(2)).isEqualTo(2); + assertThat(list.get(3)).isEqualTo(3); + assertThat(list.get(4)).isEqualTo(4); } @Test @@ -96,8 +99,9 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("integers.^[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new SetTestBean()); Object value = expression.getValue(context); - assertTrue(value instanceof Integer); - assertEquals(0, value); + boolean condition = value instanceof Integer; + assertThat(condition).isTrue(); + assertThat(value).isEqualTo(0); } @Test @@ -105,8 +109,9 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("integers.$[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new SetTestBean()); Object value = expression.getValue(context); - assertTrue(value instanceof Integer); - assertEquals(4, value); + boolean condition = value instanceof Integer; + assertThat(condition).isTrue(); + assertThat(value).isEqualTo(4); } @Test @@ -114,14 +119,15 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("integers.?[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new IterableTestBean()); Object value = expression.getValue(context); - assertTrue(value instanceof List); + boolean condition = value instanceof List; + assertThat(condition).isTrue(); List list = (List) value; - assertEquals(5, list.size()); - assertEquals(0, list.get(0)); - assertEquals(1, list.get(1)); - assertEquals(2, list.get(2)); - assertEquals(3, list.get(3)); - assertEquals(4, list.get(4)); + assertThat(list.size()).isEqualTo(5); + assertThat(list.get(0)).isEqualTo(0); + assertThat(list.get(1)).isEqualTo(1); + assertThat(list.get(2)).isEqualTo(2); + assertThat(list.get(3)).isEqualTo(3); + assertThat(list.get(4)).isEqualTo(4); } @Test @@ -129,16 +135,16 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("integers.?[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new ArrayTestBean()); Object value = expression.getValue(context); - assertTrue(value.getClass().isArray()); + assertThat(value.getClass().isArray()).isTrue(); TypedValue typedValue = new TypedValue(value); - assertEquals(Integer.class, typedValue.getTypeDescriptor().getElementTypeDescriptor().getType()); + assertThat(typedValue.getTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class); Integer[] array = (Integer[]) value; - assertEquals(5, array.length); - assertEquals(new Integer(0), array[0]); - assertEquals(new Integer(1), array[1]); - assertEquals(new Integer(2), array[2]); - assertEquals(new Integer(3), array[3]); - assertEquals(new Integer(4), array[4]); + assertThat(array.length).isEqualTo(5); + assertThat(array[0]).isEqualTo(new Integer(0)); + assertThat(array[1]).isEqualTo(new Integer(1)); + assertThat(array[2]).isEqualTo(new Integer(2)); + assertThat(array[3]).isEqualTo(new Integer(3)); + assertThat(array[4]).isEqualTo(new Integer(4)); } @Test @@ -146,8 +152,9 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("integers.^[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new ArrayTestBean()); Object value = expression.getValue(context); - assertTrue(value instanceof Integer); - assertEquals(0, value); + boolean condition = value instanceof Integer; + assertThat(condition).isTrue(); + assertThat(value).isEqualTo(0); } @Test @@ -155,8 +162,9 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("integers.$[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new ArrayTestBean()); Object value = expression.getValue(context); - assertTrue(value instanceof Integer); - assertEquals(4, value); + boolean condition = value instanceof Integer; + assertThat(condition).isTrue(); + assertThat(value).isEqualTo(4); } @Test @@ -164,16 +172,16 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("ints.?[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new ArrayTestBean()); Object value = expression.getValue(context); - assertTrue(value.getClass().isArray()); + assertThat(value.getClass().isArray()).isTrue(); TypedValue typedValue = new TypedValue(value); - assertEquals(Integer.class, typedValue.getTypeDescriptor().getElementTypeDescriptor().getType()); + assertThat(typedValue.getTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Integer.class); Integer[] array = (Integer[]) value; - assertEquals(5, array.length); - assertEquals(new Integer(0), array[0]); - assertEquals(new Integer(1), array[1]); - assertEquals(new Integer(2), array[2]); - assertEquals(new Integer(3), array[3]); - assertEquals(new Integer(4), array[4]); + assertThat(array.length).isEqualTo(5); + assertThat(array[0]).isEqualTo(new Integer(0)); + assertThat(array[1]).isEqualTo(new Integer(1)); + assertThat(array[2]).isEqualTo(new Integer(2)); + assertThat(array[3]).isEqualTo(new Integer(3)); + assertThat(array[4]).isEqualTo(new Integer(4)); } @Test @@ -181,8 +189,9 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("ints.^[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new ArrayTestBean()); Object value = expression.getValue(context); - assertTrue(value instanceof Integer); - assertEquals(0, value); + boolean condition = value instanceof Integer; + assertThat(condition).isTrue(); + assertThat(value).isEqualTo(0); } @Test @@ -190,8 +199,9 @@ public class SelectionAndProjectionTests { Expression expression = new SpelExpressionParser().parseRaw("ints.$[#this<5]"); EvaluationContext context = new StandardEvaluationContext(new ArrayTestBean()); Object value = expression.getValue(context); - assertTrue(value instanceof Integer); - assertEquals(4, value); + boolean condition = value instanceof Integer; + assertThat(condition).isTrue(); + assertThat(value).isEqualTo(4); } @Test @@ -202,10 +212,10 @@ public class SelectionAndProjectionTests { Expression exp = parser.parseExpression("colors.?[key.startsWith('b')]"); Map colorsMap = (Map) exp.getValue(context); - assertEquals(3, colorsMap.size()); - assertTrue(colorsMap.containsKey("beige")); - assertTrue(colorsMap.containsKey("blue")); - assertTrue(colorsMap.containsKey("brown")); + assertThat(colorsMap.size()).isEqualTo(3); + assertThat(colorsMap.containsKey("beige")).isTrue(); + assertThat(colorsMap.containsKey("blue")).isTrue(); + assertThat(colorsMap.containsKey("brown")).isTrue(); } @Test @@ -216,8 +226,8 @@ public class SelectionAndProjectionTests { Expression exp = parser.parseExpression("colors.^[key.startsWith('b')]"); Map colorsMap = (Map) exp.getValue(context); - assertEquals(1, colorsMap.size()); - assertEquals("beige", colorsMap.keySet().iterator().next()); + assertThat(colorsMap.size()).isEqualTo(1); + assertThat(colorsMap.keySet().iterator().next()).isEqualTo("beige"); } @Test @@ -228,8 +238,8 @@ public class SelectionAndProjectionTests { Expression exp = parser.parseExpression("colors.$[key.startsWith('b')]"); Map colorsMap = (Map) exp.getValue(context); - assertEquals(1, colorsMap.size()); - assertEquals("brown", colorsMap.keySet().iterator().next()); + assertThat(colorsMap.size()).isEqualTo(1); + assertThat(colorsMap.keySet().iterator().next()).isEqualTo("brown"); } @Test @@ -238,12 +248,13 @@ public class SelectionAndProjectionTests { EvaluationContext context = new StandardEvaluationContext(); context.setVariable("testList", IntegerTestBean.createList()); Object value = expression.getValue(context); - assertTrue(value instanceof List); + boolean condition = value instanceof List; + assertThat(condition).isTrue(); List list = (List) value; - assertEquals(3, list.size()); - assertEquals(5, list.get(0)); - assertEquals(6, list.get(1)); - assertEquals(7, list.get(2)); + assertThat(list.size()).isEqualTo(3); + assertThat(list.get(0)).isEqualTo(5); + assertThat(list.get(1)).isEqualTo(6); + assertThat(list.get(2)).isEqualTo(7); } @Test @@ -252,12 +263,13 @@ public class SelectionAndProjectionTests { EvaluationContext context = new StandardEvaluationContext(); context.setVariable("testList", IntegerTestBean.createSet()); Object value = expression.getValue(context); - assertTrue(value instanceof List); + boolean condition = value instanceof List; + assertThat(condition).isTrue(); List list = (List) value; - assertEquals(3, list.size()); - assertEquals(5, list.get(0)); - assertEquals(6, list.get(1)); - assertEquals(7, list.get(2)); + assertThat(list.size()).isEqualTo(3); + assertThat(list.get(0)).isEqualTo(5); + assertThat(list.get(1)).isEqualTo(6); + assertThat(list.get(2)).isEqualTo(7); } @Test @@ -266,12 +278,13 @@ public class SelectionAndProjectionTests { EvaluationContext context = new StandardEvaluationContext(); context.setVariable("testList", IntegerTestBean.createIterable()); Object value = expression.getValue(context); - assertTrue(value instanceof List); + boolean condition = value instanceof List; + assertThat(condition).isTrue(); List list = (List) value; - assertEquals(3, list.size()); - assertEquals(5, list.get(0)); - assertEquals(6, list.get(1)); - assertEquals(7, list.get(2)); + assertThat(list.size()).isEqualTo(3); + assertThat(list.get(0)).isEqualTo(5); + assertThat(list.get(1)).isEqualTo(6); + assertThat(list.get(2)).isEqualTo(7); } @Test @@ -280,14 +293,14 @@ public class SelectionAndProjectionTests { EvaluationContext context = new StandardEvaluationContext(); context.setVariable("testArray", IntegerTestBean.createArray()); Object value = expression.getValue(context); - assertTrue(value.getClass().isArray()); + assertThat(value.getClass().isArray()).isTrue(); TypedValue typedValue = new TypedValue(value); - assertEquals(Number.class, typedValue.getTypeDescriptor().getElementTypeDescriptor().getType()); + assertThat(typedValue.getTypeDescriptor().getElementTypeDescriptor().getType()).isEqualTo(Number.class); Number[] array = (Number[]) value; - assertEquals(3, array.length); - assertEquals(new Integer(5), array[0]); - assertEquals(5.9f, array[1]); - assertEquals(new Integer(7), array[2]); + assertThat(array.length).isEqualTo(3); + assertThat(array[0]).isEqualTo(new Integer(5)); + assertThat(array[1]).isEqualTo(5.9f); + assertThat(array[2]).isEqualTo(new Integer(7)); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java index 9778ff4c811..ffcce6b8bed 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java @@ -29,10 +29,6 @@ import org.springframework.expression.spel.testresources.PlaceOfBirth; import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * Tests set value expressions. @@ -90,7 +86,7 @@ public class SetValueTests extends AbstractExpressionTests { // PROPERTYORFIELDREFERENCE // Non existent field (or property): Expression e1 = parser.parseExpression("arrayContainer.wibble"); - assertFalse("Should not be writable!", e1.isWritable(lContext)); + assertThat(e1.isWritable(lContext)).as("Should not be writable!").isFalse(); Expression e2 = parser.parseExpression("arrayContainer.wibble.foo"); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> @@ -101,10 +97,10 @@ public class SetValueTests extends AbstractExpressionTests { // VARIABLE // the variable does not exist (but that is OK, we should be writable) Expression e3 = parser.parseExpression("#madeup1"); - assertTrue("Should be writable!",e3.isWritable(lContext)); + assertThat(e3.isWritable(lContext)).as("Should be writable!").isTrue(); Expression e4 = parser.parseExpression("#madeup2.bar"); // compound expression - assertFalse("Should not be writable!",e4.isWritable(lContext)); + assertThat(e4.isWritable(lContext)).as("Should not be writable!").isFalse(); // INDEXER // non existent indexer (wibble made up) @@ -188,8 +184,8 @@ public class SetValueTests extends AbstractExpressionTests { public void testAssign() throws Exception { StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext(); Expression e = parse("publicName='Andy'"); - assertFalse(e.isWritable(eContext)); - assertEquals("Andy",e.getValue(eContext)); + assertThat(e.isWritable(eContext)).isFalse(); + assertThat(e.getValue(eContext)).isEqualTo("Andy"); } /* @@ -199,7 +195,7 @@ public class SetValueTests extends AbstractExpressionTests { public void testSetGenericMapElementRequiresCoercion() throws Exception { StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext(); Expression e = parse("mapOfStringToBoolean[42]"); - assertNull(e.getValue(eContext)); + assertThat(e.getValue(eContext)).isNull(); // Key should be coerced to string representation of 42 e.setValue(eContext, "true"); @@ -207,18 +203,18 @@ public class SetValueTests extends AbstractExpressionTests { // All keys should be strings Set ks = parse("mapOfStringToBoolean.keySet()").getValue(eContext, Set.class); for (Object o: ks) { - assertEquals(String.class,o.getClass()); + assertThat(o.getClass()).isEqualTo(String.class); } // All values should be booleans Collection vs = parse("mapOfStringToBoolean.values()").getValue(eContext, Collection.class); for (Object o: vs) { - assertEquals(Boolean.class, o.getClass()); + assertThat(o.getClass()).isEqualTo(Boolean.class); } // One final test check coercion on the key for a map lookup Object o = e.getValue(eContext); - assertEquals(Boolean.TRUE,o); + assertThat(o).isEqualTo(Boolean.TRUE); } @@ -248,9 +244,9 @@ public class SetValueTests extends AbstractExpressionTests { SpelUtilities.printAbstractSyntaxTree(System.out, e); } StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext(); - assertTrue("Expression is not writeable but should be", e.isWritable(lContext)); + assertThat(e.isWritable(lContext)).as("Expression is not writeable but should be").isTrue(); e.setValue(lContext, value); - assertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext,value.getClass())); + assertThat(e.getValue(lContext,value.getClass())).as("Retrieved value was not equal to set value").isEqualTo(value); } catch (EvaluationException | ParseException ex) { throw new AssertionError("Unexpected Exception: " + ex.getMessage(), ex); @@ -269,7 +265,7 @@ public class SetValueTests extends AbstractExpressionTests { SpelUtilities.printAbstractSyntaxTree(System.out, e); } StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext(); - assertTrue("Expression is not writeable but should be", e.isWritable(lContext)); + assertThat(e.isWritable(lContext)).as("Expression is not writeable but should be").isTrue(); e.setValue(lContext, value); Object a = expectedValue; Object b = e.getValue(lContext); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java index bc01e6ee37f..6ccc9dd0459 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java @@ -45,12 +45,9 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.testdata.PersonInOtherPackage; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.within; /** * Checks SpelCompiler behavior. This should cover compilation all compiled node types. @@ -133,64 +130,64 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { @Test public void typeReference() throws Exception { expression = parse("T(String)"); - assertEquals(String.class, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(String.class); assertCanCompile(expression); - assertEquals(String.class, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(String.class); expression = parse("T(java.io.IOException)"); - assertEquals(IOException.class, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(IOException.class); assertCanCompile(expression); - assertEquals(IOException.class, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(IOException.class); expression = parse("T(java.io.IOException[])"); - assertEquals(IOException[].class, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(IOException[].class); assertCanCompile(expression); - assertEquals(IOException[].class, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(IOException[].class); expression = parse("T(int[][])"); - assertEquals(int[][].class, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(int[][].class); assertCanCompile(expression); - assertEquals(int[][].class, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(int[][].class); expression = parse("T(int)"); - assertEquals(Integer.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Integer.TYPE); assertCanCompile(expression); - assertEquals(Integer.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Integer.TYPE); expression = parse("T(byte)"); - assertEquals(Byte.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Byte.TYPE); assertCanCompile(expression); - assertEquals(Byte.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Byte.TYPE); expression = parse("T(char)"); - assertEquals(Character.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Character.TYPE); assertCanCompile(expression); - assertEquals(Character.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Character.TYPE); expression = parse("T(short)"); - assertEquals(Short.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Short.TYPE); assertCanCompile(expression); - assertEquals(Short.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Short.TYPE); expression = parse("T(long)"); - assertEquals(Long.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Long.TYPE); assertCanCompile(expression); - assertEquals(Long.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Long.TYPE); expression = parse("T(float)"); - assertEquals(Float.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Float.TYPE); assertCanCompile(expression); - assertEquals(Float.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Float.TYPE); expression = parse("T(double)"); - assertEquals(Double.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Double.TYPE); assertCanCompile(expression); - assertEquals(Double.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Double.TYPE); expression = parse("T(boolean)"); - assertEquals(Boolean.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Boolean.TYPE); assertCanCompile(expression); - assertEquals(Boolean.TYPE, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(Boolean.TYPE); expression = parse("T(Missing)"); assertGetValueFail(expression); @@ -201,112 +198,112 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { @Test public void operatorInstanceOf() throws Exception { expression = parse("'xyz' instanceof T(String)"); - assertEquals(true, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(true); assertCanCompile(expression); - assertEquals(true, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(true); expression = parse("'xyz' instanceof T(Integer)"); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); assertCanCompile(expression); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); List list = new ArrayList<>(); expression = parse("#root instanceof T(java.util.List)"); - assertEquals(true, expression.getValue(list)); + assertThat(expression.getValue(list)).isEqualTo(true); assertCanCompile(expression); - assertEquals(true, expression.getValue(list)); + assertThat(expression.getValue(list)).isEqualTo(true); List[] arrayOfLists = new List[] {new ArrayList()}; expression = parse("#root instanceof T(java.util.List[])"); - assertEquals(true, expression.getValue(arrayOfLists)); + assertThat(expression.getValue(arrayOfLists)).isEqualTo(true); assertCanCompile(expression); - assertEquals(true, expression.getValue(arrayOfLists)); + assertThat(expression.getValue(arrayOfLists)).isEqualTo(true); int[] intArray = new int[] {1,2,3}; expression = parse("#root instanceof T(int[])"); - assertEquals(true, expression.getValue(intArray)); + assertThat(expression.getValue(intArray)).isEqualTo(true); assertCanCompile(expression); - assertEquals(true, expression.getValue(intArray)); + assertThat(expression.getValue(intArray)).isEqualTo(true); String root = null; expression = parse("#root instanceof T(Integer)"); - assertEquals(false, expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo(false); assertCanCompile(expression); - assertEquals(false, expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo(false); // root still null expression = parse("#root instanceof T(java.lang.Object)"); - assertEquals(false, expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo(false); assertCanCompile(expression); - assertEquals(false, expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo(false); root = "howdy!"; expression = parse("#root instanceof T(java.lang.Object)"); - assertEquals(true, expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo(true); assertCanCompile(expression); - assertEquals(true, expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo(true); } @Test public void operatorInstanceOf_SPR14250() throws Exception { // primitive left operand - should get boxed, return true expression = parse("3 instanceof T(Integer)"); - assertEquals(true, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(true); assertCanCompile(expression); - assertEquals(true, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(true); // primitive left operand - should get boxed, return false expression = parse("3 instanceof T(String)"); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); assertCanCompile(expression); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); // double slot left operand - should get boxed, return false expression = parse("3.0d instanceof T(Integer)"); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); assertCanCompile(expression); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); // double slot left operand - should get boxed, return true expression = parse("3.0d instanceof T(Double)"); - assertEquals(true, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(true); assertCanCompile(expression); - assertEquals(true, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(true); // Only when the right hand operand is a direct type reference // will it be compilable. StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariable("foo", String.class); expression = parse("3 instanceof #foo"); - assertEquals(false, expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo(false); assertCantCompile(expression); // use of primitive as type for instanceof check - compilable // but always false expression = parse("3 instanceof T(int)"); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); assertCanCompile(expression); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); expression = parse("3 instanceof T(long)"); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); assertCanCompile(expression); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); } @Test public void stringLiteral() throws Exception { expression = parser.parseExpression("'abcde'"); - assertEquals("abcde", expression.getValue(new TestClass1(), String.class)); + assertThat(expression.getValue(new TestClass1(), String.class)).isEqualTo("abcde"); assertCanCompile(expression); String resultC = expression.getValue(new TestClass1(), String.class); - assertEquals("abcde", resultC); - assertEquals("abcde", expression.getValue(String.class)); - assertEquals("abcde", expression.getValue()); - assertEquals("abcde", expression.getValue(new StandardEvaluationContext())); + assertThat(resultC).isEqualTo("abcde"); + assertThat(expression.getValue(String.class)).isEqualTo("abcde"); + assertThat(expression.getValue()).isEqualTo("abcde"); + assertThat(expression.getValue(new StandardEvaluationContext())).isEqualTo("abcde"); expression = parser.parseExpression("\"abcde\""); assertCanCompile(expression); - assertEquals("abcde", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("abcde"); } @Test @@ -315,9 +312,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { Object resultI = expression.getValue(new TestClass1(), Object.class); assertCanCompile(expression); Object resultC = expression.getValue(new TestClass1(), Object.class); - assertEquals(null, resultI); - assertEquals(null, resultC); - assertEquals(null, resultC); + assertThat(resultI).isEqualTo(null); + assertThat(resultC).isEqualTo(null); + assertThat(resultC).isEqualTo(null); } @Test @@ -326,9 +323,11 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { double resultI = expression.getValue(new TestClass1(), Double.TYPE); assertCanCompile(expression); double resultC = expression.getValue(new TestClass1(), Double.TYPE); - assertEquals(3.4d, resultI, 0.1d); - assertEquals(3.4d, resultC, 0.1d); - assertEquals(3.4d, expression.getValue()); + assertThat(resultI).isCloseTo(3.4d, within(0.1d)); + + assertThat(resultC).isCloseTo(3.4d, within(0.1d)); + + assertThat(expression.getValue()).isEqualTo(3.4d); } @SuppressWarnings("rawtypes") @@ -336,38 +335,38 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { public void inlineList() throws Exception { expression = parser.parseExpression("'abcde'.substring({1,3,4}[0])"); Object o = expression.getValue(); - assertEquals("bcde",o); + assertThat(o).isEqualTo("bcde"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("bcde", o); + assertThat(o).isEqualTo("bcde"); expression = parser.parseExpression("{'abc','def'}"); List l = (List) expression.getValue(); - assertEquals("[abc, def]", l.toString()); + assertThat(l.toString()).isEqualTo("[abc, def]"); assertCanCompile(expression); l = (List) expression.getValue(); - assertEquals("[abc, def]", l.toString()); + assertThat(l.toString()).isEqualTo("[abc, def]"); expression = parser.parseExpression("{'abc','def'}[0]"); o = expression.getValue(); - assertEquals("abc",o); + assertThat(o).isEqualTo("abc"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("abc", o); + assertThat(o).isEqualTo("abc"); expression = parser.parseExpression("{'abcde','ijklm'}[0].substring({1,3,4}[0])"); o = expression.getValue(); - assertEquals("bcde",o); + assertThat(o).isEqualTo("bcde"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("bcde", o); + assertThat(o).isEqualTo("bcde"); expression = parser.parseExpression("{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])"); o = expression.getValue(); - assertEquals("bc",o); + assertThat(o).isEqualTo("bc"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("bc", o); + assertThat(o).isEqualTo("bc"); } @SuppressWarnings("rawtypes") @@ -377,73 +376,73 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parser.parseExpression("{{1,2,3},{4,5,6},{7,8,9}}"); o = expression.getValue(); - assertEquals("[[1, 2, 3], [4, 5, 6], [7, 8, 9]]",o.toString()); + assertThat(o.toString()).isEqualTo("[[1, 2, 3], [4, 5, 6], [7, 8, 9]]"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("[[1, 2, 3], [4, 5, 6], [7, 8, 9]]",o.toString()); + assertThat(o.toString()).isEqualTo("[[1, 2, 3], [4, 5, 6], [7, 8, 9]]"); expression = parser.parseExpression("{{1,2,3},{4,5,6},{7,8,9}}.toString()"); o = expression.getValue(); - assertEquals("[[1, 2, 3], [4, 5, 6], [7, 8, 9]]",o); + assertThat(o).isEqualTo("[[1, 2, 3], [4, 5, 6], [7, 8, 9]]"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("[[1, 2, 3], [4, 5, 6], [7, 8, 9]]",o); + assertThat(o).isEqualTo("[[1, 2, 3], [4, 5, 6], [7, 8, 9]]"); expression = parser.parseExpression("{{1,2,3},{4,5,6},{7,8,9}}[1][0]"); o = expression.getValue(); - assertEquals(4,o); + assertThat(o).isEqualTo(4); assertCanCompile(expression); o = expression.getValue(); - assertEquals(4,o); + assertThat(o).isEqualTo(4); expression = parser.parseExpression("{{1,2,3},'abc',{7,8,9}}[1]"); o = expression.getValue(); - assertEquals("abc",o); + assertThat(o).isEqualTo("abc"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("abc",o); + assertThat(o).isEqualTo("abc"); expression = parser.parseExpression("'abcde'.substring({{1,3},1,3,4}[0][1])"); o = expression.getValue(); - assertEquals("de",o); + assertThat(o).isEqualTo("de"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("de", o); + assertThat(o).isEqualTo("de"); expression = parser.parseExpression("'abcde'.substring({{1,3},1,3,4}[1])"); o = expression.getValue(); - assertEquals("bcde",o); + assertThat(o).isEqualTo("bcde"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("bcde", o); + assertThat(o).isEqualTo("bcde"); expression = parser.parseExpression("{'abc',{'def','ghi'}}"); List l = (List) expression.getValue(); - assertEquals("[abc, [def, ghi]]", l.toString()); + assertThat(l.toString()).isEqualTo("[abc, [def, ghi]]"); assertCanCompile(expression); l = (List) expression.getValue(); - assertEquals("[abc, [def, ghi]]", l.toString()); + assertThat(l.toString()).isEqualTo("[abc, [def, ghi]]"); expression = parser.parseExpression("{'abcde',{'ijklm','nopqr'}}[0].substring({1,3,4}[0])"); o = expression.getValue(); - assertEquals("bcde",o); + assertThat(o).isEqualTo("bcde"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("bcde", o); + assertThat(o).isEqualTo("bcde"); expression = parser.parseExpression("{'abcde',{'ijklm','nopqr'}}[1][0].substring({1,3,4}[0])"); o = expression.getValue(); - assertEquals("jklm",o); + assertThat(o).isEqualTo("jklm"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("jklm", o); + assertThat(o).isEqualTo("jklm"); expression = parser.parseExpression("{'abcde',{'ijklm','nopqr'}}[1][1].substring({1,3,4}[0],{1,3,4}[1])"); o = expression.getValue(); - assertEquals("op",o); + assertThat(o).isEqualTo("op"); assertCanCompile(expression); o = expression.getValue(); - assertEquals("op", o); + assertThat(o).isEqualTo("op"); } @Test @@ -452,13 +451,13 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { int resultI = expression.getValue(new TestClass1(), Integer.TYPE); assertCanCompile(expression); int resultC = expression.getValue(new TestClass1(), Integer.TYPE); - assertEquals(42, resultI); - assertEquals(42, resultC); + assertThat(resultI).isEqualTo(42); + assertThat(resultC).isEqualTo(42); expression = parser.parseExpression("T(Integer).valueOf(42)"); expression.getValue(Integer.class); assertCanCompile(expression); - assertEquals(new Integer(42), expression.getValue(Integer.class)); + assertThat(expression.getValue(Integer.class)).isEqualTo(new Integer(42)); // Code gen is different for -1 .. 6 because there are bytecode instructions specifically for those values @@ -468,13 +467,13 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { // assertEquals(-1, expression.getValue()); expression = parser.parseExpression("0"); assertCanCompile(expression); - assertEquals(0, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(0); expression = parser.parseExpression("2"); assertCanCompile(expression); - assertEquals(2, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2); expression = parser.parseExpression("7"); assertCanCompile(expression); - assertEquals(7, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(7); } @Test @@ -483,25 +482,25 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { long resultI = expression.getValue(new TestClass1(), Long.TYPE); assertCanCompile(expression); long resultC = expression.getValue(new TestClass1(), Long.TYPE); - assertEquals(99L, resultI); - assertEquals(99L, resultC); + assertThat(resultI).isEqualTo(99L); + assertThat(resultC).isEqualTo(99L); } @Test public void booleanLiteral() throws Exception { expression = parser.parseExpression("true"); boolean resultI = expression.getValue(1, Boolean.TYPE); - assertEquals(true, resultI); - assertTrue(SpelCompiler.compile(expression)); + assertThat(resultI).isEqualTo(true); + assertThat(SpelCompiler.compile(expression)).isTrue(); boolean resultC = expression.getValue(1, Boolean.TYPE); - assertEquals(true, resultC); + assertThat(resultC).isEqualTo(true); expression = parser.parseExpression("false"); resultI = expression.getValue(1, Boolean.TYPE); - assertEquals(false, resultI); - assertTrue(SpelCompiler.compile(expression)); + assertThat(resultI).isEqualTo(false); + assertThat(SpelCompiler.compile(expression)).isTrue(); resultC = expression.getValue(1, Boolean.TYPE); - assertEquals(false, resultC); + assertThat(resultC).isEqualTo(false); } @Test @@ -510,10 +509,11 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { float resultI = expression.getValue(new TestClass1(), Float.TYPE); assertCanCompile(expression); float resultC = expression.getValue(new TestClass1(), Float.TYPE); - assertEquals(3.4f, resultI, 0.1f); - assertEquals(3.4f, resultC, 0.1f); + assertThat(resultI).isCloseTo(3.4f, within(0.1f)); - assertEquals(3.4f, expression.getValue()); + assertThat(resultC).isCloseTo(3.4f, within(0.1f)); + + assertThat(expression.getValue()).isEqualTo(3.4f); } @Test @@ -522,37 +522,37 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { boolean resultI = expression.getValue(1, Boolean.TYPE); SpelCompiler.compile(expression); boolean resultC = expression.getValue(1, Boolean.TYPE); - assertEquals(false, resultI); - assertEquals(false, resultC); + assertThat(resultI).isEqualTo(false); + assertThat(resultC).isEqualTo(false); expression = parser.parseExpression("false or true"); resultI = expression.getValue(1, Boolean.TYPE); assertCanCompile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertEquals(true, resultI); - assertEquals(true, resultC); + assertThat(resultI).isEqualTo(true); + assertThat(resultC).isEqualTo(true); expression = parser.parseExpression("true or false"); resultI = expression.getValue(1, Boolean.TYPE); assertCanCompile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertEquals(true, resultI); - assertEquals(true, resultC); + assertThat(resultI).isEqualTo(true); + assertThat(resultC).isEqualTo(true); expression = parser.parseExpression("true or true"); resultI = expression.getValue(1, Boolean.TYPE); assertCanCompile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertEquals(true, resultI); - assertEquals(true, resultC); + assertThat(resultI).isEqualTo(true); + assertThat(resultC).isEqualTo(true); TestClass4 tc = new TestClass4(); expression = parser.parseExpression("getfalse() or gettrue()"); resultI = expression.getValue(tc, Boolean.TYPE); assertCanCompile(expression); resultC = expression.getValue(tc, Boolean.TYPE); - assertEquals(true, resultI); - assertEquals(true, resultC); + assertThat(resultI).isEqualTo(true); + assertThat(resultC).isEqualTo(true); // Can't compile this as we aren't going down the getfalse() branch in our evaluation expression = parser.parseExpression("gettrue() or getfalse()"); @@ -568,14 +568,14 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { tc.b = true; resultI = expression.getValue(tc, Boolean.TYPE); assertCanCompile(expression); // Now been down both - assertTrue(resultI); + assertThat(resultI).isTrue(); boolean b = false; expression = parse("#root or #root"); Object resultI2 = expression.getValue(b); assertCanCompile(expression); - assertFalse((Boolean) resultI2); - assertFalse((Boolean) expression.getValue(b)); + assertThat((boolean) (Boolean) resultI2).isFalse(); + assertThat((boolean) (Boolean) expression.getValue(b)).isFalse(); } @Test @@ -584,29 +584,29 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { boolean resultI = expression.getValue(1, Boolean.TYPE); SpelCompiler.compile(expression); boolean resultC = expression.getValue(1, Boolean.TYPE); - assertEquals(false, resultI); - assertEquals(false, resultC); + assertThat(resultI).isEqualTo(false); + assertThat(resultC).isEqualTo(false); expression = parser.parseExpression("false and true"); resultI = expression.getValue(1, Boolean.TYPE); SpelCompiler.compile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertEquals(false, resultI); - assertEquals(false, resultC); + assertThat(resultI).isEqualTo(false); + assertThat(resultC).isEqualTo(false); expression = parser.parseExpression("true and false"); resultI = expression.getValue(1, Boolean.TYPE); SpelCompiler.compile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertEquals(false, resultI); - assertEquals(false, resultC); + assertThat(resultI).isEqualTo(false); + assertThat(resultC).isEqualTo(false); expression = parser.parseExpression("true and true"); resultI = expression.getValue(1, Boolean.TYPE); SpelCompiler.compile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertEquals(true, resultI); - assertEquals(true, resultC); + assertThat(resultI).isEqualTo(true); + assertThat(resultC).isEqualTo(true); TestClass4 tc = new TestClass4(); @@ -624,43 +624,43 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { tc.b = false; resultI = expression.getValue(tc, Boolean.TYPE); assertCanCompile(expression); // Now been down both - assertFalse(resultI); + assertThat(resultI).isFalse(); tc.a = true; tc.b = true; resultI = expression.getValue(tc, Boolean.TYPE); - assertTrue(resultI); + assertThat(resultI).isTrue(); boolean b = true; expression = parse("#root and #root"); Object resultI2 = expression.getValue(b); assertCanCompile(expression); - assertTrue((Boolean) resultI2); - assertTrue((Boolean) expression.getValue(b)); + assertThat((boolean) (Boolean) resultI2).isTrue(); + assertThat((boolean) (Boolean) expression.getValue(b)).isTrue(); } @Test public void operatorNot() throws Exception { expression = parse("!true"); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); assertCanCompile(expression); - assertEquals(false, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(false); expression = parse("!false"); - assertEquals(true, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(true); assertCanCompile(expression); - assertEquals(true, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(true); boolean b = true; expression = parse("!#root"); - assertEquals(false, expression.getValue(b)); + assertThat(expression.getValue(b)).isEqualTo(false); assertCanCompile(expression); - assertEquals(false, expression.getValue(b)); + assertThat(expression.getValue(b)).isEqualTo(false); b = false; expression = parse("!#root"); - assertEquals(true, expression.getValue(b)); + assertThat(expression.getValue(b)).isEqualTo(true); assertCanCompile(expression); - assertEquals(true, expression.getValue(b)); + assertThat(expression.getValue(b)).isEqualTo(true); } @Test @@ -669,44 +669,44 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { String resultI = expression.getValue(String.class); assertCanCompile(expression); String resultC = expression.getValue(String.class); - assertEquals("a", resultI); - assertEquals("a", resultC); + assertThat(resultI).isEqualTo("a"); + assertThat(resultC).isEqualTo("a"); expression = parser.parseExpression("false?'a':'b'"); resultI = expression.getValue(String.class); assertCanCompile(expression); resultC = expression.getValue(String.class); - assertEquals("b", resultI); - assertEquals("b", resultC); + assertThat(resultI).isEqualTo("b"); + assertThat(resultC).isEqualTo("b"); expression = parser.parseExpression("false?1:'b'"); // All literals so we can do this straight away assertCanCompile(expression); - assertEquals("b", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("b"); boolean root = true; expression = parser.parseExpression("(#root and true)?T(Integer).valueOf(1):T(Long).valueOf(3L)"); - assertEquals(1, expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo(1); assertCantCompile(expression); // Have not gone down false branch root = false; - assertEquals(3L, expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo(3L); assertCanCompile(expression); - assertEquals(3L, expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo(3L); root = true; - assertEquals(1, expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo(1); } @Test public void ternaryWithBooleanReturn_SPR12271() { expression = parser.parseExpression("T(Boolean).TRUE?'abc':'def'"); - assertEquals("abc", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("abc"); assertCanCompile(expression); - assertEquals("abc", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("abc"); expression = parser.parseExpression("T(Boolean).FALSE?'abc':'def'"); - assertEquals("def", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("def"); assertCanCompile(expression); - assertEquals("def", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("def"); } @Test @@ -717,53 +717,53 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { // First non compiled: SpelExpression expression = (SpelExpression) parser.parseExpression("foo?.object"); - assertEquals("hello",expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("hello"); foh.foo = null; - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); // Now revert state of foh and try compiling it: foh.foo = new FooObject(); - assertEquals("hello",expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("hello"); assertCanCompile(expression); - assertEquals("hello",expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("hello"); foh.foo = null; - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); // Static references expression = (SpelExpression) parser.parseExpression("#var?.propertya"); context.setVariable("var", StaticsHelper.class); - assertEquals("sh",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("sh"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); assertCanCompile(expression); context.setVariable("var", StaticsHelper.class); - assertEquals("sh",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("sh"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); // Single size primitive (boolean) expression = (SpelExpression) parser.parseExpression("#var?.a"); context.setVariable("var", new TestClass4()); - assertFalse((Boolean)expression.getValue(context)); + assertThat((boolean) (Boolean) expression.getValue(context)).isFalse(); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); assertCanCompile(expression); context.setVariable("var", new TestClass4()); - assertFalse((Boolean)expression.getValue(context)); + assertThat((boolean) (Boolean) expression.getValue(context)).isFalse(); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); // Double slot primitives expression = (SpelExpression) parser.parseExpression("#var?.four"); context.setVariable("var", new Three()); - assertEquals("0.04",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("0.04"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); assertCanCompile(expression); context.setVariable("var", new Three()); - assertEquals("0.04",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("0.04"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); } @Test @@ -774,98 +774,98 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { // First non compiled: SpelExpression expression = (SpelExpression) parser.parseExpression("getFoo()?.getObject()"); - assertEquals("hello",expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("hello"); foh.foo = null; - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); assertCanCompile(expression); foh.foo = new FooObject(); - assertEquals("hello",expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("hello"); foh.foo = null; - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); // Static method references expression = (SpelExpression) parser.parseExpression("#var?.methoda()"); context.setVariable("var", StaticsHelper.class); - assertEquals("sh",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("sh"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); assertCanCompile(expression); context.setVariable("var", StaticsHelper.class); - assertEquals("sh",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("sh"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); // Nullsafe guard on expression element evaluating to primitive/null expression = (SpelExpression) parser.parseExpression("#var?.intValue()"); context.setVariable("var", 4); - assertEquals("4",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("4"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); assertCanCompile(expression); context.setVariable("var", 4); - assertEquals("4",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("4"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); // Nullsafe guard on expression element evaluating to primitive/null expression = (SpelExpression) parser.parseExpression("#var?.booleanValue()"); context.setVariable("var", false); - assertEquals("false",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("false"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); assertCanCompile(expression); context.setVariable("var", false); - assertEquals("false",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("false"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); // Nullsafe guard on expression element evaluating to primitive/null expression = (SpelExpression) parser.parseExpression("#var?.booleanValue()"); context.setVariable("var", true); - assertEquals("true",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("true"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); assertCanCompile(expression); context.setVariable("var", true); - assertEquals("true",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("true"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); // Nullsafe guard on expression element evaluating to primitive/null expression = (SpelExpression) parser.parseExpression("#var?.longValue()"); context.setVariable("var", 5L); - assertEquals("5",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("5"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); assertCanCompile(expression); context.setVariable("var", 5L); - assertEquals("5",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("5"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); // Nullsafe guard on expression element evaluating to primitive/null expression = (SpelExpression) parser.parseExpression("#var?.floatValue()"); context.setVariable("var", 3f); - assertEquals("3.0",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("3.0"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); assertCanCompile(expression); context.setVariable("var", 3f); - assertEquals("3.0",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("3.0"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); // Nullsafe guard on expression element evaluating to primitive/null expression = (SpelExpression) parser.parseExpression("#var?.shortValue()"); context.setVariable("var", (short)8); - assertEquals("8",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("8"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); assertCanCompile(expression); context.setVariable("var", (short)8); - assertEquals("8",expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("8"); context.setVariable("var", null); - assertNull(expression.getValue(context)); + assertThat(expression.getValue(context)).isNull(); } @Test @@ -874,21 +874,21 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { String resultI = expression.getValue(String.class); assertCanCompile(expression); String resultC = expression.getValue(String.class); - assertEquals("a", resultI); - assertEquals("a", resultC); + assertThat(resultI).isEqualTo("a"); + assertThat(resultC).isEqualTo("a"); expression = parser.parseExpression("null?:'a'"); resultI = expression.getValue(String.class); assertCanCompile(expression); resultC = expression.getValue(String.class); - assertEquals("a", resultI); - assertEquals("a", resultC); + assertThat(resultI).isEqualTo("a"); + assertThat(resultC).isEqualTo("a"); String s = "abc"; expression = parser.parseExpression("#root?:'b'"); assertCantCompile(expression); resultI = expression.getValue(s, String.class); - assertEquals("abc", resultI); + assertThat(resultI).isEqualTo("abc"); assertCanCompile(expression); } @@ -899,15 +899,15 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { String resultI = expression.getValue(s, String.class); assertCanCompile(expression); String resultC = expression.getValue(s, String.class); - assertEquals(s, resultI); - assertEquals(s, resultC); + assertThat(resultI).isEqualTo(s); + assertThat(resultC).isEqualTo(s); expression = parser.parseExpression("#root"); int i = (Integer) expression.getValue(42); - assertEquals(42,i); + assertThat(i).isEqualTo(42); assertCanCompile(expression); i = (Integer) expression.getValue(42); - assertEquals(42,i); + assertThat(i).isEqualTo(42); } public static String concat(String a, String b) { @@ -933,10 +933,10 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { DelegatingStringFormat.class.getDeclaredMethod("format", String.class, Object[].class)); ((SpelExpression) expression).setEvaluationContext(context); - assertEquals("hey there", expression.getValue(String.class)); - assertTrue(((SpelNodeImpl) ((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(String.class)).isEqualTo("hey there"); + assertThat(((SpelNodeImpl) ((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("hey there", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("hey there"); expression = parser.parseExpression("#doFormat([0], 'there')"); context = new StandardEvaluationContext(new Object[] {"hey %s"}); @@ -944,10 +944,10 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { DelegatingStringFormat.class.getDeclaredMethod("format", String.class, Object[].class)); ((SpelExpression) expression).setEvaluationContext(context); - assertEquals("hey there", expression.getValue(String.class)); - assertTrue(((SpelNodeImpl) ((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(String.class)).isEqualTo("hey there"); + assertThat(((SpelNodeImpl) ((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("hey there", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("hey there"); expression = parser.parseExpression("#doFormat([0], #arg)"); context = new StandardEvaluationContext(new Object[] {"hey %s"}); @@ -956,10 +956,10 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { context.setVariable("arg", "there"); ((SpelExpression) expression).setEvaluationContext(context); - assertEquals("hey there", expression.getValue(String.class)); - assertTrue(((SpelNodeImpl) ((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(String.class)).isEqualTo("hey there"); + assertThat(((SpelNodeImpl) ((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("hey there", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("hey there"); } @Test @@ -969,30 +969,30 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { ctx.setVariable("concat",m); expression = parser.parseExpression("#concat('a','b')"); - assertEquals("ab", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("ab"); assertCanCompile(expression); - assertEquals("ab", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("ab"); expression = parser.parseExpression("#concat(#concat('a','b'),'c').charAt(1)"); - assertEquals('b', expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo('b'); assertCanCompile(expression); - assertEquals('b', expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo('b'); expression = parser.parseExpression("#concat(#a,#b)"); ctx.setVariable("a", "foo"); ctx.setVariable("b", "bar"); - assertEquals("foobar", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("foobar"); assertCanCompile(expression); - assertEquals("foobar", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("foobar"); ctx.setVariable("b", "boo"); - assertEquals("fooboo", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("fooboo"); m = Math.class.getDeclaredMethod("pow", Double.TYPE, Double.TYPE); ctx.setVariable("kapow",m); expression = parser.parseExpression("#kapow(2.0d,2.0d)"); - assertEquals("4.0", expression.getValue(ctx).toString()); + assertThat(expression.getValue(ctx).toString()).isEqualTo("4.0"); assertCanCompile(expression); - assertEquals("4.0", expression.getValue(ctx).toString()); + assertThat(expression.getValue(ctx).toString()).isEqualTo("4.0"); } @Test @@ -1004,7 +1004,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { context.setVariable("arg", "2"); // type nor method are public expression = parser.parseExpression("#doCompare([0],#arg)"); - assertEquals("-1", expression.getValue(context, Integer.class).toString()); + assertThat(expression.getValue(context, Integer.class).toString()).isEqualTo("-1"); assertCantCompile(expression); // type not public but method is @@ -1013,7 +1013,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { "compare2", Object.class, Object.class)); context.setVariable("arg", "2"); expression = parser.parseExpression("#doCompare([0],#arg)"); - assertEquals("-1", expression.getValue(context, Integer.class).toString()); + assertThat(expression.getValue(context, Integer.class).toString()).isEqualTo("-1"); assertCantCompile(expression); } @@ -1027,9 +1027,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { context.setVariable("ints",ints); expression = parser.parseExpression("#negate(#ints.?[#this<2][0])"); - assertEquals("-1", expression.getValue(context, Integer.class).toString()); + assertThat(expression.getValue(context, Integer.class).toString()).isEqualTo("-1"); // Selection isn't compilable. - assertFalse(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isFalse(); } @Test @@ -1057,65 +1057,65 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { context.setVariable("floatArray", new float[] {5.0f,6.0f,9.0f}); expression = parser.parseExpression("#append('a','b','c')"); - assertEquals("abc", expression.getValue(context).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context).toString()).isEqualTo("abc"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("abc", expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("abc"); expression = parser.parseExpression("#append('a')"); - assertEquals("a", expression.getValue(context).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context).toString()).isEqualTo("a"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("a", expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("a"); expression = parser.parseExpression("#append()"); - assertEquals("", expression.getValue(context).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context).toString()).isEqualTo(""); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("", expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo(""); expression = parser.parseExpression("#append(#stringArray)"); - assertEquals("xyz", expression.getValue(context).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context).toString()).isEqualTo("xyz"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("xyz", expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("xyz"); // This is a methodreference invocation, to compare with functionreference expression = parser.parseExpression("append(#stringArray)"); - assertEquals("xyz", expression.getValue(context,new SomeCompareMethod2()).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context, new SomeCompareMethod2()).toString()).isEqualTo("xyz"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("xyz", expression.getValue(context,new SomeCompareMethod2()).toString()); + assertThat(expression.getValue(context, new SomeCompareMethod2()).toString()).isEqualTo("xyz"); expression = parser.parseExpression("#append2('a','b','c')"); - assertEquals("abc", expression.getValue(context).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context).toString()).isEqualTo("abc"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("abc", expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("abc"); expression = parser.parseExpression("append2('a','b')"); - assertEquals("ab", expression.getValue(context, new SomeCompareMethod2()).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context, new SomeCompareMethod2()).toString()).isEqualTo("ab"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("ab", expression.getValue(context, new SomeCompareMethod2()).toString()); + assertThat(expression.getValue(context, new SomeCompareMethod2()).toString()).isEqualTo("ab"); expression = parser.parseExpression("#append2('a','b')"); - assertEquals("ab", expression.getValue(context).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context).toString()).isEqualTo("ab"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("ab", expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("ab"); expression = parser.parseExpression("#append2()"); - assertEquals("", expression.getValue(context).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context).toString()).isEqualTo(""); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("", expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo(""); expression = parser.parseExpression("#append3(#stringArray)"); - assertEquals("xyz", expression.getValue(context, new SomeCompareMethod2()).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context, new SomeCompareMethod2()).toString()).isEqualTo("xyz"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("xyz", expression.getValue(context, new SomeCompareMethod2()).toString()); + assertThat(expression.getValue(context, new SomeCompareMethod2()).toString()).isEqualTo("xyz"); // TODO fails due to conversionservice handling of String[] to Object... // expression = parser.parseExpression("#append2(#stringArray)"); @@ -1125,108 +1125,108 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { // assertEquals("xyz", expression.getValue(context).toString()); expression = parser.parseExpression("#sum(1,2,3)"); - assertEquals(6, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(6); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(6, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(6); expression = parser.parseExpression("#sum(2)"); - assertEquals(2, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(2); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(2, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(2); expression = parser.parseExpression("#sum()"); - assertEquals(0, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(0); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(0, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(0); expression = parser.parseExpression("#sum(#intArray)"); - assertEquals(20, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(20); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(20, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(20); expression = parser.parseExpression("#sumDouble(1.0d,2.0d,3.0d)"); - assertEquals(6, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(6); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(6, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(6); expression = parser.parseExpression("#sumDouble(2.0d)"); - assertEquals(2, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(2); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(2, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(2); expression = parser.parseExpression("#sumDouble()"); - assertEquals(0, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(0); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(0, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(0); expression = parser.parseExpression("#sumDouble(#doubleArray)"); - assertEquals(20, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(20); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(20, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(20); expression = parser.parseExpression("#sumFloat(1.0f,2.0f,3.0f)"); - assertEquals(6, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(6); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(6, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(6); expression = parser.parseExpression("#sumFloat(2.0f)"); - assertEquals(2, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(2); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(2, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(2); expression = parser.parseExpression("#sumFloat()"); - assertEquals(0, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(0); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(0, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(0); expression = parser.parseExpression("#sumFloat(#floatArray)"); - assertEquals(20, expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo(20); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals(20, expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo(20); expression = parser.parseExpression("#appendChar('abc'.charAt(0),'abc'.charAt(1))"); - assertEquals("ab", expression.getValue(context)); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context)).isEqualTo("ab"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("ab", expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("ab"); expression = parser.parseExpression("#append4('a','b','c')"); - assertEquals("a::bc", expression.getValue(context).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context).toString()).isEqualTo("a::bc"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("a::bc", expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("a::bc"); expression = parser.parseExpression("#append4('a','b')"); - assertEquals("a::b", expression.getValue(context).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context).toString()).isEqualTo("a::b"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("a::b", expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("a::b"); expression = parser.parseExpression("#append4('a')"); - assertEquals("a::", expression.getValue(context).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context).toString()).isEqualTo("a::"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("a::", expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("a::"); expression = parser.parseExpression("#append4('a',#stringArray)"); - assertEquals("a::xyz", expression.getValue(context).toString()); - assertTrue(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()); + assertThat(expression.getValue(context).toString()).isEqualTo("a::xyz"); + assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertEquals("a::xyz", expression.getValue(context).toString()); + assertThat(expression.getValue(context).toString()).isEqualTo("a::xyz"); } @Test @@ -1235,9 +1235,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { Method m = getClass().getDeclaredMethod("join", String[].class); ctx.setVariable("join", m); expression = parser.parseExpression("#join('a','b','c')"); - assertEquals("abc", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("abc"); assertCanCompile(expression); - assertEquals("abc", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("abc"); } @Test @@ -1245,11 +1245,11 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { EvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariable("target", "abc"); expression = parser.parseExpression("#target"); - assertEquals("abc", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("abc"); assertCanCompile(expression); - assertEquals("abc", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("abc"); ctx.setVariable("target", "123"); - assertEquals("123", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("123"); ctx.setVariable("target", 42); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> expression.getValue(ctx)) @@ -1257,11 +1257,11 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { ctx.setVariable("target", "abc"); expression = parser.parseExpression("#target.charAt(0)"); - assertEquals('a', expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo('a'); assertCanCompile(expression); - assertEquals('a', expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo('a'); ctx.setVariable("target", "1"); - assertEquals('1', expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo('1'); ctx.setVariable("target", 42); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> expression.getValue(ctx)) @@ -1272,282 +1272,282 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { public void opLt() throws Exception { expression = parse("3.0d < 4.0d"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3446.0d < 1123.0d"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("3 < 1"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("2 < 4"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3.0f < 1.0f"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("1.0f < 5.0f"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("30L < 30L"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("15L < 20L"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); // Differing types of number, not yet supported expression = parse("1 < 3.0d"); assertCantCompile(expression); expression = parse("T(Integer).valueOf(3) < 4"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("T(Integer).valueOf(3) < T(Integer).valueOf(3)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("5 < T(Integer).valueOf(3)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); } @Test public void opLe() throws Exception { expression = parse("3.0d <= 4.0d"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3446.0d <= 1123.0d"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("3446.0d <= 3446.0d"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3 <= 1"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("2 <= 4"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3 <= 3"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3.0f <= 1.0f"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("1.0f <= 5.0f"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("2.0f <= 2.0f"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("30L <= 30L"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("15L <= 20L"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); // Differing types of number, not yet supported expression = parse("1 <= 3.0d"); assertCantCompile(expression); expression = parse("T(Integer).valueOf(3) <= 4"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("T(Integer).valueOf(3) <= T(Integer).valueOf(3)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("5 <= T(Integer).valueOf(3)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); } @Test public void opGt() throws Exception { expression = parse("3.0d > 4.0d"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("3446.0d > 1123.0d"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3 > 1"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("2 > 4"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("3.0f > 1.0f"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("1.0f > 5.0f"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("30L > 30L"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("15L > 20L"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); // Differing types of number, not yet supported expression = parse("1 > 3.0d"); assertCantCompile(expression); expression = parse("T(Integer).valueOf(3) > 4"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Integer).valueOf(3) > T(Integer).valueOf(3)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("5 > T(Integer).valueOf(3)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); } @Test public void opGe() throws Exception { expression = parse("3.0d >= 4.0d"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("3446.0d >= 1123.0d"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3446.0d >= 3446.0d"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3 >= 1"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("2 >= 4"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("3 >= 3"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3.0f >= 1.0f"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("1.0f >= 5.0f"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("3.0f >= 3.0f"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("40L >= 30L"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("15L >= 20L"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("30L >= 30L"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); // Differing types of number, not yet supported expression = parse("1 >= 3.0d"); assertCantCompile(expression); expression = parse("T(Integer).valueOf(3) >= 4"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Integer).valueOf(3) >= T(Integer).valueOf(3)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("5 >= T(Integer).valueOf(3)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); } @Test public void opEq() throws Exception { String tvar = "35"; expression = parse("#root == 35"); - assertFalse((Boolean) expression.getValue(tvar)); + assertThat((boolean) (Boolean) expression.getValue(tvar)).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue(tvar)); + assertThat((boolean) (Boolean) expression.getValue(tvar)).isFalse(); expression = parse("35 == #root"); expression.getValue(tvar); - assertFalse((Boolean) expression.getValue(tvar)); + assertThat((boolean) (Boolean) expression.getValue(tvar)).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue(tvar)); + assertThat((boolean) (Boolean) expression.getValue(tvar)).isFalse(); TestClass7 tc7 = new TestClass7(); expression = parse("property == 'UK'"); - assertTrue((Boolean) expression.getValue(tc7)); + assertThat((boolean) (Boolean) expression.getValue(tc7)).isTrue(); TestClass7.property = null; - assertFalse((Boolean) expression.getValue(tc7)); + assertThat((boolean) (Boolean) expression.getValue(tc7)).isFalse(); assertCanCompile(expression); TestClass7.reset(); - assertTrue((Boolean) expression.getValue(tc7)); + assertThat((boolean) (Boolean) expression.getValue(tc7)).isTrue(); TestClass7.property = "UK"; - assertTrue((Boolean) expression.getValue(tc7)); + assertThat((boolean) (Boolean) expression.getValue(tc7)).isTrue(); TestClass7.reset(); TestClass7.property = null; - assertFalse((Boolean) expression.getValue(tc7)); + assertThat((boolean) (Boolean) expression.getValue(tc7)).isFalse(); expression = parse("property == null"); - assertTrue((Boolean) expression.getValue(tc7)); + assertThat((boolean) (Boolean) expression.getValue(tc7)).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue(tc7)); + assertThat((boolean) (Boolean) expression.getValue(tc7)).isTrue(); expression = parse("3.0d == 4.0d"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("3446.0d == 3446.0d"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3 == 1"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("3 == 3"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3.0f == 1.0f"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("2.0f == 2.0f"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("30L == 30L"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("15L == 20L"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); // number types are not the same expression = parse("1 == 3.0d"); @@ -1555,228 +1555,228 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { Double d = 3.0d; expression = parse("#root==3.0d"); - assertTrue((Boolean) expression.getValue(d)); + assertThat((boolean) (Boolean) expression.getValue(d)).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue(d)); + assertThat((boolean) (Boolean) expression.getValue(d)).isTrue(); Integer i = 3; expression = parse("#root==3"); - assertTrue((Boolean) expression.getValue(i)); + assertThat((boolean) (Boolean) expression.getValue(i)).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue(i)); + assertThat((boolean) (Boolean) expression.getValue(i)).isTrue(); Float f = 3.0f; expression = parse("#root==3.0f"); - assertTrue((Boolean) expression.getValue(f)); + assertThat((boolean) (Boolean) expression.getValue(f)).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue(f)); + assertThat((boolean) (Boolean) expression.getValue(f)).isTrue(); long l = 300L; expression = parse("#root==300l"); - assertTrue((Boolean) expression.getValue(l)); + assertThat((boolean) (Boolean) expression.getValue(l)).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue(l)); + assertThat((boolean) (Boolean) expression.getValue(l)).isTrue(); boolean b = true; expression = parse("#root==true"); - assertTrue((Boolean) expression.getValue(b)); + assertThat((boolean) (Boolean) expression.getValue(b)).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue(b)); + assertThat((boolean) (Boolean) expression.getValue(b)).isTrue(); expression = parse("T(Integer).valueOf(3) == 4"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Integer).valueOf(3) == T(Integer).valueOf(3)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("5 == T(Integer).valueOf(3)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Float).valueOf(3.0f) == 4.0f"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Float).valueOf(3.0f) == T(Float).valueOf(3.0f)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("5.0f == T(Float).valueOf(3.0f)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Long).valueOf(3L) == 4L"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Long).valueOf(3L) == T(Long).valueOf(3L)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("5L == T(Long).valueOf(3L)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Double).valueOf(3.0d) == 4.0d"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Double).valueOf(3.0d) == T(Double).valueOf(3.0d)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("5.0d == T(Double).valueOf(3.0d)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("false == true"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Boolean).valueOf('true') == T(Boolean).valueOf('true')"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("T(Boolean).valueOf('true') == true"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("false == T(Boolean).valueOf('false')"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); } @Test public void opNe() throws Exception { expression = parse("3.0d != 4.0d"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3446.0d != 3446.0d"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("3 != 1"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("3 != 3"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("3.0f != 1.0f"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("2.0f != 2.0f"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("30L != 30L"); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("15L != 20L"); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); // not compatible number types expression = parse("1 != 3.0d"); assertCantCompile(expression); expression = parse("T(Integer).valueOf(3) != 4"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("T(Integer).valueOf(3) != T(Integer).valueOf(3)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("5 != T(Integer).valueOf(3)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("T(Float).valueOf(3.0f) != 4.0f"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("T(Float).valueOf(3.0f) != T(Float).valueOf(3.0f)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("5.0f != T(Float).valueOf(3.0f)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("T(Long).valueOf(3L) != 4L"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("T(Long).valueOf(3L) != T(Long).valueOf(3L)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("5L != T(Long).valueOf(3L)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("T(Double).valueOf(3.0d) == 4.0d"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Double).valueOf(3.0d) == T(Double).valueOf(3.0d)"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("5.0d == T(Double).valueOf(3.0d)"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("false == true"); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); assertCanCompile(expression); - assertFalse((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isFalse(); expression = parse("T(Boolean).valueOf('true') == T(Boolean).valueOf('true')"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("T(Boolean).valueOf('true') == true"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); expression = parse("false == T(Boolean).valueOf('false')"); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); assertCanCompile(expression); - assertTrue((Boolean) expression.getValue()); + assertThat((boolean) (Boolean) expression.getValue()).isTrue(); } @Test @@ -1789,22 +1789,22 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { Map data = new HashMap<>(); data.put("my-key", new String("my-value")); StandardEvaluationContext context = new StandardEvaluationContext(new MyContext(data)); - assertFalse(expression.getValue(context, Boolean.class)); + assertThat(expression.getValue(context, Boolean.class)).isFalse(); assertCanCompile(expression); ((SpelExpression) expression).compileExpression(); - assertFalse(expression.getValue(context, Boolean.class)); + assertThat(expression.getValue(context, Boolean.class)).isFalse(); List ls = new ArrayList(); ls.add(new String("foo")); context = new StandardEvaluationContext(ls); expression = parse("get(0) != 'foo'"); - assertFalse(expression.getValue(context, Boolean.class)); + assertThat(expression.getValue(context, Boolean.class)).isFalse(); assertCanCompile(expression); - assertFalse(expression.getValue(context, Boolean.class)); + assertThat(expression.getValue(context, Boolean.class)).isFalse(); ls.remove(0); ls.add("goo"); - assertTrue(expression.getValue(context, Boolean.class)); + assertThat(expression.getValue(context, Boolean.class)).isTrue(); } @Test @@ -1819,12 +1819,12 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { sec.setVariable("bb",bb); boolean b = expression.getValue(sec, Boolean.class); // Verify what the expression caused aa to be compared to - assertEquals(bb,aa.gotComparedTo); - assertFalse(b); + assertThat(aa.gotComparedTo).isEqualTo(bb); + assertThat(b).isFalse(); bb.setValue(1); b = expression.getValue(sec, Boolean.class); - assertEquals(bb,aa.gotComparedTo); - assertTrue(b); + assertThat(aa.gotComparedTo).isEqualTo(bb); + assertThat(b).isTrue(); assertCanCompile(expression); @@ -1834,25 +1834,25 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { sec.setVariable("aa",aa); sec.setVariable("bb",bb); b = expression.getValue(sec, Boolean.class); - assertFalse(b); - assertEquals(bb,aa.gotComparedTo); + assertThat(b).isFalse(); + assertThat(aa.gotComparedTo).isEqualTo(bb); bb.setValue(99); b = expression.getValue(sec, Boolean.class); - assertTrue(b); - assertEquals(bb,aa.gotComparedTo); + assertThat(b).isTrue(); + assertThat(aa.gotComparedTo).isEqualTo(bb); List ls = new ArrayList(); ls.add(new String("foo")); StandardEvaluationContext context = new StandardEvaluationContext(ls); expression = parse("get(0) == 'foo'"); - assertTrue(expression.getValue(context, Boolean.class)); + assertThat(expression.getValue(context, Boolean.class)).isTrue(); assertCanCompile(expression); - assertTrue(expression.getValue(context, Boolean.class)); + assertThat(expression.getValue(context, Boolean.class)).isTrue(); ls.remove(0); ls.add("goo"); - assertFalse(expression.getValue(context, Boolean.class)); + assertThat(expression.getValue(context, Boolean.class)).isFalse(); } @Test @@ -1860,92 +1860,92 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parse("2+2"); expression.getValue(); assertCanCompile(expression); - assertEquals(4, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4); expression = parse("2L+2L"); expression.getValue(); assertCanCompile(expression); - assertEquals(4L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4L); expression = parse("2.0f+2.0f"); expression.getValue(); assertCanCompile(expression); - assertEquals(4.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4.0f); expression = parse("3.0d+4.0d"); expression.getValue(); assertCanCompile(expression); - assertEquals(7.0d, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(7.0d); expression = parse("+1"); expression.getValue(); assertCanCompile(expression); - assertEquals(1, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1); expression = parse("+1L"); expression.getValue(); assertCanCompile(expression); - assertEquals(1L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1L); expression = parse("+1.5f"); expression.getValue(); assertCanCompile(expression); - assertEquals(1.5f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1.5f); expression = parse("+2.5d"); expression.getValue(); assertCanCompile(expression); - assertEquals(2.5d, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2.5d); expression = parse("+T(Double).valueOf(2.5d)"); expression.getValue(); assertCanCompile(expression); - assertEquals(2.5d, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2.5d); expression = parse("T(Integer).valueOf(2)+6"); - assertEquals(8, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(8); assertCanCompile(expression); - assertEquals(8, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(8); expression = parse("T(Integer).valueOf(1)+T(Integer).valueOf(3)"); - assertEquals(4, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4); assertCanCompile(expression); - assertEquals(4, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4); expression = parse("1+T(Integer).valueOf(3)"); - assertEquals(4, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4); assertCanCompile(expression); - assertEquals(4, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4); expression = parse("T(Float).valueOf(2.0f)+6"); - assertEquals(8.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(8.0f); assertCanCompile(expression); - assertEquals(8.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(8.0f); expression = parse("T(Float).valueOf(2.0f)+T(Float).valueOf(3.0f)"); - assertEquals(5.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(5.0f); assertCanCompile(expression); - assertEquals(5.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(5.0f); expression = parse("3L+T(Long).valueOf(4L)"); - assertEquals(7L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(7L); assertCanCompile(expression); - assertEquals(7L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(7L); expression = parse("T(Long).valueOf(2L)+6"); - assertEquals(8L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(8L); assertCanCompile(expression); - assertEquals(8L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(8L); expression = parse("T(Long).valueOf(2L)+T(Long).valueOf(3L)"); - assertEquals(5L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(5L); assertCanCompile(expression); - assertEquals(5L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(5L); expression = parse("1L+T(Long).valueOf(2L)"); - assertEquals(3L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(3L); assertCanCompile(expression); - assertEquals(3L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(3L); } @Test @@ -2314,86 +2314,86 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { private void checkCalc(PayloadX p, String expression, int expectedResult) { Expression expr = parse(expression); - assertEquals(expectedResult, expr.getValue(p)); + assertThat(expr.getValue(p)).isEqualTo(expectedResult); assertCanCompile(expr); - assertEquals(expectedResult, expr.getValue(p)); + assertThat(expr.getValue(p)).isEqualTo(expectedResult); } private void checkCalc(PayloadX p, String expression, float expectedResult) { Expression expr = parse(expression); - assertEquals(expectedResult, expr.getValue(p)); + assertThat(expr.getValue(p)).isEqualTo(expectedResult); assertCanCompile(expr); - assertEquals(expectedResult, expr.getValue(p)); + assertThat(expr.getValue(p)).isEqualTo(expectedResult); } private void checkCalc(PayloadX p, String expression, long expectedResult) { Expression expr = parse(expression); - assertEquals(expectedResult, expr.getValue(p)); + assertThat(expr.getValue(p)).isEqualTo(expectedResult); assertCanCompile(expr); - assertEquals(expectedResult, expr.getValue(p)); + assertThat(expr.getValue(p)).isEqualTo(expectedResult); } private void checkCalc(PayloadX p, String expression, double expectedResult) { Expression expr = parse(expression); - assertEquals(expectedResult, expr.getValue(p)); + assertThat(expr.getValue(p)).isEqualTo(expectedResult); assertCanCompile(expr); - assertEquals(expectedResult, expr.getValue(p)); + assertThat(expr.getValue(p)).isEqualTo(expectedResult); } @Test public void opPlusString() throws Exception { expression = parse("'hello' + 'world'"); - assertEquals("helloworld", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("helloworld"); assertCanCompile(expression); - assertEquals("helloworld", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("helloworld"); // Method with string return expression = parse("'hello' + getWorld()"); - assertEquals("helloworld", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("helloworld"); assertCanCompile(expression); - assertEquals("helloworld", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("helloworld"); // Method with string return expression = parse("getWorld() + 'hello'"); - assertEquals("worldhello", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("worldhello"); assertCanCompile(expression); - assertEquals("worldhello", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("worldhello"); // Three strings, optimal bytecode would only use one StringBuilder expression = parse("'hello' + getWorld() + ' spring'"); - assertEquals("helloworld spring", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("helloworld spring"); assertCanCompile(expression); - assertEquals("helloworld spring", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("helloworld spring"); // Three strings, optimal bytecode would only use one StringBuilder expression = parse("'hello' + 3 + ' spring'"); - assertEquals("hello3 spring", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("hello3 spring"); assertCantCompile(expression); expression = parse("object + 'a'"); - assertEquals("objecta", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("objecta"); assertCanCompile(expression); - assertEquals("objecta", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("objecta"); expression = parse("'a'+object"); - assertEquals("aobject", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("aobject"); assertCanCompile(expression); - assertEquals("aobject", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("aobject"); expression = parse("'a'+object+'a'"); - assertEquals("aobjecta", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("aobjecta"); assertCanCompile(expression); - assertEquals("aobjecta", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("aobjecta"); expression = parse("object+'a'+object"); - assertEquals("objectaobject", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("objectaobject"); assertCanCompile(expression); - assertEquals("objectaobject", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("objectaobject"); expression = parse("object+object"); - assertEquals("objectobject", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("objectobject"); assertCanCompile(expression); - assertEquals("objectobject", expression.getValue(new Greeter())); + assertThat(expression.getValue(new Greeter())).isEqualTo("objectobject"); } @Test @@ -2401,87 +2401,87 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parse("2-2"); expression.getValue(); assertCanCompile(expression); - assertEquals(0, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(0); expression = parse("4L-2L"); expression.getValue(); assertCanCompile(expression); - assertEquals(2L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2L); expression = parse("4.0f-2.0f"); expression.getValue(); assertCanCompile(expression); - assertEquals(2.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2.0f); expression = parse("3.0d-4.0d"); expression.getValue(); assertCanCompile(expression); - assertEquals(-1.0d, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-1.0d); expression = parse("-1"); expression.getValue(); assertCanCompile(expression); - assertEquals(-1, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-1); expression = parse("-1L"); expression.getValue(); assertCanCompile(expression); - assertEquals(-1L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-1L); expression = parse("-1.5f"); expression.getValue(); assertCanCompile(expression); - assertEquals(-1.5f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-1.5f); expression = parse("-2.5d"); expression.getValue(); assertCanCompile(expression); - assertEquals(-2.5d, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-2.5d); expression = parse("T(Integer).valueOf(2)-6"); - assertEquals(-4, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-4); assertCanCompile(expression); - assertEquals(-4, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-4); expression = parse("T(Integer).valueOf(1)-T(Integer).valueOf(3)"); - assertEquals(-2, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-2); assertCanCompile(expression); - assertEquals(-2, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-2); expression = parse("4-T(Integer).valueOf(3)"); - assertEquals(1, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1); assertCanCompile(expression); - assertEquals(1, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1); expression = parse("T(Float).valueOf(2.0f)-6"); - assertEquals(-4.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-4.0f); assertCanCompile(expression); - assertEquals(-4.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-4.0f); expression = parse("T(Float).valueOf(8.0f)-T(Float).valueOf(3.0f)"); - assertEquals(5.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(5.0f); assertCanCompile(expression); - assertEquals(5.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(5.0f); expression = parse("11L-T(Long).valueOf(4L)"); - assertEquals(7L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(7L); assertCanCompile(expression); - assertEquals(7L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(7L); expression = parse("T(Long).valueOf(9L)-6"); - assertEquals(3L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(3L); assertCanCompile(expression); - assertEquals(3L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(3L); expression = parse("T(Long).valueOf(4L)-T(Long).valueOf(3L)"); - assertEquals(1L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1L); assertCanCompile(expression); - assertEquals(1L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1L); expression = parse("8L-T(Long).valueOf(2L)"); - assertEquals(6L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(6L); assertCanCompile(expression); - assertEquals(6L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(6L); } @Test @@ -3035,57 +3035,57 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parse("2*2"); expression.getValue(); assertCanCompile(expression); - assertEquals(4, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4); expression = parse("2L*2L"); expression.getValue(); assertCanCompile(expression); - assertEquals(4L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4L); expression = parse("2.0f*2.0f"); expression.getValue(); assertCanCompile(expression); - assertEquals(4.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4.0f); expression = parse("3.0d*4.0d"); expression.getValue(); assertCanCompile(expression); - assertEquals(12.0d, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(12.0d); expression = parse("T(Float).valueOf(2.0f)*6"); - assertEquals(12.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(12.0f); assertCanCompile(expression); - assertEquals(12.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(12.0f); expression = parse("T(Float).valueOf(8.0f)*T(Float).valueOf(3.0f)"); - assertEquals(24.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(24.0f); assertCanCompile(expression); - assertEquals(24.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(24.0f); expression = parse("11L*T(Long).valueOf(4L)"); - assertEquals(44L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(44L); assertCanCompile(expression); - assertEquals(44L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(44L); expression = parse("T(Long).valueOf(9L)*6"); - assertEquals(54L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(54L); assertCanCompile(expression); - assertEquals(54L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(54L); expression = parse("T(Long).valueOf(4L)*T(Long).valueOf(3L)"); - assertEquals(12L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(12L); assertCanCompile(expression); - assertEquals(12L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(12L); expression = parse("8L*T(Long).valueOf(2L)"); - assertEquals(16L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(16L); assertCanCompile(expression); - assertEquals(16L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(16L); expression = parse("T(Float).valueOf(8.0f)*-T(Float).valueOf(3.0f)"); - assertEquals(-24.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-24.0f); assertCanCompile(expression); - assertEquals(-24.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-24.0f); } @Test @@ -3093,132 +3093,132 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parse("2/2"); expression.getValue(); assertCanCompile(expression); - assertEquals(1, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1); expression = parse("2L/2L"); expression.getValue(); assertCanCompile(expression); - assertEquals(1L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1L); expression = parse("2.0f/2.0f"); expression.getValue(); assertCanCompile(expression); - assertEquals(1.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1.0f); expression = parse("3.0d/4.0d"); expression.getValue(); assertCanCompile(expression); - assertEquals(0.75d, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(0.75d); expression = parse("T(Float).valueOf(6.0f)/2"); - assertEquals(3.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(3.0f); assertCanCompile(expression); - assertEquals(3.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(3.0f); expression = parse("T(Float).valueOf(8.0f)/T(Float).valueOf(2.0f)"); - assertEquals(4.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4.0f); assertCanCompile(expression); - assertEquals(4.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4.0f); expression = parse("12L/T(Long).valueOf(4L)"); - assertEquals(3L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(3L); assertCanCompile(expression); - assertEquals(3L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(3L); expression = parse("T(Long).valueOf(44L)/11"); - assertEquals(4L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4L); assertCanCompile(expression); - assertEquals(4L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4L); expression = parse("T(Long).valueOf(4L)/T(Long).valueOf(2L)"); - assertEquals(2L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2L); assertCanCompile(expression); - assertEquals(2L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2L); expression = parse("8L/T(Long).valueOf(2L)"); - assertEquals(4L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4L); assertCanCompile(expression); - assertEquals(4L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(4L); expression = parse("T(Float).valueOf(8.0f)/-T(Float).valueOf(4.0f)"); - assertEquals(-2.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-2.0f); assertCanCompile(expression); - assertEquals(-2.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(-2.0f); } @Test public void opModulus_12041() throws Exception { expression = parse("2%2"); - assertEquals(0, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(0); assertCanCompile(expression); - assertEquals(0, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(0); expression = parse("payload%2==0"); - assertTrue(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.TYPE)); - assertFalse(expression.getValue(new GenericMessageTestHelper<>(5), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.TYPE)).isTrue(); + assertThat(expression.getValue(new GenericMessageTestHelper<>(5), Boolean.TYPE)).isFalse(); assertCanCompile(expression); - assertTrue(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.TYPE)); - assertFalse(expression.getValue(new GenericMessageTestHelper<>(5), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.TYPE)).isTrue(); + assertThat(expression.getValue(new GenericMessageTestHelper<>(5), Boolean.TYPE)).isFalse(); expression = parse("8%3"); - assertEquals(2, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2); assertCanCompile(expression); - assertEquals(2, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2); expression = parse("17L%5L"); - assertEquals(2L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2L); assertCanCompile(expression); - assertEquals(2L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2L); expression = parse("3.0f%2.0f"); - assertEquals(1.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1.0f); assertCanCompile(expression); - assertEquals(1.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1.0f); expression = parse("3.0d%4.0d"); - assertEquals(3.0d, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(3.0d); assertCanCompile(expression); - assertEquals(3.0d, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(3.0d); expression = parse("T(Float).valueOf(6.0f)%2"); - assertEquals(0.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(0.0f); assertCanCompile(expression); - assertEquals(0.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(0.0f); expression = parse("T(Float).valueOf(6.0f)%4"); - assertEquals(2.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2.0f); assertCanCompile(expression); - assertEquals(2.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2.0f); expression = parse("T(Float).valueOf(8.0f)%T(Float).valueOf(3.0f)"); - assertEquals(2.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2.0f); assertCanCompile(expression); - assertEquals(2.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(2.0f); expression = parse("13L%T(Long).valueOf(4L)"); - assertEquals(1L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1L); assertCanCompile(expression); - assertEquals(1L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1L); expression = parse("T(Long).valueOf(44L)%12"); - assertEquals(8L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(8L); assertCanCompile(expression); - assertEquals(8L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(8L); expression = parse("T(Long).valueOf(9L)%T(Long).valueOf(2L)"); - assertEquals(1L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1L); assertCanCompile(expression); - assertEquals(1L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1L); expression = parse("7L%T(Long).valueOf(2L)"); - assertEquals(1L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1L); assertCanCompile(expression); - assertEquals(1L, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1L); expression = parse("T(Float).valueOf(9.0f)%-T(Float).valueOf(4.0f)"); - assertEquals(1.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1.0f); assertCanCompile(expression); - assertEquals(1.0f, expression.getValue()); + assertThat(expression.getValue()).isEqualTo(1.0f); } @Test @@ -3229,16 +3229,16 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(new Object[] {1}); context.setVariable("it", 3); expression.setEvaluationContext(context); - assertTrue(expression.getValue(Boolean.class)); + assertThat(expression.getValue(Boolean.class)).isTrue(); context.setVariable("it", null); - assertNull(expression.getValue(Boolean.class)); + assertThat(expression.getValue(Boolean.class)).isNull(); assertCanCompile(expression); context.setVariable("it", 3); - assertTrue(expression.getValue(Boolean.class)); + assertThat(expression.getValue(Boolean.class)).isTrue(); context.setVariable("it", null); - assertNull(expression.getValue(Boolean.class)); + assertThat(expression.getValue(Boolean.class)).isNull(); } @Test @@ -3250,18 +3250,18 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(new Object[] {1}); context.setVariable("it", person); expression.setEvaluationContext(context); - assertTrue(expression.getValue(Boolean.class)); + assertThat(expression.getValue(Boolean.class)).isTrue(); // This will trigger compilation (second usage) - assertTrue(expression.getValue(Boolean.class)); + assertThat(expression.getValue(Boolean.class)).isTrue(); context.setVariable("it", null); - assertNull(expression.getValue(Boolean.class)); + assertThat(expression.getValue(Boolean.class)).isNull(); assertCanCompile(expression); context.setVariable("it", person); - assertTrue(expression.getValue(Boolean.class)); + assertThat(expression.getValue(Boolean.class)).isTrue(); context.setVariable("it", null); - assertNull(expression.getValue(Boolean.class)); + assertThat(expression.getValue(Boolean.class)).isNull(); } @@ -3272,9 +3272,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { public void constructorReference_SPR13781() { // Static field access on a T() referenced type expression = parser.parseExpression("T(java.util.Locale).ENGLISH"); - assertEquals("en", expression.getValue().toString()); + assertThat(expression.getValue().toString()).isEqualTo("en"); assertCanCompile(expression); - assertEquals("en", expression.getValue().toString()); + assertThat(expression.getValue().toString()).isEqualTo("en"); // The actual expression from the bug report. It fails if the ENGLISH reference fails // to pop the type reference for Locale off the stack (if it isn't popped then @@ -3284,27 +3284,27 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parser.parseExpression("#userId.toString().toLowerCase(T(java.util.Locale).ENGLISH)"); StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("userId", "RoDnEy"); - assertEquals("rodney", expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("rodney"); assertCanCompile(expression); - assertEquals("rodney", expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("rodney"); // Property access on a class object expression = parser.parseExpression("T(String).name"); - assertEquals("java.lang.String", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("java.lang.String"); assertCanCompile(expression); - assertEquals("java.lang.String", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("java.lang.String"); // Now the type reference isn't on the stack, and needs loading context = new StandardEvaluationContext(String.class); expression = parser.parseExpression("name"); - assertEquals("java.lang.String", expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("java.lang.String"); assertCanCompile(expression); - assertEquals("java.lang.String", expression.getValue(context)); + assertThat(expression.getValue(context)).isEqualTo("java.lang.String"); expression = parser.parseExpression("T(String).getName()"); - assertEquals("java.lang.String", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("java.lang.String"); assertCanCompile(expression); - assertEquals("java.lang.String", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("java.lang.String"); // These tests below verify that the chain of static accesses (either method/property or field) // leave the right thing on top of the stack for processing by any outer consuming code. @@ -3315,48 +3315,48 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { String shclass = StaticsHelper.class.getName(); // Basic chain: property access then method access expression = parser.parseExpression("T(String).valueOf(T(String).name.valueOf(1))"); - assertEquals("1", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("1"); assertCanCompile(expression); - assertEquals("1", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("1"); // chain of statics ending with static method expression = parser.parseExpression("T(String).valueOf(T(" + shclass + ").methoda().methoda().methodb())"); - assertEquals("mb", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("mb"); assertCanCompile(expression); - assertEquals("mb", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("mb"); // chain of statics ending with static field expression = parser.parseExpression("T(String).valueOf(T(" + shclass + ").fielda.fielda.fieldb)"); - assertEquals("fb", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("fb"); assertCanCompile(expression); - assertEquals("fb", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("fb"); // chain of statics ending with static property access expression = parser.parseExpression("T(String).valueOf(T(" + shclass + ").propertya.propertya.propertyb)"); - assertEquals("pb", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("pb"); assertCanCompile(expression); - assertEquals("pb", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("pb"); // variety chain expression = parser.parseExpression("T(String).valueOf(T(" + shclass + ").fielda.methoda().propertya.fieldb)"); - assertEquals("fb", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("fb"); assertCanCompile(expression); - assertEquals("fb", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("fb"); expression = parser.parseExpression("T(String).valueOf(fielda.fieldb)"); - assertEquals("fb", expression.getValue(StaticsHelper.sh)); + assertThat(expression.getValue(StaticsHelper.sh)).isEqualTo("fb"); assertCanCompile(expression); - assertEquals("fb", expression.getValue(StaticsHelper.sh)); + assertThat(expression.getValue(StaticsHelper.sh)).isEqualTo("fb"); expression = parser.parseExpression("T(String).valueOf(propertya.propertyb)"); - assertEquals("pb", expression.getValue(StaticsHelper.sh)); + assertThat(expression.getValue(StaticsHelper.sh)).isEqualTo("pb"); assertCanCompile(expression); - assertEquals("pb", expression.getValue(StaticsHelper.sh)); + assertThat(expression.getValue(StaticsHelper.sh)).isEqualTo("pb"); expression = parser.parseExpression("T(String).valueOf(methoda().methodb())"); - assertEquals("mb", expression.getValue(StaticsHelper.sh)); + assertThat(expression.getValue(StaticsHelper.sh)).isEqualTo("mb"); assertCanCompile(expression); - assertEquals("mb", expression.getValue(StaticsHelper.sh)); + assertThat(expression.getValue(StaticsHelper.sh)).isEqualTo("mb"); } @@ -3366,76 +3366,76 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { String prefix = "new " + type + ".Obj"; expression = parser.parseExpression(prefix + "([0])"); - assertEquals("test", ((Obj) expression.getValue(new Object[] {"test"})).param1); + assertThat(((Obj) expression.getValue(new Object[]{"test"})).param1).isEqualTo("test"); assertCanCompile(expression); - assertEquals("test", ((Obj) expression.getValue(new Object[] {"test"})).param1); + assertThat(((Obj) expression.getValue(new Object[]{"test"})).param1).isEqualTo("test"); expression = parser.parseExpression(prefix + "2('foo','bar').output"); - assertEquals("foobar", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("foobar"); assertCanCompile(expression); - assertEquals("foobar", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("foobar"); expression = parser.parseExpression(prefix + "2('foo').output"); - assertEquals("foo", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("foo"); assertCanCompile(expression); - assertEquals("foo", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("foo"); expression = parser.parseExpression(prefix + "2().output"); - assertEquals("", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo(""); assertCanCompile(expression); - assertEquals("", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo(""); expression = parser.parseExpression(prefix + "3(1,2,3).output"); - assertEquals("123", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("123"); assertCanCompile(expression); - assertEquals("123", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("123"); expression = parser.parseExpression(prefix + "3(1).output"); - assertEquals("1", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("1"); assertCanCompile(expression); - assertEquals("1", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("1"); expression = parser.parseExpression(prefix + "3().output"); - assertEquals("", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo(""); assertCanCompile(expression); - assertEquals("", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo(""); expression = parser.parseExpression(prefix + "3('abc',5.0f,1,2,3).output"); - assertEquals("abc:5.0:123", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("abc:5.0:123"); assertCanCompile(expression); - assertEquals("abc:5.0:123", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("abc:5.0:123"); expression = parser.parseExpression(prefix + "3('abc',5.0f,1).output"); - assertEquals("abc:5.0:1", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("abc:5.0:1"); assertCanCompile(expression); - assertEquals("abc:5.0:1", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("abc:5.0:1"); expression = parser.parseExpression(prefix + "3('abc',5.0f).output"); - assertEquals("abc:5.0:", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("abc:5.0:"); assertCanCompile(expression); - assertEquals("abc:5.0:", expression.getValue(String.class)); + assertThat(expression.getValue(String.class)).isEqualTo("abc:5.0:"); expression = parser.parseExpression(prefix + "4(#root).output"); - assertEquals("123", expression.getValue(new int[] {1,2,3}, String.class)); + assertThat(expression.getValue(new int[] {1,2,3}, String.class)).isEqualTo("123"); assertCanCompile(expression); - assertEquals("123", expression.getValue(new int[] {1,2,3}, String.class)); + assertThat(expression.getValue(new int[] {1,2,3}, String.class)).isEqualTo("123"); } @Test public void methodReferenceMissingCastAndRootObjectAccessing_SPR12326() { // Need boxing code on the 1 so that toString() can be called expression = parser.parseExpression("1.toString()"); - assertEquals("1", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("1"); assertCanCompile(expression); - assertEquals("1", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("1"); expression = parser.parseExpression("#it?.age.equals([0])"); Person person = new Person(1); StandardEvaluationContext context = new StandardEvaluationContext(new Object[] {person.getAge()}); context.setVariable("it", person); - assertTrue(expression.getValue(context, Boolean.class)); + assertThat(expression.getValue(context, Boolean.class)).isTrue(); assertCanCompile(expression); - assertTrue(expression.getValue(context, Boolean.class)); + assertThat(expression.getValue(context, Boolean.class)).isTrue(); // Variant of above more like what was in the bug report: SpelExpressionParser parser = new SpelExpressionParser( @@ -3444,64 +3444,65 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { SpelExpression ex = parser.parseRaw("#it?.age.equals([0])"); context = new StandardEvaluationContext(new Object[] {person.getAge()}); context.setVariable("it", person); - assertTrue(ex.getValue(context, Boolean.class)); - assertTrue(ex.getValue(context, Boolean.class)); + assertThat(ex.getValue(context, Boolean.class)).isTrue(); + assertThat(ex.getValue(context, Boolean.class)).isTrue(); PersonInOtherPackage person2 = new PersonInOtherPackage(1); ex = parser.parseRaw("#it?.age.equals([0])"); context = new StandardEvaluationContext(new Object[] {person2.getAge()}); context.setVariable("it", person2); - assertTrue(ex.getValue(context, Boolean.class)); - assertTrue(ex.getValue(context, Boolean.class)); + assertThat(ex.getValue(context, Boolean.class)).isTrue(); + assertThat(ex.getValue(context, Boolean.class)).isTrue(); ex = parser.parseRaw("#it?.age.equals([0])"); context = new StandardEvaluationContext(new Object[] {person2.getAge()}); context.setVariable("it", person2); - assertTrue((Boolean) ex.getValue(context)); - assertTrue((Boolean) ex.getValue(context)); + assertThat((boolean) (Boolean) ex.getValue(context)).isTrue(); + assertThat((boolean) (Boolean) ex.getValue(context)).isTrue(); } @Test public void constructorReference() throws Exception { // simple ctor expression = parser.parseExpression("new String('123')"); - assertEquals("123", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("123"); assertCanCompile(expression); - assertEquals("123", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("123"); String testclass8 = "org.springframework.expression.spel.SpelCompilationCoverageTests$TestClass8"; // multi arg ctor that includes primitives expression = parser.parseExpression("new " + testclass8 + "(42,'123',4.0d,true)"); - assertEquals(testclass8, expression.getValue().getClass().getName()); + assertThat(expression.getValue().getClass().getName()).isEqualTo(testclass8); assertCanCompile(expression); Object o = expression.getValue(); - assertEquals(testclass8,o.getClass().getName()); + assertThat(o.getClass().getName()).isEqualTo(testclass8); TestClass8 tc8 = (TestClass8) o; - assertEquals(42, tc8.i); - assertEquals("123", tc8.s); - assertEquals(4.0d, tc8.d, 0.5d); - assertEquals(true, tc8.z); + assertThat(tc8.i).isEqualTo(42); + assertThat(tc8.s).isEqualTo("123"); + assertThat(tc8.d).isCloseTo(4.0d, within(0.5d)); + + assertThat(tc8.z).isEqualTo(true); // no-arg ctor expression = parser.parseExpression("new " + testclass8 + "()"); - assertEquals(testclass8, expression.getValue().getClass().getName()); + assertThat(expression.getValue().getClass().getName()).isEqualTo(testclass8); assertCanCompile(expression); o = expression.getValue(); - assertEquals(testclass8,o.getClass().getName()); + assertThat(o.getClass().getName()).isEqualTo(testclass8); // pass primitive to reference type ctor expression = parser.parseExpression("new " + testclass8 + "(42)"); - assertEquals(testclass8, expression.getValue().getClass().getName()); + assertThat(expression.getValue().getClass().getName()).isEqualTo(testclass8); assertCanCompile(expression); o = expression.getValue(); - assertEquals(testclass8,o.getClass().getName()); + assertThat(o.getClass().getName()).isEqualTo(testclass8); tc8 = (TestClass8) o; - assertEquals(42, tc8.i); + assertThat(tc8.i).isEqualTo(42); // private class, can't compile it String testclass9 = "org.springframework.expression.spel.SpelCompilationCoverageTests$TestClass9"; expression = parser.parseExpression("new " + testclass9 + "(42)"); - assertEquals(testclass9, expression.getValue().getClass().getName()); + assertThat(expression.getValue().getClass().getName()).isEqualTo(testclass9); assertCantCompile(expression); } @@ -3514,22 +3515,22 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parser.parseExpression("concat('test')"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("::test", tc.s); + assertThat(tc.s).isEqualTo("::test"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("::test", tc.s); + assertThat(tc.s).isEqualTo("::test"); tc.reset(); // This will call the varargs concat with an empty array expression = parser.parseExpression("concat()"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("", tc.s); + assertThat(tc.s).isEqualTo(""); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("", tc.s); + assertThat(tc.s).isEqualTo(""); tc.reset(); // Should call the non varargs version of concat @@ -3537,22 +3538,22 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parser.parseExpression("concat2('test')"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("::test", tc.s); + assertThat(tc.s).isEqualTo("::test"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("::test", tc.s); + assertThat(tc.s).isEqualTo("::test"); tc.reset(); // This will call the varargs concat with an empty array expression = parser.parseExpression("concat2()"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("", tc.s); + assertThat(tc.s).isEqualTo(""); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("", tc.s); + assertThat(tc.s).isEqualTo(""); tc.reset(); } @@ -3564,54 +3565,54 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parser.parseExpression("eleven()"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("", tc.s); + assertThat(tc.s).isEqualTo(""); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("", tc.s); + assertThat(tc.s).isEqualTo(""); tc.reset(); // varargs string expression = parser.parseExpression("eleven('aaa')"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("aaa", tc.s); + assertThat(tc.s).isEqualTo("aaa"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("aaa", tc.s); + assertThat(tc.s).isEqualTo("aaa"); tc.reset(); // varargs string expression = parser.parseExpression("eleven(stringArray)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("aaabbbccc", tc.s); + assertThat(tc.s).isEqualTo("aaabbbccc"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("aaabbbccc", tc.s); + assertThat(tc.s).isEqualTo("aaabbbccc"); tc.reset(); // varargs string expression = parser.parseExpression("eleven('aaa','bbb','ccc')"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("aaabbbccc", tc.s); + assertThat(tc.s).isEqualTo("aaabbbccc"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("aaabbbccc", tc.s); + assertThat(tc.s).isEqualTo("aaabbbccc"); tc.reset(); expression = parser.parseExpression("sixteen('aaa','bbb','ccc')"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("aaabbbccc", tc.s); + assertThat(tc.s).isEqualTo("aaabbbccc"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("aaabbbccc", tc.s); + assertThat(tc.s).isEqualTo("aaabbbccc"); tc.reset(); // TODO Fails related to conversion service converting a String[] to satisfy Object... @@ -3629,212 +3630,212 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parser.parseExpression("twelve(1,2,3)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals(6, tc.i); + assertThat(tc.i).isEqualTo(6); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals(6, tc.i); + assertThat(tc.i).isEqualTo(6); tc.reset(); expression = parser.parseExpression("twelve(1)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals(1, tc.i); + assertThat(tc.i).isEqualTo(1); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals(1, tc.i); + assertThat(tc.i).isEqualTo(1); tc.reset(); // one string then varargs string expression = parser.parseExpression("thirteen('aaa','bbb','ccc')"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("aaa::bbbccc", tc.s); + assertThat(tc.s).isEqualTo("aaa::bbbccc"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("aaa::bbbccc", tc.s); + assertThat(tc.s).isEqualTo("aaa::bbbccc"); tc.reset(); // nothing passed to varargs parameter expression = parser.parseExpression("thirteen('aaa')"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("aaa::", tc.s); + assertThat(tc.s).isEqualTo("aaa::"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("aaa::", tc.s); + assertThat(tc.s).isEqualTo("aaa::"); tc.reset(); // nested arrays expression = parser.parseExpression("fourteen('aaa',stringArray,stringArray)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("aaa::{aaabbbccc}{aaabbbccc}", tc.s); + assertThat(tc.s).isEqualTo("aaa::{aaabbbccc}{aaabbbccc}"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("aaa::{aaabbbccc}{aaabbbccc}", tc.s); + assertThat(tc.s).isEqualTo("aaa::{aaabbbccc}{aaabbbccc}"); tc.reset(); // nested primitive array expression = parser.parseExpression("fifteen('aaa',intArray,intArray)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("aaa::{112233}{112233}", tc.s); + assertThat(tc.s).isEqualTo("aaa::{112233}{112233}"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("aaa::{112233}{112233}", tc.s); + assertThat(tc.s).isEqualTo("aaa::{112233}{112233}"); tc.reset(); // varargs boolean expression = parser.parseExpression("arrayz(true,true,false)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("truetruefalse", tc.s); + assertThat(tc.s).isEqualTo("truetruefalse"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("truetruefalse", tc.s); + assertThat(tc.s).isEqualTo("truetruefalse"); tc.reset(); expression = parser.parseExpression("arrayz(true)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("true", tc.s); + assertThat(tc.s).isEqualTo("true"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("true", tc.s); + assertThat(tc.s).isEqualTo("true"); tc.reset(); // varargs short expression = parser.parseExpression("arrays(s1,s2,s3)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("123", tc.s); + assertThat(tc.s).isEqualTo("123"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("123", tc.s); + assertThat(tc.s).isEqualTo("123"); tc.reset(); expression = parser.parseExpression("arrays(s1)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("1", tc.s); + assertThat(tc.s).isEqualTo("1"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("1", tc.s); + assertThat(tc.s).isEqualTo("1"); tc.reset(); // varargs double expression = parser.parseExpression("arrayd(1.0d,2.0d,3.0d)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("1.02.03.0", tc.s); + assertThat(tc.s).isEqualTo("1.02.03.0"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("1.02.03.0", tc.s); + assertThat(tc.s).isEqualTo("1.02.03.0"); tc.reset(); expression = parser.parseExpression("arrayd(1.0d)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("1.0", tc.s); + assertThat(tc.s).isEqualTo("1.0"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("1.0", tc.s); + assertThat(tc.s).isEqualTo("1.0"); tc.reset(); // varargs long expression = parser.parseExpression("arrayj(l1,l2,l3)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("123", tc.s); + assertThat(tc.s).isEqualTo("123"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("123", tc.s); + assertThat(tc.s).isEqualTo("123"); tc.reset(); expression = parser.parseExpression("arrayj(l1)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("1", tc.s); + assertThat(tc.s).isEqualTo("1"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("1", tc.s); + assertThat(tc.s).isEqualTo("1"); tc.reset(); // varargs char expression = parser.parseExpression("arrayc(c1,c2,c3)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("abc", tc.s); + assertThat(tc.s).isEqualTo("abc"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("abc", tc.s); + assertThat(tc.s).isEqualTo("abc"); tc.reset(); expression = parser.parseExpression("arrayc(c1)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("a", tc.s); + assertThat(tc.s).isEqualTo("a"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("a", tc.s); + assertThat(tc.s).isEqualTo("a"); tc.reset(); // varargs byte expression = parser.parseExpression("arrayb(b1,b2,b3)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("656667", tc.s); + assertThat(tc.s).isEqualTo("656667"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("656667", tc.s); + assertThat(tc.s).isEqualTo("656667"); tc.reset(); expression = parser.parseExpression("arrayb(b1)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("65", tc.s); + assertThat(tc.s).isEqualTo("65"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("65", tc.s); + assertThat(tc.s).isEqualTo("65"); tc.reset(); // varargs float expression = parser.parseExpression("arrayf(f1,f2,f3)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("1.02.03.0", tc.s); + assertThat(tc.s).isEqualTo("1.02.03.0"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("1.02.03.0", tc.s); + assertThat(tc.s).isEqualTo("1.02.03.0"); tc.reset(); expression = parser.parseExpression("arrayf(f1)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("1.0", tc.s); + assertThat(tc.s).isEqualTo("1.0"); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("1.0", tc.s); + assertThat(tc.s).isEqualTo("1.0"); tc.reset(); } @@ -3849,7 +3850,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals(1, tc.i); + assertThat(tc.i).isEqualTo(1); tc.reset(); // static method, no args, void return @@ -3859,7 +3860,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals(1, TestClass5._i); + assertThat(TestClass5._i).isEqualTo(1); tc.reset(); // non-static method, reference type return @@ -3868,7 +3869,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression.getValue(tc); assertCanCompile(expression); tc.reset(); - assertEquals("hello", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("hello"); tc.reset(); // non-static method, primitive type return @@ -3877,7 +3878,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression.getValue(tc); assertCanCompile(expression); tc.reset(); - assertEquals(3277700L, expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo(3277700L); tc.reset(); // static method, reference type return @@ -3886,7 +3887,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression.getValue(tc); assertCanCompile(expression); tc.reset(); - assertEquals("hello", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("hello"); tc.reset(); // static method, primitive type return @@ -3895,7 +3896,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression.getValue(tc); assertCanCompile(expression); tc.reset(); - assertEquals(3277700L, expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo(3277700L); tc.reset(); // non-static method, one parameter of reference type @@ -3905,7 +3906,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("foo", tc.s); + assertThat(tc.s).isEqualTo("foo"); tc.reset(); // static method, one parameter of reference type @@ -3915,7 +3916,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals("bar", TestClass5._s); + assertThat(TestClass5._s).isEqualTo("bar"); tc.reset(); // non-static method, one parameter of primitive type @@ -3925,7 +3926,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals(231, tc.i); + assertThat(tc.i).isEqualTo(231); tc.reset(); // static method, one parameter of primitive type @@ -3935,7 +3936,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertEquals(111, TestClass5._i); + assertThat(TestClass5._i).isEqualTo(111); tc.reset(); // method that gets type converted parameters @@ -3944,41 +3945,41 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parser.parseExpression("seven(123)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("123", tc.s); + assertThat(tc.s).isEqualTo("123"); assertCantCompile(expression); // Uncompilable as argument conversion is occurring Expression expression = parser.parseExpression("'abcd'.substring(index1,index2)"); String resultI = expression.getValue(new TestClass1(), String.class); assertCanCompile(expression); String resultC = expression.getValue(new TestClass1(), String.class); - assertEquals("bc", resultI); - assertEquals("bc", resultC); + assertThat(resultI).isEqualTo("bc"); + assertThat(resultC).isEqualTo("bc"); // Converting from an int to a Number expression = parser.parseExpression("takeNumber(123)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("123", tc.s); + assertThat(tc.s).isEqualTo("123"); tc.reset(); assertCanCompile(expression); // The generated code should include boxing of the int to a Number expression.getValue(tc); - assertEquals("123", tc.s); + assertThat(tc.s).isEqualTo("123"); // Passing a subtype expression = parser.parseExpression("takeNumber(T(Integer).valueOf(42))"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("42", tc.s); + assertThat(tc.s).isEqualTo("42"); tc.reset(); assertCanCompile(expression); // The generated code should include boxing of the int to a Number expression.getValue(tc); - assertEquals("42", tc.s); + assertThat(tc.s).isEqualTo("42"); // Passing a subtype expression = parser.parseExpression("takeString(T(Integer).valueOf(42))"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("42", tc.s); + assertThat(tc.s).isEqualTo("42"); tc.reset(); assertCantCompile(expression); // method takes a string and we are passing an Integer } @@ -3993,23 +3994,23 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { int[] is = new int[] {1,2,3}; String[] strings = new String[] {"a","b","c"}; expression = parser.parseExpression("[1]"); - assertEquals(2, expression.getValue(is)); + assertThat(expression.getValue(is)).isEqualTo(2); assertCanCompile(expression); - assertEquals(2, expression.getValue(is)); + assertThat(expression.getValue(is)).isEqualTo(2); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> expression.getValue(strings)) .withCauseInstanceOf(ClassCastException.class); SpelCompiler.revertToInterpreted(expression); - assertEquals("b", expression.getValue(strings)); + assertThat(expression.getValue(strings)).isEqualTo("b"); assertCanCompile(expression); - assertEquals("b", expression.getValue(strings)); + assertThat(expression.getValue(strings)).isEqualTo("b"); tc.field = "foo"; expression = parser.parseExpression("seven(field)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("foo", tc.s); + assertThat(tc.s).isEqualTo("foo"); assertCanCompile(expression); tc.reset(); tc.field="bar"; @@ -4020,7 +4021,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parser.parseExpression("seven(obj)"); assertCantCompile(expression); expression.getValue(tc); - assertEquals("foo", tc.s); + assertThat(tc.s).isEqualTo("foo"); assertCanCompile(expression); tc.reset(); tc.obj=new Integer(42); @@ -4031,7 +4032,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { // method with changing target expression = parser.parseExpression("#root.charAt(0)"); - assertEquals('a', expression.getValue("abc")); + assertThat(expression.getValue("abc")).isEqualTo('a'); assertCanCompile(expression); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> expression.getValue(new Integer(42))) @@ -4044,8 +4045,8 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { int resultI = expression.getValue(new TestClass1(), Integer.TYPE); assertCanCompile(expression); int resultC = expression.getValue(new TestClass1(), Integer.TYPE); - assertEquals(42, resultI); - assertEquals(42, resultC); + assertThat(resultI).isEqualTo(42); + assertThat(resultC).isEqualTo(42); } @Test @@ -4054,8 +4055,8 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { String resultI = expression.getValue(new TestClass1(), String.class); assertCanCompile(expression); String resultC = expression.getValue(new TestClass1(), String.class); - assertEquals("bc", resultI); - assertEquals("bc", resultC); + assertThat(resultI).isEqualTo("bc"); + assertThat(resultC).isEqualTo("bc"); } @Test @@ -4064,18 +4065,18 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { String resultI = expression.getValue(42, String.class); assertCanCompile(expression); String resultC = expression.getValue(42, String.class); - assertEquals("42", resultI); - assertEquals("42", resultC); + assertThat(resultI).isEqualTo("42"); + assertThat(resultC).isEqualTo("42"); } @Test public void methodReference_simpleInstanceMethodNoArgReturnPrimitive() throws Exception { expression = parser.parseExpression("intValue()"); int resultI = expression.getValue(new Integer(42), Integer.TYPE); - assertEquals(42, resultI); + assertThat(resultI).isEqualTo(42); assertCanCompile(expression); int resultC = expression.getValue(new Integer(42), Integer.TYPE); - assertEquals(42, resultC); + assertThat(resultC).isEqualTo(42); } @Test @@ -4084,55 +4085,55 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { int resultI = expression.getValue("abc", Integer.TYPE); assertCanCompile(expression); int resultC = expression.getValue("abc", Integer.TYPE); - assertEquals(1, resultI); - assertEquals(1, resultC); + assertThat(resultI).isEqualTo(1); + assertThat(resultC).isEqualTo(1); } @Test public void methodReference_simpleInstanceMethodOneArgReturnPrimitive2() throws Exception { expression = parser.parseExpression("charAt(2)"); char resultI = expression.getValue("abc", Character.TYPE); - assertEquals('c', resultI); + assertThat(resultI).isEqualTo('c'); assertCanCompile(expression); char resultC = expression.getValue("abc", Character.TYPE); - assertEquals('c', resultC); + assertThat(resultC).isEqualTo('c'); } @Test public void compoundExpression() throws Exception { Payload payload = new Payload(); expression = parser.parseExpression("DR[0]"); - assertEquals("instanceof Two", expression.getValue(payload).toString()); + assertThat(expression.getValue(payload).toString()).isEqualTo("instanceof Two"); assertCanCompile(expression); - assertEquals("instanceof Two", expression.getValue(payload).toString()); + assertThat(expression.getValue(payload).toString()).isEqualTo("instanceof Two"); ast = getAst(); - assertEquals("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Two", ast.getExitDescriptor()); + assertThat(ast.getExitDescriptor()).isEqualTo("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Two"); expression = parser.parseExpression("holder.three"); - assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Three", expression.getValue(payload).getClass().getName()); + assertThat(expression.getValue(payload).getClass().getName()).isEqualTo("org.springframework.expression.spel.SpelCompilationCoverageTests$Three"); assertCanCompile(expression); - assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Three", expression.getValue(payload).getClass().getName()); + assertThat(expression.getValue(payload).getClass().getName()).isEqualTo("org.springframework.expression.spel.SpelCompilationCoverageTests$Three"); ast = getAst(); - assertEquals("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Three", ast.getExitDescriptor()); + assertThat(ast.getExitDescriptor()).isEqualTo("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Three"); expression = parser.parseExpression("DR[0]"); - assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Two", expression.getValue(payload).getClass().getName()); + assertThat(expression.getValue(payload).getClass().getName()).isEqualTo("org.springframework.expression.spel.SpelCompilationCoverageTests$Two"); assertCanCompile(expression); - assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Two", expression.getValue(payload).getClass().getName()); - assertEquals("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Two", getAst().getExitDescriptor()); + assertThat(expression.getValue(payload).getClass().getName()).isEqualTo("org.springframework.expression.spel.SpelCompilationCoverageTests$Two"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Two"); expression = parser.parseExpression("DR[0].three"); - assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Three", expression.getValue(payload).getClass().getName()); + assertThat(expression.getValue(payload).getClass().getName()).isEqualTo("org.springframework.expression.spel.SpelCompilationCoverageTests$Three"); assertCanCompile(expression); - assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Three", expression.getValue(payload).getClass().getName()); + assertThat(expression.getValue(payload).getClass().getName()).isEqualTo("org.springframework.expression.spel.SpelCompilationCoverageTests$Three"); ast = getAst(); - assertEquals("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Three", ast.getExitDescriptor()); + assertThat(ast.getExitDescriptor()).isEqualTo("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Three"); expression = parser.parseExpression("DR[0].three.four"); - assertEquals(0.04d, expression.getValue(payload)); + assertThat(expression.getValue(payload)).isEqualTo(0.04d); assertCanCompile(expression); - assertEquals(0.04d, expression.getValue(payload)); - assertEquals("D", getAst().getExitDescriptor()); + assertThat(expression.getValue(payload)).isEqualTo(0.04d); + assertThat(getAst().getExitDescriptor()).isEqualTo("D"); } @Test @@ -4141,11 +4142,11 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { m.put("andy","778"); expression = parse("['andy']==null?1:2"); - assertEquals(2, expression.getValue(m)); + assertThat(expression.getValue(m)).isEqualTo(2); assertCanCompile(expression); - assertEquals(2, expression.getValue(m)); + assertThat(expression.getValue(m)).isEqualTo(2); m.remove("andy"); - assertEquals(1, expression.getValue(m)); + assertThat(expression.getValue(m)).isEqualTo(1); } @Test @@ -4155,30 +4156,30 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { // non static field expression = parser.parseExpression("orange"); assertCantCompile(expression); - assertEquals("value1", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("value1"); assertCanCompile(expression); - assertEquals("value1", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("value1"); // static field expression = parser.parseExpression("apple"); assertCantCompile(expression); - assertEquals("value2", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("value2"); assertCanCompile(expression); - assertEquals("value2", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("value2"); // non static getter expression = parser.parseExpression("banana"); assertCantCompile(expression); - assertEquals("value3", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("value3"); assertCanCompile(expression); - assertEquals("value3", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("value3"); // static getter expression = parser.parseExpression("plum"); assertCantCompile(expression); - assertEquals("value4", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("value4"); assertCanCompile(expression); - assertEquals("value4", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("value4"); } @Test @@ -4187,9 +4188,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { ctx.setVariable("httpServletRequest", HttpServlet3RequestFactory.getOne()); // Without a fix compilation was inserting a checkcast to a private type expression = parser.parseExpression("#httpServletRequest.servletPath"); - assertEquals("wibble", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("wibble"); assertCanCompile(expression); - assertEquals("wibble", expression.getValue(ctx)); + assertThat(expression.getValue(ctx)).isEqualTo("wibble"); } @SuppressWarnings("unchecked") @@ -4207,65 +4208,65 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { // Access String (reference type) array expression = parser.parseExpression("[0]"); - assertEquals("a", expression.getValue(sss)); + assertThat(expression.getValue(sss)).isEqualTo("a"); assertCanCompile(expression); - assertEquals("a", expression.getValue(sss)); - assertEquals("Ljava/lang/String", getAst().getExitDescriptor()); + assertThat(expression.getValue(sss)).isEqualTo("a"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/String"); expression = parser.parseExpression("[1]"); - assertEquals(8, expression.getValue(ns)); + assertThat(expression.getValue(ns)).isEqualTo(8); assertCanCompile(expression); - assertEquals(8, expression.getValue(ns)); - assertEquals("Ljava/lang/Number", getAst().getExitDescriptor()); + assertThat(expression.getValue(ns)).isEqualTo(8); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Number"); // Access int array expression = parser.parseExpression("[2]"); - assertEquals(10, expression.getValue(is)); + assertThat(expression.getValue(is)).isEqualTo(10); assertCanCompile(expression); - assertEquals(10, expression.getValue(is)); - assertEquals("I", getAst().getExitDescriptor()); + assertThat(expression.getValue(is)).isEqualTo(10); + assertThat(getAst().getExitDescriptor()).isEqualTo("I"); // Access double array expression = parser.parseExpression("[1]"); - assertEquals(4.0d, expression.getValue(ds)); + assertThat(expression.getValue(ds)).isEqualTo(4.0d); assertCanCompile(expression); - assertEquals(4.0d, expression.getValue(ds)); - assertEquals("D", getAst().getExitDescriptor()); + assertThat(expression.getValue(ds)).isEqualTo(4.0d); + assertThat(getAst().getExitDescriptor()).isEqualTo("D"); // Access long array expression = parser.parseExpression("[0]"); - assertEquals(2L, expression.getValue(ls)); + assertThat(expression.getValue(ls)).isEqualTo(2L); assertCanCompile(expression); - assertEquals(2L, expression.getValue(ls)); - assertEquals("J", getAst().getExitDescriptor()); + assertThat(expression.getValue(ls)).isEqualTo(2L); + assertThat(getAst().getExitDescriptor()).isEqualTo("J"); // Access short array expression = parser.parseExpression("[2]"); - assertEquals((short)55, expression.getValue(ss)); + assertThat(expression.getValue(ss)).isEqualTo((short)55); assertCanCompile(expression); - assertEquals((short)55, expression.getValue(ss)); - assertEquals("S", getAst().getExitDescriptor()); + assertThat(expression.getValue(ss)).isEqualTo((short)55); + assertThat(getAst().getExitDescriptor()).isEqualTo("S"); // Access float array expression = parser.parseExpression("[0]"); - assertEquals(6.0f, expression.getValue(fs)); + assertThat(expression.getValue(fs)).isEqualTo(6.0f); assertCanCompile(expression); - assertEquals(6.0f, expression.getValue(fs)); - assertEquals("F", getAst().getExitDescriptor()); + assertThat(expression.getValue(fs)).isEqualTo(6.0f); + assertThat(getAst().getExitDescriptor()).isEqualTo("F"); // Access byte array expression = parser.parseExpression("[2]"); - assertEquals((byte)4, expression.getValue(bs)); + assertThat(expression.getValue(bs)).isEqualTo((byte)4); assertCanCompile(expression); - assertEquals((byte)4, expression.getValue(bs)); - assertEquals("B", getAst().getExitDescriptor()); + assertThat(expression.getValue(bs)).isEqualTo((byte)4); + assertThat(getAst().getExitDescriptor()).isEqualTo("B"); // Access char array expression = parser.parseExpression("[1]"); - assertEquals('b', expression.getValue(cs)); + assertThat(expression.getValue(cs)).isEqualTo('b'); assertCanCompile(expression); - assertEquals('b', expression.getValue(cs)); - assertEquals("C", getAst().getExitDescriptor()); + assertThat(expression.getValue(cs)).isEqualTo('b'); + assertThat(getAst().getExitDescriptor()).isEqualTo("C"); // Collections List strings = new ArrayList<>(); @@ -4273,20 +4274,20 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { strings.add("bbb"); strings.add("ccc"); expression = parser.parseExpression("[1]"); - assertEquals("bbb", expression.getValue(strings)); + assertThat(expression.getValue(strings)).isEqualTo("bbb"); assertCanCompile(expression); - assertEquals("bbb", expression.getValue(strings)); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(expression.getValue(strings)).isEqualTo("bbb"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); List ints = new ArrayList<>(); ints.add(123); ints.add(456); ints.add(789); expression = parser.parseExpression("[2]"); - assertEquals(789, expression.getValue(ints)); + assertThat(expression.getValue(ints)).isEqualTo(789); assertCanCompile(expression); - assertEquals(789, expression.getValue(ints)); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(expression.getValue(ints)).isEqualTo(789); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // Maps Map map1 = new HashMap<>(); @@ -4294,31 +4295,31 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { map1.put("bbb", 222); map1.put("ccc", 333); expression = parser.parseExpression("['aaa']"); - assertEquals(111, expression.getValue(map1)); + assertThat(expression.getValue(map1)).isEqualTo(111); assertCanCompile(expression); - assertEquals(111, expression.getValue(map1)); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(expression.getValue(map1)).isEqualTo(111); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // Object TestClass6 tc = new TestClass6(); expression = parser.parseExpression("['orange']"); - assertEquals("value1", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("value1"); assertCanCompile(expression); - assertEquals("value1", expression.getValue(tc)); - assertEquals("Ljava/lang/String", getAst().getExitDescriptor()); + assertThat(expression.getValue(tc)).isEqualTo("value1"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/String"); expression = parser.parseExpression("['peach']"); - assertEquals(34L, expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo(34L); assertCanCompile(expression); - assertEquals(34L, expression.getValue(tc)); - assertEquals("J", getAst().getExitDescriptor()); + assertThat(expression.getValue(tc)).isEqualTo(34L); + assertThat(getAst().getExitDescriptor()).isEqualTo("J"); // getter expression = parser.parseExpression("['banana']"); - assertEquals("value3", expression.getValue(tc)); + assertThat(expression.getValue(tc)).isEqualTo("value3"); assertCanCompile(expression); - assertEquals("value3", expression.getValue(tc)); - assertEquals("Ljava/lang/String", getAst().getExitDescriptor()); + assertThat(expression.getValue(tc)).isEqualTo("value3"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/String"); // list of arrays @@ -4326,31 +4327,31 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { listOfStringArrays.add(new String[] {"a","b","c"}); listOfStringArrays.add(new String[] {"d","e","f"}); expression = parser.parseExpression("[1]"); - assertEquals("d e f", stringify(expression.getValue(listOfStringArrays))); + assertThat(stringify(expression.getValue(listOfStringArrays))).isEqualTo("d e f"); assertCanCompile(expression); - assertEquals("d e f", stringify(expression.getValue(listOfStringArrays))); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(listOfStringArrays))).isEqualTo("d e f"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); expression = parser.parseExpression("[1][0]"); - assertEquals("d", stringify(expression.getValue(listOfStringArrays))); + assertThat(stringify(expression.getValue(listOfStringArrays))).isEqualTo("d"); assertCanCompile(expression); - assertEquals("d", stringify(expression.getValue(listOfStringArrays))); - assertEquals("Ljava/lang/String", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(listOfStringArrays))).isEqualTo("d"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/String"); List listOfIntegerArrays = new ArrayList<>(); listOfIntegerArrays.add(new Integer[] {1,2,3}); listOfIntegerArrays.add(new Integer[] {4,5,6}); expression = parser.parseExpression("[0]"); - assertEquals("1 2 3", stringify(expression.getValue(listOfIntegerArrays))); + assertThat(stringify(expression.getValue(listOfIntegerArrays))).isEqualTo("1 2 3"); assertCanCompile(expression); - assertEquals("1 2 3", stringify(expression.getValue(listOfIntegerArrays))); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(listOfIntegerArrays))).isEqualTo("1 2 3"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); expression = parser.parseExpression("[0][1]"); - assertEquals(2, expression.getValue(listOfIntegerArrays)); + assertThat(expression.getValue(listOfIntegerArrays)).isEqualTo(2); assertCanCompile(expression); - assertEquals(2, expression.getValue(listOfIntegerArrays)); - assertEquals("Ljava/lang/Integer", getAst().getExitDescriptor()); + assertThat(expression.getValue(listOfIntegerArrays)).isEqualTo(2); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Integer"); // array of lists List[] stringArrayOfLists = new ArrayList[2]; @@ -4363,44 +4364,44 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { stringArrayOfLists[1].add("e"); stringArrayOfLists[1].add("f"); expression = parser.parseExpression("[1]"); - assertEquals("d e f", stringify(expression.getValue(stringArrayOfLists))); + assertThat(stringify(expression.getValue(stringArrayOfLists))).isEqualTo("d e f"); assertCanCompile(expression); - assertEquals("d e f", stringify(expression.getValue(stringArrayOfLists))); - assertEquals("Ljava/util/ArrayList", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(stringArrayOfLists))).isEqualTo("d e f"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/util/ArrayList"); expression = parser.parseExpression("[1][2]"); - assertEquals("f", stringify(expression.getValue(stringArrayOfLists))); + assertThat(stringify(expression.getValue(stringArrayOfLists))).isEqualTo("f"); assertCanCompile(expression); - assertEquals("f", stringify(expression.getValue(stringArrayOfLists))); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(stringArrayOfLists))).isEqualTo("f"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // array of arrays String[][] referenceTypeArrayOfArrays = new String[][] {new String[] {"a","b","c"},new String[] {"d","e","f"}}; expression = parser.parseExpression("[1]"); - assertEquals("d e f", stringify(expression.getValue(referenceTypeArrayOfArrays))); + assertThat(stringify(expression.getValue(referenceTypeArrayOfArrays))).isEqualTo("d e f"); assertCanCompile(expression); - assertEquals("[Ljava/lang/String", getAst().getExitDescriptor()); - assertEquals("d e f", stringify(expression.getValue(referenceTypeArrayOfArrays))); - assertEquals("[Ljava/lang/String", getAst().getExitDescriptor()); + assertThat(getAst().getExitDescriptor()).isEqualTo("[Ljava/lang/String"); + assertThat(stringify(expression.getValue(referenceTypeArrayOfArrays))).isEqualTo("d e f"); + assertThat(getAst().getExitDescriptor()).isEqualTo("[Ljava/lang/String"); expression = parser.parseExpression("[1][2]"); - assertEquals("f", stringify(expression.getValue(referenceTypeArrayOfArrays))); + assertThat(stringify(expression.getValue(referenceTypeArrayOfArrays))).isEqualTo("f"); assertCanCompile(expression); - assertEquals("f", stringify(expression.getValue(referenceTypeArrayOfArrays))); - assertEquals("Ljava/lang/String", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(referenceTypeArrayOfArrays))).isEqualTo("f"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/String"); int[][] primitiveTypeArrayOfArrays = new int[][] {new int[] {1,2,3},new int[] {4,5,6}}; expression = parser.parseExpression("[1]"); - assertEquals("4 5 6", stringify(expression.getValue(primitiveTypeArrayOfArrays))); + assertThat(stringify(expression.getValue(primitiveTypeArrayOfArrays))).isEqualTo("4 5 6"); assertCanCompile(expression); - assertEquals("4 5 6", stringify(expression.getValue(primitiveTypeArrayOfArrays))); - assertEquals("[I", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(primitiveTypeArrayOfArrays))).isEqualTo("4 5 6"); + assertThat(getAst().getExitDescriptor()).isEqualTo("[I"); expression = parser.parseExpression("[1][2]"); - assertEquals("6", stringify(expression.getValue(primitiveTypeArrayOfArrays))); + assertThat(stringify(expression.getValue(primitiveTypeArrayOfArrays))).isEqualTo("6"); assertCanCompile(expression); - assertEquals("6", stringify(expression.getValue(primitiveTypeArrayOfArrays))); - assertEquals("I", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(primitiveTypeArrayOfArrays))).isEqualTo("6"); + assertThat(getAst().getExitDescriptor()).isEqualTo("I"); // list of lists of reference types List> listOfListOfStrings = new ArrayList<>(); @@ -4416,17 +4417,17 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { listOfListOfStrings.add(list); expression = parser.parseExpression("[1]"); - assertEquals("d e f", stringify(expression.getValue(listOfListOfStrings))); + assertThat(stringify(expression.getValue(listOfListOfStrings))).isEqualTo("d e f"); assertCanCompile(expression); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); - assertEquals("d e f", stringify(expression.getValue(listOfListOfStrings))); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); + assertThat(stringify(expression.getValue(listOfListOfStrings))).isEqualTo("d e f"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); expression = parser.parseExpression("[1][2]"); - assertEquals("f", stringify(expression.getValue(listOfListOfStrings))); + assertThat(stringify(expression.getValue(listOfListOfStrings))).isEqualTo("f"); assertCanCompile(expression); - assertEquals("f", stringify(expression.getValue(listOfListOfStrings))); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(listOfListOfStrings))).isEqualTo("f"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // Map of lists Map> mapToLists = new HashMap<>(); @@ -4436,17 +4437,17 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { list.add("c"); mapToLists.put("foo", list); expression = parser.parseExpression("['foo']"); - assertEquals("a b c", stringify(expression.getValue(mapToLists))); + assertThat(stringify(expression.getValue(mapToLists))).isEqualTo("a b c"); assertCanCompile(expression); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); - assertEquals("a b c", stringify(expression.getValue(mapToLists))); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); + assertThat(stringify(expression.getValue(mapToLists))).isEqualTo("a b c"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); expression = parser.parseExpression("['foo'][2]"); - assertEquals("c", stringify(expression.getValue(mapToLists))); + assertThat(stringify(expression.getValue(mapToLists))).isEqualTo("c"); assertCanCompile(expression); - assertEquals("c", stringify(expression.getValue(mapToLists))); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(mapToLists))).isEqualTo("c"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // Map to array Map mapToIntArray = new HashMap<>(); @@ -4454,65 +4455,65 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { ctx.addPropertyAccessor(new CompilableMapAccessor()); mapToIntArray.put("foo",new int[] {1,2,3}); expression = parser.parseExpression("['foo']"); - assertEquals("1 2 3", stringify(expression.getValue(mapToIntArray))); + assertThat(stringify(expression.getValue(mapToIntArray))).isEqualTo("1 2 3"); assertCanCompile(expression); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); - assertEquals("1 2 3", stringify(expression.getValue(mapToIntArray))); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); + assertThat(stringify(expression.getValue(mapToIntArray))).isEqualTo("1 2 3"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); expression = parser.parseExpression("['foo'][1]"); - assertEquals(2, expression.getValue(mapToIntArray)); + assertThat(expression.getValue(mapToIntArray)).isEqualTo(2); assertCanCompile(expression); - assertEquals(2, expression.getValue(mapToIntArray)); + assertThat(expression.getValue(mapToIntArray)).isEqualTo(2); expression = parser.parseExpression("foo"); - assertEquals("1 2 3", stringify(expression.getValue(ctx, mapToIntArray))); + assertThat(stringify(expression.getValue(ctx, mapToIntArray))).isEqualTo("1 2 3"); assertCanCompile(expression); - assertEquals("1 2 3", stringify(expression.getValue(ctx, mapToIntArray))); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(ctx, mapToIntArray))).isEqualTo("1 2 3"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); expression = parser.parseExpression("foo[1]"); - assertEquals(2, expression.getValue(ctx, mapToIntArray)); + assertThat(expression.getValue(ctx, mapToIntArray)).isEqualTo(2); assertCanCompile(expression); - assertEquals(2, expression.getValue(ctx, mapToIntArray)); + assertThat(expression.getValue(ctx, mapToIntArray)).isEqualTo(2); expression = parser.parseExpression("['foo'][2]"); - assertEquals("3", stringify(expression.getValue(ctx, mapToIntArray))); + assertThat(stringify(expression.getValue(ctx, mapToIntArray))).isEqualTo("3"); assertCanCompile(expression); - assertEquals("3", stringify(expression.getValue(ctx, mapToIntArray))); - assertEquals("I", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(ctx, mapToIntArray))).isEqualTo("3"); + assertThat(getAst().getExitDescriptor()).isEqualTo("I"); // Map array Map[] mapArray = new Map[1]; mapArray[0] = new HashMap<>(); mapArray[0].put("key", "value1"); expression = parser.parseExpression("[0]"); - assertEquals("{key=value1}", stringify(expression.getValue(mapArray))); + assertThat(stringify(expression.getValue(mapArray))).isEqualTo("{key=value1}"); assertCanCompile(expression); - assertEquals("Ljava/util/Map", getAst().getExitDescriptor()); - assertEquals("{key=value1}", stringify(expression.getValue(mapArray))); - assertEquals("Ljava/util/Map", getAst().getExitDescriptor()); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/util/Map"); + assertThat(stringify(expression.getValue(mapArray))).isEqualTo("{key=value1}"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/util/Map"); expression = parser.parseExpression("[0]['key']"); - assertEquals("value1", stringify(expression.getValue(mapArray))); + assertThat(stringify(expression.getValue(mapArray))).isEqualTo("value1"); assertCanCompile(expression); - assertEquals("value1", stringify(expression.getValue(mapArray))); - assertEquals("Ljava/lang/Object", getAst().getExitDescriptor()); + assertThat(stringify(expression.getValue(mapArray))).isEqualTo("value1"); + assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); } @Test public void plusNeedingCheckcast_SPR12426() { expression = parser.parseExpression("object + ' world'"); Object v = expression.getValue(new FooObject()); - assertEquals("hello world", v); + assertThat(v).isEqualTo("hello world"); assertCanCompile(expression); - assertEquals("hello world", v); + assertThat(v).isEqualTo("hello world"); expression = parser.parseExpression("object + ' world'"); v = expression.getValue(new FooString()); - assertEquals("hello world", v); + assertThat(v).isEqualTo("hello world"); assertCanCompile(expression); - assertEquals("hello world", v); + assertThat(v).isEqualTo("hello world"); } @Test @@ -4521,8 +4522,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = parser.parseExpression("DR[0].three"); Object v = expression.getValue(payload); - assertEquals("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Three", - getAst().getExitDescriptor()); + assertThat(getAst().getExitDescriptor()).isEqualTo("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Three"); Expression expression = parser.parseExpression("DR[0].three.four lt 0.1d?#root:null"); v = expression.getValue(payload); @@ -4532,16 +4532,16 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { OpLT oplt = (OpLT) ternary.getChild(0); CompoundExpression cExpr = (CompoundExpression) oplt.getLeftOperand(); String cExprExitDescriptor = cExpr.getExitDescriptor(); - assertEquals("D", cExprExitDescriptor); - assertEquals("Z", oplt.getExitDescriptor()); + assertThat(cExprExitDescriptor).isEqualTo("D"); + assertThat(oplt.getExitDescriptor()).isEqualTo("Z"); assertCanCompile(expression); Object vc = expression.getValue(payload); - assertEquals(payload, v); - assertEquals(payload,vc); + assertThat(v).isEqualTo(payload); + assertThat(vc).isEqualTo(payload); payload.DR[0].three.four = 0.13d; vc = expression.getValue(payload); - assertNull(vc); + assertThat(vc).isNull(); } @Test @@ -4551,7 +4551,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { ctx.addPropertyAccessor(new MyAccessor()); expression = parser.parseExpression("payload2.var1"); Object v = expression.getValue(ctx,holder); - assertEquals("abc", v); + assertThat(v).isEqualTo("abc"); // // time it interpreted // long stime = System.currentTimeMillis(); @@ -4562,7 +4562,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertCanCompile(expression); v = expression.getValue(ctx,holder); - assertEquals("abc", v); + assertThat(v).isEqualTo("abc"); // // time it compiled // stime = System.currentTimeMillis(); @@ -4575,197 +4575,197 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { @Test public void compilerWithGenerics_12040() { expression = parser.parseExpression("payload!=2"); - assertTrue(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)).isTrue(); assertCanCompile(expression); - assertFalse(expression.getValue(new GenericMessageTestHelper<>(2), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(2), Boolean.class)).isFalse(); expression = parser.parseExpression("2!=payload"); - assertTrue(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)).isTrue(); assertCanCompile(expression); - assertFalse(expression.getValue(new GenericMessageTestHelper<>(2), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(2), Boolean.class)).isFalse(); expression = parser.parseExpression("payload!=6L"); - assertTrue(expression.getValue(new GenericMessageTestHelper<>(4L), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4L), Boolean.class)).isTrue(); assertCanCompile(expression); - assertFalse(expression.getValue(new GenericMessageTestHelper<>(6L), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(6L), Boolean.class)).isFalse(); expression = parser.parseExpression("payload==2"); - assertFalse(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)).isFalse(); assertCanCompile(expression); - assertTrue(expression.getValue(new GenericMessageTestHelper<>(2), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(2), Boolean.class)).isTrue(); expression = parser.parseExpression("2==payload"); - assertFalse(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)).isFalse(); assertCanCompile(expression); - assertTrue(expression.getValue(new GenericMessageTestHelper<>(2), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(2), Boolean.class)).isTrue(); expression = parser.parseExpression("payload==6L"); - assertFalse(expression.getValue(new GenericMessageTestHelper<>(4L), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4L), Boolean.class)).isFalse(); assertCanCompile(expression); - assertTrue(expression.getValue(new GenericMessageTestHelper<>(6L), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(6L), Boolean.class)).isTrue(); expression = parser.parseExpression("2==payload"); - assertFalse(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)).isFalse(); assertCanCompile(expression); - assertTrue(expression.getValue(new GenericMessageTestHelper<>(2), Boolean.class)); + assertThat(expression.getValue(new GenericMessageTestHelper<>(2), Boolean.class)).isTrue(); expression = parser.parseExpression("payload/2"); - assertEquals(2, expression.getValue(new GenericMessageTestHelper<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4))).isEqualTo(2); assertCanCompile(expression); - assertEquals(3, expression.getValue(new GenericMessageTestHelper<>(6))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(6))).isEqualTo(3); expression = parser.parseExpression("100/payload"); - assertEquals(25, expression.getValue(new GenericMessageTestHelper<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4))).isEqualTo(25); assertCanCompile(expression); - assertEquals(10, expression.getValue(new GenericMessageTestHelper<>(10))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(10))).isEqualTo(10); expression = parser.parseExpression("payload+2"); - assertEquals(6, expression.getValue(new GenericMessageTestHelper<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4))).isEqualTo(6); assertCanCompile(expression); - assertEquals(8, expression.getValue(new GenericMessageTestHelper<>(6))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(6))).isEqualTo(8); expression = parser.parseExpression("100+payload"); - assertEquals(104, expression.getValue(new GenericMessageTestHelper<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4))).isEqualTo(104); assertCanCompile(expression); - assertEquals(110, expression.getValue(new GenericMessageTestHelper<>(10))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(10))).isEqualTo(110); expression = parser.parseExpression("payload-2"); - assertEquals(2, expression.getValue(new GenericMessageTestHelper<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4))).isEqualTo(2); assertCanCompile(expression); - assertEquals(4, expression.getValue(new GenericMessageTestHelper<>(6))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(6))).isEqualTo(4); expression = parser.parseExpression("100-payload"); - assertEquals(96, expression.getValue(new GenericMessageTestHelper<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4))).isEqualTo(96); assertCanCompile(expression); - assertEquals(90, expression.getValue(new GenericMessageTestHelper<>(10))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(10))).isEqualTo(90); expression = parser.parseExpression("payload*2"); - assertEquals(8, expression.getValue(new GenericMessageTestHelper<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4))).isEqualTo(8); assertCanCompile(expression); - assertEquals(12, expression.getValue(new GenericMessageTestHelper<>(6))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(6))).isEqualTo(12); expression = parser.parseExpression("100*payload"); - assertEquals(400, expression.getValue(new GenericMessageTestHelper<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4))).isEqualTo(400); assertCanCompile(expression); - assertEquals(1000, expression.getValue(new GenericMessageTestHelper<>(10))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(10))).isEqualTo(1000); expression = parser.parseExpression("payload/2L"); - assertEquals(2L, expression.getValue(new GenericMessageTestHelper<>(4L))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4L))).isEqualTo(2L); assertCanCompile(expression); - assertEquals(3L, expression.getValue(new GenericMessageTestHelper<>(6L))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(6L))).isEqualTo(3L); expression = parser.parseExpression("100L/payload"); - assertEquals(25L, expression.getValue(new GenericMessageTestHelper<>(4L))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4L))).isEqualTo(25L); assertCanCompile(expression); - assertEquals(10L, expression.getValue(new GenericMessageTestHelper<>(10L))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(10L))).isEqualTo(10L); expression = parser.parseExpression("payload/2f"); - assertEquals(2f, expression.getValue(new GenericMessageTestHelper<>(4f))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4f))).isEqualTo(2f); assertCanCompile(expression); - assertEquals(3f, expression.getValue(new GenericMessageTestHelper<>(6f))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(6f))).isEqualTo(3f); expression = parser.parseExpression("100f/payload"); - assertEquals(25f, expression.getValue(new GenericMessageTestHelper<>(4f))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4f))).isEqualTo(25f); assertCanCompile(expression); - assertEquals(10f, expression.getValue(new GenericMessageTestHelper<>(10f))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(10f))).isEqualTo(10f); expression = parser.parseExpression("payload/2d"); - assertEquals(2d, expression.getValue(new GenericMessageTestHelper<>(4d))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4d))).isEqualTo(2d); assertCanCompile(expression); - assertEquals(3d, expression.getValue(new GenericMessageTestHelper<>(6d))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(6d))).isEqualTo(3d); expression = parser.parseExpression("100d/payload"); - assertEquals(25d, expression.getValue(new GenericMessageTestHelper<>(4d))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(4d))).isEqualTo(25d); assertCanCompile(expression); - assertEquals(10d, expression.getValue(new GenericMessageTestHelper<>(10d))); + assertThat(expression.getValue(new GenericMessageTestHelper<>(10d))).isEqualTo(10d); } // The new helper class here uses an upper bound on the generic @Test public void compilerWithGenerics_12040_2() { expression = parser.parseExpression("payload/2"); - assertEquals(2, expression.getValue(new GenericMessageTestHelper2<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(2); assertCanCompile(expression); - assertEquals(3, expression.getValue(new GenericMessageTestHelper2<>(6))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(6))).isEqualTo(3); expression = parser.parseExpression("9/payload"); - assertEquals(1, expression.getValue(new GenericMessageTestHelper2<>(9))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(9))).isEqualTo(1); assertCanCompile(expression); - assertEquals(3, expression.getValue(new GenericMessageTestHelper2<>(3))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(3))).isEqualTo(3); expression = parser.parseExpression("payload+2"); - assertEquals(6, expression.getValue(new GenericMessageTestHelper2<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(6); assertCanCompile(expression); - assertEquals(8, expression.getValue(new GenericMessageTestHelper2<>(6))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(6))).isEqualTo(8); expression = parser.parseExpression("100+payload"); - assertEquals(104, expression.getValue(new GenericMessageTestHelper2<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(104); assertCanCompile(expression); - assertEquals(110, expression.getValue(new GenericMessageTestHelper2<>(10))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(10))).isEqualTo(110); expression = parser.parseExpression("payload-2"); - assertEquals(2, expression.getValue(new GenericMessageTestHelper2<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(2); assertCanCompile(expression); - assertEquals(4, expression.getValue(new GenericMessageTestHelper2<>(6))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(6))).isEqualTo(4); expression = parser.parseExpression("100-payload"); - assertEquals(96, expression.getValue(new GenericMessageTestHelper2<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(96); assertCanCompile(expression); - assertEquals(90, expression.getValue(new GenericMessageTestHelper2<>(10))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(10))).isEqualTo(90); expression = parser.parseExpression("payload*2"); - assertEquals(8, expression.getValue(new GenericMessageTestHelper2<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(8); assertCanCompile(expression); - assertEquals(12, expression.getValue(new GenericMessageTestHelper2<>(6))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(6))).isEqualTo(12); expression = parser.parseExpression("100*payload"); - assertEquals(400, expression.getValue(new GenericMessageTestHelper2<>(4))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(400); assertCanCompile(expression); - assertEquals(1000, expression.getValue(new GenericMessageTestHelper2<>(10))); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(10))).isEqualTo(1000); } // The other numeric operators @Test public void compilerWithGenerics_12040_3() { expression = parser.parseExpression("payload >= 2"); - assertTrue(expression.getValue(new GenericMessageTestHelper2<>(4), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(4), Boolean.TYPE)).isTrue(); assertCanCompile(expression); - assertFalse(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)).isFalse(); expression = parser.parseExpression("2 >= payload"); - assertFalse(expression.getValue(new GenericMessageTestHelper2<>(5), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(5), Boolean.TYPE)).isFalse(); assertCanCompile(expression); - assertTrue(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)).isTrue(); expression = parser.parseExpression("payload > 2"); - assertTrue(expression.getValue(new GenericMessageTestHelper2<>(4), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(4), Boolean.TYPE)).isTrue(); assertCanCompile(expression); - assertFalse(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)).isFalse(); expression = parser.parseExpression("2 > payload"); - assertFalse(expression.getValue(new GenericMessageTestHelper2<>(5), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(5), Boolean.TYPE)).isFalse(); assertCanCompile(expression); - assertTrue(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)).isTrue(); expression = parser.parseExpression("payload <=2"); - assertTrue(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)).isTrue(); assertCanCompile(expression); - assertFalse(expression.getValue(new GenericMessageTestHelper2<>(6), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(6), Boolean.TYPE)).isFalse(); expression = parser.parseExpression("2 <= payload"); - assertFalse(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)).isFalse(); assertCanCompile(expression); - assertTrue(expression.getValue(new GenericMessageTestHelper2<>(6), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(6), Boolean.TYPE)).isTrue(); expression = parser.parseExpression("payload < 2"); - assertTrue(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)).isTrue(); assertCanCompile(expression); - assertFalse(expression.getValue(new GenericMessageTestHelper2<>(6), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(6), Boolean.TYPE)).isFalse(); expression = parser.parseExpression("2 < payload"); - assertFalse(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(1), Boolean.TYPE)).isFalse(); assertCanCompile(expression); - assertTrue(expression.getValue(new GenericMessageTestHelper2<>(6), Boolean.TYPE)); + assertThat(expression.getValue(new GenericMessageTestHelper2<>(6), Boolean.TYPE)).isTrue(); } @Test @@ -4775,26 +4775,26 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { SpelExpressionParser sep = new SpelExpressionParser(spc); expression=sep.parseExpression("headers[command]"); MyMessage root = new MyMessage(); - assertEquals("wibble", expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo("wibble"); // This next call was failing because the isCompilable check in Indexer // did not check on the key being compilable (and also generateCode in the // Indexer was missing the optimization that it didn't need necessarily // need to call generateCode for that accessor) - assertEquals("wibble", expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo("wibble"); assertCanCompile(expression); // What about a map key that is an expression - ensure the getKey() is evaluated in the right scope expression=sep.parseExpression("headers[getKey()]"); - assertEquals("wobble", expression.getValue(root)); - assertEquals("wobble", expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo("wobble"); + assertThat(expression.getValue(root)).isEqualTo("wobble"); expression=sep.parseExpression("list[getKey2()]"); - assertEquals("wobble", expression.getValue(root)); - assertEquals("wobble", expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo("wobble"); + assertThat(expression.getValue(root)).isEqualTo("wobble"); expression = sep.parseExpression("ia[getKey2()]"); - assertEquals(3, expression.getValue(root)); - assertEquals(3, expression.getValue(root)); + assertThat(expression.getValue(root)).isEqualTo(3); + assertThat(expression.getValue(root)).isEqualTo(3); } @Test @@ -4803,81 +4803,81 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { Expression exp; exp = new SpelExpressionParser(configuration).parseExpression("bar()"); - assertEquals("BAR", exp.getValue(new Foo(), String.class)); + assertThat(exp.getValue(new Foo(), String.class)).isEqualTo("BAR"); assertCanCompile(exp); - assertEquals("BAR", exp.getValue(new Foo(), String.class)); + assertThat(exp.getValue(new Foo(), String.class)).isEqualTo("BAR"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("bar('baz')"); - assertEquals("BAZ", exp.getValue(new Foo(), String.class)); + assertThat(exp.getValue(new Foo(), String.class)).isEqualTo("BAZ"); assertCanCompile(exp); - assertEquals("BAZ", exp.getValue(new Foo(), String.class)); + assertThat(exp.getValue(new Foo(), String.class)).isEqualTo("BAZ"); assertIsCompiled(exp); StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("map", Collections.singletonMap("foo", "qux")); exp = new SpelExpressionParser(configuration).parseExpression("bar(#map['foo'])"); - assertEquals("QUX", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertCanCompile(exp); - assertEquals("QUX", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("bar(#map['foo'] ?: 'qux')"); - assertEquals("QUX", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertCanCompile(exp); - assertEquals("QUX", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertIsCompiled(exp); // When the condition is a primitive exp = new SpelExpressionParser(configuration).parseExpression("3?:'foo'"); - assertEquals("3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertCanCompile(exp); - assertEquals("3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertIsCompiled(exp); // When the condition is a double slot primitive exp = new SpelExpressionParser(configuration).parseExpression("3L?:'foo'"); - assertEquals("3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertCanCompile(exp); - assertEquals("3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertIsCompiled(exp); // When the condition is an empty string exp = new SpelExpressionParser(configuration).parseExpression("''?:4L"); - assertEquals("4", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("4"); assertCanCompile(exp); - assertEquals("4", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("4"); assertIsCompiled(exp); // null condition exp = new SpelExpressionParser(configuration).parseExpression("null?:4L"); - assertEquals("4", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("4"); assertCanCompile(exp); - assertEquals("4", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("4"); assertIsCompiled(exp); // variable access returning primitive exp = new SpelExpressionParser(configuration).parseExpression("#x?:'foo'"); context.setVariable("x",50); - assertEquals("50", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("50"); assertCanCompile(exp); - assertEquals("50", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("50"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("#x?:'foo'"); context.setVariable("x",null); - assertEquals("foo", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertCanCompile(exp); - assertEquals("foo", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertIsCompiled(exp); // variable access returning array exp = new SpelExpressionParser(configuration).parseExpression("#x?:'foo'"); context.setVariable("x",new int[]{1,2,3}); - assertEquals("1,2,3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("1,2,3"); assertCanCompile(exp); - assertEquals("1,2,3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("1,2,3"); assertIsCompiled(exp); } @@ -4890,43 +4890,43 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { expression = sep.parseExpression("record.get('abc')?:record.put('abc',expression.someLong?.longValue())"); rh = new RecordHolder(); - assertNull(expression.getValue(rh)); - assertEquals(3L,expression.getValue(rh)); + assertThat(expression.getValue(rh)).isNull(); + assertThat(expression.getValue(rh)).isEqualTo(3L); assertCanCompile(expression); rh = new RecordHolder(); - assertNull(expression.getValue(rh)); - assertEquals(3L,expression.getValue(rh)); + assertThat(expression.getValue(rh)).isNull(); + assertThat(expression.getValue(rh)).isEqualTo(3L); expression = sep.parseExpression("record.get('abc')?:record.put('abc',3L.longValue())"); rh = new RecordHolder(); - assertNull(expression.getValue(rh)); - assertEquals(3L,expression.getValue(rh)); + assertThat(expression.getValue(rh)).isNull(); + assertThat(expression.getValue(rh)).isEqualTo(3L); assertCanCompile(expression); rh = new RecordHolder(); - assertNull(expression.getValue(rh)); - assertEquals(3L,expression.getValue(rh)); + assertThat(expression.getValue(rh)).isNull(); + assertThat(expression.getValue(rh)).isEqualTo(3L); expression = sep.parseExpression("record.get('abc')?:record.put('abc',3L.longValue())"); rh = new RecordHolder(); - assertNull(expression.getValue(rh)); - assertEquals(3L,expression.getValue(rh)); + assertThat(expression.getValue(rh)).isNull(); + assertThat(expression.getValue(rh)).isEqualTo(3L); assertCanCompile(expression); rh = new RecordHolder(); - assertNull(expression.getValue(rh)); - assertEquals(3L,expression.getValue(rh)); + assertThat(expression.getValue(rh)).isNull(); + assertThat(expression.getValue(rh)).isEqualTo(3L); expression = sep.parseExpression("record.get('abc')==null?record.put('abc',expression.someLong?.longValue()):null"); rh = new RecordHolder(); rh.expression.someLong=6L; - assertNull(expression.getValue(rh)); - assertEquals(6L,rh.get("abc")); - assertNull(expression.getValue(rh)); + assertThat(expression.getValue(rh)).isNull(); + assertThat(rh.get("abc")).isEqualTo(6L); + assertThat(expression.getValue(rh)).isNull(); assertCanCompile(expression); rh = new RecordHolder(); rh.expression.someLong=6L; - assertNull(expression.getValue(rh)); - assertEquals(6L,rh.get("abc")); - assertNull(expression.getValue(rh)); + assertThat(expression.getValue(rh)).isNull(); + assertThat(rh.get("abc")).isEqualTo(6L); + assertThat(expression.getValue(rh)).isNull(); } @Test @@ -4982,7 +4982,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { SpelExpression fast = (SpelExpression) parser.parseExpression(expressionText); SpelExpression slow = (SpelExpression) parser.parseExpression(expressionText); fast.getValue(ctx); - assertTrue(fast.compileExpression()); + assertThat(fast.compileExpression()).isTrue(); r.setValue2(null); // try the numbers 0,1,2,null for (int i=0;i<4;i++) { @@ -4990,9 +4990,8 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { boolean slowResult = (Boolean)slow.getValue(ctx); boolean fastResult = (Boolean)fast.getValue(ctx); // System.out.println("Trying "+expressionText+" with value="+r.getValue()+" result is "+slowResult); - assertEquals(" Differing results: expression="+expressionText+ - " value="+r.getValue()+" slow="+slowResult+" fast="+fastResult, - slowResult,fastResult); + assertThat(fastResult).as(" Differing results: expression="+expressionText+ + " value="+r.getValue()+" slow="+slowResult+" fast="+fastResult).isEqualTo(slowResult); } } @@ -5000,7 +4999,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { SpelExpression fast = (SpelExpression) parser.parseExpression(expressionText); SpelExpression slow = (SpelExpression) parser.parseExpression(expressionText); fast.getValue(ctx); - assertTrue(fast.compileExpression()); + assertThat(fast.compileExpression()).isTrue(); Reg r = (Reg)ctx.getRootObject().getValue(); // try the numbers 0,1,2,null for (int i=0;i<4;i++) { @@ -5008,9 +5007,8 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { boolean slowResult = (Boolean)slow.getValue(ctx); boolean fastResult = (Boolean)fast.getValue(ctx); // System.out.println("Trying "+expressionText+" with value="+r.getValue()+" result is "+slowResult); - assertEquals(" Differing results: expression="+expressionText+ - " value="+r.getValue()+" slow="+slowResult+" fast="+fastResult, - slowResult,fastResult); + assertThat(fastResult).as(" Differing results: expression="+expressionText+ + " value="+r.getValue()+" slow="+slowResult+" fast="+fastResult).isEqualTo(slowResult); } } @@ -5022,69 +5020,69 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { context.setVariable("map", Collections.singletonMap("foo", "qux")); exp = new SpelExpressionParser(configuration).parseExpression("bar(#map['foo'] != null ? #map['foo'] : 'qux')"); - assertEquals("QUX", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertCanCompile(exp); - assertEquals("QUX", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("QUX"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("3==3?3:'foo'"); - assertEquals("3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertCanCompile(exp); - assertEquals("3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("3!=3?3:'foo'"); - assertEquals("foo", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertCanCompile(exp); - assertEquals("foo", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertIsCompiled(exp); // When the condition is a double slot primitive exp = new SpelExpressionParser(configuration).parseExpression("3==3?3L:'foo'"); - assertEquals("3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertCanCompile(exp); - assertEquals("3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("3"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("3!=3?3L:'foo'"); - assertEquals("foo", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertCanCompile(exp); - assertEquals("foo", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertIsCompiled(exp); // When the condition is an empty string exp = new SpelExpressionParser(configuration).parseExpression("''==''?'abc':4L"); - assertEquals("abc", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("abc"); assertCanCompile(exp); - assertEquals("abc", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("abc"); assertIsCompiled(exp); // null condition exp = new SpelExpressionParser(configuration).parseExpression("3==3?null:4L"); - assertEquals(null, exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo(null); assertCanCompile(exp); - assertEquals(null, exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo(null); assertIsCompiled(exp); // variable access returning primitive exp = new SpelExpressionParser(configuration).parseExpression("#x==#x?50:'foo'"); context.setVariable("x",50); - assertEquals("50", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("50"); assertCanCompile(exp); - assertEquals("50", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("50"); assertIsCompiled(exp); exp = new SpelExpressionParser(configuration).parseExpression("#x!=#x?50:'foo'"); context.setVariable("x",null); - assertEquals("foo", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertCanCompile(exp); - assertEquals("foo", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("foo"); assertIsCompiled(exp); // variable access returning array exp = new SpelExpressionParser(configuration).parseExpression("#x==#x?'1,2,3':'foo'"); context.setVariable("x",new int[]{1,2,3}); - assertEquals("1,2,3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("1,2,3"); assertCanCompile(exp); - assertEquals("1,2,3", exp.getValue(context, new Foo(), String.class)); + assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo("1,2,3"); assertIsCompiled(exp); } @@ -5097,14 +5095,14 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { Set classloadersUsed = new HashSet<>(); for (int i = 0; i < 1500; i++) { // 1500 is greater than SpelCompiler.CLASSES_DEFINED_LIMIT expression = parser.parseExpression("4 + 5"); - assertEquals(9, (int) expression.getValue(Integer.class)); + assertThat((int) expression.getValue(Integer.class)).isEqualTo(9); assertCanCompile(expression); f.setAccessible(true); CompiledExpression cEx = (CompiledExpression) f.get(expression); classloadersUsed.add(cEx.getClass().getClassLoader()); - assertEquals(9, (int) expression.getValue(Integer.class)); + assertThat((int) expression.getValue(Integer.class)).isEqualTo(9); } - assertTrue(classloadersUsed.size() > 1); + assertThat(classloadersUsed.size() > 1).isTrue(); } @@ -5146,11 +5144,11 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { } private void assertCanCompile(Expression expression) { - assertTrue(SpelCompiler.compile(expression)); + assertThat(SpelCompiler.compile(expression)).isTrue(); } private void assertCantCompile(Expression expression) { - assertFalse(SpelCompiler.compile(expression)); + assertThat(SpelCompiler.compile(expression)).isFalse(); } private Expression parse(String expression) { @@ -5167,7 +5165,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { Field field = SpelExpression.class.getDeclaredField("compiledAst"); field.setAccessible(true); Object object = field.get(expression); - assertNotNull(object); + assertThat(object).isNotNull(); } catch (Exception ex) { throw new AssertionError(ex.getMessage(), ex); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationPerformanceTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationPerformanceTests.java index af745963526..33de567b23d 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationPerformanceTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationPerformanceTests.java @@ -22,10 +22,8 @@ import org.junit.Test; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelCompiler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * Checks the speed of compiled SpEL expressions. @@ -57,7 +55,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { NumberHolder nh = new NumberHolder(); expression = parser.parseExpression("(T(Integer).valueOf(payload).doubleValue())/18D"); Object o = expression.getValue(nh); - assertEquals(2d,o); + assertThat(o).isEqualTo(2d); System.out.println("Performance check for SpEL expression: '(T(Integer).valueOf(payload).doubleValue())/18D'"); long stime = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { @@ -77,7 +75,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { compile(expression); System.out.println("Now compiled:"); o = expression.getValue(nh); - assertEquals(2d, o); + assertThat(o).isEqualTo(2d); stime = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { @@ -97,7 +95,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { expression = parser.parseExpression("payload/18D"); o = expression.getValue(nh); - assertEquals(2d,o); + assertThat(o).isEqualTo(2d); System.out.println("Performance check for SpEL expression: 'payload/18D'"); stime = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { @@ -117,7 +115,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { compile(expression); System.out.println("Now compiled:"); o = expression.getValue(nh); - assertEquals(2d, o); + assertThat(o).isEqualTo(2d); stime = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { @@ -140,7 +138,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { public void inlineLists() throws Exception { expression = parser.parseExpression("{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])"); Object o = expression.getValue(); - assertEquals("bc",o); + assertThat(o).isEqualTo("bc"); System.out.println("Performance check for SpEL expression: '{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])'"); long stime = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { @@ -160,7 +158,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { compile(expression); System.out.println("Now compiled:"); o = expression.getValue(); - assertEquals("bc", o); + assertThat(o).isEqualTo("bc"); stime = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { @@ -183,7 +181,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { public void inlineNestedLists() throws Exception { expression = parser.parseExpression("{'abcde',{'ijklm','nopqr'}}[1][0].substring({1,3,4}[0],{1,3,4}[1])"); Object o = expression.getValue(); - assertEquals("jk",o); + assertThat(o).isEqualTo("jk"); System.out.println("Performance check for SpEL expression: '{'abcde','ijklm'}[0].substring({1,3,4}[0],{1,3,4}[1])'"); long stime = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { @@ -203,7 +201,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { compile(expression); System.out.println("Now compiled:"); o = expression.getValue(); - assertEquals("jk", o); + assertThat(o).isEqualTo("jk"); stime = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { @@ -227,7 +225,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { expression = parser.parseExpression("'hello' + getWorld() + ' spring'"); Greeter g = new Greeter(); Object o = expression.getValue(g); - assertEquals("helloworld spring", o); + assertThat(o).isEqualTo("helloworld spring"); System.out.println("Performance check for SpEL expression: 'hello' + getWorld() + ' spring'"); long stime = System.currentTimeMillis(); @@ -248,7 +246,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { compile(expression); System.out.println("Now compiled:"); o = expression.getValue(g); - assertEquals("helloworld spring", o); + assertThat(o).isEqualTo("helloworld spring"); stime = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { @@ -311,15 +309,15 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { reportPerformance("complex expression",iTotal, cTotal); // Verify the result - assertFalse(b); + assertThat(b).isFalse(); // Verify the same result for compiled vs interpreted - assertEquals(b, bc); + assertThat(bc).isEqualTo(b); // Verify if the input changes, the result changes payload.DR[0].DRFixedSection.duration = 0.04d; bc = expression.getValue(payload, Boolean.TYPE); - assertTrue(bc); + assertThat(bc).isTrue(); } public static class HW { @@ -371,7 +369,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { } logln(); - assertEquals(interpretedResult,compiledResult); + assertThat(compiledResult).isEqualTo(interpretedResult); reportPerformance("method reference", interpretedTotal, compiledTotal); if (compiledTotal >= interpretedTotal) { fail("Compiled version is slower than interpreted!"); @@ -423,7 +421,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { } logln(); - assertEquals(interpretedResult,compiledResult); + assertThat(compiledResult).isEqualTo(interpretedResult); reportPerformance("property reference (field)",interpretedTotal, compiledTotal); } @@ -469,7 +467,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { } logln(); - assertEquals(interpretedResult,compiledResult); + assertThat(compiledResult).isEqualTo(interpretedResult); reportPerformance("property reference (nested field)",interpretedTotal, compiledTotal); } @@ -514,7 +512,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { } logln(); - assertEquals(interpretedResult,compiledResult); + assertThat(compiledResult).isEqualTo(interpretedResult); reportPerformance("nested property reference (mixed field/getter)",interpretedTotal, compiledTotal); } @@ -561,7 +559,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { } logln(); - assertEquals(interpretedResult,compiledResult); + assertThat(compiledResult).isEqualTo(interpretedResult); reportPerformance("nested reference (mixed field/method)", interpretedTotal, compiledTotal); } @@ -609,7 +607,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { } logln(); - assertEquals(interpretedResult,compiledResult); + assertThat(compiledResult).isEqualTo(interpretedResult); reportPerformance("property reference (getter)", interpretedTotal, compiledTotal); if (compiledTotal >= interpretedTotal) { @@ -650,7 +648,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests { } private void compile(Expression expression) { - assertTrue(SpelCompiler.compile(expression)); + assertThat(SpelCompiler.compile(expression)).isTrue(); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java index 8a809c6f9a6..9b6e0daf3e2 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java @@ -35,11 +35,8 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.testresources.Inventor; import org.springframework.expression.spel.testresources.PlaceOfBirth; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; /** * Test the examples specified in the documentation. @@ -128,7 +125,7 @@ public class SpelDocumentationTests extends AbstractExpressionTests { context.setRootObject(tesla); String name = (String) exp.getValue(context); - assertEquals("Nikola Tesla",name); + assertThat(name).isEqualTo("Nikola Tesla"); } @Test @@ -140,7 +137,7 @@ public class SpelDocumentationTests extends AbstractExpressionTests { Expression exp = parser.parseExpression("name == 'Nikola Tesla'"); boolean isEqual = exp.getValue(context, Boolean.class); // evaluates to true - assertTrue(isEqual); + assertThat(isEqual).isTrue(); } // Section 7.4.1 @@ -156,29 +153,29 @@ public class SpelDocumentationTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(); String helloWorld = (String) parser.parseExpression("'Hello World'").getValue(); // evals to "Hello World" - assertEquals("Hello World",helloWorld); + assertThat(helloWorld).isEqualTo("Hello World"); double avogadrosNumber = (Double) parser.parseExpression("6.0221415E+23").getValue(); - assertEquals(6.0221415E+23, avogadrosNumber, 0); + assertThat(avogadrosNumber).isCloseTo(6.0221415E+23, within((double) 0)); int maxValue = (Integer) parser.parseExpression("0x7FFFFFFF").getValue(); // evals to 2147483647 - assertEquals(Integer.MAX_VALUE,maxValue); + assertThat(maxValue).isEqualTo(Integer.MAX_VALUE); boolean trueValue = (Boolean) parser.parseExpression("true").getValue(); - assertTrue(trueValue); + assertThat(trueValue).isTrue(); Object nullValue = parser.parseExpression("null").getValue(); - assertNull(nullValue); + assertThat(nullValue).isNull(); } @Test public void testPropertyAccess() throws Exception { EvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); int year = (Integer) parser.parseExpression("Birthdate.Year + 1900").getValue(context); // 1856 - assertEquals(1856,year); + assertThat(year).isEqualTo(1856); String city = (String) parser.parseExpression("placeOfBirth.City").getValue(context); - assertEquals("SmilJan",city); + assertThat(city).isEqualTo("SmilJan"); } @Test @@ -191,7 +188,7 @@ public class SpelDocumentationTests extends AbstractExpressionTests { // evaluates to "Induction motor" String invention = parser.parseExpression("inventions[3]").getValue(teslaContext, String.class); - assertEquals("Induction motor",invention); + assertThat(invention).isEqualTo("Induction motor"); // Members List StandardEvaluationContext societyContext = new StandardEvaluationContext(); @@ -201,12 +198,12 @@ public class SpelDocumentationTests extends AbstractExpressionTests { // evaluates to "Nikola Tesla" String name = parser.parseExpression("Members[0].Name").getValue(societyContext, String.class); - assertEquals("Nikola Tesla",name); + assertThat(name).isEqualTo("Nikola Tesla"); // List and Array navigation // evaluates to "Wireless communication" invention = parser.parseExpression("Members[0].Inventions[6]").getValue(societyContext, String.class); - assertEquals("Wireless communication",invention); + assertThat(invention).isEqualTo("Wireless communication"); } @@ -216,20 +213,20 @@ public class SpelDocumentationTests extends AbstractExpressionTests { societyContext.setRootObject(new IEEE()); // Officer's Dictionary Inventor pupin = parser.parseExpression("officers['president']").getValue(societyContext, Inventor.class); - assertNotNull(pupin); + assertThat(pupin).isNotNull(); // evaluates to "Idvor" String city = parser.parseExpression("officers['president'].PlaceOfBirth.city").getValue(societyContext, String.class); - assertNotNull(city); + assertThat(city).isNotNull(); // setting values Inventor i = parser.parseExpression("officers['advisors'][0]").getValue(societyContext,Inventor.class); - assertEquals("Nikola Tesla",i.getName()); + assertThat(i.getName()).isEqualTo("Nikola Tesla"); parser.parseExpression("officers['advisors'][0].PlaceOfBirth.Country").setValue(societyContext, "Croatia"); Inventor i2 = parser.parseExpression("reverse[0]['advisors'][0]").getValue(societyContext,Inventor.class); - assertEquals("Nikola Tesla",i2.getName()); + assertThat(i2.getName()).isEqualTo("Nikola Tesla"); } @@ -239,13 +236,13 @@ public class SpelDocumentationTests extends AbstractExpressionTests { public void testMethodInvocation2() throws Exception { // string literal, evaluates to "bc" String c = parser.parseExpression("'abc'.substring(1, 3)").getValue(String.class); - assertEquals("bc",c); + assertThat(c).isEqualTo("bc"); StandardEvaluationContext societyContext = new StandardEvaluationContext(); societyContext.setRootObject(new IEEE()); // evaluates to true boolean isMember = parser.parseExpression("isMember('Mihajlo Pupin')").getValue(societyContext, Boolean.class); - assertTrue(isMember); + assertThat(isMember).isTrue(); } // 7.5.4.1 @@ -253,29 +250,29 @@ public class SpelDocumentationTests extends AbstractExpressionTests { @Test public void testRelationalOperators() throws Exception { boolean result = parser.parseExpression("2 == 2").getValue(Boolean.class); - assertTrue(result); + assertThat(result).isTrue(); // evaluates to false result = parser.parseExpression("2 < -5.0").getValue(Boolean.class); - assertFalse(result); + assertThat(result).isFalse(); // evaluates to true result = parser.parseExpression("'black' < 'block'").getValue(Boolean.class); - assertTrue(result); + assertThat(result).isTrue(); } @Test public void testOtherOperators() throws Exception { // evaluates to false boolean falseValue = parser.parseExpression("'xyz' instanceof T(int)").getValue(Boolean.class); - assertFalse(falseValue); + assertThat(falseValue).isFalse(); // evaluates to true boolean trueValue = parser.parseExpression("'5.00' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class); - assertTrue(trueValue); + assertThat(trueValue).isTrue(); //evaluates to false falseValue = parser.parseExpression("'5.0067' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class); - assertFalse(falseValue); + assertThat(falseValue).isFalse(); } // 7.5.4.2 @@ -290,7 +287,7 @@ public class SpelDocumentationTests extends AbstractExpressionTests { // evaluates to false boolean falseValue = parser.parseExpression("true and false").getValue(Boolean.class); - assertFalse(falseValue); + assertThat(falseValue).isFalse(); // evaluates to true String expression = "isMember('Nikola Tesla') and isMember('Mihajlo Pupin')"; boolean trueValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class); @@ -299,24 +296,24 @@ public class SpelDocumentationTests extends AbstractExpressionTests { // evaluates to true trueValue = parser.parseExpression("true or false").getValue(Boolean.class); - assertTrue(trueValue); + assertThat(trueValue).isTrue(); // evaluates to true expression = "isMember('Nikola Tesla') or isMember('Albert Einstien')"; trueValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class); - assertTrue(trueValue); + assertThat(trueValue).isTrue(); // -- NOT -- // evaluates to false falseValue = parser.parseExpression("!true").getValue(Boolean.class); - assertFalse(falseValue); + assertThat(falseValue).isFalse(); // -- AND and NOT -- expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')"; falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class); - assertFalse(falseValue); + assertThat(falseValue).isFalse(); } // 7.5.4.3 @@ -325,42 +322,42 @@ public class SpelDocumentationTests extends AbstractExpressionTests { public void testNumericalOperators() throws Exception { // Addition int two = parser.parseExpression("1 + 1").getValue(Integer.class); // 2 - assertEquals(2,two); + assertThat(two).isEqualTo(2); String testString = parser.parseExpression("'test' + ' ' + 'string'").getValue(String.class); // 'test string' - assertEquals("test string",testString); + assertThat(testString).isEqualTo("test string"); // Subtraction int four = parser.parseExpression("1 - -3").getValue(Integer.class); // 4 - assertEquals(4,four); + assertThat(four).isEqualTo(4); double d = parser.parseExpression("1000.00 - 1e4").getValue(Double.class); // -9000 - assertEquals(-9000.0d, d, 0); + assertThat(d).isCloseTo(-9000.0d, within((double) 0)); // Multiplication int six = parser.parseExpression("-2 * -3").getValue(Integer.class); // 6 - assertEquals(6,six); + assertThat(six).isEqualTo(6); double twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Double.class); // 24.0 - assertEquals(24.0d, twentyFour, 0); + assertThat(twentyFour).isCloseTo(24.0d, within((double) 0)); // Division int minusTwo = parser.parseExpression("6 / -3").getValue(Integer.class); // -2 - assertEquals(-2,minusTwo); + assertThat(minusTwo).isEqualTo(-2); double one = parser.parseExpression("8.0 / 4e0 / 2").getValue(Double.class); // 1.0 - assertEquals(1.0d, one, 0); + assertThat(one).isCloseTo(1.0d, within((double) 0)); // Modulus int three = parser.parseExpression("7 % 4").getValue(Integer.class); // 3 - assertEquals(3,three); + assertThat(three).isEqualTo(3); int oneInt = parser.parseExpression("8 / 5 % 2").getValue(Integer.class); // 1 - assertEquals(1,oneInt); + assertThat(oneInt).isEqualTo(1); // Operator precedence int minusTwentyOne = parser.parseExpression("1+2-3*8").getValue(Integer.class); // -21 - assertEquals(-21,minusTwentyOne); + assertThat(minusTwentyOne).isEqualTo(-21); } // 7.5.5 @@ -373,12 +370,12 @@ public class SpelDocumentationTests extends AbstractExpressionTests { parser.parseExpression("foo").setValue(inventorContext, "Alexander Seovic2"); - assertEquals("Alexander Seovic2",parser.parseExpression("foo").getValue(inventorContext,String.class)); + assertThat(parser.parseExpression("foo").getValue(inventorContext,String.class)).isEqualTo("Alexander Seovic2"); // alternatively String aleks = parser.parseExpression("foo = 'Alexandar Seovic'").getValue(inventorContext, String.class); - assertEquals("Alexandar Seovic",parser.parseExpression("foo").getValue(inventorContext,String.class)); - assertEquals("Alexandar Seovic",aleks); + assertThat(parser.parseExpression("foo").getValue(inventorContext,String.class)).isEqualTo("Alexandar Seovic"); + assertThat(aleks).isEqualTo("Alexandar Seovic"); } // 7.5.6 @@ -386,9 +383,9 @@ public class SpelDocumentationTests extends AbstractExpressionTests { @Test public void testTypes() throws Exception { Class dateClass = parser.parseExpression("T(java.util.Date)").getValue(Class.class); - assertEquals(Date.class, dateClass); + assertThat(dateClass).isEqualTo(Date.class); boolean trueValue = parser.parseExpression("T(java.math.RoundingMode).CEILING < T(java.math.RoundingMode).FLOOR").getValue(Boolean.class); - assertTrue(trueValue); + assertThat(trueValue).isTrue(); } // 7.5.7 @@ -399,7 +396,7 @@ public class SpelDocumentationTests extends AbstractExpressionTests { societyContext.setRootObject(new IEEE()); Inventor einstein = parser.parseExpression("new org.springframework.expression.spel.testresources.Inventor('Albert Einstein',new java.util.Date(), 'German')").getValue(Inventor.class); - assertEquals("Albert Einstein", einstein.getName()); + assertThat(einstein.getName()).isEqualTo("Albert Einstein"); //create new inventor instance within add method of List parser.parseExpression("Members2.add(new org.springframework.expression.spel.testresources.Inventor('Albert Einstein', 'German'))").getValue(societyContext); } @@ -416,7 +413,7 @@ public class SpelDocumentationTests extends AbstractExpressionTests { parser.parseExpression("foo = #newName").getValue(context); - assertEquals("Mike Tesla",tesla.getFoo()); + assertThat(tesla.getFoo()).isEqualTo("Mike Tesla"); } @SuppressWarnings("unchecked") @@ -433,7 +430,7 @@ public class SpelDocumentationTests extends AbstractExpressionTests { // all prime numbers > 10 from the list (using selection ?{...}) List primesGreaterThanTen = (List) parser.parseExpression("#primes.?[#this>10]").getValue(context); - assertEquals("[11, 13, 17]",primesGreaterThanTen.toString()); + assertThat(primesGreaterThanTen.toString()).isEqualTo("[11, 13, 17]"); } // 7.5.9 @@ -445,7 +442,7 @@ public class SpelDocumentationTests extends AbstractExpressionTests { context.registerFunction("reverseString", StringUtils.class.getDeclaredMethod("reverseString", String.class)); String helloWorldReversed = parser.parseExpression("#reverseString('hello world')").getValue(context, String.class); - assertEquals("dlrow olleh",helloWorldReversed); + assertThat(helloWorldReversed).isEqualTo("dlrow olleh"); } // 7.5.10 @@ -453,7 +450,7 @@ public class SpelDocumentationTests extends AbstractExpressionTests { @Test public void testTernary() throws Exception { String falseString = parser.parseExpression("false ? 'trueExp' : 'falseExp'").getValue(String.class); - assertEquals("falseExp",falseString); + assertThat(falseString).isEqualTo("falseExp"); StandardEvaluationContext societyContext = new StandardEvaluationContext(); societyContext.setRootObject(new IEEE()); @@ -466,7 +463,7 @@ public class SpelDocumentationTests extends AbstractExpressionTests { + "+ Name + ' Society' : #queryName + ' is not a member of the ' + Name + ' Society'"; String queryResultString = parser.parseExpression(expression).getValue(societyContext, String.class); - assertEquals("Nikola Tesla is a member of the IEEE Society",queryResultString); + assertThat(queryResultString).isEqualTo("Nikola Tesla is a member of the IEEE Society"); // queryResultString = "Nikola Tesla is a member of the IEEE Society" } @@ -478,8 +475,8 @@ public class SpelDocumentationTests extends AbstractExpressionTests { StandardEvaluationContext societyContext = new StandardEvaluationContext(); societyContext.setRootObject(new IEEE()); List list = (List) parser.parseExpression("Members2.?[nationality == 'Serbian']").getValue(societyContext); - assertEquals(1,list.size()); - assertEquals("Nikola Tesla",list.get(0).getName()); + assertThat(list.size()).isEqualTo(1); + assertThat(list.get(0).getName()).isEqualTo("Nikola Tesla"); } // 7.5.12 @@ -488,7 +485,7 @@ public class SpelDocumentationTests extends AbstractExpressionTests { public void testTemplating() throws Exception { String randomPhrase = parser.parseExpression("random number is ${T(java.lang.Math).random()}", new TemplatedParserContext()).getValue(String.class); - assertTrue(randomPhrase.startsWith("random number")); + assertThat(randomPhrase.startsWith("random number")).isTrue(); } static class TemplatedParserContext implements ParserContext { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelExceptionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelExceptionTests.java index 3bb71af8511..2d52e1edb47 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelExceptionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelExceptionTests.java @@ -26,8 +26,8 @@ import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertTrue; /** * SpelEvaluationException tests (SPR-16544). @@ -72,7 +72,7 @@ public class SpelExceptionTests { } }); boolean result = spelExpression.getValue(ctx, Boolean.class); - assertTrue(result); + assertThat(result).isTrue(); } @@ -111,7 +111,7 @@ public class SpelExceptionTests { } }); boolean result = spelExpression.getValue(ctx, Boolean.class); - assertTrue(result); + assertThat(result).isTrue(); } @Test @@ -133,7 +133,7 @@ public class SpelExceptionTests { } }); boolean result = spelExpression.getValue(ctx, Boolean.class); - assertTrue(result); + assertThat(result).isTrue(); } @Test @@ -156,7 +156,7 @@ public class SpelExceptionTests { } }); boolean result = spelExpression.getValue(ctx, Boolean.class); - assertTrue(result); + assertThat(result).isTrue(); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index 06b8dd80c67..7c81d11885e 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -63,10 +63,6 @@ import org.springframework.util.ObjectUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * Reproduction tests cornering various reported SpEL issues. @@ -104,9 +100,9 @@ public class SpelReproTests extends AbstractExpressionTests { public void SPR5899() { StandardEvaluationContext context = new StandardEvaluationContext(new Spr5899Class()); Expression expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull(12)"); - assertEquals(12, expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo(12); expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull(null)"); - assertEquals(null, expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo(null); expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull2(null)"); assertThatExceptionOfType(EvaluationException.class).isThrownBy( expr::getValue); @@ -114,39 +110,39 @@ public class SpelReproTests extends AbstractExpressionTests { // varargs expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull3(null,'a','b')"); - assertEquals("ab", expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo("ab"); // varargs 2 - null is packed into the varargs expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull3(12,'a',null,'c')"); - assertEquals("anullc", expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo("anullc"); // check we can find the ctor ok expr = new SpelExpressionParser().parseRaw("new Spr5899Class().toString()"); - assertEquals("instance", expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo("instance"); expr = new SpelExpressionParser().parseRaw("new Spr5899Class(null).toString()"); - assertEquals("instance", expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo("instance"); // ctor varargs expr = new SpelExpressionParser().parseRaw("new Spr5899Class(null,'a','b').toString()"); - assertEquals("instance", expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo("instance"); // ctor varargs 2 expr = new SpelExpressionParser().parseRaw("new Spr5899Class(null,'a', null, 'b').toString()"); - assertEquals("instance", expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo("instance"); } @Test public void SPR5905_InnerTypeReferences() { StandardEvaluationContext context = new StandardEvaluationContext(new Spr5899Class()); Expression expr = new SpelExpressionParser().parseRaw("T(java.util.Map$Entry)"); - assertEquals(Map.Entry.class, expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo(Map.Entry.class); expr = new SpelExpressionParser().parseRaw("T(org.springframework.expression.spel.SpelReproTests$Outer$Inner).run()"); - assertEquals(12, expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo(12); expr = new SpelExpressionParser().parseRaw("new org.springframework.expression.spel.SpelReproTests$Outer$Inner().run2()"); - assertEquals(13, expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo(13); } @Test @@ -156,7 +152,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(m); // root is a map instance context.addPropertyAccessor(new MapAccessor()); Expression expr = new SpelExpressionParser().parseRaw("['foo']"); - assertEquals("bar", expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo("bar"); } @Test @@ -167,17 +163,17 @@ public class SpelReproTests extends AbstractExpressionTests { expr = new SpelExpressionParser().parseRaw("jdbcProperties['username']"); name = expr.getValue(context, String.class); - assertEquals("Dave", name); + assertThat(name).isEqualTo("Dave"); expr = new SpelExpressionParser().parseRaw("jdbcProperties[username]"); name = expr.getValue(context, String.class); - assertEquals("Dave", name); + assertThat(name).isEqualTo("Dave"); // MapAccessor required for this to work expr = new SpelExpressionParser().parseRaw("jdbcProperties.username"); context.addPropertyAccessor(new MapAccessor()); name = expr.getValue(context, String.class); - assertEquals("Dave", name); + assertThat(name).isEqualTo("Dave"); // --- dotted property names @@ -186,13 +182,13 @@ public class SpelReproTests extends AbstractExpressionTests { expr = new SpelExpressionParser().parseRaw("jdbcProperties[foo.bar]"); context.addPropertyAccessor(new MapAccessor()); name = expr.getValue(context, String.class); - assertEquals("Dave2", name); + assertThat(name).isEqualTo("Dave2"); // key is foo.bar expr = new SpelExpressionParser().parseRaw("jdbcProperties['foo.bar']"); context.addPropertyAccessor(new MapAccessor()); name = expr.getValue(context, String.class); - assertEquals("Elephant", name); + assertThat(name).isEqualTo("Elephant"); } @Test @@ -234,8 +230,8 @@ public class SpelReproTests extends AbstractExpressionTests { public void propertyAccessOnNullTarget_SPR5663() throws AccessException { PropertyAccessor accessor = new ReflectivePropertyAccessor(); EvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); - assertFalse(accessor.canRead(context, null, "abc")); - assertFalse(accessor.canWrite(context, null, "abc")); + assertThat(accessor.canRead(context, null, "abc")).isFalse(); + assertThat(accessor.canWrite(context, null, "abc")).isFalse(); assertThatIllegalStateException().isThrownBy(() -> accessor.read(context, null, "abc")); assertThatIllegalStateException().isThrownBy(() -> @@ -247,7 +243,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(new Foo()); Expression expr = new SpelExpressionParser().parseRaw("resource.resource.server"); String name = expr.getValue(context, String.class); - assertEquals("abc", name); + assertThat(name).isEqualTo("abc"); } /** Should be accessing Goo.getKey because 'bar' field evaluates to "key" */ @@ -258,9 +254,9 @@ public class SpelReproTests extends AbstractExpressionTests { Expression expr = null; expr = new SpelExpressionParser().parseRaw("instance[bar]"); name = expr.getValue(context, String.class); - assertEquals("hello", name); + assertThat(name).isEqualTo("hello"); name = expr.getValue(context, String.class); // will be using the cached accessor this time - assertEquals("hello", name); + assertThat(name).isEqualTo("hello"); } /** Should be accessing Goo.getKey because 'bar' variable evaluates to "key" */ @@ -272,9 +268,9 @@ public class SpelReproTests extends AbstractExpressionTests { Expression expr = null; expr = new SpelExpressionParser().parseRaw("instance[#bar]"); name = expr.getValue(context, String.class); - assertEquals("hello", name); + assertThat(name).isEqualTo("hello"); name = expr.getValue(context, String.class); // will be using the cached accessor this time - assertEquals("hello", name); + assertThat(name).isEqualTo("hello"); } /** $ related identifiers */ @@ -294,27 +290,27 @@ public class SpelReproTests extends AbstractExpressionTests { expr = new SpelExpressionParser().parseRaw("map.$foo"); name = expr.getValue(context, String.class); - assertEquals("wibble", name); + assertThat(name).isEqualTo("wibble"); expr = new SpelExpressionParser().parseRaw("map.foo$bar"); name = expr.getValue(context, String.class); - assertEquals("wobble", name); + assertThat(name).isEqualTo("wobble"); expr = new SpelExpressionParser().parseRaw("map.foobar$$"); name = expr.getValue(context, String.class); - assertEquals("wabble", name); + assertThat(name).isEqualTo("wabble"); expr = new SpelExpressionParser().parseRaw("map.$"); name = expr.getValue(context, String.class); - assertEquals("wubble", name); + assertThat(name).isEqualTo("wubble"); expr = new SpelExpressionParser().parseRaw("map.$$"); name = expr.getValue(context, String.class); - assertEquals("webble", name); + assertThat(name).isEqualTo("webble"); expr = new SpelExpressionParser().parseRaw("map.$_$"); name = expr.getValue(context, String.class); - assertEquals("tribble", name); + assertThat(name).isEqualTo("tribble"); } /** Should be accessing Goo.wibble field because 'bar' variable evaluates to "wibble" */ @@ -327,9 +323,9 @@ public class SpelReproTests extends AbstractExpressionTests { expr = new SpelExpressionParser().parseRaw("instance[#bar]"); // will access the field 'wibble' and not use a getter name = expr.getValue(context, String.class); - assertEquals("wobble", name); + assertThat(name).isEqualTo("wobble"); name = expr.getValue(context, String.class); // will be using the cached accessor this time - assertEquals("wobble", name); + assertThat(name).isEqualTo("wobble"); } /** @@ -345,9 +341,9 @@ public class SpelReproTests extends AbstractExpressionTests { expr = new SpelExpressionParser().parseRaw("instance[#bar]='world'"); // will access the field 'wibble' and not use a getter expr.getValue(context, String.class); - assertEquals("world", g.wibble); + assertThat(g.wibble).isEqualTo("world"); expr.getValue(context, String.class); // will be using the cached accessor this time - assertEquals("world", g.wibble); + assertThat(g.wibble).isEqualTo("world"); } /** Should be accessing Goo.setKey field because 'bar' variable evaluates to "key" */ @@ -358,9 +354,9 @@ public class SpelReproTests extends AbstractExpressionTests { Expression expr = null; expr = new SpelExpressionParser().parseRaw("instance[bar]='world'"); expr.getValue(context, String.class); - assertEquals("world", g.value); + assertThat(g.value).isEqualTo("world"); expr.getValue(context, String.class); // will be using the cached accessor this time - assertEquals("world", g.value); + assertThat(g.value).isEqualTo("world"); } @Test @@ -369,7 +365,7 @@ public class SpelReproTests extends AbstractExpressionTests { Expression expr = null; expr = new SpelExpressionParser().parseRaw("m['$foo']"); context.setVariable("file_name", "$foo"); - assertEquals("wibble", expr.getValue(context, String.class)); + assertThat(expr.getValue(context, String.class)).isEqualTo("wibble"); } @Test @@ -378,7 +374,7 @@ public class SpelReproTests extends AbstractExpressionTests { Expression expr = null; expr = new SpelExpressionParser().parseRaw("m[$foo]"); context.setVariable("file_name", "$foo"); - assertEquals("wibble", expr.getValue(context, String.class)); + assertThat(expr.getValue(context, String.class)).isEqualTo("wibble"); } private void checkTemplateParsing(String expression, String expectedValue) { @@ -388,7 +384,7 @@ public class SpelReproTests extends AbstractExpressionTests { private void checkTemplateParsing(String expression, ParserContext context, String expectedValue) { SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression(expression, context); - assertEquals(expectedValue, expr.getValue(TestScenarioCreator.getTestEvaluationContext())); + assertThat(expr.getValue(TestScenarioCreator.getTestEvaluationContext())).isEqualTo(expectedValue); } private void checkTemplateParsingError(String expression, String expectedMessage) { @@ -432,46 +428,46 @@ public class SpelReproTests extends AbstractExpressionTests { // no resolver registered == exception try { expr = new SpelExpressionParser().parseRaw("@foo"); - assertEquals("custard", expr.getValue(context, String.class)); + assertThat(expr.getValue(context, String.class)).isEqualTo("custard"); } catch (SpelEvaluationException see) { - assertEquals(SpelMessage.NO_BEAN_RESOLVER_REGISTERED, see.getMessageCode()); - assertEquals("foo", see.getInserts()[0]); + assertThat(see.getMessageCode()).isEqualTo(SpelMessage.NO_BEAN_RESOLVER_REGISTERED); + assertThat(see.getInserts()[0]).isEqualTo("foo"); } context.setBeanResolver(new MyBeanResolver()); // bean exists expr = new SpelExpressionParser().parseRaw("@foo"); - assertEquals("custard", expr.getValue(context, String.class)); + assertThat(expr.getValue(context, String.class)).isEqualTo("custard"); // bean does not exist expr = new SpelExpressionParser().parseRaw("@bar"); - assertEquals(null, expr.getValue(context, String.class)); + assertThat(expr.getValue(context, String.class)).isEqualTo(null); // bean name will cause AccessException expr = new SpelExpressionParser().parseRaw("@goo"); try { - assertEquals(null, expr.getValue(context, String.class)); + assertThat(expr.getValue(context, String.class)).isEqualTo(null); } catch (SpelEvaluationException see) { - assertEquals(SpelMessage.EXCEPTION_DURING_BEAN_RESOLUTION, see.getMessageCode()); - assertEquals("goo", see.getInserts()[0]); - assertTrue(see.getCause() instanceof AccessException); - assertTrue(see.getCause().getMessage().startsWith("DONT")); + assertThat(see.getMessageCode()).isEqualTo(SpelMessage.EXCEPTION_DURING_BEAN_RESOLUTION); + assertThat(see.getInserts()[0]).isEqualTo("goo"); + assertThat(see.getCause() instanceof AccessException).isTrue(); + assertThat(see.getCause().getMessage().startsWith("DONT")).isTrue(); } // bean exists expr = new SpelExpressionParser().parseRaw("@'foo.bar'"); - assertEquals("trouble", expr.getValue(context, String.class)); + assertThat(expr.getValue(context, String.class)).isEqualTo("trouble"); // bean exists try { expr = new SpelExpressionParser().parseRaw("@378"); - assertEquals("trouble", expr.getValue(context, String.class)); + assertThat(expr.getValue(context, String.class)).isEqualTo("trouble"); } catch (SpelParseException spe) { - assertEquals(SpelMessage.INVALID_BEAN_REFERENCE, spe.getMessageCode()); + assertThat(spe.getMessageCode()).isEqualTo(SpelMessage.INVALID_BEAN_REFERENCE); } } @@ -482,18 +478,18 @@ public class SpelReproTests extends AbstractExpressionTests { // Different parts of elvis expression are null expr = new SpelExpressionParser().parseRaw("(?:'default')"); - assertEquals("default", expr.getValue()); + assertThat(expr.getValue()).isEqualTo("default"); expr = new SpelExpressionParser().parseRaw("?:'default'"); - assertEquals("default", expr.getValue()); + assertThat(expr.getValue()).isEqualTo("default"); expr = new SpelExpressionParser().parseRaw("?:"); - assertEquals(null, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(null); // Different parts of ternary expression are null assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> new SpelExpressionParser().parseRaw("(?'abc':'default')").getValue(context)) .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.TYPE_CONVERSION_ERROR)); expr = new SpelExpressionParser().parseRaw("(false?'abc':null)"); - assertEquals(null, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(null); // Assignment assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> @@ -506,11 +502,11 @@ public class SpelReproTests extends AbstractExpressionTests { Expression expr = null; // Have empty string treated as null for elvis expr = new SpelExpressionParser().parseRaw("?:'default'"); - assertEquals("default", expr.getValue()); + assertThat(expr.getValue()).isEqualTo("default"); expr = new SpelExpressionParser().parseRaw("\"\"?:'default'"); - assertEquals("default", expr.getValue()); + assertThat(expr.getValue()).isEqualTo("default"); expr = new SpelExpressionParser().parseRaw("''?:'default'"); - assertEquals("default", expr.getValue()); + assertThat(expr.getValue()).isEqualTo("default"); } @Test @@ -526,12 +522,12 @@ public class SpelReproTests extends AbstractExpressionTests { String el1 = "#root['value'].get('givenName')"; Expression exp = parser.parseExpression(el1); Object evaluated = exp.getValue(context); - assertEquals("Arthur", evaluated); + assertThat(evaluated).isEqualTo("Arthur"); String el2 = "#root['value']['givenName']"; exp = parser.parseExpression(el2); evaluated = exp.getValue(context); - assertEquals("Arthur", evaluated); + assertThat(evaluated).isEqualTo("Arthur"); } @Test @@ -542,9 +538,9 @@ public class SpelReproTests extends AbstractExpressionTests { SpelExpression exp = parser.parseRaw(el1); List value = (List) exp.getValue(context); // value is list containing [true,false] - assertEquals(Boolean.class, value.get(0).getClass()); + assertThat(value.get(0).getClass()).isEqualTo(Boolean.class); TypeDescriptor evaluated = exp.getValueTypeDescriptor(context); - assertEquals(null, evaluated.getElementTypeDescriptor()); + assertThat(evaluated.getElementTypeDescriptor()).isEqualTo(null); } @Test @@ -555,9 +551,9 @@ public class SpelReproTests extends AbstractExpressionTests { SpelExpression exp = parser.parseRaw(el1); Object[] value = (Object[]) exp.getValue(context); // value is array containing [true,false] - assertEquals(Boolean.class, value[0].getClass()); + assertThat(value[0].getClass()).isEqualTo(Boolean.class); TypeDescriptor evaluated = exp.getValueTypeDescriptor(context); - assertEquals(Boolean.class, evaluated.getElementTypeDescriptor().getType()); + assertThat(evaluated.getElementTypeDescriptor().getType()).isEqualTo(Boolean.class); } @Test @@ -568,9 +564,9 @@ public class SpelReproTests extends AbstractExpressionTests { SpelExpression exp = parser.parseRaw(el1); List value = (List) exp.getValue(context); // value is list containing [true,false] - assertEquals(Boolean.class, value.get(0).getClass()); + assertThat(value.get(0).getClass()).isEqualTo(Boolean.class); TypeDescriptor evaluated = exp.getValueTypeDescriptor(context); - assertEquals(null, evaluated.getElementTypeDescriptor()); + assertThat(evaluated.getElementTypeDescriptor()).isEqualTo(null); } @Test @@ -589,18 +585,18 @@ public class SpelReproTests extends AbstractExpressionTests { String el1 = "#root.?[a < 'hhh']"; SpelExpression exp = parser.parseRaw(el1); Object value = exp.getValue(context); - assertEquals("[D(aaa), D(bbb), D(null), D(ccc), D(null)]", value.toString()); + assertThat(value.toString()).isEqualTo("[D(aaa), D(bbb), D(null), D(ccc), D(null)]"); String el2 = "#root.?[a > 'hhh']"; SpelExpression exp2 = parser.parseRaw(el2); Object value2 = exp2.getValue(context); - assertEquals("[D(zzz)]", value2.toString()); + assertThat(value2.toString()).isEqualTo("[D(zzz)]"); // trim out the nulls first String el3 = "#root.?[a!=null].?[a < 'hhh']"; SpelExpression exp3 = parser.parseRaw(el3); Object value3 = exp3.getValue(context); - assertEquals("[D(aaa), D(bbb), D(ccc)]", value3.toString()); + assertThat(value3.toString()).isEqualTo("[D(aaa), D(bbb), D(ccc)]"); } /** @@ -645,7 +641,7 @@ public class SpelReproTests extends AbstractExpressionTests { // Compiler chooses getX(Number i) when passing Integer final int compiler = target.getX(INTEGER); // Fails! - assertEquals(compiler, actual); + assertThat(actual).isEqualTo(compiler); ConversionPriority2 target2 = new ConversionPriority2(); MethodExecutor me2 = new ReflectiveMethodResolver(true).resolve(emptyEvalContext, target2, "getX", args); @@ -654,7 +650,7 @@ public class SpelReproTests extends AbstractExpressionTests { // Compiler chooses getX(Number i) when passing Integer int compiler2 = target2.getX(INTEGER); // Fails! - assertEquals(compiler2, actual2); + assertThat(actual2).isEqualTo(compiler2); } @@ -682,7 +678,7 @@ public class SpelReproTests extends AbstractExpressionTests { final int actual = (Integer) me.execute(emptyEvalContext, target, INTEGER_VALUE).getValue(); final int compiler = target.getX(INTEGER_VALUE); - assertEquals(compiler, actual); + assertThat(actual).isEqualTo(compiler); } @Test @@ -695,8 +691,8 @@ public class SpelReproTests extends AbstractExpressionTests { getClass().getClassLoader(), new Class[] {VarargsInterface.class}, (proxy1, method, args) -> method.invoke(receiver, args)); - assertEquals("OK", expr.getValue(new StandardEvaluationContext(receiver))); - assertEquals("OK", expr.getValue(new StandardEvaluationContext(proxy))); + assertThat(expr.getValue(new StandardEvaluationContext(receiver))).isEqualTo("OK"); + assertThat(expr.getValue(new StandardEvaluationContext(proxy))).isEqualTo("OK"); } @Test @@ -715,7 +711,7 @@ public class SpelReproTests extends AbstractExpressionTests { String result = expression.getValue(evaluationContext, "foo", String.class); result = expression.getValue(evaluationContext, "foo", String.class); - assertEquals("OK", result); + assertThat(result).isEqualTo("OK"); } @Test @@ -793,28 +789,28 @@ public class SpelReproTests extends AbstractExpressionTests { String ex = "getReserver().NE"; SpelExpression exp = parser.parseRaw(ex); String value = (String) exp.getValue(context); - assertEquals("abc", value); + assertThat(value).isEqualTo("abc"); ex = "getReserver().ne"; exp = parser.parseRaw(ex); value = (String) exp.getValue(context); - assertEquals("def", value); + assertThat(value).isEqualTo("def"); ex = "getReserver().m[NE]"; exp = parser.parseRaw(ex); value = (String) exp.getValue(context); - assertEquals("xyz", value); + assertThat(value).isEqualTo("xyz"); ex = "getReserver().DIV"; exp = parser.parseRaw(ex); - assertEquals(1, exp.getValue(context)); + assertThat(exp.getValue(context)).isEqualTo(1); ex = "getReserver().div"; exp = parser.parseRaw(ex); - assertEquals(3, exp.getValue(context)); + assertThat(exp.getValue(context)).isEqualTo(3); exp = parser.parseRaw("NE"); - assertEquals("abc", exp.getValue(context)); + assertThat(exp.getValue(context)).isEqualTo("abc"); } @Test @@ -823,7 +819,7 @@ public class SpelReproTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expression = parser.parseRaw("T(org.springframework.expression.spel.testresources.le.div.mod.reserved.Reserver).CONST"); Object value = expression.getValue(context); - assertEquals(value, Reserver.CONST); + assertThat(Reserver.CONST).isEqualTo(value); } /** @@ -842,10 +838,10 @@ public class SpelReproTests extends AbstractExpressionTests { evaluationContext.addPropertyAccessor(new TestPropertyAccessor("thirdContext")); evaluationContext.addPropertyAccessor(new TestPropertyAccessor("fourthContext")); - assertEquals("first", expressionParser.parseExpression("shouldBeFirst").getValue(evaluationContext)); - assertEquals("second", expressionParser.parseExpression("shouldBeSecond").getValue(evaluationContext)); - assertEquals("third", expressionParser.parseExpression("shouldBeThird").getValue(evaluationContext)); - assertEquals("fourth", expressionParser.parseExpression("shouldBeFourth").getValue(evaluationContext)); + assertThat(expressionParser.parseExpression("shouldBeFirst").getValue(evaluationContext)).isEqualTo("first"); + assertThat(expressionParser.parseExpression("shouldBeSecond").getValue(evaluationContext)).isEqualTo("second"); + assertThat(expressionParser.parseExpression("shouldBeThird").getValue(evaluationContext)).isEqualTo("third"); + assertThat(expressionParser.parseExpression("shouldBeFourth").getValue(evaluationContext)).isEqualTo("fourth"); } /** @@ -873,7 +869,7 @@ public class SpelReproTests extends AbstractExpressionTests { Expression expression = parser.parseExpression("parseInt('-FF', 16)"); Integer result = expression.getValue(context, "", Integer.class); - assertEquals(-255, result.intValue()); + assertThat(result.intValue()).isEqualTo(-255); } @Test @@ -885,24 +881,24 @@ public class SpelReproTests extends AbstractExpressionTests { expression = parser.parseExpression("new java.lang.Long[0].class"); result = expression.getValue(context, ""); - assertEquals("Equal assertion failed: ", "class [Ljava.lang.Long;", result.toString()); + assertThat(result.toString()).as("Equal assertion failed: ").isEqualTo("class [Ljava.lang.Long;"); expression = parser.parseExpression("T(java.lang.Long[])"); result = expression.getValue(context, ""); - assertEquals("Equal assertion failed: ", "class [Ljava.lang.Long;", result.toString()); + assertThat(result.toString()).as("Equal assertion failed: ").isEqualTo("class [Ljava.lang.Long;"); expression = parser.parseExpression("T(java.lang.String[][][])"); result = expression.getValue(context, ""); - assertEquals("Equal assertion failed: ", "class [[[Ljava.lang.String;", result.toString()); - assertEquals("T(java.lang.String[][][])", ((SpelExpression) expression).toStringAST()); + assertThat(result.toString()).as("Equal assertion failed: ").isEqualTo("class [[[Ljava.lang.String;"); + assertThat(((SpelExpression) expression).toStringAST()).isEqualTo("T(java.lang.String[][][])"); expression = parser.parseExpression("new int[0].class"); result = expression.getValue(context, ""); - assertEquals("Equal assertion failed: ", "class [I", result.toString()); + assertThat(result.toString()).as("Equal assertion failed: ").isEqualTo("class [I"); expression = parser.parseExpression("T(int[][])"); result = expression.getValue(context, ""); - assertEquals("class [[I", result.toString()); + assertThat(result.toString()).isEqualTo("class [[I"); } @Test @@ -914,7 +910,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("abs(-10.2f)"); Number result = expression.getValue(context, testObject, Number.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -924,7 +920,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.21f + 10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -934,7 +930,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.21f + 10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -944,7 +940,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.21f - 10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -954,7 +950,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.21f - 10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -964,7 +960,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.21f * 10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -974,7 +970,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.21f * 10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -984,7 +980,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f / -10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -994,7 +990,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f / -10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -1004,7 +1000,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f == -10.2f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1014,7 +1010,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f == -10.2"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1024,7 +1020,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.215f == 10.2109f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1034,7 +1030,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.215f == 10.2109"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1044,7 +1040,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.215f != 10.2109f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1054,7 +1050,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.215f != 10.2109"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1064,7 +1060,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f < -10.2f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -1074,7 +1070,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f < -10.2"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -1084,7 +1080,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f <= -10.22f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -1094,7 +1090,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f <= -10.2"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -1104,7 +1100,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f > -10.2f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -1114,7 +1110,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f > -10.2"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1124,7 +1120,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f >= -10.2f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedNumber, result); + assertThat(result).isEqualTo(expectedNumber); } @Test @@ -1134,7 +1130,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("-10.21f >= -10.2"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1144,7 +1140,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.21f % 10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1154,7 +1150,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.21f % 10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1164,7 +1160,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.21f ^ -10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1174,7 +1170,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = parser.parseExpression("10.21f ^ 10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals(expectedResult, result); + assertThat(result).isEqualTo(expectedResult); } @Test @@ -1183,7 +1179,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Object target = new GenericImplementation(); TypedValue value = accessor.read(context, target, "property"); - assertEquals(Integer.class, value.getTypeDescriptor().getType()); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(Integer.class); } @Test @@ -1192,7 +1188,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); Object target = new OnlyBridgeMethod(); TypedValue value = accessor.read(context, target, "property"); - assertEquals(Integer.class, value.getTypeDescriptor().getType()); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(Integer.class); } @Test @@ -1200,7 +1196,7 @@ public class SpelReproTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Class valueType = parser.parseExpression("simpleProperty").getValueType(evaluationContext); - assertNotNull(valueType); + assertThat(valueType).isNotNull(); } @Test @@ -1208,7 +1204,7 @@ public class SpelReproTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Object value = parser.parseExpression("simpleProperty").getValue(evaluationContext); - assertNotNull(value); + assertThat(value).isNotNull(); } @Test @@ -1216,7 +1212,7 @@ public class SpelReproTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Class valueType = parser.parseExpression("primitiveProperty").getValueType(evaluationContext); - assertNotNull(valueType); + assertThat(valueType).isNotNull(); } @Test @@ -1224,7 +1220,7 @@ public class SpelReproTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Object value = parser.parseExpression("primitiveProperty").getValue(evaluationContext); - assertNotNull(value); + assertThat(value).isNotNull(); } @Test @@ -1289,19 +1285,19 @@ public class SpelReproTests extends AbstractExpressionTests { context.setVariable("enumType", ABC.class); Object result = spel.getValue(context); - assertNotNull(result); - assertTrue(result.getClass().isArray()); - assertEquals(ABC.A, Array.get(result, 0)); - assertEquals(ABC.B, Array.get(result, 1)); - assertEquals(ABC.C, Array.get(result, 2)); + assertThat(result).isNotNull(); + assertThat(result.getClass().isArray()).isTrue(); + assertThat(Array.get(result, 0)).isEqualTo(ABC.A); + assertThat(Array.get(result, 1)).isEqualTo(ABC.B); + assertThat(Array.get(result, 2)).isEqualTo(ABC.C); context.setVariable("enumType", XYZ.class); result = spel.getValue(context); - assertNotNull(result); - assertTrue(result.getClass().isArray()); - assertEquals(XYZ.X, Array.get(result, 0)); - assertEquals(XYZ.Y, Array.get(result, 1)); - assertEquals(XYZ.Z, Array.get(result, 2)); + assertThat(result).isNotNull(); + assertThat(result.getClass().isArray()).isTrue(); + assertThat(Array.get(result, 0)).isEqualTo(XYZ.X); + assertThat(Array.get(result, 1)).isEqualTo(XYZ.Y); + assertThat(Array.get(result, 2)).isEqualTo(XYZ.Z); } @Test @@ -1314,11 +1310,11 @@ public class SpelReproTests extends AbstractExpressionTests { context.setVariable("enumType", ABC.class); Object result = spel.getValue(context); - assertNotNull(result); - assertTrue(result.getClass().isArray()); - assertEquals(ABC.A, Array.get(result, 0)); - assertEquals(ABC.B, Array.get(result, 1)); - assertEquals(ABC.C, Array.get(result, 2)); + assertThat(result).isNotNull(); + assertThat(result.getClass().isArray()).isTrue(); + assertThat(Array.get(result, 0)).isEqualTo(ABC.A); + assertThat(Array.get(result, 1)).isEqualTo(ABC.B); + assertThat(Array.get(result, 2)).isEqualTo(ABC.C); context.addMethodResolver(new MethodResolver() { @Override @@ -1342,11 +1338,11 @@ public class SpelReproTests extends AbstractExpressionTests { }); result = spel.getValue(context); - assertNotNull(result); - assertTrue(result.getClass().isArray()); - assertEquals(XYZ.X, Array.get(result, 0)); - assertEquals(XYZ.Y, Array.get(result, 1)); - assertEquals(XYZ.Z, Array.get(result, 2)); + assertThat(result).isNotNull(); + assertThat(result.getClass().isArray()).isTrue(); + assertThat(Array.get(result, 0)).isEqualTo(XYZ.X); + assertThat(Array.get(result, 1)).isEqualTo(XYZ.Y); + assertThat(Array.get(result, 2)).isEqualTo(XYZ.Z); } @Test @@ -1381,7 +1377,7 @@ public class SpelReproTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("['one'] == ['two']"); - assertTrue(expr.getValue(map, Boolean.class)); + assertThat(expr.getValue(map, Boolean.class)).isTrue(); } @Test @@ -1394,18 +1390,18 @@ public class SpelReproTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("new java.util.ArrayList(#root)"); Object value = expr.getValue(coll); - assertTrue(value instanceof ArrayList); + assertThat(value instanceof ArrayList).isTrue(); @SuppressWarnings("rawtypes") ArrayList list = (ArrayList) value; - assertEquals("one", list.get(0)); - assertEquals("two", list.get(1)); + assertThat(list.get(0)).isEqualTo("one"); + assertThat(list.get(1)).isEqualTo("two"); } @Test public void SPR11445_simple() { StandardEvaluationContext context = new StandardEvaluationContext(new Spr11445Class()); Expression expr = new SpelExpressionParser().parseRaw("echo(parameter())"); - assertEquals(1, expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo(1); } @Test @@ -1413,7 +1409,7 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); context.setBeanResolver(new Spr11445Class()); Expression expr = new SpelExpressionParser().parseRaw("@bean.echo(@bean.parameter())"); - assertEquals(1, expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo(1); } @Test @@ -1430,7 +1426,7 @@ public class SpelReproTests extends AbstractExpressionTests { sec.addPropertyAccessor(new MapAccessor()); Expression exp = new SpelExpressionParser().parseExpression( "T(org.springframework.expression.spel.SpelReproTests$MapWithConstant).X"); - assertEquals(1, exp.getValue(sec)); + assertThat(exp.getValue(sec)).isEqualTo(1); } @Test @@ -1452,15 +1448,15 @@ public class SpelReproTests extends AbstractExpressionTests { Expression exp = parser.parseExpression("#item[0].name"); context.setVariable("item", item); - assertEquals("child1", exp.getValue(context)); + assertThat(exp.getValue(context)).isEqualTo("child1"); } @Test public void SPR12502() { SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("#root.getClass().getName()"); - assertEquals(UnnamedUser.class.getName(), expression.getValue(new UnnamedUser())); - assertEquals(NamedUser.class.getName(), expression.getValue(new NamedUser())); + assertThat(expression.getValue(new UnnamedUser())).isEqualTo(UnnamedUser.class.getName()); + assertThat(expression.getValue(new NamedUser())).isEqualTo(NamedUser.class.getName()); } @Test @@ -1469,8 +1465,8 @@ public class SpelReproTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("T(java.util.Arrays).asList('')"); Object value = expression.getValue(); - assertTrue(value instanceof List); - assertTrue(((List) value).isEmpty()); + assertThat(value instanceof List).isTrue(); + assertThat(((List) value).isEmpty()).isTrue(); } @Test @@ -1479,7 +1475,7 @@ public class SpelReproTests extends AbstractExpressionTests { sec.setVariable("iterable", Collections.emptyList()); SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("T(org.springframework.expression.spel.SpelReproTests.FooLists).newArrayList(#iterable)"); - assertTrue(expression.getValue(sec) instanceof ArrayList); + assertThat(expression.getValue(sec) instanceof ArrayList).isTrue(); } @Test @@ -1488,13 +1484,13 @@ public class SpelReproTests extends AbstractExpressionTests { Expression expression = parser.parseExpression("T(org.springframework.expression.spel.SpelReproTests.DistanceEnforcer).from(#no)"); StandardEvaluationContext sec = new StandardEvaluationContext(); sec.setVariable("no", new Integer(1)); - assertTrue(expression.getValue(sec).toString().startsWith("Integer")); + assertThat(expression.getValue(sec).toString().startsWith("Integer")).isTrue(); sec = new StandardEvaluationContext(); sec.setVariable("no", new Float(1.0)); - assertTrue(expression.getValue(sec).toString().startsWith("Number")); + assertThat(expression.getValue(sec).toString().startsWith("Number")).isTrue(); sec = new StandardEvaluationContext(); sec.setVariable("no", "1.0"); - assertTrue(expression.getValue(sec).toString().startsWith("Object")); + assertThat(expression.getValue(sec).toString().startsWith("Object")).isTrue(); } @Test @@ -1519,14 +1515,14 @@ public class SpelReproTests extends AbstractExpressionTests { String ex = "#root.![T(org.springframework.util.StringUtils).collectionToCommaDelimitedString(#this.values())]"; List res = parser.parseExpression(ex).getValue(context, List.class); - assertEquals("[test12,test11, test22,test21]", res.toString()); + assertThat(res.toString()).isEqualTo("[test12,test11, test22,test21]"); res = parser.parseExpression("#root.![#this.values()]").getValue(context, List.class); - assertEquals("[[test12, test11], [test22, test21]]", res.toString()); + assertThat(res.toString()).isEqualTo("[[test12, test11], [test22, test21]]"); res = parser.parseExpression("#root.![values()]").getValue(context, List.class); - assertEquals("[[test12, test11], [test22, test21]]", res.toString()); + assertThat(res.toString()).isEqualTo("[[test12, test11], [test22, test21]]"); } @Test @@ -1534,9 +1530,9 @@ public class SpelReproTests extends AbstractExpressionTests { StandardEvaluationContext context = new StandardEvaluationContext(); context.setBeanResolver(new MyBeanResolver()); Expression expr = new SpelExpressionParser().parseRaw("@foo"); - assertEquals("custard", expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo("custard"); expr = new SpelExpressionParser().parseRaw("&foo"); - assertEquals("foo factory",expr.getValue(context)); + assertThat(expr.getValue(context)).isEqualTo("foo factory"); assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> new SpelExpressionParser().parseRaw("&@foo")) @@ -1558,10 +1554,10 @@ public class SpelReproTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(); Expression expression1 = parser.parseExpression("list.?[ value>2 ].size()!=0"); - assertTrue(expression1.getValue(new BeanClass(new ListOf(1.1), new ListOf(2.2)), Boolean.class)); + assertThat(expression1.getValue(new BeanClass(new ListOf(1.1), new ListOf(2.2)), Boolean.class)).isTrue(); Expression expression2 = parser.parseExpression("list.?[ T(java.lang.Math).abs(value) > 2 ].size()!=0"); - assertTrue(expression2.getValue(new BeanClass(new ListOf(1.1), new ListOf(-2.2)), Boolean.class)); + assertThat(expression2.getValue(new BeanClass(new ListOf(1.1), new ListOf(-2.2)), Boolean.class)).isTrue(); } @Test @@ -1570,13 +1566,13 @@ public class SpelReproTests extends AbstractExpressionTests { ExpressionParser parser = new SpelExpressionParser(); Expression ex = parser.parseExpression("{'a':'y','b':'n'}.![value=='y'?key:null]"); - assertEquals("[a, null]", ex.getValue(context).toString()); + assertThat(ex.getValue(context).toString()).isEqualTo("[a, null]"); ex = parser.parseExpression("{2:4,3:6}.![T(java.lang.Math).abs(#this.key) + 5]"); - assertEquals("[7, 8]", ex.getValue(context).toString()); + assertThat(ex.getValue(context).toString()).isEqualTo("[7, 8]"); ex = parser.parseExpression("{2:4,3:6}.![T(java.lang.Math).abs(#this.value) + 5]"); - assertEquals("[9, 11]", ex.getValue(context).toString()); + assertThat(ex.getValue(context).toString()).isEqualTo("[9, 11]"); } @Test @@ -1596,12 +1592,12 @@ public class SpelReproTests extends AbstractExpressionTests { // #this should be the element from list1 Expression ex = parser.parseExpression("#list1.?[#list2.contains(#this)]"); Object result = ex.getValue(context); - assertEquals("[x]", result.toString()); + assertThat(result.toString()).isEqualTo("[x]"); // toString() should be called on the element from list1 ex = parser.parseExpression("#list1.?[#list2.contains(toString())]"); result = ex.getValue(context); - assertEquals("[x]", result.toString()); + assertThat(result.toString()).isEqualTo("[x]"); List list3 = new ArrayList(); list3.add(1); @@ -1613,11 +1609,11 @@ public class SpelReproTests extends AbstractExpressionTests { context.setVariable("list3", list3); ex = parser.parseExpression("#list3.?[#this > 2]"); result = ex.getValue(context); - assertEquals("[3, 4]", result.toString()); + assertThat(result.toString()).isEqualTo("[3, 4]"); ex = parser.parseExpression("#list3.?[#this >= T(java.lang.Math).abs(T(java.lang.Math).abs(#this))]"); result = ex.getValue(context); - assertEquals("[1, 2, 3, 4]", result.toString()); + assertThat(result.toString()).isEqualTo("[1, 2, 3, 4]"); } @Test @@ -1637,11 +1633,11 @@ public class SpelReproTests extends AbstractExpressionTests { // #this should be the element from list1 Expression ex = parser.parseExpression("#map1.?[#map2.containsKey(#this.getKey())]"); Object result = ex.getValue(context); - assertEquals("{X=66}", result.toString()); + assertThat(result.toString()).isEqualTo("{X=66}"); ex = parser.parseExpression("#map1.?[#map2.containsKey(key)]"); result = ex.getValue(context); - assertEquals("{X=66}", result.toString()); + assertThat(result.toString()).isEqualTo("{X=66}"); } @Test @@ -1651,7 +1647,7 @@ public class SpelReproTests extends AbstractExpressionTests { Expression ex = parser.parseExpression("T(java.nio.charset.Charset).forName(#encoding)"); Object result = ex.getValue(context); - assertEquals(StandardCharsets.UTF_8, result); + assertThat(result).isEqualTo(StandardCharsets.UTF_8); } @Test @@ -1661,7 +1657,7 @@ public class SpelReproTests extends AbstractExpressionTests { Expression ex = parser.parseExpression("#str?.split('\0')"); Object result = ex.getValue(context); - assertTrue(ObjectUtils.nullSafeEquals(result, new String[] {"a", "b"})); + assertThat(ObjectUtils.nullSafeEquals(result, new String[] {"a", "b"})).isTrue(); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/StandardTypeLocatorTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/StandardTypeLocatorTests.java index 95c93f90fe7..e51555ef3c3 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/StandardTypeLocatorTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/StandardTypeLocatorTests.java @@ -24,9 +24,6 @@ import org.springframework.expression.spel.support.StandardTypeLocator; import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for type comparison @@ -38,15 +35,15 @@ public class StandardTypeLocatorTests { @Test public void testImports() throws EvaluationException { StandardTypeLocator locator = new StandardTypeLocator(); - assertEquals(Integer.class,locator.findType("java.lang.Integer")); - assertEquals(String.class,locator.findType("java.lang.String")); + assertThat(locator.findType("java.lang.Integer")).isEqualTo(Integer.class); + assertThat(locator.findType("java.lang.String")).isEqualTo(String.class); List prefixes = locator.getImportPrefixes(); - assertEquals(1,prefixes.size()); - assertTrue(prefixes.contains("java.lang")); - assertFalse(prefixes.contains("java.util")); + assertThat(prefixes.size()).isEqualTo(1); + assertThat(prefixes.contains("java.lang")).isTrue(); + assertThat(prefixes.contains("java.util")).isFalse(); - assertEquals(Boolean.class,locator.findType("Boolean")); + assertThat(locator.findType("Boolean")).isEqualTo(Boolean.class); // currently does not know about java.util by default // assertEquals(java.util.List.class,locator.findType("List")); @@ -54,7 +51,7 @@ public class StandardTypeLocatorTests { locator.findType("URL")) .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.TYPE_NOT_FOUND)); locator.registerImport("java.net"); - assertEquals(java.net.URL.class,locator.findType("URL")); + assertThat(locator.findType("URL")).isEqualTo(java.net.URL.class); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java index 8ca249301c2..12a35edcc6f 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java @@ -30,9 +30,6 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; import static org.assertj.core.api.Assertions.assertThat; 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; /** * @author Andy Clement @@ -76,7 +73,7 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("hello ${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT); Object o = expr.getValue(); - assertEquals("hello world", o.toString()); + assertThat(o.toString()).isEqualTo("hello world"); } @Test @@ -84,7 +81,7 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("hello ${'to'} you", DEFAULT_TEMPLATE_PARSER_CONTEXT); Object o = expr.getValue(); - assertEquals("hello to you", o.toString()); + assertThat(o.toString()).isEqualTo("hello to you"); } @Test @@ -93,7 +90,7 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { Expression expr = parser.parseExpression("The quick ${'brown'} fox jumped over the ${'lazy'} dog", DEFAULT_TEMPLATE_PARSER_CONTEXT); Object o = expr.getValue(); - assertEquals("The quick brown fox jumped over the lazy dog", o.toString()); + assertThat(o.toString()).isEqualTo("The quick brown fox jumped over the lazy dog"); } @Test @@ -101,19 +98,19 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("${'hello'} world", DEFAULT_TEMPLATE_PARSER_CONTEXT); Object o = expr.getValue(); - assertEquals("hello world", o.toString()); + assertThat(o.toString()).isEqualTo("hello world"); expr = parser.parseExpression("", DEFAULT_TEMPLATE_PARSER_CONTEXT); o = expr.getValue(); - assertEquals("", o.toString()); + assertThat(o.toString()).isEqualTo(""); expr = parser.parseExpression("abc", DEFAULT_TEMPLATE_PARSER_CONTEXT); o = expr.getValue(); - assertEquals("abc", o.toString()); + assertThat(o.toString()).isEqualTo("abc"); expr = parser.parseExpression("abc", DEFAULT_TEMPLATE_PARSER_CONTEXT); o = expr.getValue((Object)null); - assertEquals("abc", o.toString()); + assertThat(o.toString()).isEqualTo("abc"); } @Test @@ -133,19 +130,19 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { assertThat(ex.getValue(ctx, new Rooty())).isInstanceOf(String.class).isEqualTo("hello world"); assertThat(ex.getValue(ctx, new Rooty(), String.class)).isInstanceOf(String.class).isEqualTo("hello world"); assertThat(ex.getValue(ctx, new Rooty(), String.class)).isInstanceOf(String.class).isEqualTo("hello world"); - assertEquals("hello ${'world'}", ex.getExpressionString()); - assertFalse(ex.isWritable(new StandardEvaluationContext())); - assertFalse(ex.isWritable(new Rooty())); - assertFalse(ex.isWritable(new StandardEvaluationContext(), new Rooty())); + assertThat(ex.getExpressionString()).isEqualTo("hello ${'world'}"); + assertThat(ex.isWritable(new StandardEvaluationContext())).isFalse(); + assertThat(ex.isWritable(new Rooty())).isFalse(); + assertThat(ex.isWritable(new StandardEvaluationContext(), new Rooty())).isFalse(); - assertEquals(String.class,ex.getValueType()); - assertEquals(String.class,ex.getValueType(ctx)); - assertEquals(String.class,ex.getValueTypeDescriptor().getType()); - assertEquals(String.class,ex.getValueTypeDescriptor(ctx).getType()); - assertEquals(String.class,ex.getValueType(new Rooty())); - assertEquals(String.class,ex.getValueType(ctx, new Rooty())); - assertEquals(String.class,ex.getValueTypeDescriptor(new Rooty()).getType()); - assertEquals(String.class,ex.getValueTypeDescriptor(ctx, new Rooty()).getType()); + assertThat(ex.getValueType()).isEqualTo(String.class); + assertThat(ex.getValueType(ctx)).isEqualTo(String.class); + assertThat(ex.getValueTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(ex.getValueTypeDescriptor(ctx).getType()).isEqualTo(String.class); + assertThat(ex.getValueType(new Rooty())).isEqualTo(String.class); + assertThat(ex.getValueType(ctx, new Rooty())).isEqualTo(String.class); + assertThat(ex.getValueTypeDescriptor(new Rooty()).getType()).isEqualTo(String.class); + assertThat(ex.getValueTypeDescriptor(ctx, new Rooty()).getType()).isEqualTo(String.class); assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> ex.setValue(ctx, null)); assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> @@ -162,21 +159,21 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { // treat the nested ${..} as a part of the expression Expression ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#this<5]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT); String s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class); - assertEquals("hello 4 world",s); + assertThat(s).isEqualTo("hello 4 world"); // not a useful expression but tests nested expression syntax that clashes with template prefix/suffix ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#root.listOfNumbersUpToTen.$[#this%2==1]==3]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT); - assertEquals(CompositeStringExpression.class,ex.getClass()); + assertThat(ex.getClass()).isEqualTo(CompositeStringExpression.class); CompositeStringExpression cse = (CompositeStringExpression)ex; Expression[] exprs = cse.getExpressions(); - assertEquals(3,exprs.length); - assertEquals("listOfNumbersUpToTen.$[#root.listOfNumbersUpToTen.$[#this%2==1]==3]",exprs[1].getExpressionString()); + assertThat(exprs.length).isEqualTo(3); + assertThat(exprs[1].getExpressionString()).isEqualTo("listOfNumbersUpToTen.$[#root.listOfNumbersUpToTen.$[#this%2==1]==3]"); s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class); - assertEquals("hello world",s); + assertThat(s).isEqualTo("hello world"); ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#this<5]} ${listOfNumbersUpToTen.$[#this>5]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT); s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class); - assertEquals("hello 4 10 world",s); + assertThat(s).isEqualTo("hello 4 10 world"); assertThatExceptionOfType(ParseException.class).isThrownBy(() -> parser.parseExpression("hello ${listOfNumbersUpToTen.$[#this<5]} ${listOfNumbersUpToTen.$[#this>5] world",DEFAULT_TEMPLATE_PARSER_CONTEXT)) @@ -193,21 +190,21 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { // Just wanting to use the prefix or suffix within the template: Expression ex = parser.parseExpression("hello ${3+4} world",DEFAULT_TEMPLATE_PARSER_CONTEXT); String s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class); - assertEquals("hello 7 world", s); + assertThat(s).isEqualTo("hello 7 world"); ex = parser.parseExpression("hello ${3+4} wo${'${'}rld",DEFAULT_TEMPLATE_PARSER_CONTEXT); s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class); - assertEquals("hello 7 wo${rld", s); + assertThat(s).isEqualTo("hello 7 wo${rld"); ex = parser.parseExpression("hello ${3+4} wo}rld",DEFAULT_TEMPLATE_PARSER_CONTEXT); s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class); - assertEquals("hello 7 wo}rld", s); + assertThat(s).isEqualTo("hello 7 wo}rld"); } @Test public void testParsingNormalExpressionThroughTemplateParser() throws Exception { Expression expr = parser.parseExpression("1+2+3"); - assertEquals(6, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(6); } @Test @@ -229,19 +226,19 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests { @Test public void testTemplateParserContext() { TemplateParserContext tpc = new TemplateParserContext("abc","def"); - assertEquals("abc", tpc.getExpressionPrefix()); - assertEquals("def", tpc.getExpressionSuffix()); - assertTrue(tpc.isTemplate()); + assertThat(tpc.getExpressionPrefix()).isEqualTo("abc"); + assertThat(tpc.getExpressionSuffix()).isEqualTo("def"); + assertThat(tpc.isTemplate()).isTrue(); tpc = new TemplateParserContext(); - assertEquals("#{", tpc.getExpressionPrefix()); - assertEquals("}", tpc.getExpressionSuffix()); - assertTrue(tpc.isTemplate()); + assertThat(tpc.getExpressionPrefix()).isEqualTo("#{"); + assertThat(tpc.getExpressionSuffix()).isEqualTo("}"); + assertThat(tpc.isTemplate()).isTrue(); ParserContext pc = ParserContext.TEMPLATE_EXPRESSION; - assertEquals("#{", pc.getExpressionPrefix()); - assertEquals("}", pc.getExpressionSuffix()); - assertTrue(pc.isTemplate()); + assertThat(pc.getExpressionPrefix()).isEqualTo("#{"); + assertThat(pc.getExpressionSuffix()).isEqualTo("}"); + assertThat(pc.isTemplate()).isTrue(); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ast/FormatHelperTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ast/FormatHelperTests.java index 24985783027..99a001d7277 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ast/FormatHelperTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ast/FormatHelperTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import org.springframework.core.convert.TypeDescriptor; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Andy Wilkinson @@ -32,13 +32,13 @@ public class FormatHelperTests { @Test public void formatMethodWithSingleArgumentForMessage() { String message = FormatHelper.formatMethodForMessage("foo", Arrays.asList(TypeDescriptor.forObject("a string"))); - assertEquals("foo(java.lang.String)", message); + assertThat(message).isEqualTo("foo(java.lang.String)"); } @Test public void formatMethodWithMultipleArgumentsForMessage() { String message = FormatHelper.formatMethodForMessage("foo", Arrays.asList(TypeDescriptor.forObject("a string"), TypeDescriptor.forObject(Integer.valueOf(5)))); - assertEquals("foo(java.lang.String,java.lang.Integer)", message); + assertThat(message).isEqualTo("foo(java.lang.String,java.lang.Integer)"); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ast/OpPlusTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ast/OpPlusTests.java index 8acdb6cd9b3..3e715a4a5e4 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ast/OpPlusTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ast/OpPlusTests.java @@ -30,9 +30,9 @@ import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.support.StandardTypeConverter; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * Unit tests for SpEL's plus operator. @@ -70,9 +70,9 @@ public class OpPlusTests { OpPlus o = new OpPlus(-1, -1, realLiteral); TypedValue value = o.getValueInternal(expressionState); - assertEquals(Double.class, value.getTypeDescriptor().getObjectType()); - assertEquals(Double.class, value.getTypeDescriptor().getType()); - assertEquals(realLiteral.getLiteralValue().getValue(), value.getValue()); + assertThat(value.getTypeDescriptor().getObjectType()).isEqualTo(Double.class); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(Double.class); + assertThat(value.getValue()).isEqualTo(realLiteral.getLiteralValue().getValue()); } { @@ -80,9 +80,9 @@ public class OpPlusTests { OpPlus o = new OpPlus(-1, -1, intLiteral); TypedValue value = o.getValueInternal(expressionState); - assertEquals(Integer.class, value.getTypeDescriptor().getObjectType()); - assertEquals(Integer.class, value.getTypeDescriptor().getType()); - assertEquals(intLiteral.getLiteralValue().getValue(), value.getValue()); + assertThat(value.getTypeDescriptor().getObjectType()).isEqualTo(Integer.class); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(value.getValue()).isEqualTo(intLiteral.getLiteralValue().getValue()); } { @@ -90,9 +90,9 @@ public class OpPlusTests { OpPlus o = new OpPlus(-1, -1, longLiteral); TypedValue value = o.getValueInternal(expressionState); - assertEquals(Long.class, value.getTypeDescriptor().getObjectType()); - assertEquals(Long.class, value.getTypeDescriptor().getType()); - assertEquals(longLiteral.getLiteralValue().getValue(), value.getValue()); + assertThat(value.getTypeDescriptor().getObjectType()).isEqualTo(Long.class); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(Long.class); + assertThat(value.getValue()).isEqualTo(longLiteral.getLiteralValue().getValue()); } } @@ -106,9 +106,9 @@ public class OpPlusTests { OpPlus o = new OpPlus(-1, -1, n1, n2); TypedValue value = o.getValueInternal(expressionState); - assertEquals(Double.class, value.getTypeDescriptor().getObjectType()); - assertEquals(Double.class, value.getTypeDescriptor().getType()); - assertEquals(Double.valueOf(123.0 + 456.0), value.getValue()); + assertThat(value.getTypeDescriptor().getObjectType()).isEqualTo(Double.class); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(Double.class); + assertThat(value.getValue()).isEqualTo(Double.valueOf(123.0 + 456.0)); } { @@ -117,9 +117,9 @@ public class OpPlusTests { OpPlus o = new OpPlus(-1, -1, n1, n2); TypedValue value = o.getValueInternal(expressionState); - assertEquals(Long.class, value.getTypeDescriptor().getObjectType()); - assertEquals(Long.class, value.getTypeDescriptor().getType()); - assertEquals(Long.valueOf(123L + 456L), value.getValue()); + assertThat(value.getTypeDescriptor().getObjectType()).isEqualTo(Long.class); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(Long.class); + assertThat(value.getValue()).isEqualTo(Long.valueOf(123L + 456L)); } { @@ -128,9 +128,9 @@ public class OpPlusTests { OpPlus o = new OpPlus(-1, -1, n1, n2); TypedValue value = o.getValueInternal(expressionState); - assertEquals(Integer.class, value.getTypeDescriptor().getObjectType()); - assertEquals(Integer.class, value.getTypeDescriptor().getType()); - assertEquals(Integer.valueOf(123 + 456), value.getValue()); + assertThat(value.getTypeDescriptor().getObjectType()).isEqualTo(Integer.class); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(Integer.class); + assertThat(value.getValue()).isEqualTo(Integer.valueOf(123 + 456)); } } @@ -143,9 +143,9 @@ public class OpPlusTests { OpPlus o = new OpPlus(-1, -1, n1, n2); TypedValue value = o.getValueInternal(expressionState); - assertEquals(String.class, value.getTypeDescriptor().getObjectType()); - assertEquals(String.class, value.getTypeDescriptor().getType()); - assertEquals("foobar", value.getValue()); + assertThat(value.getTypeDescriptor().getObjectType()).isEqualTo(String.class); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(value.getValue()).isEqualTo("foobar"); } @Test @@ -157,9 +157,9 @@ public class OpPlusTests { OpPlus o = new OpPlus(-1, -1, n1, n2); TypedValue value = o.getValueInternal(expressionState); - assertEquals(String.class, value.getTypeDescriptor().getObjectType()); - assertEquals(String.class, value.getTypeDescriptor().getType()); - assertEquals("number is 123", value.getValue()); + assertThat(value.getTypeDescriptor().getObjectType()).isEqualTo(String.class); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(value.getValue()).isEqualTo("number is 123"); } @Test @@ -171,9 +171,9 @@ public class OpPlusTests { OpPlus o = new OpPlus(-1, -1, n1, n2); TypedValue value = o.getValueInternal(expressionState); - assertEquals(String.class, value.getTypeDescriptor().getObjectType()); - assertEquals(String.class, value.getTypeDescriptor().getType()); - assertEquals("123 is a number", value.getValue()); + assertThat(value.getTypeDescriptor().getObjectType()).isEqualTo(String.class); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(value.getValue()).isEqualTo("123 is a number"); } @Test @@ -188,9 +188,9 @@ public class OpPlusTests { OpPlus o = new OpPlus(-1, -1, var, n2); TypedValue value = o.getValueInternal(expressionState); - assertEquals(String.class, value.getTypeDescriptor().getObjectType()); - assertEquals(String.class, value.getTypeDescriptor().getType()); - assertEquals(time + " is now", value.getValue()); + assertThat(value.getTypeDescriptor().getObjectType()).isEqualTo(String.class); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(value.getValue()).isEqualTo((time + " is now")); } @Test @@ -213,9 +213,9 @@ public class OpPlusTests { OpPlus o = new OpPlus(-1, -1, var, n2); TypedValue value = o.getValueInternal(expressionState); - assertEquals(String.class, value.getTypeDescriptor().getObjectType()); - assertEquals(String.class, value.getTypeDescriptor().getType()); - assertEquals(format.format(time) + " is now", value.getValue()); + assertThat(value.getTypeDescriptor().getObjectType()).isEqualTo(String.class); + assertThat(value.getTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(value.getValue()).isEqualTo((format.format(time) + " is now")); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/standard/PropertiesConversionSpelTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/standard/PropertiesConversionSpelTests.java index a449b184f18..e5b55ef2cc9 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/standard/PropertiesConversionSpelTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/standard/PropertiesConversionSpelTests.java @@ -26,7 +26,7 @@ import org.junit.Test; import org.springframework.expression.Expression; import org.springframework.expression.spel.support.StandardEvaluationContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher @@ -45,7 +45,7 @@ public class PropertiesConversionSpelTests { StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("props", props); String result = expression.getValue(context, new TestBean(), String.class); - assertEquals("123", result); + assertThat(result).isEqualTo("123"); } @Test @@ -58,7 +58,7 @@ public class PropertiesConversionSpelTests { StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("props", map); String result = expression.getValue(context, new TestBean(), String.class); - assertEquals("123", result); + assertThat(result).isEqualTo("123"); } @Test @@ -72,7 +72,7 @@ public class PropertiesConversionSpelTests { StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("props", map); String result = expression.getValue(context, new TestBean(), String.class); - assertEquals("1null3", result); + assertThat(result).isEqualTo("1null3"); } @Test @@ -85,7 +85,7 @@ public class PropertiesConversionSpelTests { StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("props", map); String result = expression.getValue(context, new TestBean(), String.class); - assertEquals("1null3", result); + assertThat(result).isEqualTo("1null3"); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/standard/SpelParserTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/standard/SpelParserTests.java index 582145eea14..c0c60bd6f04 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/standard/SpelParserTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/standard/SpelParserTests.java @@ -31,11 +31,6 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Andy Clement @@ -47,11 +42,11 @@ public class SpelParserTests { public void theMostBasic() { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expr = parser.parseRaw("2"); - assertNotNull(expr); - assertNotNull(expr.getAST()); - assertEquals(2, expr.getValue()); - assertEquals(Integer.class, expr.getValueType()); - assertEquals(2, expr.getAST().getValue(null)); + assertThat(expr).isNotNull(); + assertThat(expr.getAST()).isNotNull(); + assertThat(expr.getValue()).isEqualTo(2); + assertThat(expr.getValueType()).isEqualTo(Integer.class); + assertThat(expr.getAST().getValue(null)).isEqualTo(2); } @Test @@ -59,61 +54,61 @@ public class SpelParserTests { SpelExpressionParser parser = new SpelExpressionParser(); EvaluationContext ctx = new StandardEvaluationContext(); Class c = parser.parseRaw("2").getValueType(); - assertEquals(Integer.class, c); + assertThat(c).isEqualTo(Integer.class); c = parser.parseRaw("12").getValueType(ctx); - assertEquals(Integer.class, c); + assertThat(c).isEqualTo(Integer.class); c = parser.parseRaw("null").getValueType(); - assertNull(c); + assertThat(c).isNull(); c = parser.parseRaw("null").getValueType(ctx); - assertNull(c); + assertThat(c).isNull(); Object o = parser.parseRaw("null").getValue(ctx, Integer.class); - assertNull(o); + assertThat(o).isNull(); } @Test public void whitespace() { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expr = parser.parseRaw("2 + 3"); - assertEquals(5, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(5); expr = parser.parseRaw("2 + 3"); - assertEquals(5, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(5); expr = parser.parseRaw("2\n+\t3"); - assertEquals(5, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(5); expr = parser.parseRaw("2\r\n+\t3"); - assertEquals(5, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(5); } @Test public void arithmeticPlus1() { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expr = parser.parseRaw("2+2"); - assertNotNull(expr); - assertNotNull(expr.getAST()); - assertEquals(4, expr.getValue()); + assertThat(expr).isNotNull(); + assertThat(expr.getAST()).isNotNull(); + assertThat(expr.getValue()).isEqualTo(4); } @Test public void arithmeticPlus2() { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expr = parser.parseRaw("37+41"); - assertEquals(78, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(78); } @Test public void arithmeticMultiply1() { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expr = parser.parseRaw("2*3"); - assertNotNull(expr); - assertNotNull(expr.getAST()); + assertThat(expr).isNotNull(); + assertThat(expr.getAST()).isNotNull(); // printAst(expr.getAST(),0); - assertEquals(6, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(6); } @Test public void arithmeticPrecedence1() { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expr = parser.parseRaw("2*3+5"); - assertEquals(11, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(11); } @Test @@ -169,89 +164,89 @@ public class SpelParserTests { public void arithmeticPrecedence2() { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expr = parser.parseRaw("2+3*5"); - assertEquals(17, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(17); } @Test public void arithmeticPrecedence3() { SpelExpression expr = new SpelExpressionParser().parseRaw("3+10/2"); - assertEquals(8, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(8); } @Test public void arithmeticPrecedence4() { SpelExpression expr = new SpelExpressionParser().parseRaw("10/2+3"); - assertEquals(8, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(8); } @Test public void arithmeticPrecedence5() { SpelExpression expr = new SpelExpressionParser().parseRaw("(4+10)/2"); - assertEquals(7, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(7); } @Test public void arithmeticPrecedence6() { SpelExpression expr = new SpelExpressionParser().parseRaw("(3+2)*2"); - assertEquals(10, expr.getValue()); + assertThat(expr.getValue()).isEqualTo(10); } @Test public void booleanOperators() { SpelExpression expr = new SpelExpressionParser().parseRaw("true"); - assertEquals(Boolean.TRUE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); expr = new SpelExpressionParser().parseRaw("false"); - assertEquals(Boolean.FALSE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); expr = new SpelExpressionParser().parseRaw("false and false"); - assertEquals(Boolean.FALSE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); expr = new SpelExpressionParser().parseRaw("true and (true or false)"); - assertEquals(Boolean.TRUE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); expr = new SpelExpressionParser().parseRaw("true and true or false"); - assertEquals(Boolean.TRUE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); expr = new SpelExpressionParser().parseRaw("!true"); - assertEquals(Boolean.FALSE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); expr = new SpelExpressionParser().parseRaw("!(false or true)"); - assertEquals(Boolean.FALSE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); } @Test public void booleanOperators_symbolic_spr9614() { SpelExpression expr = new SpelExpressionParser().parseRaw("true"); - assertEquals(Boolean.TRUE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); expr = new SpelExpressionParser().parseRaw("false"); - assertEquals(Boolean.FALSE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); expr = new SpelExpressionParser().parseRaw("false && false"); - assertEquals(Boolean.FALSE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); expr = new SpelExpressionParser().parseRaw("true && (true || false)"); - assertEquals(Boolean.TRUE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); expr = new SpelExpressionParser().parseRaw("true && true || false"); - assertEquals(Boolean.TRUE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); expr = new SpelExpressionParser().parseRaw("!true"); - assertEquals(Boolean.FALSE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); expr = new SpelExpressionParser().parseRaw("!(false || true)"); - assertEquals(Boolean.FALSE, expr.getValue(Boolean.class)); + assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); } @Test public void stringLiterals() { SpelExpression expr = new SpelExpressionParser().parseRaw("'howdy'"); - assertEquals("howdy", expr.getValue()); + assertThat(expr.getValue()).isEqualTo("howdy"); expr = new SpelExpressionParser().parseRaw("'hello '' world'"); - assertEquals("hello ' world", expr.getValue()); + assertThat(expr.getValue()).isEqualTo("hello ' world"); } @Test public void stringLiterals2() { SpelExpression expr = new SpelExpressionParser().parseRaw("'howdy'.substring(0,2)"); - assertEquals("ho", expr.getValue()); + assertThat(expr.getValue()).isEqualTo("ho"); } @Test public void testStringLiterals_DoubleQuotes_spr9620() { SpelExpression expr = new SpelExpressionParser().parseRaw("\"double quote: \"\".\""); - assertEquals("double quote: \".", expr.getValue()); + assertThat(expr.getValue()).isEqualTo("double quote: \"."); expr = new SpelExpressionParser().parseRaw("\"hello \"\" world\""); - assertEquals("hello \" world", expr.getValue()); + assertThat(expr.getValue()).isEqualTo("hello \" world"); } @Test @@ -273,72 +268,72 @@ public class SpelParserTests { SpelNode rightOrOperand = operatorOr.getRightOperand(); // check position for final 'false' - assertEquals(17, rightOrOperand.getStartPosition()); - assertEquals(22, rightOrOperand.getEndPosition()); + assertThat(rightOrOperand.getStartPosition()).isEqualTo(17); + assertThat(rightOrOperand.getEndPosition()).isEqualTo(22); // check position for first 'true' - assertEquals(0, operatorAnd.getLeftOperand().getStartPosition()); - assertEquals(4, operatorAnd.getLeftOperand().getEndPosition()); + assertThat(operatorAnd.getLeftOperand().getStartPosition()).isEqualTo(0); + assertThat(operatorAnd.getLeftOperand().getEndPosition()).isEqualTo(4); // check position for second 'true' - assertEquals(9, operatorAnd.getRightOperand().getStartPosition()); - assertEquals(13, operatorAnd.getRightOperand().getEndPosition()); + assertThat(operatorAnd.getRightOperand().getStartPosition()).isEqualTo(9); + assertThat(operatorAnd.getRightOperand().getEndPosition()).isEqualTo(13); // check position for OperatorAnd - assertEquals(5, operatorAnd.getStartPosition()); - assertEquals(8, operatorAnd.getEndPosition()); + assertThat(operatorAnd.getStartPosition()).isEqualTo(5); + assertThat(operatorAnd.getEndPosition()).isEqualTo(8); // check position for OperatorOr - assertEquals(14, operatorOr.getStartPosition()); - assertEquals(16, operatorOr.getEndPosition()); + assertThat(operatorOr.getStartPosition()).isEqualTo(14); + assertThat(operatorOr.getEndPosition()).isEqualTo(16); } @Test public void tokenKind() { TokenKind tk = TokenKind.NOT; - assertFalse(tk.hasPayload()); - assertEquals("NOT(!)", tk.toString()); + assertThat(tk.hasPayload()).isFalse(); + assertThat(tk.toString()).isEqualTo("NOT(!)"); tk = TokenKind.MINUS; - assertFalse(tk.hasPayload()); - assertEquals("MINUS(-)", tk.toString()); + assertThat(tk.hasPayload()).isFalse(); + assertThat(tk.toString()).isEqualTo("MINUS(-)"); tk = TokenKind.LITERAL_STRING; - assertEquals("LITERAL_STRING", tk.toString()); - assertTrue(tk.hasPayload()); + assertThat(tk.toString()).isEqualTo("LITERAL_STRING"); + assertThat(tk.hasPayload()).isTrue(); } @Test public void token() { Token token = new Token(TokenKind.NOT, 0, 3); - assertEquals(TokenKind.NOT, token.kind); - assertEquals(0, token.startPos); - assertEquals(3, token.endPos); - assertEquals("[NOT(!)](0,3)", token.toString()); + assertThat(token.kind).isEqualTo(TokenKind.NOT); + assertThat(token.startPos).isEqualTo(0); + assertThat(token.endPos).isEqualTo(3); + assertThat(token.toString()).isEqualTo("[NOT(!)](0,3)"); token = new Token(TokenKind.LITERAL_STRING, "abc".toCharArray(), 0, 3); - assertEquals(TokenKind.LITERAL_STRING, token.kind); - assertEquals(0, token.startPos); - assertEquals(3, token.endPos); - assertEquals("[LITERAL_STRING:abc](0,3)", token.toString()); + assertThat(token.kind).isEqualTo(TokenKind.LITERAL_STRING); + assertThat(token.startPos).isEqualTo(0); + assertThat(token.endPos).isEqualTo(3); + assertThat(token.toString()).isEqualTo("[LITERAL_STRING:abc](0,3)"); } @Test public void exceptions() { ExpressionException exprEx = new ExpressionException("test"); - assertEquals("test", exprEx.getSimpleMessage()); - assertEquals("test", exprEx.toDetailedString()); - assertEquals("test", exprEx.getMessage()); + assertThat(exprEx.getSimpleMessage()).isEqualTo("test"); + assertThat(exprEx.toDetailedString()).isEqualTo("test"); + assertThat(exprEx.getMessage()).isEqualTo("test"); exprEx = new ExpressionException("wibble", "test"); - assertEquals("test", exprEx.getSimpleMessage()); - assertEquals("Expression [wibble]: test", exprEx.toDetailedString()); - assertEquals("Expression [wibble]: test", exprEx.getMessage()); + assertThat(exprEx.getSimpleMessage()).isEqualTo("test"); + assertThat(exprEx.toDetailedString()).isEqualTo("Expression [wibble]: test"); + assertThat(exprEx.getMessage()).isEqualTo("Expression [wibble]: test"); exprEx = new ExpressionException("wibble", 3, "test"); - assertEquals("test", exprEx.getSimpleMessage()); - assertEquals("Expression [wibble] @3: test", exprEx.toDetailedString()); - assertEquals("Expression [wibble] @3: test", exprEx.getMessage()); + assertThat(exprEx.getSimpleMessage()).isEqualTo("test"); + assertThat(exprEx.toDetailedString()).isEqualTo("Expression [wibble] @3: test"); + assertThat(exprEx.getMessage()).isEqualTo("Expression [wibble] @3: test"); } @Test @@ -380,8 +375,8 @@ public class SpelParserTests { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expr = parser.parseRaw(expression); Object exprVal = expr.getValue(); - assertEquals(value, exprVal); - assertEquals(type, exprVal.getClass()); + assertThat(exprVal).isEqualTo(value); + assertThat(exprVal.getClass()).isEqualTo(type); } catch (Exception ex) { throw new AssertionError(ex.getMessage(), ex); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java index fe839095bc2..2c7a29740d4 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java @@ -34,13 +34,8 @@ import org.springframework.expression.spel.SpelUtilities; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.support.ReflectionHelper.ArgumentsMatchKind; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Tests for reflection helper code. @@ -76,8 +71,8 @@ public class ReflectionHelperTests extends AbstractExpressionTests { // CompoundExpression value:2 // IntLiteral value:2 // ===> Expression '3+4+5+6+7-2' - AST end - assertTrue(s.contains("===> Expression '3+4+5+6+7-2' - AST start")); - assertTrue(s.contains(" OpPlus value:((((3 + 4) + 5) + 6) + 7) #children:2")); + assertThat(s.contains("===> Expression '3+4+5+6+7-2' - AST start")).isTrue(); + assertThat(s.contains(" OpPlus value:((((3 + 4) + 5) + 6) + 7) #children:2")).isTrue(); } @Test @@ -85,17 +80,17 @@ public class ReflectionHelperTests extends AbstractExpressionTests { TypedValue tv1 = new TypedValue("hello"); TypedValue tv2 = new TypedValue("hello"); TypedValue tv3 = new TypedValue("bye"); - assertEquals(String.class, tv1.getTypeDescriptor().getType()); - assertEquals("TypedValue: 'hello' of [java.lang.String]", tv1.toString()); - assertEquals(tv1, tv2); - assertEquals(tv2, tv1); - assertNotEquals(tv1, tv3); - assertNotEquals(tv2, tv3); - assertNotEquals(tv3, tv1); - assertNotEquals(tv3, tv2); - assertEquals(tv1.hashCode(), tv2.hashCode()); - assertNotEquals(tv1.hashCode(), tv3.hashCode()); - assertNotEquals(tv2.hashCode(), tv3.hashCode()); + assertThat(tv1.getTypeDescriptor().getType()).isEqualTo(String.class); + assertThat(tv1.toString()).isEqualTo("TypedValue: 'hello' of [java.lang.String]"); + assertThat(tv2).isEqualTo(tv1); + assertThat(tv1).isEqualTo(tv2); + assertThat(tv3).isNotEqualTo(tv1); + assertThat(tv3).isNotEqualTo(tv2); + assertThat(tv1).isNotEqualTo(tv3); + assertThat(tv2).isNotEqualTo(tv3); + assertThat(tv2.hashCode()).isEqualTo(tv1.hashCode()); + assertThat(tv3.hashCode()).isNotEqualTo((long) tv1.hashCode()); + assertThat(tv3.hashCode()).isNotEqualTo((long) tv2.hashCode()); } @Test @@ -258,14 +253,14 @@ public class ReflectionHelperTests extends AbstractExpressionTests { Object[] newArray = ReflectionHelper.setupArgumentsForVarargsInvocation( new Class[] {String[].class}, "a", "b", "c"); - assertEquals(1, newArray.length); + assertThat(newArray.length).isEqualTo(1); Object firstParam = newArray[0]; - assertEquals(String.class,firstParam.getClass().getComponentType()); + assertThat(firstParam.getClass().getComponentType()).isEqualTo(String.class); Object[] firstParamArray = (Object[]) firstParam; - assertEquals(3,firstParamArray.length); - assertEquals("a",firstParamArray[0]); - assertEquals("b",firstParamArray[1]); - assertEquals("c",firstParamArray[2]); + assertThat(firstParamArray.length).isEqualTo(3); + assertThat(firstParamArray[0]).isEqualTo("a"); + assertThat(firstParamArray[1]).isEqualTo("b"); + assertThat(firstParamArray[2]).isEqualTo("c"); } @Test @@ -274,19 +269,21 @@ public class ReflectionHelperTests extends AbstractExpressionTests { Tester t = new Tester(); t.setProperty("hello"); EvaluationContext ctx = new StandardEvaluationContext(t); - assertTrue(rpa.canRead(ctx, t, "property")); - assertEquals("hello",rpa.read(ctx, t, "property").getValue()); - assertEquals("hello",rpa.read(ctx, t, "property").getValue()); // cached accessor used + assertThat(rpa.canRead(ctx, t, "property")).isTrue(); + assertThat(rpa.read(ctx, t, "property").getValue()).isEqualTo("hello"); + // cached accessor used + assertThat(rpa.read(ctx, t, "property").getValue()).isEqualTo("hello"); - assertTrue(rpa.canRead(ctx, t, "field")); - assertEquals(3,rpa.read(ctx, t, "field").getValue()); - assertEquals(3,rpa.read(ctx, t, "field").getValue()); // cached accessor used + assertThat(rpa.canRead(ctx, t, "field")).isTrue(); + assertThat(rpa.read(ctx, t, "field").getValue()).isEqualTo(3); + // cached accessor used + assertThat(rpa.read(ctx, t, "field").getValue()).isEqualTo(3); - assertTrue(rpa.canWrite(ctx, t, "property")); + assertThat(rpa.canWrite(ctx, t, "property")).isTrue(); rpa.write(ctx, t, "property", "goodbye"); rpa.write(ctx, t, "property", "goodbye"); // cached accessor used - assertTrue(rpa.canWrite(ctx, t, "field")); + assertThat(rpa.canWrite(ctx, t, "field")).isTrue(); rpa.write(ctx, t, "field", 12); rpa.write(ctx, t, "field", 12); @@ -294,37 +291,37 @@ public class ReflectionHelperTests extends AbstractExpressionTests { // of populating type descriptor cache rpa.write(ctx, t, "field2", 3); rpa.write(ctx, t, "property2", "doodoo"); - assertEquals(3,rpa.read(ctx, t, "field2").getValue()); + assertThat(rpa.read(ctx, t, "field2").getValue()).isEqualTo(3); // Attempted read as first activity on this field and property (no canRead before them) - assertEquals(0,rpa.read(ctx, t, "field3").getValue()); - assertEquals("doodoo",rpa.read(ctx, t, "property3").getValue()); + assertThat(rpa.read(ctx, t, "field3").getValue()).isEqualTo(0); + assertThat(rpa.read(ctx, t, "property3").getValue()).isEqualTo("doodoo"); // Access through is method - assertEquals(0,rpa .read(ctx, t, "field3").getValue()); - assertEquals(false,rpa.read(ctx, t, "property4").getValue()); - assertTrue(rpa.canRead(ctx, t, "property4")); + assertThat(rpa .read(ctx, t, "field3").getValue()).isEqualTo(0); + assertThat(rpa.read(ctx, t, "property4").getValue()).isEqualTo(false); + assertThat(rpa.canRead(ctx, t, "property4")).isTrue(); // repro SPR-9123, ReflectivePropertyAccessor JavaBean property names compliance tests - assertEquals("iD",rpa.read(ctx, t, "iD").getValue()); - assertTrue(rpa.canRead(ctx, t, "iD")); - assertEquals("id",rpa.read(ctx, t, "id").getValue()); - assertTrue(rpa.canRead(ctx, t, "id")); - assertEquals("ID",rpa.read(ctx, t, "ID").getValue()); - assertTrue(rpa.canRead(ctx, t, "ID")); + assertThat(rpa.read(ctx, t, "iD").getValue()).isEqualTo("iD"); + assertThat(rpa.canRead(ctx, t, "iD")).isTrue(); + assertThat(rpa.read(ctx, t, "id").getValue()).isEqualTo("id"); + assertThat(rpa.canRead(ctx, t, "id")).isTrue(); + assertThat(rpa.read(ctx, t, "ID").getValue()).isEqualTo("ID"); + assertThat(rpa.canRead(ctx, t, "ID")).isTrue(); // note: "Id" is not a valid JavaBean name, nevertheless it is treated as "id" - assertEquals("id",rpa.read(ctx, t, "Id").getValue()); - assertTrue(rpa.canRead(ctx, t, "Id")); + assertThat(rpa.read(ctx, t, "Id").getValue()).isEqualTo("id"); + assertThat(rpa.canRead(ctx, t, "Id")).isTrue(); // repro SPR-10994 - assertEquals("xyZ",rpa.read(ctx, t, "xyZ").getValue()); - assertTrue(rpa.canRead(ctx, t, "xyZ")); - assertEquals("xY",rpa.read(ctx, t, "xY").getValue()); - assertTrue(rpa.canRead(ctx, t, "xY")); + assertThat(rpa.read(ctx, t, "xyZ").getValue()).isEqualTo("xyZ"); + assertThat(rpa.canRead(ctx, t, "xyZ")).isTrue(); + assertThat(rpa.read(ctx, t, "xY").getValue()).isEqualTo("xY"); + assertThat(rpa.canRead(ctx, t, "xY")).isTrue(); // SPR-10122, ReflectivePropertyAccessor JavaBean property names compliance tests - setters rpa.write(ctx, t, "pEBS", "Test String"); - assertEquals("Test String",rpa.read(ctx, t, "pEBS").getValue()); + assertThat(rpa.read(ctx, t, "pEBS").getValue()).isEqualTo("Test String"); } @Test @@ -333,33 +330,36 @@ public class ReflectionHelperTests extends AbstractExpressionTests { Tester tester = new Tester(); tester.setProperty("hello"); EvaluationContext ctx = new StandardEvaluationContext(tester); - assertTrue(reflective.canRead(ctx, tester, "property")); - assertEquals("hello", reflective.read(ctx, tester, "property").getValue()); - assertEquals("hello", reflective.read(ctx, tester, "property").getValue()); // cached accessor used + assertThat(reflective.canRead(ctx, tester, "property")).isTrue(); + assertThat(reflective.read(ctx, tester, "property").getValue()).isEqualTo("hello"); + // cached accessor used + assertThat(reflective.read(ctx, tester, "property").getValue()).isEqualTo("hello"); PropertyAccessor property = reflective.createOptimalAccessor(ctx, tester, "property"); - assertTrue(property.canRead(ctx, tester, "property")); - assertFalse(property.canRead(ctx, tester, "property2")); + assertThat(property.canRead(ctx, tester, "property")).isTrue(); + assertThat(property.canRead(ctx, tester, "property2")).isFalse(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> property.canWrite(ctx, tester, "property")); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> property.canWrite(ctx, tester, "property2")); - assertEquals("hello",property.read(ctx, tester, "property").getValue()); - assertEquals("hello",property.read(ctx, tester, "property").getValue()); // cached accessor used + assertThat(property.read(ctx, tester, "property").getValue()).isEqualTo("hello"); + // cached accessor used + assertThat(property.read(ctx, tester, "property").getValue()).isEqualTo("hello"); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> property.getSpecificTargetClasses()); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> property.write(ctx, tester, "property", null)); PropertyAccessor field = reflective.createOptimalAccessor(ctx, tester, "field"); - assertTrue(field.canRead(ctx, tester, "field")); - assertFalse(field.canRead(ctx, tester, "field2")); + assertThat(field.canRead(ctx, tester, "field")).isTrue(); + assertThat(field.canRead(ctx, tester, "field2")).isFalse(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> field.canWrite(ctx, tester, "field")); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> field.canWrite(ctx, tester, "field2")); - assertEquals(3,field.read(ctx, tester, "field").getValue()); - assertEquals(3,field.read(ctx, tester, "field").getValue()); // cached accessor used + assertThat(field.read(ctx, tester, "field").getValue()).isEqualTo(3); + // cached accessor used + assertThat(field.read(ctx, tester, "field").getValue()).isEqualTo(3); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> field.getSpecificTargetClasses()); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> @@ -373,20 +373,20 @@ public class ReflectionHelperTests extends AbstractExpressionTests { private void checkMatch(Class[] inputTypes, Class[] expectedTypes, StandardTypeConverter typeConverter, ArgumentsMatchKind expectedMatchKind) { ReflectionHelper.ArgumentsMatchInfo matchInfo = ReflectionHelper.compareArguments(getTypeDescriptors(expectedTypes), getTypeDescriptors(inputTypes), typeConverter); if (expectedMatchKind == null) { - assertNull("Did not expect them to match in any way", matchInfo); + assertThat(matchInfo).as("Did not expect them to match in any way").isNull(); } else { - assertNotNull("Should not be a null match", matchInfo); + assertThat(matchInfo).as("Should not be a null match").isNotNull(); } if (expectedMatchKind == ArgumentsMatchKind.EXACT) { - assertTrue(matchInfo.isExactMatch()); + assertThat(matchInfo.isExactMatch()).isTrue(); } else if (expectedMatchKind == ArgumentsMatchKind.CLOSE) { - assertTrue(matchInfo.isCloseMatch()); + assertThat(matchInfo.isCloseMatch()).isTrue(); } else if (expectedMatchKind == ArgumentsMatchKind.REQUIRES_CONVERSION) { - assertTrue("expected to be a match requiring conversion, but was " + matchInfo, matchInfo.isMatchRequiringConversion()); + assertThat(matchInfo.isMatchRequiringConversion()).as("expected to be a match requiring conversion, but was " + matchInfo).isTrue(); } } @@ -396,32 +396,32 @@ public class ReflectionHelperTests extends AbstractExpressionTests { private void checkMatch2(Class[] inputTypes, Class[] expectedTypes, StandardTypeConverter typeConverter, ArgumentsMatchKind expectedMatchKind) { ReflectionHelper.ArgumentsMatchInfo matchInfo = ReflectionHelper.compareArgumentsVarargs(getTypeDescriptors(expectedTypes), getTypeDescriptors(inputTypes), typeConverter); if (expectedMatchKind == null) { - assertNull("Did not expect them to match in any way: " + matchInfo, matchInfo); + assertThat(matchInfo).as("Did not expect them to match in any way: " + matchInfo).isNull(); } else { - assertNotNull("Should not be a null match", matchInfo); + assertThat(matchInfo).as("Should not be a null match").isNotNull(); } if (expectedMatchKind == ArgumentsMatchKind.EXACT) { - assertTrue(matchInfo.isExactMatch()); + assertThat(matchInfo.isExactMatch()).isTrue(); } else if (expectedMatchKind == ArgumentsMatchKind.CLOSE) { - assertTrue(matchInfo.isCloseMatch()); + assertThat(matchInfo.isCloseMatch()).isTrue(); } else if (expectedMatchKind == ArgumentsMatchKind.REQUIRES_CONVERSION) { - assertTrue("expected to be a match requiring conversion, but was " + matchInfo, matchInfo.isMatchRequiringConversion()); + assertThat(matchInfo.isMatchRequiringConversion()).as("expected to be a match requiring conversion, but was " + matchInfo).isTrue(); } } private void checkArguments(Object[] args, Object... expected) { - assertEquals(expected.length,args.length); + assertThat(args.length).isEqualTo(expected.length); for (int i = 0; i < expected.length; i++) { checkArgument(expected[i],args[i]); } } private void checkArgument(Object expected, Object actual) { - assertEquals(expected,actual); + assertThat(actual).isEqualTo(expected); } private List getTypeDescriptors(Class... types) { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java index 96db109c74b..e561ce1e114 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java @@ -28,31 +28,29 @@ import org.springframework.expression.TypeComparator; import org.springframework.expression.TypeConverter; import org.springframework.expression.TypeLocator; +import static org.assertj.core.api.Assertions.assertThat; 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; public class StandardComponentsTests { @Test public void testStandardEvaluationContext() { StandardEvaluationContext context = new StandardEvaluationContext(); - assertNotNull(context.getTypeComparator()); + assertThat(context.getTypeComparator()).isNotNull(); TypeComparator tc = new StandardTypeComparator(); context.setTypeComparator(tc); - assertEquals(tc, context.getTypeComparator()); + assertThat(context.getTypeComparator()).isEqualTo(tc); TypeLocator tl = new StandardTypeLocator(); context.setTypeLocator(tl); - assertEquals(tl, context.getTypeLocator()); + assertThat(context.getTypeLocator()).isEqualTo(tl); } @Test public void testStandardOperatorOverloader() throws EvaluationException { OperatorOverloader oo = new StandardOperatorOverloader(); - assertFalse(oo.overridesOperation(Operation.ADD, null, null)); + assertThat(oo.overridesOperation(Operation.ADD, null, null)).isFalse(); assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> oo.operate(Operation.ADD, 2, 3)); } @@ -61,13 +59,13 @@ public class StandardComponentsTests { public void testStandardTypeLocator() { StandardTypeLocator tl = new StandardTypeLocator(); List prefixes = tl.getImportPrefixes(); - assertEquals(1, prefixes.size()); + assertThat(prefixes.size()).isEqualTo(1); tl.registerImport("java.util"); prefixes = tl.getImportPrefixes(); - assertEquals(2, prefixes.size()); + assertThat(prefixes.size()).isEqualTo(2); tl.removeImport("java.util"); prefixes = tl.getImportPrefixes(); - assertEquals(1, prefixes.size()); + assertThat(prefixes.size()).isEqualTo(1); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/config/InitializeDatabaseIntegrationTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/config/InitializeDatabaseIntegrationTests.java index 26496f93137..5fce291bdee 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/config/InitializeDatabaseIntegrationTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/config/InitializeDatabaseIntegrationTests.java @@ -29,8 +29,8 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.core.JdbcTemplate; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Dave Syer @@ -87,7 +87,7 @@ public class InitializeDatabaseIntegrationTests { DataSource dataSource = context.getBean("dataSource", DataSource.class); assertCorrectSetup(dataSource); JdbcTemplate t = new JdbcTemplate(dataSource); - assertEquals("Dave", t.queryForObject("select name from T_TEST", String.class)); + assertThat(t.queryForObject("select name from T_TEST", String.class)).isEqualTo("Dave"); } @Test @@ -109,12 +109,12 @@ public class InitializeDatabaseIntegrationTests { context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-cache-config.xml"); assertCorrectSetup(context.getBean("dataSource", DataSource.class)); CacheData cache = context.getBean(CacheData.class); - assertEquals(1, cache.getCachedData().size()); + assertThat(cache.getCachedData().size()).isEqualTo(1); } private void assertCorrectSetup(DataSource dataSource) { JdbcTemplate jt = new JdbcTemplate(dataSource); - assertEquals(1, jt.queryForObject("select count(*) from T_TEST", Integer.class).intValue()); + assertThat(jt.queryForObject("select count(*) from T_TEST", Integer.class).intValue()).isEqualTo(1); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java index 16bf08db0dc..887cb07c2e7 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java @@ -38,8 +38,6 @@ import org.springframework.tests.TestGroup; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory.DEFAULT_DATABASE_NAME; /** @@ -186,7 +184,7 @@ public class JdbcNamespaceIntegrationTests { } private void assertNumRowsInTestTable(JdbcTemplate template, int count) { - assertEquals(count, template.queryForObject("select count(*) from T_TEST", Integer.class).intValue()); + assertThat(template.queryForObject("select count(*) from T_TEST", Integer.class).intValue()).isEqualTo(count); } private void assertCorrectSetup(String file, String... dataSources) { @@ -199,7 +197,7 @@ public class JdbcNamespaceIntegrationTests { for (String dataSourceName : dataSources) { DataSource dataSource = context.getBean(dataSourceName, DataSource.class); assertNumRowsInTestTable(new JdbcTemplate(dataSource), count); - assertTrue(dataSource instanceof AbstractDriverBasedDataSource); + assertThat(dataSource instanceof AbstractDriverBasedDataSource).isTrue(); AbstractDriverBasedDataSource adbDataSource = (AbstractDriverBasedDataSource) dataSource; assertThat(adbDataSource.getUrl()).contains(dataSourceName); } @@ -214,9 +212,9 @@ public class JdbcNamespaceIntegrationTests { try { DataSource dataSource = context.getBean(DataSource.class); assertNumRowsInTestTable(new JdbcTemplate(dataSource), 1); - assertTrue(dataSource instanceof AbstractDriverBasedDataSource); + assertThat(dataSource instanceof AbstractDriverBasedDataSource).isTrue(); AbstractDriverBasedDataSource adbDataSource = (AbstractDriverBasedDataSource) dataSource; - assertTrue(urlPredicate.test(adbDataSource.getUrl())); + assertThat(urlPredicate.test(adbDataSource.getUrl())).isTrue(); } finally { context.close(); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java index 1ef7379aff0..a0f97306395 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java @@ -23,6 +23,7 @@ import java.sql.ResultSetMetaData; import java.sql.SQLFeatureNotSupportedException; import java.sql.Statement; import java.sql.Timestamp; +import java.util.Date; import org.springframework.jdbc.core.test.ConcretePerson; import org.springframework.jdbc.core.test.DatePerson; @@ -31,7 +32,7 @@ import org.springframework.jdbc.core.test.SpacePerson; import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; @@ -48,31 +49,31 @@ import static org.mockito.Mockito.verify; public abstract class AbstractRowMapperTests { protected void verifyPerson(Person bean) throws Exception { - assertEquals("Bubba", bean.getName()); - assertEquals(22L, bean.getAge()); - assertEquals(new java.util.Date(1221222L), bean.getBirth_date()); - assertEquals(new BigDecimal("1234.56"), bean.getBalance()); + assertThat(bean.getName()).isEqualTo("Bubba"); + assertThat(bean.getAge()).isEqualTo(22L); + assertThat(bean.getBirth_date()).usingComparator(Date::compareTo).isEqualTo(new java.util.Date(1221222L)); + assertThat(bean.getBalance()).isEqualTo(new BigDecimal("1234.56")); } protected void verifyPerson(ConcretePerson bean) throws Exception { - assertEquals("Bubba", bean.getName()); - assertEquals(22L, bean.getAge()); - assertEquals(new java.util.Date(1221222L), bean.getBirth_date()); - assertEquals(new BigDecimal("1234.56"), bean.getBalance()); + assertThat(bean.getName()).isEqualTo("Bubba"); + assertThat(bean.getAge()).isEqualTo(22L); + assertThat(bean.getBirth_date()).usingComparator(Date::compareTo).isEqualTo(new java.util.Date(1221222L)); + assertThat(bean.getBalance()).isEqualTo(new BigDecimal("1234.56")); } protected void verifyPerson(SpacePerson bean) { - assertEquals("Bubba", bean.getLastName()); - assertEquals(22L, bean.getAge()); - assertEquals(new java.sql.Timestamp(1221222L).toLocalDateTime(), bean.getBirthDate()); - assertEquals(new BigDecimal("1234.56"), bean.getBalance()); + assertThat(bean.getLastName()).isEqualTo("Bubba"); + assertThat(bean.getAge()).isEqualTo(22L); + assertThat(bean.getBirthDate()).isEqualTo(new Timestamp(1221222L).toLocalDateTime()); + assertThat(bean.getBalance()).isEqualTo(new BigDecimal("1234.56")); } protected void verifyPerson(DatePerson bean) { - assertEquals("Bubba", bean.getLastName()); - assertEquals(22L, bean.getAge()); - assertEquals(new java.sql.Date(1221222L).toLocalDate(), bean.getBirthDate()); - assertEquals(new BigDecimal("1234.56"), bean.getBalance()); + assertThat(bean.getLastName()).isEqualTo("Bubba"); + assertThat(bean.getAge()).isEqualTo(22L); + assertThat(bean.getBirthDate()).isEqualTo(new java.sql.Date(1221222L).toLocalDate()); + assertThat(bean.getBalance()).isEqualTo(new BigDecimal("1234.56")); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/BeanPropertyRowMapperTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/BeanPropertyRowMapperTests.java index 1d6f5a23a03..b5dd056f02c 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/BeanPropertyRowMapperTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/BeanPropertyRowMapperTests.java @@ -28,8 +28,8 @@ import org.springframework.jdbc.core.test.ExtendedPerson; import org.springframework.jdbc.core.test.Person; import org.springframework.jdbc.core.test.SpacePerson; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Thomas Risberg @@ -58,7 +58,7 @@ public class BeanPropertyRowMapperTests extends AbstractRowMapperTests { List result = mock.getJdbcTemplate().query( "select name, age, birth_date, balance from people", new BeanPropertyRowMapper<>(Person.class)); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); verifyPerson(result.get(0)); mock.verifyClosed(); } @@ -69,7 +69,7 @@ public class BeanPropertyRowMapperTests extends AbstractRowMapperTests { List result = mock.getJdbcTemplate().query( "select name, age, birth_date, balance from people", new BeanPropertyRowMapper<>(ConcretePerson.class)); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); verifyPerson(result.get(0)); mock.verifyClosed(); } @@ -80,7 +80,7 @@ public class BeanPropertyRowMapperTests extends AbstractRowMapperTests { List result = mock.getJdbcTemplate().query( "select name, age, birth_date, balance from people", new BeanPropertyRowMapper<>(ConcretePerson.class, true)); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); verifyPerson(result.get(0)); mock.verifyClosed(); } @@ -91,7 +91,7 @@ public class BeanPropertyRowMapperTests extends AbstractRowMapperTests { List result = mock.getJdbcTemplate().query( "select name, age, birth_date, balance from people", new BeanPropertyRowMapper<>(ExtendedPerson.class)); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); ExtendedPerson bean = result.get(0); verifyPerson(bean); mock.verifyClosed(); @@ -119,7 +119,7 @@ public class BeanPropertyRowMapperTests extends AbstractRowMapperTests { List result = mock.getJdbcTemplate().query( "select last_name as \"Last Name\", age, birth_date, balance from people", new BeanPropertyRowMapper<>(SpacePerson.class)); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); verifyPerson(result.get(0)); mock.verifyClosed(); } @@ -130,7 +130,7 @@ public class BeanPropertyRowMapperTests extends AbstractRowMapperTests { List result = mock.getJdbcTemplate().query( "select last_name as \"Last Name\", age, birth_date, balance from people", new BeanPropertyRowMapper<>(DatePerson.class)); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); verifyPerson(result.get(0)); mock.verifyClosed(); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateQueryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateQueryTests.java index 1297952a451..f5b6e4e805b 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateQueryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateQueryTests.java @@ -33,10 +33,8 @@ import org.junit.Test; import org.springframework.dao.IncorrectResultSizeDataAccessException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -91,9 +89,9 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, true, false); given(this.resultSet.getObject(1)).willReturn(11, 12); List> li = this.template.queryForList(sql); - assertEquals("All rows returned", 2, li.size()); - assertEquals("First row is Integer", 11, ((Integer) li.get(0).get("age")).intValue()); - assertEquals("Second row is Integer", 12, ((Integer) li.get(1).get("age")).intValue()); + assertThat(li.size()).as("All rows returned").isEqualTo(2); + assertThat(((Integer) li.get(0).get("age")).intValue()).as("First row is Integer").isEqualTo(11); + assertThat(((Integer) li.get(1).get("age")).intValue()).as("Second row is Integer").isEqualTo(12); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -103,7 +101,7 @@ public class JdbcTemplateQueryTests { String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3"; given(this.resultSet.next()).willReturn(false); List> li = this.template.queryForList(sql); - assertEquals("All rows returned", 0, li.size()); + assertThat(li.size()).as("All rows returned").isEqualTo(0); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -114,8 +112,8 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getObject(1)).willReturn(11); List> li = this.template.queryForList(sql); - assertEquals("All rows returned", 1, li.size()); - assertEquals("First row is Integer", 11, ((Integer) li.get(0).get("age")).intValue()); + assertThat(li.size()).as("All rows returned").isEqualTo(1); + assertThat(((Integer) li.get(0).get("age")).intValue()).as("First row is Integer").isEqualTo(11); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -126,8 +124,8 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getInt(1)).willReturn(11); List li = this.template.queryForList(sql, Integer.class); - assertEquals("All rows returned", 1, li.size()); - assertEquals("Element is Integer", 11, li.get(0).intValue()); + assertThat(li.size()).as("All rows returned").isEqualTo(1); + assertThat(li.get(0).intValue()).as("Element is Integer").isEqualTo(11); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -138,7 +136,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getObject(1)).willReturn(11); Map map = this.template.queryForMap(sql); - assertEquals("Wow is Integer", 11, ((Integer) map.get("age")).intValue()); + assertThat(((Integer) map.get("age")).intValue()).as("Wow is Integer").isEqualTo(11); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -165,7 +163,8 @@ public class JdbcTemplateQueryTests { return rs.getInt(1); } }); - assertTrue("Correct result type", o instanceof Integer); + boolean condition = o instanceof Integer; + assertThat(condition).as("Correct result type").isTrue(); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -175,7 +174,7 @@ public class JdbcTemplateQueryTests { String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getString(1)).willReturn("myvalue"); - assertEquals("myvalue", this.template.queryForObject(sql, String.class)); + assertThat(this.template.queryForObject(sql, String.class)).isEqualTo("myvalue"); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -185,7 +184,7 @@ public class JdbcTemplateQueryTests { String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getObject(1, BigInteger.class)).willReturn(new BigInteger("22")); - assertEquals(new BigInteger("22"), this.template.queryForObject(sql, BigInteger.class)); + assertThat(this.template.queryForObject(sql, BigInteger.class)).isEqualTo(new BigInteger("22")); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -195,7 +194,7 @@ public class JdbcTemplateQueryTests { String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getBigDecimal(1)).willReturn(new BigDecimal("22.5")); - assertEquals(new BigDecimal("22.5"), this.template.queryForObject(sql, BigDecimal.class)); + assertThat(this.template.queryForObject(sql, BigDecimal.class)).isEqualTo(new BigDecimal("22.5")); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -205,7 +204,7 @@ public class JdbcTemplateQueryTests { String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3"; given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getInt(1)).willReturn(22); - assertEquals(Integer.valueOf(22), this.template.queryForObject(sql, Integer.class)); + assertThat(this.template.queryForObject(sql, Integer.class)).isEqualTo(Integer.valueOf(22)); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -216,7 +215,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getInt(1)).willReturn(0); given(this.resultSet.wasNull()).willReturn(true); - assertNull(this.template.queryForObject(sql, Integer.class)); + assertThat(this.template.queryForObject(sql, Integer.class)).isNull(); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -227,7 +226,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getInt(1)).willReturn(22); int i = this.template.queryForObject(sql, Integer.class).intValue(); - assertEquals("Return of an int", 22, i); + assertThat(i).as("Return of an int").isEqualTo(22); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -238,7 +237,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getInt(1)).willReturn(22); int i = this.template.queryForObject(sql, int.class); - assertEquals("Return of an int", 22, i); + assertThat(i).as("Return of an int").isEqualTo(22); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -249,7 +248,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getLong(1)).willReturn(87L); long l = this.template.queryForObject(sql, Long.class).longValue(); - assertEquals("Return of a long", 87, l); + assertThat(l).as("Return of a long").isEqualTo(87); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -260,7 +259,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getLong(1)).willReturn(87L); long l = this.template.queryForObject(sql, long.class); - assertEquals("Return of a long", 87, l); + assertThat(l).as("Return of a long").isEqualTo(87); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -279,9 +278,9 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, true, false); given(this.resultSet.getObject(1)).willReturn(11, 12); List> li = this.template.queryForList(sql, new Object[] {3}); - assertEquals("All rows returned", 2, li.size()); - assertEquals("First row is Integer", 11, ((Integer) li.get(0).get("age")).intValue()); - assertEquals("Second row is Integer", 12, ((Integer) li.get(1).get("age")).intValue()); + assertThat(li.size()).as("All rows returned").isEqualTo(2); + assertThat(((Integer) li.get(0).get("age")).intValue()).as("First row is Integer").isEqualTo(11); + assertThat(((Integer) li.get(1).get("age")).intValue()).as("Second row is Integer").isEqualTo(12); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); verify(this.preparedStatement).close(); @@ -292,7 +291,7 @@ public class JdbcTemplateQueryTests { String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?"; given(this.resultSet.next()).willReturn(false); List> li = this.template.queryForList(sql, new Object[] {3}); - assertEquals("All rows returned", 0, li.size()); + assertThat(li.size()).as("All rows returned").isEqualTo(0); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); verify(this.preparedStatement).close(); @@ -304,8 +303,8 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getObject(1)).willReturn(11); List> li = this.template.queryForList(sql, new Object[] {3}); - assertEquals("All rows returned", 1, li.size()); - assertEquals("First row is Integer", 11, ((Integer) li.get(0).get("age")).intValue()); + assertThat(li.size()).as("All rows returned").isEqualTo(1); + assertThat(((Integer) li.get(0).get("age")).intValue()).as("First row is Integer").isEqualTo(11); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); verify(this.preparedStatement).close(); @@ -317,8 +316,8 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getInt(1)).willReturn(11); List li = this.template.queryForList(sql, new Object[] {3}, Integer.class); - assertEquals("All rows returned", 1, li.size()); - assertEquals("First row is Integer", 11, li.get(0).intValue()); + assertThat(li.size()).as("All rows returned").isEqualTo(1); + assertThat(li.get(0).intValue()).as("First row is Integer").isEqualTo(11); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); verify(this.preparedStatement).close(); @@ -330,7 +329,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getObject(1)).willReturn(11); Map map = this.template.queryForMap(sql, new Object[] {3}); - assertEquals("Row is Integer", 11, ((Integer) map.get("age")).intValue()); + assertThat(((Integer) map.get("age")).intValue()).as("Row is Integer").isEqualTo(11); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); verify(this.preparedStatement).close(); @@ -347,7 +346,8 @@ public class JdbcTemplateQueryTests { return rs.getInt(1); } }); - assertTrue("Correct result type", o instanceof Integer); + boolean condition = o instanceof Integer; + assertThat(condition).as("Correct result type").isTrue(); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); verify(this.preparedStatement).close(); @@ -359,7 +359,8 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getInt(1)).willReturn(22); Object o = this.template.queryForObject(sql, new Object[] {3}, Integer.class); - assertTrue("Correct result type", o instanceof Integer); + boolean condition = o instanceof Integer; + assertThat(condition).as("Correct result type").isTrue(); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); verify(this.preparedStatement).close(); @@ -371,7 +372,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getInt(1)).willReturn(22); int i = this.template.queryForObject(sql, new Object[] {3}, Integer.class).intValue(); - assertEquals("Return of an int", 22, i); + assertThat(i).as("Return of an int").isEqualTo(22); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); verify(this.preparedStatement).close(); @@ -383,7 +384,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getLong(1)).willReturn(87L); long l = this.template.queryForObject(sql, new Object[] {3}, Long.class).longValue(); - assertEquals("Return of a long", 87, l); + assertThat(l).as("Return of a long").isEqualTo(87); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); verify(this.preparedStatement).close(); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java index 183abbf8e5b..981cf2a34aa 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java @@ -54,10 +54,6 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; @@ -116,10 +112,11 @@ public class JdbcTemplateTests { @Test public void testBeanProperties() throws Exception { - assertTrue("datasource ok", this.template.getDataSource() == this.dataSource); - assertTrue("ignores warnings by default", this.template.isIgnoreWarnings()); + assertThat(this.template.getDataSource() == this.dataSource).as("datasource ok").isTrue(); + assertThat(this.template.isIgnoreWarnings()).as("ignores warnings by default").isTrue(); this.template.setIgnoreWarnings(false); - assertTrue("can set NOT to ignore warnings", !this.template.isIgnoreWarnings()); + boolean condition = !this.template.isIgnoreWarnings(); + assertThat(condition).as("can set NOT to ignore warnings").isTrue(); } @Test @@ -129,7 +126,7 @@ public class JdbcTemplateTests { given(this.preparedStatement.executeUpdate()).willReturn(1); Dispatcher d = new Dispatcher(idParam, sql); int rowsAffected = this.template.update(d); - assertTrue("1 update affected 1 row", rowsAffected == 1); + assertThat(rowsAffected == 1).as("1 update affected 1 row").isTrue(); verify(this.preparedStatement).setInt(1, idParam); verify(this.preparedStatement).close(); verify(this.connection).close(); @@ -226,9 +223,9 @@ public class JdbcTemplateTests { // Match String[] forenames = sh.getStrings(); - assertTrue("same length", forenames.length == results.length); + assertThat(forenames.length == results.length).as("same length").isTrue(); for (int i = 0; i < forenames.length; i++) { - assertTrue("Row " + i + " matches", forenames[i].equals(results[i])); + assertThat(forenames[i].equals(results[i])).as("Row " + i + " matches").isTrue(); } if (fetchSize != null) { @@ -272,12 +269,12 @@ public class JdbcTemplateTests { String result = this.template.execute(new ConnectionCallback() { @Override public String doInConnection(Connection con) { - assertTrue(con instanceof ConnectionProxy); - assertSame(JdbcTemplateTests.this.connection, ((ConnectionProxy) con).getTargetConnection()); + assertThat(con instanceof ConnectionProxy).isTrue(); + assertThat(((ConnectionProxy) con).getTargetConnection()).isSameAs(JdbcTemplateTests.this.connection); return "test"; } }); - assertEquals("test", result); + assertThat(result).isEqualTo("test"); } @Test @@ -293,7 +290,7 @@ public class JdbcTemplateTests { } }); - assertEquals("test", result); + assertThat(result).isEqualTo("test"); verify(this.preparedStatement).setFetchSize(10); verify(this.preparedStatement).setMaxRows(20); verify(this.preparedStatement).close(); @@ -352,7 +349,7 @@ public class JdbcTemplateTests { given(this.connection.createStatement()).willReturn(this.statement); int actualRowsAffected = this.template.update(sql); - assertTrue("Actual rows affected is correct", actualRowsAffected == rowsAffected); + assertThat(actualRowsAffected == rowsAffected).as("Actual rows affected is correct").isTrue(); verify(this.statement).close(); verify(this.connection).close(); } @@ -368,7 +365,7 @@ public class JdbcTemplateTests { int actualRowsAffected = this.template.update(sql, 4, new SqlParameterValue(Types.NUMERIC, 2, Float.valueOf(1.4142f))); - assertTrue("Actual rows affected is correct", actualRowsAffected == rowsAffected); + assertThat(actualRowsAffected == rowsAffected).as("Actual rows affected is correct").isTrue(); verify(this.preparedStatement).setObject(1, 4); verify(this.preparedStatement).setObject(2, Float.valueOf(1.4142f), Types.NUMERIC, 2); verify(this.preparedStatement).close(); @@ -399,7 +396,7 @@ public class JdbcTemplateTests { given(this.connection.createStatement()).willReturn(this.statement); int actualRowsAffected = this.template.update(sql); - assertTrue("Actual rows affected is correct", actualRowsAffected == rowsAffected); + assertThat(actualRowsAffected == rowsAffected).as("Actual rows affected is correct").isTrue(); verify(this.statement).close(); verify(this.connection).close(); @@ -417,7 +414,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); verify(this.statement).addBatch(sql[0]); verify(this.statement).addBatch(sql[1]); @@ -457,7 +454,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); verify(this.statement, never()).addBatch(anyString()); verify(this.statement).close(); @@ -506,9 +503,9 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, setter); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(this.preparedStatement, times(2)).addBatch(); verify(this.preparedStatement).setInt(1, ids[0]); @@ -547,9 +544,9 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, setter); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(this.preparedStatement, times(2)).addBatch(); verify(this.preparedStatement).setInt(1, ids[0]); @@ -584,9 +581,9 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, setter); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(this.preparedStatement, times(2)).addBatch(); verify(this.preparedStatement).setInt(1, ids[0]); @@ -621,9 +618,9 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, setter); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(this.preparedStatement, never()).addBatch(); verify(this.preparedStatement).setInt(1, ids[0]); @@ -652,9 +649,9 @@ public class JdbcTemplateTests { }; int[] actualRowsAffected = this.template.batchUpdate(sql, setter); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(this.preparedStatement, never()).addBatch(); verify(this.preparedStatement).setInt(1, ids[0]); @@ -703,7 +700,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, Collections.emptyList()); - assertTrue("executed 0 updates", actualRowsAffected.length == 0); + assertThat(actualRowsAffected.length == 0).as("executed 0 updates").isTrue(); } @Test @@ -719,9 +716,9 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, ids); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(this.preparedStatement, times(2)).addBatch(); verify(this.preparedStatement).setObject(1, 100); @@ -744,9 +741,9 @@ public class JdbcTemplateTests { this.template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = this.template.batchUpdate(sql, ids, sqlTypes); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(this.preparedStatement, times(2)).addBatch(); verify(this.preparedStatement).setObject(1, 100, sqlTypes[0]); verify(this.preparedStatement).setObject(1, 200, sqlTypes[0]); @@ -768,10 +765,10 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[][] actualRowsAffected = template.batchUpdate(sql, ids, 2, setter); - assertEquals("executed 2 updates", 2, actualRowsAffected[0].length); - assertEquals(rowsAffected1[0], actualRowsAffected[0][0]); - assertEquals(rowsAffected1[1], actualRowsAffected[0][1]); - assertEquals(rowsAffected2[0], actualRowsAffected[1][0]); + assertThat(actualRowsAffected[0].length).as("executed 2 updates").isEqualTo(2); + assertThat(actualRowsAffected[0][0]).isEqualTo(rowsAffected1[0]); + assertThat(actualRowsAffected[0][1]).isEqualTo(rowsAffected1[1]); + assertThat(actualRowsAffected[1][0]).isEqualTo(rowsAffected2[0]); verify(this.preparedStatement, times(3)).addBatch(); verify(this.preparedStatement).setInt(1, ids.get(0)); @@ -860,7 +857,7 @@ public class JdbcTemplateTests { PreparedStatementSetter pss = ps -> ps.setString(1, name); int actualRowsUpdated = new JdbcTemplate(this.dataSource).update(sql, pss); - assertEquals("updated correct # of rows", actualRowsUpdated, expectedRowsUpdated); + assertThat(expectedRowsUpdated).as("updated correct # of rows").isEqualTo(actualRowsUpdated); verify(this.preparedStatement).setString(1, name); verify(this.preparedStatement).close(); verify(this.connection).close(); @@ -1057,19 +1054,18 @@ public class JdbcTemplateTests { given(this.callableStatement.getUpdateCount()).willReturn(-1); given(this.callableStatement.getObject(1)).willReturn("X"); - assertTrue("default should have been NOT case insensitive", - !this.template.isResultsMapCaseInsensitive()); + boolean condition = !this.template.isResultsMapCaseInsensitive(); + assertThat(condition).as("default should have been NOT case insensitive").isTrue(); this.template.setResultsMapCaseInsensitive(true); - assertTrue("now it should have been set to case insensitive", - this.template.isResultsMapCaseInsensitive()); + assertThat(this.template.isResultsMapCaseInsensitive()).as("now it should have been set to case insensitive").isTrue(); Map out = this.template.call( conn -> conn.prepareCall("my query"), Collections.singletonList(new SqlOutParameter("a", 12))); assertThat(out).isInstanceOf(LinkedCaseInsensitiveMap.class); - assertNotNull("we should have gotten the result with upper case", out.get("A")); - assertNotNull("we should have gotten the result with lower case", out.get("a")); + assertThat(out.get("A")).as("we should have gotten the result with upper case").isNotNull(); + assertThat(out.get("a")).as("we should have gotten the result with lower case").isNotNull(); verify(this.callableStatement).close(); verify(this.connection).close(); } @@ -1089,8 +1085,8 @@ public class JdbcTemplateTests { given(this.resultSet.getObject(2)).willReturn("second value"); Map map = this.template.queryForMap("my query"); - assertEquals(1, map.size()); - assertEquals("first value", map.get("x")); + assertThat(map.size()).isEqualTo(1); + assertThat(map.get("x")).isEqualTo("first value"); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java index 2bb3e87020e..c29e9c9fb7f 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java @@ -32,8 +32,7 @@ import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -84,14 +83,14 @@ public class RowMapperTests { @After public void verifyResults() { - assertNotNull(result); - assertEquals(2, result.size()); + assertThat(result).isNotNull(); + assertThat(result.size()).isEqualTo(2); TestBean testBean1 = result.get(0); TestBean testBean2 = result.get(1); - assertEquals("tb1", testBean1.getName()); - assertEquals("tb2", testBean2.getName()); - assertEquals(1, testBean1.getAge()); - assertEquals(2, testBean2.getAge()); + assertThat(testBean1.getName()).isEqualTo("tb1"); + assertThat(testBean2.getName()).isEqualTo("tb2"); + assertThat(testBean1.getAge()).isEqualTo(1); + assertThat(testBean2.getAge()).isEqualTo(2); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/SingleColumnRowMapperTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/SingleColumnRowMapperTests.java index 80e78733b11..3a32cb31d3b 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/SingleColumnRowMapperTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/SingleColumnRowMapperTests.java @@ -28,9 +28,8 @@ import org.junit.Test; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.dao.TypeMismatchDataAccessException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -58,7 +57,7 @@ public class SingleColumnRowMapperTests { LocalDateTime actualLocalDateTime = rowMapper.mapRow(resultSet, 1); - assertEquals(timestamp.toLocalDateTime(), actualLocalDateTime); + assertThat(actualLocalDateTime).isEqualTo(timestamp.toLocalDateTime()); } @Test // SPR-16483 @@ -81,8 +80,8 @@ public class SingleColumnRowMapperTests { MyLocalDateTime actualMyLocalDateTime = rowMapper.mapRow(resultSet, 1); - assertNotNull(actualMyLocalDateTime); - assertEquals(timestamp.toLocalDateTime(), actualMyLocalDateTime.value); + assertThat(actualMyLocalDateTime).isNotNull(); + assertThat(actualMyLocalDateTime.value).isEqualTo(timestamp.toLocalDateTime()); } @Test // SPR-16483 diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java index a51865c5f03..16ab1809b21 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java @@ -25,9 +25,6 @@ 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Rick Evans @@ -53,28 +50,28 @@ public class BeanPropertySqlParameterSourceTests { @Test public void successfulPropertyAccess() { BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99)); - assertTrue(Arrays.asList(source.getReadablePropertyNames()).contains("name")); - assertTrue(Arrays.asList(source.getReadablePropertyNames()).contains("age")); - assertEquals("tb", source.getValue("name")); - assertEquals(99, source.getValue("age")); - assertEquals(Types.VARCHAR, source.getSqlType("name")); - assertEquals(Types.INTEGER, source.getSqlType("age")); + assertThat(Arrays.asList(source.getReadablePropertyNames()).contains("name")).isTrue(); + assertThat(Arrays.asList(source.getReadablePropertyNames()).contains("age")).isTrue(); + assertThat(source.getValue("name")).isEqualTo("tb"); + assertThat(source.getValue("age")).isEqualTo(99); + assertThat(source.getSqlType("name")).isEqualTo(Types.VARCHAR); + assertThat(source.getSqlType("age")).isEqualTo(Types.INTEGER); } @Test public void successfulPropertyAccessWithOverriddenSqlType() { BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99)); source.registerSqlType("age", Types.NUMERIC); - assertEquals("tb", source.getValue("name")); - assertEquals(99, source.getValue("age")); - assertEquals(Types.VARCHAR, source.getSqlType("name")); - assertEquals(Types.NUMERIC, source.getSqlType("age")); + assertThat(source.getValue("name")).isEqualTo("tb"); + assertThat(source.getValue("age")).isEqualTo(99); + assertThat(source.getSqlType("name")).isEqualTo(Types.VARCHAR); + assertThat(source.getSqlType("age")).isEqualTo(Types.NUMERIC); } @Test public void hasValueWhereTheUnderlyingBeanHasNoSuchProperty() { BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean()); - assertFalse(source.hasValue("thisPropertyDoesNotExist")); + assertThat(source.hasValue("thisPropertyDoesNotExist")).isFalse(); } @Test @@ -87,7 +84,7 @@ public class BeanPropertySqlParameterSourceTests { @Test public void hasValueWhereTheUnderlyingBeanPropertyIsNotReadable() { BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new NoReadableProperties()); - assertFalse(source.hasValue("noOp")); + assertThat(source.hasValue("noOp")).isFalse(); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSourceTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSourceTests.java index 97f59531e74..d437ff9105a 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSourceTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/MapSqlParameterSourceTests.java @@ -23,8 +23,8 @@ import org.junit.Test; import org.springframework.jdbc.core.SqlParameterValue; import org.springframework.jdbc.support.JdbcUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @author Rick Evans @@ -48,28 +48,28 @@ public class MapSqlParameterSourceTests { @Test public void sqlParameterValueRegistersSqlType() { MapSqlParameterSource msps = new MapSqlParameterSource("FOO", new SqlParameterValue(Types.NUMERIC, "Foo")); - assertEquals("Correct SQL Type not registered", 2, msps.getSqlType("FOO")); + assertThat(msps.getSqlType("FOO")).as("Correct SQL Type not registered").isEqualTo(2); MapSqlParameterSource msps2 = new MapSqlParameterSource(); msps2.addValues(msps.getValues()); - assertEquals("Correct SQL Type not registered", 2, msps2.getSqlType("FOO")); + assertThat(msps2.getSqlType("FOO")).as("Correct SQL Type not registered").isEqualTo(2); } @Test public void toStringShowsParameterDetails() { MapSqlParameterSource source = new MapSqlParameterSource("FOO", new SqlParameterValue(Types.NUMERIC, "Foo")); - assertEquals("MapSqlParameterSource {FOO=Foo (type:NUMERIC)}", source.toString()); + assertThat(source.toString()).isEqualTo("MapSqlParameterSource {FOO=Foo (type:NUMERIC)}"); } @Test public void toStringShowsCustomSqlType() { MapSqlParameterSource source = new MapSqlParameterSource("FOO", new SqlParameterValue(Integer.MAX_VALUE, "Foo")); - assertEquals("MapSqlParameterSource {FOO=Foo (type:" + Integer.MAX_VALUE + ")}", source.toString()); + assertThat(source.toString()).isEqualTo(("MapSqlParameterSource {FOO=Foo (type:" + Integer.MAX_VALUE + ")}")); } @Test public void toStringDoesNotShowTypeUnknown() { MapSqlParameterSource source = new MapSqlParameterSource("FOO", new SqlParameterValue(JdbcUtils.TYPE_UNKNOWN, "Foo")); - assertEquals("MapSqlParameterSource {FOO=Foo}", source.toString()); + assertThat(source.toString()).isEqualTo("MapSqlParameterSource {FOO=Foo}"); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java index 946e2ac8675..ce2eeaa1452 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java @@ -41,10 +41,8 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.jdbc.core.SqlParameterValue; +import static org.assertj.core.api.Assertions.assertThat; 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.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; @@ -128,7 +126,7 @@ public class NamedParameterJdbcTemplateTests { @Test public void testTemplateConfiguration() { - assertSame(dataSource, namedParameterTemplate.getJdbcTemplate().getDataSource()); + assertThat(namedParameterTemplate.getJdbcTemplate().getDataSource()).isSameAs(dataSource); } @Test @@ -139,12 +137,12 @@ public class NamedParameterJdbcTemplateTests { params.put("priceId", 1); Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params, (PreparedStatementCallback) ps -> { - assertEquals(preparedStatement, ps); + assertThat(ps).isEqualTo(preparedStatement); ps.executeUpdate(); return "result"; }); - assertEquals("result", result); + assertThat(result).isEqualTo("result"); verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1); verify(preparedStatement).setObject(2, 1); @@ -163,12 +161,12 @@ public class NamedParameterJdbcTemplateTests { params.put("id", 1); Object result = namedParameterTemplate.execute(UPDATE_ARRAY_PARAMETERS, params, (PreparedStatementCallback) ps -> { - assertEquals(preparedStatement, ps); + assertThat(ps).isEqualTo(preparedStatement); ps.executeUpdate(); return "result"; }); - assertEquals("result", result); + assertThat(result).isEqualTo("result"); verify(connection).prepareStatement(UPDATE_ARRAY_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1); verify(preparedStatement).setObject(2, 2); @@ -186,12 +184,12 @@ public class NamedParameterJdbcTemplateTests { params.put("priceId", new SqlParameterValue(Types.INTEGER, 1)); Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params, (PreparedStatementCallback) ps -> { - assertEquals(preparedStatement, ps); + assertThat(ps).isEqualTo(preparedStatement); ps.executeUpdate(); return "result"; }); - assertEquals("result", result); + assertThat(result).isEqualTo("result"); verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setObject(2, 1, Types.INTEGER); @@ -205,12 +203,12 @@ public class NamedParameterJdbcTemplateTests { Object result = namedParameterTemplate.execute(SELECT_NO_PARAMETERS, (PreparedStatementCallback) ps -> { - assertEquals(preparedStatement, ps); + assertThat(ps).isEqualTo(preparedStatement); ps.executeQuery(); return "result"; }); - assertEquals("result", result); + assertThat(result).isEqualTo("result"); verify(connection).prepareStatement(SELECT_NO_PARAMETERS); verify(preparedStatement).close(); verify(connection).close(); @@ -233,8 +231,8 @@ public class NamedParameterJdbcTemplateTests { return cust1; }); - assertTrue("Customer id was assigned correctly", cust.getId() == 1); - assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod")); + assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setString(2, "UK"); @@ -257,8 +255,8 @@ public class NamedParameterJdbcTemplateTests { return cust1; }); - assertTrue("Customer id was assigned correctly", cust.getId() == 1); - assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod")); + assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(connection).prepareStatement(SELECT_NO_PARAMETERS); verify(preparedStatement).close(); verify(connection).close(); @@ -280,9 +278,9 @@ public class NamedParameterJdbcTemplateTests { customers.add(cust); }); - assertEquals(1, customers.size()); - assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1); - assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod")); + assertThat(customers.size()).isEqualTo(1); + assertThat(customers.get(0).getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(customers.get(0).getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setString(2, "UK"); @@ -304,9 +302,9 @@ public class NamedParameterJdbcTemplateTests { customers.add(cust); }); - assertEquals(1, customers.size()); - assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1); - assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod")); + assertThat(customers.size()).isEqualTo(1); + assertThat(customers.get(0).getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(customers.get(0).getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(connection).prepareStatement(SELECT_NO_PARAMETERS); verify(preparedStatement).close(); verify(connection).close(); @@ -327,9 +325,9 @@ public class NamedParameterJdbcTemplateTests { cust.setForename(rs.getString(COLUMN_NAMES[1])); return cust; }); - assertEquals(1, customers.size()); - assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1); - assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod")); + assertThat(customers.size()).isEqualTo(1); + assertThat(customers.get(0).getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(customers.get(0).getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setString(2, "UK"); @@ -350,9 +348,9 @@ public class NamedParameterJdbcTemplateTests { cust.setForename(rs.getString(COLUMN_NAMES[1])); return cust; }); - assertEquals(1, customers.size()); - assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1); - assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod")); + assertThat(customers.size()).isEqualTo(1); + assertThat(customers.get(0).getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(customers.get(0).getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(connection).prepareStatement(SELECT_NO_PARAMETERS); verify(preparedStatement).close(); verify(connection).close(); @@ -373,8 +371,8 @@ public class NamedParameterJdbcTemplateTests { cust1.setForename(rs.getString(COLUMN_NAMES[1])); return cust1; }); - assertTrue("Customer id was assigned correctly", cust.getId() == 1); - assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod")); + assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setString(2, "UK"); @@ -390,7 +388,7 @@ public class NamedParameterJdbcTemplateTests { params.put("priceId", 1); int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params); - assertEquals(1, rowsAffected); + assertThat(rowsAffected).isEqualTo(1); verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1); verify(preparedStatement).setObject(2, 1); @@ -406,7 +404,7 @@ public class NamedParameterJdbcTemplateTests { params.put("priceId", new SqlParameterValue(Types.INTEGER, 1)); int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params); - assertEquals(1, rowsAffected); + assertThat(rowsAffected).isEqualTo(1); verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setObject(2, 1, Types.INTEGER); @@ -428,9 +426,9 @@ public class NamedParameterJdbcTemplateTests { int[] actualRowsAffected = namedParameterTemplate.batchUpdate( "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(connection).prepareStatement("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"); verify(preparedStatement).setObject(1, 100); verify(preparedStatement).setObject(1, 200); @@ -447,7 +445,7 @@ public class NamedParameterJdbcTemplateTests { int[] actualRowsAffected = namedParameterTemplate.batchUpdate( "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids); - assertTrue("executed 0 updates", actualRowsAffected.length == 0); + assertThat(actualRowsAffected.length == 0).as("executed 0 updates").isTrue(); } @Test @@ -463,9 +461,9 @@ public class NamedParameterJdbcTemplateTests { int[] actualRowsAffected = namedParameterTemplate.batchUpdate( "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(connection).prepareStatement("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"); verify(preparedStatement).setObject(1, 100); verify(preparedStatement).setObject(1, 200); @@ -493,7 +491,7 @@ public class NamedParameterJdbcTemplateTests { parameters ); - assertEquals("executed 2 updates", 2, actualRowsAffected.length); + assertThat(actualRowsAffected.length).as("executed 2 updates").isEqualTo(2); InOrder inOrder = inOrder(preparedStatement); @@ -522,9 +520,9 @@ public class NamedParameterJdbcTemplateTests { int[] actualRowsAffected = namedParameterTemplate.batchUpdate( "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(connection).prepareStatement("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"); verify(preparedStatement).setObject(1, 100, Types.NUMERIC); verify(preparedStatement).setObject(1, 200, Types.NUMERIC); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterQueryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterQueryTests.java index 78bedda52c2..5491a73996f 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterQueryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterQueryTests.java @@ -36,8 +36,7 @@ import org.junit.Test; import org.springframework.jdbc.core.RowMapper; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -96,11 +95,9 @@ public class NamedParameterQueryTests { List> li = template.queryForList( "SELECT AGE FROM CUSTMR WHERE ID < :id", params); - assertEquals("All rows returned", 2, li.size()); - assertEquals("First row is Integer", 11, - ((Integer) li.get(0).get("age")).intValue()); - assertEquals("Second row is Integer", 12, - ((Integer) li.get(1).get("age")).intValue()); + assertThat(li.size()).as("All rows returned").isEqualTo(2); + assertThat(((Integer) li.get(0).get("age")).intValue()).as("First row is Integer").isEqualTo(11); + assertThat(((Integer) li.get(1).get("age")).intValue()).as("Second row is Integer").isEqualTo(12); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?"); verify(preparedStatement).setObject(1, 3); @@ -115,7 +112,7 @@ public class NamedParameterQueryTests { List> li = template.queryForList( "SELECT AGE FROM CUSTMR WHERE ID < :id", params); - assertEquals("All rows returned", 0, li.size()); + assertThat(li.size()).as("All rows returned").isEqualTo(0); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?"); verify(preparedStatement).setObject(1, 3); } @@ -131,9 +128,8 @@ public class NamedParameterQueryTests { List> li = template.queryForList( "SELECT AGE FROM CUSTMR WHERE ID < :id", params); - assertEquals("All rows returned", 1, li.size()); - assertEquals("First row is Integer", 11, - ((Integer) li.get(0).get("age")).intValue()); + assertThat(li.size()).as("All rows returned").isEqualTo(1); + assertThat(((Integer) li.get(0).get("age")).intValue()).as("First row is Integer").isEqualTo(11); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?"); verify(preparedStatement).setObject(1, 3); } @@ -150,8 +146,8 @@ public class NamedParameterQueryTests { List li = template.queryForList("SELECT AGE FROM CUSTMR WHERE ID < :id", params, Integer.class); - assertEquals("All rows returned", 1, li.size()); - assertEquals("First row is Integer", 11, li.get(0).intValue()); + assertThat(li.size()).as("All rows returned").isEqualTo(1); + assertThat(li.get(0).intValue()).as("First row is Integer").isEqualTo(11); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?"); verify(preparedStatement).setObject(1, 3); } @@ -166,7 +162,7 @@ public class NamedParameterQueryTests { params.addValue("id", 3); Map map = template.queryForMap("SELECT AGE FROM CUSTMR WHERE ID < :id", params); - assertEquals("Row is Integer", 11, ((Integer) map.get("age")).intValue()); + assertThat(((Integer) map.get("age")).intValue()).as("Row is Integer").isEqualTo(11); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID < ?"); verify(preparedStatement).setObject(1, 3); } @@ -186,7 +182,8 @@ public class NamedParameterQueryTests { } }); - assertTrue("Correct result type", o instanceof Integer); + boolean condition = o instanceof Integer; + assertThat(condition).as("Correct result type").isTrue(); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?"); verify(preparedStatement).setObject(1, 3); } @@ -202,7 +199,8 @@ public class NamedParameterQueryTests { Object o = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id", params, Integer.class); - assertTrue("Correct result type", o instanceof Integer); + boolean condition = o instanceof Integer; + assertThat(condition).as("Correct result type").isTrue(); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?"); verify(preparedStatement).setObject(1, 3); } @@ -218,7 +216,8 @@ public class NamedParameterQueryTests { Object o = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id", params, Integer.class); - assertTrue("Correct result type", o instanceof Integer); + boolean condition = o instanceof Integer; + assertThat(condition).as("Correct result type").isTrue(); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?"); verify(preparedStatement).setObject(1, 3); } @@ -235,7 +234,8 @@ public class NamedParameterQueryTests { params.addValue("ids", Arrays.asList(3, 4)); Object o = template.queryForObject(sql, params, Integer.class); - assertTrue("Correct result type", o instanceof Integer); + boolean condition = o instanceof Integer; + assertThat(condition).as("Correct result type").isTrue(); verify(connection).prepareStatement(sqlToUse); verify(preparedStatement).setObject(1, 3); } @@ -255,7 +255,8 @@ public class NamedParameterQueryTests { "SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN (:multiExpressionList)", params, Integer.class); - assertTrue("Correct result type", o instanceof Integer); + boolean condition = o instanceof Integer; + assertThat(condition).as("Correct result type").isTrue(); verify(connection).prepareStatement( "SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN ((?, ?), (?, ?))"); verify(preparedStatement).setObject(1, 3); @@ -271,7 +272,7 @@ public class NamedParameterQueryTests { params.addValue("id", 3); int i = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id", params, Integer.class).intValue(); - assertEquals("Return of an int", 22, i); + assertThat(i).as("Return of an int").isEqualTo(22); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?"); verify(preparedStatement).setObject(1, 3); } @@ -285,7 +286,7 @@ public class NamedParameterQueryTests { BeanPropertySqlParameterSource params = new BeanPropertySqlParameterSource(new ParameterBean(3)); long l = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id", params, Long.class).longValue(); - assertEquals("Return of a long", 87, l); + assertThat(l).as("Return of a long").isEqualTo(87); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?"); verify(preparedStatement).setObject(1, 3, Types.INTEGER); } @@ -299,7 +300,7 @@ public class NamedParameterQueryTests { BeanPropertySqlParameterSource params = new BeanPropertySqlParameterSource(new ParameterCollectionBean(3, 5)); long l = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID IN (:ids)", params, Long.class).longValue(); - assertEquals("Return of a long", 87, l); + assertThat(l).as("Return of a long").isEqualTo(87); verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID IN (?, ?)"); verify(preparedStatement).setObject(1, 3); verify(preparedStatement).setObject(2, 5); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java index ed8ea39df09..ee230e4f973 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java @@ -24,9 +24,8 @@ import org.junit.Test; import org.springframework.dao.InvalidDataAccessApiUsageException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; /** * @author Thomas Risberg @@ -40,34 +39,33 @@ public class NamedParameterUtilsTests { public void parseSql() { String sql = "xxx :a yyyy :b :c :a zzzzz"; ParsedSql psql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals("xxx ? yyyy ? ? ? zzzzz", NamedParameterUtils.substituteNamedParameters(psql, null)); - assertEquals("a", psql.getParameterNames().get(0)); - assertEquals("c", psql.getParameterNames().get(2)); - assertEquals("a", psql.getParameterNames().get(3)); - assertEquals(4, psql.getTotalParameterCount()); - assertEquals(3, psql.getNamedParameterCount()); + assertThat(NamedParameterUtils.substituteNamedParameters(psql, null)).isEqualTo("xxx ? yyyy ? ? ? zzzzz"); + assertThat(psql.getParameterNames().get(0)).isEqualTo("a"); + assertThat(psql.getParameterNames().get(2)).isEqualTo("c"); + assertThat(psql.getParameterNames().get(3)).isEqualTo("a"); + assertThat(psql.getTotalParameterCount()).isEqualTo(4); + assertThat(psql.getNamedParameterCount()).isEqualTo(3); String sql2 = "xxx &a yyyy ? zzzzz"; ParsedSql psql2 = NamedParameterUtils.parseSqlStatement(sql2); - assertEquals("xxx ? yyyy ? zzzzz", NamedParameterUtils.substituteNamedParameters(psql2, null)); - assertEquals("a", psql2.getParameterNames().get(0)); - assertEquals(2, psql2.getTotalParameterCount()); - assertEquals(1, psql2.getNamedParameterCount()); + assertThat(NamedParameterUtils.substituteNamedParameters(psql2, null)).isEqualTo("xxx ? yyyy ? zzzzz"); + assertThat(psql2.getParameterNames().get(0)).isEqualTo("a"); + assertThat(psql2.getTotalParameterCount()).isEqualTo(2); + assertThat(psql2.getNamedParameterCount()).isEqualTo(1); String sql3 = "xxx &ä+:ö" + '\t' + ":ü%10 yyyy ? zzzzz"; ParsedSql psql3 = NamedParameterUtils.parseSqlStatement(sql3); - assertEquals("ä", psql3.getParameterNames().get(0)); - assertEquals("ö", psql3.getParameterNames().get(1)); - assertEquals("ü", psql3.getParameterNames().get(2)); + assertThat(psql3.getParameterNames().get(0)).isEqualTo("ä"); + assertThat(psql3.getParameterNames().get(1)).isEqualTo("ö"); + assertThat(psql3.getParameterNames().get(2)).isEqualTo("ü"); } @Test public void substituteNamedParameters() { MapSqlParameterSource namedParams = new MapSqlParameterSource(); namedParams.addValue("a", "a").addValue("b", "b").addValue("c", "c"); - assertEquals("xxx ? ? ?", NamedParameterUtils.substituteNamedParameters("xxx :a :b :c", namedParams)); - assertEquals("xxx ? ? ? xx ? ?", - NamedParameterUtils.substituteNamedParameters("xxx :a :b :c xx :a :a", namedParams)); + assertThat(NamedParameterUtils.substituteNamedParameters("xxx :a :b :c", namedParams)).isEqualTo("xxx ? ? ?"); + assertThat(NamedParameterUtils.substituteNamedParameters("xxx :a :b :c xx :a :a", namedParams)).isEqualTo("xxx ? ? ? xx ? ?"); } @Test @@ -76,10 +74,10 @@ public class NamedParameterUtilsTests { paramMap.put("a", "a"); paramMap.put("b", "b"); paramMap.put("c", "c"); - assertSame(3, NamedParameterUtils.buildValueArray("xxx :a :b :c", paramMap).length); - assertSame(5, NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap).length); - assertSame(5, NamedParameterUtils.buildValueArray("xxx :a :a :a xx :a :a", paramMap).length); - assertEquals("b", NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap)[4]); + assertThat(NamedParameterUtils.buildValueArray("xxx :a :b :c", paramMap).length).isSameAs(3); + assertThat(NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap).length).isSameAs(5); + assertThat(NamedParameterUtils.buildValueArray("xxx :a :a :a xx :a :a", paramMap).length).isSameAs(5); + assertThat(NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap)[4]).isEqualTo("b"); assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).as("mixed named parameters and ? placeholders").isThrownBy(() -> NamedParameterUtils.buildValueArray("xxx :a :b ?", paramMap)); } @@ -88,30 +86,30 @@ public class NamedParameterUtilsTests { public void convertTypeMapToArray() { MapSqlParameterSource namedParams = new MapSqlParameterSource(); namedParams.addValue("a", "a", 1).addValue("b", "b", 2).addValue("c", "c", 3); - assertSame(3, NamedParameterUtils - .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).length); - assertSame(5, NamedParameterUtils - .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams).length); - assertSame(5, NamedParameterUtils - .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :a :a xx :a :a"), namedParams).length); - assertEquals(2, NamedParameterUtils - .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams)[4]); + assertThat(NamedParameterUtils + .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).length).isSameAs(3); + assertThat(NamedParameterUtils + .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams).length).isSameAs(5); + assertThat(NamedParameterUtils + .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :a :a xx :a :a"), namedParams).length).isSameAs(5); + assertThat(NamedParameterUtils + .buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams)[4]).isEqualTo(2); } @Test public void convertTypeMapToSqlParameterList() { MapSqlParameterSource namedParams = new MapSqlParameterSource(); namedParams.addValue("a", "a", 1).addValue("b", "b", 2).addValue("c", "c", 3, "SQL_TYPE"); - assertSame(3, NamedParameterUtils - .buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).size()); - assertSame(5, NamedParameterUtils - .buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams).size()); - assertSame(5, NamedParameterUtils - .buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :a :a xx :a :a"), namedParams).size()); - assertEquals(2, NamedParameterUtils - .buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams).get(4).getSqlType()); - assertEquals("SQL_TYPE", NamedParameterUtils - .buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).get(2).getTypeName()); + assertThat(NamedParameterUtils + .buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).size()).isSameAs(3); + assertThat(NamedParameterUtils + .buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams).size()).isSameAs(5); + assertThat(NamedParameterUtils + .buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :a :a xx :a :a"), namedParams).size()).isSameAs(5); + assertThat(NamedParameterUtils + .buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams).get(4).getSqlType()).isEqualTo(2); + assertThat(NamedParameterUtils + .buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).get(2).getTypeName()).isEqualTo("SQL_TYPE"); } @Test @@ -126,7 +124,7 @@ public class NamedParameterUtilsTests { String expectedSql = "select 'first name' from artists where id = ? and quote = 'exsqueeze me?'"; String sql = "select 'first name' from artists where id = :id and quote = 'exsqueeze me?'"; String newSql = NamedParameterUtils.substituteNamedParameters(sql, new MapSqlParameterSource()); - assertEquals(expectedSql, newSql); + assertThat(newSql).isEqualTo(expectedSql); } @Test @@ -134,41 +132,37 @@ public class NamedParameterUtilsTests { String expectedSql = "select 'first name' from artists where id = ? and quote = 'exsqueeze me?'"; String sql = "select 'first name' from artists where id = :id and quote = 'exsqueeze me?'"; ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals(expectedSql, NamedParameterUtils.substituteNamedParameters(parsedSql, null)); + assertThat(NamedParameterUtils.substituteNamedParameters(parsedSql, null)).isEqualTo(expectedSql); } @Test // SPR-4789 public void parseSqlContainingComments() { String sql1 = "/*+ HINT */ xxx /* comment ? */ :a yyyy :b :c :a zzzzz -- :xx XX\n"; ParsedSql psql1 = NamedParameterUtils.parseSqlStatement(sql1); - assertEquals("/*+ HINT */ xxx /* comment ? */ ? yyyy ? ? ? zzzzz -- :xx XX\n", - NamedParameterUtils.substituteNamedParameters(psql1, null)); + assertThat(NamedParameterUtils.substituteNamedParameters(psql1, null)).isEqualTo("/*+ HINT */ xxx /* comment ? */ ? yyyy ? ? ? zzzzz -- :xx XX\n"); MapSqlParameterSource paramMap = new MapSqlParameterSource(); paramMap.addValue("a", "a"); paramMap.addValue("b", "b"); paramMap.addValue("c", "c"); Object[] params = NamedParameterUtils.buildValueArray(psql1, paramMap, null); - assertEquals(4, params.length); - assertEquals("a", params[0]); - assertEquals("b", params[1]); - assertEquals("c", params[2]); - assertEquals("a", params[3]); + assertThat(params.length).isEqualTo(4); + assertThat(params[0]).isEqualTo("a"); + assertThat(params[1]).isEqualTo("b"); + assertThat(params[2]).isEqualTo("c"); + assertThat(params[3]).isEqualTo("a"); String sql2 = "/*+ HINT */ xxx /* comment ? */ :a yyyy :b :c :a zzzzz -- :xx XX"; ParsedSql psql2 = NamedParameterUtils.parseSqlStatement(sql2); - assertEquals("/*+ HINT */ xxx /* comment ? */ ? yyyy ? ? ? zzzzz -- :xx XX", - NamedParameterUtils.substituteNamedParameters(psql2, null)); + assertThat(NamedParameterUtils.substituteNamedParameters(psql2, null)).isEqualTo("/*+ HINT */ xxx /* comment ? */ ? yyyy ? ? ? zzzzz -- :xx XX"); String sql3 = "/*+ HINT */ xxx /* comment ? */ :a yyyy :b :c :a zzzzz /* :xx XX*"; ParsedSql psql3 = NamedParameterUtils.parseSqlStatement(sql3); - assertEquals("/*+ HINT */ xxx /* comment ? */ ? yyyy ? ? ? zzzzz /* :xx XX*", - NamedParameterUtils.substituteNamedParameters(psql3, null)); + assertThat(NamedParameterUtils.substituteNamedParameters(psql3, null)).isEqualTo("/*+ HINT */ xxx /* comment ? */ ? yyyy ? ? ? zzzzz /* :xx XX*"); String sql4 = "/*+ HINT */ xxx /* comment :a ? */ :a yyyy :b :c :a zzzzz /* :xx XX*"; ParsedSql psql4 = NamedParameterUtils.parseSqlStatement(sql4); Map parameters = Collections.singletonMap("a", "0"); - assertEquals("/*+ HINT */ xxx /* comment :a ? */ ? yyyy ? ? ? zzzzz /* :xx XX*", - NamedParameterUtils.substituteNamedParameters(psql4, new MapSqlParameterSource(parameters))); + assertThat(NamedParameterUtils.substituteNamedParameters(psql4, new MapSqlParameterSource(parameters))).isEqualTo("/*+ HINT */ xxx /* comment :a ? */ ? yyyy ? ? ? zzzzz /* :xx XX*"); } @Test // SPR-4612 @@ -176,7 +170,7 @@ public class NamedParameterUtilsTests { String expectedSql = "select 'first name' from artists where id = ? and birth_date=?::timestamp"; String sql = "select 'first name' from artists where id = :id and birth_date=:birthDate::timestamp"; ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals(expectedSql, NamedParameterUtils.substituteNamedParameters(parsedSql, null)); + assertThat(NamedParameterUtils.substituteNamedParameters(parsedSql, null)).isEqualTo(expectedSql); } @Test // SPR-13582 @@ -184,8 +178,8 @@ public class NamedParameterUtilsTests { String expectedSql = "select 'first name' from artists where info->'stat'->'albums' = ?? ? and '[\"1\",\"2\",\"3\"]'::jsonb ?? '4'"; String sql = "select 'first name' from artists where info->'stat'->'albums' = ?? :album and '[\"1\",\"2\",\"3\"]'::jsonb ?? '4'"; ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals(1, parsedSql.getTotalParameterCount()); - assertEquals(expectedSql, NamedParameterUtils.substituteNamedParameters(parsedSql, null)); + assertThat(parsedSql.getTotalParameterCount()).isEqualTo(1); + assertThat(NamedParameterUtils.substituteNamedParameters(parsedSql, null)).isEqualTo(expectedSql); } @Test // SPR-15382 @@ -194,8 +188,8 @@ public class NamedParameterUtilsTests { String sql = "select '[\"3\", \"11\"]'::jsonb ?| '{1,3,11,12,17}'::text[]"; ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals(0, parsedSql.getTotalParameterCount()); - assertEquals(expectedSql, NamedParameterUtils.substituteNamedParameters(parsedSql, null)); + assertThat(parsedSql.getTotalParameterCount()).isEqualTo(0); + assertThat(NamedParameterUtils.substituteNamedParameters(parsedSql, null)).isEqualTo(expectedSql); } @Test // SPR-15382 @@ -204,8 +198,8 @@ public class NamedParameterUtilsTests { String sql = "select '[\"3\", \"11\"]'::jsonb ?& '{1,3,11,12,17}'::text[] AND :album = 'Back in Black'"; ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals(1, parsedSql.getTotalParameterCount()); - assertEquals(expectedSql, NamedParameterUtils.substituteNamedParameters(parsedSql, null)); + assertThat(parsedSql.getTotalParameterCount()).isEqualTo(1); + assertThat(NamedParameterUtils.substituteNamedParameters(parsedSql, null)).isEqualTo(expectedSql); } @Test // SPR-7476 @@ -214,11 +208,11 @@ public class NamedParameterUtilsTests { String sql = "select '0\\:0' as a, foo from bar where baz < DATE(:p1 23\\:59\\:59) and baz = :p2"; ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals(2, parsedSql.getParameterNames().size()); - assertEquals("p1", parsedSql.getParameterNames().get(0)); - assertEquals("p2", parsedSql.getParameterNames().get(1)); + assertThat(parsedSql.getParameterNames().size()).isEqualTo(2); + assertThat(parsedSql.getParameterNames().get(0)).isEqualTo("p1"); + assertThat(parsedSql.getParameterNames().get(1)).isEqualTo("p2"); String finalSql = NamedParameterUtils.substituteNamedParameters(parsedSql, null); - assertEquals(expectedSql, finalSql); + assertThat(finalSql).isEqualTo(expectedSql); } @Test // SPR-7476 @@ -227,11 +221,11 @@ public class NamedParameterUtilsTests { String sql = "select foo from bar where baz = b:{p1}:{p2}z"; ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals(2, parsedSql.getParameterNames().size()); - assertEquals("p1", parsedSql.getParameterNames().get(0)); - assertEquals("p2", parsedSql.getParameterNames().get(1)); + assertThat(parsedSql.getParameterNames().size()).isEqualTo(2); + assertThat(parsedSql.getParameterNames().get(0)).isEqualTo("p1"); + assertThat(parsedSql.getParameterNames().get(1)).isEqualTo("p2"); String finalSql = NamedParameterUtils.substituteNamedParameters(parsedSql, null); - assertEquals(expectedSql, finalSql); + assertThat(finalSql).isEqualTo(expectedSql); } @Test // SPR-7476 @@ -239,17 +233,17 @@ public class NamedParameterUtilsTests { String expectedSql = "select foo from bar where baz = b:{}z"; String sql = "select foo from bar where baz = b:{}z"; ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals(0, parsedSql.getParameterNames().size()); + assertThat(parsedSql.getParameterNames().size()).isEqualTo(0); String finalSql = NamedParameterUtils.substituteNamedParameters(parsedSql, null); - assertEquals(expectedSql, finalSql); + assertThat(finalSql).isEqualTo(expectedSql); String expectedSql2 = "select foo from bar where baz = 'b:{p1}z'"; String sql2 = "select foo from bar where baz = 'b:{p1}z'"; ParsedSql parsedSql2 = NamedParameterUtils.parseSqlStatement(sql2); - assertEquals(0, parsedSql2.getParameterNames().size()); + assertThat(parsedSql2.getParameterNames().size()).isEqualTo(0); String finalSql2 = NamedParameterUtils.substituteNamedParameters(parsedSql2, null); - assertEquals(expectedSql2, finalSql2); + assertThat(finalSql2).isEqualTo(expectedSql2); } @Test @@ -258,55 +252,55 @@ public class NamedParameterUtilsTests { String sql = "select foo from bar where baz = b:{p}z"; ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals(1, parsedSql.getParameterNames().size()); - assertEquals("p", parsedSql.getParameterNames().get(0)); + assertThat(parsedSql.getParameterNames().size()).isEqualTo(1); + assertThat(parsedSql.getParameterNames().get(0)).isEqualTo("p"); String finalSql = NamedParameterUtils.substituteNamedParameters(parsedSql, null); - assertEquals(expectedSql, finalSql); + assertThat(finalSql).isEqualTo(expectedSql); } @Test // SPR-2544 public void parseSqlStatementWithLogicalAnd() { String expectedSql = "xxx & yyyy"; ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(expectedSql); - assertEquals(expectedSql, NamedParameterUtils.substituteNamedParameters(parsedSql, null)); + assertThat(NamedParameterUtils.substituteNamedParameters(parsedSql, null)).isEqualTo(expectedSql); } @Test // SPR-2544 public void substituteNamedParametersWithLogicalAnd() { String expectedSql = "xxx & yyyy"; String newSql = NamedParameterUtils.substituteNamedParameters(expectedSql, new MapSqlParameterSource()); - assertEquals(expectedSql, newSql); + assertThat(newSql).isEqualTo(expectedSql); } @Test // SPR-3173 public void variableAssignmentOperator() { String expectedSql = "x := 1"; String newSql = NamedParameterUtils.substituteNamedParameters(expectedSql, new MapSqlParameterSource()); - assertEquals(expectedSql, newSql); + assertThat(newSql).isEqualTo(expectedSql); } @Test // SPR-8280 public void parseSqlStatementWithQuotedSingleQuote() { String sql = "SELECT ':foo'':doo', :xxx FROM DUAL"; ParsedSql psql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals(1, psql.getTotalParameterCount()); - assertEquals("xxx", psql.getParameterNames().get(0)); + assertThat(psql.getTotalParameterCount()).isEqualTo(1); + assertThat(psql.getParameterNames().get(0)).isEqualTo("xxx"); } @Test public void parseSqlStatementWithQuotesAndCommentBefore() { String sql = "SELECT /*:doo*/':foo', :xxx FROM DUAL"; ParsedSql psql = NamedParameterUtils.parseSqlStatement(sql); - assertEquals(1, psql.getTotalParameterCount()); - assertEquals("xxx", psql.getParameterNames().get(0)); + assertThat(psql.getTotalParameterCount()).isEqualTo(1); + assertThat(psql.getParameterNames().get(0)).isEqualTo("xxx"); } @Test public void parseSqlStatementWithQuotesAndCommentAfter() { String sql2 = "SELECT ':foo'/*:doo*/, :xxx FROM DUAL"; ParsedSql psql2 = NamedParameterUtils.parseSqlStatement(sql2); - assertEquals(1, psql2.getTotalParameterCount()); - assertEquals("xxx", psql2.getParameterNames().get(0)); + assertThat(psql2.getTotalParameterCount()).isEqualTo(1); + assertThat(psql2.getParameterNames().get(0)).isEqualTo("xxx"); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/CallMetaDataContextTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/CallMetaDataContextTests.java index 4e671a2d52c..2f8f6b9840b 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/CallMetaDataContextTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/CallMetaDataContextTests.java @@ -34,8 +34,7 @@ import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.metadata.CallMetaDataContext; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -94,16 +93,17 @@ public class CallMetaDataContextTests { context.processParameters(parameters); Map inParameters = context.matchInParameterValuesWithCallParameters(parameterSource); - assertEquals("Wrong number of matched in parameter values", 2, inParameters.size()); - assertTrue("in parameter value missing", inParameters.containsKey("id")); - assertTrue("in out parameter value missing", inParameters.containsKey("name")); - assertTrue("out parameter value matched", !inParameters.containsKey("customer_no")); + assertThat(inParameters.size()).as("Wrong number of matched in parameter values").isEqualTo(2); + assertThat(inParameters.containsKey("id")).as("in parameter value missing").isTrue(); + assertThat(inParameters.containsKey("name")).as("in out parameter value missing").isTrue(); + boolean condition = !inParameters.containsKey("customer_no"); + assertThat(condition).as("out parameter value matched").isTrue(); List names = context.getOutParameterNames(); - assertEquals("Wrong number of out parameters", 2, names.size()); + assertThat(names.size()).as("Wrong number of out parameters").isEqualTo(2); List callParameters = context.getCallParameters(); - assertEquals("Wrong number of call parameters", 3, callParameters.size()); + assertThat(callParameters.size()).as("Wrong number of call parameters").isEqualTo(3); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcCallTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcCallTests.java index 91aa00ca84b..7ae26bfac9d 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcCallTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcCallTests.java @@ -33,8 +33,8 @@ import org.springframework.jdbc.core.SqlOutParameter; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; @@ -110,7 +110,7 @@ public class SimpleJdbcCallTests { Number newId = adder.executeObject(Number.class, new MapSqlParameterSource(). addValue("amount", 1103). addValue("custid", 3)); - assertEquals(4, newId.intValue()); + assertThat(newId.intValue()).isEqualTo(4); verifyAddInvoiceWithoutMetaData(false); verify(connection, atLeastOnce()).close(); } @@ -124,7 +124,7 @@ public class SimpleJdbcCallTests { new SqlParameter("custid", Types.INTEGER), new SqlOutParameter("newid", Types.INTEGER)); Number newId = adder.executeObject(Number.class, 1103, 3); - assertEquals(4, newId.intValue()); + assertThat(newId.intValue()).isEqualTo(4); verifyAddInvoiceWithoutMetaData(false); verify(connection, atLeastOnce()).close(); } @@ -136,7 +136,7 @@ public class SimpleJdbcCallTests { Number newId = adder.executeObject(Number.class, new MapSqlParameterSource() .addValue("amount", 1103) .addValue("custid", 3)); - assertEquals(4, newId.intValue()); + assertThat(newId.intValue()).isEqualTo(4); verifyAddInvoiceWithMetaData(false); verify(connection, atLeastOnce()).close(); } @@ -146,7 +146,7 @@ public class SimpleJdbcCallTests { initializeAddInvoiceWithMetaData(false); SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withProcedureName("add_invoice"); Number newId = adder.executeObject(Number.class, 1103, 3); - assertEquals(4, newId.intValue()); + assertThat(newId.intValue()).isEqualTo(4); verifyAddInvoiceWithMetaData(false); verify(connection, atLeastOnce()).close(); } @@ -162,7 +162,7 @@ public class SimpleJdbcCallTests { Number newId = adder.executeFunction(Number.class, new MapSqlParameterSource() .addValue("amount", 1103) .addValue("custid", 3)); - assertEquals(4, newId.intValue()); + assertThat(newId.intValue()).isEqualTo(4); verifyAddInvoiceWithoutMetaData(true); verify(connection, atLeastOnce()).close(); } @@ -176,7 +176,7 @@ public class SimpleJdbcCallTests { new SqlParameter("amount", Types.INTEGER), new SqlParameter("custid", Types.INTEGER)); Number newId = adder.executeFunction(Number.class, 1103, 3); - assertEquals(4, newId.intValue()); + assertThat(newId.intValue()).isEqualTo(4); verifyAddInvoiceWithoutMetaData(true); verify(connection, atLeastOnce()).close(); } @@ -188,7 +188,7 @@ public class SimpleJdbcCallTests { Number newId = adder.executeFunction(Number.class, new MapSqlParameterSource() .addValue("amount", 1103) .addValue("custid", 3)); - assertEquals(4, newId.intValue()); + assertThat(newId.intValue()).isEqualTo(4); verifyAddInvoiceWithMetaData(true); verify(connection, atLeastOnce()).close(); @@ -199,7 +199,7 @@ public class SimpleJdbcCallTests { initializeAddInvoiceWithMetaData(true); SimpleJdbcCall adder = new SimpleJdbcCall(dataSource).withFunctionName("add_invoice"); Number newId = adder.executeFunction(Number.class, 1103, 3); - assertEquals(4, newId.intValue()); + assertThat(newId.intValue()).isEqualTo(4); verifyAddInvoiceWithMetaData(true); verify(connection, atLeastOnce()).close(); @@ -231,7 +231,7 @@ public class SimpleJdbcCallTests { private void verifyStatement(SimpleJdbcCall adder, String expected) { - assertEquals("Incorrect call statement", expected, adder.getCallString()); + assertThat(adder.getCallString()).as("Incorrect call statement").isEqualTo(expected); } private void initializeAddInvoiceWithoutMetaData(boolean isFunction) throws SQLException { diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java index 14cfbc62179..bd93e253409 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java @@ -32,8 +32,7 @@ import org.springframework.jdbc.core.SqlParameterValue; import org.springframework.jdbc.core.metadata.TableMetaDataContext; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; @@ -106,13 +105,15 @@ public class TableMetaDataContextTests { List values = context.matchInParameterValuesWithInsertColumns(map); - assertEquals("wrong number of parameters: ", 4, values.size()); - assertTrue("id not wrapped with type info", values.get(0) instanceof Number); - assertTrue("name not wrapped with type info", values.get(1) instanceof String); - assertTrue("date wrapped with type info", - values.get(2) instanceof SqlParameterValue); - assertTrue("version wrapped with type info", - values.get(3) instanceof SqlParameterValue); + assertThat(values.size()).as("wrong number of parameters: ").isEqualTo(4); + boolean condition3 = values.get(0) instanceof Number; + assertThat(condition3).as("id not wrapped with type info").isTrue(); + boolean condition2 = values.get(1) instanceof String; + assertThat(condition2).as("name not wrapped with type info").isTrue(); + boolean condition1 = values.get(2) instanceof SqlParameterValue; + assertThat(condition1).as("date wrapped with type info").isTrue(); + boolean condition = values.get(3) instanceof SqlParameterValue; + assertThat(condition).as("version wrapped with type info").isTrue(); verify(metaDataResultSet, atLeastOnce()).next(); verify(columnsResultSet, atLeastOnce()).next(); verify(metaDataResultSet).close(); @@ -150,8 +151,8 @@ public class TableMetaDataContextTests { List values = context.matchInParameterValuesWithInsertColumns(map); String insertString = context.createInsertString(keyCols); - assertEquals("wrong number of parameters: ", 0, values.size()); - assertEquals("empty insert not generated correctly", "INSERT INTO customers () VALUES()", insertString); + assertThat(values.size()).as("wrong number of parameters: ").isEqualTo(0); + assertThat(insertString).as("empty insert not generated correctly").isEqualTo("INSERT INTO customers () VALUES()"); verify(metaDataResultSet, atLeastOnce()).next(); verify(columnsResultSet, atLeastOnce()).next(); verify(metaDataResultSet).close(); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReaderTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReaderTests.java index 19d199b5189..bef52ee3e69 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReaderTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReaderTests.java @@ -26,7 +26,7 @@ import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -58,9 +58,9 @@ public class JdbcBeanDefinitionReaderTests { JdbcBeanDefinitionReader reader = new JdbcBeanDefinitionReader(bf); reader.setDataSource(dataSource); reader.loadBeanDefinitions(sql); - assertEquals("Incorrect number of bean definitions", 1, bf.getBeanDefinitionCount()); + assertThat(bf.getBeanDefinitionCount()).as("Incorrect number of bean definitions").isEqualTo(1); TestBean tb = (TestBean) bf.getBean("one"); - assertEquals("Age in TestBean was wrong.", 53, tb.getAge()); + assertThat(tb.getAge()).as("Age in TestBean was wrong.").isEqualTo(53); verify(resultSet).close(); verify(statement).close(); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcDaoSupportTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcDaoSupportTests.java index e459113f80b..8d419f99459 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcDaoSupportTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcDaoSupportTests.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -45,9 +45,9 @@ public class JdbcDaoSupportTests { }; dao.setDataSource(ds); dao.afterPropertiesSet(); - assertEquals("Correct DataSource", ds, dao.getDataSource()); - assertEquals("Correct JdbcTemplate", ds, dao.getJdbcTemplate().getDataSource()); - assertEquals("initDao called", 1, test.size()); + assertThat(dao.getDataSource()).as("Correct DataSource").isEqualTo(ds); + assertThat(dao.getJdbcTemplate().getDataSource()).as("Correct JdbcTemplate").isEqualTo(ds); + assertThat(test.size()).as("initDao called").isEqualTo(1); } @Test @@ -62,8 +62,8 @@ public class JdbcDaoSupportTests { }; dao.setJdbcTemplate(template); dao.afterPropertiesSet(); - assertEquals("Correct JdbcTemplate", dao.getJdbcTemplate(), template); - assertEquals("initDao called", 1, test.size()); + assertThat(template).as("Correct JdbcTemplate").isEqualTo(dao.getJdbcTemplate()); + assertThat(test.size()).as("initDao called").isEqualTo(1); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/LobSupportTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/LobSupportTests.java index 543dea462a2..bab20e2da59 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/LobSupportTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/LobSupportTests.java @@ -29,9 +29,8 @@ import org.springframework.jdbc.LobRetrievalFailureException; import org.springframework.jdbc.support.lob.LobCreator; import org.springframework.jdbc.support.lob.LobHandler; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -65,8 +64,8 @@ public class LobSupportTests { } }; - assertEquals(Integer.valueOf(3), psc.doInPreparedStatement(ps)); - assertTrue(svc.b); + assertThat(psc.doInPreparedStatement(ps)).isEqualTo(Integer.valueOf(3)); + assertThat(svc.b).isTrue(); verify(creator).close(); verify(handler).getLobCreator(); verify(ps).executeUpdate(); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java index f5714ca0b39..0a81c6f3c36 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java @@ -46,11 +46,8 @@ import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.atLeastOnce; @@ -83,12 +80,12 @@ public class DataSourceJtaTransactionTests { @After public void verifyTransactionSynchronizationManagerState() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertNull(TransactionSynchronizationManager.getCurrentTransactionName()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertNull(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()).isNull(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } @Test @@ -113,22 +110,25 @@ public class DataSourceJtaTransactionTests { JtaTransactionManager ptm = new JtaTransactionManager(userTransaction); TransactionTemplate tt = new TransactionTemplate(ptm); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource)); - assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(dataSource); + assertThat(condition3).as("Hasn't thread connection").isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).as("JTA synchronizations not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource)); - assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); + boolean condition = !TransactionSynchronizationManager.hasResource(dataSource); + assertThat(condition).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("JTA synchronizations active").isTrue(); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); Connection c = DataSourceUtils.getConnection(dataSource); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource)); + assertThat(TransactionSynchronizationManager.hasResource(dataSource)).as("Has thread connection").isTrue(); DataSourceUtils.releaseConnection(c, dataSource); c = DataSourceUtils.getConnection(dataSource); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource)); + assertThat(TransactionSynchronizationManager.hasResource(dataSource)).as("Has thread connection").isTrue(); DataSourceUtils.releaseConnection(c, dataSource); if (rollback) { @@ -137,8 +137,10 @@ public class DataSourceJtaTransactionTests { } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource)); - assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(dataSource); + assertThat(condition1).as("Hasn't thread connection").isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).as("JTA synchronizations not active").isTrue(); verify(userTransaction).begin(); if (rollback) { verify(userTransaction).rollback(); @@ -218,24 +220,27 @@ public class DataSourceJtaTransactionTests { JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager); final TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(dsToUse); + assertThat(condition3).as("Hasn't thread connection").isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).as("JTA synchronizations not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); + boolean condition = !TransactionSynchronizationManager.hasResource(dsToUse); + assertThat(condition).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("JTA synchronizations active").isTrue(); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); Connection c = DataSourceUtils.getConnection(dsToUse); try { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); c.isReadOnly(); DataSourceUtils.releaseConnection(c, dsToUse); c = DataSourceUtils.getConnection(dsToUse); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); if (!openOuterConnection) { DataSourceUtils.releaseConnection(c, dsToUse); } @@ -248,18 +253,19 @@ public class DataSourceJtaTransactionTests { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); + boolean condition = !TransactionSynchronizationManager.hasResource(dsToUse); + assertThat(condition).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("JTA synchronizations active").isTrue(); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); try { Connection c = DataSourceUtils.getConnection(dsToUse); c.isReadOnly(); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); DataSourceUtils.releaseConnection(c, dsToUse); c = DataSourceUtils.getConnection(dsToUse); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); DataSourceUtils.releaseConnection(c, dsToUse); } catch (SQLException ex) { @@ -278,12 +284,12 @@ public class DataSourceJtaTransactionTests { if (!openOuterConnection) { c = DataSourceUtils.getConnection(dsToUse); } - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); c.isReadOnly(); DataSourceUtils.releaseConnection(c, dsToUse); c = DataSourceUtils.getConnection(dsToUse); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); DataSourceUtils.releaseConnection(c, dsToUse); } catch (SQLException ex) { @@ -298,8 +304,10 @@ public class DataSourceJtaTransactionTests { } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(dsToUse); + assertThat(condition1).as("Hasn't thread connection").isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).as("JTA synchronizations not active").isTrue(); verify(userTransaction, times(6)).begin(); verify(transactionManager, times(5)).resume(transaction); if (rollback) { @@ -366,15 +374,15 @@ public class DataSourceJtaTransactionTests { tt.setPropagationBehavior(notSupported ? TransactionDefinition.PROPAGATION_NOT_SUPPORTED : TransactionDefinition.PROPAGATION_SUPPORTS); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertSame(connection1, DataSourceUtils.getConnection(dataSource)); - assertSame(connection1, DataSourceUtils.getConnection(dataSource)); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(DataSourceUtils.getConnection(dataSource)).isSameAs(connection1); + assertThat(DataSourceUtils.getConnection(dataSource)).isSameAs(connection1); TransactionTemplate tt2 = new TransactionTemplate(ptm); tt2.setPropagationBehavior(requiresNew ? @@ -382,21 +390,21 @@ public class DataSourceJtaTransactionTests { tt2.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertSame(connection2, DataSourceUtils.getConnection(dataSource)); - assertSame(connection2, DataSourceUtils.getConnection(dataSource)); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(DataSourceUtils.getConnection(dataSource)).isSameAs(connection2); + assertThat(DataSourceUtils.getConnection(dataSource)).isSameAs(connection2); } }); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertSame(connection1, DataSourceUtils.getConnection(dataSource)); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(DataSourceUtils.getConnection(dataSource)).isSameAs(connection1); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(userTransaction).begin(); verify(userTransaction).commit(); if (notSupported) { @@ -472,26 +480,29 @@ public class DataSourceJtaTransactionTests { JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager); final TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(dsToUse); + assertThat(condition3).as("Hasn't thread connection").isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).as("JTA synchronizations not active").isTrue(); assertThatExceptionOfType(TransactionException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); + boolean condition = !TransactionSynchronizationManager.hasResource(dsToUse); + assertThat(condition).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("JTA synchronizations active").isTrue(); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); Connection c = DataSourceUtils.getConnection(dsToUse); try { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); c.isReadOnly(); DataSourceUtils.releaseConnection(c, dsToUse); c = DataSourceUtils.getConnection(dsToUse); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); if (!openOuterConnection) { DataSourceUtils.releaseConnection(c, dsToUse); } @@ -503,16 +514,17 @@ public class DataSourceJtaTransactionTests { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); + boolean condition = !TransactionSynchronizationManager.hasResource(dsToUse); + assertThat(condition).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("JTA synchronizations active").isTrue(); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); Connection c = DataSourceUtils.getConnection(dsToUse); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); DataSourceUtils.releaseConnection(c, dsToUse); c = DataSourceUtils.getConnection(dsToUse); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); DataSourceUtils.releaseConnection(c, dsToUse); } }); @@ -530,8 +542,10 @@ public class DataSourceJtaTransactionTests { } })); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(dsToUse); + assertThat(condition1).as("Hasn't thread connection").isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).as("JTA synchronizations not active").isTrue(); verify(userTransaction).begin(); if (suspendException) { @@ -572,8 +586,10 @@ public class DataSourceJtaTransactionTests { } }; TransactionTemplate tt = new TransactionTemplate(ptm); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource)); - assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(dataSource); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("JTA synchronizations not active").isTrue(); given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE); for (int i = 0; i < 3; i++) { @@ -582,15 +598,16 @@ public class DataSourceJtaTransactionTests { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is existing transaction", !status.isNewTransaction()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("JTA synchronizations active").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Is existing transaction").isTrue(); Connection c = DataSourceUtils.getConnection(dataSource); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource)); + assertThat(TransactionSynchronizationManager.hasResource(dataSource)).as("Has thread connection").isTrue(); DataSourceUtils.releaseConnection(c, dataSource); c = DataSourceUtils.getConnection(dataSource); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dataSource)); + assertThat(TransactionSynchronizationManager.hasResource(dataSource)).as("Has thread connection").isTrue(); if (releaseCon) { DataSourceUtils.releaseConnection(c, dataSource); } @@ -598,12 +615,14 @@ public class DataSourceJtaTransactionTests { }); if (!releaseCon) { - assertTrue("Still has connection holder", TransactionSynchronizationManager.hasResource(dataSource)); + assertThat(TransactionSynchronizationManager.hasResource(dataSource)).as("Still has connection holder").isTrue(); } else { - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dataSource)); + boolean condition = !TransactionSynchronizationManager.hasResource(dataSource); + assertThat(condition).as("Hasn't thread connection").isTrue(); } - assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).as("JTA synchronizations not active").isTrue(); } verify(connection, times(3)).close(); } @@ -630,8 +649,8 @@ public class DataSourceJtaTransactionTests { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { Connection c = DataSourceUtils.getConnection(dsToUse); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); - assertSame(connection, c); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); + assertThat(c).isSameAs(connection); DataSourceUtils.releaseConnection(c, dsToUse); } }); @@ -642,8 +661,8 @@ public class DataSourceJtaTransactionTests { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { Connection c = DataSourceUtils.getConnection(dsToUse); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); - assertSame(connection, c); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); + assertThat(c).isSameAs(connection); DataSourceUtils.releaseConnection(c, dsToUse); } }); @@ -701,8 +720,8 @@ given( userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, St @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { Connection c = DataSourceUtils.getConnection(dsToUse); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); - assertSame(connection1, c); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); + assertThat(c).isSameAs(connection1); DataSourceUtils.releaseConnection(c, dsToUse); } }); @@ -712,8 +731,8 @@ given( userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, St @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { Connection c = DataSourceUtils.getConnection(dsToUse); - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); - assertSame(connection2, c); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); + assertThat(c).isSameAs(connection2); DataSourceUtils.releaseConnection(c, dsToUse); } }); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java index 34062b11213..f93f7995ab1 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java @@ -48,14 +48,10 @@ import org.springframework.transaction.support.TransactionSynchronizationAdapter import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.inOrder; @@ -86,10 +82,10 @@ public class DataSourceTransactionManagerTests { @After public void verifyTransactionSynchronizationManagerState() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } @@ -138,17 +134,19 @@ public class DataSourceTransactionManagerTests { final DataSource dsToUse = (lazyConnection ? new LazyConnectionDataSourceProxy(ds) : ds); tm = new DataSourceTransactionManager(dsToUse); TransactionTemplate tt = new TransactionTemplate(tm); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(dsToUse); + assertThat(condition3).as("Hasn't thread connection").isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); Connection tCon = DataSourceUtils.getConnection(dsToUse); try { if (createStatement) { @@ -161,8 +159,10 @@ public class DataSourceTransactionManagerTests { } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(dsToUse); + assertThat(condition1).as("Hasn't thread connection").isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).as("Synchronization not active").isTrue(); if (autoCommit && (!lazyConnection || createStatement)) { InOrder ordered = inOrder(con); @@ -223,17 +223,19 @@ public class DataSourceTransactionManagerTests { final DataSource dsToUse = (lazyConnection ? new LazyConnectionDataSourceProxy(ds) : ds); tm = new DataSourceTransactionManager(dsToUse); TransactionTemplate tt = new TransactionTemplate(tm); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(dsToUse); + assertThat(condition3).as("Hasn't thread connection").isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).as("Synchronization not active").isTrue(); final RuntimeException ex = new RuntimeException("Application exception"); assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); Connection con = DataSourceUtils.getConnection(dsToUse); if (createStatement) { try { @@ -248,8 +250,10 @@ public class DataSourceTransactionManagerTests { })) .isEqualTo(ex); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).as("Synchronization not active").isTrue(); if (autoCommit && (!lazyConnection || createStatement)) { InOrder ordered = inOrder(con); @@ -269,8 +273,10 @@ public class DataSourceTransactionManagerTests { public void testTransactionRollbackOnly() throws Exception { tm.setTransactionSynchronization(DataSourceTransactionManager.SYNCHRONIZATION_NEVER); TransactionTemplate tt = new TransactionTemplate(tm); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); ConnectionHolder conHolder = new ConnectionHolder(con); conHolder.setTransactionActive(true); @@ -280,9 +286,11 @@ public class DataSourceTransactionManagerTests { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is existing transaction", !status.isNewTransaction()); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Is existing transaction").isTrue(); throw ex; } }); @@ -290,14 +298,16 @@ public class DataSourceTransactionManagerTests { } catch (RuntimeException ex2) { // expected - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); - assertEquals("Correct exception thrown", ex, ex2); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).as("Synchronization not active").isTrue(); + assertThat(ex2).as("Correct exception thrown").isEqualTo(ex); } finally { TransactionSynchronizationManager.unbindResource(ds); } - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); } @Test @@ -315,8 +325,10 @@ public class DataSourceTransactionManagerTests { if (failEarly) { tm.setFailEarlyOnGlobalRollbackOnly(true); } - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); TestTransactionSynchronization synch = @@ -325,25 +337,28 @@ public class DataSourceTransactionManagerTests { boolean outerTransactionBoundaryReached = false; try { - assertTrue("Is new transaction", ts.isNewTransaction()); + assertThat(ts.isNewTransaction()).as("Is new transaction").isTrue(); final TransactionTemplate tt = new TransactionTemplate(tm); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is existing transaction", !status.isNewTransaction()); - assertFalse("Is not rollback-only", status.isRollbackOnly()); + boolean condition1 = !status.isNewTransaction(); + assertThat(condition1).as("Is existing transaction").isTrue(); + assertThat(status.isRollbackOnly()).as("Is not rollback-only").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is existing transaction", !status.isNewTransaction()); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Is existing transaction").isTrue(); status.setRollbackOnly(); } }); - assertTrue("Is existing transaction", !status.isNewTransaction()); - assertTrue("Is rollback-only", status.isRollbackOnly()); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Is existing transaction").isTrue(); + assertThat(status.isRollbackOnly()).as("Is rollback-only").isTrue(); } }); @@ -358,18 +373,19 @@ public class DataSourceTransactionManagerTests { tm.rollback(ts); } if (failEarly) { - assertFalse(outerTransactionBoundaryReached); + assertThat(outerTransactionBoundaryReached).isFalse(); } else { - assertTrue(outerTransactionBoundaryReached); + assertThat(outerTransactionBoundaryReached).isTrue(); } } - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertFalse(synch.beforeCommitCalled); - assertTrue(synch.beforeCompletionCalled); - assertFalse(synch.afterCommitCalled); - assertTrue(synch.afterCompletionCalled); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); + assertThat(synch.beforeCommitCalled).isFalse(); + assertThat(synch.beforeCompletionCalled).isTrue(); + assertThat(synch.afterCommitCalled).isFalse(); + assertThat(synch.afterCompletionCalled).isTrue(); verify(con).rollback(); verify(con).close(); } @@ -378,8 +394,10 @@ public class DataSourceTransactionManagerTests { public void testParticipatingTransactionWithIncompatibleIsolationLevel() throws Exception { tm.setValidateExistingTransaction(true); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> { final TransactionTemplate tt = new TransactionTemplate(tm); @@ -389,19 +407,20 @@ public class DataSourceTransactionManagerTests { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertFalse("Is not rollback-only", status.isRollbackOnly()); + assertThat(status.isRollbackOnly()).as("Is not rollback-only").isFalse(); tt2.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { status.setRollbackOnly(); } }); - assertTrue("Is rollback-only", status.isRollbackOnly()); + assertThat(status.isRollbackOnly()).as("Is rollback-only").isTrue(); } }); }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).rollback(); verify(con).close(); } @@ -411,8 +430,10 @@ public class DataSourceTransactionManagerTests { willThrow(new SQLException("read-only not supported")).given(con).setReadOnly(true); tm.setValidateExistingTransaction(true); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> { final TransactionTemplate tt = new TransactionTemplate(tm); @@ -423,27 +444,30 @@ public class DataSourceTransactionManagerTests { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertFalse("Is not rollback-only", status.isRollbackOnly()); + assertThat(status.isRollbackOnly()).as("Is not rollback-only").isFalse(); tt2.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { status.setRollbackOnly(); } }); - assertTrue("Is rollback-only", status.isRollbackOnly()); + assertThat(status.isRollbackOnly()).as("Is rollback-only").isTrue(); } }); }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).rollback(); verify(con).close(); } @Test public void testParticipatingTransactionWithTransactionStartedFromSynch() throws Exception { - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); @@ -471,12 +495,14 @@ public class DataSourceTransactionManagerTests { } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue(synch.beforeCommitCalled); - assertTrue(synch.beforeCompletionCalled); - assertTrue(synch.afterCommitCalled); - assertTrue(synch.afterCompletionCalled); - assertTrue(synch.afterCompletionException instanceof IllegalStateException); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); + assertThat(synch.beforeCommitCalled).isTrue(); + assertThat(synch.beforeCompletionCalled).isTrue(); + assertThat(synch.afterCommitCalled).isTrue(); + assertThat(synch.afterCompletionCalled).isTrue(); + boolean condition3 = synch.afterCompletionException instanceof IllegalStateException; + assertThat(condition3).isTrue(); verify(con, times(2)).commit(); verify(con, times(2)).close(); } @@ -487,8 +513,10 @@ public class DataSourceTransactionManagerTests { final Connection con2 = mock(Connection.class); given(ds2.getConnection()).willReturn(con2); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -509,12 +537,13 @@ public class DataSourceTransactionManagerTests { } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue(synch.beforeCommitCalled); - assertTrue(synch.beforeCompletionCalled); - assertTrue(synch.afterCommitCalled); - assertTrue(synch.afterCompletionCalled); - assertNull(synch.afterCompletionException); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); + assertThat(synch.beforeCommitCalled).isTrue(); + assertThat(synch.beforeCompletionCalled).isTrue(); + assertThat(synch.afterCommitCalled).isTrue(); + assertThat(synch.afterCompletionCalled).isTrue(); + assertThat(synch.afterCompletionException).isNull(); verify(con).commit(); verify(con).close(); verify(con2).close(); @@ -526,32 +555,37 @@ public class DataSourceTransactionManagerTests { DataSourceTransactionManager tm2 = new DataSourceTransactionManager(ds); // tm has no synch enabled (used at outer level), tm2 has synch enabled (inner level) - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); final TestTransactionSynchronization synch = new TestTransactionSynchronization(ds, TransactionSynchronization.STATUS_UNKNOWN); assertThatExceptionOfType(UnexpectedRollbackException.class).isThrownBy(() -> { - assertTrue("Is new transaction", ts.isNewTransaction()); + assertThat(ts.isNewTransaction()).as("Is new transaction").isTrue(); final TransactionTemplate tt = new TransactionTemplate(tm2); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is existing transaction", !status.isNewTransaction()); - assertFalse("Is not rollback-only", status.isRollbackOnly()); + boolean condition1 = !status.isNewTransaction(); + assertThat(condition1).as("Is existing transaction").isTrue(); + assertThat(status.isRollbackOnly()).as("Is not rollback-only").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is existing transaction", !status.isNewTransaction()); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Is existing transaction").isTrue(); status.setRollbackOnly(); } }); - assertTrue("Is existing transaction", !status.isNewTransaction()); - assertTrue("Is rollback-only", status.isRollbackOnly()); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Is existing transaction").isTrue(); + assertThat(status.isRollbackOnly()).as("Is rollback-only").isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); } }); @@ -559,11 +593,12 @@ public class DataSourceTransactionManagerTests { tm.commit(ts); }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertFalse(synch.beforeCommitCalled); - assertTrue(synch.beforeCompletionCalled); - assertFalse(synch.afterCommitCalled); - assertTrue(synch.afterCompletionCalled); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); + assertThat(synch.beforeCommitCalled).isFalse(); + assertThat(synch.beforeCompletionCalled).isTrue(); + assertThat(synch.afterCommitCalled).isFalse(); + assertThat(synch.afterCompletionCalled).isTrue(); verify(con).rollback(); verify(con).close(); } @@ -572,34 +607,37 @@ public class DataSourceTransactionManagerTests { public void testPropagationRequiresNewWithExistingTransaction() throws Exception { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); status.setRollbackOnly(); } }); - assertTrue("Is new transaction", status.isNewTransaction()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).rollback(); verify(con).commit(); verify(con, times(2)).close(); @@ -618,36 +656,41 @@ public class DataSourceTransactionManagerTests { final TransactionTemplate tt2 = new TransactionTemplate(tm2); tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds2)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition4 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition4).as("Hasn't thread connection").isTrue(); + boolean condition3 = !TransactionSynchronizationManager.hasResource(ds2); + assertThat(condition3).as("Hasn't thread connection").isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); tt2.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); status.setRollbackOnly(); } }); - assertTrue("Is new transaction", status.isNewTransaction()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds2)); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); + boolean condition = !TransactionSynchronizationManager.hasResource(ds2); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).commit(); verify(con).close(); verify(con2).rollback(); @@ -669,18 +712,21 @@ public class DataSourceTransactionManagerTests { final TransactionTemplate tt2 = new TransactionTemplate(tm2); tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds2)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition4 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition4).as("Hasn't thread connection").isTrue(); + boolean condition3 = !TransactionSynchronizationManager.hasResource(ds2); + assertThat(condition3).as("Hasn't thread connection").isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).as("Synchronization not active").isTrue(); assertThatExceptionOfType(CannotCreateTransactionException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); tt2.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { @@ -690,8 +736,10 @@ public class DataSourceTransactionManagerTests { } })).withCause(failure); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds2)); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); + boolean condition = !TransactionSynchronizationManager.hasResource(ds2); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).rollback(); verify(con).close(); } @@ -700,34 +748,39 @@ public class DataSourceTransactionManagerTests { public void testPropagationNotSupportedWithExistingTransaction() throws Exception { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Isn't new transaction", !status.isNewTransaction()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Isn't new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); status.setRollbackOnly(); } }); - assertTrue("Is new transaction", status.isNewTransaction()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).commit(); verify(con).close(); } @@ -736,14 +789,16 @@ public class DataSourceTransactionManagerTests { public void testPropagationNeverWithExistingTransaction() throws Exception { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -755,7 +810,8 @@ public class DataSourceTransactionManagerTests { } })); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).rollback(); verify(con).close(); } @@ -764,29 +820,32 @@ public class DataSourceTransactionManagerTests { public void testPropagationSupportsAndRequiresNew() throws Exception { TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); TransactionTemplate tt2 = new TransactionTemplate(tm); tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tt2.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); - assertSame(con, DataSourceUtils.getConnection(ds)); - assertSame(con, DataSourceUtils.getConnection(ds)); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(DataSourceUtils.getConnection(ds)).isSameAs(con); + assertThat(DataSourceUtils.getConnection(ds)).isSameAs(con); } }); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).commit(); verify(con).close(); } @@ -800,32 +859,35 @@ public class DataSourceTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertSame(con1, DataSourceUtils.getConnection(ds)); - assertSame(con1, DataSourceUtils.getConnection(ds)); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + assertThat(DataSourceUtils.getConnection(ds)).isSameAs(con1); + assertThat(DataSourceUtils.getConnection(ds)).isSameAs(con1); TransactionTemplate tt2 = new TransactionTemplate(tm); tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tt2.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Is new transaction", status.isNewTransaction()); - assertSame(con2, DataSourceUtils.getConnection(ds)); - assertSame(con2, DataSourceUtils.getConnection(ds)); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + assertThat(DataSourceUtils.getConnection(ds)).isSameAs(con2); + assertThat(DataSourceUtils.getConnection(ds)).isSameAs(con2); } }); - assertSame(con1, DataSourceUtils.getConnection(ds)); + assertThat(DataSourceUtils.getConnection(ds)).isSameAs(con1); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con1).close(); verify(con2).commit(); verify(con2).close(); @@ -840,17 +902,19 @@ public class DataSourceTransactionManagerTests { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); tt.setReadOnly(true); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); // something transactional } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); InOrder ordered = inOrder(con); ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); ordered.verify(con).setAutoCommit(false); @@ -871,17 +935,19 @@ public class DataSourceTransactionManagerTests { TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tt.setReadOnly(true); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); // something transactional } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); InOrder ordered = inOrder(con, stmt); ordered.verify(con).setAutoCommit(false); ordered.verify(stmt).executeUpdate("SET TRANSACTION READ ONLY"); @@ -910,7 +976,8 @@ public class DataSourceTransactionManagerTests { TransactionTemplate tt = new TransactionTemplate(tm); tt.setTimeout(timeout); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); try { tt.execute(new TransactionCallbackWithoutResult() { @@ -944,7 +1011,8 @@ public class DataSourceTransactionManagerTests { } } - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); if (timeout > 1) { verify(ps).setQueryTimeout(timeout - 1); verify(con).commit(); @@ -964,15 +1032,16 @@ public class DataSourceTransactionManagerTests { given(con.getAutoCommit()).willReturn(true); TransactionTemplate tt = new TransactionTemplate(tm); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional - assertEquals(con, DataSourceUtils.getConnection(ds)); + assertThat(DataSourceUtils.getConnection(ds)).isEqualTo(con); TransactionAwareDataSourceProxy dsProxy = new TransactionAwareDataSourceProxy(ds); try { - assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()); + assertThat(((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()).isEqualTo(con); // should be ignored dsProxy.getConnection().close(); } @@ -982,7 +1051,8 @@ public class DataSourceTransactionManagerTests { } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); InOrder ordered = inOrder(con); ordered.verify(con).setAutoCommit(false); ordered.verify(con).commit(); @@ -996,16 +1066,17 @@ public class DataSourceTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional - assertEquals(con, DataSourceUtils.getConnection(ds)); + assertThat(DataSourceUtils.getConnection(ds)).isEqualTo(con); final TransactionAwareDataSourceProxy dsProxy = new TransactionAwareDataSourceProxy(ds); try { - assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()); + assertThat(((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()).isEqualTo(con); // should be ignored dsProxy.getConnection().close(); } @@ -1017,9 +1088,9 @@ public class DataSourceTransactionManagerTests { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional - assertEquals(con, DataSourceUtils.getConnection(ds)); + assertThat(DataSourceUtils.getConnection(ds)).isEqualTo(con); try { - assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()); + assertThat(((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()).isEqualTo(con); // should be ignored dsProxy.getConnection().close(); } @@ -1030,7 +1101,7 @@ public class DataSourceTransactionManagerTests { }); try { - assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()); + assertThat(((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()).isEqualTo(con); // should be ignored dsProxy.getConnection().close(); } @@ -1040,7 +1111,8 @@ public class DataSourceTransactionManagerTests { } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); InOrder ordered = inOrder(con); ordered.verify(con).setAutoCommit(false); ordered.verify(con).commit(); @@ -1054,17 +1126,18 @@ public class DataSourceTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional - assertEquals(con, DataSourceUtils.getConnection(ds)); + assertThat(DataSourceUtils.getConnection(ds)).isEqualTo(con); final TransactionAwareDataSourceProxy dsProxy = new TransactionAwareDataSourceProxy(ds); dsProxy.setReobtainTransactionalConnections(true); try { - assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()); + assertThat(((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()).isEqualTo(con); // should be ignored dsProxy.getConnection().close(); } @@ -1076,9 +1149,9 @@ public class DataSourceTransactionManagerTests { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional - assertEquals(con, DataSourceUtils.getConnection(ds)); + assertThat(DataSourceUtils.getConnection(ds)).isEqualTo(con); try { - assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()); + assertThat(((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()).isEqualTo(con); // should be ignored dsProxy.getConnection().close(); } @@ -1089,7 +1162,7 @@ public class DataSourceTransactionManagerTests { }); try { - assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()); + assertThat(((ConnectionProxy) dsProxy.getConnection()).getTargetConnection()).isEqualTo(con); // should be ignored dsProxy.getConnection().close(); } @@ -1099,7 +1172,8 @@ public class DataSourceTransactionManagerTests { } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); InOrder ordered = inOrder(con); ordered.verify(con).setAutoCommit(false); ordered.verify(con).commit(); @@ -1123,7 +1197,8 @@ public class DataSourceTransactionManagerTests { } })); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).close(); } @@ -1140,7 +1215,8 @@ public class DataSourceTransactionManagerTests { } })); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).close(); } @@ -1158,7 +1234,8 @@ public class DataSourceTransactionManagerTests { } })); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).rollback(); verify(con).close(); } @@ -1177,7 +1254,8 @@ public class DataSourceTransactionManagerTests { } })); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); InOrder ordered = inOrder(con); ordered.verify(con).setAutoCommit(false); ordered.verify(con).rollback(); @@ -1189,52 +1267,64 @@ public class DataSourceTransactionManagerTests { public void testTransactionWithPropagationSupports() throws Exception { TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Is not new transaction", !status.isNewTransaction()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Is not new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); } @Test public void testTransactionWithPropagationNotSupported() throws Exception { TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Is not new transaction", !status.isNewTransaction()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Is not new transaction").isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); } @Test public void testTransactionWithPropagationNever() throws Exception { TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Is not new transaction", !status.isNewTransaction()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition1).as("Hasn't thread connection").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Is not new transaction").isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); } @Test @@ -1259,31 +1349,37 @@ public class DataSourceTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); - assertTrue("Isn't nested transaction", !status.hasSavepoint()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + boolean condition1 = !status.hasSavepoint(); + assertThat(condition1).as("Isn't nested transaction").isTrue(); for (int i = 0; i < count; i++) { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Isn't new transaction", !status.isNewTransaction()); - assertTrue("Is nested transaction", status.hasSavepoint()); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Isn't new transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Is nested transaction").isTrue(); } }); } - assertTrue("Is new transaction", status.isNewTransaction()); - assertTrue("Isn't nested transaction", !status.hasSavepoint()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + boolean condition = !status.hasSavepoint(); + assertThat(condition).as("Isn't nested transaction").isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con, times(count)).releaseSavepoint(sp); verify(con).commit(); verify(con).close(); @@ -1300,30 +1396,36 @@ public class DataSourceTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); - assertTrue("Isn't nested transaction", !status.hasSavepoint()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + boolean condition1 = !status.hasSavepoint(); + assertThat(condition1).as("Isn't nested transaction").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Isn't new transaction", !status.isNewTransaction()); - assertTrue("Is nested transaction", status.hasSavepoint()); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Isn't new transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Is nested transaction").isTrue(); status.setRollbackOnly(); } }); - assertTrue("Is new transaction", status.isNewTransaction()); - assertTrue("Isn't nested transaction", !status.hasSavepoint()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + boolean condition = !status.hasSavepoint(); + assertThat(condition).as("Isn't nested transaction").isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).rollback(sp); verify(con).releaseSavepoint(sp); verify(con).commit(); @@ -1342,41 +1444,49 @@ public class DataSourceTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); - assertTrue("Isn't nested transaction", !status.hasSavepoint()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + boolean condition1 = !status.hasSavepoint(); + assertThat(condition1).as("Isn't nested transaction").isTrue(); assertThatIllegalStateException().isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Isn't new transaction", !status.isNewTransaction()); - assertTrue("Is nested transaction", status.hasSavepoint()); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Isn't new transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Is nested transaction").isTrue(); TransactionTemplate ntt = new TransactionTemplate(tm); ntt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Isn't new transaction", !status.isNewTransaction()); - assertTrue("Is regular transaction", !status.hasSavepoint()); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + boolean condition1 = !status.isNewTransaction(); + assertThat(condition1).as("Isn't new transaction").isTrue(); + boolean condition = !status.hasSavepoint(); + assertThat(condition).as("Is regular transaction").isTrue(); throw new IllegalStateException(); } }); } })); - assertTrue("Is new transaction", status.isNewTransaction()); - assertTrue("Isn't nested transaction", !status.hasSavepoint()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + boolean condition = !status.hasSavepoint(); + assertThat(condition).as("Isn't nested transaction").isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).rollback(sp); verify(con).releaseSavepoint(sp); verify(con).commit(); @@ -1395,41 +1505,49 @@ public class DataSourceTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); - assertTrue("Isn't nested transaction", !status.hasSavepoint()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + boolean condition1 = !status.hasSavepoint(); + assertThat(condition1).as("Isn't nested transaction").isTrue(); assertThatExceptionOfType(UnexpectedRollbackException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Isn't new transaction", !status.isNewTransaction()); - assertTrue("Is nested transaction", status.hasSavepoint()); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).as("Isn't new transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Is nested transaction").isTrue(); TransactionTemplate ntt = new TransactionTemplate(tm); ntt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue("Isn't new transaction", !status.isNewTransaction()); - assertTrue("Is regular transaction", !status.hasSavepoint()); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); + boolean condition1 = !status.isNewTransaction(); + assertThat(condition1).as("Isn't new transaction").isTrue(); + boolean condition = !status.hasSavepoint(); + assertThat(condition).as("Is regular transaction").isTrue(); status.setRollbackOnly(); } }); } })); - assertTrue("Is new transaction", status.isNewTransaction()); - assertTrue("Isn't nested transaction", !status.hasSavepoint()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); + boolean condition = !status.hasSavepoint(); + assertThat(condition).as("Isn't nested transaction").isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).rollback(sp); verify(con).releaseSavepoint(sp); verify(con).commit(); @@ -1448,20 +1566,23 @@ public class DataSourceTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); Object savepoint = status.createSavepoint(); status.releaseSavepoint(savepoint); - assertTrue("Is new transaction", status.isNewTransaction()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).releaseSavepoint(sp); verify(con).commit(); verify(con).close(); @@ -1479,20 +1600,23 @@ public class DataSourceTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); Object savepoint = status.createSavepoint(); status.rollbackToSavepoint(savepoint); - assertTrue("Is new transaction", status.isNewTransaction()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).rollback(sp); verify(con).commit(); verify(con).close(); @@ -1502,17 +1626,20 @@ public class DataSourceTransactionManagerTests { public void testTransactionWithPropagationNested() throws Exception { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).commit(); verify(con).close(); } @@ -1521,18 +1648,21 @@ public class DataSourceTransactionManagerTests { public void testTransactionWithPropagationNestedAndRollback() throws Exception { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); - assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition2).as("Hasn't thread connection").isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).as("Synchronization not active").isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertTrue("Is new transaction", status.isNewTransaction()); + assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); status.setRollbackOnly(); } }); - assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); + boolean condition = !TransactionSynchronizationManager.hasResource(ds); + assertThat(condition).as("Hasn't thread connection").isTrue(); verify(con).rollback(); verify(con).close(); } @@ -1576,13 +1706,13 @@ public class DataSourceTransactionManagerTests { if (this.status != TransactionSynchronization.STATUS_COMMITTED) { fail("Should never be called"); } - assertFalse(this.beforeCommitCalled); + assertThat(this.beforeCommitCalled).isFalse(); this.beforeCommitCalled = true; } @Override public void beforeCompletion() { - assertFalse(this.beforeCompletionCalled); + assertThat(this.beforeCompletionCalled).isFalse(); this.beforeCompletionCalled = true; } @@ -1591,7 +1721,7 @@ public class DataSourceTransactionManagerTests { if (this.status != TransactionSynchronization.STATUS_COMMITTED) { fail("Should never be called"); } - assertFalse(this.afterCommitCalled); + assertThat(this.afterCommitCalled).isFalse(); this.afterCommitCalled = true; } @@ -1606,10 +1736,10 @@ public class DataSourceTransactionManagerTests { } protected void doAfterCompletion(int status) { - assertFalse(this.afterCompletionCalled); + assertThat(this.afterCompletionCalled).isFalse(); this.afterCompletionCalled = true; - assertTrue(status == this.status); - assertTrue(TransactionSynchronizationManager.hasResource(this.dataSource)); + assertThat(status == this.status).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(this.dataSource)).isTrue(); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java index 4edbf49ae54..e4f27e05156 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java @@ -21,9 +21,8 @@ import java.util.Properties; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; /** @@ -42,9 +41,9 @@ public class DriverManagerDataSourceTests { class TestDriverManagerDataSource extends DriverManagerDataSource { @Override protected Connection getConnectionFromDriverManager(String url, Properties props) { - assertEquals(jdbcUrl, url); - assertEquals(uname, props.getProperty("user")); - assertEquals(pwd, props.getProperty("password")); + assertThat(url).isEqualTo(jdbcUrl); + assertThat(props.getProperty("user")).isEqualTo(uname); + assertThat(props.getProperty("password")).isEqualTo(pwd); return connection; } } @@ -56,11 +55,11 @@ public class DriverManagerDataSourceTests { ds.setPassword(pwd); Connection actualCon = ds.getConnection(); - assertTrue(actualCon == connection); + assertThat(actualCon == connection).isTrue(); - assertTrue(ds.getUrl().equals(jdbcUrl)); - assertTrue(ds.getPassword().equals(pwd)); - assertTrue(ds.getUsername().equals(uname)); + assertThat(ds.getUrl().equals(jdbcUrl)).isTrue(); + assertThat(ds.getPassword().equals(pwd)).isTrue(); + assertThat(ds.getUsername().equals(uname)).isTrue(); } @Test @@ -76,11 +75,11 @@ public class DriverManagerDataSourceTests { class TestDriverManagerDataSource extends DriverManagerDataSource { @Override protected Connection getConnectionFromDriverManager(String url, Properties props) { - assertEquals(jdbcUrl, url); - assertEquals("uname", props.getProperty("user")); - assertEquals("pwd", props.getProperty("password")); - assertEquals("myValue", props.getProperty("myProp")); - assertEquals("yourValue", props.getProperty("yourProp")); + assertThat(url).isEqualTo(jdbcUrl); + assertThat(props.getProperty("user")).isEqualTo("uname"); + assertThat(props.getProperty("password")).isEqualTo("pwd"); + assertThat(props.getProperty("myProp")).isEqualTo("myValue"); + assertThat(props.getProperty("yourProp")).isEqualTo("yourValue"); return connection; } } @@ -91,9 +90,9 @@ public class DriverManagerDataSourceTests { ds.setConnectionProperties(connProps); Connection actualCon = ds.getConnection(); - assertTrue(actualCon == connection); + assertThat(actualCon == connection).isTrue(); - assertTrue(ds.getUrl().equals(jdbcUrl)); + assertThat(ds.getUrl().equals(jdbcUrl)).isTrue(); } @Test @@ -111,11 +110,11 @@ public class DriverManagerDataSourceTests { class TestDriverManagerDataSource extends DriverManagerDataSource { @Override protected Connection getConnectionFromDriverManager(String url, Properties props) { - assertEquals(jdbcUrl, url); - assertEquals(uname, props.getProperty("user")); - assertEquals(pwd, props.getProperty("password")); - assertEquals("myValue", props.getProperty("myProp")); - assertEquals("yourValue", props.getProperty("yourProp")); + assertThat(url).isEqualTo(jdbcUrl); + assertThat(props.getProperty("user")).isEqualTo(uname); + assertThat(props.getProperty("password")).isEqualTo(pwd); + assertThat(props.getProperty("myProp")).isEqualTo("myValue"); + assertThat(props.getProperty("yourProp")).isEqualTo("yourValue"); return connection; } } @@ -128,11 +127,11 @@ public class DriverManagerDataSourceTests { ds.setConnectionProperties(connProps); Connection actualCon = ds.getConnection(); - assertTrue(actualCon == connection); + assertThat(actualCon == connection).isTrue(); - assertTrue(ds.getUrl().equals(jdbcUrl)); - assertTrue(ds.getPassword().equals(pwd)); - assertTrue(ds.getUsername().equals(uname)); + assertThat(ds.getUrl().equals(jdbcUrl)).isTrue(); + assertThat(ds.getPassword().equals(pwd)).isTrue(); + assertThat(ds.getUsername().equals(uname)).isTrue(); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapterTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapterTests.java index f2813ec51c7..e5418b2f0cb 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapterTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapterTests.java @@ -22,7 +22,7 @@ import javax.sql.DataSource; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -42,7 +42,7 @@ public class UserCredentialsDataSourceAdapterTests { adapter.setTargetDataSource(dataSource); adapter.setUsername("user"); adapter.setPassword("pw"); - assertEquals(connection, adapter.getConnection()); + assertThat(adapter.getConnection()).isEqualTo(connection); } @Test @@ -52,7 +52,7 @@ public class UserCredentialsDataSourceAdapterTests { given(dataSource.getConnection()).willReturn(connection); UserCredentialsDataSourceAdapter adapter = new UserCredentialsDataSourceAdapter(); adapter.setTargetDataSource(dataSource); - assertEquals(connection, adapter.getConnection()); + assertThat(adapter.getConnection()).isEqualTo(connection); } @Test @@ -66,7 +66,7 @@ public class UserCredentialsDataSourceAdapterTests { adapter.setCredentialsForCurrentThread("user", "pw"); try { - assertEquals(connection, adapter.getConnection()); + assertThat(adapter.getConnection()).isEqualTo(connection); } finally { adapter.removeCredentialsFromCurrentThread(); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java index 3c67ebb1d24..8222a8566f3 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java @@ -23,8 +23,8 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.init.CannotReadScriptException; import org.springframework.jdbc.datasource.init.ScriptStatementFailedException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.DERBY; import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.H2; @@ -205,7 +205,7 @@ public class EmbeddedDatabaseBuilderTests { } private void assertNumRowsInTestTable(JdbcTemplate template, int count) { - assertEquals(count, template.queryForObject("select count(*) from T_TEST", Integer.class).intValue()); + assertThat(template.queryForObject("select count(*) from T_TEST", Integer.class).intValue()).isEqualTo(count); } private void assertDatabaseCreated(EmbeddedDatabase db) { diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryBeanTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryBeanTests.java index 8745f441cac..973125ed0eb 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryBeanTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryBeanTests.java @@ -25,7 +25,7 @@ import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Keith Donald @@ -48,7 +48,7 @@ public class EmbeddedDatabaseFactoryBeanTests { bean.afterPropertiesSet(); DataSource ds = bean.getObject(); JdbcTemplate template = new JdbcTemplate(ds); - assertEquals("Keith", template.queryForObject("select NAME from T_TEST", String.class)); + assertThat(template.queryForObject("select NAME from T_TEST", String.class)).isEqualTo("Keith"); bean.destroy(); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryTests.java index a4043cc2e14..c811a4a4fd0 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactoryTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import org.springframework.jdbc.datasource.init.DatabasePopulator; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Keith Donald @@ -37,7 +37,7 @@ public class EmbeddedDatabaseFactoryTests { StubDatabasePopulator populator = new StubDatabasePopulator(); factory.setDatabasePopulator(populator); EmbeddedDatabase db = factory.getDatabase(); - assertTrue(populator.populateCalled); + assertThat(populator.populateCalled).isTrue(); db.shutdown(); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java index f0b033bd386..c36205ef78a 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/AbstractDatabasePopulatorTests.java @@ -25,7 +25,6 @@ import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.transaction.support.TransactionSynchronizationManager; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -190,7 +189,7 @@ public abstract class AbstractDatabasePopulatorTests extends AbstractDatabaseIni } private void assertTestDatabaseCreated(String name) { - assertEquals(name, jdbcTemplate.queryForObject("select NAME from T_TEST", String.class)); + assertThat(jdbcTemplate.queryForObject("select NAME from T_TEST", String.class)).isEqualTo(name); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulatorTests.java index 02065a93035..4f12b8560cd 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulatorTests.java @@ -21,8 +21,8 @@ import org.mockito.Mockito; import org.springframework.core.io.Resource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link ResourceDatabasePopulator}. @@ -53,22 +53,22 @@ public class ResourceDatabasePopulatorTests { @Test public void constructWithResource() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(script1); - assertEquals(1, databasePopulator.scripts.size()); + assertThat(databasePopulator.scripts.size()).isEqualTo(1); } @Test public void constructWithMultipleResources() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(script1, script2); - assertEquals(2, databasePopulator.scripts.size()); + assertThat(databasePopulator.scripts.size()).isEqualTo(2); } @Test public void constructWithMultipleResourcesAndThenAddScript() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(script1, script2); - assertEquals(2, databasePopulator.scripts.size()); + assertThat(databasePopulator.scripts.size()).isEqualTo(2); databasePopulator.addScript(script3); - assertEquals(3, databasePopulator.scripts.size()); + assertThat(databasePopulator.scripts.size()).isEqualTo(3); } @Test @@ -102,13 +102,13 @@ public class ResourceDatabasePopulatorTests { @Test public void setScriptsAndThenAddScript() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); - assertEquals(0, databasePopulator.scripts.size()); + assertThat(databasePopulator.scripts.size()).isEqualTo(0); databasePopulator.setScripts(script1, script2); - assertEquals(2, databasePopulator.scripts.size()); + assertThat(databasePopulator.scripts.size()).isEqualTo(2); databasePopulator.addScript(script3); - assertEquals(3, databasePopulator.scripts.size()); + assertThat(databasePopulator.scripts.size()).isEqualTo(3); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsUnitTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsUnitTests.java index 05cc55cb13a..d69e43051f3 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsUnitTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsUnitTests.java @@ -24,9 +24,7 @@ import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.EncodedResource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.jdbc.datasource.init.ScriptUtils.DEFAULT_STATEMENT_SEPARATOR; import static org.springframework.jdbc.datasource.init.ScriptUtils.containsSqlScriptDelimiters; import static org.springframework.jdbc.datasource.init.ScriptUtils.splitSqlScript; @@ -56,10 +54,10 @@ public class ScriptUtilsUnitTests { String script = rawStatement1 + delim + rawStatement2 + delim + rawStatement3 + delim; List statements = new ArrayList<>(); splitSqlScript(script, delim, statements); - assertEquals("wrong number of statements", 3, statements.size()); - assertEquals("statement 1 not split correctly", cleanedStatement1, statements.get(0)); - assertEquals("statement 2 not split correctly", cleanedStatement2, statements.get(1)); - assertEquals("statement 3 not split correctly", cleanedStatement3, statements.get(2)); + assertThat(statements.size()).as("wrong number of statements").isEqualTo(3); + assertThat(statements.get(0)).as("statement 1 not split correctly").isEqualTo(cleanedStatement1); + assertThat(statements.get(1)).as("statement 2 not split correctly").isEqualTo(cleanedStatement2); + assertThat(statements.get(2)).as("statement 3 not split correctly").isEqualTo(cleanedStatement3); } @Test @@ -71,10 +69,10 @@ public class ScriptUtilsUnitTests { String script = statement1 + delim + statement2 + delim + statement3 + delim; List statements = new ArrayList<>(); splitSqlScript(script, delim, statements); - assertEquals("wrong number of statements", 3, statements.size()); - assertEquals("statement 1 not split correctly", statement1, statements.get(0)); - assertEquals("statement 2 not split correctly", statement2, statements.get(1)); - assertEquals("statement 3 not split correctly", statement3, statements.get(2)); + assertThat(statements.size()).as("wrong number of statements").isEqualTo(3); + assertThat(statements.get(0)).as("statement 1 not split correctly").isEqualTo(statement1); + assertThat(statements.get(1)).as("statement 2 not split correctly").isEqualTo(statement2); + assertThat(statements.get(2)).as("statement 3 not split correctly").isEqualTo(statement3); } @Test @@ -85,9 +83,8 @@ public class ScriptUtilsUnitTests { String script = statement1 + delim + statement2 + delim; List statements = new ArrayList<>(); splitSqlScript(script, DEFAULT_STATEMENT_SEPARATOR, statements); - assertEquals("wrong number of statements", 1, statements.size()); - assertEquals("script should have been 'stripped' but not actually 'split'", script.replace('\n', ' '), - statements.get(0)); + assertThat(statements.size()).as("wrong number of statements").isEqualTo(1); + assertThat(statements.get(0)).as("script should have been 'stripped' but not actually 'split'").isEqualTo(script.replace('\n', ' ')); } @Test // SPR-13218 @@ -98,9 +95,9 @@ public class ScriptUtilsUnitTests { String script = statement1 + delim + statement2 + delim; List statements = new ArrayList<>(); splitSqlScript(script, ';', statements); - assertEquals("wrong number of statements", 2, statements.size()); - assertEquals("statement 1 not split correctly", statement1, statements.get(0)); - assertEquals("statement 2 not split correctly", statement2, statements.get(1)); + assertThat(statements.size()).as("wrong number of statements").isEqualTo(2); + assertThat(statements.get(0)).as("statement 1 not split correctly").isEqualTo(statement1); + assertThat(statements.get(1)).as("statement 2 not split correctly").isEqualTo(statement2); } @Test // SPR-11560 @@ -112,9 +109,9 @@ public class ScriptUtilsUnitTests { String statement1 = "insert into T_TEST (NAME) values ('Keith')"; String statement2 = "insert into T_TEST (NAME) values ('Dave')"; - assertEquals("wrong number of statements", 2, statements.size()); - assertEquals("statement 1 not split correctly", statement1, statements.get(0)); - assertEquals("statement 2 not split correctly", statement2, statements.get(1)); + assertThat(statements.size()).as("wrong number of statements").isEqualTo(2); + assertThat(statements.get(0)).as("statement 1 not split correctly").isEqualTo(statement1); + assertThat(statements.get(1)).as("statement 2 not split correctly").isEqualTo(statement2); } @Test @@ -129,11 +126,11 @@ public class ScriptUtilsUnitTests { // Statement 4 addresses the error described in SPR-9982. String statement4 = "INSERT INTO persons( person_id , name) VALUES( 1 , 'Name' )"; - assertEquals("wrong number of statements", 4, statements.size()); - assertEquals("statement 1 not split correctly", statement1, statements.get(0)); - assertEquals("statement 2 not split correctly", statement2, statements.get(1)); - assertEquals("statement 3 not split correctly", statement3, statements.get(2)); - assertEquals("statement 4 not split correctly", statement4, statements.get(3)); + assertThat(statements.size()).as("wrong number of statements").isEqualTo(4); + assertThat(statements.get(0)).as("statement 1 not split correctly").isEqualTo(statement1); + assertThat(statements.get(1)).as("statement 2 not split correctly").isEqualTo(statement2); + assertThat(statements.get(2)).as("statement 3 not split correctly").isEqualTo(statement3); + assertThat(statements.get(3)).as("statement 4 not split correctly").isEqualTo(statement4); } @Test // SPR-10330 @@ -146,10 +143,10 @@ public class ScriptUtilsUnitTests { String statement2 = "insert into orders(id, order_date, customer_id) values (1, '2013-06-08', 1)"; String statement3 = "insert into orders(id, order_date, customer_id) values (2, '2013-06-08', 1)"; - assertEquals("wrong number of statements", 3, statements.size()); - assertEquals("statement 1 not split correctly", statement1, statements.get(0)); - assertEquals("statement 2 not split correctly", statement2, statements.get(1)); - assertEquals("statement 3 not split correctly", statement3, statements.get(2)); + assertThat(statements.size()).as("wrong number of statements").isEqualTo(3); + assertThat(statements.get(0)).as("statement 1 not split correctly").isEqualTo(statement1); + assertThat(statements.get(1)).as("statement 2 not split correctly").isEqualTo(statement2); + assertThat(statements.get(2)).as("statement 3 not split correctly").isEqualTo(statement3); } @Test // SPR-9531 @@ -161,9 +158,9 @@ public class ScriptUtilsUnitTests { String statement1 = "INSERT INTO users(first_name, last_name) VALUES('Juergen', 'Hoeller')"; String statement2 = "INSERT INTO users(first_name, last_name) VALUES( 'Sam' , 'Brannen' )"; - assertEquals("wrong number of statements", 2, statements.size()); - assertEquals("statement 1 not split correctly", statement1, statements.get(0)); - assertEquals("statement 2 not split correctly", statement2, statements.get(1)); + assertThat(statements.size()).as("wrong number of statements").isEqualTo(2); + assertThat(statements.get(0)).as("statement 1 not split correctly").isEqualTo(statement1); + assertThat(statements.get(1)).as("statement 2 not split correctly").isEqualTo(statement2); } @Test @@ -175,25 +172,25 @@ public class ScriptUtilsUnitTests { String statement1 = "INSERT INTO users(first_name, last_name) VALUES('Juergen', 'Hoeller')"; String statement2 = "INSERT INTO users(first_name, last_name) VALUES( 'Sam' , 'Brannen' )"; - assertEquals("wrong number of statements", 2, statements.size()); - assertEquals("statement 1 not split correctly", statement1, statements.get(0)); - assertEquals("statement 2 not split correctly", statement2, statements.get(1)); + assertThat(statements.size()).as("wrong number of statements").isEqualTo(2); + assertThat(statements.get(0)).as("statement 1 not split correctly").isEqualTo(statement1); + assertThat(statements.get(1)).as("statement 2 not split correctly").isEqualTo(statement2); } @Test public void containsDelimiters() { - assertFalse(containsSqlScriptDelimiters("select 1\n select ';'", ";")); - assertTrue(containsSqlScriptDelimiters("select 1; select 2", ";")); + assertThat(containsSqlScriptDelimiters("select 1\n select ';'", ";")).isFalse(); + assertThat(containsSqlScriptDelimiters("select 1; select 2", ";")).isTrue(); - assertFalse(containsSqlScriptDelimiters("select 1; select '\\n\n';", "\n")); - assertTrue(containsSqlScriptDelimiters("select 1\n select 2", "\n")); + assertThat(containsSqlScriptDelimiters("select 1; select '\\n\n';", "\n")).isFalse(); + assertThat(containsSqlScriptDelimiters("select 1\n select 2", "\n")).isTrue(); - assertFalse(containsSqlScriptDelimiters("select 1\n select 2", "\n\n")); - assertTrue(containsSqlScriptDelimiters("select 1\n\n select 2", "\n\n")); + assertThat(containsSqlScriptDelimiters("select 1\n select 2", "\n\n")).isFalse(); + assertThat(containsSqlScriptDelimiters("select 1\n\n select 2", "\n\n")).isTrue(); // MySQL style escapes '\\' - assertFalse(containsSqlScriptDelimiters("insert into users(first_name, last_name)\nvalues('a\\\\', 'b;')", ";")); - assertTrue(containsSqlScriptDelimiters("insert into users(first_name, last_name)\nvalues('Charles', 'd\\'Artagnan'); select 1;", ";")); + assertThat(containsSqlScriptDelimiters("insert into users(first_name, last_name)\nvalues('a\\\\', 'b;')", ";")).isFalse(); + assertThat(containsSqlScriptDelimiters("insert into users(first_name, last_name)\nvalues('Charles', 'd\\'Artagnan'); select 1;", ";")).isTrue(); } private String readScript(String path) throws Exception { diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java index 12b464af609..524e7ac12a8 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java @@ -23,10 +23,9 @@ import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanNotOfRequiredTypeException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -50,9 +49,9 @@ public class BeanFactoryDataSourceLookupTests { BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(); lookup.setBeanFactory(beanFactory); DataSource dataSource = lookup.getDataSource(DATASOURCE_BEAN_NAME); - assertNotNull("A DataSourceLookup implementation must *never* return null from " + - "getDataSource(): this one obviously (and incorrectly) is", dataSource); - assertSame(expectedDataSource, dataSource); + assertThat(dataSource).as("A DataSourceLookup implementation must *never* return null from " + + "getDataSource(): this one obviously (and incorrectly) is").isNotNull(); + assertThat(dataSource).isSameAs(expectedDataSource); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/JndiDataSourceLookupTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/JndiDataSourceLookupTests.java index bd04f50c99d..33e4f84e095 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/JndiDataSourceLookupTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/JndiDataSourceLookupTests.java @@ -21,10 +21,8 @@ import javax.sql.DataSource; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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 Rick Evans @@ -40,13 +38,13 @@ public class JndiDataSourceLookupTests { JndiDataSourceLookup lookup = new JndiDataSourceLookup() { @Override protected T lookup(String jndiName, Class requiredType) { - assertEquals(DATA_SOURCE_NAME, jndiName); + assertThat(jndiName).isEqualTo(DATA_SOURCE_NAME); return requiredType.cast(expectedDataSource); } }; DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME); - assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource); - assertSame(expectedDataSource, dataSource); + assertThat(dataSource).as("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is").isNotNull(); + assertThat(dataSource).isSameAs(expectedDataSource); } @Test @@ -54,7 +52,7 @@ public class JndiDataSourceLookupTests { JndiDataSourceLookup lookup = new JndiDataSourceLookup() { @Override protected T lookup(String jndiName, Class requiredType) throws NamingException { - assertEquals(DATA_SOURCE_NAME, jndiName); + assertThat(jndiName).isEqualTo(DATA_SOURCE_NAME); throw new NamingException(); } }; diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/MapDataSourceLookupTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/MapDataSourceLookupTests.java index 60af638b809..ffb28069860 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/MapDataSourceLookupTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/MapDataSourceLookupTests.java @@ -22,9 +22,8 @@ import javax.sql.DataSource; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; /** * @author Rick Evans @@ -53,8 +52,8 @@ public class MapDataSourceLookupTests { MapDataSourceLookup lookup = new MapDataSourceLookup(); lookup.setDataSources(dataSources); DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME); - assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource); - assertSame(expectedDataSource, dataSource); + assertThat(dataSource).as("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is").isNotNull(); + assertThat(dataSource).isSameAs(expectedDataSource); } @Test @@ -66,8 +65,8 @@ public class MapDataSourceLookupTests { lookup.setDataSources(dataSources); lookup.setDataSources(null); // must be idempotent (i.e. the following lookup must still work); DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME); - assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource); - assertSame(expectedDataSource, dataSource); + assertThat(dataSource).as("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is").isNotNull(); + assertThat(dataSource).isSameAs(expectedDataSource); } @Test @@ -80,8 +79,8 @@ public class MapDataSourceLookupTests { lookup.setDataSources(dataSources); lookup.addDataSource(DATA_SOURCE_NAME, expectedDataSource); // must override existing entry DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME); - assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource); - assertSame(expectedDataSource, dataSource); + assertThat(dataSource).as("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is").isNotNull(); + assertThat(dataSource).isSameAs(expectedDataSource); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/BatchSqlUpdateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/BatchSqlUpdateTests.java index c18b490eec1..1cc00856647 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/BatchSqlUpdateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/BatchSqlUpdateTests.java @@ -26,8 +26,7 @@ import org.junit.Test; import org.springframework.jdbc.core.SqlParameter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -76,33 +75,33 @@ public class BatchSqlUpdateTests { update.update(ids[1]); if (flushThroughBatchSize) { - assertEquals(0, update.getQueueCount()); - assertEquals(2, update.getRowsAffected().length); + assertThat(update.getQueueCount()).isEqualTo(0); + assertThat(update.getRowsAffected().length).isEqualTo(2); } else { - assertEquals(2, update.getQueueCount()); - assertEquals(0, update.getRowsAffected().length); + assertThat(update.getQueueCount()).isEqualTo(2); + assertThat(update.getRowsAffected().length).isEqualTo(0); } int[] actualRowsAffected = update.flush(); - assertEquals(0, update.getQueueCount()); + assertThat(update.getQueueCount()).isEqualTo(0); if (flushThroughBatchSize) { - assertTrue("flush did not execute updates", actualRowsAffected.length == 0); + assertThat(actualRowsAffected.length == 0).as("flush did not execute updates").isTrue(); } else { - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); } actualRowsAffected = update.getRowsAffected(); - assertTrue("executed 2 updates", actualRowsAffected.length == 2); - assertEquals(rowsAffected[0], actualRowsAffected[0]); - assertEquals(rowsAffected[1], actualRowsAffected[1]); + assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); + assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); update.reset(); - assertEquals(0, update.getRowsAffected().length); + assertThat(update.getRowsAffected().length).isEqualTo(0); verify(preparedStatement).setObject(1, ids[0], Types.INTEGER); verify(preparedStatement).setObject(1, ids[1], Types.INTEGER); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericSqlQueryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericSqlQueryTests.java index 9a348afc630..ad6ee1212c8 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericSqlQueryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericSqlQueryTests.java @@ -35,7 +35,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.Customer; import org.springframework.jdbc.datasource.TestDataSourceWrapper; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -109,10 +109,10 @@ public class GenericSqlQueryTests { Object[] params = new Object[] {1, "UK"}; queryResults = query.execute(params); } - assertTrue("Customer was returned correctly", queryResults.size() == 1); + assertThat(queryResults.size() == 1).as("Customer was returned correctly").isTrue(); Customer cust = (Customer) queryResults.get(0); - assertTrue("Customer id was assigned correctly", cust.getId() == 1); - assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod")); + assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(resultSet).close(); verify(preparedStatement).setObject(1, 1, Types.INTEGER); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericStoredProcedureTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericStoredProcedureTests.java index 072474645f3..196b4c9f795 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericStoredProcedureTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericStoredProcedureTests.java @@ -30,7 +30,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.TestDataSourceWrapper; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -64,7 +64,7 @@ public class GenericStoredProcedureTests { in.put("custid", 3); Map out = adder.execute(in); Integer id = (Integer) out.get("newid"); - assertEquals(4, id.intValue()); + assertThat(id.intValue()).isEqualTo(4); verify(callableStatement).setObject(1, 1106, Types.INTEGER); verify(callableStatement).setObject(2, 3, Types.INTEGER); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/RdbmsOperationTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/RdbmsOperationTests.java index 66655ed69f0..1014dc4e172 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/RdbmsOperationTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/RdbmsOperationTests.java @@ -30,8 +30,8 @@ import org.springframework.jdbc.core.SqlOutParameter; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * @author Trevor Cook @@ -132,9 +132,9 @@ public class RdbmsOperationTests { operation.setFetchSize(10); operation.setMaxRows(20); JdbcTemplate jt = operation.getJdbcTemplate(); - assertEquals(ds, jt.getDataSource()); - assertEquals(10, jt.getFetchSize()); - assertEquals(20, jt.getMaxRows()); + assertThat(jt.getDataSource()).isEqualTo(ds); + assertThat(jt.getFetchSize()).isEqualTo(10); + assertThat(jt.getMaxRows()).isEqualTo(20); } @Test @@ -156,7 +156,7 @@ public class RdbmsOperationTests { new SqlParameter("two", Types.NUMERIC)}); operation.afterPropertiesSet(); operation.validateParameters(new Object[] { 1, "2" }); - assertEquals(2, operation.getDeclaredParameters().size()); + assertThat(operation.getDeclaredParameters().size()).isEqualTo(2); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlQueryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlQueryTests.java index 0c54377cb9c..666ac15eb75 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlQueryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlQueryTests.java @@ -41,8 +41,6 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -112,8 +110,8 @@ public class SqlQueryTests { @Override protected Integer mapRow(ResultSet rs, int rownum, @Nullable Object[] params, @Nullable Map context) throws SQLException { - assertTrue("params were null", params == null); - assertTrue("context was null", context == null); + assertThat(params == null).as("params were null").isTrue(); + assertThat(context == null).as("context was null").isTrue(); return rs.getInt(1); } }; @@ -222,8 +220,8 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); Customer cust = query.findCustomer(1, 1); - assertTrue("Customer id was assigned correctly", cust.getId() == 1); - assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod")); + assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setObject(2, 1, Types.NUMERIC); verify(connection).prepareStatement(SELECT_ID_WHERE); @@ -262,9 +260,8 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); Customer cust = query.findCustomer("rod"); - assertTrue("Customer id was assigned correctly", cust.getId() == 1); - assertTrue("Customer forename was assigned correctly", - cust.getForename().equals("rod")); + assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(preparedStatement).setString(1, "rod"); verify(connection).prepareStatement(SELECT_ID_FORENAME_WHERE); verify(resultSet).close(); @@ -309,11 +306,11 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); Customer cust1 = query.findCustomer(1, "rod"); - assertTrue("Found customer", cust1 != null); - assertTrue("Customer id was assigned correctly", cust1.getId() == 1); + assertThat(cust1 != null).as("Found customer").isTrue(); + assertThat(cust1.getId() == 1).as("Customer id was assigned correctly").isTrue(); Customer cust2 = query.findCustomer(1, "Roger"); - assertTrue("No customer found", cust2 == null); + assertThat(cust2 == null).as("No customer found").isTrue(); verify(preparedStatement).setObject(1, 1, Types.INTEGER); verify(preparedStatement).setString(2, "rod"); @@ -389,7 +386,7 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); List list = query.execute(1, 1); - assertTrue("2 results in list", list.size() == 2); + assertThat(list.size() == 2).as("2 results in list").isTrue(); assertThat(list.get(0).getForename()).isEqualTo("rod"); assertThat(list.get(1).getForename()).isEqualTo("dave"); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); @@ -425,7 +422,7 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); List list = query.execute("one"); - assertTrue("2 results in list", list.size() == 2); + assertThat(list.size() == 2).as("2 results in list").isTrue(); assertThat(list.get(0).getForename()).isEqualTo("rod"); assertThat(list.get(1).getForename()).isEqualTo("dave"); verify(preparedStatement).setString(1, "one"); @@ -469,8 +466,8 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); Customer cust = query.findCustomer(1); - assertTrue("Customer id was assigned correctly", cust.getId() == 1); - assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod")); + assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(resultSet).close(); verify(preparedStatement).close(); @@ -565,8 +562,8 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); Customer cust = query.findCustomer(1, "UK"); - assertTrue("Customer id was assigned correctly", cust.getId() == 1); - assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod")); + assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setString(2, "UK"); verify(resultSet).close(); @@ -614,11 +611,11 @@ public class SqlQueryTests { ids.add(2); List cust = query.findCustomers(ids); - assertEquals("We got two customers back", 2, cust.size()); - assertEquals("First customer id was assigned correctly", cust.get(0).getId(), 1); - assertEquals("First customer forename was assigned correctly", cust.get(0).getForename(), "rod"); - assertEquals("Second customer id was assigned correctly", cust.get(1).getId(), 2); - assertEquals("Second customer forename was assigned correctly", cust.get(1).getForename(), "juergen"); + assertThat(cust.size()).as("We got two customers back").isEqualTo(2); + assertThat(1).as("First customer id was assigned correctly").isEqualTo(cust.get(0).getId()); + assertThat("rod").as("First customer forename was assigned correctly").isEqualTo(cust.get(0).getForename()); + assertThat(2).as("Second customer id was assigned correctly").isEqualTo(cust.get(1).getId()); + assertThat("juergen").as("Second customer forename was assigned correctly").isEqualTo(cust.get(1).getForename()); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setObject(2, 2, Types.NUMERIC); verify(resultSet).close(); @@ -663,11 +660,11 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); List cust = query.findCustomers(1); - assertEquals("We got two customers back", 2, cust.size()); - assertEquals("First customer id was assigned correctly", cust.get(0).getId(), 1); - assertEquals("First customer forename was assigned correctly", cust.get(0).getForename(), "rod"); - assertEquals("Second customer id was assigned correctly", cust.get(1).getId(), 2); - assertEquals("Second customer forename was assigned correctly", cust.get(1).getForename(), "juergen"); + assertThat(cust.size()).as("We got two customers back").isEqualTo(2); + assertThat(1).as("First customer id was assigned correctly").isEqualTo(cust.get(0).getId()); + assertThat("rod").as("First customer forename was assigned correctly").isEqualTo(cust.get(0).getForename()); + assertThat(2).as("Second customer id was assigned correctly").isEqualTo(cust.get(1).getId()); + assertThat("juergen").as("Second customer forename was assigned correctly").isEqualTo(cust.get(1).getForename()); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setObject(2, 1, Types.NUMERIC); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlUpdateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlUpdateTests.java index 2e2a83464c6..ca95483ccd9 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlUpdateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlUpdateTests.java @@ -35,8 +35,8 @@ import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -105,7 +105,7 @@ public class SqlUpdateTests { Updater pc = new Updater(); int rowsAffected = pc.run(); - assertEquals(1, rowsAffected); + assertThat(rowsAffected).isEqualTo(1); } @Test @@ -116,7 +116,7 @@ public class SqlUpdateTests { IntUpdater pc = new IntUpdater(); int rowsAffected = pc.run(1); - assertEquals(1, rowsAffected); + assertThat(rowsAffected).isEqualTo(1); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); } @@ -128,7 +128,7 @@ public class SqlUpdateTests { IntIntUpdater pc = new IntIntUpdater(); int rowsAffected = pc.run(1, 1); - assertEquals(1, rowsAffected); + assertThat(rowsAffected).isEqualTo(1); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setObject(2, 1, Types.NUMERIC); } @@ -173,7 +173,7 @@ public class SqlUpdateTests { NamedParameterUpdater pc = new NamedParameterUpdater(); int rowsAffected = pc.run(1, 1); - assertEquals(1, rowsAffected); + assertThat(rowsAffected).isEqualTo(1); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setObject(2, 1, Types.DECIMAL); } @@ -186,7 +186,7 @@ public class SqlUpdateTests { StringUpdater pc = new StringUpdater(); int rowsAffected = pc.run("rod"); - assertEquals(1, rowsAffected); + assertThat(rowsAffected).isEqualTo(1); verify(preparedStatement).setString(1, "rod"); } @@ -198,7 +198,7 @@ public class SqlUpdateTests { MixedUpdater pc = new MixedUpdater(); int rowsAffected = pc.run(1, 1, "rod", true); - assertEquals(1, rowsAffected); + assertThat(rowsAffected).isEqualTo(1); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setObject(2, 1, Types.NUMERIC, 2); verify(preparedStatement).setString(3, "rod"); @@ -222,9 +222,9 @@ public class SqlUpdateTests { KeyHolder generatedKeyHolder = new GeneratedKeyHolder(); int rowsAffected = pc.run("rod", generatedKeyHolder); - assertEquals(1, rowsAffected); - assertEquals(1, generatedKeyHolder.getKeyList().size()); - assertEquals(11, generatedKeyHolder.getKey().intValue()); + assertThat(rowsAffected).isEqualTo(1); + assertThat(generatedKeyHolder.getKeyList().size()).isEqualTo(1); + assertThat(generatedKeyHolder.getKey().intValue()).isEqualTo(11); verify(preparedStatement).setString(1, "rod"); verify(resultSet).close(); } @@ -237,7 +237,7 @@ public class SqlUpdateTests { int rowsAffected = pc.run(1, 1, "rod", true); - assertEquals(1, rowsAffected); + assertThat(rowsAffected).isEqualTo(1); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setObject(2, 1, Types.NUMERIC); verify(preparedStatement).setString(3, "rod"); @@ -252,7 +252,7 @@ public class SqlUpdateTests { MaxRowsUpdater pc = new MaxRowsUpdater(); int rowsAffected = pc.run(); - assertEquals(3, rowsAffected); + assertThat(rowsAffected).isEqualTo(3); } @Test @@ -263,7 +263,7 @@ public class SqlUpdateTests { MaxRowsUpdater pc = new MaxRowsUpdater(); int rowsAffected = pc.run(); - assertEquals(5, rowsAffected); + assertThat(rowsAffected).isEqualTo(5); } @Test @@ -285,7 +285,7 @@ public class SqlUpdateTests { RequiredRowsUpdater pc = new RequiredRowsUpdater(); int rowsAffected = pc.run(); - assertEquals(3, rowsAffected); + assertThat(rowsAffected).isEqualTo(3); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java index f29f762dfc3..de3ca838077 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java @@ -50,9 +50,8 @@ import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; import org.springframework.lang.Nullable; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.startsWith; import static org.mockito.BDDMockito.given; @@ -107,14 +106,14 @@ public class StoredProcedureTests { private void testAddInvoice(final int amount, final int custid) throws Exception { AddInvoice adder = new AddInvoice(dataSource); int id = adder.execute(amount, custid); - assertEquals(4, id); + assertThat(id).isEqualTo(4); } private void testAddInvoiceUsingObjectArray(final int amount, final int custid) throws Exception { AddInvoiceUsingObjectArray adder = new AddInvoiceUsingObjectArray(dataSource); int id = adder.execute(amount, custid); - assertEquals(5, id); + assertThat(id).isEqualTo(5); } @Test @@ -195,8 +194,8 @@ public class StoredProcedureTests { t.setExceptionTranslator(new SQLStateSQLExceptionTranslator()); StoredProcedureConfiguredViaJdbcTemplate sp = new StoredProcedureConfiguredViaJdbcTemplate(t); - assertEquals(5, sp.execute(11)); - assertEquals(1, t.calls); + assertThat(sp.execute(11)).isEqualTo(5); + assertThat(t.calls).isEqualTo(1); verify(callableStatement).setObject(1, 11, Types.INTEGER); verify(callableStatement).registerOutParameter(2, Types.INTEGER); @@ -215,7 +214,7 @@ public class StoredProcedureTests { JdbcTemplate t = new JdbcTemplate(); t.setDataSource(dataSource); StoredProcedureConfiguredViaJdbcTemplate sp = new StoredProcedureConfiguredViaJdbcTemplate(t); - assertEquals(4, sp.execute(1106)); + assertThat(sp.execute(1106)).isEqualTo(4); verify(callableStatement).setObject(1, 1106, Types.INTEGER); verify(callableStatement).registerOutParameter(2, Types.INTEGER); } @@ -270,7 +269,7 @@ public class StoredProcedureTests { ).willReturn(callableStatement); StoredProcedureWithResultSet sproc = new StoredProcedureWithResultSet(dataSource); sproc.execute(); - assertEquals(2, sproc.getCount()); + assertThat(sproc.getCount()).isEqualTo(2); verify(resultSet).close(); } @@ -290,9 +289,9 @@ public class StoredProcedureTests { StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(dataSource); Map res = sproc.execute(); List rs = (List) res.get("rs"); - assertEquals(2, rs.size()); - assertEquals("Foo", rs.get(0)); - assertEquals("Bar", rs.get(1)); + assertThat(rs.size()).isEqualTo(2); + assertThat(rs.get(0)).isEqualTo("Foo"); + assertThat(rs.get(1)).isEqualTo("Bar"); verify(resultSet).close(); } @@ -325,23 +324,24 @@ public class StoredProcedureTests { StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(dataSource); Map res = sproc.execute(); - assertEquals("incorrect number of returns", 3, res.size()); + assertThat(res.size()).as("incorrect number of returns").isEqualTo(3); List rs1 = (List) res.get("rs"); - assertEquals(2, rs1.size()); - assertEquals("Foo", rs1.get(0)); - assertEquals("Bar", rs1.get(1)); + assertThat(rs1.size()).isEqualTo(2); + assertThat(rs1.get(0)).isEqualTo("Foo"); + assertThat(rs1.get(1)).isEqualTo("Bar"); List rs2 = (List) res.get("#result-set-2"); - assertEquals(1, rs2.size()); + assertThat(rs2.size()).isEqualTo(1); Object o2 = rs2.get(0); - assertTrue("wron type returned for result set 2", o2 instanceof Map); + boolean condition = o2 instanceof Map; + assertThat(condition).as("wron type returned for result set 2").isTrue(); Map m2 = (Map) o2; - assertEquals("Spam", m2.get("spam")); - assertEquals("Eggs", m2.get("eggs")); + assertThat(m2.get("spam")).isEqualTo("Spam"); + assertThat(m2.get("eggs")).isEqualTo("Eggs"); Number n = (Number) res.get("#update-count-1"); - assertEquals("wrong update count", 0, n.intValue()); + assertThat(n.intValue()).as("wrong update count").isEqualTo(0); verify(resultSet1).close(); verify(resultSet2).close(); } @@ -357,7 +357,7 @@ public class StoredProcedureTests { StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped( jdbcTemplate); Map res = sproc.execute(); - assertEquals("incorrect number of returns", 0, res.size()); + assertThat(res.size()).as("incorrect number of returns").isEqualTo(0); } @Test @@ -380,11 +380,11 @@ public class StoredProcedureTests { jdbcTemplate); Map res = sproc.execute(); - assertEquals("incorrect number of returns", 1, res.size()); + assertThat(res.size()).as("incorrect number of returns").isEqualTo(1); List rs1 = (List) res.get("rs"); - assertEquals(2, rs1.size()); - assertEquals("Foo", rs1.get(0)); - assertEquals("Bar", rs1.get(1)); + assertThat(rs1.size()).isEqualTo(2); + assertThat(rs1.get(0)).isEqualTo("Foo"); + assertThat(rs1.get(1)).isEqualTo("Bar"); verify(resultSet).close(); } @@ -398,7 +398,7 @@ public class StoredProcedureTests { ParameterMapperStoredProcedure pmsp = new ParameterMapperStoredProcedure(dataSource); Map out = pmsp.executeTest(); - assertEquals("OK", out.get("out")); + assertThat(out.get("out")).isEqualTo("OK"); verify(callableStatement).setString(eq(1), startsWith("Mock for Connection")); verify(callableStatement).registerOutParameter(2, Types.VARCHAR); @@ -415,7 +415,7 @@ public class StoredProcedureTests { SqlTypeValueStoredProcedure stvsp = new SqlTypeValueStoredProcedure(dataSource); Map out = stvsp.executeTest(testVal); - assertEquals("OK", out.get("out")); + assertThat(out.get("out")).isEqualTo("OK"); verify(callableStatement).setObject(1, testVal, Types.ARRAY); verify(callableStatement).registerOutParameter(2, Types.VARCHAR); } @@ -429,7 +429,7 @@ public class StoredProcedureTests { ).willReturn(callableStatement); NumericWithScaleStoredProcedure nwssp = new NumericWithScaleStoredProcedure(dataSource); Map out = nwssp.executeTest(); - assertEquals(new BigDecimal("12345.6789"), out.get("out")); + assertThat(out.get("out")).isEqualTo(new BigDecimal("12345.6789")); verify(callableStatement).registerOutParameter(1, Types.DECIMAL, 4); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/CustomSQLExceptionTranslatorRegistrarTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/CustomSQLExceptionTranslatorRegistrarTests.java index 9a6c5af3777..6001786ad79 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/CustomSQLExceptionTranslatorRegistrarTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/CustomSQLExceptionTranslatorRegistrarTests.java @@ -25,9 +25,7 @@ import org.springframework.dao.DataAccessException; import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.BadSqlGrammarException; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for custom {@link SQLExceptionTranslator}. @@ -47,17 +45,15 @@ public class CustomSQLExceptionTranslatorRegistrarTests { sext.setSqlErrorCodes(codes); DataAccessException exFor4200 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 42000)); - assertNotNull("Should have been translated", exFor4200); - assertTrue("Should have been instance of BadSqlGrammarException", - BadSqlGrammarException.class.isAssignableFrom(exFor4200.getClass())); + assertThat(exFor4200).as("Should have been translated").isNotNull(); + assertThat(BadSqlGrammarException.class.isAssignableFrom(exFor4200.getClass())).as("Should have been instance of BadSqlGrammarException").isTrue(); DataAccessException exFor2 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 2)); - assertNotNull("Should have been translated", exFor2); - assertTrue("Should have been instance of TransientDataAccessResourceException", - TransientDataAccessResourceException.class.isAssignableFrom(exFor2.getClass())); + assertThat(exFor2).as("Should have been translated").isNotNull(); + assertThat(TransientDataAccessResourceException.class.isAssignableFrom(exFor2.getClass())).as("Should have been instance of TransientDataAccessResourceException").isTrue(); DataAccessException exFor3 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 3)); - assertNull("Should not have been translated", exFor3); + assertThat(exFor3).as("Should not have been translated").isNull(); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/DataFieldMaxValueIncrementerTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/DataFieldMaxValueIncrementerTests.java index 4facf62c9b9..5fe3e41acb4 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/DataFieldMaxValueIncrementerTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/DataFieldMaxValueIncrementerTests.java @@ -30,7 +30,7 @@ import org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer; import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer; import org.springframework.jdbc.support.incrementer.PostgresSequenceMaxValueIncrementer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -65,8 +65,8 @@ public class DataFieldMaxValueIncrementerTests { incrementer.setPaddingLength(2); incrementer.afterPropertiesSet(); - assertEquals(10, incrementer.nextLongValue()); - assertEquals("12", incrementer.nextStringValue()); + assertThat(incrementer.nextLongValue()).isEqualTo(10); + assertThat(incrementer.nextStringValue()).isEqualTo("12"); verify(resultSet, times(2)).close(); verify(statement, times(2)).close(); @@ -89,11 +89,11 @@ public class DataFieldMaxValueIncrementerTests { incrementer.setPaddingLength(3); incrementer.afterPropertiesSet(); - assertEquals(0, incrementer.nextIntValue()); - assertEquals(1, incrementer.nextLongValue()); - assertEquals("002", incrementer.nextStringValue()); - assertEquals(3, incrementer.nextIntValue()); - assertEquals(4, incrementer.nextLongValue()); + assertThat(incrementer.nextIntValue()).isEqualTo(0); + assertThat(incrementer.nextLongValue()).isEqualTo(1); + assertThat(incrementer.nextStringValue()).isEqualTo("002"); + assertThat(incrementer.nextIntValue()).isEqualTo(3); + assertThat(incrementer.nextLongValue()).isEqualTo(4); verify(statement, times(6)).executeUpdate("insert into myseq values(null)"); verify(statement).executeUpdate("delete from myseq where seq < 2"); @@ -120,11 +120,11 @@ public class DataFieldMaxValueIncrementerTests { incrementer.setDeleteSpecificValues(true); incrementer.afterPropertiesSet(); - assertEquals(0, incrementer.nextIntValue()); - assertEquals(1, incrementer.nextLongValue()); - assertEquals("002", incrementer.nextStringValue()); - assertEquals(3, incrementer.nextIntValue()); - assertEquals(4, incrementer.nextLongValue()); + assertThat(incrementer.nextIntValue()).isEqualTo(0); + assertThat(incrementer.nextLongValue()).isEqualTo(1); + assertThat(incrementer.nextStringValue()).isEqualTo("002"); + assertThat(incrementer.nextIntValue()).isEqualTo(3); + assertThat(incrementer.nextLongValue()).isEqualTo(4); verify(statement, times(6)).executeUpdate("insert into myseq values(null)"); verify(statement).executeUpdate("delete from myseq where seq in (-1, 0, 1)"); @@ -150,10 +150,10 @@ public class DataFieldMaxValueIncrementerTests { incrementer.setPaddingLength(1); incrementer.afterPropertiesSet(); - assertEquals(1, incrementer.nextIntValue()); - assertEquals(2, incrementer.nextLongValue()); - assertEquals("3", incrementer.nextStringValue()); - assertEquals(4, incrementer.nextLongValue()); + assertThat(incrementer.nextIntValue()).isEqualTo(1); + assertThat(incrementer.nextLongValue()).isEqualTo(2); + assertThat(incrementer.nextStringValue()).isEqualTo("3"); + assertThat(incrementer.nextLongValue()).isEqualTo(4); verify(statement, times(2)).executeUpdate("update myseq set seq = last_insert_id(seq + 2)"); verify(resultSet, times(2)).close(); @@ -175,8 +175,8 @@ public class DataFieldMaxValueIncrementerTests { incrementer.setPaddingLength(2); incrementer.afterPropertiesSet(); - assertEquals(10, incrementer.nextLongValue()); - assertEquals("12", incrementer.nextStringValue()); + assertThat(incrementer.nextLongValue()).isEqualTo(10); + assertThat(incrementer.nextStringValue()).isEqualTo("12"); verify(resultSet, times(2)).close(); verify(statement, times(2)).close(); @@ -197,8 +197,8 @@ public class DataFieldMaxValueIncrementerTests { incrementer.setPaddingLength(5); incrementer.afterPropertiesSet(); - assertEquals("00010", incrementer.nextStringValue()); - assertEquals(12, incrementer.nextIntValue()); + assertThat(incrementer.nextStringValue()).isEqualTo("00010"); + assertThat(incrementer.nextIntValue()).isEqualTo(12); verify(resultSet, times(2)).close(); verify(statement, times(2)).close(); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/JdbcUtilsTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/JdbcUtilsTests.java index fcaf2810016..43bdb2660b3 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/JdbcUtilsTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/JdbcUtilsTests.java @@ -20,8 +20,7 @@ import java.sql.Types; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link JdbcUtils}. @@ -33,27 +32,27 @@ public class JdbcUtilsTests { @Test public void commonDatabaseName() { - assertEquals("Oracle", JdbcUtils.commonDatabaseName("Oracle")); - assertEquals("DB2", JdbcUtils.commonDatabaseName("DB2-for-Spring")); - assertEquals("Sybase", JdbcUtils.commonDatabaseName("Sybase SQL Server")); - assertEquals("Sybase", JdbcUtils.commonDatabaseName("Adaptive Server Enterprise")); - assertEquals("MySQL", JdbcUtils.commonDatabaseName("MySQL")); + assertThat(JdbcUtils.commonDatabaseName("Oracle")).isEqualTo("Oracle"); + assertThat(JdbcUtils.commonDatabaseName("DB2-for-Spring")).isEqualTo("DB2"); + assertThat(JdbcUtils.commonDatabaseName("Sybase SQL Server")).isEqualTo("Sybase"); + assertThat(JdbcUtils.commonDatabaseName("Adaptive Server Enterprise")).isEqualTo("Sybase"); + assertThat(JdbcUtils.commonDatabaseName("MySQL")).isEqualTo("MySQL"); } @Test public void resolveTypeName() { - assertEquals("VARCHAR", JdbcUtils.resolveTypeName(Types.VARCHAR)); - assertEquals("NUMERIC", JdbcUtils.resolveTypeName(Types.NUMERIC)); - assertEquals("INTEGER", JdbcUtils.resolveTypeName(Types.INTEGER)); - assertNull(JdbcUtils.resolveTypeName(JdbcUtils.TYPE_UNKNOWN)); + assertThat(JdbcUtils.resolveTypeName(Types.VARCHAR)).isEqualTo("VARCHAR"); + assertThat(JdbcUtils.resolveTypeName(Types.NUMERIC)).isEqualTo("NUMERIC"); + assertThat(JdbcUtils.resolveTypeName(Types.INTEGER)).isEqualTo("INTEGER"); + assertThat(JdbcUtils.resolveTypeName(JdbcUtils.TYPE_UNKNOWN)).isNull(); } @Test public void convertUnderscoreNameToPropertyName() { - assertEquals("myName", JdbcUtils.convertUnderscoreNameToPropertyName("MY_NAME")); - assertEquals("yourName", JdbcUtils.convertUnderscoreNameToPropertyName("yOUR_nAME")); - assertEquals("AName", JdbcUtils.convertUnderscoreNameToPropertyName("a_name")); - assertEquals("someoneElsesName", JdbcUtils.convertUnderscoreNameToPropertyName("someone_elses_name")); + assertThat(JdbcUtils.convertUnderscoreNameToPropertyName("MY_NAME")).isEqualTo("myName"); + assertThat(JdbcUtils.convertUnderscoreNameToPropertyName("yOUR_nAME")).isEqualTo("yourName"); + assertThat(JdbcUtils.convertUnderscoreNameToPropertyName("a_name")).isEqualTo("AName"); + assertThat(JdbcUtils.convertUnderscoreNameToPropertyName("someone_elses_name")).isEqualTo("someoneElsesName"); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/KeyHolderTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/KeyHolderTests.java index 90789d6d735..8bb38b025e7 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/KeyHolderTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/KeyHolderTests.java @@ -28,8 +28,8 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * Tests for {@link KeyHolder} and {@link GeneratedKeyHolder}. @@ -48,7 +48,7 @@ public class KeyHolderTests { public void singleKey() { kh.getKeyList().addAll(singletonList(singletonMap("key", 1))); - assertEquals("single key should be returned", 1, kh.getKey().intValue()); + assertThat(kh.getKey().intValue()).as("single key should be returned").isEqualTo(1); } @Test @@ -77,7 +77,7 @@ public class KeyHolderTests { }}; kh.getKeyList().addAll(singletonList(m)); - assertEquals("two keys should be in the map", 2, kh.getKeys().size()); + assertThat(kh.getKeys().size()).as("two keys should be in the map").isEqualTo(2); assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> kh.getKey()) .withMessageStartingWith("The getKey method should only be used when a single key is returned."); @@ -91,7 +91,7 @@ public class KeyHolderTests { }}; kh.getKeyList().addAll(asList(m, m)); - assertEquals("two rows should be in the list", 2, kh.getKeyList().size()); + assertThat(kh.getKeyList().size()).as("two rows should be in the list").isEqualTo(2); assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() -> kh.getKeys()) .withMessageStartingWith("The getKeys method should only be used when keys for a single row are returned."); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java index 25cb2089c6c..2bddf3d8f91 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java @@ -33,9 +33,8 @@ import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.InvalidResultSetAccessException; import org.springframework.lang.Nullable; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -63,13 +62,13 @@ public class SQLErrorCodeSQLExceptionTranslatorTests { SQLException badSqlEx = new SQLException("", "", 1); BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx); - assertEquals("SQL", bsgex.getSql()); - assertEquals(badSqlEx, bsgex.getSQLException()); + assertThat(bsgex.getSql()).isEqualTo("SQL"); + assertThat((Object) bsgex.getSQLException()).isEqualTo(badSqlEx); SQLException invResEx = new SQLException("", "", 4); InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx); - assertEquals("SQL", irsex.getSql()); - assertEquals(invResEx, irsex.getSQLException()); + assertThat(irsex.getSql()).isEqualTo("SQL"); + assertThat((Object) irsex.getSQLException()).isEqualTo(invResEx); checkTranslation(sext, 5, DataAccessResourceFailureException.class); checkTranslation(sext, 6, DataIntegrityViolationException.class); @@ -80,22 +79,21 @@ public class SQLErrorCodeSQLExceptionTranslatorTests { SQLException dupKeyEx = new SQLException("", "", 10); DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx); - assertTrue("Not instance of DataIntegrityViolationException", - DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass())); + assertThat(DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass())).as("Not instance of DataIntegrityViolationException").isTrue(); // Test fallback. We assume that no database will ever return this error code, // but 07xxx will be bad grammar picked up by the fallback SQLState translator SQLException sex = new SQLException("", "07xxx", 666666666); BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex); - assertEquals("SQL2", bsgex2.getSql()); - assertEquals(sex, bsgex2.getSQLException()); + assertThat(bsgex2.getSql()).isEqualTo("SQL2"); + assertThat((Object) bsgex2.getSQLException()).isEqualTo(sex); } private void checkTranslation(SQLExceptionTranslator sext, int errorCode, Class exClass) { SQLException sex = new SQLException("", "", errorCode); DataAccessException ex = sext.translate("", "", sex); - assertTrue(exClass.isInstance(ex)); - assertTrue(ex.getCause() == sex); + assertThat(exClass.isInstance(ex)).isTrue(); + assertThat(ex.getCause() == sex).isTrue(); } @Test @@ -106,8 +104,8 @@ public class SQLErrorCodeSQLExceptionTranslatorTests { BatchUpdateException batchUpdateEx = new BatchUpdateException(); batchUpdateEx.setNextException(badSqlEx); BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", batchUpdateEx); - assertEquals("SQL", bsgex.getSql()); - assertEquals(badSqlEx, bsgex.getSQLException()); + assertThat(bsgex.getSql()).isEqualTo("SQL"); + assertThat((Object) bsgex.getSQLException()).isEqualTo(badSqlEx); } @Test @@ -117,7 +115,7 @@ public class SQLErrorCodeSQLExceptionTranslatorTests { SQLException dataAccessEx = new SQLException("", "", 5); DataTruncation dataTruncation = new DataTruncation(1, true, true, 1, 1, dataAccessEx); DataAccessResourceFailureException daex = (DataAccessResourceFailureException) sext.translate("task", "SQL", dataTruncation); - assertEquals(dataTruncation, daex.getCause()); + assertThat(daex.getCause()).isEqualTo(dataTruncation); } @SuppressWarnings("serial") @@ -134,17 +132,17 @@ public class SQLErrorCodeSQLExceptionTranslatorTests { @Override @Nullable protected DataAccessException customTranslate(String task, @Nullable String sql, SQLException sqlex) { - assertEquals(TASK, task); - assertEquals(SQL, sql); + assertThat(task).isEqualTo(TASK); + assertThat(sql).isEqualTo(SQL); return (sqlex == badSqlEx) ? customDex : null; } }; sext.setSqlErrorCodes(ERROR_CODES); // Shouldn't custom translate this - assertEquals(customDex, sext.translate(TASK, SQL, badSqlEx)); + assertThat(sext.translate(TASK, SQL, badSqlEx)).isEqualTo(customDex); DataIntegrityViolationException diex = (DataIntegrityViolationException) sext.translate(TASK, SQL, intVioEx); - assertEquals(intVioEx, diex.getCause()); + assertThat(diex.getCause()).isEqualTo(intVioEx); } @Test @@ -165,13 +163,13 @@ public class SQLErrorCodeSQLExceptionTranslatorTests { // Should custom translate this SQLException badSqlEx = new SQLException("", "", 1); - assertEquals(CustomErrorCodeException.class, sext.translate(TASK, SQL, badSqlEx).getClass()); - assertEquals(badSqlEx, sext.translate(TASK, SQL, badSqlEx).getCause()); + assertThat(sext.translate(TASK, SQL, badSqlEx).getClass()).isEqualTo(CustomErrorCodeException.class); + assertThat(sext.translate(TASK, SQL, badSqlEx).getCause()).isEqualTo(badSqlEx); // Shouldn't custom translate this SQLException invResEx = new SQLException("", "", 3); DataIntegrityViolationException diex = (DataIntegrityViolationException) sext.translate(TASK, SQL, invResEx); - assertEquals(invResEx, diex.getCause()); + assertThat(diex.getCause()).isEqualTo(invResEx); // Shouldn't custom translate this - invalid class assertThatIllegalArgumentException().isThrownBy(() -> diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodesFactoryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodesFactoryTests.java index 216345bec73..13279760945 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodesFactoryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodesFactoryTests.java @@ -28,10 +28,6 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -51,8 +47,8 @@ public class SQLErrorCodesFactoryTests { @Test public void testDefaultInstanceWithNoSuchDatabase() { SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes("xx"); - assertTrue(sec.getBadSqlGrammarCodes().length == 0); - assertTrue(sec.getDataIntegrityViolationCodes().length == 0); + assertThat(sec.getBadSqlGrammarCodes().length == 0).isTrue(); + assertThat(sec.getDataIntegrityViolationCodes().length == 0).isTrue(); } /** @@ -65,80 +61,80 @@ public class SQLErrorCodesFactoryTests { } private void assertIsOracle(SQLErrorCodes sec) { - assertTrue(sec.getBadSqlGrammarCodes().length > 0); - assertTrue(sec.getDataIntegrityViolationCodes().length > 0); + assertThat(sec.getBadSqlGrammarCodes().length > 0).isTrue(); + assertThat(sec.getDataIntegrityViolationCodes().length > 0).isTrue(); // These had better be a Bad SQL Grammar code - assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942") >= 0); - assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "6550") >= 0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "6550") >= 0).isTrue(); // This had better NOT be - assertFalse(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "9xx42") >= 0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "9xx42") >= 0).isFalse(); } private void assertIsSQLServer(SQLErrorCodes sec) { assertThat(sec.getDatabaseProductName()).isEqualTo("Microsoft SQL Server"); - assertTrue(sec.getBadSqlGrammarCodes().length > 0); + assertThat(sec.getBadSqlGrammarCodes().length > 0).isTrue(); - assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "156") >= 0); - assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "170") >= 0); - assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "207") >= 0); - assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "208") >= 0); - assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "209") >= 0); - assertFalse(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "9xx42") >= 0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "156") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "170") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "207") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "208") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "209") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "9xx42") >= 0).isFalse(); - assertTrue(sec.getPermissionDeniedCodes().length > 0); - assertTrue(Arrays.binarySearch(sec.getPermissionDeniedCodes(), "229") >= 0); + assertThat(sec.getPermissionDeniedCodes().length > 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getPermissionDeniedCodes(), "229") >= 0).isTrue(); - assertTrue(sec.getDuplicateKeyCodes().length > 0); - assertTrue(Arrays.binarySearch(sec.getDuplicateKeyCodes(), "2601") >= 0); - assertTrue(Arrays.binarySearch(sec.getDuplicateKeyCodes(), "2627") >= 0); + assertThat(sec.getDuplicateKeyCodes().length > 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getDuplicateKeyCodes(), "2601") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getDuplicateKeyCodes(), "2627") >= 0).isTrue(); - assertTrue(sec.getDataIntegrityViolationCodes().length > 0); - assertTrue(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "544") >= 0); - assertTrue(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "8114") >= 0); - assertTrue(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "8115") >= 0); + assertThat(sec.getDataIntegrityViolationCodes().length > 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "544") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "8114") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "8115") >= 0).isTrue(); - assertTrue(sec.getDataAccessResourceFailureCodes().length > 0); - assertTrue(Arrays.binarySearch(sec.getDataAccessResourceFailureCodes(), "4060") >= 0); + assertThat(sec.getDataAccessResourceFailureCodes().length > 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getDataAccessResourceFailureCodes(), "4060") >= 0).isTrue(); - assertTrue(sec.getCannotAcquireLockCodes().length > 0); - assertTrue(Arrays.binarySearch(sec.getCannotAcquireLockCodes(), "1222") >= 0); + assertThat(sec.getCannotAcquireLockCodes().length > 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getCannotAcquireLockCodes(), "1222") >= 0).isTrue(); - assertTrue(sec.getDeadlockLoserCodes().length > 0); - assertTrue(Arrays.binarySearch(sec.getDeadlockLoserCodes(), "1205") >= 0); + assertThat(sec.getDeadlockLoserCodes().length > 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getDeadlockLoserCodes(), "1205") >= 0).isTrue(); } private void assertIsHsql(SQLErrorCodes sec) { - assertTrue(sec.getBadSqlGrammarCodes().length > 0); - assertTrue(sec.getDataIntegrityViolationCodes().length > 0); + assertThat(sec.getBadSqlGrammarCodes().length > 0).isTrue(); + assertThat(sec.getDataIntegrityViolationCodes().length > 0).isTrue(); // This had better be a Bad SQL Grammar code - assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-22") >= 0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-22") >= 0).isTrue(); // This had better NOT be - assertFalse(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-9") >= 0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-9") >= 0).isFalse(); } private void assertIsDB2(SQLErrorCodes sec) { - assertTrue(sec.getBadSqlGrammarCodes().length > 0); - assertTrue(sec.getDataIntegrityViolationCodes().length > 0); + assertThat(sec.getBadSqlGrammarCodes().length > 0).isTrue(); + assertThat(sec.getDataIntegrityViolationCodes().length > 0).isTrue(); - assertFalse(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942") >= 0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942") >= 0).isFalse(); // This had better NOT be - assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-204") >= 0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-204") >= 0).isTrue(); } private void assertIsHana(SQLErrorCodes sec) { - assertTrue(sec.getBadSqlGrammarCodes().length > 0); - assertTrue(sec.getDataIntegrityViolationCodes().length > 0); + assertThat(sec.getBadSqlGrammarCodes().length > 0).isTrue(); + assertThat(sec.getDataIntegrityViolationCodes().length > 0).isTrue(); - assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "368") >= 0); - assertTrue(Arrays.binarySearch(sec.getPermissionDeniedCodes(), "10") >= 0); - assertTrue(Arrays.binarySearch(sec.getDuplicateKeyCodes(), "301") >= 0); - assertTrue(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "461") >= 0); - assertTrue(Arrays.binarySearch(sec.getDataAccessResourceFailureCodes(), "-813") >=0); - assertTrue(Arrays.binarySearch(sec.getInvalidResultSetAccessCodes(), "582") >=0); - assertTrue(Arrays.binarySearch(sec.getCannotAcquireLockCodes(), "131") >= 0); - assertTrue(Arrays.binarySearch(sec.getCannotSerializeTransactionCodes(), "138") >= 0); - assertTrue(Arrays.binarySearch(sec.getDeadlockLoserCodes(), "133") >= 0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "368") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getPermissionDeniedCodes(), "10") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getDuplicateKeyCodes(), "301") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "461") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getDataAccessResourceFailureCodes(), "-813") >=0).isTrue(); + assertThat(Arrays.binarySearch(sec.getInvalidResultSetAccessCodes(), "582") >=0).isTrue(); + assertThat(Arrays.binarySearch(sec.getCannotAcquireLockCodes(), "131") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getCannotSerializeTransactionCodes(), "138") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getDeadlockLoserCodes(), "133") >= 0).isTrue(); } @@ -150,13 +146,13 @@ public class SQLErrorCodesFactoryTests { protected Resource loadResource(String path) { ++lookups; if (lookups == 1) { - assertEquals(SQLErrorCodesFactory.SQL_ERROR_CODE_DEFAULT_PATH, path); + assertThat(path).isEqualTo(SQLErrorCodesFactory.SQL_ERROR_CODE_DEFAULT_PATH); return null; } else { // Should have only one more lookup - assertEquals(2, lookups); - assertEquals(SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH, path); + assertThat(lookups).isEqualTo(2); + assertThat(path).isEqualTo(SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH); return null; } } @@ -164,8 +160,8 @@ public class SQLErrorCodesFactoryTests { // Should have failed to load without error TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory(); - assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0); - assertTrue(sf.getErrorCodes("Oracle").getDataIntegrityViolationCodes().length == 0); + assertThat(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0).isTrue(); + assertThat(sf.getErrorCodes("Oracle").getDataIntegrityViolationCodes().length == 0).isTrue(); } /** @@ -185,10 +181,10 @@ public class SQLErrorCodesFactoryTests { // Should have loaded without error TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory(); - assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0); - assertEquals(2, sf.getErrorCodes("Oracle").getBadSqlGrammarCodes().length); - assertEquals("1", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[0]); - assertEquals("2", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[1]); + assertThat(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0).isTrue(); + assertThat(sf.getErrorCodes("Oracle").getBadSqlGrammarCodes().length).isEqualTo(2); + assertThat(sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[0]).isEqualTo("1"); + assertThat(sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[1]).isEqualTo("2"); } @Test @@ -206,8 +202,8 @@ public class SQLErrorCodesFactoryTests { // Should have failed to load without error TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory(); - assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0); - assertEquals(0, sf.getErrorCodes("Oracle").getBadSqlGrammarCodes().length); + assertThat(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0).isTrue(); + assertThat(sf.getErrorCodes("Oracle").getBadSqlGrammarCodes().length).isEqualTo(0); } /** @@ -227,11 +223,11 @@ public class SQLErrorCodesFactoryTests { // Should have loaded without error TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory(); - assertEquals(1, sf.getErrorCodes("Oracle").getCustomTranslations().length); + assertThat(sf.getErrorCodes("Oracle").getCustomTranslations().length).isEqualTo(1); CustomSQLErrorCodesTranslation translation = sf.getErrorCodes("Oracle").getCustomTranslations()[0]; - assertEquals(CustomErrorCodeException.class, translation.getExceptionClass()); - assertEquals(1, translation.getErrorCodes().length); + assertThat(translation.getExceptionClass()).isEqualTo(CustomErrorCodeException.class); + assertThat(translation.getErrorCodes().length).isEqualTo(1); } @Test @@ -259,8 +255,8 @@ public class SQLErrorCodesFactoryTests { private void assertIsEmpty(SQLErrorCodes sec) { // Codes should be empty - assertEquals(0, sec.getBadSqlGrammarCodes().length); - assertEquals(0, sec.getDataIntegrityViolationCodes().length); + assertThat(sec.getBadSqlGrammarCodes().length).isEqualTo(0); + assertThat(sec.getDataIntegrityViolationCodes().length).isEqualTo(0); } private SQLErrorCodes getErrorCodesFromDataSource(String productName, SQLErrorCodesFactory factory) throws Exception { @@ -285,7 +281,7 @@ public class SQLErrorCodesFactoryTests { SQLErrorCodes sec2 = secf.getErrorCodes(dataSource); - assertSame("Cached per DataSource", sec2, sec); + assertThat(sec).as("Cached per DataSource").isSameAs(sec2); verify(connection).close(); return sec; diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java index 84319166df9..14e9aec8549 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java @@ -25,7 +25,6 @@ import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.BadSqlGrammarException; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Unit tests for custom SQLException translation. @@ -50,7 +49,7 @@ public class SQLExceptionCustomTranslatorTests { public void badSqlGrammarException() { SQLException badSqlGrammarExceptionEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 1); DataAccessException dae = sext.translate("task", "SQL", badSqlGrammarExceptionEx); - assertEquals(badSqlGrammarExceptionEx, dae.getCause()); + assertThat(dae.getCause()).isEqualTo(badSqlGrammarExceptionEx); assertThat(dae).isInstanceOf(BadSqlGrammarException.class); } @@ -58,7 +57,7 @@ public class SQLExceptionCustomTranslatorTests { public void dataAccessResourceException() { SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 2); DataAccessException dae = sext.translate("task", "SQL", dataAccessResourceEx); - assertEquals(dataAccessResourceEx, dae.getCause()); + assertThat(dae.getCause()).isEqualTo(dataAccessResourceEx); assertThat(dae).isInstanceOf(TransientDataAccessResourceException.class); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionSubclassTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionSubclassTranslatorTests.java index 89a71b0ca27..8ae02516b79 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionSubclassTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionSubclassTranslatorTests.java @@ -30,7 +30,7 @@ import org.springframework.dao.RecoverableDataAccessException; import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.BadSqlGrammarException; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Thomas Risberg @@ -50,62 +50,62 @@ public class SQLExceptionSubclassTranslatorTests { SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 0); DataIntegrityViolationException divex = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx); - assertEquals(dataIntegrityViolationEx, divex.getCause()); + assertThat(divex.getCause()).isEqualTo(dataIntegrityViolationEx); SQLException featureNotSupEx = SQLExceptionSubclassFactory.newSQLFeatureNotSupportedException("", "", 0); InvalidDataAccessApiUsageException idaex = (InvalidDataAccessApiUsageException) sext.translate("task", "SQL", featureNotSupEx); - assertEquals(featureNotSupEx, idaex.getCause()); + assertThat(idaex.getCause()).isEqualTo(featureNotSupEx); SQLException dataIntegrityViolationEx2 = SQLExceptionSubclassFactory.newSQLIntegrityConstraintViolationException("", "", 0); DataIntegrityViolationException divex2 = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx2); - assertEquals(dataIntegrityViolationEx2, divex2.getCause()); + assertThat(divex2.getCause()).isEqualTo(dataIntegrityViolationEx2); SQLException permissionDeniedEx = SQLExceptionSubclassFactory.newSQLInvalidAuthorizationSpecException("", "", 0); PermissionDeniedDataAccessException pdaex = (PermissionDeniedDataAccessException) sext.translate("task", "SQL", permissionDeniedEx); - assertEquals(permissionDeniedEx, pdaex.getCause()); + assertThat(pdaex.getCause()).isEqualTo(permissionDeniedEx); SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLNonTransientConnectionException("", "", 0); DataAccessResourceFailureException darex = (DataAccessResourceFailureException) sext.translate("task", "SQL", dataAccessResourceEx); - assertEquals(dataAccessResourceEx, darex.getCause()); + assertThat(darex.getCause()).isEqualTo(dataAccessResourceEx); SQLException badSqlEx2 = SQLExceptionSubclassFactory.newSQLSyntaxErrorException("", "", 0); BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", badSqlEx2); - assertEquals("SQL2", bsgex2.getSql()); - assertEquals(badSqlEx2, bsgex2.getSQLException()); + assertThat(bsgex2.getSql()).isEqualTo("SQL2"); + assertThat((Object) bsgex2.getSQLException()).isEqualTo(badSqlEx2); SQLException tranRollbackEx = SQLExceptionSubclassFactory.newSQLTransactionRollbackException("", "", 0); ConcurrencyFailureException cfex = (ConcurrencyFailureException) sext.translate("task", "SQL", tranRollbackEx); - assertEquals(tranRollbackEx, cfex.getCause()); + assertThat(cfex.getCause()).isEqualTo(tranRollbackEx); SQLException transientConnEx = SQLExceptionSubclassFactory.newSQLTransientConnectionException("", "", 0); TransientDataAccessResourceException tdarex = (TransientDataAccessResourceException) sext.translate("task", "SQL", transientConnEx); - assertEquals(transientConnEx, tdarex.getCause()); + assertThat(tdarex.getCause()).isEqualTo(transientConnEx); SQLException transientConnEx2 = SQLExceptionSubclassFactory.newSQLTimeoutException("", "", 0); QueryTimeoutException tdarex2 = (QueryTimeoutException) sext.translate("task", "SQL", transientConnEx2); - assertEquals(transientConnEx2, tdarex2.getCause()); + assertThat(tdarex2.getCause()).isEqualTo(transientConnEx2); SQLException recoverableEx = SQLExceptionSubclassFactory.newSQLRecoverableException("", "", 0); RecoverableDataAccessException rdaex2 = (RecoverableDataAccessException) sext.translate("task", "SQL", recoverableEx); - assertEquals(recoverableEx, rdaex2.getCause()); + assertThat(rdaex2.getCause()).isEqualTo(recoverableEx); // Test classic error code translation. We should move there next if the exception we pass in is not one // of the new sub-classes. SQLException sexEct = new SQLException("", "", 1); BadSqlGrammarException bsgEct = (BadSqlGrammarException) sext.translate("task", "SQL-ECT", sexEct); - assertEquals("SQL-ECT", bsgEct.getSql()); - assertEquals(sexEct, bsgEct.getSQLException()); + assertThat(bsgEct.getSql()).isEqualTo("SQL-ECT"); + assertThat((Object) bsgEct.getSQLException()).isEqualTo(sexEct); // Test fallback. We assume that no database will ever return this error code, // but 07xxx will be bad grammar picked up by the fallback SQLState translator SQLException sexFbt = new SQLException("", "07xxx", 666666666); BadSqlGrammarException bsgFbt = (BadSqlGrammarException) sext.translate("task", "SQL-FBT", sexFbt); - assertEquals("SQL-FBT", bsgFbt.getSql()); - assertEquals(sexFbt, bsgFbt.getSQLException()); + assertThat(bsgFbt.getSql()).isEqualTo("SQL-FBT"); + assertThat((Object) bsgFbt.getSQLException()).isEqualTo(sexFbt); // and 08xxx will be data resource failure (non-transient) picked up by the fallback SQLState translator SQLException sexFbt2 = new SQLException("", "08xxx", 666666666); DataAccessResourceFailureException darfFbt = (DataAccessResourceFailureException) sext.translate("task", "SQL-FBT2", sexFbt2); - assertEquals(sexFbt2, darfFbt.getCause()); + assertThat(darfFbt.getCause()).isEqualTo(sexFbt2); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java index a0a37afac7c..05078a91fce 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.UncategorizedSQLException; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -46,8 +46,8 @@ public class SQLStateExceptionTranslatorTests { } catch (BadSqlGrammarException ex) { // OK - assertTrue("SQL is correct", sql.equals(ex.getSql())); - assertTrue("Exception matches", sex.equals(ex.getSQLException())); + assertThat(sql.equals(ex.getSql())).as("SQL is correct").isTrue(); + assertThat(sex.equals(ex.getSQLException())).as("Exception matches").isTrue(); } } @@ -59,8 +59,8 @@ public class SQLStateExceptionTranslatorTests { } catch (UncategorizedSQLException ex) { // OK - assertTrue("SQL is correct", sql.equals(ex.getSql())); - assertTrue("Exception matches", sex.equals(ex.getSQLException())); + assertThat(sql.equals(ex.getSql())).as("SQL is correct").isTrue(); + assertThat(sex.equals(ex.getSQLException())).as("Exception matches").isTrue(); } } @@ -89,8 +89,8 @@ public class SQLStateExceptionTranslatorTests { } catch (UncategorizedSQLException ex) { // OK - assertTrue("SQL is correct", sql.equals(ex.getSql())); - assertTrue("Exception matches", sex.equals(ex.getSQLException())); + assertThat(sql.equals(ex.getSql())).as("SQL is correct").isTrue(); + assertThat(sex.equals(ex.getSQLException())).as("Exception matches").isTrue(); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslatorTests.java index bd148cc6f83..32fcac97e2f 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslatorTests.java @@ -28,10 +28,8 @@ import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.UncategorizedSQLException; +import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; /** * @author Rick Evans @@ -88,10 +86,10 @@ public class SQLStateSQLExceptionTranslatorTests { SQLException ex = new SQLException(REASON, sqlState); SQLExceptionTranslator translator = new SQLStateSQLExceptionTranslator(); DataAccessException dax = translator.translate(TASK, SQL, ex); - assertNotNull("Translation must *never* result in a null DataAccessException being returned.", dax); - assertEquals("Wrong DataAccessException type returned as the result of the translation", dataAccessExceptionType, dax.getClass()); - assertNotNull("The original SQLException must be preserved in the translated DataAccessException", dax.getCause()); - assertSame("The exact same original SQLException must be preserved in the translated DataAccessException", ex, dax.getCause()); + assertThat(dax).as("Translation must *never* result in a null DataAccessException being returned.").isNotNull(); + assertThat(dax.getClass()).as("Wrong DataAccessException type returned as the result of the translation").isEqualTo(dataAccessExceptionType); + assertThat(dax.getCause()).as("The original SQLException must be preserved in the translated DataAccessException").isNotNull(); + assertThat(dax.getCause()).as("The exact same original SQLException must be preserved in the translated DataAccessException").isSameAs(ex); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/annotation/AbstractJmsAnnotationDrivenTests.java b/spring-jms/src/test/java/org/springframework/jms/annotation/AbstractJmsAnnotationDrivenTests.java index 69f7f938a85..0383fef3887 100644 --- a/spring-jms/src/test/java/org/springframework/jms/annotation/AbstractJmsAnnotationDrivenTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/annotation/AbstractJmsAnnotationDrivenTests.java @@ -39,8 +39,7 @@ import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.validation.annotation.Validated; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -86,8 +85,8 @@ public abstract class AbstractJmsAnnotationDrivenTests { context.getBean("jmsListenerContainerFactory", JmsListenerContainerTestFactory.class); JmsListenerContainerTestFactory simpleFactory = context.getBean("simpleFactory", JmsListenerContainerTestFactory.class); - assertEquals(1, defaultFactory.getListenerContainers().size()); - assertEquals(1, simpleFactory.getListenerContainers().size()); + assertThat(defaultFactory.getListenerContainers().size()).isEqualTo(1); + assertThat(simpleFactory.getListenerContainers().size()).isEqualTo(1); } /** @@ -98,19 +97,19 @@ public abstract class AbstractJmsAnnotationDrivenTests { public void testFullConfiguration(ApplicationContext context) { JmsListenerContainerTestFactory simpleFactory = context.getBean("simpleFactory", JmsListenerContainerTestFactory.class); - assertEquals(1, simpleFactory.getListenerContainers().size()); + assertThat(simpleFactory.getListenerContainers().size()).isEqualTo(1); MethodJmsListenerEndpoint endpoint = (MethodJmsListenerEndpoint) simpleFactory.getListenerContainers().get(0).getEndpoint(); - assertEquals("listener1", endpoint.getId()); - assertEquals("queueIn", endpoint.getDestination()); - assertEquals("mySelector", endpoint.getSelector()); - assertEquals("mySubscription", endpoint.getSubscription()); - assertEquals("1-10", endpoint.getConcurrency()); + assertThat(endpoint.getId()).isEqualTo("listener1"); + assertThat(endpoint.getDestination()).isEqualTo("queueIn"); + assertThat(endpoint.getSelector()).isEqualTo("mySelector"); + assertThat(endpoint.getSubscription()).isEqualTo("mySubscription"); + assertThat(endpoint.getConcurrency()).isEqualTo("1-10"); Method m = ReflectionUtils.findMethod(endpoint.getClass(), "getDefaultResponseDestination"); ReflectionUtils.makeAccessible(m); Object destination = ReflectionUtils.invokeMethod(m, endpoint); - assertEquals("queueOut", destination); + assertThat(destination).isEqualTo("queueOut"); } /** @@ -123,23 +122,18 @@ public abstract class AbstractJmsAnnotationDrivenTests { context.getBean("jmsListenerContainerFactory", JmsListenerContainerTestFactory.class); JmsListenerContainerTestFactory customFactory = context.getBean("customFactory", JmsListenerContainerTestFactory.class); - assertEquals(1, defaultFactory.getListenerContainers().size()); - assertEquals(1, customFactory.getListenerContainers().size()); + assertThat(defaultFactory.getListenerContainers().size()).isEqualTo(1); + assertThat(customFactory.getListenerContainers().size()).isEqualTo(1); JmsListenerEndpoint endpoint = defaultFactory.getListenerContainers().get(0).getEndpoint(); - assertEquals("Wrong endpoint type", SimpleJmsListenerEndpoint.class, endpoint.getClass()); - assertEquals("Wrong listener set in custom endpoint", context.getBean("simpleMessageListener"), - ((SimpleJmsListenerEndpoint) endpoint).getMessageListener()); + assertThat(endpoint.getClass()).as("Wrong endpoint type").isEqualTo(SimpleJmsListenerEndpoint.class); + assertThat(((SimpleJmsListenerEndpoint) endpoint).getMessageListener()).as("Wrong listener set in custom endpoint").isEqualTo(context.getBean("simpleMessageListener")); JmsListenerEndpointRegistry customRegistry = context.getBean("customRegistry", JmsListenerEndpointRegistry.class); - assertEquals("Wrong number of containers in the registry", 2, - customRegistry.getListenerContainerIds().size()); - assertEquals("Wrong number of containers in the registry", 2, - customRegistry.getListenerContainers().size()); - assertNotNull("Container with custom id on the annotation should be found", - customRegistry.getListenerContainer("listenerId")); - assertNotNull("Container created with custom id should be found", - customRegistry.getListenerContainer("myCustomEndpointId")); + assertThat(customRegistry.getListenerContainerIds().size()).as("Wrong number of containers in the registry").isEqualTo(2); + assertThat(customRegistry.getListenerContainers().size()).as("Wrong number of containers in the registry").isEqualTo(2); + assertThat(customRegistry.getListenerContainer("listenerId")).as("Container with custom id on the annotation should be found").isNotNull(); + assertThat(customRegistry.getListenerContainer("myCustomEndpointId")).as("Container created with custom id should be found").isNotNull(); } /** @@ -150,7 +144,7 @@ public abstract class AbstractJmsAnnotationDrivenTests { public void testExplicitContainerFactoryConfiguration(ApplicationContext context) { JmsListenerContainerTestFactory defaultFactory = context.getBean("simpleFactory", JmsListenerContainerTestFactory.class); - assertEquals(1, defaultFactory.getListenerContainers().size()); + assertThat(defaultFactory.getListenerContainers().size()).isEqualTo(1); } /** @@ -160,7 +154,7 @@ public abstract class AbstractJmsAnnotationDrivenTests { public void testDefaultContainerFactoryConfiguration(ApplicationContext context) { JmsListenerContainerTestFactory defaultFactory = context.getBean("jmsListenerContainerFactory", JmsListenerContainerTestFactory.class); - assertEquals(1, defaultFactory.getListenerContainers().size()); + assertThat(defaultFactory.getListenerContainers().size()).isEqualTo(1); } /** @@ -172,7 +166,7 @@ public abstract class AbstractJmsAnnotationDrivenTests { public void testJmsHandlerMethodFactoryConfiguration(ApplicationContext context) throws JMSException { JmsListenerContainerTestFactory simpleFactory = context.getBean("defaultFactory", JmsListenerContainerTestFactory.class); - assertEquals(1, simpleFactory.getListenerContainers().size()); + assertThat(simpleFactory.getListenerContainers().size()).isEqualTo(1); MethodJmsListenerEndpoint endpoint = (MethodJmsListenerEndpoint) simpleFactory.getListenerContainers().get(0).getEndpoint(); @@ -189,19 +183,19 @@ public abstract class AbstractJmsAnnotationDrivenTests { public void testJmsListenerRepeatable(ApplicationContext context) { JmsListenerContainerTestFactory simpleFactory = context.getBean("jmsListenerContainerFactory", JmsListenerContainerTestFactory.class); - assertEquals(2, simpleFactory.getListenerContainers().size()); + assertThat(simpleFactory.getListenerContainers().size()).isEqualTo(2); MethodJmsListenerEndpoint first = (MethodJmsListenerEndpoint) simpleFactory.getListenerContainer("first").getEndpoint(); - assertEquals("first", first.getId()); - assertEquals("myQueue", first.getDestination()); - assertEquals(null, first.getConcurrency()); + assertThat(first.getId()).isEqualTo("first"); + assertThat(first.getDestination()).isEqualTo("myQueue"); + assertThat(first.getConcurrency()).isEqualTo(null); MethodJmsListenerEndpoint second = (MethodJmsListenerEndpoint) simpleFactory.getListenerContainer("second").getEndpoint(); - assertEquals("second", second.getId()); - assertEquals("anotherQueue", second.getDestination()); - assertEquals("2-10", second.getConcurrency()); + assertThat(second.getId()).isEqualTo("second"); + assertThat(second.getDestination()).isEqualTo("anotherQueue"); + assertThat(second.getConcurrency()).isEqualTo("2-10"); } diff --git a/spring-jms/src/test/java/org/springframework/jms/annotation/EnableJmsTests.java b/spring-jms/src/test/java/org/springframework/jms/annotation/EnableJmsTests.java index 833339f3e3e..0547fc5b091 100644 --- a/spring-jms/src/test/java/org/springframework/jms/annotation/EnableJmsTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/annotation/EnableJmsTests.java @@ -45,11 +45,8 @@ import org.springframework.messaging.handler.annotation.support.MessageHandlerMe import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException; import org.springframework.stereotype.Component; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * @author Stephane Nicoll @@ -111,8 +108,8 @@ public class EnableJmsTests extends AbstractJmsAnnotationDrivenTests { JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); MessageListenerTestContainer container = factory.getListenerContainers().get(0); - assertTrue(container.isAutoStartup()); - assertTrue(container.isStarted()); + assertThat(container.isAutoStartup()).isTrue(); + assertThat(container.isStarted()).isTrue(); } @Test @@ -122,11 +119,11 @@ public class EnableJmsTests extends AbstractJmsAnnotationDrivenTests { JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); MessageListenerTestContainer container = factory.getListenerContainers().get(0); - assertFalse(container.isAutoStartup()); - assertFalse(container.isStarted()); + assertThat(container.isAutoStartup()).isFalse(); + assertThat(container.isStarted()).isFalse(); JmsListenerEndpointRegistry registry = context.getBean(JmsListenerEndpointRegistry.class); registry.start(); - assertTrue(container.isStarted()); + assertThat(container.isStarted()).isTrue(); } @Override @@ -162,19 +159,19 @@ public class EnableJmsTests extends AbstractJmsAnnotationDrivenTests { EnableJmsDefaultContainerFactoryConfig.class, ComposedJmsListenersBean.class)) { JmsListenerContainerTestFactory simpleFactory = context.getBean("jmsListenerContainerFactory", JmsListenerContainerTestFactory.class); - assertEquals(2, simpleFactory.getListenerContainers().size()); + assertThat(simpleFactory.getListenerContainers().size()).isEqualTo(2); MethodJmsListenerEndpoint first = (MethodJmsListenerEndpoint) simpleFactory.getListenerContainer( "first").getEndpoint(); - assertEquals("first", first.getId()); - assertEquals("orderQueue", first.getDestination()); - assertNull(first.getConcurrency()); + assertThat(first.getId()).isEqualTo("first"); + assertThat(first.getDestination()).isEqualTo("orderQueue"); + assertThat(first.getConcurrency()).isNull(); MethodJmsListenerEndpoint second = (MethodJmsListenerEndpoint) simpleFactory.getListenerContainer( "second").getEndpoint(); - assertEquals("second", second.getId()); - assertEquals("billingQueue", second.getDestination()); - assertEquals("2-10", second.getConcurrency()); + assertThat(second.getId()).isEqualTo("second"); + assertThat(second.getDestination()).isEqualTo("billingQueue"); + assertThat(second.getConcurrency()).isEqualTo("2-10"); } } @@ -193,14 +190,14 @@ public class EnableJmsTests extends AbstractJmsAnnotationDrivenTests { EnableJmsDefaultContainerFactoryConfig.class, LazyBean.class); JmsListenerContainerTestFactory defaultFactory = context.getBean("jmsListenerContainerFactory", JmsListenerContainerTestFactory.class); - assertEquals(0, defaultFactory.getListenerContainers().size()); + assertThat(defaultFactory.getListenerContainers().size()).isEqualTo(0); context.getBean(LazyBean.class); // trigger lazy resolution - assertEquals(1, defaultFactory.getListenerContainers().size()); + assertThat(defaultFactory.getListenerContainers().size()).isEqualTo(1); MessageListenerTestContainer container = defaultFactory.getListenerContainers().get(0); - assertTrue("Should have been started " + container, container.isStarted()); + assertThat(container.isStarted()).as("Should have been started " + container).isTrue(); context.close(); // close and stop the listeners - assertTrue("Should have been stopped " + container, container.isStopped()); + assertThat(container.isStopped()).as("Should have been stopped " + container).isTrue(); } diff --git a/spring-jms/src/test/java/org/springframework/jms/annotation/JmsListenerAnnotationBeanPostProcessorTests.java b/spring-jms/src/test/java/org/springframework/jms/annotation/JmsListenerAnnotationBeanPostProcessorTests.java index d282665f073..a1802e00bd1 100644 --- a/spring-jms/src/test/java/org/springframework/jms/annotation/JmsListenerAnnotationBeanPostProcessorTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/annotation/JmsListenerAnnotationBeanPostProcessorTests.java @@ -45,10 +45,8 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ReflectionUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; import static org.mockito.Mockito.mock; /** @@ -63,25 +61,23 @@ public class JmsListenerAnnotationBeanPostProcessorTests { Config.class, SimpleMessageListenerTestBean.class); JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); - assertEquals("One container should have been registered", 1, factory.getListenerContainers().size()); + assertThat(factory.getListenerContainers().size()).as("One container should have been registered").isEqualTo(1); MessageListenerTestContainer container = factory.getListenerContainers().get(0); JmsListenerEndpoint endpoint = container.getEndpoint(); - assertEquals("Wrong endpoint type", MethodJmsListenerEndpoint.class, endpoint.getClass()); + assertThat(endpoint.getClass()).as("Wrong endpoint type").isEqualTo(MethodJmsListenerEndpoint.class); MethodJmsListenerEndpoint methodEndpoint = (MethodJmsListenerEndpoint) endpoint; - assertEquals(SimpleMessageListenerTestBean.class, methodEndpoint.getBean().getClass()); - assertEquals(SimpleMessageListenerTestBean.class.getMethod("handleIt", String.class), - methodEndpoint.getMethod()); - assertEquals(SimpleMessageListenerTestBean.class.getMethod("handleIt", String.class), - methodEndpoint.getMostSpecificMethod()); + assertThat(methodEndpoint.getBean().getClass()).isEqualTo(SimpleMessageListenerTestBean.class); + assertThat(methodEndpoint.getMethod()).isEqualTo(SimpleMessageListenerTestBean.class.getMethod("handleIt", String.class)); + assertThat(methodEndpoint.getMostSpecificMethod()).isEqualTo(SimpleMessageListenerTestBean.class.getMethod("handleIt", String.class)); SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(); methodEndpoint.setupListenerContainer(listenerContainer); - assertNotNull(listenerContainer.getMessageListener()); + assertThat(listenerContainer.getMessageListener()).isNotNull(); - assertTrue("Should have been started " + container, container.isStarted()); + assertThat(container.isStarted()).as("Should have been started " + container).isTrue(); context.close(); // Close and stop the listeners - assertTrue("Should have been stopped " + container, container.isStopped()); + assertThat(container.isStopped()).as("Should have been stopped " + container).isTrue(); } @Test @@ -91,17 +87,15 @@ public class JmsListenerAnnotationBeanPostProcessorTests { try { JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); - assertEquals("one container should have been registered", 1, factory.getListenerContainers().size()); + assertThat(factory.getListenerContainers().size()).as("one container should have been registered").isEqualTo(1); JmsListenerEndpoint endpoint = factory.getListenerContainers().get(0).getEndpoint(); - assertEquals("Wrong endpoint type", MethodJmsListenerEndpoint.class, endpoint.getClass()); + assertThat(endpoint.getClass()).as("Wrong endpoint type").isEqualTo(MethodJmsListenerEndpoint.class); MethodJmsListenerEndpoint methodEndpoint = (MethodJmsListenerEndpoint) endpoint; - assertEquals(MetaAnnotationTestBean.class, methodEndpoint.getBean().getClass()); - assertEquals(MetaAnnotationTestBean.class.getMethod("handleIt", String.class), - methodEndpoint.getMethod()); - assertEquals(MetaAnnotationTestBean.class.getMethod("handleIt", String.class), - methodEndpoint.getMostSpecificMethod()); - assertEquals("metaTestQueue", ((AbstractJmsListenerEndpoint) endpoint).getDestination()); + assertThat(methodEndpoint.getBean().getClass()).isEqualTo(MetaAnnotationTestBean.class); + assertThat(methodEndpoint.getMethod()).isEqualTo(MetaAnnotationTestBean.class.getMethod("handleIt", String.class)); + assertThat(methodEndpoint.getMostSpecificMethod()).isEqualTo(MetaAnnotationTestBean.class.getMethod("handleIt", String.class)); + assertThat(((AbstractJmsListenerEndpoint) endpoint).getDestination()).isEqualTo("metaTestQueue"); } finally { context.close(); @@ -114,22 +108,21 @@ public class JmsListenerAnnotationBeanPostProcessorTests { Config.class, ProxyConfig.class, InterfaceProxyTestBean.class); try { JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); - assertEquals("one container should have been registered", 1, factory.getListenerContainers().size()); + assertThat(factory.getListenerContainers().size()).as("one container should have been registered").isEqualTo(1); JmsListenerEndpoint endpoint = factory.getListenerContainers().get(0).getEndpoint(); - assertEquals("Wrong endpoint type", MethodJmsListenerEndpoint.class, endpoint.getClass()); + assertThat(endpoint.getClass()).as("Wrong endpoint type").isEqualTo(MethodJmsListenerEndpoint.class); MethodJmsListenerEndpoint methodEndpoint = (MethodJmsListenerEndpoint) endpoint; - assertTrue(AopUtils.isJdkDynamicProxy(methodEndpoint.getBean())); - assertTrue(methodEndpoint.getBean() instanceof SimpleService); - assertEquals(SimpleService.class.getMethod("handleIt", String.class, String.class), - methodEndpoint.getMethod()); - assertEquals(InterfaceProxyTestBean.class.getMethod("handleIt", String.class, String.class), - methodEndpoint.getMostSpecificMethod()); + assertThat(AopUtils.isJdkDynamicProxy(methodEndpoint.getBean())).isTrue(); + boolean condition = methodEndpoint.getBean() instanceof SimpleService; + assertThat(condition).isTrue(); + assertThat(methodEndpoint.getMethod()).isEqualTo(SimpleService.class.getMethod("handleIt", String.class, String.class)); + assertThat(methodEndpoint.getMostSpecificMethod()).isEqualTo(InterfaceProxyTestBean.class.getMethod("handleIt", String.class, String.class)); Method method = ReflectionUtils.findMethod(endpoint.getClass(), "getDefaultResponseDestination"); ReflectionUtils.makeAccessible(method); Object destination = ReflectionUtils.invokeMethod(method, endpoint); - assertEquals("SendTo annotation not found on proxy", "foobar", destination); + assertThat(destination).as("SendTo annotation not found on proxy").isEqualTo("foobar"); } finally { context.close(); @@ -142,22 +135,21 @@ public class JmsListenerAnnotationBeanPostProcessorTests { Config.class, ProxyConfig.class, ClassProxyTestBean.class); try { JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); - assertEquals("one container should have been registered", 1, factory.getListenerContainers().size()); + assertThat(factory.getListenerContainers().size()).as("one container should have been registered").isEqualTo(1); JmsListenerEndpoint endpoint = factory.getListenerContainers().get(0).getEndpoint(); - assertEquals("Wrong endpoint type", MethodJmsListenerEndpoint.class, endpoint.getClass()); + assertThat(endpoint.getClass()).as("Wrong endpoint type").isEqualTo(MethodJmsListenerEndpoint.class); MethodJmsListenerEndpoint methodEndpoint = (MethodJmsListenerEndpoint) endpoint; - assertTrue(AopUtils.isCglibProxy(methodEndpoint.getBean())); - assertTrue(methodEndpoint.getBean() instanceof ClassProxyTestBean); - assertEquals(ClassProxyTestBean.class.getMethod("handleIt", String.class, String.class), - methodEndpoint.getMethod()); - assertEquals(ClassProxyTestBean.class.getMethod("handleIt", String.class, String.class), - methodEndpoint.getMostSpecificMethod()); + assertThat(AopUtils.isCglibProxy(methodEndpoint.getBean())).isTrue(); + boolean condition = methodEndpoint.getBean() instanceof ClassProxyTestBean; + assertThat(condition).isTrue(); + assertThat(methodEndpoint.getMethod()).isEqualTo(ClassProxyTestBean.class.getMethod("handleIt", String.class, String.class)); + assertThat(methodEndpoint.getMostSpecificMethod()).isEqualTo(ClassProxyTestBean.class.getMethod("handleIt", String.class, String.class)); Method method = ReflectionUtils.findMethod(endpoint.getClass(), "getDefaultResponseDestination"); ReflectionUtils.makeAccessible(method); Object destination = ReflectionUtils.invokeMethod(method, endpoint); - assertEquals("SendTo annotation not found on proxy", "foobar", destination); + assertThat(destination).as("SendTo annotation not found on proxy").isEqualTo("foobar"); } finally { context.close(); diff --git a/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerContainerFactoryIntegrationTests.java b/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerContainerFactoryIntegrationTests.java index 6cc258afbbe..b769a3f86c7 100644 --- a/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerContainerFactoryIntegrationTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerContainerFactoryIntegrationTests.java @@ -41,8 +41,7 @@ import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -136,7 +135,7 @@ public class JmsListenerContainerFactoryIntegrationTests { } private void assertListenerMethodInvocation(String methodName) { - assertTrue("Method " + methodName + " should have been invoked", sample.invocations.get(methodName)); + assertThat((boolean) sample.invocations.get(methodName)).as("Method " + methodName + " should have been invoked").isTrue(); } private MethodJmsListenerEndpoint createMethodJmsEndpoint(DefaultMessageHandlerMethodFactory factory, Method method) { @@ -169,8 +168,8 @@ public class JmsListenerContainerFactoryIntegrationTests { public void handleIt(@Payload String msg, @Header("my-header") String myHeader) { invocations.put("handleIt", true); - assertEquals("Unexpected payload message", "FOO-BAR", msg); - assertEquals("Unexpected header value", "my-value", myHeader); + assertThat(msg).as("Unexpected payload message").isEqualTo("FOO-BAR"); + assertThat(myHeader).as("Unexpected header value").isEqualTo("my-value"); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerContainerFactoryTests.java b/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerContainerFactoryTests.java index ca5d0e9695b..84a3502de5b 100644 --- a/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerContainerFactoryTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerContainerFactoryTests.java @@ -40,10 +40,8 @@ import org.springframework.jms.support.destination.DynamicDestinationResolver; import org.springframework.util.backoff.BackOff; import org.springframework.util.backoff.FixedBackOff; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; /** @@ -73,8 +71,8 @@ public class JmsListenerContainerFactoryTests { SimpleMessageListenerContainer container = factory.createListenerContainer(endpoint); assertDefaultJmsConfig(container); - assertEquals(messageListener, container.getMessageListener()); - assertEquals("myQueue", container.getDestinationName()); + assertThat(container.getMessageListener()).isEqualTo(messageListener); + assertThat(container.getDestinationName()).isEqualTo("myQueue"); } @Test @@ -92,13 +90,13 @@ public class JmsListenerContainerFactoryTests { DefaultMessageListenerContainer container = factory.createListenerContainer(endpoint); assertDefaultJmsConfig(container); - assertEquals(DefaultMessageListenerContainer.CACHE_CONSUMER, container.getCacheLevel()); - assertEquals(3, container.getConcurrentConsumers()); - assertEquals(10, container.getMaxConcurrentConsumers()); - assertEquals(5, container.getMaxMessagesPerTask()); + assertThat(container.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); + assertThat(container.getConcurrentConsumers()).isEqualTo(3); + assertThat(container.getMaxConcurrentConsumers()).isEqualTo(10); + assertThat(container.getMaxMessagesPerTask()).isEqualTo(5); - assertEquals(messageListener, container.getMessageListener()); - assertEquals("myQueue", container.getDestinationName()); + assertThat(container.getMessageListener()).isEqualTo(messageListener); + assertThat(container.getDestinationName()).isEqualTo("myQueue"); } @Test @@ -114,9 +112,9 @@ public class JmsListenerContainerFactoryTests { JmsMessageEndpointManager container = factory.createListenerContainer(endpoint); assertDefaultJcaConfig(container); - assertEquals(10, container.getActivationSpecConfig().getMaxConcurrency()); - assertEquals(messageListener, container.getMessageListener()); - assertEquals("myQueue", container.getActivationSpecConfig().getDestinationName()); + assertThat(container.getActivationSpecConfig().getMaxConcurrency()).isEqualTo(10); + assertThat(container.getMessageListener()).isEqualTo(messageListener); + assertThat(container.getActivationSpecConfig().getDestinationName()).isEqualTo("myQueue"); } @Test @@ -144,7 +142,7 @@ public class JmsListenerContainerFactoryTests { endpoint.setDestination("myQueue"); DefaultMessageListenerContainer container = factory.createListenerContainer(endpoint); - assertSame(backOff, new DirectFieldAccessor(container).getPropertyValue("backOff")); + assertThat(new DirectFieldAccessor(container).getPropertyValue("backOff")).isSameAs(backOff); } @Test @@ -158,8 +156,8 @@ public class JmsListenerContainerFactoryTests { endpoint.setDestination("myQueue"); endpoint.setConcurrency("4-6"); DefaultMessageListenerContainer container = factory.createListenerContainer(endpoint); - assertEquals(4, container.getConcurrentConsumers()); - assertEquals(6, container.getMaxConcurrentConsumers()); + assertThat(container.getConcurrentConsumers()).isEqualTo(4); + assertThat(container.getMaxConcurrentConsumers()).isEqualTo(6); } @@ -178,17 +176,17 @@ public class JmsListenerContainerFactoryTests { } private void assertDefaultJmsConfig(AbstractMessageListenerContainer container) { - assertEquals(this.connectionFactory, container.getConnectionFactory()); - assertEquals(this.destinationResolver, container.getDestinationResolver()); - assertEquals(this.messageConverter, container.getMessageConverter()); - assertEquals(true, container.isSessionTransacted()); - assertEquals(Session.DUPS_OK_ACKNOWLEDGE, container.getSessionAcknowledgeMode()); - assertEquals(true, container.isPubSubDomain()); - assertEquals(true, container.isReplyPubSubDomain()); - assertEquals(new QosSettings(1, 7, 5000), container.getReplyQosSettings()); - assertEquals(true, container.isSubscriptionDurable()); - assertEquals("client-1234", container.getClientId()); - assertEquals(false, container.isAutoStartup()); + assertThat(container.getConnectionFactory()).isEqualTo(this.connectionFactory); + assertThat(container.getDestinationResolver()).isEqualTo(this.destinationResolver); + assertThat(container.getMessageConverter()).isEqualTo(this.messageConverter); + assertThat(container.isSessionTransacted()).isEqualTo(true); + assertThat(container.getSessionAcknowledgeMode()).isEqualTo(Session.DUPS_OK_ACKNOWLEDGE); + assertThat(container.isPubSubDomain()).isEqualTo(true); + assertThat(container.isReplyPubSubDomain()).isEqualTo(true); + assertThat(container.getReplyQosSettings()).isEqualTo(new QosSettings(1, 7, 5000)); + assertThat(container.isSubscriptionDurable()).isEqualTo(true); + assertThat(container.getClientId()).isEqualTo("client-1234"); + assertThat(container.isAutoStartup()).isEqualTo(false); } private void setDefaultJcaConfig(DefaultJcaListenerContainerFactory factory) { @@ -203,15 +201,15 @@ public class JmsListenerContainerFactoryTests { } private void assertDefaultJcaConfig(JmsMessageEndpointManager container) { - assertEquals(this.messageConverter, container.getMessageConverter()); - assertEquals(this.destinationResolver, container.getDestinationResolver()); + assertThat(container.getMessageConverter()).isEqualTo(this.messageConverter); + assertThat(container.getDestinationResolver()).isEqualTo(this.destinationResolver); JmsActivationSpecConfig config = container.getActivationSpecConfig(); - assertNotNull(config); - assertEquals(Session.DUPS_OK_ACKNOWLEDGE, config.getAcknowledgeMode()); - assertEquals(true, config.isPubSubDomain()); - assertEquals(new QosSettings(1, 7, 5000), container.getReplyQosSettings()); - assertEquals(true, config.isSubscriptionDurable()); - assertEquals("client-1234", config.getClientId()); + assertThat(config).isNotNull(); + assertThat(config.getAcknowledgeMode()).isEqualTo(Session.DUPS_OK_ACKNOWLEDGE); + assertThat(config.isPubSubDomain()).isEqualTo(true); + assertThat(container.getReplyQosSettings()).isEqualTo(new QosSettings(1, 7, 5000)); + assertThat(config.isSubscriptionDurable()).isEqualTo(true); + assertThat(config.getClientId()).isEqualTo("client-1234"); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerEndpointRegistrarTests.java b/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerEndpointRegistrarTests.java index 123814e4a90..986fce8e55d 100644 --- a/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerEndpointRegistrarTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerEndpointRegistrarTests.java @@ -21,10 +21,9 @@ import org.junit.Test; import org.springframework.beans.factory.support.StaticListableBeanFactory; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * @author Stephane Nicoll @@ -73,9 +72,9 @@ public class JmsListenerEndpointRegistrarTests { this.registrar.setContainerFactory(this.containerFactory); this.registrar.registerEndpoint(endpoint, null); this.registrar.afterPropertiesSet(); - assertNotNull("Container not created", this.registry.getListenerContainer("some id")); - assertEquals(1, this.registry.getListenerContainers().size()); - assertEquals("some id", this.registry.getListenerContainerIds().iterator().next()); + assertThat(this.registry.getListenerContainer("some id")).as("Container not created").isNotNull(); + assertThat(this.registry.getListenerContainers().size()).isEqualTo(1); + assertThat(this.registry.getListenerContainerIds().iterator().next()).isEqualTo("some id"); } @Test @@ -96,9 +95,9 @@ public class JmsListenerEndpointRegistrarTests { this.registrar.setContainerFactory(this.containerFactory); this.registrar.registerEndpoint(endpoint); this.registrar.afterPropertiesSet(); - assertNotNull("Container not created", this.registry.getListenerContainer("myEndpoint")); - assertEquals(1, this.registry.getListenerContainers().size()); - assertEquals("myEndpoint", this.registry.getListenerContainerIds().iterator().next()); + assertThat(this.registry.getListenerContainer("myEndpoint")).as("Container not created").isNotNull(); + assertThat(this.registry.getListenerContainers().size()).isEqualTo(1); + assertThat(this.registry.getListenerContainerIds().iterator().next()).isEqualTo("myEndpoint"); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerEndpointTests.java b/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerEndpointTests.java index fb2379388db..86b9c822281 100644 --- a/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerEndpointTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/config/JmsListenerEndpointTests.java @@ -28,9 +28,9 @@ import org.springframework.jms.listener.adapter.MessageListenerAdapter; import org.springframework.jms.listener.endpoint.JmsActivationSpecConfig; import org.springframework.jms.listener.endpoint.JmsMessageEndpointManager; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; /** @@ -50,12 +50,12 @@ public class JmsListenerEndpointTests { endpoint.setMessageListener(messageListener); endpoint.setupListenerContainer(container); - assertEquals("myQueue", container.getDestinationName()); - assertEquals("foo = 'bar'", container.getMessageSelector()); - assertEquals("mySubscription", container.getSubscriptionName()); - assertEquals(5, container.getConcurrentConsumers()); - assertEquals(10, container.getMaxConcurrentConsumers()); - assertEquals(messageListener, container.getMessageListener()); + assertThat(container.getDestinationName()).isEqualTo("myQueue"); + assertThat(container.getMessageSelector()).isEqualTo("foo = 'bar'"); + assertThat(container.getSubscriptionName()).isEqualTo("mySubscription"); + assertThat(container.getConcurrentConsumers()).isEqualTo(5); + assertThat(container.getMaxConcurrentConsumers()).isEqualTo(10); + assertThat(container.getMessageListener()).isEqualTo(messageListener); } @Test @@ -71,11 +71,11 @@ public class JmsListenerEndpointTests { endpoint.setupListenerContainer(container); JmsActivationSpecConfig config = container.getActivationSpecConfig(); - assertEquals("myQueue", config.getDestinationName()); - assertEquals("foo = 'bar'", config.getMessageSelector()); - assertEquals("mySubscription", config.getSubscriptionName()); - assertEquals(10, config.getMaxConcurrency()); - assertEquals(messageListener, container.getMessageListener()); + assertThat(config.getDestinationName()).isEqualTo("myQueue"); + assertThat(config.getMessageSelector()).isEqualTo("foo = 'bar'"); + assertThat(config.getSubscriptionName()).isEqualTo("mySubscription"); + assertThat(config.getMaxConcurrency()).isEqualTo(10); + assertThat(container.getMessageListener()).isEqualTo(messageListener); } @Test @@ -87,7 +87,7 @@ public class JmsListenerEndpointTests { endpoint.setMessageListener(messageListener); endpoint.setupListenerContainer(container); - assertEquals(10, new DirectFieldAccessor(container).getPropertyValue("concurrentConsumers")); + assertThat(new DirectFieldAccessor(container).getPropertyValue("concurrentConsumers")).isEqualTo(10); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java b/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java index ef9aa305aca..8a165a39565 100644 --- a/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java @@ -48,11 +48,7 @@ import org.springframework.util.ErrorHandler; import org.springframework.util.backoff.BackOff; import org.springframework.util.backoff.FixedBackOff; -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.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -85,14 +81,14 @@ public class JmsNamespaceHandlerTests { @Test public void testBeansCreated() { Map containers = context.getBeansOfType(DefaultMessageListenerContainer.class); - assertEquals("Context should contain 3 JMS listener containers", 3, containers.size()); + assertThat(containers.size()).as("Context should contain 3 JMS listener containers").isEqualTo(3); containers = context.getBeansOfType(GenericMessageEndpointManager.class); - assertEquals("Context should contain 3 JCA endpoint containers", 3, containers.size()); + assertThat(containers.size()).as("Context should contain 3 JCA endpoint containers").isEqualTo(3); Map containerFactories = context.getBeansOfType(JmsListenerContainerFactory.class); - assertEquals("Context should contain 3 JmsListenerContainerFactory instances", 3, containerFactories.size()); + assertThat(containerFactories.size()).as("Context should contain 3 JmsListenerContainerFactory instances").isEqualTo(3); } @Test @@ -113,33 +109,28 @@ public class JmsNamespaceHandlerTests { } } - assertEquals("1 container should have the default connectionFactory", 1, defaultConnectionFactoryCount); - assertEquals("2 containers should have the explicit connectionFactory", 2, explicitConnectionFactoryCount); + assertThat(defaultConnectionFactoryCount).as("1 container should have the default connectionFactory").isEqualTo(1); + assertThat(explicitConnectionFactoryCount).as("2 containers should have the explicit connectionFactory").isEqualTo(2); } @Test public void testJcaContainerConfiguration() throws Exception { Map containers = context.getBeansOfType(JmsMessageEndpointManager.class); - assertTrue("listener3 not found", containers.containsKey("listener3")); + assertThat(containers.containsKey("listener3")).as("listener3 not found").isTrue(); JmsMessageEndpointManager listener3 = containers.get("listener3"); - assertEquals("Wrong resource adapter", - context.getBean("testResourceAdapter"), listener3.getResourceAdapter()); - assertEquals("Wrong activation spec factory", context.getBean("testActivationSpecFactory"), - new DirectFieldAccessor(listener3).getPropertyValue("activationSpecFactory")); + assertThat(listener3.getResourceAdapter()).as("Wrong resource adapter").isEqualTo(context.getBean("testResourceAdapter")); + assertThat(new DirectFieldAccessor(listener3).getPropertyValue("activationSpecFactory")).as("Wrong activation spec factory").isEqualTo(context.getBean("testActivationSpecFactory")); Object endpointFactory = new DirectFieldAccessor(listener3).getPropertyValue("endpointFactory"); Object messageListener = new DirectFieldAccessor(endpointFactory).getPropertyValue("messageListener"); - assertEquals("Wrong message listener", MessageListenerAdapter.class, messageListener.getClass()); + assertThat(messageListener.getClass()).as("Wrong message listener").isEqualTo(MessageListenerAdapter.class); MessageListenerAdapter adapter = (MessageListenerAdapter) messageListener; DirectFieldAccessor adapterFieldAccessor = new DirectFieldAccessor(adapter); - assertEquals("Message converter not set properly", context.getBean("testMessageConverter"), - adapterFieldAccessor.getPropertyValue("messageConverter")); - assertEquals("Wrong delegate", context.getBean("testBean1"), - adapterFieldAccessor.getPropertyValue("delegate")); - assertEquals("Wrong method name", "setName", - adapterFieldAccessor.getPropertyValue("defaultListenerMethod")); + assertThat(adapterFieldAccessor.getPropertyValue("messageConverter")).as("Message converter not set properly").isEqualTo(context.getBean("testMessageConverter")); + assertThat(adapterFieldAccessor.getPropertyValue("delegate")).as("Wrong delegate").isEqualTo(context.getBean("testBean1")); + assertThat(adapterFieldAccessor.getPropertyValue("defaultListenerMethod")).as("Wrong method name").isEqualTo("setName"); } @Test @@ -147,24 +138,21 @@ public class JmsNamespaceHandlerTests { Map containers = context.getBeansOfType(DefaultJmsListenerContainerFactory.class); DefaultJmsListenerContainerFactory factory = containers.get("testJmsFactory"); - assertNotNull("No factory registered with testJmsFactory id", factory); + assertThat(factory).as("No factory registered with testJmsFactory id").isNotNull(); DefaultMessageListenerContainer container = factory.createListenerContainer(createDummyEndpoint()); - assertEquals("explicit connection factory not set", - context.getBean(EXPLICIT_CONNECTION_FACTORY), container.getConnectionFactory()); - assertEquals("explicit destination resolver not set", - context.getBean("testDestinationResolver"), container.getDestinationResolver()); - assertEquals("explicit message converter not set", - context.getBean("testMessageConverter"), container.getMessageConverter()); - assertEquals("Wrong pub/sub", true, container.isPubSubDomain()); - assertEquals("Wrong durable flag", true, container.isSubscriptionDurable()); - assertEquals("wrong cache", DefaultMessageListenerContainer.CACHE_CONNECTION, container.getCacheLevel()); - assertEquals("wrong concurrency", 3, container.getConcurrentConsumers()); - assertEquals("wrong concurrency", 5, container.getMaxConcurrentConsumers()); - assertEquals("wrong prefetch", 50, container.getMaxMessagesPerTask()); - assertEquals("Wrong phase", 99, container.getPhase()); - assertSame(context.getBean("testBackOff"), new DirectFieldAccessor(container).getPropertyValue("backOff")); + assertThat(container.getConnectionFactory()).as("explicit connection factory not set").isEqualTo(context.getBean(EXPLICIT_CONNECTION_FACTORY)); + assertThat(container.getDestinationResolver()).as("explicit destination resolver not set").isEqualTo(context.getBean("testDestinationResolver")); + assertThat(container.getMessageConverter()).as("explicit message converter not set").isEqualTo(context.getBean("testMessageConverter")); + assertThat(container.isPubSubDomain()).as("Wrong pub/sub").isEqualTo(true); + assertThat(container.isSubscriptionDurable()).as("Wrong durable flag").isEqualTo(true); + assertThat(container.getCacheLevel()).as("wrong cache").isEqualTo(DefaultMessageListenerContainer.CACHE_CONNECTION); + assertThat(container.getConcurrentConsumers()).as("wrong concurrency").isEqualTo(3); + assertThat(container.getMaxConcurrentConsumers()).as("wrong concurrency").isEqualTo(5); + assertThat(container.getMaxMessagesPerTask()).as("wrong prefetch").isEqualTo(50); + assertThat(container.getPhase()).as("Wrong phase").isEqualTo(99); + assertThat(new DirectFieldAccessor(container).getPropertyValue("backOff")).isSameAs(context.getBean("testBackOff")); } @Test @@ -172,18 +160,16 @@ public class JmsNamespaceHandlerTests { Map containers = context.getBeansOfType(DefaultJcaListenerContainerFactory.class); DefaultJcaListenerContainerFactory factory = containers.get("testJcaFactory"); - assertNotNull("No factory registered with testJcaFactory id", factory); + assertThat(factory).as("No factory registered with testJcaFactory id").isNotNull(); JmsMessageEndpointManager container = factory.createListenerContainer(createDummyEndpoint()); - assertEquals("explicit resource adapter not set", - context.getBean("testResourceAdapter"),container.getResourceAdapter()); - assertEquals("explicit message converter not set", - context.getBean("testMessageConverter"), container.getActivationSpecConfig().getMessageConverter()); - assertEquals("Wrong pub/sub", true, container.isPubSubDomain()); - assertEquals("wrong concurrency", 5, container.getActivationSpecConfig().getMaxConcurrency()); - assertEquals("Wrong prefetch", 50, container.getActivationSpecConfig().getPrefetchSize()); - assertEquals("Wrong phase", 77, container.getPhase()); + assertThat(container.getResourceAdapter()).as("explicit resource adapter not set").isEqualTo(context.getBean("testResourceAdapter")); + assertThat(container.getActivationSpecConfig().getMessageConverter()).as("explicit message converter not set").isEqualTo(context.getBean("testMessageConverter")); + assertThat(container.isPubSubDomain()).as("Wrong pub/sub").isEqualTo(true); + assertThat(container.getActivationSpecConfig().getMaxConcurrency()).as("wrong concurrency").isEqualTo(5); + assertThat(container.getActivationSpecConfig().getPrefetchSize()).as("Wrong prefetch").isEqualTo(50); + assertThat(container.getPhase()).as("Wrong phase").isEqualTo(77); } @Test @@ -192,29 +178,29 @@ public class JmsNamespaceHandlerTests { TestBean testBean2 = context.getBean("testBean2", TestBean.class); TestMessageListener testBean3 = context.getBean("testBean3", TestMessageListener.class); - assertNull(testBean1.getName()); - assertNull(testBean2.getName()); - assertNull(testBean3.message); + assertThat(testBean1.getName()).isNull(); + assertThat(testBean2.getName()).isNull(); + assertThat(testBean3.message).isNull(); TextMessage message1 = mock(TextMessage.class); given(message1.getText()).willReturn("Test1"); MessageListener listener1 = getListener("listener1"); listener1.onMessage(message1); - assertEquals("Test1", testBean1.getName()); + assertThat(testBean1.getName()).isEqualTo("Test1"); TextMessage message2 = mock(TextMessage.class); given(message2.getText()).willReturn("Test2"); MessageListener listener2 = getListener("listener2"); listener2.onMessage(message2); - assertEquals("Test2", testBean2.getName()); + assertThat(testBean2.getName()).isEqualTo("Test2"); TextMessage message3 = mock(TextMessage.class); MessageListener listener3 = getListener(DefaultMessageListenerContainer.class.getName() + "#0"); listener3.onMessage(message3); - assertSame(message3, testBean3.message); + assertThat(testBean3.message).isSameAs(message3); } @Test @@ -224,9 +210,9 @@ public class JmsNamespaceHandlerTests { BackOff backOff2 = getBackOff("listener2"); long recoveryInterval3 = getRecoveryInterval(DefaultMessageListenerContainer.class.getName() + "#0"); - assertSame(testBackOff, backOff1); - assertSame(testBackOff, backOff2); - assertEquals(DefaultMessageListenerContainer.DEFAULT_RECOVERY_INTERVAL, recoveryInterval3); + assertThat(backOff1).isSameAs(testBackOff); + assertThat(backOff2).isSameAs(testBackOff); + assertThat(recoveryInterval3).isEqualTo(DefaultMessageListenerContainer.DEFAULT_RECOVERY_INTERVAL); } @Test @@ -239,22 +225,20 @@ public class JmsNamespaceHandlerTests { DefaultMessageListenerContainer listener2 = this.context .getBean("listener2", DefaultMessageListenerContainer.class); - assertEquals("Wrong concurrency on listener using placeholder", 2, listener0.getConcurrentConsumers()); - assertEquals("Wrong concurrency on listener using placeholder", 3, listener0.getMaxConcurrentConsumers()); - assertEquals("Wrong concurrency on listener1", 3, listener1.getConcurrentConsumers()); - assertEquals("Wrong max concurrency on listener1", 5, listener1.getMaxConcurrentConsumers()); - assertEquals("Wrong custom concurrency on listener2", 5, listener2.getConcurrentConsumers()); - assertEquals("Wrong custom max concurrency on listener2", 10, listener2.getMaxConcurrentConsumers()); + assertThat(listener0.getConcurrentConsumers()).as("Wrong concurrency on listener using placeholder").isEqualTo(2); + assertThat(listener0.getMaxConcurrentConsumers()).as("Wrong concurrency on listener using placeholder").isEqualTo(3); + assertThat(listener1.getConcurrentConsumers()).as("Wrong concurrency on listener1").isEqualTo(3); + assertThat(listener1.getMaxConcurrentConsumers()).as("Wrong max concurrency on listener1").isEqualTo(5); + assertThat(listener2.getConcurrentConsumers()).as("Wrong custom concurrency on listener2").isEqualTo(5); + assertThat(listener2.getMaxConcurrentConsumers()).as("Wrong custom max concurrency on listener2").isEqualTo(10); // JCA JmsMessageEndpointManager listener3 = this.context .getBean("listener3", JmsMessageEndpointManager.class); JmsMessageEndpointManager listener4 = this.context .getBean("listener4", JmsMessageEndpointManager.class); - assertEquals("Wrong concurrency on listener3", 5, - listener3.getActivationSpecConfig().getMaxConcurrency()); - assertEquals("Wrong custom concurrency on listener4", 7, - listener4.getActivationSpecConfig().getMaxConcurrency()); + assertThat(listener3.getActivationSpecConfig().getMaxConcurrency()).as("Wrong concurrency on listener3").isEqualTo(5); + assertThat(listener4.getActivationSpecConfig().getMaxConcurrency()).as("Wrong custom concurrency on listener4").isEqualTo(7); } @Test @@ -264,20 +248,20 @@ public class JmsNamespaceHandlerTests { .getBean("listener1", DefaultMessageListenerContainer.class); DefaultMessageListenerContainer listener2 = this.context .getBean("listener2", DefaultMessageListenerContainer.class); - assertEquals("Wrong destination type on listener1", true, listener1.isPubSubDomain()); - assertEquals("Wrong destination type on listener2", true, listener2.isPubSubDomain()); - assertEquals("Wrong response destination type on listener1", false, listener1.isReplyPubSubDomain()); - assertEquals("Wrong response destination type on listener2", false, listener2.isReplyPubSubDomain()); + assertThat(listener1.isPubSubDomain()).as("Wrong destination type on listener1").isEqualTo(true); + assertThat(listener2.isPubSubDomain()).as("Wrong destination type on listener2").isEqualTo(true); + assertThat(listener1.isReplyPubSubDomain()).as("Wrong response destination type on listener1").isEqualTo(false); + assertThat(listener2.isReplyPubSubDomain()).as("Wrong response destination type on listener2").isEqualTo(false); // JCA JmsMessageEndpointManager listener3 = this.context .getBean("listener3", JmsMessageEndpointManager.class); JmsMessageEndpointManager listener4 = this.context .getBean("listener4", JmsMessageEndpointManager.class); - assertEquals("Wrong destination type on listener3", true, listener3.isPubSubDomain()); - assertEquals("Wrong destination type on listener4", true, listener4.isPubSubDomain()); - assertEquals("Wrong response destination type on listener3", false, listener3.isReplyPubSubDomain()); - assertEquals("Wrong response destination type on listener4", false, listener4.isReplyPubSubDomain()); + assertThat(listener3.isPubSubDomain()).as("Wrong destination type on listener3").isEqualTo(true); + assertThat(listener4.isPubSubDomain()).as("Wrong destination type on listener4").isEqualTo(true); + assertThat(listener3.isReplyPubSubDomain()).as("Wrong response destination type on listener3").isEqualTo(false); + assertThat(listener4.isReplyPubSubDomain()).as("Wrong response destination type on listener4").isEqualTo(false); } @Test @@ -286,9 +270,9 @@ public class JmsNamespaceHandlerTests { ErrorHandler errorHandler1 = getErrorHandler("listener1"); ErrorHandler errorHandler2 = getErrorHandler("listener2"); ErrorHandler defaultErrorHandler = getErrorHandler(DefaultMessageListenerContainer.class.getName() + "#0"); - assertSame(expected, errorHandler1); - assertSame(expected, errorHandler2); - assertNull(defaultErrorHandler); + assertThat(errorHandler1).isSameAs(expected); + assertThat(errorHandler2).isSameAs(expected); + assertThat(defaultErrorHandler).isNull(); } @Test @@ -298,33 +282,25 @@ public class JmsNamespaceHandlerTests { int phase3 = getPhase("listener3"); int phase4 = getPhase("listener4"); int defaultPhase = getPhase(DefaultMessageListenerContainer.class.getName() + "#0"); - assertEquals(99, phase1); - assertEquals(99, phase2); - assertEquals(77, phase3); - assertEquals(77, phase4); - assertEquals(Integer.MAX_VALUE, defaultPhase); + assertThat(phase1).isEqualTo(99); + assertThat(phase2).isEqualTo(99); + assertThat(phase3).isEqualTo(77); + assertThat(phase4).isEqualTo(77); + assertThat(defaultPhase).isEqualTo(Integer.MAX_VALUE); } @Test public void testComponentRegistration() { - assertTrue("Parser should have registered a component named 'listener1'", - context.containsComponentDefinition("listener1")); - assertTrue("Parser should have registered a component named 'listener2'", - context.containsComponentDefinition("listener2")); - assertTrue("Parser should have registered a component named 'listener3'", - context.containsComponentDefinition("listener3")); - assertTrue("Parser should have registered a component named '" - + DefaultMessageListenerContainer.class.getName() + "#0'", - context.containsComponentDefinition(DefaultMessageListenerContainer.class.getName() + "#0")); - assertTrue("Parser should have registered a component named '" - + JmsMessageEndpointManager.class.getName() + "#0'", - context.containsComponentDefinition(JmsMessageEndpointManager.class.getName() + "#0")); - assertTrue("Parser should have registered a component named 'testJmsFactory", - context.containsComponentDefinition("testJmsFactory")); - assertTrue("Parser should have registered a component named 'testJcaFactory", - context.containsComponentDefinition("testJcaFactory")); - assertTrue("Parser should have registered a component named 'testJcaFactory", - context.containsComponentDefinition("onlyJmsFactory")); + assertThat(context.containsComponentDefinition("listener1")).as("Parser should have registered a component named 'listener1'").isTrue(); + assertThat(context.containsComponentDefinition("listener2")).as("Parser should have registered a component named 'listener2'").isTrue(); + assertThat(context.containsComponentDefinition("listener3")).as("Parser should have registered a component named 'listener3'").isTrue(); + assertThat(context.containsComponentDefinition(DefaultMessageListenerContainer.class.getName() + "#0")).as("Parser should have registered a component named '" + + DefaultMessageListenerContainer.class.getName() + "#0'").isTrue(); + assertThat(context.containsComponentDefinition(JmsMessageEndpointManager.class.getName() + "#0")).as("Parser should have registered a component named '" + + JmsMessageEndpointManager.class.getName() + "#0'").isTrue(); + assertThat(context.containsComponentDefinition("testJmsFactory")).as("Parser should have registered a component named 'testJmsFactory").isTrue(); + assertThat(context.containsComponentDefinition("testJcaFactory")).as("Parser should have registered a component named 'testJcaFactory").isTrue(); + assertThat(context.containsComponentDefinition("onlyJmsFactory")).as("Parser should have registered a component named 'testJcaFactory").isTrue(); } @Test @@ -332,7 +308,7 @@ public class JmsNamespaceHandlerTests { Iterator iterator = context.getRegisteredComponents(); while (iterator.hasNext()) { ComponentDefinition compDef = iterator.next(); - assertNotNull("CompositeComponentDefinition '" + compDef.getName() + "' has no source attachment", compDef.getSource()); + assertThat(compDef.getSource()).as("CompositeComponentDefinition '" + compDef.getName() + "' has no source attachment").isNotNull(); validateComponentDefinition(compDef); } } @@ -341,7 +317,7 @@ public class JmsNamespaceHandlerTests { private void validateComponentDefinition(ComponentDefinition compDef) { BeanDefinition[] beanDefs = compDef.getBeanDefinitions(); for (BeanDefinition beanDef : beanDefs) { - assertNotNull("BeanDefinition has no source attachment", beanDef.getSource()); + assertThat(beanDef.getSource()).as("BeanDefinition has no source attachment").isNotNull(); } } @@ -362,7 +338,7 @@ public class JmsNamespaceHandlerTests { private long getRecoveryInterval(String containerBeanName) { BackOff backOff = getBackOff(containerBeanName); - assertEquals(FixedBackOff.class, backOff.getClass()); + assertThat(backOff.getClass()).isEqualTo(FixedBackOff.class); return ((FixedBackOff)backOff).getInterval(); } diff --git a/spring-jms/src/test/java/org/springframework/jms/config/MethodJmsListenerEndpointTests.java b/spring-jms/src/test/java/org/springframework/jms/config/MethodJmsListenerEndpointTests.java index 3252b94a49e..60546cd96fb 100644 --- a/spring-jms/src/test/java/org/springframework/jms/config/MethodJmsListenerEndpointTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/config/MethodJmsListenerEndpointTests.java @@ -62,12 +62,9 @@ import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.validation.annotation.Validated; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -111,7 +108,7 @@ public class MethodJmsListenerEndpointTests { endpoint.setMethod(getTestMethod()); endpoint.setMessageHandlerMethodFactory(this.factory); - assertNotNull(endpoint.createMessageListener(this.container)); + assertThat(endpoint.createMessageListener(this.container)).isNotNull(); } @Test @@ -124,8 +121,8 @@ public class MethodJmsListenerEndpointTests { MessagingMessageListenerAdapter listener = createInstance(this.factory, getListenerMethod("resolveObjectPayload", MyBean.class), this.container); DirectFieldAccessor accessor = new DirectFieldAccessor(listener); - assertSame(messageConverter, accessor.getPropertyValue("messageConverter")); - assertSame(destinationResolver, accessor.getPropertyValue("destinationResolver")); + assertThat(accessor.getPropertyValue("messageConverter")).isSameAs(messageConverter); + assertThat(accessor.getPropertyValue("destinationResolver")).isSameAs(destinationResolver); } @Test @@ -477,7 +474,7 @@ public class MethodJmsListenerEndpointTests { private Method getListenerMethod(String methodName, Class... parameterTypes) { Method method = ReflectionUtils.findMethod(JmsEndpointSampleBean.class, methodName, parameterTypes); - assertNotNull("no method found with name " + methodName + " and parameters " + Arrays.toString(parameterTypes)); + assertThat(("no method found with name " + methodName + " and parameters " + Arrays.toString(parameterTypes))).isNotNull(); return method; } @@ -490,7 +487,7 @@ public class MethodJmsListenerEndpointTests { } private void assertListenerMethodInvocation(JmsEndpointSampleBean bean, String methodName) { - assertTrue("Method " + methodName + " should have been invoked", bean.invocations.get(methodName)); + assertThat((boolean) bean.invocations.get(methodName)).as("Method " + methodName + " should have been invoked").isTrue(); } private void initializeFactory(DefaultMessageHandlerMethodFactory factory) { @@ -526,66 +523,66 @@ public class MethodJmsListenerEndpointTests { public void resolveMessageAndSession(javax.jms.Message message, Session session) { this.invocations.put("resolveMessageAndSession", true); - assertNotNull("Message not injected", message); - assertNotNull("Session not injected", session); + assertThat(message).as("Message not injected").isNotNull(); + assertThat(session).as("Session not injected").isNotNull(); } public void resolveGenericMessage(Message message) { this.invocations.put("resolveGenericMessage", true); - assertNotNull("Generic message not injected", message); - assertEquals("Wrong message payload", "test", message.getPayload()); + assertThat(message).as("Generic message not injected").isNotNull(); + assertThat(message.getPayload()).as("Wrong message payload").isEqualTo("test"); } public void resolveHeaderAndPayload(@Payload String content, @Header int myCounter) { this.invocations.put("resolveHeaderAndPayload", true); - assertEquals("Wrong @Payload resolution", "my payload", content); - assertEquals("Wrong @Header resolution", 55, myCounter); + assertThat(content).as("Wrong @Payload resolution").isEqualTo("my payload"); + assertThat(myCounter).as("Wrong @Header resolution").isEqualTo(55); } public void resolveCustomHeaderNameAndPayload(@Payload String content, @Header("myCounter") int counter) { this.invocations.put("resolveCustomHeaderNameAndPayload", true); - assertEquals("Wrong @Payload resolution", "my payload", content); - assertEquals("Wrong @Header resolution", 24, counter); + assertThat(content).as("Wrong @Payload resolution").isEqualTo("my payload"); + assertThat(counter).as("Wrong @Header resolution").isEqualTo(24); } public void resolveCustomHeaderNameAndPayloadWithHeaderNameSet(@Payload String content, @Header(name = "myCounter") int counter) { this.invocations.put("resolveCustomHeaderNameAndPayloadWithHeaderNameSet", true); - assertEquals("Wrong @Payload resolution", "my payload", content); - assertEquals("Wrong @Header resolution", 24, counter); + assertThat(content).as("Wrong @Payload resolution").isEqualTo("my payload"); + assertThat(counter).as("Wrong @Header resolution").isEqualTo(24); } public void resolveHeaders(String content, @Headers Map headers) { this.invocations.put("resolveHeaders", true); - assertEquals("Wrong payload resolution", "my payload", content); - assertNotNull("headers not injected", headers); - assertEquals("Missing JMS message id header", "abcd-1234", headers.get(JmsHeaders.MESSAGE_ID)); - assertEquals("Missing custom header", 1234, headers.get("customInt")); + assertThat(content).as("Wrong payload resolution").isEqualTo("my payload"); + assertThat(headers).as("headers not injected").isNotNull(); + assertThat(headers.get(JmsHeaders.MESSAGE_ID)).as("Missing JMS message id header").isEqualTo("abcd-1234"); + assertThat(headers.get("customInt")).as("Missing custom header").isEqualTo(1234); } public void resolveMessageHeaders(MessageHeaders headers) { this.invocations.put("resolveMessageHeaders", true); - assertNotNull("MessageHeaders not injected", headers); - assertEquals("Missing JMS message type header", "myMessageType", headers.get(JmsHeaders.TYPE)); - assertEquals("Missing custom header", 4567L, (long) headers.get("customLong"), 0.0); + assertThat(headers).as("MessageHeaders not injected").isNotNull(); + assertThat(headers.get(JmsHeaders.TYPE)).as("Missing JMS message type header").isEqualTo("myMessageType"); + assertThat((long) headers.get("customLong")).as("Missing custom header").isEqualTo(4567); } public void resolveJmsMessageHeaderAccessor(JmsMessageHeaderAccessor headers) { this.invocations.put("resolveJmsMessageHeaderAccessor", true); - assertNotNull("MessageHeaders not injected", headers); - assertEquals("Missing JMS message priority header", Integer.valueOf(9), headers.getPriority()); - assertEquals("Missing custom header", true, headers.getHeader("customBoolean")); + assertThat(headers).as("MessageHeaders not injected").isNotNull(); + assertThat(headers.getPriority()).as("Missing JMS message priority header").isEqualTo(Integer.valueOf(9)); + assertThat(headers.getHeader("customBoolean")).as("Missing custom header").isEqualTo(true); } public void resolveObjectPayload(MyBean bean) { this.invocations.put("resolveObjectPayload", true); - assertNotNull("Object payload not injected", bean); - assertEquals("Wrong content for payload", "myBean name", bean.name); + assertThat(bean).as("Object payload not injected").isNotNull(); + assertThat(bean.name).as("Wrong content for payload").isEqualTo("myBean name"); } public void resolveConvertedPayload(Integer counter) { this.invocations.put("resolveConvertedPayload", true); - assertNotNull("Payload not injected", counter); - assertEquals("Wrong content for payload", Integer.valueOf(33), counter); + assertThat(counter).as("Payload not injected").isNotNull(); + assertThat(counter).as("Wrong content for payload").isEqualTo(Integer.valueOf(33)); } public String processAndReply(@Payload String content) { diff --git a/spring-jms/src/test/java/org/springframework/jms/config/SimpleJmsListenerEndpointTests.java b/spring-jms/src/test/java/org/springframework/jms/config/SimpleJmsListenerEndpointTests.java index 496388845d9..adfdfa7838a 100644 --- a/spring-jms/src/test/java/org/springframework/jms/config/SimpleJmsListenerEndpointTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/config/SimpleJmsListenerEndpointTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.jms.listener.SimpleMessageListenerContainer; import org.springframework.jms.listener.adapter.MessageListenerAdapter; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -38,7 +38,7 @@ public class SimpleJmsListenerEndpointTests { SimpleJmsListenerEndpoint endpoint = new SimpleJmsListenerEndpoint(); MessageListener messageListener = new MessageListenerAdapter(); endpoint.setMessageListener(messageListener); - assertSame(messageListener, endpoint.createMessageListener(container)); + assertThat(endpoint.createMessageListener(container)).isSameAs(messageListener); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java b/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java index 9c8ed75678c..704f38b0fe4 100644 --- a/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java @@ -38,11 +38,8 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -56,8 +53,8 @@ public class JmsTransactionManagerTests { @After public void verifyTransactionSynchronizationManagerState() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } @@ -74,7 +71,7 @@ public class JmsTransactionManagerTests { TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); JmsTemplate jt = new JmsTemplate(cf); jt.execute((SessionCallback) sess -> { - assertSame(sess, session); + assertThat(session).isSameAs(sess); return null; }); tm.commit(ts); @@ -97,7 +94,7 @@ public class JmsTransactionManagerTests { TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); JmsTemplate jt = new JmsTemplate(cf); jt.execute((SessionCallback) sess -> { - assertSame(sess, session); + assertThat(session).isSameAs(sess); return null; }); tm.rollback(ts); @@ -120,7 +117,7 @@ public class JmsTransactionManagerTests { TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); final JmsTemplate jt = new JmsTemplate(cf); jt.execute((SessionCallback) sess -> { - assertSame(sess, session); + assertThat(session).isSameAs(sess); return null; }); TransactionTemplate tt = new TransactionTemplate(tm); @@ -128,7 +125,7 @@ public class JmsTransactionManagerTests { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jt.execute((SessionCallback) sess -> { - assertSame(sess, session); + assertThat(session).isSameAs(sess); return null; }); } @@ -153,7 +150,7 @@ public class JmsTransactionManagerTests { TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); final JmsTemplate jt = new JmsTemplate(cf); jt.execute((SessionCallback) sess -> { - assertSame(sess, session); + assertThat(session).isSameAs(sess); return null; }); TransactionTemplate tt = new TransactionTemplate(tm); @@ -161,7 +158,7 @@ public class JmsTransactionManagerTests { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jt.execute((SessionCallback) sess -> { - assertSame(sess, session); + assertThat(session).isSameAs(sess); return null; }); status.setRollbackOnly(); @@ -190,7 +187,7 @@ public class JmsTransactionManagerTests { TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); final JmsTemplate jt = new JmsTemplate(cf); jt.execute((SessionCallback) sess -> { - assertSame(sess, session); + assertThat(session).isSameAs(sess); return null; }); TransactionTemplate tt = new TransactionTemplate(tm); @@ -199,13 +196,13 @@ public class JmsTransactionManagerTests { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jt.execute((SessionCallback) sess -> { - assertNotSame(sess, session); + assertThat(session).isNotSameAs(sess); return null; }); } }); jt.execute((SessionCallback) sess -> { - assertSame(sess, session); + assertThat(session).isSameAs(sess); return null; }); tm.commit(ts); @@ -230,7 +227,7 @@ public class JmsTransactionManagerTests { TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); final JmsTemplate jt = new JmsTemplate(cf); jt.execute((SessionCallback) sess -> { - assertSame(sess, session); + assertThat(session).isSameAs(sess); return null; }); TransactionTemplate tt = new TransactionTemplate(tm); @@ -239,13 +236,13 @@ public class JmsTransactionManagerTests { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jt.execute((SessionCallback) sess -> { - assertNotSame(sess, session); + assertThat(session).isNotSameAs(sess); return null; }); } }); jt.execute((SessionCallback) sess -> { - assertSame(sess, session); + assertThat(session).isSameAs(sess); return null; }); tm.commit(ts); @@ -300,7 +297,7 @@ public class JmsTransactionManagerTests { JmsTemplate jt = new JmsTemplate(cf); jt.execute((SessionCallback) sess -> { - assertSame(sess, session); + assertThat(session).isSameAs(sess); return null; }); tm.commit(ts); diff --git a/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java b/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java index aefc957b3bd..2a857daa0f6 100644 --- a/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java @@ -30,9 +30,7 @@ import javax.jms.TopicSession; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -285,7 +283,7 @@ public class SingleConnectionFactoryTests { SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setExceptionListener(listener); Connection con1 = scf.createConnection(); - assertEquals(listener, con1.getExceptionListener()); + assertThat(con1.getExceptionListener()).isEqualTo(listener); con1.start(); con1.stop(); con1.close(); @@ -310,15 +308,15 @@ public class SingleConnectionFactoryTests { SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setReconnectOnException(true); Connection con1 = scf.createConnection(); - assertNull(con1.getExceptionListener()); + assertThat(con1.getExceptionListener()).isNull(); con1.start(); con.getExceptionListener().onException(new JMSException("")); Connection con2 = scf.createConnection(); con2.start(); scf.destroy(); // should trigger actual close - assertEquals(2, con.getStartCount()); - assertEquals(2, con.getCloseCount()); + assertThat(con.getStartCount()).isEqualTo(2); + assertThat(con.getCloseCount()).isEqualTo(2); } @Test @@ -332,16 +330,16 @@ public class SingleConnectionFactoryTests { scf.setExceptionListener(listener); scf.setReconnectOnException(true); Connection con1 = scf.createConnection(); - assertSame(listener, con1.getExceptionListener()); + assertThat(con1.getExceptionListener()).isSameAs(listener); con1.start(); con.getExceptionListener().onException(new JMSException("")); Connection con2 = scf.createConnection(); con2.start(); scf.destroy(); // should trigger actual close - assertEquals(2, con.getStartCount()); - assertEquals(2, con.getCloseCount()); - assertEquals(1, listener.getCount()); + assertThat(con.getStartCount()).isEqualTo(2); + assertThat(con.getCloseCount()).isEqualTo(2); + assertThat(listener.getCount()).isEqualTo(1); } @Test @@ -364,10 +362,10 @@ public class SingleConnectionFactoryTests { scf.setExceptionListener(listener0); Connection con1 = scf.createConnection(); con1.setExceptionListener(listener1); - assertSame(listener1, con1.getExceptionListener()); + assertThat(con1.getExceptionListener()).isSameAs(listener1); Connection con2 = scf.createConnection(); con2.setExceptionListener(listener2); - assertSame(listener2, con2.getExceptionListener()); + assertThat(con2.getExceptionListener()).isSameAs(listener2); con.getExceptionListener().onException(new JMSException("")); con2.close(); con.getExceptionListener().onException(new JMSException("")); @@ -375,11 +373,11 @@ public class SingleConnectionFactoryTests { con.getExceptionListener().onException(new JMSException("")); scf.destroy(); // should trigger actual close - assertEquals(0, con.getStartCount()); - assertEquals(1, con.getCloseCount()); - assertEquals(3, listener0.getCount()); - assertEquals(2, listener1.getCount()); - assertEquals(1, listener2.getCount()); + assertThat(con.getStartCount()).isEqualTo(0); + assertThat(con.getCloseCount()).isEqualTo(1); + assertThat(listener0.getCount()).isEqualTo(3); + assertThat(listener1.getCount()).isEqualTo(2); + assertThat(listener2.getCount()).isEqualTo(1); } @Test @@ -397,11 +395,11 @@ public class SingleConnectionFactoryTests { scf.setExceptionListener(listener0); Connection con1 = scf.createConnection(); con1.setExceptionListener(listener1); - assertSame(listener1, con1.getExceptionListener()); + assertThat(con1.getExceptionListener()).isSameAs(listener1); con1.start(); Connection con2 = scf.createConnection(); con2.setExceptionListener(listener2); - assertSame(listener2, con2.getExceptionListener()); + assertThat(con2.getExceptionListener()).isSameAs(listener2); con.getExceptionListener().onException(new JMSException("")); con2.close(); con1.getMetaData(); @@ -409,11 +407,11 @@ public class SingleConnectionFactoryTests { con1.close(); scf.destroy(); // should trigger actual close - assertEquals(2, con.getStartCount()); - assertEquals(2, con.getCloseCount()); - assertEquals(2, listener0.getCount()); - assertEquals(2, listener1.getCount()); - assertEquals(1, listener2.getCount()); + assertThat(con.getStartCount()).isEqualTo(2); + assertThat(con.getCloseCount()).isEqualTo(2); + assertThat(listener0.getCount()).isEqualTo(2); + assertThat(listener1.getCount()).isEqualTo(2); + assertThat(listener2.getCount()).isEqualTo(1); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/core/JmsMessagingTemplateTests.java b/spring-jms/src/test/java/org/springframework/jms/core/JmsMessagingTemplateTests.java index 7c929cc576a..7b58e436a0b 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/JmsMessagingTemplateTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/JmsMessagingTemplateTests.java @@ -48,12 +48,9 @@ import org.springframework.messaging.MessagingException; import org.springframework.messaging.converter.GenericMessageConverter; import org.springframework.messaging.support.MessageBuilder; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -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.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -87,7 +84,7 @@ public class JmsMessagingTemplateTests { @Test public void validateJmsTemplate() { - assertSame(this.jmsTemplate, this.messagingTemplate.getJmsTemplate()); + assertThat(this.messagingTemplate.getJmsTemplate()).isSameAs(this.jmsTemplate); } @Test @@ -125,10 +122,10 @@ public class JmsMessagingTemplateTests { private void assertPayloadConverter(JmsMessagingTemplate messagingTemplate, MessageConverter messageConverter) { MessageConverter jmsMessageConverter = messagingTemplate.getJmsMessageConverter(); - assertNotNull(jmsMessageConverter); - assertEquals(MessagingMessageConverter.class, jmsMessageConverter.getClass()); - assertSame(messageConverter, new DirectFieldAccessor(jmsMessageConverter) - .getPropertyValue("payloadConverter")); + assertThat(jmsMessageConverter).isNotNull(); + assertThat(jmsMessageConverter.getClass()).isEqualTo(MessagingMessageConverter.class); + assertThat(new DirectFieldAccessor(jmsMessageConverter) + .getPropertyValue("payloadConverter")).isSameAs(messageConverter); } @Test @@ -199,7 +196,7 @@ public class JmsMessagingTemplateTests { this.messagingTemplate.convertAndSend(destination, "my Payload"); verify(this.jmsTemplate).send(eq(destination), this.messageCreator.capture()); TextMessage textMessage = createTextMessage(this.messageCreator.getValue()); - assertEquals("my Payload", textMessage.getText()); + assertThat(textMessage.getText()).isEqualTo("my Payload"); } @Test @@ -207,7 +204,7 @@ public class JmsMessagingTemplateTests { this.messagingTemplate.convertAndSend("myQueue", "my Payload"); verify(this.jmsTemplate).send(eq("myQueue"), this.messageCreator.capture()); TextMessage textMessage = createTextMessage(this.messageCreator.getValue()); - assertEquals("my Payload", textMessage.getText()); + assertThat(textMessage.getText()).isEqualTo("my Payload"); } @Test @@ -218,7 +215,7 @@ public class JmsMessagingTemplateTests { this.messagingTemplate.convertAndSend("my Payload"); verify(this.jmsTemplate).send(eq(destination), this.messageCreator.capture()); TextMessage textMessage = createTextMessage(this.messageCreator.getValue()); - assertEquals("my Payload", textMessage.getText()); + assertThat(textMessage.getText()).isEqualTo("my Payload"); } @Test @@ -228,7 +225,7 @@ public class JmsMessagingTemplateTests { this.messagingTemplate.convertAndSend("my Payload"); verify(this.jmsTemplate).send(eq("myQueue"), this.messageCreator.capture()); TextMessage textMessage = createTextMessage(this.messageCreator.getValue()); - assertEquals("my Payload", textMessage.getText()); + assertThat(textMessage.getText()).isEqualTo("my Payload"); } @Test @@ -333,7 +330,7 @@ public class JmsMessagingTemplateTests { given(this.jmsTemplate.receive(destination)).willReturn(jmsMessage); String payload = this.messagingTemplate.receiveAndConvert(destination, String.class); - assertEquals("my Payload", payload); + assertThat(payload).isEqualTo("my Payload"); verify(this.jmsTemplate).receive(destination); } @@ -343,7 +340,7 @@ public class JmsMessagingTemplateTests { given(this.jmsTemplate.receive("myQueue")).willReturn(jmsMessage); String payload = this.messagingTemplate.receiveAndConvert("myQueue", String.class); - assertEquals("my Payload", payload); + assertThat(payload).isEqualTo("my Payload"); verify(this.jmsTemplate).receive("myQueue"); } @@ -355,7 +352,7 @@ public class JmsMessagingTemplateTests { given(this.jmsTemplate.receive(destination)).willReturn(jmsMessage); String payload = this.messagingTemplate.receiveAndConvert(String.class); - assertEquals("my Payload", payload); + assertThat(payload).isEqualTo("my Payload"); verify(this.jmsTemplate).receive(destination); } @@ -366,7 +363,7 @@ public class JmsMessagingTemplateTests { given(this.jmsTemplate.receive("myQueue")).willReturn(jmsMessage); String payload = this.messagingTemplate.receiveAndConvert(String.class); - assertEquals("my Payload", payload); + assertThat(payload).isEqualTo("my Payload"); verify(this.jmsTemplate).receive("myQueue"); } @@ -378,7 +375,7 @@ public class JmsMessagingTemplateTests { this.messagingTemplate.setMessageConverter(new GenericMessageConverter()); Integer payload = this.messagingTemplate.receiveAndConvert("myQueue", Integer.class); - assertEquals(Integer.valueOf(123), payload); + assertThat(payload).isEqualTo(Integer.valueOf(123)); verify(this.jmsTemplate).receive("myQueue"); } @@ -395,7 +392,7 @@ public class JmsMessagingTemplateTests { public void receiveAndConvertNoInput() { given(this.jmsTemplate.receive("myQueue")).willReturn(null); - assertNull(this.messagingTemplate.receiveAndConvert("myQueue", String.class)); + assertThat(this.messagingTemplate.receiveAndConvert("myQueue", String.class)).isNull(); } @Test @@ -462,7 +459,7 @@ public class JmsMessagingTemplateTests { String reply = this.messagingTemplate.convertSendAndReceive(destination, "my Payload", String.class); verify(this.jmsTemplate, times(1)).sendAndReceive(eq(destination), any()); - assertEquals("My reply", reply); + assertThat(reply).isEqualTo("My reply"); } @Test @@ -472,7 +469,7 @@ public class JmsMessagingTemplateTests { String reply = this.messagingTemplate.convertSendAndReceive("myQueue", "my Payload", String.class); verify(this.jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), any()); - assertEquals("My reply", reply); + assertThat(reply).isEqualTo("My reply"); } @Test @@ -484,7 +481,7 @@ public class JmsMessagingTemplateTests { String reply = this.messagingTemplate.convertSendAndReceive("my Payload", String.class); verify(this.jmsTemplate, times(1)).sendAndReceive(eq(destination), any()); - assertEquals("My reply", reply); + assertThat(reply).isEqualTo("My reply"); } @Test @@ -495,7 +492,7 @@ public class JmsMessagingTemplateTests { String reply = this.messagingTemplate.convertSendAndReceive("my Payload", String.class); verify(this.jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), any()); - assertEquals("My reply", reply); + assertThat(reply).isEqualTo("My reply"); } @Test @@ -634,8 +631,8 @@ public class JmsMessagingTemplateTests { private void assertTextMessage(MessageCreator messageCreator) { try { TextMessage jmsMessage = createTextMessage(messageCreator); - assertEquals("Wrong body message", "Hello", jmsMessage.getText()); - assertEquals("Invalid foo property", "bar", jmsMessage.getStringProperty("foo")); + assertThat(jmsMessage.getText()).as("Wrong body message").isEqualTo("Hello"); + assertThat(jmsMessage.getStringProperty("foo")).as("Invalid foo property").isEqualTo("bar"); } catch (JMSException e) { throw new IllegalStateException("Wrong text message", e); @@ -643,9 +640,9 @@ public class JmsMessagingTemplateTests { } private void assertTextMessage(Message message) { - assertNotNull("message should not be null", message); - assertEquals("Wrong payload", "Hello", message.getPayload()); - assertEquals("Invalid foo property", "bar", message.getHeaders().get("foo")); + assertThat(message).as("message should not be null").isNotNull(); + assertThat(message.getPayload()).as("Wrong payload").isEqualTo("Hello"); + assertThat(message.getHeaders().get("foo")).as("Invalid foo property").isEqualTo("bar"); } diff --git a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java index ba8afe6cf27..9180c34858d 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java @@ -60,10 +60,8 @@ import org.springframework.jndi.JndiTemplate; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -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.willThrow; import static org.mockito.Mockito.mock; @@ -146,7 +144,7 @@ public class JmsTemplateTests { PrintWriter out = new PrintWriter(sw); springJmsEx.printStackTrace(out); String trace = sw.toString(); - assertTrue("inner jms exception not found", trace.indexOf("host not found") > 0); + assertThat(trace.indexOf("host not found") > 0).as("inner jms exception not found").isTrue(); } @Test @@ -236,8 +234,8 @@ public class JmsTemplateTests { } }); - assertSame(this.session, ConnectionFactoryUtils.getTransactionalSession(scf, null, false)); - assertSame(this.session, ConnectionFactoryUtils.getTransactionalSession(scf, scf.createConnection(), false)); + assertThat(ConnectionFactoryUtils.getTransactionalSession(scf, null, false)).isSameAs(this.session); + assertThat(ConnectionFactoryUtils.getTransactionalSession(scf, scf.createConnection(), false)).isSameAs(this.session); TransactionAwareConnectionFactoryProxy tacf = new TransactionAwareConnectionFactoryProxy(scf); Connection tac = tacf.createConnection(); @@ -247,7 +245,7 @@ public class JmsTemplateTests { tac.close(); List synchs = TransactionSynchronizationManager.getSynchronizations(); - assertEquals(1, synchs.size()); + assertThat(synchs.size()).isEqualTo(1); TransactionSynchronization synch = synchs.get(0); synch.beforeCommit(false); synch.beforeCompletion(); @@ -258,7 +256,7 @@ public class JmsTemplateTests { TransactionSynchronizationManager.clearSynchronization(); scf.destroy(); } - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); verify(this.connection).start(); if (useTransactedTemplate()) { @@ -619,10 +617,10 @@ public class JmsTemplateTests { } if (testConverter) { - assertEquals("Message text should be equal", "Hello World!", textFromMessage); + assertThat(textFromMessage).as("Message text should be equal").isEqualTo("Hello World!"); } else { - assertEquals("Messages should refer to the same object", message, textMessage); + assertThat(textMessage).as("Messages should refer to the same object").isEqualTo(message); } verify(this.connection).start(); @@ -712,7 +710,7 @@ public class JmsTemplateTests { // replyTO set on the request verify(request).setJMSReplyTo(replyDestination); - assertSame("Reply message not received", reply, message); + assertThat(message).as("Reply message not received").isSameAs(reply); verify(this.connection).start(); verify(this.connection).close(); verify(localSession).close(); diff --git a/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java b/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java index f91b7ebce40..9d2c5dbe615 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.jms.core.JmsTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -44,9 +44,9 @@ public class JmsGatewaySupportTests { }; gateway.setConnectionFactory(mockConnectionFactory); gateway.afterPropertiesSet(); - assertEquals("Correct ConnectionFactory", mockConnectionFactory, gateway.getConnectionFactory()); - assertEquals("Correct JmsTemplate", mockConnectionFactory, gateway.getJmsTemplate().getConnectionFactory()); - assertEquals("initGateway called", 1, test.size()); + assertThat(gateway.getConnectionFactory()).as("Correct ConnectionFactory").isEqualTo(mockConnectionFactory); + assertThat(gateway.getJmsTemplate().getConnectionFactory()).as("Correct JmsTemplate").isEqualTo(mockConnectionFactory); + assertThat(test.size()).as("initGateway called").isEqualTo(1); } @Test @@ -61,8 +61,8 @@ public class JmsGatewaySupportTests { }; gateway.setJmsTemplate(template); gateway.afterPropertiesSet(); - assertEquals("Correct JmsTemplate", template, gateway.getJmsTemplate()); - assertEquals("initGateway called", 1, test.size()); + assertThat(gateway.getJmsTemplate()).as("Correct JmsTemplate").isEqualTo(template); + assertThat(test.size()).as("initGateway called").isEqualTo(1); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/DefaultMessageListenerContainerTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/DefaultMessageListenerContainerTests.java index 10ad9690f75..6b9118db3c3 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/DefaultMessageListenerContainerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/DefaultMessageListenerContainerTests.java @@ -30,7 +30,7 @@ import org.mockito.stubbing.Answer; import org.springframework.util.backoff.BackOff; import org.springframework.util.backoff.BackOffExecution; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -51,11 +51,11 @@ public class DefaultMessageListenerContainerTests { DefaultMessageListenerContainer container = createContainer(createFailingContainerFactory()); container.setBackOff(backOff); container.start(); - assertEquals(true, container.isRunning()); + assertThat(container.isRunning()).isEqualTo(true); container.refreshConnectionUntilSuccessful(); - assertEquals(false, container.isRunning()); + assertThat(container.isRunning()).isEqualTo(false); verify(backOff).start(); verify(execution).nextBackOff(); } @@ -72,7 +72,7 @@ public class DefaultMessageListenerContainerTests { container.start(); container.refreshConnectionUntilSuccessful(); - assertEquals(false, container.isRunning()); + assertThat(container.isRunning()).isEqualTo(false); verify(backOff).start(); verify(execution, times(2)).nextBackOff(); } @@ -89,7 +89,7 @@ public class DefaultMessageListenerContainerTests { container.start(); container.refreshConnectionUntilSuccessful(); - assertEquals(true, container.isRunning()); + assertThat(container.isRunning()).isEqualTo(true); verify(backOff).start(); verify(execution, times(1)).nextBackOff(); // only on attempt as the second one lead to a recovery } @@ -182,7 +182,7 @@ public class DefaultMessageListenerContainerTests { public void waitForCompletion() throws InterruptedException { this.countDownLatch.await(2, TimeUnit.SECONDS); - assertEquals("callback was not invoked", 0, this.countDownLatch.getCount()); + assertThat(this.countDownLatch.getCount()).as("callback was not invoked").isEqualTo(0); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java index d50501fe4b1..52be6935aec 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java @@ -35,12 +35,9 @@ import org.springframework.jms.StubQueue; import org.springframework.lang.Nullable; import org.springframework.util.ErrorHandler; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -65,7 +62,7 @@ public class SimpleMessageListenerContainerTests { @Test public void testSettingMessageListenerToANullType() { this.container.setMessageListener(null); - assertNull(this.container.getMessageListener()); + assertThat(this.container.getMessageListener()).isNull(); } @Test @@ -76,10 +73,9 @@ public class SimpleMessageListenerContainerTests { @Test public void testSessionTransactedModeReallyDoesDefaultToFalse() { - assertFalse("The [pubSubLocal] property of SimpleMessageListenerContainer " + + assertThat(this.container.isPubSubNoLocal()).as("The [pubSubLocal] property of SimpleMessageListenerContainer " + "must default to false. Change this test (and the " + - "attendant Javadoc) if you have changed the default.", - this.container.isPubSubNoLocal()); + "attendant Javadoc) if you have changed the default.").isFalse(); } @Test @@ -190,7 +186,7 @@ public class SimpleMessageListenerContainerTests { public void onMessage(Message message, @Nullable Session sess) { try { // Check correct Session passed into SessionAwareMessageListener. - assertSame(sess, session); + assertThat(session).isSameAs(sess); } catch (Throwable ex) { failure.add("MessageListener execution failed: " + ex); @@ -238,9 +234,9 @@ public class SimpleMessageListenerContainerTests { @Override public void execute(Runnable task) { listener.executorInvoked = true; - assertFalse(listener.listenerInvoked); + assertThat(listener.listenerInvoked).isFalse(); task.run(); - assertTrue(listener.listenerInvoked); + assertThat(listener.listenerInvoked).isTrue(); } }); this.container.afterPropertiesSet(); @@ -249,8 +245,8 @@ public class SimpleMessageListenerContainerTests { final Message message = mock(Message.class); messageConsumer.sendMessage(message); - assertTrue(listener.executorInvoked); - assertTrue(listener.listenerInvoked); + assertThat(listener.executorInvoked).isTrue(); + assertThat(listener.listenerInvoked).isTrue(); verify(connection).setExceptionListener(this.container); verify(connection).start(); diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/JmsResponseTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/JmsResponseTests.java index ac8125cb758..b33ef3a23fa 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/JmsResponseTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/JmsResponseTests.java @@ -24,8 +24,8 @@ import org.junit.Test; import org.springframework.jms.support.destination.DestinationResolver; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertSame; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -38,7 +38,7 @@ public class JmsResponseTests { public void destinationDoesNotUseDestinationResolver() throws JMSException { Destination destination = mock(Destination.class); Destination actual = JmsResponse.forDestination("foo", destination).resolveDestination(null, null); - assertSame(destination, actual); + assertThat(actual).isSameAs(destination); } @Test @@ -50,7 +50,7 @@ public class JmsResponseTests { given(destinationResolver.resolveDestinationName(session, "myQueue", false)).willReturn(destination); JmsResponse jmsResponse = JmsResponse.forQueue("foo", "myQueue"); Destination actual = jmsResponse.resolveDestination(destinationResolver, session); - assertSame(destination, actual); + assertThat(actual).isSameAs(destination); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java index a861810ca78..6cbe1bfb88d 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java @@ -37,12 +37,8 @@ import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; +import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; @@ -151,7 +147,7 @@ public class MessageListenerAdapterTests { StubMessageListenerAdapter adapter = new StubMessageListenerAdapter(); adapter.onMessage(textMessage); - assertTrue(adapter.wasCalled()); + assertThat(adapter.wasCalled()).isTrue(); } @Test @@ -163,7 +159,7 @@ public class MessageListenerAdapterTests { StubMessageListenerAdapter adapter = new StubMessageListenerAdapter(); adapter.setDefaultListenerMethod("walnutsRock"); adapter.onMessage(textMessage); - assertFalse(adapter.wasCalled()); + assertThat(adapter.wasCalled()).isFalse(); } @Test @@ -177,13 +173,13 @@ public class MessageListenerAdapterTests { MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override protected void handleListenerException(Throwable ex) { - assertNotNull("The Throwable passed to the handleListenerException(..) method must never be null.", ex); - assertTrue("The Throwable passed to the handleListenerException(..) method must be of type [ListenerExecutionFailedException].", - ex instanceof ListenerExecutionFailedException); + assertThat(ex).as("The Throwable passed to the handleListenerException(..) method must never be null.").isNotNull(); + boolean condition = ex instanceof ListenerExecutionFailedException; + assertThat(condition).as("The Throwable passed to the handleListenerException(..) method must be of type [ListenerExecutionFailedException].").isTrue(); ListenerExecutionFailedException lefx = (ListenerExecutionFailedException) ex; Throwable cause = lefx.getCause(); - assertNotNull("The cause of a ListenerExecutionFailedException must be preserved.", cause); - assertSame(exception, cause); + assertThat(cause).as("The cause of a ListenerExecutionFailedException must be preserved.").isNotNull(); + assertThat(cause).isSameAs(exception); } }; // we DON'T want the default SimpleMessageConversion happening... @@ -194,21 +190,21 @@ public class MessageListenerAdapterTests { @Test public void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter() throws Exception { MessageListenerAdapter adapter = new MessageListenerAdapter(); - assertNotNull("The default [MessageConverter] must never be null.", adapter.getMessageConverter()); - assertTrue("The default [MessageConverter] must be of the type [SimpleMessageConverter]", - adapter.getMessageConverter() instanceof SimpleMessageConverter); + assertThat(adapter.getMessageConverter()).as("The default [MessageConverter] must never be null.").isNotNull(); + boolean condition = adapter.getMessageConverter() instanceof SimpleMessageConverter; + assertThat(condition).as("The default [MessageConverter] must be of the type [SimpleMessageConverter]").isTrue(); } @Test public void testThatWhenNoDelegateIsSuppliedTheDelegateIsAssumedToBeTheMessageListenerAdapterItself() throws Exception { MessageListenerAdapter adapter = new MessageListenerAdapter(); - assertSame(adapter, adapter.getDelegate()); + assertThat(adapter.getDelegate()).isSameAs(adapter); } @Test public void testThatTheDefaultMessageHandlingMethodNameIsTheConstantDefault() throws Exception { MessageListenerAdapter adapter = new MessageListenerAdapter(); - assertEquals(MessageListenerAdapter.ORIGINAL_DEFAULT_LISTENER_METHOD, adapter.getDefaultListenerMethod()); + assertThat(adapter.getDefaultListenerMethod()).isEqualTo(MessageListenerAdapter.ORIGINAL_DEFAULT_LISTENER_METHOD); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java index 87710b6c589..3437ceafd5f 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java @@ -48,8 +48,6 @@ import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -89,11 +87,11 @@ public class MessagingMessageListenerAdapterTests { javax.jms.Message replyMessage = listener.buildMessage(session, result); verify(session).createTextMessage("Response"); - assertNotNull("reply should never be null", replyMessage); - assertEquals("Response", ((TextMessage) replyMessage).getText()); - assertEquals("custom header not copied", "bar", replyMessage.getStringProperty("foo")); - assertEquals("type header not copied", "msg_type", replyMessage.getJMSType()); - assertEquals("replyTo header not copied", replyTo, replyMessage.getJMSReplyTo()); + assertThat(replyMessage).as("reply should never be null").isNotNull(); + assertThat(((TextMessage) replyMessage).getText()).isEqualTo("Response"); + assertThat(replyMessage.getStringProperty("foo")).as("custom header not copied").isEqualTo("bar"); + assertThat(replyMessage.getJMSType()).as("type header not copied").isEqualTo("msg_type"); + assertThat(replyMessage.getJMSReplyTo()).as("replyTo header not copied").isEqualTo(replyTo); } @Test @@ -127,7 +125,7 @@ public class MessagingMessageListenerAdapterTests { listener.setMessageConverter(messageConverter); Message message = listener.toMessagingMessage(jmsMessage); verify(messageConverter, never()).fromMessage(jmsMessage); - assertEquals("FooBar", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("FooBar"); verify(messageConverter, times(1)).fromMessage(jmsMessage); } @@ -154,8 +152,8 @@ public class MessagingMessageListenerAdapterTests { listener.setMessageConverter(messageConverter); listener.onMessage(jmsMessage, session); verify(messageConverter, times(1)).fromMessage(jmsMessage); - assertEquals(1, sample.simples.size()); - assertEquals("FooBar", sample.simples.get(0).getPayload()); + assertThat(sample.simples.size()).isEqualTo(1); + assertThat(sample.simples.get(0).getPayload()).isEqualTo("FooBar"); } @Test @@ -170,8 +168,8 @@ public class MessagingMessageListenerAdapterTests { javax.jms.Message replyMessage = listener.buildMessage(session, result); verify(messageConverter, times(1)).toMessage("Response", session); - assertNotNull("reply should never be null", replyMessage); - assertEquals("Response", ((TextMessage) replyMessage).getText()); + assertThat(replyMessage).as("reply should never be null").isNotNull(); + assertThat(((TextMessage) replyMessage).getText()).isEqualTo("Response"); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java index 6ad702dee78..75ec188fc1a 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java @@ -25,8 +25,7 @@ import org.springframework.jca.StubResourceAdapter; import org.springframework.jms.StubQueue; import org.springframework.jms.support.destination.DestinationResolver; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -54,9 +53,9 @@ public class DefaultJmsActivationSpecFactoryTests { StubActiveMQActivationSpec spec = (StubActiveMQActivationSpec) activationSpecFactory.createActivationSpec( new StubActiveMQResourceAdapter(), activationSpecConfig); - assertEquals(5, spec.getMaxSessions()); - assertEquals(3, spec.getMaxMessagesPerSessions()); - assertTrue(spec.isUseRAManagedTransaction()); + assertThat(spec.getMaxSessions()).isEqualTo(5); + assertThat(spec.getMaxMessagesPerSessions()).isEqualTo(3); + assertThat(spec.isUseRAManagedTransaction()).isTrue(); } @Test @@ -72,9 +71,9 @@ public class DefaultJmsActivationSpecFactoryTests { StubWebSphereActivationSpecImpl spec = (StubWebSphereActivationSpecImpl) activationSpecFactory .createActivationSpec(new StubWebSphereResourceAdapterImpl(), activationSpecConfig); - assertEquals(destination, spec.getDestination()); - assertEquals(5, spec.getMaxConcurrency()); - assertEquals(3, spec.getMaxBatchSize()); + assertThat(spec.getDestination()).isEqualTo(destination); + assertThat(spec.getMaxConcurrency()).isEqualTo(5); + assertThat(spec.getMaxBatchSize()).isEqualTo(3); } diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/JmsMessageEndpointManagerTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/JmsMessageEndpointManagerTests.java index 0f0ab66fd94..f233bb89b4a 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/JmsMessageEndpointManagerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/JmsMessageEndpointManagerTests.java @@ -20,10 +20,8 @@ import org.junit.Test; import org.springframework.jms.support.QosSettings; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; /** * @author Stephane Nicoll @@ -36,8 +34,8 @@ public class JmsMessageEndpointManagerTests { JmsActivationSpecConfig config = new JmsActivationSpecConfig(); config.setPubSubDomain(false); endpoint.setActivationSpecConfig(config); - assertEquals(false, endpoint.isPubSubDomain()); - assertEquals(false, endpoint.isReplyPubSubDomain()); + assertThat(endpoint.isPubSubDomain()).isEqualTo(false); + assertThat(endpoint.isReplyPubSubDomain()).isEqualTo(false); } @Test @@ -46,8 +44,8 @@ public class JmsMessageEndpointManagerTests { JmsActivationSpecConfig config = new JmsActivationSpecConfig(); config.setPubSubDomain(true); endpoint.setActivationSpecConfig(config); - assertEquals(true, endpoint.isPubSubDomain()); - assertEquals(true, endpoint.isReplyPubSubDomain()); + assertThat(endpoint.isPubSubDomain()).isEqualTo(true); + assertThat(endpoint.isReplyPubSubDomain()).isEqualTo(true); } @Test @@ -57,8 +55,8 @@ public class JmsMessageEndpointManagerTests { config.setPubSubDomain(true); config.setReplyPubSubDomain(false); endpoint.setActivationSpecConfig(config); - assertEquals(true, endpoint.isPubSubDomain()); - assertEquals(false, endpoint.isReplyPubSubDomain()); + assertThat(endpoint.isPubSubDomain()).isEqualTo(true); + assertThat(endpoint.isReplyPubSubDomain()).isEqualTo(false); } @Test @@ -68,10 +66,10 @@ public class JmsMessageEndpointManagerTests { QosSettings settings = new QosSettings(1, 3, 5); config.setReplyQosSettings(settings); endpoint.setActivationSpecConfig(config); - assertNotNull(endpoint.getReplyQosSettings()); - assertEquals(1, endpoint.getReplyQosSettings().getDeliveryMode()); - assertEquals(3, endpoint.getReplyQosSettings().getPriority()); - assertEquals(5, endpoint.getReplyQosSettings().getTimeToLive()); + assertThat(endpoint.getReplyQosSettings()).isNotNull(); + assertThat(endpoint.getReplyQosSettings().getDeliveryMode()).isEqualTo(1); + assertThat(endpoint.getReplyQosSettings().getPriority()).isEqualTo(3); + assertThat(endpoint.getReplyQosSettings().getTimeToLive()).isEqualTo(5); } @Test @@ -101,12 +99,12 @@ public class JmsMessageEndpointManagerTests { @Test public void getMessageConverterNoConfig() { JmsMessageEndpointManager endpoint = new JmsMessageEndpointManager(); - assertNull(endpoint.getMessageConverter()); + assertThat(endpoint.getMessageConverter()).isNull(); } @Test public void getDestinationResolverNoConfig() { JmsMessageEndpointManager endpoint = new JmsMessageEndpointManager(); - assertNull(endpoint.getDestinationResolver()); + assertThat(endpoint.getDestinationResolver()).isNull(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java b/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java index b1957ddb3fd..56f41f3f050 100644 --- a/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java @@ -40,10 +40,9 @@ import org.springframework.remoting.RemoteTimeoutException; import org.springframework.tests.sample.beans.ITestBean; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -122,7 +121,7 @@ public class JmsInvokerTests { ResponseStoringProducer mockProducer = new ResponseStoringProducer(); given(mockExporterSession.createProducer(requestMessage.getJMSReplyTo())).willReturn(mockProducer); exporter.onMessage(requestMessage, mockExporterSession); - assertTrue(mockProducer.closed); + assertThat(mockProducer.closed).isTrue(); return mockProducer.response; } }; @@ -139,12 +138,12 @@ public class JmsInvokerTests { pfb.afterPropertiesSet(); ITestBean proxy = (ITestBean) pfb.getObject(); - assertEquals("myname", proxy.getName()); - assertEquals(99, proxy.getAge()); + assertThat(proxy.getName()).isEqualTo("myname"); + assertThat(proxy.getAge()).isEqualTo(99); proxy.setAge(50); - assertEquals(50, proxy.getAge()); + assertThat(proxy.getAge()).isEqualTo(50); proxy.setStringArray(new String[] {"str1", "str2"}); - assertTrue(Arrays.equals(new String[] {"str1", "str2"}, proxy.getStringArray())); + assertThat(Arrays.equals(new String[] {"str1", "str2"}, proxy.getStringArray())).isTrue(); assertThatIllegalStateException().isThrownBy(() -> proxy.exceptional(new IllegalStateException())); assertThatExceptionOfType(IllegalAccessException.class).isThrownBy(() -> diff --git a/spring-jms/src/test/java/org/springframework/jms/support/JmsAccessorTests.java b/spring-jms/src/test/java/org/springframework/jms/support/JmsAccessorTests.java index b355795e14b..b0778ba445a 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/JmsAccessorTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/JmsAccessorTests.java @@ -20,9 +20,8 @@ import javax.jms.Session; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; /** * Unit tests for the {@link JmsAccessor} class. @@ -42,20 +41,17 @@ public class JmsAccessorTests { @Test public void testSessionTransactedModeReallyDoesDefaultToFalse() throws Exception { JmsAccessor accessor = new StubJmsAccessor(); - assertFalse("The [sessionTransacted] property of JmsAccessor must default to " + + assertThat(accessor.isSessionTransacted()).as("The [sessionTransacted] property of JmsAccessor must default to " + "false. Change this test (and the attendant Javadoc) if you have " + - "changed the default.", - accessor.isSessionTransacted()); + "changed the default.").isFalse(); } @Test public void testAcknowledgeModeReallyDoesDefaultToAutoAcknowledge() throws Exception { JmsAccessor accessor = new StubJmsAccessor(); - assertEquals("The [sessionAcknowledgeMode] property of JmsAccessor must default to " + + assertThat(accessor.getSessionAcknowledgeMode()).as("The [sessionAcknowledgeMode] property of JmsAccessor must default to " + "[Session.AUTO_ACKNOWLEDGE]. Change this test (and the attendant " + - "Javadoc) if you have changed the default.", - Session.AUTO_ACKNOWLEDGE, - accessor.getSessionAcknowledgeMode()); + "Javadoc) if you have changed the default.").isEqualTo(Session.AUTO_ACKNOWLEDGE); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/support/JmsMessageHeaderAccessorTests.java b/spring-jms/src/test/java/org/springframework/jms/support/JmsMessageHeaderAccessorTests.java index 7febb7cf9cd..cc0b71d928e 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/JmsMessageHeaderAccessorTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/JmsMessageHeaderAccessorTests.java @@ -26,8 +26,7 @@ import org.springframework.jms.StubTextMessage; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @@ -57,19 +56,20 @@ public class JmsMessageHeaderAccessorTests { Map mappedHeaders = new SimpleJmsHeaderMapper().toHeaders(jmsMessage); Message message = MessageBuilder.withPayload("test").copyHeaders(mappedHeaders).build(); JmsMessageHeaderAccessor headerAccessor = JmsMessageHeaderAccessor.wrap(message); - assertEquals("correlation-1234", headerAccessor.getCorrelationId()); - assertEquals(destination, headerAccessor.getDestination()); - assertEquals(Integer.valueOf(1), headerAccessor.getDeliveryMode()); - assertEquals(1234L, headerAccessor.getExpiration(), 0.0); - assertEquals("abcd-1234", headerAccessor.getMessageId()); - assertEquals(Integer.valueOf(9), headerAccessor.getPriority()); - assertEquals(replyTo, headerAccessor.getReplyTo()); - assertEquals(true, headerAccessor.getRedelivered()); - assertEquals("type", headerAccessor.getType()); - assertEquals(4567L, headerAccessor.getTimestamp(), 0.0); + assertThat(headerAccessor.getCorrelationId()).isEqualTo("correlation-1234"); + assertThat(headerAccessor.getDestination()).isEqualTo(destination); + assertThat(headerAccessor.getDeliveryMode()).isEqualTo(Integer.valueOf(1)); + assertThat(headerAccessor.getExpiration()).isEqualTo(1234); + + assertThat(headerAccessor.getMessageId()).isEqualTo("abcd-1234"); + assertThat(headerAccessor.getPriority()).isEqualTo(Integer.valueOf(9)); + assertThat(headerAccessor.getReplyTo()).isEqualTo(replyTo); + assertThat(headerAccessor.getRedelivered()).isEqualTo(true); + assertThat(headerAccessor.getType()).isEqualTo("type"); + assertThat(headerAccessor.getTimestamp()).isEqualTo(4567); // Making sure replyChannel is not mixed with replyTo - assertNull(headerAccessor.getReplyChannel()); + assertThat(headerAccessor.getReplyChannel()).isNull(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/SimpleJmsHeaderMapperTests.java b/spring-jms/src/test/java/org/springframework/jms/support/SimpleJmsHeaderMapperTests.java index c37998505ab..44e6ea65e04 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/SimpleJmsHeaderMapperTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/SimpleJmsHeaderMapperTests.java @@ -29,11 +29,7 @@ import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.MessageBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @@ -56,8 +52,8 @@ public class SimpleJmsHeaderMapperTests { javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertNotNull(jmsMessage.getJMSReplyTo()); - assertSame(replyTo, jmsMessage.getJMSReplyTo()); + assertThat(jmsMessage.getJMSReplyTo()).isNotNull(); + assertThat(jmsMessage.getJMSReplyTo()).isSameAs(replyTo); } @Test @@ -66,7 +62,7 @@ public class SimpleJmsHeaderMapperTests { .setHeader(JmsHeaders.REPLY_TO, "not-a-destination").build(); javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertNull(jmsMessage.getJMSReplyTo()); + assertThat(jmsMessage.getJMSReplyTo()).isNull(); } @Test @@ -76,8 +72,8 @@ public class SimpleJmsHeaderMapperTests { .setHeader(JmsHeaders.CORRELATION_ID, jmsCorrelationId).build(); javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertNotNull(jmsMessage.getJMSCorrelationID()); - assertEquals(jmsCorrelationId, jmsMessage.getJMSCorrelationID()); + assertThat(jmsMessage.getJMSCorrelationID()).isNotNull(); + assertThat(jmsMessage.getJMSCorrelationID()).isEqualTo(jmsCorrelationId); } @Test @@ -86,7 +82,7 @@ public class SimpleJmsHeaderMapperTests { .setHeader(JmsHeaders.CORRELATION_ID, 123).build(); javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertEquals("123", jmsMessage.getJMSCorrelationID()); + assertThat(jmsMessage.getJMSCorrelationID()).isEqualTo("123"); } @Test @@ -95,7 +91,7 @@ public class SimpleJmsHeaderMapperTests { .setHeader(JmsHeaders.CORRELATION_ID, new Date()).build(); javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertNull(jmsMessage.getJMSCorrelationID()); + assertThat(jmsMessage.getJMSCorrelationID()).isNull(); } @Test @@ -105,8 +101,8 @@ public class SimpleJmsHeaderMapperTests { .setHeader(JmsHeaders.TYPE, jmsType).build(); javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertNotNull(jmsMessage.getJMSType()); - assertEquals(jmsType, jmsMessage.getJMSType()); + assertThat(jmsMessage.getJMSType()).isNotNull(); + assertThat(jmsMessage.getJMSType()).isEqualTo(jmsType); } @Test @@ -115,7 +111,7 @@ public class SimpleJmsHeaderMapperTests { .setHeader(JmsHeaders.TYPE, 123).build(); javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertNull(jmsMessage.getJMSType()); + assertThat(jmsMessage.getJMSType()).isNull(); } @Test @@ -131,13 +127,13 @@ public class SimpleJmsHeaderMapperTests { .build(); javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertNull(jmsMessage.getJMSDestination()); - assertEquals(DeliveryMode.PERSISTENT, jmsMessage.getJMSDeliveryMode()); - assertEquals(0, jmsMessage.getJMSExpiration()); - assertNull(jmsMessage.getJMSMessageID()); - assertEquals(javax.jms.Message.DEFAULT_PRIORITY, jmsMessage.getJMSPriority()); - assertFalse(jmsMessage.getJMSRedelivered()); - assertEquals(0, jmsMessage.getJMSTimestamp()); + assertThat(jmsMessage.getJMSDestination()).isNull(); + assertThat(jmsMessage.getJMSDeliveryMode()).isEqualTo(DeliveryMode.PERSISTENT); + assertThat(jmsMessage.getJMSExpiration()).isEqualTo(0); + assertThat(jmsMessage.getJMSMessageID()).isNull(); + assertThat(jmsMessage.getJMSPriority()).isEqualTo(javax.jms.Message.DEFAULT_PRIORITY); + assertThat(jmsMessage.getJMSRedelivered()).isFalse(); + assertThat(jmsMessage.getJMSTimestamp()).isEqualTo(0); } @Test @@ -148,8 +144,8 @@ public class SimpleJmsHeaderMapperTests { javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); Object value = jmsMessage.getObjectProperty(JmsHeaderMapper.CONTENT_TYPE_PROPERTY); - assertNotNull(value); - assertEquals("foo", value); + assertThat(value).isNotNull(); + assertThat(value).isEqualTo("foo"); } @Test @@ -160,9 +156,9 @@ public class SimpleJmsHeaderMapperTests { javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); Object value = jmsMessage.getObjectProperty("foo"); - assertNotNull(value); - assertEquals(Integer.class, value.getClass()); - assertEquals(123, ((Integer) value).intValue()); + assertThat(value).isNotNull(); + assertThat(value.getClass()).isEqualTo(Integer.class); + assertThat(((Integer) value).intValue()).isEqualTo(123); } @Test @@ -174,9 +170,9 @@ public class SimpleJmsHeaderMapperTests { javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); Object value = jmsMessage.getObjectProperty("custom_foo"); - assertNotNull(value); - assertEquals(Integer.class, value.getClass()); - assertEquals(123, ((Integer) value).intValue()); + assertThat(value).isNotNull(); + assertThat(value.getClass()).isEqualTo(Integer.class); + assertThat(((Integer) value).intValue()).isEqualTo(123); } @Test @@ -188,7 +184,7 @@ public class SimpleJmsHeaderMapperTests { javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); Object value = jmsMessage.getObjectProperty("destination"); - assertNull(value); + assertThat(value).isNull(); } @Test @@ -433,11 +429,11 @@ public class SimpleJmsHeaderMapperTests { }; mapper.fromHeaders(message.getHeaders(), jmsMessage); Object foo = jmsMessage.getObjectProperty("foo"); - assertNotNull(foo); + assertThat(foo).isNotNull(); Object bar = jmsMessage.getObjectProperty("bar"); - assertNotNull(bar); + assertThat(bar).isNotNull(); Object bad = jmsMessage.getObjectProperty("bad"); - assertNull(bad); + assertThat(bad).isNull(); } @Test @@ -458,11 +454,11 @@ public class SimpleJmsHeaderMapperTests { }; mapper.fromHeaders(message.getHeaders(), jmsMessage); Object foo = jmsMessage.getObjectProperty("foo"); - assertNotNull(foo); + assertThat(foo).isNotNull(); Object bar = jmsMessage.getObjectProperty("bar"); - assertNotNull(bar); + assertThat(bar).isNotNull(); Object bad = jmsMessage.getObjectProperty("bad"); - assertNull(bad); + assertThat(bad).isNull(); } @Test @@ -478,9 +474,9 @@ public class SimpleJmsHeaderMapperTests { } }; mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertNull(jmsMessage.getJMSReplyTo()); - assertNotNull(jmsMessage.getStringProperty("foo")); - assertEquals("bar", jmsMessage.getStringProperty("foo")); + assertThat(jmsMessage.getJMSReplyTo()).isNull(); + assertThat(jmsMessage.getStringProperty("foo")).isNotNull(); + assertThat(jmsMessage.getStringProperty("foo")).isEqualTo("bar"); } @Test @@ -496,9 +492,9 @@ public class SimpleJmsHeaderMapperTests { } }; mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertNull(jmsMessage.getJMSType()); - assertNotNull(jmsMessage.getStringProperty("foo")); - assertEquals("bar", jmsMessage.getStringProperty("foo")); + assertThat(jmsMessage.getJMSType()).isNull(); + assertThat(jmsMessage.getStringProperty("foo")).isNotNull(); + assertThat(jmsMessage.getStringProperty("foo")).isEqualTo("bar"); } @Test @@ -514,9 +510,9 @@ public class SimpleJmsHeaderMapperTests { } }; mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertNull(jmsMessage.getJMSCorrelationID()); - assertNotNull(jmsMessage.getStringProperty("foo")); - assertEquals("bar", jmsMessage.getStringProperty("foo")); + assertThat(jmsMessage.getJMSCorrelationID()).isNull(); + assertThat(jmsMessage.getStringProperty("foo")).isNotNull(); + assertThat(jmsMessage.getStringProperty("foo")).isEqualTo("bar"); } @Test @@ -532,9 +528,9 @@ public class SimpleJmsHeaderMapperTests { } }; mapper.fromHeaders(message.getHeaders(), jmsMessage); - assertNull(jmsMessage.getJMSCorrelationID()); - assertNotNull(jmsMessage.getStringProperty("foo")); - assertEquals("bar", jmsMessage.getStringProperty("foo")); + assertThat(jmsMessage.getJMSCorrelationID()).isNull(); + assertThat(jmsMessage.getStringProperty("foo")).isNotNull(); + assertThat(jmsMessage.getStringProperty("foo")).isEqualTo("bar"); } @@ -542,12 +538,12 @@ public class SimpleJmsHeaderMapperTests { Map headers = mapper.toHeaders(jmsMessage); Object headerValue = headers.get(headerId); if (value == null) { - assertNull(headerValue); + assertThat(headerValue).isNull(); } else { - assertNotNull(headerValue); - assertEquals(value.getClass(), headerValue.getClass()); - assertEquals(value, headerValue); + assertThat(headerValue).isNotNull(); + assertThat(headerValue.getClass()).isEqualTo(value.getClass()); + assertThat(headerValue).isEqualTo(value); } } @@ -555,9 +551,9 @@ public class SimpleJmsHeaderMapperTests { throws JMSException { jmsMessage.setStringProperty("foo", "bar"); Map headers = mapper.toHeaders(jmsMessage); - assertNull(headers.get(headerId)); - assertNotNull(headers.get("foo")); - assertEquals("bar", headers.get("foo")); + assertThat(headers.get(headerId)).isNull(); + assertThat(headers.get("foo")).isNotNull(); + assertThat(headers.get("foo")).isEqualTo("bar"); } private MessageBuilder initBuilder() { diff --git a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java index 10bba348ffa..2e68dd6bbbb 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java @@ -35,9 +35,8 @@ import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -64,7 +63,7 @@ public class SimpleMessageConverterTests { SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); - assertEquals(content, converter.fromMessage(msg)); + assertThat(converter.fromMessage(msg)).isEqualTo(content); } @Test @@ -86,7 +85,7 @@ public class SimpleMessageConverterTests { SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); - assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length); + assertThat(((byte[]) converter.fromMessage(msg)).length).isEqualTo(content.length); verify(message).writeBytes(content); } @@ -108,7 +107,7 @@ public class SimpleMessageConverterTests { SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); - assertEquals(content, converter.fromMessage(msg)); + assertThat(converter.fromMessage(msg)).isEqualTo(content); verify(message).setObject("key1", "value1"); verify(message).setObject("key2", "value2"); @@ -126,7 +125,7 @@ public class SimpleMessageConverterTests { SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); - assertEquals(content, converter.fromMessage(msg)); + assertThat(converter.fromMessage(msg)).isEqualTo(content); } @Test @@ -148,7 +147,7 @@ public class SimpleMessageConverterTests { SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(message, session); - assertSame(message, msg); + assertThat(msg).isSameAs(message); } @Test @@ -157,7 +156,7 @@ public class SimpleMessageConverterTests { SimpleMessageConverter converter = new SimpleMessageConverter(); Object msg = converter.fromMessage(message); - assertSame(message, msg); + assertThat(msg).isSameAs(message); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java index 808b56a6f5b..66419419ce7 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java @@ -35,8 +35,8 @@ import org.mockito.stubbing.Answer; import org.springframework.core.MethodParameter; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; @@ -98,7 +98,7 @@ public class MappingJackson2MessageConverterTests { }); Object result = converter.fromMessage(bytesMessageMock); - assertEquals("Invalid result", result, unmarshalled); + assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test @@ -136,7 +136,7 @@ public class MappingJackson2MessageConverterTests { given(textMessageMock.getText()).willReturn(text); MyBean result = (MyBean)converter.fromMessage(textMessageMock); - assertEquals("Invalid result", result, unmarshalled); + assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test @@ -149,7 +149,7 @@ public class MappingJackson2MessageConverterTests { given(textMessageMock.getText()).willReturn(text); MyBean result = (MyBean)converter.fromMessage(textMessageMock); - assertEquals("Invalid result", result, unmarshalled); + assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test @@ -162,7 +162,7 @@ public class MappingJackson2MessageConverterTests { given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); - assertEquals("Invalid result", result, unmarshalled); + assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test @@ -175,7 +175,7 @@ public class MappingJackson2MessageConverterTests { given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); - assertEquals("Invalid result", result, unmarshalled); + assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java index 2e61b7d7b0b..e9410d7e46a 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java @@ -28,7 +28,7 @@ import org.junit.Test; import org.springframework.oxm.Marshaller; import org.springframework.oxm.Unmarshaller; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; @@ -80,7 +80,7 @@ public class MarshallingMessageConverterTests { given(unmarshallerMock.unmarshal(isA(Source.class))).willReturn(unmarshalled); Object result = converter.fromMessage(bytesMessageMock); - assertEquals("Invalid result", result, unmarshalled); + assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test @@ -106,7 +106,7 @@ public class MarshallingMessageConverterTests { given(unmarshallerMock.unmarshal(isA(Source.class))).willReturn(unmarshalled); Object result = converter.fromMessage(textMessageMock); - assertEquals("Invalid result", result, unmarshalled); + assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MessagingMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MessagingMessageConverterTests.java index fa51ce96ac1..dc43c080acf 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MessagingMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MessagingMessageConverterTests.java @@ -28,8 +28,8 @@ import org.springframework.jms.StubTextMessage; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -65,7 +65,7 @@ public class MessagingMessageConverterTests { this.converter.setPayloadConverter(new TestMessageConverter()); Message msg = (Message) this.converter.fromMessage(jmsMsg); - assertEquals(1224L, msg.getPayload()); + assertThat(msg.getPayload()).isEqualTo(1224L); } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java index 4f97dea28f1..84345e9c4c9 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java @@ -29,8 +29,7 @@ import org.junit.Test; import org.springframework.jms.StubQueue; import org.springframework.jms.StubTopic; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -77,8 +76,8 @@ public class DynamicDestinationResolverTests { private static void testResolveDestination(Session session, Destination expectedDestination, boolean isPubSub) throws JMSException { DynamicDestinationResolver resolver = new DynamicDestinationResolver(); Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, isPubSub); - assertNotNull(destination); - assertSame(expectedDestination, destination); + assertThat(destination).isNotNull(); + assertThat(destination).isSameAs(expectedDestination); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java index 388e4282f33..b5d55cc51e7 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java @@ -20,8 +20,8 @@ import javax.jms.ConnectionFactory; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; /** @@ -43,10 +43,9 @@ public class JmsDestinationAccessorTests { @Test public void testSessionTransactedModeReallyDoesDefaultToFalse() throws Exception { JmsDestinationAccessor accessor = new StubJmsDestinationAccessor(); - assertFalse("The [pubSubDomain] property of JmsDestinationAccessor must default to " + + assertThat(accessor.isPubSubDomain()).as("The [pubSubDomain] property of JmsDestinationAccessor must default to " + "false (i.e. Queues are used by default). Change this test (and the " + - "attendant Javadoc) if you have changed the default.", - accessor.isPubSubDomain()); + "attendant Javadoc) if you have changed the default.").isFalse(); } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java index b90336a2bff..ca13d3f6ec3 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java @@ -26,9 +26,6 @@ import org.springframework.jms.StubTopic; import static org.assertj.core.api.Assertions.assertThat; 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.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -50,8 +47,8 @@ public class JndiDestinationResolverTests { JndiDestinationResolver resolver = new OneTimeLookupJndiDestinationResolver(); Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true); - assertNotNull(destination); - assertSame(DESTINATION, destination); + assertThat(destination).isNotNull(); + assertThat(destination).isSameAs(DESTINATION); } @Test @@ -63,14 +60,14 @@ public class JndiDestinationResolverTests { = new CountingCannedJndiDestinationResolver(); resolver.setCache(false); Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true); - assertNotNull(destination); - assertSame(DESTINATION, destination); - assertEquals(1, resolver.getCallCount()); + assertThat(destination).isNotNull(); + assertThat(destination).isSameAs(DESTINATION); + assertThat(resolver.getCallCount()).isEqualTo(1); destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true); - assertNotNull(destination); - assertSame(DESTINATION, destination); - assertEquals(2, resolver.getCallCount()); + assertThat(destination).isNotNull(); + assertThat(destination).isSameAs(DESTINATION); + assertThat(resolver.getCallCount()).isEqualTo(2); } @Test @@ -91,8 +88,8 @@ public class JndiDestinationResolverTests { resolver.setDynamicDestinationResolver(dynamicResolver); Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true); - assertNotNull(destination); - assertSame(DESTINATION, destination); + assertThat(destination).isNotNull(); + assertThat(destination).isSameAs(DESTINATION); } @Test @@ -120,7 +117,7 @@ public class JndiDestinationResolverTests { @Override protected T lookup(String jndiName, Class requiredType) throws NamingException { assertThat(called).as("delegating to lookup(..) not cache").isFalse(); - assertEquals(DESTINATION_NAME, jndiName); + assertThat(jndiName).isEqualTo(DESTINATION_NAME); called = true; return requiredType.cast(DESTINATION); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java b/spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java index a9786bef3d6..0267e2e9a9f 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java @@ -27,13 +27,8 @@ import org.junit.Test; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Test fixture for {@link MessageHeaders}. @@ -47,7 +42,7 @@ public class MessageHeadersTests { @Test public void testTimestamp() { MessageHeaders headers = new MessageHeaders(null); - assertNotNull(headers.getTimestamp()); + assertThat(headers.getTimestamp()).isNotNull(); } @Test @@ -55,59 +50,59 @@ public class MessageHeadersTests { MessageHeaders headers1 = new MessageHeaders(null); Thread.sleep(50L); MessageHeaders headers2 = new MessageHeaders(headers1); - assertNotSame(headers1.getTimestamp(), headers2.getTimestamp()); + assertThat(headers2.getTimestamp()).isNotSameAs(headers1.getTimestamp()); } @Test public void testTimestampProvided() throws Exception { MessageHeaders headers = new MessageHeaders(null, null, 10L); - assertEquals(10L, (long) headers.getTimestamp()); + assertThat(headers.getTimestamp()).isEqualTo(10L); } @Test public void testTimestampProvidedNullValue() throws Exception { Map input = Collections.singletonMap(MessageHeaders.TIMESTAMP, 1L); MessageHeaders headers = new MessageHeaders(input, null, null); - assertNotNull(headers.getTimestamp()); + assertThat(headers.getTimestamp()).isNotNull(); } @Test public void testTimestampNone() throws Exception { MessageHeaders headers = new MessageHeaders(null, null, -1L); - assertNull(headers.getTimestamp()); + assertThat(headers.getTimestamp()).isNull(); } @Test public void testIdOverwritten() throws Exception { MessageHeaders headers1 = new MessageHeaders(null); MessageHeaders headers2 = new MessageHeaders(headers1); - assertNotSame(headers1.getId(), headers2.getId()); + assertThat(headers2.getId()).isNotSameAs(headers1.getId()); } @Test public void testId() { MessageHeaders headers = new MessageHeaders(null); - assertNotNull(headers.getId()); + assertThat(headers.getId()).isNotNull(); } @Test public void testIdProvided() { UUID id = new UUID(0L, 25L); MessageHeaders headers = new MessageHeaders(null, id, null); - assertEquals(id, headers.getId()); + assertThat(headers.getId()).isEqualTo(id); } @Test public void testIdProvidedNullValue() { Map input = Collections.singletonMap(MessageHeaders.ID, new UUID(0L, 25L)); MessageHeaders headers = new MessageHeaders(input, null, null); - assertNotNull(headers.getId()); + assertThat(headers.getId()).isNotNull(); } @Test public void testIdNone() { MessageHeaders headers = new MessageHeaders(null, MessageHeaders.ID_VALUE_NONE, null); - assertNull(headers.getId()); + assertThat(headers.getId()).isNull(); } @Test @@ -116,7 +111,7 @@ public class MessageHeadersTests { Map map = new HashMap<>(); map.put("test", value); MessageHeaders headers = new MessageHeaders(map); - assertEquals(value, headers.get("test")); + assertThat(headers.get("test")).isEqualTo(value); } @Test @@ -125,7 +120,7 @@ public class MessageHeadersTests { Map map = new HashMap<>(); map.put("test", value); MessageHeaders headers = new MessageHeaders(map); - assertEquals(value, headers.get("test", Integer.class)); + assertThat(headers.get("test", Integer.class)).isEqualTo(value); } @Test @@ -142,14 +137,14 @@ public class MessageHeadersTests { public void testNullHeaderValue() { Map map = new HashMap<>(); MessageHeaders headers = new MessageHeaders(map); - assertNull(headers.get("nosuchattribute")); + assertThat(headers.get("nosuchattribute")).isNull(); } @Test public void testNullHeaderValueWithTypedAccess() { Map map = new HashMap<>(); MessageHeaders headers = new MessageHeaders(map); - assertNull(headers.get("nosuchattribute", String.class)); + assertThat(headers.get("nosuchattribute", String.class)).isNull(); } @Test @@ -159,8 +154,8 @@ public class MessageHeadersTests { map.put("key2", new Integer(123)); MessageHeaders headers = new MessageHeaders(map); Set keys = headers.keySet(); - assertTrue(keys.contains("key1")); - assertTrue(keys.contains("key2")); + assertThat(keys.contains("key1")).isTrue(); + assertThat(keys.contains("key2")).isTrue(); } @Test @@ -170,10 +165,10 @@ public class MessageHeadersTests { map.put("age", 42); MessageHeaders input = new MessageHeaders(map); MessageHeaders output = (MessageHeaders) SerializationTestUtils.serializeAndDeserialize(input); - assertEquals("joe", output.get("name")); - assertEquals(42, output.get("age")); - assertEquals("joe", input.get("name")); - assertEquals(42, input.get("age")); + assertThat(output.get("name")).isEqualTo("joe"); + assertThat(output.get("age")).isEqualTo(42); + assertThat(input.get("name")).isEqualTo("joe"); + assertThat(input.get("age")).isEqualTo(42); } @Test @@ -184,10 +179,10 @@ public class MessageHeadersTests { map.put("address", address); MessageHeaders input = new MessageHeaders(map); MessageHeaders output = (MessageHeaders) SerializationTestUtils.serializeAndDeserialize(input); - assertEquals("joe", output.get("name")); - assertNull(output.get("address")); - assertEquals("joe", input.get("name")); - assertSame(address, input.get("address")); + assertThat(output.get("name")).isEqualTo("joe"); + assertThat(output.get("address")).isNull(); + assertThat(input.get("name")).isEqualTo("joe"); + assertThat(input.get("address")).isSameAs(address); } @Test @@ -200,8 +195,8 @@ public class MessageHeadersTests { } } MessageHeaders headers = new MyMH(); - assertEquals("00000000-0000-0000-0000-000000000001", headers.getId().toString()); - assertEquals(1, headers.size()); + assertThat(headers.getId().toString()).isEqualTo("00000000-0000-0000-0000-000000000001"); + assertThat(headers.size()).isEqualTo(1); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/DefaultContentTypeResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/DefaultContentTypeResolverTests.java index e4d8e2ae7a4..6382f4aa3be 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/DefaultContentTypeResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/DefaultContentTypeResolverTests.java @@ -27,10 +27,9 @@ import org.springframework.messaging.MessageHeaders; import org.springframework.util.InvalidMimeTypeException; import org.springframework.util.MimeTypeUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * Test fixture for {@link org.springframework.messaging.converter.DefaultContentTypeResolver}. @@ -53,7 +52,7 @@ public class DefaultContentTypeResolverTests { map.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON); MessageHeaders headers = new MessageHeaders(map); - assertEquals(MimeTypeUtils.APPLICATION_JSON, this.resolver.resolve(headers)); + assertThat(this.resolver.resolve(headers)).isEqualTo(MimeTypeUtils.APPLICATION_JSON); } @Test @@ -62,7 +61,7 @@ public class DefaultContentTypeResolverTests { map.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON_VALUE); MessageHeaders headers = new MessageHeaders(map); - assertEquals(MimeTypeUtils.APPLICATION_JSON, this.resolver.resolve(headers)); + assertThat(this.resolver.resolve(headers)).isEqualTo(MimeTypeUtils.APPLICATION_JSON); } @Test @@ -87,7 +86,7 @@ public class DefaultContentTypeResolverTests { public void resolveNoContentTypeHeader() { MessageHeaders headers = new MessageHeaders(Collections.emptyMap()); - assertNull(this.resolver.resolve(headers)); + assertThat(this.resolver.resolve(headers)).isNull(); } @Test @@ -95,7 +94,7 @@ public class DefaultContentTypeResolverTests { this.resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON); MessageHeaders headers = new MessageHeaders(Collections.emptyMap()); - assertEquals(MimeTypeUtils.APPLICATION_JSON, this.resolver.resolve(headers)); + assertThat(this.resolver.resolve(headers)).isEqualTo(MimeTypeUtils.APPLICATION_JSON); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/GenericMessageConverterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/GenericMessageConverterTests.java index 96c733866a6..98b66b2b1e6 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/GenericMessageConverterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/GenericMessageConverterTests.java @@ -26,9 +26,8 @@ import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * @@ -42,13 +41,13 @@ public class GenericMessageConverterTests { @Test public void fromMessageWithConversion() { Message content = MessageBuilder.withPayload("33").build(); - assertEquals(33, converter.fromMessage(content, Integer.class)); + assertThat(converter.fromMessage(content, Integer.class)).isEqualTo(33); } @Test public void fromMessageNoConverter() { Message content = MessageBuilder.withPayload(1234).build(); - assertNull("No converter from integer to locale", converter.fromMessage(content, Locale.class)); + assertThat(converter.fromMessage(content, Locale.class)).as("No converter from integer to locale").isNull(); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/MappingJackson2MessageConverterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/MappingJackson2MessageConverterTests.java index ff11926e6fc..bd4eff692fc 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/MappingJackson2MessageConverterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/MappingJackson2MessageConverterTests.java @@ -35,13 +35,7 @@ import org.springframework.util.MimeType; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.within; /** * Test fixture for {@link MappingJackson2MessageConverter}. @@ -56,8 +50,8 @@ public class MappingJackson2MessageConverterTests { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); assertThat(converter.getSupportedMimeTypes()) .contains(new MimeType("application", "json")); - assertFalse(converter.getObjectMapper().getDeserializationConfig() - .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); + assertThat(converter.getObjectMapper().getDeserializationConfig() + .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); } @Test // SPR-12724 @@ -65,8 +59,8 @@ public class MappingJackson2MessageConverterTests { MimeType mimetype = new MimeType("application", "xml", StandardCharsets.UTF_8); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(mimetype); assertThat(converter.getSupportedMimeTypes()).contains(mimetype); - assertFalse(converter.getObjectMapper().getDeserializationConfig() - .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); + assertThat(converter.getObjectMapper().getDeserializationConfig() + .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); } @Test // SPR-12724 @@ -75,8 +69,8 @@ public class MappingJackson2MessageConverterTests { MimeType xmlMimetype = new MimeType("application", "xml", StandardCharsets.UTF_8); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(jsonMimetype, xmlMimetype); assertThat(converter.getSupportedMimeTypes()).contains(jsonMimetype, xmlMimetype); - assertFalse(converter.getObjectMapper().getDeserializationConfig() - .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); + assertThat(converter.getObjectMapper().getDeserializationConfig() + .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); } @Test @@ -92,12 +86,12 @@ public class MappingJackson2MessageConverterTests { Message message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); MyBean actual = (MyBean) converter.fromMessage(message, MyBean.class); - assertEquals("Foo", actual.getString()); - assertEquals(42, actual.getNumber()); - assertEquals(42F, actual.getFraction(), 0F); - assertArrayEquals(new String[]{"Foo", "Bar"}, actual.getArray()); - assertTrue(actual.isBool()); - assertArrayEquals(new byte[]{0x1, 0x2}, actual.getBytes()); + assertThat(actual.getString()).isEqualTo("Foo"); + assertThat(actual.getNumber()).isEqualTo(42); + assertThat(actual.getFraction()).isCloseTo(42F, within(0F)); + assertThat(actual.getArray()).isEqualTo(new String[]{"Foo", "Bar"}); + assertThat(actual.isBool()).isTrue(); + assertThat(actual.getBytes()).isEqualTo(new byte[]{0x1, 0x2}); } @Test @@ -109,12 +103,12 @@ public class MappingJackson2MessageConverterTests { @SuppressWarnings("unchecked") HashMap actual = (HashMap) converter.fromMessage(message, HashMap.class); - assertEquals("Foo", actual.get("string")); - assertEquals(42, actual.get("number")); - assertEquals(42D, (Double) actual.get("fraction"), 0D); - assertEquals(Arrays.asList("Foo", "Bar"), actual.get("array")); - assertEquals(Boolean.TRUE, actual.get("bool")); - assertEquals("AQI=", actual.get("bytes")); + assertThat(actual.get("string")).isEqualTo("Foo"); + assertThat(actual.get("number")).isEqualTo(42); + assertThat((Double) actual.get("fraction")).isCloseTo(42D, within(0D)); + assertThat(actual.get("array")).isEqualTo(Arrays.asList("Foo", "Bar")); + assertThat(actual.get("bool")).isEqualTo(Boolean.TRUE); + assertThat(actual.get("bytes")).isEqualTo("AQI="); } @Test // gh-22386 @@ -122,7 +116,7 @@ public class MappingJackson2MessageConverterTests { MyBean myBean = new MyBean(); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); Message message = MessageBuilder.withPayload(myBean).build(); - assertSame(myBean, converter.fromMessage(message, MyBean.class)); + assertThat(converter.fromMessage(message, MyBean.class)).isSameAs(myBean); } @Test @@ -140,7 +134,7 @@ public class MappingJackson2MessageConverterTests { String payload = "{\"string\":\"string\",\"unknownProperty\":\"value\"}"; Message message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); MyBean myBean = (MyBean)converter.fromMessage(message, MyBean.class); - assertEquals("string", myBean.getString()); + assertThat(myBean.getString()).isEqualTo("string"); } @Test // SPR-16252 @@ -153,8 +147,8 @@ public class MappingJackson2MessageConverterTests { MethodParameter param = new MethodParameter(method, 0); Object actual = converter.fromMessage(message, List.class, param); - assertNotNull(actual); - assertEquals(Arrays.asList(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L), actual); + assertThat(actual).isNotNull(); + assertThat(actual).isEqualTo(Arrays.asList(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L)); } @Test // SPR-16486 @@ -167,8 +161,8 @@ public class MappingJackson2MessageConverterTests { MethodParameter param = new MethodParameter(method, 0); Object actual = converter.fromMessage(message, MyBean.class, param); - assertTrue(actual instanceof MyBean); - assertEquals("foo", ((MyBean) actual).getString()); + assertThat(actual instanceof MyBean).isTrue(); + assertThat(((MyBean) actual).getString()).isEqualTo("foo"); } @Test @@ -185,14 +179,13 @@ public class MappingJackson2MessageConverterTests { Message message = converter.toMessage(payload, null); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); - assertTrue(actual.contains("\"string\":\"Foo\"")); - assertTrue(actual.contains("\"number\":42")); - assertTrue(actual.contains("fraction\":42.0")); - assertTrue(actual.contains("\"array\":[\"Foo\",\"Bar\"]")); - assertTrue(actual.contains("\"bool\":true")); - assertTrue(actual.contains("\"bytes\":\"AQI=\"")); - assertEquals("Invalid content-type", new MimeType("application", "json"), - message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)); + assertThat(actual.contains("\"string\":\"Foo\"")).isTrue(); + assertThat(actual.contains("\"number\":42")).isTrue(); + assertThat(actual.contains("fraction\":42.0")).isTrue(); + assertThat(actual.contains("\"array\":[\"Foo\",\"Bar\"]")).isTrue(); + assertThat(actual.contains("\"bool\":true")).isTrue(); + assertThat(actual.contains("\"bytes\":\"AQI=\"")).isTrue(); + assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)).as("Invalid content-type").isEqualTo(new MimeType("application", "json")); } @Test @@ -205,8 +198,8 @@ public class MappingJackson2MessageConverterTests { String payload = "H\u00e9llo W\u00f6rld"; Message message = converter.toMessage(payload, headers); - assertEquals("\"" + payload + "\"", new String((byte[]) message.getPayload(), StandardCharsets.UTF_16BE)); - assertEquals(contentType, message.getHeaders().get(MessageHeaders.CONTENT_TYPE)); + assertThat(new String((byte[]) message.getPayload(), StandardCharsets.UTF_16BE)).isEqualTo(("\"" + payload + "\"")); + assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo(contentType); } @Test @@ -221,8 +214,8 @@ public class MappingJackson2MessageConverterTests { String payload = "H\u00e9llo W\u00f6rld"; Message message = converter.toMessage(payload, headers); - assertEquals("\"" + payload + "\"", message.getPayload()); - assertEquals(contentType, message.getHeaders().get(MessageHeaders.CONTENT_TYPE)); + assertThat(message.getPayload()).isEqualTo(("\"" + payload + "\"")); + assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo(contentType); } @Test @@ -242,9 +235,9 @@ public class MappingJackson2MessageConverterTests { method = getClass().getDeclaredMethod("jsonViewPayload", JacksonViewBean.class); MethodParameter param = new MethodParameter(method, 0); JacksonViewBean back = (JacksonViewBean) converter.fromMessage(message, JacksonViewBean.class, param); - assertNull(back.getWithView1()); - assertEquals("with", back.getWithView2()); - assertNull(back.getWithoutView()); + assertThat(back.getWithView1()).isNull(); + assertThat(back.getWithView2()).isEqualTo("with"); + assertThat(back.getWithoutView()).isNull(); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/MarshallingMessageConverterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/MarshallingMessageConverterTests.java index 40631c1fe20..9f18d6fbe66 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/MarshallingMessageConverterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/MarshallingMessageConverterTests.java @@ -31,8 +31,6 @@ import org.springframework.tests.XmlContent; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.xmlunit.diff.ComparisonType.XML_STANDALONE; import static org.xmlunit.diff.DifferenceEvaluators.Default; import static org.xmlunit.diff.DifferenceEvaluators.chain; @@ -62,8 +60,8 @@ public class MarshallingMessageConverterTests { Message message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); MyBean actual = (MyBean) this.converter.fromMessage(message, MyBean.class); - assertNotNull(actual); - assertEquals("Foo", actual.getName()); + assertThat(actual).isNotNull(); + assertThat(actual.getName()).isEqualTo("Foo"); } @Test @@ -88,7 +86,7 @@ public class MarshallingMessageConverterTests { payload.setName("Foo"); Message message = this.converter.toMessage(payload, null); - assertNotNull(message); + assertThat(message).isNotNull(); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); DifferenceEvaluator ev = chain(Default, downgradeDifferencesToEqual(XML_STANDALONE)); diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/MessageConverterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/MessageConverterTests.java index 3169a826765..fd2dcb0d2dc 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/MessageConverterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/MessageConverterTests.java @@ -33,13 +33,8 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; +import static org.assertj.core.api.Assertions.assertThat; 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; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Unit tests for @@ -56,8 +51,8 @@ public class MessageConverterTests { public void supportsTargetClass() { Message message = MessageBuilder.withPayload("ABC").build(); - assertEquals("success-from", this.converter.fromMessage(message, String.class)); - assertNull(this.converter.fromMessage(message, Integer.class)); + assertThat(this.converter.fromMessage(message, String.class)).isEqualTo("success-from"); + assertThat(this.converter.fromMessage(message, Integer.class)).isNull(); } @Test @@ -65,7 +60,7 @@ public class MessageConverterTests { Message message = MessageBuilder.withPayload( "ABC").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build(); - assertEquals("success-from", this.converter.fromMessage(message, String.class)); + assertThat(this.converter.fromMessage(message, String.class)).isEqualTo("success-from"); } @Test @@ -73,13 +68,13 @@ public class MessageConverterTests { Message message = MessageBuilder.withPayload( "ABC").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON).build(); - assertNull(this.converter.fromMessage(message, String.class)); + assertThat(this.converter.fromMessage(message, String.class)).isNull(); } @Test public void supportsMimeTypeNotSpecified() { Message message = MessageBuilder.withPayload("ABC").build(); - assertEquals("success-from", this.converter.fromMessage(message, String.class)); + assertThat(this.converter.fromMessage(message, String.class)).isEqualTo("success-from"); } @Test @@ -88,7 +83,7 @@ public class MessageConverterTests { "ABC").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON).build(); this.converter = new TestMessageConverter(Collections.emptyList()); - assertEquals("success-from", this.converter.fromMessage(message, String.class)); + assertThat(this.converter.fromMessage(message, String.class)).isEqualTo("success-from"); } @Test @@ -97,11 +92,11 @@ public class MessageConverterTests { this.converter.setStrictContentTypeMatch(true); Message message = MessageBuilder.withPayload("ABC").build(); - assertFalse(this.converter.canConvertFrom(message, String.class)); + assertThat(this.converter.canConvertFrom(message, String.class)).isFalse(); message = MessageBuilder.withPayload("ABC") .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build(); - assertTrue(this.converter.canConvertFrom(message, String.class)); + assertThat(this.converter.canConvertFrom(message, String.class)).isTrue(); } @@ -119,10 +114,10 @@ public class MessageConverterTests { MessageHeaders headers = new MessageHeaders(map); Message message = this.converter.toMessage("ABC", headers); - assertNotNull(message.getHeaders().getId()); - assertNotNull(message.getHeaders().getTimestamp()); - assertEquals(MimeTypeUtils.TEXT_PLAIN, message.getHeaders().get(MessageHeaders.CONTENT_TYPE)); - assertEquals("bar", message.getHeaders().get("foo")); + assertThat(message.getHeaders().getId()).isNotNull(); + assertThat(message.getHeaders().getTimestamp()).isNotNull(); + assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo(MimeTypeUtils.TEXT_PLAIN); + assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -135,16 +130,16 @@ public class MessageConverterTests { MessageHeaders headers = accessor.getMessageHeaders(); Message message = this.converter.toMessage("ABC", headers); - assertSame(headers, message.getHeaders()); - assertNull(message.getHeaders().getId()); - assertNull(message.getHeaders().getTimestamp()); - assertEquals(MimeTypeUtils.TEXT_PLAIN, message.getHeaders().get(MessageHeaders.CONTENT_TYPE)); + assertThat(message.getHeaders()).isSameAs(headers); + assertThat(message.getHeaders().getId()).isNull(); + assertThat(message.getHeaders().getTimestamp()).isNull(); + assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo(MimeTypeUtils.TEXT_PLAIN); } @Test public void toMessageContentTypeHeader() { Message message = this.converter.toMessage("ABC", null); - assertEquals(MimeTypeUtils.TEXT_PLAIN, message.getHeaders().get(MessageHeaders.CONTENT_TYPE)); + assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo(MimeTypeUtils.TEXT_PLAIN); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/SimpleMessageConverterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/SimpleMessageConverterTests.java index 78e68cb3461..b28fc94f26a 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/SimpleMessageConverterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/SimpleMessageConverterTests.java @@ -24,8 +24,7 @@ import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.MessageHeaderAccessor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for @@ -43,8 +42,8 @@ public class SimpleMessageConverterTests { MessageHeaders headers = new MessageHeaders(Collections.singletonMap("foo", "bar")); Message message = this.converter.toMessage("payload", headers); - assertEquals("payload", message.getPayload()); - assertEquals("bar", message.getHeaders().get("foo")); + assertThat(message.getPayload()).isEqualTo("payload"); + assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -56,8 +55,8 @@ public class SimpleMessageConverterTests { Message message = this.converter.toMessage("payload", headers); - assertEquals("payload", message.getPayload()); - assertSame(headers, message.getHeaders()); - assertEquals("bar", message.getHeaders().get("foo")); + assertThat(message.getPayload()).isEqualTo("payload"); + assertThat(message.getHeaders()).isSameAs(headers); + assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/StringMessageConverterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/StringMessageConverterTests.java index c0a6edc3de0..d151c237e6c 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/StringMessageConverterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/StringMessageConverterTests.java @@ -28,8 +28,7 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link org.springframework.messaging.converter.StringMessageConverter}. @@ -45,20 +44,20 @@ public class StringMessageConverterTests { public void fromByteArrayMessage() { Message message = MessageBuilder.withPayload( "ABC".getBytes()).setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build(); - assertEquals("ABC", this.converter.fromMessage(message, String.class)); + assertThat(this.converter.fromMessage(message, String.class)).isEqualTo("ABC"); } @Test public void fromStringMessage() { Message message = MessageBuilder.withPayload( "ABC").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build(); - assertEquals("ABC", this.converter.fromMessage(message, String.class)); + assertThat(this.converter.fromMessage(message, String.class)).isEqualTo("ABC"); } @Test public void fromMessageNoContentTypeHeader() { Message message = MessageBuilder.withPayload("ABC".getBytes()).build(); - assertEquals("ABC", this.converter.fromMessage(message, String.class)); + assertThat(this.converter.fromMessage(message, String.class)).isEqualTo("ABC"); } @Test @@ -66,27 +65,27 @@ public class StringMessageConverterTests { String payload = "H\u00e9llo W\u00f6rld"; Message message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.ISO_8859_1)) .setHeader(MessageHeaders.CONTENT_TYPE, new MimeType("text", "plain", StandardCharsets.ISO_8859_1)).build(); - assertEquals(payload, this.converter.fromMessage(message, String.class)); + assertThat(this.converter.fromMessage(message, String.class)).isEqualTo(payload); } @Test public void fromMessageDefaultCharset() { String payload = "H\u00e9llo W\u00f6rld"; Message message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); - assertEquals(payload, this.converter.fromMessage(message, String.class)); + assertThat(this.converter.fromMessage(message, String.class)).isEqualTo(payload); } @Test public void fromMessageTargetClassNotSupported() { Message message = MessageBuilder.withPayload("ABC".getBytes()).build(); - assertNull(this.converter.fromMessage(message, Integer.class)); + assertThat(this.converter.fromMessage(message, Integer.class)).isNull(); } @Test public void fromMessageByteArray() { Message message = MessageBuilder.withPayload( "ABC".getBytes()).setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build(); - assertEquals("ABC", this.converter.fromMessage(message, String.class)); + assertThat(this.converter.fromMessage(message, String.class)).isEqualTo("ABC"); } @Test @@ -96,7 +95,7 @@ public class StringMessageConverterTests { MessageHeaders headers = new MessageHeaders(map); Message message = this.converter.toMessage("ABC", headers); - assertEquals("ABC", new String(((byte[]) message.getPayload()))); + assertThat(new String(((byte[]) message.getPayload()))).isEqualTo("ABC"); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/core/CachingDestinationResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/core/CachingDestinationResolverTests.java index 6f8d1d4ecae..60f20e0c7af 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/core/CachingDestinationResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/core/CachingDestinationResolverTests.java @@ -18,8 +18,8 @@ package org.springframework.messaging.core; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -42,10 +42,10 @@ public class CachingDestinationResolverTests { given(resolver.resolveDestination("abcd")).willReturn("dcba"); given(resolver.resolveDestination("1234")).willReturn("4321"); - assertEquals("dcba", resolverProxy.resolveDestination("abcd")); - assertEquals("4321", resolverProxy.resolveDestination("1234")); - assertEquals("4321", resolverProxy.resolveDestination("1234")); - assertEquals("dcba", resolverProxy.resolveDestination("abcd")); + assertThat(resolverProxy.resolveDestination("abcd")).isEqualTo("dcba"); + assertThat(resolverProxy.resolveDestination("1234")).isEqualTo("4321"); + assertThat(resolverProxy.resolveDestination("1234")).isEqualTo("4321"); + assertThat(resolverProxy.resolveDestination("abcd")).isEqualTo("dcba"); verify(resolver, times(1)).resolveDestination("abcd"); verify(resolver, times(1)).resolveDestination("1234"); diff --git a/spring-messaging/src/test/java/org/springframework/messaging/core/DestinationResolvingMessagingTemplateTests.java b/spring-messaging/src/test/java/org/springframework/messaging/core/DestinationResolvingMessagingTemplateTests.java index a53e6e49dfb..e6f9186a651 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/core/DestinationResolvingMessagingTemplateTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/core/DestinationResolvingMessagingTemplateTests.java @@ -28,10 +28,8 @@ import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.ExecutorSubscribableChannel; import org.springframework.messaging.support.GenericMessage; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; /** * Unit tests for {@link AbstractDestinationResolvingMessagingTemplate}. @@ -71,8 +69,8 @@ public class DestinationResolvingMessagingTemplateTests { Message message = new GenericMessage("payload"); this.template.send("myChannel", message); - assertSame(this.myChannel, this.template.messageChannel); - assertSame(message, this.template.message); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); + assertThat(this.template.message).isSameAs(message); } @Test @@ -86,44 +84,44 @@ public class DestinationResolvingMessagingTemplateTests { public void convertAndSendPayload() { this.template.convertAndSend("myChannel", "payload"); - assertSame(this.myChannel, this.template.messageChannel); - assertNotNull(this.template.message); - assertSame("payload", this.template.message.getPayload()); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); + assertThat(this.template.message).isNotNull(); + assertThat(this.template.message.getPayload()).isSameAs("payload"); } @Test public void convertAndSendPayloadAndHeaders() { this.template.convertAndSend("myChannel", "payload", this.headers); - assertSame(this.myChannel, this.template.messageChannel); - assertNotNull(this.template.message); - assertEquals("value", this.template.message.getHeaders().get("key")); - assertEquals("payload", this.template.message.getPayload()); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); + assertThat(this.template.message).isNotNull(); + assertThat(this.template.message.getHeaders().get("key")).isEqualTo("value"); + assertThat(this.template.message.getPayload()).isEqualTo("payload"); } @Test public void convertAndSendPayloadWithPostProcessor() { this.template.convertAndSend("myChannel", "payload", this.postProcessor); - assertSame(this.myChannel, this.template.messageChannel); - assertNotNull(this.template.message); - assertEquals("payload", this.template.message.getPayload()); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); + assertThat(this.template.message).isNotNull(); + assertThat(this.template.message.getPayload()).isEqualTo("payload"); - assertNotNull(this.postProcessor.getMessage()); - assertSame(this.postProcessor.getMessage(), this.template.message); + assertThat(this.postProcessor.getMessage()).isNotNull(); + assertThat(this.template.message).isSameAs(this.postProcessor.getMessage()); } @Test public void convertAndSendPayloadAndHeadersWithPostProcessor() { this.template.convertAndSend("myChannel", "payload", this.headers, this.postProcessor); - assertSame(this.myChannel, this.template.messageChannel); - assertNotNull(this.template.message); - assertEquals("value", this.template.message.getHeaders().get("key")); - assertEquals("payload", this.template.message.getPayload()); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); + assertThat(this.template.message).isNotNull(); + assertThat(this.template.message.getHeaders().get("key")).isEqualTo("value"); + assertThat(this.template.message.getPayload()).isEqualTo("payload"); - assertNotNull(this.postProcessor.getMessage()); - assertSame(this.postProcessor.getMessage(), this.template.message); + assertThat(this.postProcessor.getMessage()).isNotNull(); + assertThat(this.template.message).isSameAs(this.postProcessor.getMessage()); } @Test @@ -132,8 +130,8 @@ public class DestinationResolvingMessagingTemplateTests { this.template.setReceiveMessage(expected); Message actual = this.template.receive("myChannel"); - assertSame(expected, actual); - assertSame(this.myChannel, this.template.messageChannel); + assertThat(actual).isSameAs(expected); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); } @Test @@ -142,8 +140,8 @@ public class DestinationResolvingMessagingTemplateTests { this.template.setReceiveMessage(expected); String payload = this.template.receiveAndConvert("myChannel", String.class); - assertEquals("payload", payload); - assertSame(this.myChannel, this.template.messageChannel); + assertThat(payload).isEqualTo("payload"); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); } @Test @@ -153,9 +151,9 @@ public class DestinationResolvingMessagingTemplateTests { this.template.setReceiveMessage(responseMessage); Message actual = this.template.sendAndReceive("myChannel", requestMessage); - assertEquals(requestMessage, this.template.message); - assertSame(responseMessage, actual); - assertSame(this.myChannel, this.template.messageChannel); + assertThat(this.template.message).isEqualTo(requestMessage); + assertThat(actual).isSameAs(responseMessage); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); } @Test @@ -164,9 +162,9 @@ public class DestinationResolvingMessagingTemplateTests { this.template.setReceiveMessage(responseMessage); String actual = this.template.convertSendAndReceive("myChannel", "request", String.class); - assertEquals("request", this.template.message.getPayload()); - assertSame("response", actual); - assertSame(this.myChannel, this.template.messageChannel); + assertThat(this.template.message.getPayload()).isEqualTo("request"); + assertThat(actual).isSameAs("response"); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); } @Test @@ -175,10 +173,10 @@ public class DestinationResolvingMessagingTemplateTests { this.template.setReceiveMessage(responseMessage); String actual = this.template.convertSendAndReceive("myChannel", "request", this.headers, String.class); - assertEquals("value", this.template.message.getHeaders().get("key")); - assertEquals("request", this.template.message.getPayload()); - assertSame("response", actual); - assertSame(this.myChannel, this.template.messageChannel); + assertThat(this.template.message.getHeaders().get("key")).isEqualTo("value"); + assertThat(this.template.message.getPayload()).isEqualTo("request"); + assertThat(actual).isSameAs("response"); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); } @Test @@ -187,10 +185,10 @@ public class DestinationResolvingMessagingTemplateTests { this.template.setReceiveMessage(responseMessage); String actual = this.template.convertSendAndReceive("myChannel", "request", String.class, this.postProcessor); - assertEquals("request", this.template.message.getPayload()); - assertSame("request", this.postProcessor.getMessage().getPayload()); - assertSame("response", actual); - assertSame(this.myChannel, this.template.messageChannel); + assertThat(this.template.message.getPayload()).isEqualTo("request"); + assertThat(this.postProcessor.getMessage().getPayload()).isSameAs("request"); + assertThat(actual).isSameAs("response"); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); } @Test @@ -200,11 +198,11 @@ public class DestinationResolvingMessagingTemplateTests { String actual = this.template.convertSendAndReceive("myChannel", "request", this.headers, String.class, this.postProcessor); - assertEquals("value", this.template.message.getHeaders().get("key")); - assertEquals("request", this.template.message.getPayload()); - assertSame("request", this.postProcessor.getMessage().getPayload()); - assertSame("response", actual); - assertSame(this.myChannel, this.template.messageChannel); + assertThat(this.template.message.getHeaders().get("key")).isEqualTo("value"); + assertThat(this.template.message.getPayload()).isEqualTo("request"); + assertThat(this.postProcessor.getMessage().getPayload()).isSameAs("request"); + assertThat(actual).isSameAs("response"); + assertThat(this.template.messageChannel).isSameAs(this.myChannel); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/core/GenericMessagingTemplateTests.java b/spring-messaging/src/test/java/org/springframework/messaging/core/GenericMessagingTemplateTests.java index 52ccdf1da20..ff77007911a 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/core/GenericMessagingTemplateTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/core/GenericMessagingTemplateTests.java @@ -38,12 +38,7 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; @@ -90,9 +85,9 @@ public class GenericMessagingTemplateTests { .build(); this.template.send(channel, message); verify(channel).send(any(Message.class), eq(30_000L)); - assertNotNull(sent.get()); - assertFalse(sent.get().getHeaders().containsKey(GenericMessagingTemplate.DEFAULT_SEND_TIMEOUT_HEADER)); - assertFalse(sent.get().getHeaders().containsKey(GenericMessagingTemplate.DEFAULT_RECEIVE_TIMEOUT_HEADER)); + assertThat(sent.get()).isNotNull(); + assertThat(sent.get().getHeaders().containsKey(GenericMessagingTemplate.DEFAULT_SEND_TIMEOUT_HEADER)).isFalse(); + assertThat(sent.get().getHeaders().containsKey(GenericMessagingTemplate.DEFAULT_RECEIVE_TIMEOUT_HEADER)).isFalse(); } @Test @@ -109,9 +104,9 @@ public class GenericMessagingTemplateTests { accessor.setHeader(GenericMessagingTemplate.DEFAULT_SEND_TIMEOUT_HEADER, 30_000L); this.template.send(channel, message); verify(channel).send(any(Message.class), eq(30_000L)); - assertNotNull(sent.get()); - assertFalse(sent.get().getHeaders().containsKey(GenericMessagingTemplate.DEFAULT_SEND_TIMEOUT_HEADER)); - assertFalse(sent.get().getHeaders().containsKey(GenericMessagingTemplate.DEFAULT_RECEIVE_TIMEOUT_HEADER)); + assertThat(sent.get()).isNotNull(); + assertThat(sent.get().getHeaders().containsKey(GenericMessagingTemplate.DEFAULT_SEND_TIMEOUT_HEADER)).isFalse(); + assertThat(sent.get().getHeaders().containsKey(GenericMessagingTemplate.DEFAULT_RECEIVE_TIMEOUT_HEADER)).isFalse(); } @Test @@ -126,7 +121,7 @@ public class GenericMessagingTemplateTests { }); String actual = this.template.convertSendAndReceive(channel, "request", String.class); - assertEquals("response", actual); + assertThat(actual).isEqualTo("response"); } @Test @@ -145,8 +140,8 @@ public class GenericMessagingTemplateTests { return true; }).given(channel).send(any(Message.class), anyLong()); - assertNull(this.template.convertSendAndReceive(channel, "request", String.class)); - assertTrue(latch.await(10_000, TimeUnit.MILLISECONDS)); + assertThat(this.template.convertSendAndReceive(channel, "request", String.class)).isNull(); + assertThat(latch.await(10_000, TimeUnit.MILLISECONDS)).isTrue(); Throwable ex = failure.get(); if (ex != null) { @@ -175,8 +170,8 @@ public class GenericMessagingTemplateTests { .setHeader(GenericMessagingTemplate.DEFAULT_SEND_TIMEOUT_HEADER, 30_000L) .setHeader(GenericMessagingTemplate.DEFAULT_RECEIVE_TIMEOUT_HEADER, 1L) .build(); - assertNull(this.template.sendAndReceive(channel, message)); - assertTrue(latch.await(10_000, TimeUnit.MILLISECONDS)); + assertThat(this.template.sendAndReceive(channel, message)).isNull(); + assertThat(latch.await(10_000, TimeUnit.MILLISECONDS)).isTrue(); Throwable ex = failure.get(); if (ex != null) { @@ -207,8 +202,8 @@ public class GenericMessagingTemplateTests { .setHeader("sto", 30_000L) .setHeader("rto", 1L) .build(); - assertNull(this.template.sendAndReceive(channel, message)); - assertTrue(latch.await(10_000, TimeUnit.MILLISECONDS)); + assertThat(this.template.sendAndReceive(channel, message)).isNull(); + assertThat(latch.await(10_000, TimeUnit.MILLISECONDS)).isTrue(); Throwable ex = failure.get(); if (ex != null) { @@ -254,8 +249,8 @@ public class GenericMessagingTemplateTests { List> messages = this.messageChannel.getMessages(); Message message = messages.get(0); - assertSame(headers, message.getHeaders()); - assertFalse(accessor.isMutable()); + assertThat(message.getHeaders()).isSameAs(headers); + assertThat(accessor.isMutable()).isFalse(); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageReceivingTemplateTests.java b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageReceivingTemplateTests.java index 58c4198ad31..6ef71bd4130 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageReceivingTemplateTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageReceivingTemplateTests.java @@ -27,11 +27,9 @@ import org.springframework.messaging.converter.GenericMessageConverter; import org.springframework.messaging.converter.MessageConversionException; import org.springframework.messaging.support.GenericMessage; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Unit tests for receiving operations in {@link AbstractMessagingTemplate}. @@ -56,8 +54,8 @@ public class MessageReceivingTemplateTests { this.template.setReceiveMessage(expected); Message actual = this.template.receive(); - assertEquals("home", this.template.destination); - assertSame(expected, actual); + assertThat(this.template.destination).isEqualTo("home"); + assertThat(actual).isSameAs(expected); } @Test @@ -72,8 +70,8 @@ public class MessageReceivingTemplateTests { this.template.setReceiveMessage(expected); Message actual = this.template.receive("somewhere"); - assertEquals("somewhere", this.template.destination); - assertSame(expected, actual); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(actual).isSameAs(expected); } @Test @@ -83,8 +81,8 @@ public class MessageReceivingTemplateTests { this.template.setReceiveMessage(expected); String payload = this.template.receiveAndConvert(String.class); - assertEquals("home", this.template.destination); - assertSame("payload", payload); + assertThat(this.template.destination).isEqualTo("home"); + assertThat(payload).isSameAs("payload"); } @Test @@ -93,8 +91,8 @@ public class MessageReceivingTemplateTests { this.template.setReceiveMessage(expected); String payload = this.template.receiveAndConvert("somewhere", String.class); - assertEquals("somewhere", this.template.destination); - assertSame("payload", payload); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(payload).isSameAs("payload"); } @Test @@ -118,8 +116,8 @@ public class MessageReceivingTemplateTests { this.template.receiveAndConvert(Writer.class); } catch (MessageConversionException ex) { - assertTrue("Invalid exception message '" + ex.getMessage() + "'", ex.getMessage().contains("payload")); - assertSame(expected, ex.getFailedMessage()); + assertThat(ex.getMessage().contains("payload")).as("Invalid exception message '" + ex.getMessage() + "'").isTrue(); + assertThat(ex.getFailedMessage()).isSameAs(expected); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageRequestReplyTemplateTests.java b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageRequestReplyTemplateTests.java index 9cf965ab30c..76679e17ee8 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageRequestReplyTemplateTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageRequestReplyTemplateTests.java @@ -25,9 +25,8 @@ import org.junit.Test; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; /** * Unit tests for request and reply operations in {@link AbstractMessagingTemplate}. @@ -61,9 +60,9 @@ public class MessageRequestReplyTemplateTests { this.template.setReceiveMessage(responseMessage); Message actual = this.template.sendAndReceive(requestMessage); - assertEquals("home", this.template.destination); - assertSame(requestMessage, this.template.requestMessage); - assertSame(responseMessage, actual); + assertThat(this.template.destination).isEqualTo("home"); + assertThat(this.template.requestMessage).isSameAs(requestMessage); + assertThat(actual).isSameAs(responseMessage); } @Test @@ -79,9 +78,9 @@ public class MessageRequestReplyTemplateTests { this.template.setReceiveMessage(responseMessage); Message actual = this.template.sendAndReceive("somewhere", requestMessage); - assertEquals("somewhere", this.template.destination); - assertSame(requestMessage, this.template.requestMessage); - assertSame(responseMessage, actual); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(this.template.requestMessage).isSameAs(requestMessage); + assertThat(actual).isSameAs(responseMessage); } @Test @@ -91,9 +90,9 @@ public class MessageRequestReplyTemplateTests { this.template.setReceiveMessage(responseMessage); String response = this.template.convertSendAndReceive("request", String.class); - assertEquals("home", this.template.destination); - assertSame("request", this.template.requestMessage.getPayload()); - assertSame("response", response); + assertThat(this.template.destination).isEqualTo("home"); + assertThat(this.template.requestMessage.getPayload()).isSameAs("request"); + assertThat(response).isSameAs("response"); } @Test @@ -102,9 +101,9 @@ public class MessageRequestReplyTemplateTests { this.template.setReceiveMessage(responseMessage); String response = this.template.convertSendAndReceive("somewhere", "request", String.class); - assertEquals("somewhere", this.template.destination); - assertSame("request", this.template.requestMessage.getPayload()); - assertSame("response", response); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(this.template.requestMessage.getPayload()).isSameAs("request"); + assertThat(response).isSameAs("response"); } @Test @@ -113,10 +112,10 @@ public class MessageRequestReplyTemplateTests { this.template.setReceiveMessage(responseMessage); String response = this.template.convertSendAndReceive("somewhere", "request", this.headers, String.class); - assertEquals("somewhere", this.template.destination); - assertEquals("value", this.template.requestMessage.getHeaders().get("key")); - assertSame("request", this.template.requestMessage.getPayload()); - assertSame("response", response); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(this.template.requestMessage.getHeaders().get("key")).isEqualTo("value"); + assertThat(this.template.requestMessage.getPayload()).isSameAs("request"); + assertThat(response).isSameAs("response"); } @Test @@ -126,10 +125,10 @@ public class MessageRequestReplyTemplateTests { this.template.setReceiveMessage(responseMessage); String response = this.template.convertSendAndReceive("request", String.class, this.postProcessor); - assertEquals("home", this.template.destination); - assertSame("request", this.template.requestMessage.getPayload()); - assertSame("response", response); - assertSame(this.postProcessor.getMessage(), this.template.requestMessage); + assertThat(this.template.destination).isEqualTo("home"); + assertThat(this.template.requestMessage.getPayload()).isSameAs("request"); + assertThat(response).isSameAs("response"); + assertThat(this.template.requestMessage).isSameAs(this.postProcessor.getMessage()); } @Test @@ -138,10 +137,10 @@ public class MessageRequestReplyTemplateTests { this.template.setReceiveMessage(responseMessage); String response = this.template.convertSendAndReceive("somewhere", "request", String.class, this.postProcessor); - assertEquals("somewhere", this.template.destination); - assertSame("request", this.template.requestMessage.getPayload()); - assertSame("response", response); - assertSame(this.postProcessor.getMessage(), this.template.requestMessage); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(this.template.requestMessage.getPayload()).isSameAs("request"); + assertThat(response).isSameAs("response"); + assertThat(this.template.requestMessage).isSameAs(this.postProcessor.getMessage()); } @Test @@ -151,11 +150,11 @@ public class MessageRequestReplyTemplateTests { String response = this.template.convertSendAndReceive("somewhere", "request", this.headers, String.class, this.postProcessor); - assertEquals("somewhere", this.template.destination); - assertEquals("value", this.template.requestMessage.getHeaders().get("key")); - assertSame("request", this.template.requestMessage.getPayload()); - assertSame("response", response); - assertSame(this.postProcessor.getMessage(), this.template.requestMessage); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(this.template.requestMessage.getHeaders().get("key")).isEqualTo("value"); + assertThat(this.template.requestMessage.getPayload()).isSameAs("request"); + assertThat(response).isSameAs("response"); + assertThat(this.template.requestMessage).isSameAs(this.postProcessor.getMessage()); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageSendingTemplateTests.java b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageSendingTemplateTests.java index b79e5792831..ab7b2ee765e 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/core/MessageSendingTemplateTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/core/MessageSendingTemplateTests.java @@ -36,11 +36,9 @@ import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; /** * Unit tests for {@link AbstractMessageSendingTemplate}. @@ -70,8 +68,8 @@ public class MessageSendingTemplateTests { this.template.setDefaultDestination("home"); this.template.send(message); - assertEquals("home", this.template.destination); - assertSame(message, this.template.message); + assertThat(this.template.destination).isEqualTo("home"); + assertThat(this.template.message).isSameAs(message); } @Test @@ -79,8 +77,8 @@ public class MessageSendingTemplateTests { Message message = new GenericMessage("payload"); this.template.send("somewhere", message); - assertEquals("somewhere", this.template.destination); - assertSame(message, this.template.message); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(this.template.message).isSameAs(message); } @Test @@ -94,13 +92,13 @@ public class MessageSendingTemplateTests { public void convertAndSend() { this.template.convertAndSend("somewhere", "payload", headers, this.postProcessor); - assertEquals("somewhere", this.template.destination); - assertNotNull(this.template.message); - assertEquals("value", this.template.message.getHeaders().get("key")); - assertEquals("payload", this.template.message.getPayload()); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(this.template.message).isNotNull(); + assertThat(this.template.message.getHeaders().get("key")).isEqualTo("value"); + assertThat(this.template.message.getPayload()).isEqualTo("payload"); - assertNotNull(this.postProcessor.getMessage()); - assertSame(this.template.message, this.postProcessor.getMessage()); + assertThat(this.postProcessor.getMessage()).isNotNull(); + assertThat(this.postProcessor.getMessage()).isSameAs(this.template.message); } @Test @@ -108,30 +106,30 @@ public class MessageSendingTemplateTests { this.template.setDefaultDestination("home"); this.template.convertAndSend("payload"); - assertEquals("home", this.template.destination); - assertNotNull(this.template.message); - assertEquals("expected 'id' and 'timestamp' headers only", 2, this.template.message.getHeaders().size()); - assertEquals("payload", this.template.message.getPayload()); + assertThat(this.template.destination).isEqualTo("home"); + assertThat(this.template.message).isNotNull(); + assertThat(this.template.message.getHeaders().size()).as("expected 'id' and 'timestamp' headers only").isEqualTo(2); + assertThat(this.template.message.getPayload()).isEqualTo("payload"); } @Test public void convertAndSendPayloadToDestination() { this.template.convertAndSend("somewhere", "payload"); - assertEquals("somewhere", this.template.destination); - assertNotNull(this.template.message); - assertEquals("expected 'id' and 'timestamp' headers only", 2, this.template.message.getHeaders().size()); - assertEquals("payload", this.template.message.getPayload()); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(this.template.message).isNotNull(); + assertThat(this.template.message.getHeaders().size()).as("expected 'id' and 'timestamp' headers only").isEqualTo(2); + assertThat(this.template.message.getPayload()).isEqualTo("payload"); } @Test public void convertAndSendPayloadAndHeadersToDestination() { this.template.convertAndSend("somewhere", "payload", headers); - assertEquals("somewhere", this.template.destination); - assertNotNull(this.template.message); - assertEquals("value", this.template.message.getHeaders().get("key")); - assertEquals("payload", this.template.message.getPayload()); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(this.template.message).isNotNull(); + assertThat(this.template.message.getHeaders().get("key")).isEqualTo("value"); + assertThat(this.template.message.getPayload()).isEqualTo("payload"); } @Test @@ -145,9 +143,9 @@ public class MessageSendingTemplateTests { this.template.convertAndSend("somewhere", "payload", messageHeaders); MessageHeaders actual = this.template.message.getHeaders(); - assertSame(messageHeaders, actual); - assertEquals(new MimeType("text", "plain", StandardCharsets.UTF_8), actual.get(MessageHeaders.CONTENT_TYPE)); - assertEquals("bar", actual.get("foo")); + assertThat(actual).isSameAs(messageHeaders); + assertThat(actual.get(MessageHeaders.CONTENT_TYPE)).isEqualTo(new MimeType("text", "plain", StandardCharsets.UTF_8)); + assertThat(actual.get("foo")).isEqualTo("bar"); } @Test @@ -155,26 +153,26 @@ public class MessageSendingTemplateTests { this.template.setDefaultDestination("home"); this.template.convertAndSend((Object) "payload", this.postProcessor); - assertEquals("home", this.template.destination); - assertNotNull(this.template.message); - assertEquals("expected 'id' and 'timestamp' headers only", 2, this.template.message.getHeaders().size()); - assertEquals("payload", this.template.message.getPayload()); + assertThat(this.template.destination).isEqualTo("home"); + assertThat(this.template.message).isNotNull(); + assertThat(this.template.message.getHeaders().size()).as("expected 'id' and 'timestamp' headers only").isEqualTo(2); + assertThat(this.template.message.getPayload()).isEqualTo("payload"); - assertNotNull(this.postProcessor.getMessage()); - assertSame(this.template.message, this.postProcessor.getMessage()); + assertThat(this.postProcessor.getMessage()).isNotNull(); + assertThat(this.postProcessor.getMessage()).isSameAs(this.template.message); } @Test public void convertAndSendPayloadWithPostProcessorToDestination() { this.template.convertAndSend("somewhere", "payload", this.postProcessor); - assertEquals("somewhere", this.template.destination); - assertNotNull(this.template.message); - assertEquals("expected 'id' and 'timestamp' headers only", 2, this.template.message.getHeaders().size()); - assertEquals("payload", this.template.message.getPayload()); + assertThat(this.template.destination).isEqualTo("somewhere"); + assertThat(this.template.message).isNotNull(); + assertThat(this.template.message.getHeaders().size()).as("expected 'id' and 'timestamp' headers only").isEqualTo(2); + assertThat(this.template.message.getPayload()).isEqualTo("payload"); - assertNotNull(this.postProcessor.getMessage()); - assertSame(this.template.message, this.postProcessor.getMessage()); + assertThat(this.postProcessor.getMessage()).isNotNull(); + assertThat(this.postProcessor.getMessage()).isSameAs(this.template.message); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/DestinationPatternsMessageConditionTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/DestinationPatternsMessageConditionTests.java index 61420fbfe9e..41c7d9cf79e 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/DestinationPatternsMessageConditionTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/DestinationPatternsMessageConditionTests.java @@ -22,8 +22,7 @@ import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.AntPathMatcher; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link DestinationPatternsMessageCondition}. @@ -35,7 +34,7 @@ public class DestinationPatternsMessageConditionTests { @Test public void prependSlash() { DestinationPatternsMessageCondition c = condition("foo"); - assertEquals("/foo", c.getPatterns().iterator().next()); + assertThat(c.getPatterns().iterator().next()).isEqualTo("/foo"); } @Test @@ -43,8 +42,7 @@ public class DestinationPatternsMessageConditionTests { DestinationPatternsMessageCondition c = new DestinationPatternsMessageCondition(new String[] {"foo"}, new AntPathMatcher(".")); - assertEquals("Pre-pending should be disabled when not using '/' as path separator", - "foo", c.getPatterns().iterator().next()); + assertThat(c.getPatterns().iterator().next()).as("Pre-pending should be disabled when not using '/' as path separator").isEqualTo("foo"); } // SPR-8255 @@ -52,7 +50,7 @@ public class DestinationPatternsMessageConditionTests { @Test public void prependNonEmptyPatternsOnly() { DestinationPatternsMessageCondition c = condition(""); - assertEquals("", c.getPatterns().iterator().next()); + assertThat(c.getPatterns().iterator().next()).isEqualTo(""); } @Test @@ -60,7 +58,7 @@ public class DestinationPatternsMessageConditionTests { DestinationPatternsMessageCondition c1 = condition(); DestinationPatternsMessageCondition c2 = condition(); - assertEquals(condition(""), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(condition("")); } @Test @@ -68,12 +66,12 @@ public class DestinationPatternsMessageConditionTests { DestinationPatternsMessageCondition c1 = condition("/type1", "/type2"); DestinationPatternsMessageCondition c2 = condition(); - assertEquals(condition("/type1", "/type2"), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(condition("/type1", "/type2")); c1 = condition(); c2 = condition("/method1", "/method2"); - assertEquals(condition("/method1", "/method2"), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(condition("/method1", "/method2")); } @Test @@ -81,8 +79,8 @@ public class DestinationPatternsMessageConditionTests { DestinationPatternsMessageCondition c1 = condition("/t1", "/t2"); DestinationPatternsMessageCondition c2 = condition("/m1", "/m2"); - assertEquals(new DestinationPatternsMessageCondition( - "/t1/m1", "/t1/m2", "/t2/m1", "/t2/m2"), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(new DestinationPatternsMessageCondition( + "/t1/m1", "/t1/m2", "/t2/m1", "/t2/m2")); } @Test @@ -90,7 +88,7 @@ public class DestinationPatternsMessageConditionTests { DestinationPatternsMessageCondition condition = condition("/foo"); DestinationPatternsMessageCondition match = condition.getMatchingCondition(messageTo("/foo")); - assertNotNull(match); + assertThat(match).isNotNull(); } @Test @@ -98,7 +96,7 @@ public class DestinationPatternsMessageConditionTests { DestinationPatternsMessageCondition condition = condition("/foo/*"); DestinationPatternsMessageCondition match = condition.getMatchingCondition(messageTo("/foo/bar")); - assertNotNull(match); + assertThat(match).isNotNull(); } @Test @@ -107,7 +105,7 @@ public class DestinationPatternsMessageConditionTests { DestinationPatternsMessageCondition match = condition.getMatchingCondition(messageTo("/foo/bar")); DestinationPatternsMessageCondition expected = condition("/foo/bar", "/foo/*", "/**"); - assertEquals(expected, match); + assertThat(match).isEqualTo(expected); } @Test @@ -115,7 +113,7 @@ public class DestinationPatternsMessageConditionTests { DestinationPatternsMessageCondition c1 = condition("/foo*"); DestinationPatternsMessageCondition c2 = condition("/foo*"); - assertEquals(0, c1.compareTo(c2, messageTo("/foo"))); + assertThat(c1.compareTo(c2, messageTo("/foo"))).isEqualTo(0); } @Test @@ -123,7 +121,7 @@ public class DestinationPatternsMessageConditionTests { DestinationPatternsMessageCondition c1 = condition("/fo*"); DestinationPatternsMessageCondition c2 = condition("/foo"); - assertEquals(1, c1.compareTo(c2, messageTo("/foo"))); + assertThat(c1.compareTo(c2, messageTo("/foo"))).isEqualTo(1); } @Test @@ -136,7 +134,7 @@ public class DestinationPatternsMessageConditionTests { DestinationPatternsMessageCondition match1 = c1.getMatchingCondition(message); DestinationPatternsMessageCondition match2 = c2.getMatchingCondition(message); - assertEquals(1, match1.compareTo(match2, message)); + assertThat(match1.compareTo(match2, message)).isEqualTo(1); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/DestinationVariableMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/DestinationVariableMethodArgumentResolverTests.java index aa231e3b87a..97185f893a1 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/DestinationVariableMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/DestinationVariableMethodArgumentResolverTests.java @@ -30,10 +30,8 @@ import org.springframework.messaging.handler.annotation.DestinationVariable; import org.springframework.messaging.handler.invocation.ResolvableMethod; import org.springframework.messaging.support.MessageBuilder; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.springframework.messaging.handler.annotation.MessagingPredicates.destinationVar; /** @@ -51,8 +49,8 @@ public class DestinationVariableMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(resolver.supportsParameter(this.resolvable.annot(destinationVar().noValue()).arg())); - assertFalse(resolver.supportsParameter(this.resolvable.annotNotPresent(DestinationVariable.class).arg())); + assertThat(resolver.supportsParameter(this.resolvable.annot(destinationVar().noValue()).arg())).isTrue(); + assertThat(resolver.supportsParameter(this.resolvable.annotNotPresent(DestinationVariable.class).arg())).isFalse(); } @Test @@ -66,10 +64,10 @@ public class DestinationVariableMethodArgumentResolverTests { DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars).build(); Object result = resolveArgument(this.resolvable.annot(destinationVar().noValue()).arg(), message); - assertEquals("bar", result); + assertThat(result).isEqualTo("bar"); result = resolveArgument(this.resolvable.annot(destinationVar("name")).arg(), message); - assertEquals("value", result); + assertThat(result).isEqualTo("value"); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeaderMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeaderMethodArgumentResolverTests.java index efc06f2378a..e4c62ac40e9 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeaderMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeaderMethodArgumentResolverTests.java @@ -34,10 +34,8 @@ import org.springframework.messaging.handler.invocation.ResolvableMethod; import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.NativeMessageHeaderAccessor; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.springframework.messaging.handler.annotation.MessagingPredicates.header; import static org.springframework.messaging.handler.annotation.MessagingPredicates.headerPlain; @@ -62,15 +60,15 @@ public class HeaderMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter(this.resolvable.annot(headerPlain()).arg())); - assertFalse(this.resolver.supportsParameter(this.resolvable.annotNotPresent(Header.class).arg())); + assertThat(this.resolver.supportsParameter(this.resolvable.annot(headerPlain()).arg())).isTrue(); + assertThat(this.resolver.supportsParameter(this.resolvable.annotNotPresent(Header.class).arg())).isFalse(); } @Test public void resolveArgument() { Message message = MessageBuilder.withPayload(new byte[0]).setHeader("param1", "foo").build(); Object result = resolveArgument(this.resolvable.annot(headerPlain()).arg(), message); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); } @Test // SPR-11326 @@ -78,7 +76,7 @@ public class HeaderMethodArgumentResolverTests { TestMessageHeaderAccessor headers = new TestMessageHeaderAccessor(); headers.setNativeHeader("param1", "foo"); Message message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); - assertEquals("foo", resolveArgument(this.resolvable.annot(headerPlain()).arg(), message)); + assertThat(this.resolveArgument(this.resolvable.annot(headerPlain()).arg(), message)).isEqualTo("foo"); } @Test @@ -88,11 +86,11 @@ public class HeaderMethodArgumentResolverTests { headers.setNativeHeader("param1", "native-foo"); Message message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); - assertEquals("foo", resolveArgument( - this.resolvable.annot(headerPlain()).arg(), message)); + assertThat(this.resolveArgument( + this.resolvable.annot(headerPlain()).arg(), message)).isEqualTo("foo"); - assertEquals("native-foo", resolveArgument( - this.resolvable.annot(header("nativeHeaders.param1")).arg(), message)); + assertThat(this.resolveArgument( + this.resolvable.annot(header("nativeHeaders.param1")).arg(), message)).isEqualTo("native-foo"); } @Test @@ -106,7 +104,7 @@ public class HeaderMethodArgumentResolverTests { public void resolveArgumentDefaultValue() { Message message = MessageBuilder.withPayload(new byte[0]).build(); Object result = resolveArgument(this.resolvable.annot(header("name", "bar")).arg(), message); - assertEquals("bar", result); + assertThat(result).isEqualTo("bar"); } @Test @@ -116,7 +114,7 @@ public class HeaderMethodArgumentResolverTests { Message message = MessageBuilder.withPayload(new byte[0]).build(); MethodParameter param = this.resolvable.annot(header("name", "#{systemProperties.systemProperty}")).arg(); Object result = resolveArgument(param, message); - assertEquals("sysbar", result); + assertThat(result).isEqualTo("sysbar"); } finally { System.clearProperty("systemProperty"); @@ -130,7 +128,7 @@ public class HeaderMethodArgumentResolverTests { Message message = MessageBuilder.withPayload(new byte[0]).setHeader("sysbar", "foo").build(); MethodParameter param = this.resolvable.annot(header("#{systemProperties.systemProperty}")).arg(); Object result = resolveArgument(param, message); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); } finally { System.clearProperty("systemProperty"); @@ -142,7 +140,7 @@ public class HeaderMethodArgumentResolverTests { Message message = MessageBuilder.withPayload("foo").setHeader("foo", "bar").build(); MethodParameter param = this.resolvable.annot(header("foo")).arg(Optional.class, String.class); Object result = resolveArgument(param, message); - assertEquals(Optional.of("bar"), result); + assertThat(result).isEqualTo(Optional.of("bar")); } @Test @@ -150,7 +148,7 @@ public class HeaderMethodArgumentResolverTests { Message message = MessageBuilder.withPayload("foo").build(); MethodParameter param = this.resolvable.annot(header("foo")).arg(Optional.class, String.class); Object result = resolveArgument(param, message); - assertEquals(Optional.empty(), result); + assertThat(result).isEqualTo(Optional.empty()); } @SuppressWarnings({"unchecked", "ConstantConditions"}) diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeadersMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeadersMethodArgumentResolverTests.java index 0c8ad4d2513..2eca6191a8d 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeadersMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/HeadersMethodArgumentResolverTests.java @@ -31,10 +31,8 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.messaging.support.NativeMessageHeaderAccessor; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Test fixture for {@link HeadersMethodArgumentResolver} tests. @@ -53,14 +51,14 @@ public class HeadersMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter( - this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class))); + assertThat(this.resolver.supportsParameter( + this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class))).isTrue(); - assertTrue(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaders.class))); - assertTrue(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaderAccessor.class))); - assertTrue(this.resolver.supportsParameter(this.resolvable.arg(TestMessageHeaderAccessor.class))); + assertThat(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaders.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaderAccessor.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.resolvable.arg(TestMessageHeaderAccessor.class))).isTrue(); - assertFalse(this.resolver.supportsParameter(this.resolvable.annotPresent(Headers.class).arg(String.class))); + assertThat(this.resolver.supportsParameter(this.resolvable.annotPresent(Headers.class).arg(String.class))).isFalse(); } @Test @@ -68,7 +66,7 @@ public class HeadersMethodArgumentResolverTests { public void resolveArgumentAnnotated() { MethodParameter param = this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class); Map headers = resolveArgument(param); - assertEquals("bar", headers.get("foo")); + assertThat(headers.get("foo")).isEqualTo("bar"); } @Test @@ -80,19 +78,19 @@ public class HeadersMethodArgumentResolverTests { @Test public void resolveArgumentMessageHeaders() { MessageHeaders headers = resolveArgument(this.resolvable.arg(MessageHeaders.class)); - assertEquals("bar", headers.get("foo")); + assertThat(headers.get("foo")).isEqualTo("bar"); } @Test public void resolveArgumentMessageHeaderAccessor() { MessageHeaderAccessor headers = resolveArgument(this.resolvable.arg(MessageHeaderAccessor.class)); - assertEquals("bar", headers.getHeader("foo")); + assertThat(headers.getHeader("foo")).isEqualTo("bar"); } @Test public void resolveArgumentMessageHeaderAccessorSubclass() { TestMessageHeaderAccessor headers = resolveArgument(this.resolvable.arg(TestMessageHeaderAccessor.class)); - assertEquals("bar", headers.getHeader("foo")); + assertThat(headers.getHeader("foo")).isEqualTo("bar"); } @SuppressWarnings({"unchecked", "ConstantConditions"}) diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/MessageMappingMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/MessageMappingMessageHandlerTests.java index be99afaf2df..6bf5ad3d6e6 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/MessageMappingMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/MessageMappingMessageHandlerTests.java @@ -51,7 +51,7 @@ import org.springframework.util.AntPathMatcher; import org.springframework.util.SimpleRouteMatcher; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link MessageMappingMessageHandler}. @@ -123,8 +123,7 @@ public class MessageMappingMessageHandlerTests { new SimpleRouteMatcher(new AntPathMatcher()).parseRoute("string"))); StepVerifier.create(initMesssageHandler().handleMessage(message)) - .expectErrorSatisfies(ex -> assertTrue("Actual: " + ex.getMessage(), - ex.getMessage().startsWith("Could not resolve method parameter at index 0"))) + .expectErrorSatisfies(ex -> assertThat(ex.getMessage().startsWith("Could not resolve method parameter at index 0")).as("Actual: " + ex.getMessage()).isTrue()) .verify(Duration.ofSeconds(5)); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/PayloadMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/PayloadMethodArgumentResolverTests.java index e99aeae07d6..06ea2f9e92c 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/PayloadMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/PayloadMethodArgumentResolverTests.java @@ -47,10 +47,7 @@ import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.validation.annotation.Validated; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** @@ -71,14 +68,14 @@ public class PayloadMethodArgumentResolverTests { boolean useDefaultResolution = true; PayloadMethodArgumentResolver resolver = createResolver(null, useDefaultResolution); - assertTrue(resolver.supportsParameter(this.testMethod.annotPresent(Payload.class).arg())); - assertTrue(resolver.supportsParameter(this.testMethod.annotNotPresent(Payload.class).arg(String.class))); + assertThat(resolver.supportsParameter(this.testMethod.annotPresent(Payload.class).arg())).isTrue(); + assertThat(resolver.supportsParameter(this.testMethod.annotNotPresent(Payload.class).arg(String.class))).isTrue(); useDefaultResolution = false; resolver = createResolver(null, useDefaultResolution); - assertTrue(resolver.supportsParameter(this.testMethod.annotPresent(Payload.class).arg())); - assertFalse(resolver.supportsParameter(this.testMethod.annotNotPresent(Payload.class).arg(String.class))); + assertThat(resolver.supportsParameter(this.testMethod.annotPresent(Payload.class).arg())).isTrue(); + assertThat(resolver.supportsParameter(this.testMethod.annotNotPresent(Payload.class).arg(String.class))).isFalse(); } @Test @@ -88,8 +85,8 @@ public class PayloadMethodArgumentResolverTests { StepVerifier.create(mono) .consumeErrorWith(ex -> { - assertEquals(MethodArgumentResolutionException.class, ex.getClass()); - assertTrue(ex.getMessage(), ex.getMessage().contains("Payload content is missing")); + assertThat(ex.getClass()).isEqualTo(MethodArgumentResolutionException.class); + assertThat(ex.getMessage().contains("Payload content is missing")).as(ex.getMessage()).isTrue(); }) .verify(); } @@ -97,7 +94,7 @@ public class PayloadMethodArgumentResolverTests { @Test public void emptyBodyWhenNotRequired() { MethodParameter param = this.testMethod.annotPresent(Payload.class).arg(); - assertNull(resolveValue(param, Mono.empty(), null)); + assertThat(this.resolveValue(param, Mono.empty(), null)).isNull(); } @Test @@ -107,7 +104,7 @@ public class PayloadMethodArgumentResolverTests { Mono mono = resolveValue(param, Mono.delay(Duration.ofMillis(10)).map(aLong -> toDataBuffer(body)), null); - assertEquals(body, mono.block()); + assertThat(mono.block()).isEqualTo(body); } @Test @@ -118,7 +115,7 @@ public class PayloadMethodArgumentResolverTests { Flux flux = resolveValue(param, Flux.fromIterable(body).delayElements(Duration.ofMillis(10)).map(this::toDataBuffer), null); - assertEquals(body, flux.collectList().block()); + assertThat(flux.collectList().block()).isEqualTo(body); } @Test @@ -127,7 +124,7 @@ public class PayloadMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotNotPresent(Payload.class).arg(String.class); Object value = resolveValue(param, Mono.just(toDataBuffer(body)), null); - assertEquals(body, value); + assertThat(value).isEqualTo(body); } @Test @@ -173,7 +170,7 @@ public class PayloadMethodArgumentResolverTests { Object value = result.block(Duration.ofSeconds(5)); if (value != null) { Class expectedType = param.getParameterType(); - assertTrue("Unexpected return value type: " + value, expectedType.isAssignableFrom(value.getClass())); + assertThat(expectedType.isAssignableFrom(value.getClass())).as("Unexpected return value type: " + value).isTrue(); } return (T) value; } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/AnnotationExceptionHandlerMethodResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/AnnotationExceptionHandlerMethodResolverTests.java index 42003a37124..d0173fed3c7 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/AnnotationExceptionHandlerMethodResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/AnnotationExceptionHandlerMethodResolverTests.java @@ -27,9 +27,8 @@ import org.springframework.messaging.handler.annotation.MessageExceptionHandler; import org.springframework.stereotype.Controller; import org.springframework.util.ClassUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * Test fixture for {@link AnnotationExceptionHandlerMethodResolver} tests. @@ -46,52 +45,52 @@ public class AnnotationExceptionHandlerMethodResolverTests { @Test public void resolveMethodFromAnnotation() { IOException exception = new IOException(); - assertEquals("handleIOException", this.resolver.resolveMethod(exception).getName()); + assertThat(this.resolver.resolveMethod(exception).getName()).isEqualTo("handleIOException"); } @Test public void resolveMethodFromArgument() { IllegalArgumentException exception = new IllegalArgumentException(); - assertEquals("handleIllegalArgumentException", this.resolver.resolveMethod(exception).getName()); + assertThat(this.resolver.resolveMethod(exception).getName()).isEqualTo("handleIllegalArgumentException"); } @Test public void resolveMethodFromArgumentWithErrorType() { AssertionError exception = new AssertionError(); - assertEquals("handleAssertionError", this.resolver.resolveMethod(new IllegalStateException(exception)).getName()); + assertThat(this.resolver.resolveMethod(new IllegalStateException(exception)).getName()).isEqualTo("handleAssertionError"); } @Test public void resolveMethodExceptionSubType() { IOException ioException = new FileNotFoundException(); - assertEquals("handleIOException", this.resolver.resolveMethod(ioException).getName()); + assertThat(this.resolver.resolveMethod(ioException).getName()).isEqualTo("handleIOException"); SocketException bindException = new BindException(); - assertEquals("handleSocketException", this.resolver.resolveMethod(bindException).getName()); + assertThat(this.resolver.resolveMethod(bindException).getName()).isEqualTo("handleSocketException"); } @Test public void resolveMethodBestMatch() { SocketException exception = new SocketException(); - assertEquals("handleSocketException", this.resolver.resolveMethod(exception).getName()); + assertThat(this.resolver.resolveMethod(exception).getName()).isEqualTo("handleSocketException"); } @Test public void resolveMethodNoMatch() { Exception exception = new Exception(); - assertNull("1st lookup", this.resolver.resolveMethod(exception)); - assertNull("2nd lookup from cache", this.resolver.resolveMethod(exception)); + assertThat(this.resolver.resolveMethod(exception)).as("1st lookup").isNull(); + assertThat(this.resolver.resolveMethod(exception)).as("2nd lookup from cache").isNull(); } @Test public void resolveMethodInherited() { IOException exception = new IOException(); - assertEquals("handleIOException", this.resolver.resolveMethod(exception).getName()); + assertThat(this.resolver.resolveMethod(exception).getName()).isEqualTo("handleIOException"); } @Test public void resolveMethodAgainstCause() { IllegalStateException exception = new IllegalStateException(new IOException()); - assertEquals("handleIOException", this.resolver.resolveMethod(exception).getName()); + assertThat(this.resolver.resolveMethod(exception).getName()).isEqualTo("handleIOException"); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DefaultMessageHandlerMethodFactoryTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DefaultMessageHandlerMethodFactoryTests.java index a5b6ba44828..34c59860577 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DefaultMessageHandlerMethodFactoryTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DefaultMessageHandlerMethodFactoryTests.java @@ -46,11 +46,8 @@ import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.validation.annotation.Validated; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * @author Stephane Nicoll @@ -87,8 +84,7 @@ public class DefaultMessageHandlerMethodFactoryTests { public void customConversionServiceFailure() throws Exception { DefaultMessageHandlerMethodFactory instance = createInstance(); GenericConversionService conversionService = new GenericConversionService(); - assertFalse("conversion service should fail to convert payload", - conversionService.canConvert(Integer.class, String.class)); + assertThat(conversionService.canConvert(Integer.class, String.class)).as("conversion service should fail to convert payload").isFalse(); instance.setConversionService(conversionService); instance.afterPropertiesSet(); @@ -189,7 +185,7 @@ public class DefaultMessageHandlerMethodFactoryTests { private void assertMethodInvocation(SampleBean bean, String methodName) { - assertTrue("Method " + methodName + " should have been invoked", bean.invocations.get(methodName)); + assertThat((boolean) bean.invocations.get(methodName)).as("Method " + methodName + " should have been invoked").isTrue(); } private InvocableHandlerMethod createInvocableHandlerMethod( @@ -205,7 +201,7 @@ public class DefaultMessageHandlerMethodFactoryTests { private Method getListenerMethod(String methodName, Class... parameterTypes) { Method method = ReflectionUtils.findMethod(SampleBean.class, methodName, parameterTypes); - assertNotNull("no method found with name " + methodName + " and parameters " + Arrays.toString(parameterTypes)); + assertThat(("no method found with name " + methodName + " and parameters " + Arrays.toString(parameterTypes))).isNotNull(); return method; } @@ -224,7 +220,7 @@ public class DefaultMessageHandlerMethodFactoryTests { public void customArgumentResolver(Locale locale) { invocations.put("customArgumentResolver", true); - assertEquals("Wrong value for locale", Locale.getDefault(), locale); + assertThat(locale).as("Wrong value for locale").isEqualTo(Locale.getDefault()); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DestinationVariableMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DestinationVariableMethodArgumentResolverTests.java index 28d75b9c05d..b71c9b86f41 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DestinationVariableMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DestinationVariableMethodArgumentResolverTests.java @@ -29,10 +29,8 @@ import org.springframework.messaging.handler.annotation.DestinationVariable; import org.springframework.messaging.handler.invocation.ResolvableMethod; import org.springframework.messaging.support.MessageBuilder; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.springframework.messaging.handler.annotation.MessagingPredicates.destinationVar; /** @@ -51,8 +49,8 @@ public class DestinationVariableMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(resolver.supportsParameter(this.resolvable.annot(destinationVar().noValue()).arg())); - assertFalse(resolver.supportsParameter(this.resolvable.annotNotPresent(DestinationVariable.class).arg())); + assertThat(resolver.supportsParameter(this.resolvable.annot(destinationVar().noValue()).arg())).isTrue(); + assertThat(resolver.supportsParameter(this.resolvable.annotNotPresent(DestinationVariable.class).arg())).isFalse(); } @Test @@ -67,11 +65,11 @@ public class DestinationVariableMethodArgumentResolverTests { MethodParameter param = this.resolvable.annot(destinationVar().noValue()).arg(); Object result = this.resolver.resolveArgument(param, message); - assertEquals("bar", result); + assertThat(result).isEqualTo("bar"); param = this.resolvable.annot(destinationVar("name")).arg(); result = this.resolver.resolveArgument(param, message); - assertEquals("value", result); + assertThat(result).isEqualTo("value"); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolverTests.java index fcad7d4ff20..89dbeeb5cd0 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolverTests.java @@ -33,10 +33,8 @@ import org.springframework.messaging.handler.invocation.ResolvableMethod; import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.NativeMessageHeaderAccessor; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.springframework.messaging.handler.annotation.MessagingPredicates.header; import static org.springframework.messaging.handler.annotation.MessagingPredicates.headerPlain; @@ -64,15 +62,15 @@ public class HeaderMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter(this.resolvable.annot(headerPlain()).arg())); - assertFalse(this.resolver.supportsParameter(this.resolvable.annotNotPresent(Header.class).arg())); + assertThat(this.resolver.supportsParameter(this.resolvable.annot(headerPlain()).arg())).isTrue(); + assertThat(this.resolver.supportsParameter(this.resolvable.annotNotPresent(Header.class).arg())).isFalse(); } @Test public void resolveArgument() throws Exception { Message message = MessageBuilder.withPayload(new byte[0]).setHeader("param1", "foo").build(); Object result = this.resolver.resolveArgument(this.resolvable.annot(headerPlain()).arg(), message); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); } @Test // SPR-11326 @@ -80,7 +78,7 @@ public class HeaderMethodArgumentResolverTests { TestMessageHeaderAccessor headers = new TestMessageHeaderAccessor(); headers.setNativeHeader("param1", "foo"); Message message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); - assertEquals("foo", this.resolver.resolveArgument(this.resolvable.annot(headerPlain()).arg(), message)); + assertThat(this.resolver.resolveArgument(this.resolvable.annot(headerPlain()).arg(), message)).isEqualTo("foo"); } @Test @@ -90,11 +88,11 @@ public class HeaderMethodArgumentResolverTests { headers.setNativeHeader("param1", "native-foo"); Message message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); - assertEquals("foo", this.resolver.resolveArgument( - this.resolvable.annot(headerPlain()).arg(), message)); + assertThat(this.resolver.resolveArgument( + this.resolvable.annot(headerPlain()).arg(), message)).isEqualTo("foo"); - assertEquals("native-foo", this.resolver.resolveArgument( - this.resolvable.annot(header("nativeHeaders.param1")).arg(), message)); + assertThat(this.resolver.resolveArgument( + this.resolvable.annot(header("nativeHeaders.param1")).arg(), message)).isEqualTo("native-foo"); } @Test @@ -108,7 +106,7 @@ public class HeaderMethodArgumentResolverTests { public void resolveArgumentDefaultValue() throws Exception { Message message = MessageBuilder.withPayload(new byte[0]).build(); Object result = this.resolver.resolveArgument(this.resolvable.annot(header("name", "bar")).arg(), message); - assertEquals("bar", result); + assertThat(result).isEqualTo("bar"); } @Test @@ -118,7 +116,7 @@ public class HeaderMethodArgumentResolverTests { Message message = MessageBuilder.withPayload(new byte[0]).build(); MethodParameter param = this.resolvable.annot(header("name", "#{systemProperties.systemProperty}")).arg(); Object result = resolver.resolveArgument(param, message); - assertEquals("sysbar", result); + assertThat(result).isEqualTo("sysbar"); } finally { System.clearProperty("systemProperty"); @@ -132,7 +130,7 @@ public class HeaderMethodArgumentResolverTests { Message message = MessageBuilder.withPayload(new byte[0]).setHeader("sysbar", "foo").build(); MethodParameter param = this.resolvable.annot(header("#{systemProperties.systemProperty}")).arg(); Object result = resolver.resolveArgument(param, message); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); } finally { System.clearProperty("systemProperty"); @@ -144,7 +142,7 @@ public class HeaderMethodArgumentResolverTests { Message message = MessageBuilder.withPayload("foo").setHeader("foo", "bar").build(); MethodParameter param = this.resolvable.annot(header("foo")).arg(Optional.class, String.class); Object result = resolver.resolveArgument(param, message); - assertEquals(Optional.of("bar"), result); + assertThat(result).isEqualTo(Optional.of("bar")); } @Test @@ -152,7 +150,7 @@ public class HeaderMethodArgumentResolverTests { Message message = MessageBuilder.withPayload("foo").build(); MethodParameter param = this.resolvable.annot(header("foo")).arg(Optional.class, String.class); Object result = resolver.resolveArgument(param, message); - assertEquals(Optional.empty(), result); + assertThat(result).isEqualTo(Optional.empty()); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeadersMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeadersMethodArgumentResolverTests.java index 0bb45346260..c58b4692bc9 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeadersMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeadersMethodArgumentResolverTests.java @@ -30,10 +30,8 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.messaging.support.NativeMessageHeaderAccessor; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Test fixture for {@link HeadersMethodArgumentResolver} tests. @@ -54,14 +52,14 @@ public class HeadersMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter( - this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class))); + assertThat(this.resolver.supportsParameter( + this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class))).isTrue(); - assertTrue(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaders.class))); - assertTrue(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaderAccessor.class))); - assertTrue(this.resolver.supportsParameter(this.resolvable.arg(TestMessageHeaderAccessor.class))); + assertThat(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaders.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaderAccessor.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.resolvable.arg(TestMessageHeaderAccessor.class))).isTrue(); - assertFalse(this.resolver.supportsParameter(this.resolvable.annotPresent(Headers.class).arg(String.class))); + assertThat(this.resolver.supportsParameter(this.resolvable.annotPresent(Headers.class).arg(String.class))).isFalse(); } @Test @@ -69,10 +67,11 @@ public class HeadersMethodArgumentResolverTests { MethodParameter param = this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class); Object resolved = this.resolver.resolveArgument(param, this.message); - assertTrue(resolved instanceof Map); + boolean condition = resolved instanceof Map; + assertThat(condition).isTrue(); @SuppressWarnings("unchecked") Map headers = (Map) resolved; - assertEquals("bar", headers.get("foo")); + assertThat(headers.get("foo")).isEqualTo("bar"); } @Test @@ -85,9 +84,10 @@ public class HeadersMethodArgumentResolverTests { public void resolveArgumentMessageHeaders() throws Exception { Object resolved = this.resolver.resolveArgument(this.resolvable.arg(MessageHeaders.class), this.message); - assertTrue(resolved instanceof MessageHeaders); + boolean condition = resolved instanceof MessageHeaders; + assertThat(condition).isTrue(); MessageHeaders headers = (MessageHeaders) resolved; - assertEquals("bar", headers.get("foo")); + assertThat(headers.get("foo")).isEqualTo("bar"); } @Test @@ -95,9 +95,10 @@ public class HeadersMethodArgumentResolverTests { MethodParameter param = this.resolvable.arg(MessageHeaderAccessor.class); Object resolved = this.resolver.resolveArgument(param, this.message); - assertTrue(resolved instanceof MessageHeaderAccessor); + boolean condition = resolved instanceof MessageHeaderAccessor; + assertThat(condition).isTrue(); MessageHeaderAccessor headers = (MessageHeaderAccessor) resolved; - assertEquals("bar", headers.getHeader("foo")); + assertThat(headers.getHeader("foo")).isEqualTo("bar"); } @Test @@ -105,9 +106,10 @@ public class HeadersMethodArgumentResolverTests { MethodParameter param = this.resolvable.arg(TestMessageHeaderAccessor.class); Object resolved = this.resolver.resolveArgument(param, this.message); - assertTrue(resolved instanceof TestMessageHeaderAccessor); + boolean condition = resolved instanceof TestMessageHeaderAccessor; + assertThat(condition).isTrue(); TestMessageHeaderAccessor headers = (TestMessageHeaderAccessor) resolved; - assertEquals("bar", headers.getHeader("foo")); + assertThat(headers.getHeader("foo")).isEqualTo("bar"); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/MessageMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/MessageMethodArgumentResolverTests.java index 89dc482b248..641d774d4b8 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/MessageMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/MessageMethodArgumentResolverTests.java @@ -31,11 +31,8 @@ import org.springframework.messaging.support.ErrorMessage; import org.springframework.messaging.support.GenericMessage; import org.springframework.messaging.support.MessageBuilder; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -69,8 +66,8 @@ public class MessageMethodArgumentResolverTests { Message message = MessageBuilder.withPayload("test").build(); MethodParameter parameter = new MethodParameter(this.method, 0); - assertTrue(this.resolver.supportsParameter(parameter)); - assertSame(message, this.resolver.resolveArgument(parameter, message)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); + assertThat(this.resolver.resolveArgument(parameter, message)).isSameAs(message); } @Test @@ -78,8 +75,8 @@ public class MessageMethodArgumentResolverTests { Message message = MessageBuilder.withPayload(123).build(); MethodParameter parameter = new MethodParameter(this.method, 1); - assertTrue(this.resolver.supportsParameter(parameter)); - assertSame(message, this.resolver.resolveArgument(parameter, message)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); + assertThat(this.resolver.resolveArgument(parameter, message)).isSameAs(message); } @Test @@ -87,8 +84,8 @@ public class MessageMethodArgumentResolverTests { Message message = MessageBuilder.withPayload(123).build(); MethodParameter parameter = new MethodParameter(this.method, 2); - assertTrue(this.resolver.supportsParameter(parameter)); - assertSame(message, this.resolver.resolveArgument(parameter, message)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); + assertThat(this.resolver.resolveArgument(parameter, message)).isSameAs(message); } @Test @@ -101,9 +98,9 @@ public class MessageMethodArgumentResolverTests { @SuppressWarnings("unchecked") Message actual = (Message) this.resolver.resolveArgument(parameter, message); - assertNotNull(actual); - assertSame(message.getHeaders(), actual.getHeaders()); - assertEquals(new Integer(4), actual.getPayload()); + assertThat(actual).isNotNull(); + assertThat(actual.getHeaders()).isSameAs(message.getHeaders()); + assertThat(actual.getPayload()).isEqualTo(new Integer(4)); } @Test @@ -111,7 +108,7 @@ public class MessageMethodArgumentResolverTests { Message message = MessageBuilder.withPayload("test").build(); MethodParameter parameter = new MethodParameter(this.method, 1); - assertTrue(this.resolver.supportsParameter(parameter)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> this.resolver.resolveArgument(parameter, message)) .withMessageContaining(Integer.class.getName()) @@ -123,7 +120,7 @@ public class MessageMethodArgumentResolverTests { Message message = MessageBuilder.withPayload("").build(); MethodParameter parameter = new MethodParameter(this.method, 1); - assertTrue(this.resolver.supportsParameter(parameter)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> this.resolver.resolveArgument(parameter, message)) .withMessageContaining("payload is empty") @@ -136,8 +133,8 @@ public class MessageMethodArgumentResolverTests { Message message = MessageBuilder.withPayload(123).build(); MethodParameter parameter = new MethodParameter(this.method, 3); - assertTrue(this.resolver.supportsParameter(parameter)); - assertSame(message, this.resolver.resolveArgument(parameter, message)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); + assertThat(this.resolver.resolveArgument(parameter, message)).isSameAs(message); } @Test @@ -145,7 +142,7 @@ public class MessageMethodArgumentResolverTests { Message message = MessageBuilder.withPayload(Locale.getDefault()).build(); MethodParameter parameter = new MethodParameter(this.method, 3); - assertTrue(this.resolver.supportsParameter(parameter)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> this.resolver.resolveArgument(parameter, message)) .withMessageContaining(Number.class.getName()) @@ -157,8 +154,8 @@ public class MessageMethodArgumentResolverTests { ErrorMessage message = new ErrorMessage(new UnsupportedOperationException()); MethodParameter parameter = new MethodParameter(this.method, 4); - assertTrue(this.resolver.supportsParameter(parameter)); - assertSame(message, this.resolver.resolveArgument(parameter, message)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); + assertThat(this.resolver.resolveArgument(parameter, message)).isSameAs(message); } @Test @@ -166,8 +163,8 @@ public class MessageMethodArgumentResolverTests { ErrorMessage message = new ErrorMessage(new UnsupportedOperationException()); MethodParameter parameter = new MethodParameter(this.method, 0); - assertTrue(this.resolver.supportsParameter(parameter)); - assertSame(message, this.resolver.resolveArgument(parameter, message)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); + assertThat(this.resolver.resolveArgument(parameter, message)).isSameAs(message); } @Test @@ -176,7 +173,7 @@ public class MessageMethodArgumentResolverTests { Message message = new GenericMessage(ex); MethodParameter parameter = new MethodParameter(this.method, 4); - assertTrue(this.resolver.supportsParameter(parameter)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); assertThatExceptionOfType(MethodArgumentTypeMismatchException.class).isThrownBy(() -> this.resolver.resolveArgument(parameter, message)) .withMessageContaining(ErrorMessage.class.getName()) @@ -190,8 +187,8 @@ public class MessageMethodArgumentResolverTests { Message message = MessageBuilder.withPayload("test").build(); MethodParameter parameter = new MethodParameter(this.method, 0); - assertTrue(this.resolver.supportsParameter(parameter)); - assertSame(message, this.resolver.resolveArgument(parameter, message)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); + assertThat(this.resolver.resolveArgument(parameter, message)).isSameAs(message); } @Test @@ -201,7 +198,7 @@ public class MessageMethodArgumentResolverTests { Message message = MessageBuilder.withPayload("test").build(); MethodParameter parameter = new MethodParameter(this.method, 1); - assertTrue(this.resolver.supportsParameter(parameter)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> this.resolver.resolveArgument(parameter, message)) .withMessageContaining(Integer.class.getName()) @@ -215,7 +212,7 @@ public class MessageMethodArgumentResolverTests { Message message = MessageBuilder.withPayload("").build(); MethodParameter parameter = new MethodParameter(this.method, 1); - assertTrue(this.resolver.supportsParameter(parameter)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> this.resolver.resolveArgument(parameter, message)) .withMessageContaining("payload is empty") @@ -231,10 +228,12 @@ public class MessageMethodArgumentResolverTests { this.resolver = new MessageMethodArgumentResolver(new MappingJackson2MessageConverter()); Object actual = this.resolver.resolveArgument(parameter, inMessage); - assertTrue(actual instanceof Message); + boolean condition1 = actual instanceof Message; + assertThat(condition1).isTrue(); Message outMessage = (Message) actual; - assertTrue(outMessage.getPayload() instanceof Foo); - assertEquals("bar", ((Foo) outMessage.getPayload()).getFoo()); + boolean condition = outMessage.getPayload() instanceof Foo; + assertThat(condition).isTrue(); + assertThat(((Foo) outMessage.getPayload()).getFoo()).isEqualTo("bar"); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/PayloadMethodArgumentResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/PayloadMethodArgumentResolverTests.java index 2b951732d00..3c91c83bc62 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/PayloadMethodArgumentResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/PayloadMethodArgumentResolverTests.java @@ -38,12 +38,9 @@ import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.validation.annotation.Validated; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertNull; -import static org.junit.Assert.assertTrue; /** * Test fixture for {@link PayloadMethodArgumentResolver}. @@ -91,14 +88,14 @@ public class PayloadMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter(this.paramAnnotated)); - assertTrue(this.resolver.supportsParameter(this.paramNotAnnotated)); + assertThat(this.resolver.supportsParameter(this.paramAnnotated)).isTrue(); + assertThat(this.resolver.supportsParameter(this.paramNotAnnotated)).isTrue(); PayloadMethodArgumentResolver strictResolver = new PayloadMethodArgumentResolver( new StringMessageConverter(), testValidator(), false); - assertTrue(strictResolver.supportsParameter(this.paramAnnotated)); - assertFalse(strictResolver.supportsParameter(this.paramNotAnnotated)); + assertThat(strictResolver.supportsParameter(this.paramAnnotated)).isTrue(); + assertThat(strictResolver.supportsParameter(this.paramNotAnnotated)).isFalse(); } @Test @@ -106,7 +103,7 @@ public class PayloadMethodArgumentResolverTests { Message message = MessageBuilder.withPayload("ABC".getBytes()).build(); Object actual = this.resolver.resolveArgument(paramAnnotated, message); - assertEquals("ABC", actual); + assertThat(actual).isEqualTo("ABC"); } @Test @@ -128,13 +125,13 @@ public class PayloadMethodArgumentResolverTests { @Test public void resolveNotRequired() throws Exception { Message emptyByteArrayMessage = MessageBuilder.withPayload(new byte[0]).build(); - assertNull(this.resolver.resolveArgument(this.paramAnnotatedNotRequired, emptyByteArrayMessage)); + assertThat(this.resolver.resolveArgument(this.paramAnnotatedNotRequired, emptyByteArrayMessage)).isNull(); Message emptyStringMessage = MessageBuilder.withPayload("").build(); - assertNull(this.resolver.resolveArgument(this.paramAnnotatedNotRequired, emptyStringMessage)); + assertThat(this.resolver.resolveArgument(this.paramAnnotatedNotRequired, emptyStringMessage)).isNull(); Message notEmptyMessage = MessageBuilder.withPayload("ABC".getBytes()).build(); - assertEquals("ABC", this.resolver.resolveArgument(this.paramAnnotatedNotRequired, notEmptyMessage)); + assertThat(this.resolver.resolveArgument(this.paramAnnotatedNotRequired, notEmptyMessage)).isEqualTo("ABC"); } @Test @@ -180,7 +177,7 @@ public class PayloadMethodArgumentResolverTests { @Test public void resolveNonAnnotatedParameter() throws Exception { Message notEmptyMessage = MessageBuilder.withPayload("ABC".getBytes()).build(); - assertEquals("ABC", this.resolver.resolveArgument(this.paramNotAnnotated, notEmptyMessage)); + assertThat(this.resolver.resolveArgument(this.paramNotAnnotated, notEmptyMessage)).isEqualTo("ABC"); Message emptyStringMessage = MessageBuilder.withPayload("").build(); assertThatExceptionOfType(MethodArgumentNotValidException.class).isThrownBy(() -> @@ -192,8 +189,7 @@ public class PayloadMethodArgumentResolverTests { // See testValidator() Message message = MessageBuilder.withPayload("invalidValue".getBytes()).build(); - assertThatExceptionOfType(MethodArgumentNotValidException.class).isThrownBy(() -> - assertEquals("invalidValue", this.resolver.resolveArgument(this.paramValidatedNotAnnotated, message))) + assertThatExceptionOfType(MethodArgumentNotValidException.class).isThrownBy(() -> assertThat(this.resolver.resolveArgument(this.paramValidatedNotAnnotated, message)).isEqualTo("invalidValue")) .withMessageContaining("invalid value"); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethodTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethodTests.java index d666f1f717e..91c50900aa3 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethodTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethodTests.java @@ -24,11 +24,10 @@ import org.springframework.core.MethodParameter; import org.springframework.lang.Nullable; import org.springframework.messaging.Message; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; /** @@ -50,11 +49,11 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invoke(new Handler(), method); - assertEquals(1, getStubResolver(0).getResolvedParameters().size()); - assertEquals(1, getStubResolver(1).getResolvedParameters().size()); - assertEquals("99-value", value); - assertEquals("intArg", getStubResolver(0).getResolvedParameters().get(0).getParameterName()); - assertEquals("stringArg", getStubResolver(1).getResolvedParameters().get(0).getParameterName()); + assertThat(getStubResolver(0).getResolvedParameters().size()).isEqualTo(1); + assertThat(getStubResolver(1).getResolvedParameters().size()).isEqualTo(1); + assertThat(value).isEqualTo("99-value"); + assertThat(getStubResolver(0).getResolvedParameters().get(0).getParameterName()).isEqualTo("intArg"); + assertThat(getStubResolver(1).getResolvedParameters().get(0).getParameterName()).isEqualTo("stringArg"); } @Test @@ -64,9 +63,9 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invoke(new Handler(), method); - assertEquals(1, getStubResolver(0).getResolvedParameters().size()); - assertEquals(1, getStubResolver(1).getResolvedParameters().size()); - assertEquals("null-null", value); + assertThat(getStubResolver(0).getResolvedParameters().size()).isEqualTo(1); + assertThat(getStubResolver(1).getResolvedParameters().size()).isEqualTo(1); + assertThat(value).isEqualTo("null-null"); } @Test @@ -82,9 +81,9 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invoke(new Handler(), method, 99, "value"); - assertNotNull(value); - assertEquals(String.class, value.getClass()); - assertEquals("99-value", value); + assertThat(value).isNotNull(); + assertThat(value.getClass()).isEqualTo(String.class); + assertThat(value).isEqualTo("99-value"); } @Test @@ -94,7 +93,7 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invoke(new Handler(), method, 2, "value2"); - assertEquals("2-value2", value); + assertThat(value).isEqualTo("2-value2"); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/MethodMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/MethodMessageHandlerTests.java index 0ef4b074f79..7df777e0a48 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/MethodMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/MethodMessageHandlerTests.java @@ -42,8 +42,6 @@ import org.springframework.util.PathMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Test fixture for @@ -86,7 +84,7 @@ public class MethodMessageHandlerTests { Map handlerMethods = this.messageHandler.getHandlerMethods(); - assertNotNull(handlerMethods); + assertThat(handlerMethods).isNotNull(); assertThat(handlerMethods).hasSize(3); } @@ -98,7 +96,7 @@ public class MethodMessageHandlerTests { this.messageHandler.handleMessage(toDestination("/test/handlerPathMatchFoo")); - assertEquals("pathMatchWildcard", this.testController.method); + assertThat(this.testController.method).isEqualTo("pathMatchWildcard"); } @Test @@ -112,7 +110,7 @@ public class MethodMessageHandlerTests { this.messageHandler.handleMessage(toDestination("/test/bestmatch/bar/path")); - assertEquals("bestMatch", this.testController.method); + assertThat(this.testController.method).isEqualTo("bestMatch"); } @Test @@ -120,8 +118,8 @@ public class MethodMessageHandlerTests { this.messageHandler.handleMessage(toDestination("/test/handlerArgumentResolver")); - assertEquals("handlerArgumentResolver", this.testController.method); - assertNotNull(this.testController.arguments.get("message")); + assertThat(this.testController.method).isEqualTo("handlerArgumentResolver"); + assertThat(this.testController.arguments.get("message")).isNotNull(); } @Test @@ -129,8 +127,8 @@ public class MethodMessageHandlerTests { this.messageHandler.handleMessage(toDestination("/test/handlerThrowsExc")); - assertEquals("illegalStateException", this.testController.method); - assertNotNull(this.testController.arguments.get("exception")); + assertThat(this.testController.method).isEqualTo("illegalStateException"); + assertThat(this.testController.arguments.get("exception")).isNotNull(); } private Message toDestination(String destination) { diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/InvocableHandlerMethodTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/InvocableHandlerMethodTests.java index b4833cee56d..e8091e27d70 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/InvocableHandlerMethodTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/InvocableHandlerMethodTests.java @@ -32,13 +32,10 @@ import org.springframework.messaging.Message; import org.springframework.messaging.handler.invocation.MethodArgumentResolutionException; import org.springframework.messaging.handler.invocation.ResolvableMethod; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -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.mockito.Mockito.mock; /** @@ -61,11 +58,11 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invokeAndBlock(new Handler(), method); - assertEquals(1, getStubResolver(0).getResolvedParameters().size()); - assertEquals(1, getStubResolver(1).getResolvedParameters().size()); - assertEquals("99-value", value); - assertEquals("intArg", getStubResolver(0).getResolvedParameters().get(0).getParameterName()); - assertEquals("stringArg", getStubResolver(1).getResolvedParameters().get(0).getParameterName()); + assertThat(getStubResolver(0).getResolvedParameters().size()).isEqualTo(1); + assertThat(getStubResolver(1).getResolvedParameters().size()).isEqualTo(1); + assertThat(value).isEqualTo("99-value"); + assertThat(getStubResolver(0).getResolvedParameters().get(0).getParameterName()).isEqualTo("intArg"); + assertThat(getStubResolver(1).getResolvedParameters().get(0).getParameterName()).isEqualTo("stringArg"); } @Test @@ -75,9 +72,9 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invokeAndBlock(new Handler(), method); - assertEquals(1, getStubResolver(0).getResolvedParameters().size()); - assertEquals(1, getStubResolver(1).getResolvedParameters().size()); - assertEquals("null-null", value); + assertThat(getStubResolver(0).getResolvedParameters().size()).isEqualTo(1); + assertThat(getStubResolver(1).getResolvedParameters().size()).isEqualTo(1); + assertThat(value).isEqualTo("null-null"); } @Test @@ -93,9 +90,9 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invokeAndBlock(new Handler(), method, 99, "value"); - assertNotNull(value); - assertEquals(String.class, value.getClass()); - assertEquals("99-value", value); + assertThat(value).isNotNull(); + assertThat(value.getClass()).isEqualTo(String.class); + assertThat(value).isEqualTo("99-value"); } @Test @@ -105,7 +102,7 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(Handler.class).mockCall(c -> c.handle(0, "")).method(); Object value = invokeAndBlock(new Handler(), method, 2, "value2"); - assertEquals("2-value2", value); + assertThat(value).isEqualTo("2-value2"); } @Test @@ -137,7 +134,7 @@ public class InvocableHandlerMethodTests { Throwable expected = new Throwable("error"); Mono result = invoke(new Handler(), method, expected); - StepVerifier.create(result).expectErrorSatisfies(actual -> assertSame(expected, actual)).verify(); + StepVerifier.create(result).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(); } @Test @@ -147,10 +144,10 @@ public class InvocableHandlerMethodTests { Handler handler = new Handler(); Object value = invokeAndBlock(handler, method); - assertNull(value); - assertEquals(1, getStubResolver(0).getResolvedParameters().size()); - assertEquals("5.25", handler.getResult()); - assertEquals("amount", getStubResolver(0).getResolvedParameters().get(0).getParameterName()); + assertThat(value).isNull(); + assertThat(getStubResolver(0).getResolvedParameters().size()).isEqualTo(1); + assertThat(handler.getResult()).isEqualTo("5.25"); + assertThat(getStubResolver(0).getResolvedParameters().get(0).getParameterName()).isEqualTo("amount"); } @Test @@ -159,8 +156,8 @@ public class InvocableHandlerMethodTests { Handler handler = new Handler(); Object value = invokeAndBlock(handler, method); - assertNull(value); - assertEquals("success", handler.getResult()); + assertThat(value).isNull(); + assertThat(handler.getResult()).isEqualTo("success"); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/MethodMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/MethodMessageHandlerTests.java index 1c61fd2a438..5adc945f2f7 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/MethodMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/reactive/MethodMessageHandlerTests.java @@ -48,7 +48,6 @@ import org.springframework.util.SimpleRouteMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link AbstractMethodMessageHandler}. @@ -68,7 +67,7 @@ public class MethodMessageHandlerTests { TestMethodMessageHandler messageHandler = initMethodMessageHandler(TestController.class); Map mappings = messageHandler.getHandlerMethods(); - assertEquals(5, mappings.keySet().size()); + assertThat(mappings.keySet().size()).isEqualTo(5); assertThat(mappings).containsOnlyKeys( "/handleMessage", "/handleMessageWithArgument", "/handleMessageWithError", "/handleMessageMatch1", "/handleMessageMatch2"); diff --git a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java index 00872d7cdc0..56eebe53df1 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterTests.java @@ -44,11 +44,8 @@ import org.springframework.messaging.rsocket.RSocketRequester.ResponseSpec; import org.springframework.util.MimeTypeUtils; import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link DefaultRSocketRequester}. @@ -97,9 +94,9 @@ public class DefaultRSocketRequesterTests { private void testSinglePayload(Function mapper, String expectedValue) { mapper.apply(this.requester.route("toA")).send().block(Duration.ofSeconds(5)); - assertEquals("fireAndForget", this.rsocket.getSavedMethodName()); - assertEquals("toA", this.rsocket.getSavedPayload().getMetadataUtf8()); - assertEquals(expectedValue, this.rsocket.getSavedPayload().getDataUtf8()); + assertThat(this.rsocket.getSavedMethodName()).isEqualTo("fireAndForget"); + assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("toA"); + assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo(expectedValue); } @Test @@ -122,20 +119,18 @@ public class DefaultRSocketRequesterTests { this.rsocket.reset(); mapper.apply(this.requester.route("toA")).retrieveFlux(String.class).blockLast(Duration.ofSeconds(5)); - assertEquals("requestChannel", this.rsocket.getSavedMethodName()); + assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestChannel"); List payloads = this.rsocket.getSavedPayloadFlux().collectList().block(Duration.ofSeconds(5)); - assertNotNull(payloads); + assertThat(payloads).isNotNull(); if (Arrays.equals(new String[] {""}, expectedValues)) { - assertEquals(1, payloads.size()); - assertEquals("toA", payloads.get(0).getMetadataUtf8()); - assertEquals("", payloads.get(0).getDataUtf8()); + assertThat(payloads.size()).isEqualTo(1); + assertThat(payloads.get(0).getMetadataUtf8()).isEqualTo("toA"); + assertThat(payloads.get(0).getDataUtf8()).isEqualTo(""); } else { - assertArrayEquals(new String[] {"toA", "", ""}, - payloads.stream().map(Payload::getMetadataUtf8).toArray(String[]::new)); - assertArrayEquals(expectedValues, - payloads.stream().map(Payload::getDataUtf8).toArray(String[]::new)); + assertThat(payloads.stream().map(Payload::getMetadataUtf8).toArray(String[]::new)).isEqualTo(new String[] {"toA", "", ""}); + assertThat(payloads.stream().map(Payload::getDataUtf8).toArray(String[]::new)).isEqualTo(expectedValues); } } @@ -144,9 +139,9 @@ public class DefaultRSocketRequesterTests { String value = "bodyA"; this.requester.route("toA").data(value).send().block(Duration.ofSeconds(5)); - assertEquals("fireAndForget", this.rsocket.getSavedMethodName()); - assertEquals("toA", this.rsocket.getSavedPayload().getMetadataUtf8()); - assertEquals("bodyA", this.rsocket.getSavedPayload().getDataUtf8()); + assertThat(this.rsocket.getSavedMethodName()).isEqualTo("fireAndForget"); + assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("toA"); + assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo("bodyA"); } @Test @@ -156,7 +151,7 @@ public class DefaultRSocketRequesterTests { Mono response = this.requester.route("").data("").retrieveMono(String.class); StepVerifier.create(response).expectNext(value).expectComplete().verify(Duration.ofSeconds(5)); - assertEquals("requestResponse", this.rsocket.getSavedMethodName()); + assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestResponse"); } @Test @@ -166,8 +161,8 @@ public class DefaultRSocketRequesterTests { this.rsocket.setPayloadMonoToReturn(mono); this.requester.route("").data("").retrieveMono(Void.class).block(Duration.ofSeconds(5)); - assertTrue(consumed.get()); - assertEquals("requestResponse", this.rsocket.getSavedMethodName()); + assertThat(consumed.get()).isTrue(); + assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestResponse"); } @Test @@ -177,7 +172,7 @@ public class DefaultRSocketRequesterTests { Flux response = this.requester.route("").data("").retrieveFlux(String.class); StepVerifier.create(response).expectNext(values).expectComplete().verify(Duration.ofSeconds(5)); - assertEquals("requestStream", this.rsocket.getSavedMethodName()); + assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestStream"); } @Test @@ -188,8 +183,8 @@ public class DefaultRSocketRequesterTests { this.rsocket.setPayloadFluxToReturn(flux); this.requester.route("").data("").retrieveFlux(Void.class).blockLast(Duration.ofSeconds(5)); - assertTrue(consumed.get()); - assertEquals("requestStream", this.rsocket.getSavedMethodName()); + assertThat(consumed.get()).isTrue(); + assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestStream"); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketBufferLeakTests.java b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketBufferLeakTests.java index 260a9dc2ec8..416f4d5fa94 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketBufferLeakTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketBufferLeakTests.java @@ -61,7 +61,7 @@ import org.springframework.messaging.handler.annotation.Payload; import org.springframework.stereotype.Controller; import org.springframework.util.ObjectUtils; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for scenarios that could lead to Payload and/or DataBuffer leaks. @@ -348,7 +348,7 @@ public class RSocketBufferLeakTests { while (true) { try { int count = info.getReferenceCount(); - assertTrue("Leaked payload (refCnt=" + count + "): " + info, count == 0); + assertThat(count == 0).as("Leaked payload (refCnt=" + count + "): " + info).isTrue(); break; } catch (AssertionError ex) { diff --git a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketClientToServerIntegrationTests.java b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketClientToServerIntegrationTests.java index 93155653138..b340f50b892 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketClientToServerIntegrationTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketClientToServerIntegrationTests.java @@ -41,7 +41,7 @@ import org.springframework.messaging.handler.annotation.MessageExceptionHandler; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.stereotype.Controller; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Server-side handling of RSocket requests. @@ -100,9 +100,8 @@ public class RSocketClientToServerIntegrationTests { .thenCancel() .verify(Duration.ofSeconds(5)); - assertEquals(1, interceptor.getRSocketCount()); - assertEquals("Fire and forget requests did not actually complete handling on the server side", - 3, interceptor.getFireAndForgetCount(0)); + assertThat(interceptor.getRSocketCount()).isEqualTo(1); + assertThat(interceptor.getFireAndForgetCount(0)).as("Fire and forget requests did not actually complete handling on the server side").isEqualTo(3); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessageHeaderAccessorTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessageHeaderAccessorTests.java index 4dfc04e6f0f..69221a00776 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessageHeaderAccessorTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessageHeaderAccessorTests.java @@ -20,7 +20,7 @@ import java.util.Collections; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for SimpMessageHeaderAccessor. @@ -32,7 +32,7 @@ public class SimpMessageHeaderAccessorTests { @Test public void getShortLogMessage() { - assertEquals("MESSAGE session=null payload=p", SimpMessageHeaderAccessor.create().getShortLogMessage("p")); + assertThat(SimpMessageHeaderAccessor.create().getShortLogMessage("p")).isEqualTo("MESSAGE session=null payload=p"); } @Test @@ -44,8 +44,8 @@ public class SimpMessageHeaderAccessorTests { accessor.setUser(new TestPrincipal("user")); accessor.setSessionAttributes(Collections.singletonMap("key", "value")); - assertEquals("MESSAGE destination=/destination subscriptionId=subscription " + - "session=session user=user attributes[1] payload=p", accessor.getShortLogMessage("p")); + assertThat(accessor.getShortLogMessage("p")).isEqualTo(("MESSAGE destination=/destination subscriptionId=subscription " + + "session=session user=user attributes[1] payload=p")); } @Test @@ -58,9 +58,9 @@ public class SimpMessageHeaderAccessorTests { accessor.setSessionAttributes(Collections.singletonMap("key", "value")); accessor.setNativeHeader("nativeKey", "nativeValue"); - assertEquals("MESSAGE destination=/destination subscriptionId=subscription " + + assertThat(accessor.getDetailedLogMessage("p")).isEqualTo(("MESSAGE destination=/destination subscriptionId=subscription " + "session=session user=user attributes={key=value} nativeHeaders=" + - "{nativeKey=[nativeValue]} payload=p", accessor.getDetailedLogMessage("p")); + "{nativeKey=[nativeValue]} payload=p")); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessageTypeMessageConditionTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessageTypeMessageConditionTests.java index bd63f140b76..f3876c56576 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessageTypeMessageConditionTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessageTypeMessageConditionTests.java @@ -21,9 +21,7 @@ import org.junit.Test; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for SimpMessageTypeMessageCondition. @@ -38,13 +36,13 @@ public class SimpMessageTypeMessageConditionTests { SimpMessageType subscribeType = SimpMessageType.SUBSCRIBE; SimpMessageType actual = condition(messageType).combine(condition(subscribeType)).getMessageType(); - assertEquals(subscribeType, actual); + assertThat(actual).isEqualTo(subscribeType); actual = condition(messageType).combine(condition(messageType)).getMessageType(); - assertEquals(messageType, actual); + assertThat(actual).isEqualTo(messageType); actual = condition(subscribeType).combine(condition(subscribeType)).getMessageType(); - assertEquals(subscribeType, actual); + assertThat(actual).isEqualTo(subscribeType); } @Test @@ -53,8 +51,8 @@ public class SimpMessageTypeMessageConditionTests { SimpMessageTypeMessageCondition condition = condition(SimpMessageType.MESSAGE); SimpMessageTypeMessageCondition actual = condition.getMatchingCondition(message); - assertNotNull(actual); - assertEquals(SimpMessageType.MESSAGE, actual.getMessageType()); + assertThat(actual).isNotNull(); + assertThat(actual.getMessageType()).isEqualTo(SimpMessageType.MESSAGE); } @Test @@ -62,14 +60,14 @@ public class SimpMessageTypeMessageConditionTests { Message message = message(null); SimpMessageTypeMessageCondition condition = condition(SimpMessageType.MESSAGE); - assertNull(condition.getMatchingCondition(message)); + assertThat(condition.getMatchingCondition(message)).isNull(); } @Test public void compareTo() { Message message = message(null); - assertEquals(0, condition(SimpMessageType.MESSAGE).compareTo(condition(SimpMessageType.MESSAGE), message)); - assertEquals(0, condition(SimpMessageType.MESSAGE).compareTo(condition(SimpMessageType.SUBSCRIBE), message)); + assertThat(condition(SimpMessageType.MESSAGE).compareTo(condition(SimpMessageType.MESSAGE), message)).isEqualTo(0); + assertThat(condition(SimpMessageType.MESSAGE).compareTo(condition(SimpMessageType.SUBSCRIBE), message)).isEqualTo(0); } private Message message(SimpMessageType messageType) { diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessagingTemplateTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessagingTemplateTests.java index b6e8864f3f2..70c103dc74e 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessagingTemplateTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/SimpMessagingTemplateTests.java @@ -35,12 +35,7 @@ import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.messaging.support.NativeMessageHeaderAccessor; import org.springframework.util.LinkedMultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link org.springframework.messaging.simp.SimpMessagingTemplate}. @@ -66,15 +61,15 @@ public class SimpMessagingTemplateTests { this.messagingTemplate.convertAndSendToUser("joe", "/queue/foo", "data"); List> messages = this.messageChannel.getMessages(); - assertEquals(1, messages.size()); + assertThat(messages.size()).isEqualTo(1); Message message = messages.get(0); SimpMessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class); - assertNotNull(headerAccessor); - assertEquals(SimpMessageType.MESSAGE, headerAccessor.getMessageType()); - assertEquals("/user/joe/queue/foo", headerAccessor.getDestination()); + assertThat(headerAccessor).isNotNull(); + assertThat(headerAccessor.getMessageType()).isEqualTo(SimpMessageType.MESSAGE); + assertThat(headerAccessor.getDestination()).isEqualTo("/user/joe/queue/foo"); } @Test @@ -82,13 +77,13 @@ public class SimpMessagingTemplateTests { this.messagingTemplate.convertAndSendToUser("https://joe.openid.example.org/", "/queue/foo", "data"); List> messages = this.messageChannel.getMessages(); - assertEquals(1, messages.size()); + assertThat(messages.size()).isEqualTo(1); SimpMessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(messages.get(0), SimpMessageHeaderAccessor.class); - assertNotNull(headerAccessor); - assertEquals("/user/https:%2F%2Fjoe.openid.example.org%2F/queue/foo", headerAccessor.getDestination()); + assertThat(headerAccessor).isNotNull(); + assertThat(headerAccessor.getDestination()).isEqualTo("/user/https:%2F%2Fjoe.openid.example.org%2F/queue/foo"); } @Test @@ -101,9 +96,9 @@ public class SimpMessagingTemplateTests { SimpMessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(messages.get(0), SimpMessageHeaderAccessor.class); - assertNotNull(headerAccessor); - assertNull(headerAccessor.toMap().get("key")); - assertEquals(Arrays.asList("value"), headerAccessor.getNativeHeader("key")); + assertThat(headerAccessor).isNotNull(); + assertThat(headerAccessor.toMap().get("key")).isNull(); + assertThat(headerAccessor.getNativeHeader("key")).isEqualTo(Arrays.asList("value")); } @Test @@ -118,9 +113,9 @@ public class SimpMessagingTemplateTests { SimpMessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(messages.get(0), SimpMessageHeaderAccessor.class); - assertNotNull(headerAccessor); - assertEquals("value", headerAccessor.toMap().get("key")); - assertNull(headerAccessor.getNativeHeader("key")); + assertThat(headerAccessor).isNotNull(); + assertThat(headerAccessor.toMap().get("key")).isEqualTo("value"); + assertThat(headerAccessor.getNativeHeader("key")).isNull(); } // SPR-11868 @@ -131,15 +126,15 @@ public class SimpMessagingTemplateTests { this.messagingTemplate.convertAndSendToUser("joe", "/queue/foo", "data"); List> messages = this.messageChannel.getMessages(); - assertEquals(1, messages.size()); + assertThat(messages.size()).isEqualTo(1); Message message = messages.get(0); SimpMessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class); - assertNotNull(headerAccessor); - assertEquals(SimpMessageType.MESSAGE, headerAccessor.getMessageType()); - assertEquals("/prefix/joe/queue/foo", headerAccessor.getDestination()); + assertThat(headerAccessor).isNotNull(); + assertThat(headerAccessor.getMessageType()).isEqualTo(SimpMessageType.MESSAGE); + assertThat(headerAccessor.getDestination()).isEqualTo("/prefix/joe/queue/foo"); } @Test @@ -155,22 +150,22 @@ public class SimpMessagingTemplateTests { List> messages = this.messageChannel.getMessages(); Message message = messages.get(0); - assertSame(headers, message.getHeaders()); - assertFalse(accessor.isMutable()); + assertThat(message.getHeaders()).isSameAs(headers); + assertThat(accessor.isMutable()).isFalse(); } @Test public void processHeadersToSend() { Map map = this.messagingTemplate.processHeadersToSend(null); - assertNotNull(map); - assertTrue("Actual: " + map.getClass().toString(), MessageHeaders.class.isAssignableFrom(map.getClass())); + assertThat(map).isNotNull(); + assertThat(MessageHeaders.class.isAssignableFrom(map.getClass())).as("Actual: " + map.getClass().toString()).isTrue(); SimpMessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor((MessageHeaders) map, SimpMessageHeaderAccessor.class); - assertTrue(headerAccessor.isMutable()); - assertEquals(SimpMessageType.MESSAGE, headerAccessor.getMessageType()); + assertThat(headerAccessor.isMutable()).isTrue(); + assertThat(headerAccessor.getMessageType()).isEqualTo(SimpMessageType.MESSAGE); } @Test @@ -187,8 +182,8 @@ public class SimpMessagingTemplateTests { List> messages = this.messageChannel.getMessages(); Message sentMessage = messages.get(0); - assertSame(message, sentMessage); - assertFalse(accessor.isMutable()); + assertThat(sentMessage).isSameAs(message); + assertThat(accessor.isMutable()).isFalse(); } @Test @@ -203,8 +198,8 @@ public class SimpMessagingTemplateTests { Message sentMessage = messages.get(0); MessageHeaderAccessor sentAccessor = MessageHeaderAccessor.getAccessor(sentMessage, MessageHeaderAccessor.class); - assertEquals(StompHeaderAccessor.class, sentAccessor.getClass()); - assertEquals("/queue/foo-user123", ((StompHeaderAccessor) sentAccessor).getDestination()); + assertThat(sentAccessor.getClass()).isEqualTo(StompHeaderAccessor.class); + assertThat(((StompHeaderAccessor) sentAccessor).getDestination()).isEqualTo("/queue/foo-user123"); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SendToMethodReturnValueHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SendToMethodReturnValueHandlerTests.java index cfb76ca6c77..03c61ba62b2 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SendToMethodReturnValueHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SendToMethodReturnValueHandlerTests.java @@ -54,11 +54,7 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.util.MimeType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -136,18 +132,18 @@ public class SendToMethodReturnValueHandlerTests { @Test public void supportsReturnType() throws Exception { - assertTrue(this.handler.supportsReturnType(this.sendToReturnType)); - assertTrue(this.handler.supportsReturnType(this.sendToUserReturnType)); - assertFalse(this.handler.supportsReturnType(this.noAnnotationsReturnType)); - assertTrue(this.handlerAnnotationNotRequired.supportsReturnType(this.noAnnotationsReturnType)); + assertThat(this.handler.supportsReturnType(this.sendToReturnType)).isTrue(); + assertThat(this.handler.supportsReturnType(this.sendToUserReturnType)).isTrue(); + assertThat(this.handler.supportsReturnType(this.noAnnotationsReturnType)).isFalse(); + assertThat(this.handlerAnnotationNotRequired.supportsReturnType(this.noAnnotationsReturnType)).isTrue(); - assertTrue(this.handler.supportsReturnType(this.defaultNoAnnotation)); - assertTrue(this.handler.supportsReturnType(this.defaultEmptyAnnotation)); - assertTrue(this.handler.supportsReturnType(this.defaultOverrideAnnotation)); + assertThat(this.handler.supportsReturnType(this.defaultNoAnnotation)).isTrue(); + assertThat(this.handler.supportsReturnType(this.defaultEmptyAnnotation)).isTrue(); + assertThat(this.handler.supportsReturnType(this.defaultOverrideAnnotation)).isTrue(); - assertTrue(this.handler.supportsReturnType(this.userDefaultNoAnnotation)); - assertTrue(this.handler.supportsReturnType(this.userDefaultEmptyAnnotation)); - assertTrue(this.handler.supportsReturnType(this.userDefaultOverrideAnnotation)); + assertThat(this.handler.supportsReturnType(this.userDefaultNoAnnotation)).isTrue(); + assertThat(this.handler.supportsReturnType(this.userDefaultEmptyAnnotation)).isTrue(); + assertThat(this.handler.supportsReturnType(this.userDefaultOverrideAnnotation)).isTrue(); } @Test @@ -299,11 +295,11 @@ public class SendToMethodReturnValueHandlerTests { int index, String destination) { SimpMessageHeaderAccessor accessor = getCapturedAccessor(index); - assertEquals(sessionId, accessor.getSessionId()); - assertEquals(destination, accessor.getDestination()); - assertEquals(MIME_TYPE, accessor.getContentType()); - assertNull("Subscription id should not be copied", accessor.getSubscriptionId()); - assertEquals(methodParameter, accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)); + assertThat(accessor.getSessionId()).isEqualTo(sessionId); + assertThat(accessor.getDestination()).isEqualTo(destination); + assertThat(accessor.getContentType()).isEqualTo(MIME_TYPE); + assertThat(accessor.getSubscriptionId()).as("Subscription id should not be copied").isNull(); + assertThat(accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)).isEqualTo(methodParameter); } @Test @@ -316,7 +312,7 @@ public class SendToMethodReturnValueHandlerTests { verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); - assertEquals("/topic/dest.foo.bar", accessor.getDestination()); + assertThat(accessor.getDestination()).isEqualTo("/topic/dest.foo.bar"); } @Test @@ -334,12 +330,11 @@ public class SendToMethodReturnValueHandlerTests { MessageHeaders headers = captor.getValue(); SimpMessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers, SimpMessageHeaderAccessor.class); - assertNotNull(accessor); - assertTrue(accessor.isMutable()); - assertEquals("sess1", accessor.getSessionId()); - assertNull("Subscription id should not be copied", accessor.getSubscriptionId()); - assertEquals(this.noAnnotationsReturnType, - accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)); + assertThat(accessor).isNotNull(); + assertThat(accessor.isMutable()).isTrue(); + assertThat(accessor.getSessionId()).isEqualTo("sess1"); + assertThat(accessor.getSubscriptionId()).as("Subscription id should not be copied").isNull(); + assertThat(accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)).isEqualTo(this.noAnnotationsReturnType); } @Test @@ -354,14 +349,14 @@ public class SendToMethodReturnValueHandlerTests { verify(this.messageChannel, times(2)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); - assertNull(accessor.getSessionId()); - assertNull(accessor.getSubscriptionId()); - assertEquals("/user/" + user.getName() + "/dest1", accessor.getDestination()); + assertThat(accessor.getSessionId()).isNull(); + assertThat(accessor.getSubscriptionId()).isNull(); + assertThat(accessor.getDestination()).isEqualTo(("/user/" + user.getName() + "/dest1")); accessor = getCapturedAccessor(1); - assertNull(accessor.getSessionId()); - assertNull(accessor.getSubscriptionId()); - assertEquals("/user/" + user.getName() + "/dest2", accessor.getDestination()); + assertThat(accessor.getSessionId()).isNull(); + assertThat(accessor.getSubscriptionId()).isNull(); + assertThat(accessor.getDestination()).isEqualTo(("/user/" + user.getName() + "/dest2")); } @Test @@ -376,24 +371,24 @@ public class SendToMethodReturnValueHandlerTests { verify(this.messageChannel, times(4)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); - assertNull(accessor.getSessionId()); - assertNull(accessor.getSubscriptionId()); - assertEquals("/user/" + user.getName() + "/dest1", accessor.getDestination()); + assertThat(accessor.getSessionId()).isNull(); + assertThat(accessor.getSubscriptionId()).isNull(); + assertThat(accessor.getDestination()).isEqualTo(("/user/" + user.getName() + "/dest1")); accessor = getCapturedAccessor(1); - assertNull(accessor.getSessionId()); - assertNull(accessor.getSubscriptionId()); - assertEquals("/user/" + user.getName() + "/dest2", accessor.getDestination()); + assertThat(accessor.getSessionId()).isNull(); + assertThat(accessor.getSubscriptionId()).isNull(); + assertThat(accessor.getDestination()).isEqualTo(("/user/" + user.getName() + "/dest2")); accessor = getCapturedAccessor(2); - assertEquals("sess1", accessor.getSessionId()); - assertNull(accessor.getSubscriptionId()); - assertEquals("/dest1", accessor.getDestination()); + assertThat(accessor.getSessionId()).isEqualTo("sess1"); + assertThat(accessor.getSubscriptionId()).isNull(); + assertThat(accessor.getDestination()).isEqualTo("/dest1"); accessor = getCapturedAccessor(3); - assertEquals("sess1", accessor.getSessionId()); - assertNull(accessor.getSubscriptionId()); - assertEquals("/dest2", accessor.getDestination()); + assertThat(accessor.getSessionId()).isEqualTo("sess1"); + assertThat(accessor.getSubscriptionId()).isNull(); + assertThat(accessor.getDestination()).isEqualTo("/dest2"); } @Test // SPR-12170 @@ -414,8 +409,8 @@ public class SendToMethodReturnValueHandlerTests { verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor actual = getCapturedAccessor(0); - assertEquals(sessionId, actual.getSessionId()); - assertEquals("/topic/chat.message.filtered.roomA", actual.getDestination()); + assertThat(actual.getSessionId()).isEqualTo(sessionId); + assertThat(actual.getDestination()).isEqualTo("/topic/chat.message.filtered.roomA"); } @Test @@ -430,20 +425,18 @@ public class SendToMethodReturnValueHandlerTests { verify(this.messageChannel, times(2)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); - assertEquals(sessionId, accessor.getSessionId()); - assertEquals(MIME_TYPE, accessor.getContentType()); - assertEquals("/user/" + user.getName() + "/dest1", accessor.getDestination()); - assertNull("Subscription id should not be copied", accessor.getSubscriptionId()); - assertEquals(this.sendToUserInSessionReturnType, - accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)); + assertThat(accessor.getSessionId()).isEqualTo(sessionId); + assertThat(accessor.getContentType()).isEqualTo(MIME_TYPE); + assertThat(accessor.getDestination()).isEqualTo(("/user/" + user.getName() + "/dest1")); + assertThat(accessor.getSubscriptionId()).as("Subscription id should not be copied").isNull(); + assertThat(accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)).isEqualTo(this.sendToUserInSessionReturnType); accessor = getCapturedAccessor(1); - assertEquals(sessionId, accessor.getSessionId()); - assertEquals("/user/" + user.getName() + "/dest2", accessor.getDestination()); - assertEquals(MIME_TYPE, accessor.getContentType()); - assertNull("Subscription id should not be copied", accessor.getSubscriptionId()); - assertEquals(this.sendToUserInSessionReturnType, - accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)); + assertThat(accessor.getSessionId()).isEqualTo(sessionId); + assertThat(accessor.getDestination()).isEqualTo(("/user/" + user.getName() + "/dest2")); + assertThat(accessor.getContentType()).isEqualTo(MIME_TYPE); + assertThat(accessor.getSubscriptionId()).as("Subscription id should not be copied").isNull(); + assertThat(accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)).isEqualTo(this.sendToUserInSessionReturnType); } @Test @@ -458,10 +451,10 @@ public class SendToMethodReturnValueHandlerTests { verify(this.messageChannel, times(2)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); - assertEquals("/user/Me myself and I/dest1", accessor.getDestination()); + assertThat(accessor.getDestination()).isEqualTo("/user/Me myself and I/dest1"); accessor = getCapturedAccessor(1); - assertEquals("/user/Me myself and I/dest2", accessor.getDestination()); + assertThat(accessor.getDestination()).isEqualTo("/user/Me myself and I/dest2"); } @Test @@ -476,9 +469,9 @@ public class SendToMethodReturnValueHandlerTests { verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); - assertNull(accessor.getSessionId()); - assertNull(accessor.getSubscriptionId()); - assertEquals("/user/" + user.getName() + "/queue/dest", accessor.getDestination()); + assertThat(accessor.getSessionId()).isNull(); + assertThat(accessor.getSubscriptionId()).isNull(); + assertThat(accessor.getDestination()).isEqualTo(("/user/" + user.getName() + "/queue/dest")); } @Test @@ -492,7 +485,7 @@ public class SendToMethodReturnValueHandlerTests { verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); - assertEquals("/user/" + user.getName() + "/queue/dest.foo.bar", accessor.getDestination()); + assertThat(accessor.getDestination()).isEqualTo(("/user/" + user.getName() + "/queue/dest.foo.bar")); } @Test @@ -507,12 +500,11 @@ public class SendToMethodReturnValueHandlerTests { verify(this.messageChannel, times(1)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); - assertEquals(sessionId, accessor.getSessionId()); - assertEquals("/user/" + user.getName() + "/queue/dest", accessor.getDestination()); - assertEquals(MIME_TYPE, accessor.getContentType()); - assertNull("Subscription id should not be copied", accessor.getSubscriptionId()); - assertEquals(this.sendToUserInSessionDefaultDestReturnType, - accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)); + assertThat(accessor.getSessionId()).isEqualTo(sessionId); + assertThat(accessor.getDestination()).isEqualTo(("/user/" + user.getName() + "/queue/dest")); + assertThat(accessor.getContentType()).isEqualTo(MIME_TYPE); + assertThat(accessor.getSubscriptionId()).as("Subscription id should not be copied").isNull(); + assertThat(accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)).isEqualTo(this.sendToUserInSessionDefaultDestReturnType); } @Test @@ -526,12 +518,12 @@ public class SendToMethodReturnValueHandlerTests { verify(this.messageChannel, times(2)).send(this.messageCaptor.capture()); SimpMessageHeaderAccessor accessor = getCapturedAccessor(0); - assertEquals("/user/sess1/dest1", accessor.getDestination()); - assertEquals("sess1", accessor.getSessionId()); + assertThat(accessor.getDestination()).isEqualTo("/user/sess1/dest1"); + assertThat(accessor.getSessionId()).isEqualTo("sess1"); accessor = getCapturedAccessor(1); - assertEquals("/user/sess1/dest2", accessor.getDestination()); - assertEquals("sess1", accessor.getSessionId()); + assertThat(accessor.getDestination()).isEqualTo("/user/sess1/dest2"); + assertThat(accessor.getSessionId()).isEqualTo("sess1"); } @Test @@ -544,10 +536,10 @@ public class SendToMethodReturnValueHandlerTests { verify(this.messageChannel).send(this.messageCaptor.capture()); Message message = this.messageCaptor.getValue(); - assertNotNull(message); + assertThat(message).isNotNull(); String bytes = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); - assertEquals("{\"withView1\":\"with\"}", bytes); + assertThat(bytes).isEqualTo("{\"withView1\":\"with\"}"); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandlerTests.java index cea060e088e..a3599f1105c 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandlerTests.java @@ -68,10 +68,6 @@ import org.springframework.validation.Validator; import org.springframework.validation.annotation.Validated; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; @@ -128,9 +124,9 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("headers", this.testController.method); - assertEquals("bar", this.testController.arguments.get("foo")); - assertEquals("bar", ((Map) this.testController.arguments.get("headers")).get("foo")); + assertThat(this.testController.method).isEqualTo("headers"); + assertThat(this.testController.arguments.get("foo")).isEqualTo("bar"); + assertThat(((Map) this.testController.arguments.get("headers")).get("foo")).isEqualTo("bar"); } @Test @@ -140,9 +136,9 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("optionalHeaders", this.testController.method); - assertEquals("bar", this.testController.arguments.get("foo1")); - assertEquals("bar", this.testController.arguments.get("foo2")); + assertThat(this.testController.method).isEqualTo("optionalHeaders"); + assertThat(this.testController.arguments.get("foo1")).isEqualTo("bar"); + assertThat(this.testController.arguments.get("foo2")).isEqualTo("bar"); } @Test @@ -151,9 +147,9 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("optionalHeaders", this.testController.method); - assertNull(this.testController.arguments.get("foo1")); - assertNull(this.testController.arguments.get("foo2")); + assertThat(this.testController.method).isEqualTo("optionalHeaders"); + assertThat(this.testController.arguments.get("foo1")).isNull(); + assertThat(this.testController.arguments.get("foo2")).isNull(); } @Test @@ -162,9 +158,9 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("messageMappingDestinationVariable", this.testController.method); - assertEquals("bar", this.testController.arguments.get("foo")); - assertEquals("value", this.testController.arguments.get("name")); + assertThat(this.testController.method).isEqualTo("messageMappingDestinationVariable"); + assertThat(this.testController.arguments.get("foo")).isEqualTo("bar"); + assertThat(this.testController.arguments.get("name")).isEqualTo("value"); } @Test @@ -173,9 +169,9 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("subscribeEventDestinationVariable", this.testController.method); - assertEquals("bar", this.testController.arguments.get("foo")); - assertEquals("value", this.testController.arguments.get("name")); + assertThat(this.testController.method).isEqualTo("subscribeEventDestinationVariable"); + assertThat(this.testController.arguments.get("foo")).isEqualTo("bar"); + assertThat(this.testController.arguments.get("name")).isEqualTo("value"); } @Test @@ -184,9 +180,9 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("simpleBinding", this.testController.method); - assertTrue("should be bound to type long", this.testController.arguments.get("id") instanceof Long); - assertEquals(12L, this.testController.arguments.get("id")); + assertThat(this.testController.method).isEqualTo("simpleBinding"); + assertThat(this.testController.arguments.get("id") instanceof Long).as("should be bound to type long").isTrue(); + assertThat(this.testController.arguments.get("id")).isEqualTo(12L); } @Test @@ -195,7 +191,7 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("handleValidationException", this.testController.method); + assertThat(this.testController.method).isEqualTo("handleValidationException"); } @Test @@ -204,10 +200,10 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("handleExceptionWithHandlerMethodArg", this.testController.method); + assertThat(this.testController.method).isEqualTo("handleExceptionWithHandlerMethodArg"); HandlerMethod handlerMethod = (HandlerMethod) this.testController.arguments.get("handlerMethod"); - assertNotNull(handlerMethod); - assertEquals("illegalState", handlerMethod.getMethod().getName()); + assertThat(handlerMethod).isNotNull(); + assertThat(handlerMethod.getMethod().getName()).isEqualTo("illegalState"); } @Test @@ -216,10 +212,10 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("handleExceptionWithHandlerMethodArg", this.testController.method); + assertThat(this.testController.method).isEqualTo("handleExceptionWithHandlerMethodArg"); HandlerMethod handlerMethod = (HandlerMethod) this.testController.arguments.get("handlerMethod"); - assertNotNull(handlerMethod); - assertEquals("illegalStateCause", handlerMethod.getMethod().getName()); + assertThat(handlerMethod).isNotNull(); + assertThat(handlerMethod.getMethod().getName()).isEqualTo("illegalStateCause"); } @Test @@ -228,10 +224,10 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("handleErrorWithHandlerMethodArg", this.testController.method); + assertThat(this.testController.method).isEqualTo("handleErrorWithHandlerMethodArg"); HandlerMethod handlerMethod = (HandlerMethod) this.testController.arguments.get("handlerMethod"); - assertNotNull(handlerMethod); - assertEquals("errorAsThrowable", handlerMethod.getMethod().getName()); + assertThat(handlerMethod).isNotNull(); + assertThat(handlerMethod.getMethod().getName()).isEqualTo("errorAsThrowable"); } @Test @@ -247,7 +243,7 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("scope", this.testController.method); + assertThat(this.testController.method).isEqualTo("scope"); } @Test @@ -262,12 +258,12 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("handleFoo", controller.method); + assertThat(controller.method).isEqualTo("handleFoo"); message = createMessage("/app2/pre.foo"); this.messageHandler.handleMessage(message); - assertEquals("handleFoo", controller.method); + assertThat(controller.method).isEqualTo("handleFoo"); } @Test @@ -284,10 +280,10 @@ public class SimpAnnotationMethodMessageHandlerTests { Message message = createMessage("/app1/listenable-future/success"); this.messageHandler.handleMessage(message); - assertNotNull(controller.future); + assertThat(controller.future).isNotNull(); controller.future.run(); verify(this.converter).toMessage(this.payloadCaptor.capture(), any(MessageHeaders.class)); - assertEquals("foo", this.payloadCaptor.getValue()); + assertThat(this.payloadCaptor.getValue()).isEqualTo("foo"); } @Test @@ -305,7 +301,7 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.handleMessage(message); controller.future.run(); - assertTrue(controller.exceptionCaught); + assertThat(controller.exceptionCaught).isTrue(); } @Test @@ -322,10 +318,10 @@ public class SimpAnnotationMethodMessageHandlerTests { Message message = createMessage("/app1/completable-future"); this.messageHandler.handleMessage(message); - assertNotNull(controller.future); + assertThat(controller.future).isNotNull(); controller.future.complete("foo"); verify(this.converter).toMessage(this.payloadCaptor.capture(), any(MessageHeaders.class)); - assertEquals("foo", this.payloadCaptor.getValue()); + assertThat(this.payloadCaptor.getValue()).isEqualTo("foo"); } @Test @@ -343,7 +339,7 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.handleMessage(message); controller.future.completeExceptionally(new IllegalStateException()); - assertTrue(controller.exceptionCaught); + assertThat(controller.exceptionCaught).isTrue(); } @Test @@ -360,10 +356,10 @@ public class SimpAnnotationMethodMessageHandlerTests { Message message = createMessage("/app1/mono"); this.messageHandler.handleMessage(message); - assertNotNull(controller.mono); + assertThat(controller.mono).isNotNull(); controller.mono.onNext("foo"); verify(this.converter).toMessage(this.payloadCaptor.capture(), any(MessageHeaders.class)); - assertEquals("foo", this.payloadCaptor.getValue()); + assertThat(this.payloadCaptor.getValue()).isEqualTo("foo"); } @Test @@ -381,7 +377,7 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.handleMessage(message); controller.mono.onError(new IllegalStateException()); - assertTrue(controller.exceptionCaught); + assertThat(controller.exceptionCaught).isTrue(); } @Test @@ -398,7 +394,7 @@ public class SimpAnnotationMethodMessageHandlerTests { Message message = createMessage("/app1/flux"); this.messageHandler.handleMessage(message); - assertNotNull(controller.flux); + assertThat(controller.flux).isNotNull(); controller.flux.onNext("foo"); verify(this.converter, never()).toMessage(any(), any(MessageHeaders.class)); @@ -411,7 +407,7 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.registerHandler(this.testController); this.messageHandler.handleMessage(message); - assertEquals("placeholder", this.testController.method); + assertThat(this.testController.method).isEqualTo("placeholder"); } @@ -525,14 +521,14 @@ public class SimpAnnotationMethodMessageHandlerTests { public void handleExceptionWithHandlerMethodArg(IllegalStateException ex, HandlerMethod handlerMethod) { this.method = "handleExceptionWithHandlerMethodArg"; this.arguments.put("handlerMethod", handlerMethod); - assertEquals("my cause", ex.getMessage()); + assertThat(ex.getMessage()).isEqualTo("my cause"); } @MessageExceptionHandler public void handleErrorWithHandlerMethodArg(Error ex, HandlerMethod handlerMethod) { this.method = "handleErrorWithHandlerMethodArg"; this.arguments.put("handlerMethod", handlerMethod); - assertEquals("my cause", ex.getMessage()); + assertThat(ex.getMessage()).isEqualTo("my cause"); } @MessageMapping("/scope") diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SubscriptionMethodReturnValueHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SubscriptionMethodReturnValueHandlerTests.java index 581cee94bcc..20a1ecd53bf 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SubscriptionMethodReturnValueHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SubscriptionMethodReturnValueHandlerTests.java @@ -45,11 +45,7 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.util.MimeType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -113,9 +109,9 @@ public class SubscriptionMethodReturnValueHandlerTests { @Test public void supportsReturnType() throws Exception { - assertTrue(this.handler.supportsReturnType(this.subscribeEventReturnType)); - assertFalse(this.handler.supportsReturnType(this.subscribeEventSendToReturnType)); - assertFalse(this.handler.supportsReturnType(this.messageMappingReturnType)); + assertThat(this.handler.supportsReturnType(this.subscribeEventReturnType)).isTrue(); + assertThat(this.handler.supportsReturnType(this.subscribeEventSendToReturnType)).isFalse(); + assertThat(this.handler.supportsReturnType(this.messageMappingReturnType)).isFalse(); } @Test @@ -130,18 +126,18 @@ public class SubscriptionMethodReturnValueHandlerTests { this.handler.handleReturnValue(PAYLOAD, this.subscribeEventReturnType, inputMessage); verify(this.messageChannel).send(this.messageCaptor.capture()); - assertNotNull(this.messageCaptor.getValue()); + assertThat(this.messageCaptor.getValue()).isNotNull(); Message message = this.messageCaptor.getValue(); SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.wrap(message); - assertNull("SimpMessageHeaderAccessor should have disabled id", headerAccessor.getId()); - assertNull("SimpMessageHeaderAccessor should have disabled timestamp", headerAccessor.getTimestamp()); - assertEquals(sessionId, headerAccessor.getSessionId()); - assertEquals(subscriptionId, headerAccessor.getSubscriptionId()); - assertEquals(destination, headerAccessor.getDestination()); - assertEquals(MIME_TYPE, headerAccessor.getContentType()); - assertEquals(this.subscribeEventReturnType, headerAccessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)); + assertThat(headerAccessor.getId()).as("SimpMessageHeaderAccessor should have disabled id").isNull(); + assertThat(headerAccessor.getTimestamp()).as("SimpMessageHeaderAccessor should have disabled timestamp").isNull(); + assertThat(headerAccessor.getSessionId()).isEqualTo(sessionId); + assertThat(headerAccessor.getSubscriptionId()).isEqualTo(subscriptionId); + assertThat(headerAccessor.getDestination()).isEqualTo(destination); + assertThat(headerAccessor.getContentType()).isEqualTo(MIME_TYPE); + assertThat(headerAccessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)).isEqualTo(this.subscribeEventReturnType); } @Test @@ -163,11 +159,11 @@ public class SubscriptionMethodReturnValueHandlerTests { SimpMessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(captor.getValue(), SimpMessageHeaderAccessor.class); - assertNotNull(headerAccessor); - assertTrue(headerAccessor.isMutable()); - assertEquals(sessionId, headerAccessor.getSessionId()); - assertEquals(subscriptionId, headerAccessor.getSubscriptionId()); - assertEquals(this.subscribeEventReturnType, headerAccessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)); + assertThat(headerAccessor).isNotNull(); + assertThat(headerAccessor.isMutable()).isTrue(); + assertThat(headerAccessor.getSessionId()).isEqualTo(sessionId); + assertThat(headerAccessor.getSubscriptionId()).isEqualTo(subscriptionId); + assertThat(headerAccessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)).isEqualTo(this.subscribeEventReturnType); } @Test @@ -183,9 +179,9 @@ public class SubscriptionMethodReturnValueHandlerTests { verify(this.messageChannel).send(this.messageCaptor.capture()); Message message = this.messageCaptor.getValue(); - assertNotNull(message); + assertThat(message).isNotNull(); - assertEquals("{\"withView1\":\"with\"}", new String((byte[]) message.getPayload(), StandardCharsets.UTF_8)); + assertThat(new String((byte[]) message.getPayload(), StandardCharsets.UTF_8)).isEqualTo("{\"withView1\":\"with\"}"); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/BrokerMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/BrokerMessageHandlerTests.java index c6bb7f265cf..e51ec4cd036 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/BrokerMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/BrokerMessageHandlerTests.java @@ -32,9 +32,7 @@ import org.springframework.messaging.MessageChannel; import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.support.GenericMessage; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -56,44 +54,44 @@ public class BrokerMessageHandlerTests { @Test public void startShouldUpdateIsRunning() { - assertFalse(this.handler.isRunning()); + assertThat(this.handler.isRunning()).isFalse(); this.handler.start(); - assertTrue(this.handler.isRunning()); + assertThat(this.handler.isRunning()).isTrue(); } @Test public void stopShouldUpdateIsRunning() { this.handler.start(); - assertTrue(this.handler.isRunning()); + assertThat(this.handler.isRunning()).isTrue(); this.handler.stop(); - assertFalse(this.handler.isRunning()); + assertThat(this.handler.isRunning()).isFalse(); } @Test public void startAndStopShouldNotPublishBrokerAvailabilityEvents() { this.handler.start(); this.handler.stop(); - assertEquals(Collections.emptyList(), this.handler.availabilityEvents); + assertThat(this.handler.availabilityEvents).isEqualTo(Collections.emptyList()); } @Test public void handleMessageWhenBrokerNotRunning() { this.handler.handleMessage(new GenericMessage("payload")); - assertEquals(Collections.emptyList(), this.handler.messages); + assertThat(this.handler.messages).isEqualTo(Collections.emptyList()); } @Test public void publishBrokerAvailableEvent() { - assertFalse(this.handler.isBrokerAvailable()); - assertEquals(Collections.emptyList(), this.handler.availabilityEvents); + assertThat(this.handler.isBrokerAvailable()).isFalse(); + assertThat(this.handler.availabilityEvents).isEqualTo(Collections.emptyList()); this.handler.publishBrokerAvailableEvent(); - assertTrue(this.handler.isBrokerAvailable()); - assertEquals(Arrays.asList(true), this.handler.availabilityEvents); + assertThat(this.handler.isBrokerAvailable()).isTrue(); + assertThat(this.handler.availabilityEvents).isEqualTo(Arrays.asList(true)); } @Test @@ -102,19 +100,19 @@ public class BrokerMessageHandlerTests { this.handler.publishBrokerAvailableEvent(); this.handler.publishBrokerAvailableEvent(); - assertEquals(Arrays.asList(true), this.handler.availabilityEvents); + assertThat(this.handler.availabilityEvents).isEqualTo(Arrays.asList(true)); } @Test public void publishBrokerUnavailableEvent() { this.handler.publishBrokerAvailableEvent(); - assertTrue(this.handler.isBrokerAvailable()); + assertThat(this.handler.isBrokerAvailable()).isTrue(); this.handler.publishBrokerUnavailableEvent(); - assertFalse(this.handler.isBrokerAvailable()); + assertThat(this.handler.isBrokerAvailable()).isFalse(); - assertEquals(Arrays.asList(true, false), this.handler.availabilityEvents); + assertThat(this.handler.availabilityEvents).isEqualTo(Arrays.asList(true, false)); } @Test @@ -124,7 +122,7 @@ public class BrokerMessageHandlerTests { this.handler.publishBrokerUnavailableEvent(); this.handler.publishBrokerUnavailableEvent(); - assertEquals(Arrays.asList(true, false), this.handler.availabilityEvents); + assertThat(this.handler.availabilityEvents).isEqualTo(Arrays.asList(true, false)); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistryTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistryTests.java index 41186e612d8..1342b2cfda1 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistryTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistryTests.java @@ -30,8 +30,7 @@ import org.springframework.messaging.simp.SimpMessageType; import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for @@ -53,18 +52,18 @@ public class DefaultSubscriptionRegistryTests { this.registry.registerSubscription(subscribeMessage(null, subsId, dest)); MultiValueMap actual = this.registry.findSubscriptions(createMessage(dest)); - assertNotNull(actual); - assertEquals(0, actual.size()); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(0); this.registry.registerSubscription(subscribeMessage(sessId, null, dest)); actual = this.registry.findSubscriptions(createMessage(dest)); - assertNotNull(actual); - assertEquals(0, actual.size()); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(0); this.registry.registerSubscription(subscribeMessage(sessId, subsId, null)); actual = this.registry.findSubscriptions(createMessage(dest)); - assertNotNull(actual); - assertEquals(0, actual.size()); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(0); } @Test @@ -76,9 +75,9 @@ public class DefaultSubscriptionRegistryTests { this.registry.registerSubscription(subscribeMessage(sessId, subsId, dest)); MultiValueMap actual = this.registry.findSubscriptions(createMessage(dest)); - assertNotNull(actual); - assertEquals("Expected one element " + actual, 1, actual.size()); - assertEquals(Collections.singletonList(subsId), actual.get(sessId)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).as("Expected one element " + actual).isEqualTo(1); + assertThat(actual.get(sessId)).isEqualTo(Collections.singletonList(subsId)); } @Test @@ -92,9 +91,9 @@ public class DefaultSubscriptionRegistryTests { } MultiValueMap actual = this.registry.findSubscriptions(createMessage(dest)); - assertNotNull(actual); - assertEquals(1, actual.size()); - assertEquals(subscriptionIds, sort(actual.get(sessId))); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(1); + assertThat(sort(actual.get(sessId))).isEqualTo(subscriptionIds); } @Test @@ -110,11 +109,11 @@ public class DefaultSubscriptionRegistryTests { } MultiValueMap actual = this.registry.findSubscriptions(createMessage(dest)); - assertNotNull(actual); - assertEquals(3, actual.size()); - assertEquals(subscriptionIds, sort(actual.get(sessIds.get(0)))); - assertEquals(subscriptionIds, sort(actual.get(sessIds.get(1)))); - assertEquals(subscriptionIds, sort(actual.get(sessIds.get(2)))); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(3); + assertThat(sort(actual.get(sessIds.get(0)))).isEqualTo(subscriptionIds); + assertThat(sort(actual.get(sessIds.get(1)))).isEqualTo(subscriptionIds); + assertThat(sort(actual.get(sessIds.get(2)))).isEqualTo(subscriptionIds); } @Test @@ -126,9 +125,9 @@ public class DefaultSubscriptionRegistryTests { this.registry.registerSubscription(subscribeMessage(sessId, subsId, destPattern)); MultiValueMap actual = this.registry.findSubscriptions(createMessage(dest)); - assertNotNull(actual); - assertEquals("Expected one element " + actual, 1, actual.size()); - assertEquals(Collections.singletonList(subsId), actual.get(sessId)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).as("Expected one element " + actual).isEqualTo(1); + assertThat(actual.get(sessId)).isEqualTo(Collections.singletonList(subsId)); } @Test // SPR-11657 @@ -147,56 +146,56 @@ public class DefaultSubscriptionRegistryTests { this.registry.registerSubscription(subscribeMessage(sess1, subs1, "/topic/PRICE.STOCK.*.IBM")); MultiValueMap actual = this.registry.findSubscriptions(destNasdaqIbmMessage); - assertNotNull(actual); - assertEquals(1, actual.size()); - assertEquals(Arrays.asList(subs2, subs1), actual.get(sess1)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(1); + assertThat(actual.get(sess1)).isEqualTo(Arrays.asList(subs2, subs1)); this.registry.registerSubscription(subscribeMessage(sess2, subs1, destNasdaqIbm)); this.registry.registerSubscription(subscribeMessage(sess2, subs2, "/topic/PRICE.STOCK.NYSE.IBM")); this.registry.registerSubscription(subscribeMessage(sess2, subs3, "/topic/PRICE.STOCK.NASDAQ.GOOG")); actual = this.registry.findSubscriptions(destNasdaqIbmMessage); - assertNotNull(actual); - assertEquals(2, actual.size()); - assertEquals(Arrays.asList(subs2, subs1), actual.get(sess1)); - assertEquals(Collections.singletonList(subs1), actual.get(sess2)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(2); + assertThat(actual.get(sess1)).isEqualTo(Arrays.asList(subs2, subs1)); + assertThat(actual.get(sess2)).isEqualTo(Collections.singletonList(subs1)); this.registry.unregisterAllSubscriptions(sess1); actual = this.registry.findSubscriptions(destNasdaqIbmMessage); - assertNotNull(actual); - assertEquals(1, actual.size()); - assertEquals(Collections.singletonList(subs1), actual.get(sess2)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(1); + assertThat(actual.get(sess2)).isEqualTo(Collections.singletonList(subs1)); this.registry.registerSubscription(subscribeMessage(sess1, subs1, "/topic/PRICE.STOCK.*.IBM")); this.registry.registerSubscription(subscribeMessage(sess1, subs2, destNasdaqIbm)); actual = this.registry.findSubscriptions(destNasdaqIbmMessage); - assertNotNull(actual); - assertEquals(2, actual.size()); - assertEquals(Arrays.asList(subs1, subs2), actual.get(sess1)); - assertEquals(Collections.singletonList(subs1), actual.get(sess2)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(2); + assertThat(actual.get(sess1)).isEqualTo(Arrays.asList(subs1, subs2)); + assertThat(actual.get(sess2)).isEqualTo(Collections.singletonList(subs1)); this.registry.unregisterSubscription(unsubscribeMessage(sess1, subs2)); actual = this.registry.findSubscriptions(destNasdaqIbmMessage); - assertNotNull(actual); - assertEquals(2, actual.size()); - assertEquals(Collections.singletonList(subs1), actual.get(sess1)); - assertEquals(Collections.singletonList(subs1), actual.get(sess2)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(2); + assertThat(actual.get(sess1)).isEqualTo(Collections.singletonList(subs1)); + assertThat(actual.get(sess2)).isEqualTo(Collections.singletonList(subs1)); this.registry.unregisterSubscription(unsubscribeMessage(sess1, subs1)); actual = this.registry.findSubscriptions(destNasdaqIbmMessage); - assertNotNull(actual); - assertEquals(1, actual.size()); - assertEquals(Collections.singletonList(subs1), actual.get(sess2)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(1); + assertThat(actual.get(sess2)).isEqualTo(Collections.singletonList(subs1)); this.registry.unregisterSubscription(unsubscribeMessage(sess2, subs1)); actual = this.registry.findSubscriptions(destNasdaqIbmMessage); - assertNotNull(actual); - assertEquals(0, actual.size()); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(0); } @Test // SPR-11755 @@ -241,20 +240,20 @@ public class DefaultSubscriptionRegistryTests { this.registry.registerSubscription(subscribeMessage(sessId, subsId, destPattern)); Message message = createMessage("/topic/PRICE.STOCK.NASDAQ.IBM"); MultiValueMap actual = this.registry.findSubscriptions(message); - assertNotNull(actual); - assertEquals("Expected one element " + actual, 1, actual.size()); - assertEquals(Collections.singletonList(subsId), actual.get(sessId)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).as("Expected one element " + actual).isEqualTo(1); + assertThat(actual.get(sessId)).isEqualTo(Collections.singletonList(subsId)); message = createMessage("/topic/PRICE.STOCK.NASDAQ.MSFT"); actual = this.registry.findSubscriptions(message); - assertNotNull(actual); - assertEquals("Expected one element " + actual, 1, actual.size()); - assertEquals(Collections.singletonList(subsId), actual.get(sessId)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).as("Expected one element " + actual).isEqualTo(1); + assertThat(actual.get(sessId)).isEqualTo(Collections.singletonList(subsId)); message = createMessage("/topic/PRICE.STOCK.NASDAQ.VMW"); actual = this.registry.findSubscriptions(message); - assertNotNull(actual); - assertEquals("Expected no elements " + actual, 0, actual.size()); + assertThat(actual).isNotNull(); + assertThat(actual.size()).as("Expected no elements " + actual).isEqualTo(0); } @Test @@ -274,15 +273,15 @@ public class DefaultSubscriptionRegistryTests { Message message = MessageBuilder.createMessage("", accessor.getMessageHeaders()); MultiValueMap actual = this.registry.findSubscriptions(message); - assertNotNull(actual); - assertEquals(1, actual.size()); - assertEquals(Collections.singletonList(subscriptionId), actual.get(sessionId)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(1); + assertThat(actual.get(sessionId)).isEqualTo(Collections.singletonList(subscriptionId)); // Then without actual = this.registry.findSubscriptions(createMessage(destination)); - assertNotNull(actual); - assertEquals(0, actual.size()); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(0); } @Test @@ -301,9 +300,9 @@ public class DefaultSubscriptionRegistryTests { Message message = MessageBuilder.createMessage("", accessor.getMessageHeaders()); MultiValueMap actual = this.registry.findSubscriptions(message); - assertNotNull(actual); - assertEquals(1, actual.size()); - assertEquals(Collections.singletonList(subscriptionId), actual.get(sessionId)); + assertThat(actual).isNotNull(); + assertThat(actual.size()).isEqualTo(1); + assertThat(actual.get(sessionId)).isEqualTo(Collections.singletonList(subscriptionId)); } @Test // SPR-11931 @@ -312,22 +311,22 @@ public class DefaultSubscriptionRegistryTests { this.registry.registerSubscription(subscribeMessage("sess01", "subs02", "/foo")); MultiValueMap actual = this.registry.findSubscriptions(createMessage("/foo")); - assertNotNull(actual); - assertEquals("Expected 1 element", 1, actual.size()); - assertEquals(Arrays.asList("subs01", "subs02"), actual.get("sess01")); + assertThat(actual).isNotNull(); + assertThat(actual.size()).as("Expected 1 element").isEqualTo(1); + assertThat(actual.get("sess01")).isEqualTo(Arrays.asList("subs01", "subs02")); this.registry.unregisterSubscription(unsubscribeMessage("sess01", "subs01")); actual = this.registry.findSubscriptions(createMessage("/foo")); - assertNotNull(actual); - assertEquals("Expected 1 element", 1, actual.size()); - assertEquals(Collections.singletonList("subs02"), actual.get("sess01")); + assertThat(actual).isNotNull(); + assertThat(actual.size()).as("Expected 1 element").isEqualTo(1); + assertThat(actual.get("sess01")).isEqualTo(Collections.singletonList("subs02")); this.registry.unregisterSubscription(unsubscribeMessage("sess01", "subs02")); actual = this.registry.findSubscriptions(createMessage("/foo")); - assertNotNull(actual); - assertEquals("Expected no element", 0, actual.size()); + assertThat(actual).isNotNull(); + assertThat(actual.size()).as("Expected no element").isEqualTo(0); } @Test @@ -347,10 +346,10 @@ public class DefaultSubscriptionRegistryTests { this.registry.unregisterSubscription(unsubscribeMessage(sessIds.get(0), subscriptionIds.get(2))); MultiValueMap actual = this.registry.findSubscriptions(createMessage(dest)); - assertNotNull(actual); - assertEquals("Expected two elements: " + actual, 2, actual.size()); - assertEquals(subscriptionIds, sort(actual.get(sessIds.get(1)))); - assertEquals(subscriptionIds, sort(actual.get(sessIds.get(2)))); + assertThat(actual).isNotNull(); + assertThat(actual.size()).as("Expected two elements: " + actual).isEqualTo(2); + assertThat(sort(actual.get(sessIds.get(1)))).isEqualTo(subscriptionIds); + assertThat(sort(actual.get(sessIds.get(2)))).isEqualTo(subscriptionIds); } @Test @@ -369,9 +368,9 @@ public class DefaultSubscriptionRegistryTests { this.registry.unregisterAllSubscriptions(sessIds.get(1)); MultiValueMap actual = this.registry.findSubscriptions(createMessage(dest)); - assertNotNull(actual); - assertEquals("Expected one element: " + actual, 1, actual.size()); - assertEquals(subscriptionIds, sort(actual.get(sessIds.get(2)))); + assertThat(actual).isNotNull(); + assertThat(actual.size()).as("Expected one element: " + actual).isEqualTo(1); + assertThat(sort(actual.get(sessIds.get(2)))).isEqualTo(subscriptionIds); } @Test @@ -383,8 +382,8 @@ public class DefaultSubscriptionRegistryTests { @Test public void findSubscriptionsNoMatches() { MultiValueMap actual = this.registry.findSubscriptions(createMessage("/foo")); - assertNotNull(actual); - assertEquals("Expected no elements " + actual, 0, actual.size()); + assertThat(actual).isNotNull(); + assertThat(actual.size()).as("Expected no elements " + actual).isEqualTo(0); } @Test // SPR-12665 @@ -393,8 +392,8 @@ public class DefaultSubscriptionRegistryTests { this.registry.registerSubscription(subscribeMessage("sess2", "1", "/foo")); MultiValueMap subscriptions = this.registry.findSubscriptions(createMessage("/foo")); - assertNotNull(subscriptions); - assertEquals(2, subscriptions.size()); + assertThat(subscriptions).isNotNull(); + assertThat(subscriptions.size()).isEqualTo(2); Iterator>> iterator = subscriptions.entrySet().iterator(); iterator.next(); @@ -411,8 +410,8 @@ public class DefaultSubscriptionRegistryTests { this.registry.registerSubscription(subscribeMessage("sess1", "2", "/foo")); MultiValueMap allSubscriptions = this.registry.findSubscriptions(createMessage("/foo")); - assertNotNull(allSubscriptions); - assertEquals(1, allSubscriptions.size()); + assertThat(allSubscriptions).isNotNull(); + assertThat(allSubscriptions.size()).isEqualTo(1); Iterator iteratorValues = allSubscriptions.get("sess1").iterator(); iteratorValues.next(); @@ -429,14 +428,14 @@ public class DefaultSubscriptionRegistryTests { this.registry.registerSubscription(subscribeMessage("sess1", "1", "/foo")); this.registry.registerSubscription(subscribeMessage("sess1", "2", "/bar")); - assertEquals(1, this.registry.findSubscriptions(createMessage("/foo")).size()); - assertEquals(1, this.registry.findSubscriptions(createMessage("/bar")).size()); + assertThat(this.registry.findSubscriptions(createMessage("/foo")).size()).isEqualTo(1); + assertThat(this.registry.findSubscriptions(createMessage("/bar")).size()).isEqualTo(1); this.registry.registerSubscription(subscribeMessage("sess2", "1", "/foo")); this.registry.registerSubscription(subscribeMessage("sess2", "2", "/bar")); - assertEquals(2, this.registry.findSubscriptions(createMessage("/foo")).size()); - assertEquals(2, this.registry.findSubscriptions(createMessage("/bar")).size()); + assertThat(this.registry.findSubscriptions(createMessage("/foo")).size()).isEqualTo(2); + assertThat(this.registry.findSubscriptions(createMessage("/bar")).size()).isEqualTo(2); } private Message createMessage(String destination) { diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/OrderedMessageSenderTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/OrderedMessageSenderTests.java index c2646bfb129..8d95371bdee 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/OrderedMessageSenderTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/OrderedMessageSenderTests.java @@ -33,7 +33,7 @@ import org.springframework.messaging.support.ExecutorSubscribableChannel; import org.springframework.messaging.support.MessageBuilder; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link OrderedMessageSender}. @@ -112,7 +112,7 @@ public class OrderedMessageSenderTests { } latch.await(10, TimeUnit.SECONDS); - assertEquals("Done", result.get()); + assertThat(result.get()).isEqualTo("Done"); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java index 8924b8a0293..7ffcd239368 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java @@ -38,13 +38,8 @@ import org.springframework.messaging.simp.TestPrincipal; import org.springframework.messaging.support.MessageBuilder; import org.springframework.scheduling.TaskScheduler; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -107,12 +102,12 @@ public class SimpleBrokerMessageHandlerTests { this.messageHandler.handleMessage(createMessage("/bar", "message2")); verify(this.clientOutChannel, times(6)).send(this.messageCaptor.capture()); - assertTrue(messageCaptured("sess1", "sub1", "/foo")); - assertTrue(messageCaptured("sess1", "sub2", "/foo")); - assertTrue(messageCaptured("sess2", "sub1", "/foo")); - assertTrue(messageCaptured("sess2", "sub2", "/foo")); - assertTrue(messageCaptured("sess1", "sub3", "/bar")); - assertTrue(messageCaptured("sess2", "sub3", "/bar")); + assertThat(messageCaptured("sess1", "sub1", "/foo")).isTrue(); + assertThat(messageCaptured("sess1", "sub2", "/foo")).isTrue(); + assertThat(messageCaptured("sess2", "sub1", "/foo")).isTrue(); + assertThat(messageCaptured("sess2", "sub2", "/foo")).isTrue(); + assertThat(messageCaptured("sess1", "sub3", "/bar")).isTrue(); + assertThat(messageCaptured("sess2", "sub3", "/bar")).isTrue(); } @Test @@ -143,14 +138,14 @@ public class SimpleBrokerMessageHandlerTests { verify(this.clientOutChannel, times(4)).send(this.messageCaptor.capture()); Message captured = this.messageCaptor.getAllValues().get(2); - assertEquals(SimpMessageType.DISCONNECT_ACK, SimpMessageHeaderAccessor.getMessageType(captured.getHeaders())); - assertSame(message, captured.getHeaders().get(SimpMessageHeaderAccessor.DISCONNECT_MESSAGE_HEADER)); - assertEquals(sess1, SimpMessageHeaderAccessor.getSessionId(captured.getHeaders())); - assertEquals("joe", SimpMessageHeaderAccessor.getUser(captured.getHeaders()).getName()); + assertThat(SimpMessageHeaderAccessor.getMessageType(captured.getHeaders())).isEqualTo(SimpMessageType.DISCONNECT_ACK); + assertThat(captured.getHeaders().get(SimpMessageHeaderAccessor.DISCONNECT_MESSAGE_HEADER)).isSameAs(message); + assertThat(SimpMessageHeaderAccessor.getSessionId(captured.getHeaders())).isEqualTo(sess1); + assertThat(SimpMessageHeaderAccessor.getUser(captured.getHeaders()).getName()).isEqualTo("joe"); - assertTrue(messageCaptured(sess2, "sub1", "/foo")); - assertTrue(messageCaptured(sess2, "sub2", "/foo")); - assertTrue(messageCaptured(sess2, "sub3", "/bar")); + assertThat(messageCaptured(sess2, "sub1", "/foo")).isTrue(); + assertThat(messageCaptured(sess2, "sub2", "/foo")).isTrue(); + assertThat(messageCaptured(sess2, "sub3", "/bar")).isTrue(); } @Test @@ -161,20 +156,19 @@ public class SimpleBrokerMessageHandlerTests { Message connectAckMessage = this.messageCaptor.getValue(); SimpMessageHeaderAccessor connectAckHeaders = SimpMessageHeaderAccessor.wrap(connectAckMessage); - assertEquals(connectMessage, connectAckHeaders.getHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER)); - assertEquals(id, connectAckHeaders.getSessionId()); - assertEquals("joe", connectAckHeaders.getUser().getName()); - assertArrayEquals(new long[] {10000, 10000}, - SimpMessageHeaderAccessor.getHeartbeat(connectAckHeaders.getMessageHeaders())); + assertThat(connectAckHeaders.getHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER)).isEqualTo(connectMessage); + assertThat(connectAckHeaders.getSessionId()).isEqualTo(id); + assertThat(connectAckHeaders.getUser().getName()).isEqualTo("joe"); + assertThat(SimpMessageHeaderAccessor.getHeartbeat(connectAckHeaders.getMessageHeaders())).isEqualTo(new long[] {10000, 10000}); } @Test public void heartbeatValueWithAndWithoutTaskScheduler() { - assertNull(this.messageHandler.getHeartbeatValue()); + assertThat(this.messageHandler.getHeartbeatValue()).isNull(); this.messageHandler.setTaskScheduler(this.taskScheduler); - assertNotNull(this.messageHandler.getHeartbeatValue()); - assertArrayEquals(new long[] {10000, 10000}, this.messageHandler.getHeartbeatValue()); + assertThat(this.messageHandler.getHeartbeatValue()).isNotNull(); + assertThat(this.messageHandler.getHeartbeatValue()).isEqualTo(new long[] {10000, 10000}); } @Test @@ -222,7 +216,7 @@ public class SimpleBrokerMessageHandlerTests { ArgumentCaptor taskCaptor = ArgumentCaptor.forClass(Runnable.class); verify(this.taskScheduler).scheduleWithFixedDelay(taskCaptor.capture(), eq(1L)); Runnable heartbeatTask = taskCaptor.getValue(); - assertNotNull(heartbeatTask); + assertThat(heartbeatTask).isNotNull(); String id = "sess1"; TestPrincipal user = new TestPrincipal("joe"); @@ -234,14 +228,14 @@ public class SimpleBrokerMessageHandlerTests { verify(this.clientOutChannel, atLeast(2)).send(this.messageCaptor.capture()); List> messages = this.messageCaptor.getAllValues(); - assertEquals(2, messages.size()); + assertThat(messages.size()).isEqualTo(2); MessageHeaders headers = messages.get(0).getHeaders(); - assertEquals(SimpMessageType.CONNECT_ACK, headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)); + assertThat(headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)).isEqualTo(SimpMessageType.CONNECT_ACK); headers = messages.get(1).getHeaders(); - assertEquals(SimpMessageType.DISCONNECT_ACK, headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)); - assertEquals(id, headers.get(SimpMessageHeaderAccessor.SESSION_ID_HEADER)); - assertEquals(user, headers.get(SimpMessageHeaderAccessor.USER_HEADER)); + assertThat(headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)).isEqualTo(SimpMessageType.DISCONNECT_ACK); + assertThat(headers.get(SimpMessageHeaderAccessor.SESSION_ID_HEADER)).isEqualTo(id); + assertThat(headers.get(SimpMessageHeaderAccessor.USER_HEADER)).isEqualTo(user); } @Test @@ -253,7 +247,7 @@ public class SimpleBrokerMessageHandlerTests { ArgumentCaptor taskCaptor = ArgumentCaptor.forClass(Runnable.class); verify(this.taskScheduler).scheduleWithFixedDelay(taskCaptor.capture(), eq(1L)); Runnable heartbeatTask = taskCaptor.getValue(); - assertNotNull(heartbeatTask); + assertThat(heartbeatTask).isNotNull(); String id = "sess1"; TestPrincipal user = new TestPrincipal("joe"); @@ -265,14 +259,14 @@ public class SimpleBrokerMessageHandlerTests { verify(this.clientOutChannel, times(2)).send(this.messageCaptor.capture()); List> messages = this.messageCaptor.getAllValues(); - assertEquals(2, messages.size()); + assertThat(messages.size()).isEqualTo(2); MessageHeaders headers = messages.get(0).getHeaders(); - assertEquals(SimpMessageType.CONNECT_ACK, headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)); + assertThat(headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)).isEqualTo(SimpMessageType.CONNECT_ACK); headers = messages.get(1).getHeaders(); - assertEquals(SimpMessageType.HEARTBEAT, headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)); - assertEquals(id, headers.get(SimpMessageHeaderAccessor.SESSION_ID_HEADER)); - assertEquals(user, headers.get(SimpMessageHeaderAccessor.USER_HEADER)); + assertThat(headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)).isEqualTo(SimpMessageType.HEARTBEAT); + assertThat(headers.get(SimpMessageHeaderAccessor.SESSION_ID_HEADER)).isEqualTo(id); + assertThat(headers.get(SimpMessageHeaderAccessor.USER_HEADER)).isEqualTo(user); } @Test @@ -284,7 +278,7 @@ public class SimpleBrokerMessageHandlerTests { ArgumentCaptor taskCaptor = ArgumentCaptor.forClass(Runnable.class); verify(this.taskScheduler).scheduleWithFixedDelay(taskCaptor.capture(), eq(1L)); Runnable heartbeatTask = taskCaptor.getValue(); - assertNotNull(heartbeatTask); + assertThat(heartbeatTask).isNotNull(); String id = "sess1"; TestPrincipal user = new TestPrincipal("joe"); @@ -296,9 +290,8 @@ public class SimpleBrokerMessageHandlerTests { verify(this.clientOutChannel, times(1)).send(this.messageCaptor.capture()); List> messages = this.messageCaptor.getAllValues(); - assertEquals(1, messages.size()); - assertEquals(SimpMessageType.CONNECT_ACK, - messages.get(0).getHeaders().get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)); + assertThat(messages.size()).isEqualTo(1); + assertThat(messages.get(0).getHeaders().get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)).isEqualTo(SimpMessageType.CONNECT_ACK); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java index 56d6cd39d1b..5864d57e5d2 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java @@ -77,12 +77,6 @@ import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -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.mockito.Mockito.mock; /** @@ -101,10 +95,10 @@ public class MessageBrokerConfigurationTests { TestChannel channel = context.getBean("clientInboundChannel", TestChannel.class); Set handlers = channel.getSubscribers(); - assertEquals(3, handlers.size()); - assertTrue(handlers.contains(context.getBean(SimpAnnotationMethodMessageHandler.class))); - assertTrue(handlers.contains(context.getBean(UserDestinationMessageHandler.class))); - assertTrue(handlers.contains(context.getBean(SimpleBrokerMessageHandler.class))); + assertThat(handlers.size()).isEqualTo(3); + assertThat(handlers.contains(context.getBean(SimpAnnotationMethodMessageHandler.class))).isTrue(); + assertThat(handlers.contains(context.getBean(UserDestinationMessageHandler.class))).isTrue(); + assertThat(handlers.contains(context.getBean(SimpleBrokerMessageHandler.class))).isTrue(); } @Test @@ -114,10 +108,10 @@ public class MessageBrokerConfigurationTests { TestChannel channel = context.getBean("clientInboundChannel", TestChannel.class); Set handlers = channel.getSubscribers(); - assertEquals(3, handlers.size()); - assertTrue(handlers.contains(context.getBean(SimpAnnotationMethodMessageHandler.class))); - assertTrue(handlers.contains(context.getBean(UserDestinationMessageHandler.class))); - assertTrue(handlers.contains(context.getBean(StompBrokerRelayMessageHandler.class))); + assertThat(handlers.size()).isEqualTo(3); + assertThat(handlers.contains(context.getBean(SimpAnnotationMethodMessageHandler.class))).isTrue(); + assertThat(handlers.contains(context.getBean(UserDestinationMessageHandler.class))).isTrue(); + assertThat(handlers.contains(context.getBean(StompBrokerRelayMessageHandler.class))).isTrue(); } @Test @@ -126,13 +120,13 @@ public class MessageBrokerConfigurationTests { AbstractSubscribableChannel channel = context.getBean( "clientInboundChannel", AbstractSubscribableChannel.class); - assertEquals(3, channel.getInterceptors().size()); + assertThat(channel.getInterceptors().size()).isEqualTo(3); CustomThreadPoolTaskExecutor taskExecutor = context.getBean( "clientInboundChannelExecutor", CustomThreadPoolTaskExecutor.class); - assertEquals(11, taskExecutor.getCorePoolSize()); - assertEquals(12, taskExecutor.getMaxPoolSize()); - assertEquals(13, taskExecutor.getKeepAliveSeconds()); + assertThat(taskExecutor.getCorePoolSize()).isEqualTo(11); + assertThat(taskExecutor.getMaxPoolSize()).isEqualTo(12); + assertThat(taskExecutor.getKeepAliveSeconds()).isEqualTo(13); } @Test @@ -155,9 +149,9 @@ public class MessageBrokerConfigurationTests { message = channel.messages.get(0); headers = StompHeaderAccessor.wrap(message); - assertEquals(SimpMessageType.MESSAGE, headers.getMessageType()); - assertEquals("/foo", headers.getDestination()); - assertEquals("bar", new String((byte[]) message.getPayload())); + assertThat(headers.getMessageType()).isEqualTo(SimpMessageType.MESSAGE); + assertThat(headers.getDestination()).isEqualTo("/foo"); + assertThat(new String((byte[]) message.getPayload())).isEqualTo("bar"); } @Test @@ -188,9 +182,9 @@ public class MessageBrokerConfigurationTests { message = outboundChannel.messages.get(1); headers = StompHeaderAccessor.wrap(message); - assertEquals(SimpMessageType.MESSAGE, headers.getMessageType()); - assertEquals("/foo", headers.getDestination()); - assertEquals("bar", new String((byte[]) message.getPayload())); + assertThat(headers.getMessageType()).isEqualTo(SimpMessageType.MESSAGE); + assertThat(headers.getDestination()).isEqualTo("/foo"); + assertThat(new String((byte[]) message.getPayload())).isEqualTo("bar"); } @Test @@ -200,18 +194,18 @@ public class MessageBrokerConfigurationTests { AbstractSubscribableChannel channel = context.getBean( "clientOutboundChannel", AbstractSubscribableChannel.class); - assertEquals(4, channel.getInterceptors().size()); + assertThat(channel.getInterceptors().size()).isEqualTo(4); ThreadPoolTaskExecutor taskExecutor = context.getBean( "clientOutboundChannelExecutor", ThreadPoolTaskExecutor.class); - assertEquals(21, taskExecutor.getCorePoolSize()); - assertEquals(22, taskExecutor.getMaxPoolSize()); - assertEquals(23, taskExecutor.getKeepAliveSeconds()); + assertThat(taskExecutor.getCorePoolSize()).isEqualTo(21); + assertThat(taskExecutor.getMaxPoolSize()).isEqualTo(22); + assertThat(taskExecutor.getKeepAliveSeconds()).isEqualTo(23); SimpleBrokerMessageHandler broker = context.getBean("simpleBrokerMessageHandler", SimpleBrokerMessageHandler.class); - assertTrue(broker.isPreservePublishOrder()); + assertThat(broker.isPreservePublishOrder()).isTrue(); } @Test @@ -221,11 +215,11 @@ public class MessageBrokerConfigurationTests { TestChannel channel = context.getBean("brokerChannel", TestChannel.class); Set handlers = channel.getSubscribers(); - assertEquals(2, handlers.size()); - assertTrue(handlers.contains(context.getBean(UserDestinationMessageHandler.class))); - assertTrue(handlers.contains(context.getBean(SimpleBrokerMessageHandler.class))); + assertThat(handlers.size()).isEqualTo(2); + assertThat(handlers.contains(context.getBean(UserDestinationMessageHandler.class))).isTrue(); + assertThat(handlers.contains(context.getBean(SimpleBrokerMessageHandler.class))).isTrue(); - assertNull(channel.getExecutor()); + assertThat((Object) channel.getExecutor()).isNull(); } @Test @@ -235,9 +229,9 @@ public class MessageBrokerConfigurationTests { TestChannel channel = context.getBean("brokerChannel", TestChannel.class); Set handlers = channel.getSubscribers(); - assertEquals(2, handlers.size()); - assertTrue(handlers.contains(context.getBean(UserDestinationMessageHandler.class))); - assertTrue(handlers.contains(context.getBean(StompBrokerRelayMessageHandler.class))); + assertThat(handlers.size()).isEqualTo(2); + assertThat(handlers.contains(context.getBean(UserDestinationMessageHandler.class))).isTrue(); + assertThat(handlers.contains(context.getBean(StompBrokerRelayMessageHandler.class))).isTrue(); } @Test @@ -259,9 +253,9 @@ public class MessageBrokerConfigurationTests { message = channel.messages.get(0); headers = StompHeaderAccessor.wrap(message); - assertEquals(SimpMessageType.MESSAGE, headers.getMessageType()); - assertEquals("/bar", headers.getDestination()); - assertEquals("bar", new String((byte[]) message.getPayload())); + assertThat(headers.getMessageType()).isEqualTo(SimpMessageType.MESSAGE); + assertThat(headers.getDestination()).isEqualTo("/bar"); + assertThat(new String((byte[]) message.getPayload())).isEqualTo("bar"); } @Test @@ -271,14 +265,14 @@ public class MessageBrokerConfigurationTests { AbstractSubscribableChannel channel = context.getBean( "brokerChannel", AbstractSubscribableChannel.class); - assertEquals(4, channel.getInterceptors().size()); + assertThat(channel.getInterceptors().size()).isEqualTo(4); ThreadPoolTaskExecutor taskExecutor = context.getBean( "brokerChannelExecutor", ThreadPoolTaskExecutor.class); - assertEquals(31, taskExecutor.getCorePoolSize()); - assertEquals(32, taskExecutor.getMaxPoolSize()); - assertEquals(33, taskExecutor.getKeepAliveSeconds()); + assertThat(taskExecutor.getCorePoolSize()).isEqualTo(31); + assertThat(taskExecutor.getMaxPoolSize()).isEqualTo(32); + assertThat(taskExecutor.getKeepAliveSeconds()).isEqualTo(33); } @Test @@ -293,7 +287,7 @@ public class MessageBrokerConfigurationTests { assertThat(converters.get(2)).isInstanceOf(MappingJackson2MessageConverter.class); ContentTypeResolver resolver = ((MappingJackson2MessageConverter) converters.get(2)).getContentTypeResolver(); - assertEquals(MimeTypeUtils.APPLICATION_JSON, ((DefaultContentTypeResolver) resolver).getDefaultMimeType()); + assertThat(((DefaultContentTypeResolver) resolver).getDefaultMimeType()).isEqualTo(MimeTypeUtils.APPLICATION_JSON); } @Test @@ -302,17 +296,17 @@ public class MessageBrokerConfigurationTests { String name = "clientInboundChannelExecutor"; ThreadPoolTaskExecutor executor = context.getBean(name, ThreadPoolTaskExecutor.class); - assertEquals(Runtime.getRuntime().availableProcessors() * 2, executor.getCorePoolSize()); + assertThat(executor.getCorePoolSize()).isEqualTo(Runtime.getRuntime().availableProcessors() * 2); // No way to verify queue capacity name = "clientOutboundChannelExecutor"; executor = context.getBean(name, ThreadPoolTaskExecutor.class); - assertEquals(Runtime.getRuntime().availableProcessors() * 2, executor.getCorePoolSize()); + assertThat(executor.getCorePoolSize()).isEqualTo(Runtime.getRuntime().availableProcessors() * 2); name = "brokerChannelExecutor"; executor = context.getBean(name, ThreadPoolTaskExecutor.class); - assertEquals(0, executor.getCorePoolSize()); - assertEquals(1, executor.getMaxPoolSize()); + assertThat(executor.getCorePoolSize()).isEqualTo(0); + assertThat(executor.getMaxPoolSize()).isEqualTo(1); } @Test @@ -361,12 +355,12 @@ public class MessageBrokerConfigurationTests { context.getBean(SimpAnnotationMethodMessageHandler.class); List customResolvers = handler.getCustomArgumentResolvers(); - assertEquals(1, customResolvers.size()); - assertTrue(handler.getArgumentResolvers().contains(customResolvers.get(0))); + assertThat(customResolvers.size()).isEqualTo(1); + assertThat(handler.getArgumentResolvers().contains(customResolvers.get(0))).isTrue(); List customHandlers = handler.getCustomReturnValueHandlers(); - assertEquals(1, customHandlers.size()); - assertTrue(handler.getReturnValueHandlers().contains(customHandlers.get(0))); + assertThat(customHandlers.size()).isEqualTo(1); + assertThat(handler.getReturnValueHandlers().contains(customHandlers.get(0))).isTrue(); } @Test @@ -388,7 +382,7 @@ public class MessageBrokerConfigurationTests { } }; - assertSame(validator, config.simpValidator()); + assertThat(config.simpValidator()).isSameAs(validator); } @Test @@ -418,16 +412,16 @@ public class MessageBrokerConfigurationTests { SimpleBrokerMessageHandler broker = context.getBean(SimpleBrokerMessageHandler.class); DefaultSubscriptionRegistry registry = (DefaultSubscriptionRegistry) broker.getSubscriptionRegistry(); - assertEquals("a.a", registry.getPathMatcher().combine("a", "a")); + assertThat(registry.getPathMatcher().combine("a", "a")).isEqualTo("a.a"); PathMatcher pathMatcher = context.getBean(SimpAnnotationMethodMessageHandler.class).getPathMatcher(); - assertEquals("a.a", pathMatcher.combine("a", "a")); + assertThat(pathMatcher.combine("a", "a")).isEqualTo("a.a"); DefaultUserDestinationResolver resolver = context.getBean(DefaultUserDestinationResolver.class); - assertNotNull(resolver); - assertEquals(false, resolver.isRemoveLeadingSlash()); + assertThat(resolver).isNotNull(); + assertThat(resolver.isRemoveLeadingSlash()).isEqualTo(false); } @Test @@ -436,7 +430,7 @@ public class MessageBrokerConfigurationTests { SimpleBrokerMessageHandler broker = context.getBean(SimpleBrokerMessageHandler.class); DefaultSubscriptionRegistry registry = (DefaultSubscriptionRegistry) broker.getSubscriptionRegistry(); - assertEquals(8192, registry.getCacheLimit()); + assertThat(registry.getCacheLimit()).isEqualTo(8192); } @Test @@ -444,8 +438,8 @@ public class MessageBrokerConfigurationTests { ApplicationContext context = loadConfig(CustomConfig.class); SimpUserRegistry registry = context.getBean(SimpUserRegistry.class); - assertTrue(registry instanceof TestUserRegistry); - assertEquals(99, ((TestUserRegistry) registry).getOrder()); + assertThat(registry instanceof TestUserRegistry).isTrue(); + assertThat(((TestUserRegistry) registry).getOrder()).isEqualTo(99); } @Test @@ -453,19 +447,19 @@ public class MessageBrokerConfigurationTests { ApplicationContext context = loadConfig(BrokerRelayConfig.class); SimpUserRegistry userRegistry = context.getBean(SimpUserRegistry.class); - assertEquals(MultiServerUserRegistry.class, userRegistry.getClass()); + assertThat(userRegistry.getClass()).isEqualTo(MultiServerUserRegistry.class); UserDestinationMessageHandler handler1 = context.getBean(UserDestinationMessageHandler.class); - assertEquals("/topic/unresolved-user-destination", handler1.getBroadcastDestination()); + assertThat(handler1.getBroadcastDestination()).isEqualTo("/topic/unresolved-user-destination"); UserRegistryMessageHandler handler2 = context.getBean(UserRegistryMessageHandler.class); - assertEquals("/topic/simp-user-registry", handler2.getBroadcastDestination()); + assertThat(handler2.getBroadcastDestination()).isEqualTo("/topic/simp-user-registry"); StompBrokerRelayMessageHandler relay = context.getBean(StompBrokerRelayMessageHandler.class); - assertNotNull(relay.getSystemSubscriptions()); - assertEquals(2, relay.getSystemSubscriptions().size()); - assertSame(handler1, relay.getSystemSubscriptions().get("/topic/unresolved-user-destination")); - assertSame(handler2, relay.getSystemSubscriptions().get("/topic/simp-user-registry")); + assertThat(relay.getSystemSubscriptions()).isNotNull(); + assertThat(relay.getSystemSubscriptions().size()).isEqualTo(2); + assertThat(relay.getSystemSubscriptions().get("/topic/unresolved-user-destination")).isSameAs(handler1); + assertThat(relay.getSystemSubscriptions().get("/topic/simp-user-registry")).isSameAs(handler2); } @Test @@ -473,14 +467,14 @@ public class MessageBrokerConfigurationTests { ApplicationContext context = loadConfig(SimpleBrokerConfig.class); SimpUserRegistry registry = context.getBean(SimpUserRegistry.class); - assertNotNull(registry); - assertNotEquals(MultiServerUserRegistry.class, registry.getClass()); + assertThat(registry).isNotNull(); + assertThat(registry.getClass()).isNotEqualTo(MultiServerUserRegistry.class); UserDestinationMessageHandler handler = context.getBean(UserDestinationMessageHandler.class); - assertNull(handler.getBroadcastDestination()); + assertThat((Object) handler.getBroadcastDestination()).isNull(); Object nullBean = context.getBean("userRegistryMessageHandler"); - assertTrue(nullBean.equals(null)); + assertThat(nullBean.equals(null)).isTrue(); } @Test // SPR-16275 @@ -519,13 +513,14 @@ public class MessageBrokerConfigurationTests { message = MessageBuilder.createMessage("123".getBytes(), headers.getMessageHeaders()); inChannel.send(message); - assertEquals(2, outChannel.messages.size()); + assertThat(outChannel.messages.size()).isEqualTo(2); Message outputMessage = outChannel.messages.remove(1); headers = StompHeaderAccessor.wrap(outputMessage); - assertEquals(SimpMessageType.MESSAGE, headers.getMessageType()); - assertEquals(expectLeadingSlash ? "/queue.q1-usersess1" : "queue.q1-usersess1", headers.getDestination()); - assertEquals("123", new String((byte[]) outputMessage.getPayload())); + assertThat(headers.getMessageType()).isEqualTo(SimpMessageType.MESSAGE); + Object expecteds1 = expectLeadingSlash ? "/queue.q1-usersess1" : "queue.q1-usersess1"; + assertThat(headers.getDestination()).isEqualTo(expecteds1); + assertThat(new String((byte[]) outputMessage.getPayload())).isEqualTo("123"); outChannel.messages.clear(); // 3. Send message via broker channel @@ -535,13 +530,14 @@ public class MessageBrokerConfigurationTests { accessor.setSessionId("sess1"); template.convertAndSendToUser("sess1", "queue.q1", "456".getBytes(), accessor.getMessageHeaders()); - assertEquals(1, outChannel.messages.size()); + assertThat(outChannel.messages.size()).isEqualTo(1); outputMessage = outChannel.messages.remove(0); headers = StompHeaderAccessor.wrap(outputMessage); - assertEquals(SimpMessageType.MESSAGE, headers.getMessageType()); - assertEquals(expectLeadingSlash ? "/queue.q1-usersess1" : "queue.q1-usersess1", headers.getDestination()); - assertEquals("456", new String((byte[]) outputMessage.getPayload())); + assertThat(headers.getMessageType()).isEqualTo(SimpMessageType.MESSAGE); + Object expecteds = expectLeadingSlash ? "/queue.q1-usersess1" : "queue.q1-usersess1"; + assertThat(headers.getDestination()).isEqualTo(expecteds); + assertThat(new String((byte[]) outputMessage.getPayload())).isEqualTo("456"); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/config/StompBrokerRelayRegistrationTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/config/StompBrokerRelayRegistrationTests.java index 72a7011ed43..687fcc3ea29 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/config/StompBrokerRelayRegistrationTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/config/StompBrokerRelayRegistrationTests.java @@ -24,8 +24,7 @@ import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.simp.stomp.StompBrokerRelayMessageHandler; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for @@ -53,14 +52,14 @@ public class StompBrokerRelayRegistrationTests { StompBrokerRelayMessageHandler handler = registration.getMessageHandler(new StubMessageChannel()); - assertArrayEquals(prefixes, StringUtils.toStringArray(handler.getDestinationPrefixes())); - assertEquals("clientlogin", handler.getClientLogin()); - assertEquals("clientpasscode", handler.getClientPasscode()); - assertEquals("syslogin", handler.getSystemLogin()); - assertEquals("syspasscode", handler.getSystemPasscode()); - assertEquals(123, handler.getSystemHeartbeatReceiveInterval()); - assertEquals(456, handler.getSystemHeartbeatSendInterval()); - assertEquals("example.org", handler.getVirtualHost()); + assertThat(StringUtils.toStringArray(handler.getDestinationPrefixes())).isEqualTo(prefixes); + assertThat(handler.getClientLogin()).isEqualTo("clientlogin"); + assertThat(handler.getClientPasscode()).isEqualTo("clientpasscode"); + assertThat(handler.getSystemLogin()).isEqualTo("syslogin"); + assertThat(handler.getSystemPasscode()).isEqualTo("syspasscode"); + assertThat(handler.getSystemHeartbeatReceiveInterval()).isEqualTo(123); + assertThat(handler.getSystemHeartbeatSendInterval()).isEqualTo(456); + assertThat(handler.getVirtualHost()).isEqualTo("example.org"); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/BufferingStompDecoderTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/BufferingStompDecoderTests.java index 873ce160003..c8358c52e18 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/BufferingStompDecoderTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/BufferingStompDecoderTests.java @@ -25,9 +25,8 @@ import org.junit.Test; import org.springframework.messaging.Message; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * Unit tests for {@link BufferingStompDecoder}. @@ -46,11 +45,11 @@ public class BufferingStompDecoderTests { String chunk = "SEND\na:alpha\n\nMessage body\0"; List> messages = stompDecoder.decode(toByteBuffer(chunk)); - assertEquals(1, messages.size()); - assertEquals("Message body", new String(messages.get(0).getPayload())); + assertThat(messages.size()).isEqualTo(1); + assertThat(new String(messages.get(0).getPayload())).isEqualTo("Message body"); - assertEquals(0, stompDecoder.getBufferSize()); - assertNull(stompDecoder.getExpectedContentLength()); + assertThat(stompDecoder.getBufferSize()).isEqualTo(0); + assertThat(stompDecoder.getExpectedContentLength()).isNull(); } @Test @@ -60,14 +59,14 @@ public class BufferingStompDecoderTests { String chunk2 = " body\0"; List> messages = stompDecoder.decode(toByteBuffer(chunk1)); - assertEquals(Collections.>emptyList(), messages); + assertThat(messages).isEqualTo(Collections.>emptyList()); messages = stompDecoder.decode(toByteBuffer(chunk2)); - assertEquals(1, messages.size()); - assertEquals("Message body", new String(messages.get(0).getPayload())); + assertThat(messages.size()).isEqualTo(1); + assertThat(new String(messages.get(0).getPayload())).isEqualTo("Message body"); - assertEquals(0, stompDecoder.getBufferSize()); - assertNull(stompDecoder.getExpectedContentLength()); + assertThat(stompDecoder.getBufferSize()).isEqualTo(0); + assertThat(stompDecoder.getExpectedContentLength()).isNull(); } @Test @@ -76,12 +75,12 @@ public class BufferingStompDecoderTests { String chunk = "SEND\na:alpha\n\nPayload1\0" + "SEND\na:alpha\n\nPayload2\0"; List> messages = stompDecoder.decode(toByteBuffer(chunk)); - assertEquals(2, messages.size()); - assertEquals("Payload1", new String(messages.get(0).getPayload())); - assertEquals("Payload2", new String(messages.get(1).getPayload())); + assertThat(messages.size()).isEqualTo(2); + assertThat(new String(messages.get(0).getPayload())).isEqualTo("Payload1"); + assertThat(new String(messages.get(1).getPayload())).isEqualTo("Payload2"); - assertEquals(0, stompDecoder.getBufferSize()); - assertNull(stompDecoder.getExpectedContentLength()); + assertThat(stompDecoder.getBufferSize()).isEqualTo(0); + assertThat(stompDecoder.getExpectedContentLength()).isNull(); } @Test @@ -91,26 +90,26 @@ public class BufferingStompDecoderTests { String chunk1 = "SEND\na:alpha\n\nPayload1\0SEND\ncontent-length:" + contentLength + "\n"; List> messages = stompDecoder.decode(toByteBuffer(chunk1)); - assertEquals(1, messages.size()); - assertEquals("Payload1", new String(messages.get(0).getPayload())); + assertThat(messages.size()).isEqualTo(1); + assertThat(new String(messages.get(0).getPayload())).isEqualTo("Payload1"); - assertEquals(23, stompDecoder.getBufferSize()); - assertEquals(contentLength, (int) stompDecoder.getExpectedContentLength()); + assertThat(stompDecoder.getBufferSize()).isEqualTo(23); + assertThat((int) stompDecoder.getExpectedContentLength()).isEqualTo(contentLength); String chunk2 = "\nPayload2a"; messages = stompDecoder.decode(toByteBuffer(chunk2)); - assertEquals(0, messages.size()); - assertEquals(33, stompDecoder.getBufferSize()); - assertEquals(contentLength, (int) stompDecoder.getExpectedContentLength()); + assertThat(messages.size()).isEqualTo(0); + assertThat(stompDecoder.getBufferSize()).isEqualTo(33); + assertThat((int) stompDecoder.getExpectedContentLength()).isEqualTo(contentLength); String chunk3 = "-Payload2b\0"; messages = stompDecoder.decode(toByteBuffer(chunk3)); - assertEquals(1, messages.size()); - assertEquals("Payload2a-Payload2b", new String(messages.get(0).getPayload())); - assertEquals(0, stompDecoder.getBufferSize()); - assertNull(stompDecoder.getExpectedContentLength()); + assertThat(messages.size()).isEqualTo(1); + assertThat(new String(messages.get(0).getPayload())).isEqualTo("Payload2a-Payload2b"); + assertThat(stompDecoder.getBufferSize()).isEqualTo(0); + assertThat(stompDecoder.getExpectedContentLength()).isNull(); } @Test @@ -119,26 +118,26 @@ public class BufferingStompDecoderTests { String chunk1 = "SEND\na:alpha\n\nPayload1\0SEND\na:alpha\n"; List> messages = stompDecoder.decode(toByteBuffer(chunk1)); - assertEquals(1, messages.size()); - assertEquals("Payload1", new String(messages.get(0).getPayload())); + assertThat(messages.size()).isEqualTo(1); + assertThat(new String(messages.get(0).getPayload())).isEqualTo("Payload1"); - assertEquals(13, stompDecoder.getBufferSize()); - assertNull(stompDecoder.getExpectedContentLength()); + assertThat(stompDecoder.getBufferSize()).isEqualTo(13); + assertThat(stompDecoder.getExpectedContentLength()).isNull(); String chunk2 = "\nPayload2a"; messages = stompDecoder.decode(toByteBuffer(chunk2)); - assertEquals(0, messages.size()); - assertEquals(23, stompDecoder.getBufferSize()); - assertNull(stompDecoder.getExpectedContentLength()); + assertThat(messages.size()).isEqualTo(0); + assertThat(stompDecoder.getBufferSize()).isEqualTo(23); + assertThat(stompDecoder.getExpectedContentLength()).isNull(); String chunk3 = "-Payload2b\0"; messages = stompDecoder.decode(toByteBuffer(chunk3)); - assertEquals(1, messages.size()); - assertEquals("Payload2a-Payload2b", new String(messages.get(0).getPayload())); - assertEquals(0, stompDecoder.getBufferSize()); - assertNull(stompDecoder.getExpectedContentLength()); + assertThat(messages.size()).isEqualTo(1); + assertThat(new String(messages.get(0).getPayload())).isEqualTo("Payload2a-Payload2b"); + assertThat(stompDecoder.getBufferSize()).isEqualTo(0); + assertThat(stompDecoder.getExpectedContentLength()).isNull(); } @Test @@ -147,11 +146,11 @@ public class BufferingStompDecoderTests { String chunk1 = "SEND\na:alpha\n\nPayload1\0SEND\ncontent-length:129\n"; List> messages = stompDecoder.decode(toByteBuffer(chunk1)); - assertEquals("We should have gotten the 1st message", 1, messages.size()); - assertEquals("Payload1", new String(messages.get(0).getPayload())); + assertThat(messages.size()).as("We should have gotten the 1st message").isEqualTo(1); + assertThat(new String(messages.get(0).getPayload())).isEqualTo("Payload1"); - assertEquals(24, stompDecoder.getBufferSize()); - assertEquals(129, (int) stompDecoder.getExpectedContentLength()); + assertThat(stompDecoder.getBufferSize()).isEqualTo(24); + assertThat((int) stompDecoder.getExpectedContentLength()).isEqualTo(129); String chunk2 = "\nPayload2a"; assertThatExceptionOfType(StompConversionException.class).isThrownBy(() -> @@ -172,7 +171,7 @@ public class BufferingStompDecoderTests { String chunk = "MESSAG"; List> messages = stompDecoder.decode(toByteBuffer(chunk)); - assertEquals(0, messages.size()); + assertThat(messages.size()).isEqualTo(0); } // SPR-13416 @@ -183,7 +182,7 @@ public class BufferingStompDecoderTests { String chunk = "SEND\na:long\\"; List> messages = stompDecoder.decode(toByteBuffer(chunk)); - assertEquals(0, messages.size()); + assertThat(messages.size()).isEqualTo(0); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/DefaultStompSessionTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/DefaultStompSessionTests.java index 893c845f4a8..e4e0387a762 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/DefaultStompSessionTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/DefaultStompSessionTests.java @@ -45,12 +45,6 @@ import org.springframework.util.concurrent.SettableListenableFuture; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.notNull; @@ -99,31 +93,31 @@ public class DefaultStompSessionTests { @Test public void afterConnected() { - assertFalse(this.session.isConnected()); + assertThat(this.session.isConnected()).isFalse(); this.connectHeaders.setHost("my-host"); this.connectHeaders.setHeartbeat(new long[] {11, 12}); this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals(StompCommand.CONNECT, accessor.getCommand()); - assertEquals("my-host", accessor.getHost()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.CONNECT); + assertThat(accessor.getHost()).isEqualTo("my-host"); assertThat(accessor.getAcceptVersion()).containsExactly("1.1", "1.2"); - assertArrayEquals(new long[] {11, 12}, accessor.getHeartbeat()); + assertThat(accessor.getHeartbeat()).isEqualTo(new long[] {11, 12}); } @Test // SPR-16844 public void afterConnectedWithSpecificVersion() { - assertFalse(this.session.isConnected()); + assertThat(this.session.isConnected()).isFalse(); this.connectHeaders.setAcceptVersion(new String[] {"1.1"}); this.session.afterConnected(this.connection); Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals(StompCommand.CONNECT, accessor.getCommand()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.CONNECT); assertThat(accessor.getAcceptVersion()).containsExactly("1.1"); } @@ -138,7 +132,7 @@ public class DefaultStompSessionTests { @Test public void handleConnectedFrame() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); this.connectHeaders.setHeartbeat(new long[] {10000, 10000}); @@ -156,7 +150,7 @@ public class DefaultStompSessionTests { @Test public void heartbeatValues() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); this.connectHeaders.setHeartbeat(new long[] {10000, 10000}); @@ -168,11 +162,11 @@ public class DefaultStompSessionTests { ArgumentCaptor writeInterval = ArgumentCaptor.forClass(Long.class); verify(this.connection).onWriteInactivity(any(Runnable.class), writeInterval.capture()); - assertEquals(20000, (long) writeInterval.getValue()); + assertThat((long) writeInterval.getValue()).isEqualTo(20000); ArgumentCaptor readInterval = ArgumentCaptor.forClass(Long.class); verify(this.connection).onReadInactivity(any(Runnable.class), readInterval.capture()); - assertEquals(60000, (long) readInterval.getValue()); + assertThat((long) readInterval.getValue()).isEqualTo(60000); } @Test @@ -211,8 +205,8 @@ public class DefaultStompSessionTests { Runnable writeTask = writeTaskCaptor.getValue(); Runnable readTask = readTaskCaptor.getValue(); - assertNotNull(writeTask); - assertNotNull(readTask); + assertThat(writeTask).isNotNull(); + assertThat(readTask).isNotNull(); writeTask.run(); StompHeaderAccessor accessor = StompHeaderAccessor.createForHeartbeat(); @@ -306,7 +300,7 @@ public class DefaultStompSessionTests { @Test public void handleMessageFrameWithConversionException() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); StompFrameHandler frameHandler = mock(StompFrameHandler.class); String destination = "/topic/foo"; @@ -353,7 +347,7 @@ public class DefaultStompSessionTests { @Test public void send() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); String destination = "/topic/foo"; String payload = "sample payload"; @@ -361,21 +355,22 @@ public class DefaultStompSessionTests { Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals(StompCommand.SEND, accessor.getCommand()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.SEND); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertEquals(stompHeaders.toString(), 2, stompHeaders.size()); + assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(2); - assertEquals(destination, stompHeaders.getDestination()); - assertEquals(new MimeType("text", "plain", StandardCharsets.UTF_8), stompHeaders.getContentType()); - assertEquals(-1, stompHeaders.getContentLength()); // StompEncoder isn't involved - assertEquals(payload, new String(message.getPayload(), StandardCharsets.UTF_8)); + assertThat(stompHeaders.getDestination()).isEqualTo(destination); + assertThat(stompHeaders.getContentType()).isEqualTo(new MimeType("text", "plain", StandardCharsets.UTF_8)); + // StompEncoder isn't involved + assertThat(stompHeaders.getContentLength()).isEqualTo(-1); + assertThat(new String(message.getPayload(), StandardCharsets.UTF_8)).isEqualTo(payload); } @Test public void sendWithReceipt() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); this.session.setTaskScheduler(mock(TaskScheduler.class)); this.session.setAutoReceipt(true); @@ -383,7 +378,7 @@ public class DefaultStompSessionTests { Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertNotNull(accessor.getReceipt()); + assertThat(accessor.getReceipt()).isNotNull(); StompHeaders stompHeaders = new StompHeaders(); stompHeaders.setDestination("/topic/foo"); @@ -392,13 +387,13 @@ public class DefaultStompSessionTests { message = this.messageCaptor.getValue(); accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals("my-receipt", accessor.getReceipt()); + assertThat(accessor.getReceipt()).isEqualTo("my-receipt"); } @Test public void sendWithConversionException() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); StompHeaders stompHeaders = new StompHeaders(); stompHeaders.setDestination("/topic/foo"); @@ -412,7 +407,7 @@ public class DefaultStompSessionTests { @Test public void sendWithExecutionException() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); IllegalStateException exception = new IllegalStateException("simulated exception"); SettableListenableFuture future = new SettableListenableFuture<>(); @@ -427,7 +422,7 @@ public class DefaultStompSessionTests { @Test public void subscribe() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); String destination = "/topic/foo"; StompFrameHandler frameHandler = mock(StompFrameHandler.class); @@ -435,18 +430,18 @@ public class DefaultStompSessionTests { Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals(StompCommand.SUBSCRIBE, accessor.getCommand()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.SUBSCRIBE); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertEquals(stompHeaders.toString(), 2, stompHeaders.size()); - assertEquals(destination, stompHeaders.getDestination()); - assertEquals(subscription.getSubscriptionId(), stompHeaders.getId()); + assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(2); + assertThat(stompHeaders.getDestination()).isEqualTo(destination); + assertThat(stompHeaders.getId()).isEqualTo(subscription.getSubscriptionId()); } @Test public void subscribeWithHeaders() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); String subscriptionId = "123"; String destination = "/topic/foo"; @@ -457,22 +452,22 @@ public class DefaultStompSessionTests { StompFrameHandler frameHandler = mock(StompFrameHandler.class); Subscription subscription = this.session.subscribe(stompHeaders, frameHandler); - assertEquals(subscriptionId, subscription.getSubscriptionId()); + assertThat(subscription.getSubscriptionId()).isEqualTo(subscriptionId); Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals(StompCommand.SUBSCRIBE, accessor.getCommand()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.SUBSCRIBE); stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertEquals(stompHeaders.toString(), 2, stompHeaders.size()); - assertEquals(destination, stompHeaders.getDestination()); - assertEquals(subscriptionId, stompHeaders.getId()); + assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(2); + assertThat(stompHeaders.getDestination()).isEqualTo(destination); + assertThat(stompHeaders.getId()).isEqualTo(subscriptionId); } @Test public void unsubscribe() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); String destination = "/topic/foo"; StompFrameHandler frameHandler = mock(StompFrameHandler.class); @@ -481,17 +476,17 @@ public class DefaultStompSessionTests { Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals(StompCommand.UNSUBSCRIBE, accessor.getCommand()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.UNSUBSCRIBE); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertEquals(stompHeaders.toString(), 1, stompHeaders.size()); - assertEquals(subscription.getSubscriptionId(), stompHeaders.getId()); + assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(1); + assertThat(stompHeaders.getId()).isEqualTo(subscription.getSubscriptionId()); } @Test // SPR-15131 public void unsubscribeWithCustomHeader() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); String headerName = "durable-subscription-name"; String headerValue = "123"; @@ -508,46 +503,46 @@ public class DefaultStompSessionTests { Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals(StompCommand.UNSUBSCRIBE, accessor.getCommand()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.UNSUBSCRIBE); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertEquals(stompHeaders.toString(), 2, stompHeaders.size()); - assertEquals(subscription.getSubscriptionId(), stompHeaders.getId()); - assertEquals(headerValue, stompHeaders.getFirst(headerName)); + assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(2); + assertThat(stompHeaders.getId()).isEqualTo(subscription.getSubscriptionId()); + assertThat(stompHeaders.getFirst(headerName)).isEqualTo(headerValue); } @Test public void ack() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); String messageId = "123"; this.session.acknowledge(messageId, true); Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals(StompCommand.ACK, accessor.getCommand()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.ACK); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertEquals(stompHeaders.toString(), 1, stompHeaders.size()); - assertEquals(messageId, stompHeaders.getId()); + assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(1); + assertThat(stompHeaders.getId()).isEqualTo(messageId); } @Test public void nack() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); String messageId = "123"; this.session.acknowledge(messageId, false); Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals(StompCommand.NACK, accessor.getCommand()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.NACK); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertEquals(stompHeaders.toString(), 1, stompHeaders.size()); - assertEquals(messageId, stompHeaders.getId()); + assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(1); + assertThat(stompHeaders.getId()).isEqualTo(messageId); } @Test @@ -563,15 +558,15 @@ public class DefaultStompSessionTests { Subscription subscription = this.session.subscribe(headers, mock(StompFrameHandler.class)); subscription.addReceiptTask(() -> received.set(true)); - assertNull(received.get()); + assertThat((Object) received.get()).isNull(); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.RECEIPT); accessor.setReceiptId("my-receipt"); accessor.setLeaveMutable(true); this.session.handleMessage(MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders())); - assertNotNull(received.get()); - assertTrue(received.get()); + assertThat(received.get()).isNotNull(); + assertThat(received.get()).isTrue(); } @Test @@ -593,8 +588,8 @@ public class DefaultStompSessionTests { subscription.addReceiptTask(() -> received.set(true)); - assertNotNull(received.get()); - assertTrue(received.get()); + assertThat(received.get()).isNotNull(); + assertThat(received.get()).isTrue(); } @Test @@ -619,12 +614,12 @@ public class DefaultStompSessionTests { ArgumentCaptor taskCaptor = ArgumentCaptor.forClass(Runnable.class); verify(taskScheduler).schedule(taskCaptor.capture(), (Date) notNull()); Runnable scheduledTask = taskCaptor.getValue(); - assertNotNull(scheduledTask); + assertThat(scheduledTask).isNotNull(); - assertNull(notReceived.get()); + assertThat((Object) notReceived.get()).isNull(); scheduledTask.run(); - assertTrue(notReceived.get()); + assertThat(notReceived.get()).isTrue(); verify(future).cancel(true); verifyNoMoreInteractions(future); } @@ -632,10 +627,10 @@ public class DefaultStompSessionTests { @Test public void disconnect() { this.session.afterConnected(this.connection); - assertTrue(this.session.isConnected()); + assertThat(this.session.isConnected()).isTrue(); this.session.disconnect(); - assertFalse(this.session.isConnected()); + assertThat(this.session.isConnected()).isFalse(); verifyNoMoreInteractions(this.sessionHandler); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java index 4e06b868ee5..8313c9f589c 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/ReactorNettyTcpStompClientTests.java @@ -41,7 +41,6 @@ import org.springframework.util.SocketUtils; import org.springframework.util.concurrent.ListenableFuture; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; /** * Integration tests for {@link ReactorNettyTcpStompClient}. @@ -110,18 +109,18 @@ public class ReactorNettyTcpStompClientTests { ConsumingHandler consumingHandler2 = new ConsumingHandler(destination); ListenableFuture consumerFuture2 = this.client.connect(consumingHandler2); - assertTrue(consumingHandler1.awaitForSubscriptions(5000)); - assertTrue(consumingHandler2.awaitForSubscriptions(5000)); + assertThat(consumingHandler1.awaitForSubscriptions(5000)).isTrue(); + assertThat(consumingHandler2.awaitForSubscriptions(5000)).isTrue(); ProducingHandler producingHandler = new ProducingHandler(); producingHandler.addToSend(destination, "foo1"); producingHandler.addToSend(destination, "foo2"); ListenableFuture producerFuture = this.client.connect(producingHandler); - assertTrue(consumingHandler1.awaitForMessageCount(2, 5000)); + assertThat(consumingHandler1.awaitForMessageCount(2, 5000)).isTrue(); assertThat(consumingHandler1.getReceived()).containsExactly("foo1", "foo2"); - assertTrue(consumingHandler2.awaitForMessageCount(2, 5000)); + assertThat(consumingHandler2.awaitForMessageCount(2, 5000)).isTrue(); assertThat(consumingHandler2.getReceived()).containsExactly("foo1", "foo2"); consumerFuture1.get().disconnect(); diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java index ca4085bfeec..7883c7e852f 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java @@ -49,10 +49,8 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.Assert; import org.springframework.util.SocketUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * Integration tests for {@link StompBrokerRelayMessageHandler} running against ActiveMQ. @@ -140,7 +138,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests { } }); this.activeMQBroker.stop(); - assertTrue("Broker did not stop", latch.await(5, TimeUnit.SECONDS)); + assertThat(latch.await(5, TimeUnit.SECONDS)).as("Broker did not stop").isTrue(); logger.debug("Broker stopped"); } @@ -263,8 +261,8 @@ public class StompBrokerRelayMessageHandlerIntegrationTests { public void expectBrokerAvailabilityEvent(boolean isBrokerAvailable) throws InterruptedException { BrokerAvailabilityEvent event = this.eventQueue.poll(20000, TimeUnit.MILLISECONDS); - assertNotNull("Times out waiting for BrokerAvailabilityEvent[" + isBrokerAvailable + "]", event); - assertEquals(isBrokerAvailable, event.isBrokerAvailable()); + assertThat(event).as("Times out waiting for BrokerAvailabilityEvent[" + isBrokerAvailable + "]").isNotNull(); + assertThat(event.isBrokerAvailable()).isEqualTo(isBrokerAvailable); } } @@ -286,9 +284,9 @@ public class StompBrokerRelayMessageHandlerIntegrationTests { new ArrayList<>(Arrays.asList(messageExchanges)); while (expectedMessages.size() > 0) { Message message = this.queue.poll(10000, TimeUnit.MILLISECONDS); - assertNotNull("Timed out waiting for messages, expected [" + expectedMessages + "]", message); + assertThat(message).as("Timed out waiting for messages, expected [" + expectedMessages + "]").isNotNull(); MessageExchange match = findMatch(expectedMessages, message); - assertNotNull("Unexpected message=" + message + ", expected [" + expectedMessages + "]", match); + assertThat(match).as("Unexpected message=" + message + ", expected [" + expectedMessages + "]").isNotNull(); expectedMessages.remove(match); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerTests.java index 08321390cd6..f330a1696e0 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerTests.java @@ -41,10 +41,7 @@ import org.springframework.messaging.tcp.TcpOperations; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureTask; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -90,17 +87,17 @@ public class StompBrokerRelayMessageHandlerTests { this.brokerRelay.start(); this.brokerRelay.handleMessage(connectMessage("sess1", "joe")); - assertEquals(2, this.tcpClient.getSentMessages().size()); + assertThat(this.tcpClient.getSentMessages().size()).isEqualTo(2); StompHeaderAccessor headers1 = this.tcpClient.getSentHeaders(0); - assertEquals(StompCommand.CONNECT, headers1.getCommand()); - assertEquals(StompBrokerRelayMessageHandler.SYSTEM_SESSION_ID, headers1.getSessionId()); - assertEquals("ABC", headers1.getHost()); + assertThat(headers1.getCommand()).isEqualTo(StompCommand.CONNECT); + assertThat(headers1.getSessionId()).isEqualTo(StompBrokerRelayMessageHandler.SYSTEM_SESSION_ID); + assertThat(headers1.getHost()).isEqualTo("ABC"); StompHeaderAccessor headers2 = this.tcpClient.getSentHeaders(1); - assertEquals(StompCommand.CONNECT, headers2.getCommand()); - assertEquals("sess1", headers2.getSessionId()); - assertEquals("ABC", headers2.getHost()); + assertThat(headers2.getCommand()).isEqualTo(StompCommand.CONNECT); + assertThat(headers2.getSessionId()).isEqualTo("sess1"); + assertThat(headers2.getHost()).isEqualTo("ABC"); } @Test @@ -114,17 +111,17 @@ public class StompBrokerRelayMessageHandlerTests { this.brokerRelay.start(); this.brokerRelay.handleMessage(connectMessage("sess1", "joe")); - assertEquals(2, this.tcpClient.getSentMessages().size()); + assertThat(this.tcpClient.getSentMessages().size()).isEqualTo(2); StompHeaderAccessor headers1 = this.tcpClient.getSentHeaders(0); - assertEquals(StompCommand.CONNECT, headers1.getCommand()); - assertEquals("syslogin", headers1.getLogin()); - assertEquals("syspasscode", headers1.getPasscode()); + assertThat(headers1.getCommand()).isEqualTo(StompCommand.CONNECT); + assertThat(headers1.getLogin()).isEqualTo("syslogin"); + assertThat(headers1.getPasscode()).isEqualTo("syspasscode"); StompHeaderAccessor headers2 = this.tcpClient.getSentHeaders(1); - assertEquals(StompCommand.CONNECT, headers2.getCommand()); - assertEquals("clientlogin", headers2.getLogin()); - assertEquals("clientpasscode", headers2.getPasscode()); + assertThat(headers2.getCommand()).isEqualTo(StompCommand.CONNECT); + assertThat(headers2.getLogin()).isEqualTo("clientlogin"); + assertThat(headers2.getPasscode()).isEqualTo("clientpasscode"); } @Test @@ -137,10 +134,10 @@ public class StompBrokerRelayMessageHandlerTests { headers.setDestination("/user/daisy/foo"); this.brokerRelay.handleMessage(MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders())); - assertEquals(1, this.tcpClient.getSentMessages().size()); + assertThat(this.tcpClient.getSentMessages().size()).isEqualTo(1); StompHeaderAccessor headers1 = this.tcpClient.getSentHeaders(0); - assertEquals(StompCommand.CONNECT, headers1.getCommand()); - assertEquals(StompBrokerRelayMessageHandler.SYSTEM_SESSION_ID, headers1.getSessionId()); + assertThat(headers1.getCommand()).isEqualTo(StompCommand.CONNECT); + assertThat(headers1.getSessionId()).isEqualTo(StompBrokerRelayMessageHandler.SYSTEM_SESSION_ID); } @Test @@ -149,16 +146,16 @@ public class StompBrokerRelayMessageHandlerTests { this.brokerRelay.start(); this.brokerRelay.handleMessage(connectMessage("sess1", "joe")); - assertEquals(2, this.tcpClient.getSentMessages().size()); - assertEquals(StompCommand.CONNECT, this.tcpClient.getSentHeaders(0).getCommand()); - assertEquals(StompCommand.CONNECT, this.tcpClient.getSentHeaders(1).getCommand()); + assertThat(this.tcpClient.getSentMessages().size()).isEqualTo(2); + assertThat(this.tcpClient.getSentHeaders(0).getCommand()).isEqualTo(StompCommand.CONNECT); + assertThat(this.tcpClient.getSentHeaders(1).getCommand()).isEqualTo(StompCommand.CONNECT); this.tcpClient.handleMessage(message(StompCommand.MESSAGE, null, null, null)); Message message = this.outboundChannel.getMessages().get(0); StompHeaderAccessor accessor = StompHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals("sess1", accessor.getSessionId()); - assertEquals("joe", accessor.getUser().getName()); + assertThat(accessor.getSessionId()).isEqualTo("sess1"); + assertThat(accessor.getUser().getName()).isEqualTo("joe"); } // SPR-12820 @@ -172,31 +169,31 @@ public class StompBrokerRelayMessageHandlerTests { Message message = this.outboundChannel.getMessages().get(0); StompHeaderAccessor accessor = StompHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals(StompCommand.ERROR, accessor.getCommand()); - assertEquals("sess1", accessor.getSessionId()); - assertEquals("joe", accessor.getUser().getName()); - assertEquals("Broker not available.", accessor.getMessage()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.ERROR); + assertThat(accessor.getSessionId()).isEqualTo("sess1"); + assertThat(accessor.getUser().getName()).isEqualTo("joe"); + assertThat(accessor.getMessage()).isEqualTo("Broker not available."); } @Test public void sendAfterBrokerUnavailable() throws Exception { this.brokerRelay.start(); - assertEquals(1, this.brokerRelay.getConnectionCount()); + assertThat(this.brokerRelay.getConnectionCount()).isEqualTo(1); this.brokerRelay.handleMessage(connectMessage("sess1", "joe")); - assertEquals(2, this.brokerRelay.getConnectionCount()); + assertThat(this.brokerRelay.getConnectionCount()).isEqualTo(2); this.brokerRelay.stopInternal(); this.brokerRelay.handleMessage(message(StompCommand.SEND, "sess1", "joe", "/foo")); - assertEquals(1, this.brokerRelay.getConnectionCount()); + assertThat(this.brokerRelay.getConnectionCount()).isEqualTo(1); Message message = this.outboundChannel.getMessages().get(0); StompHeaderAccessor accessor = StompHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertEquals(StompCommand.ERROR, accessor.getCommand()); - assertEquals("sess1", accessor.getSessionId()); - assertEquals("joe", accessor.getUser().getName()); - assertEquals("Broker not available.", accessor.getMessage()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.ERROR); + assertThat(accessor.getSessionId()).isEqualTo("sess1"); + assertThat(accessor.getUser().getName()).isEqualTo("joe"); + assertThat(accessor.getMessage()).isEqualTo("Broker not available."); } @Test @@ -211,17 +208,17 @@ public class StompBrokerRelayMessageHandlerTests { MessageHeaders headers = accessor.getMessageHeaders(); this.tcpClient.handleMessage(MessageBuilder.createMessage(new byte[0], headers)); - assertEquals(2, this.tcpClient.getSentMessages().size()); - assertEquals(StompCommand.CONNECT, this.tcpClient.getSentHeaders(0).getCommand()); - assertEquals(StompCommand.SUBSCRIBE, this.tcpClient.getSentHeaders(1).getCommand()); - assertEquals("/topic/foo", this.tcpClient.getSentHeaders(1).getDestination()); + assertThat(this.tcpClient.getSentMessages().size()).isEqualTo(2); + assertThat(this.tcpClient.getSentHeaders(0).getCommand()).isEqualTo(StompCommand.CONNECT); + assertThat(this.tcpClient.getSentHeaders(1).getCommand()).isEqualTo(StompCommand.SUBSCRIBE); + assertThat(this.tcpClient.getSentHeaders(1).getDestination()).isEqualTo("/topic/foo"); Message message = message(StompCommand.MESSAGE, null, null, "/topic/foo"); this.tcpClient.handleMessage(message); ArgumentCaptor captor = ArgumentCaptor.forClass(Message.class); verify(handler).handleMessage(captor.capture()); - assertSame(message, captor.getValue()); + assertThat(captor.getValue()).isSameAs(message); } private Message connectMessage(String sessionId, String user) { @@ -282,10 +279,10 @@ public class StompBrokerRelayMessageHandlerTests { } public StompHeaderAccessor getSentHeaders(int index) { - assertTrue("Size: " + getSentMessages().size(), getSentMessages().size() > index); + assertThat(getSentMessages().size() > index).as("Size: " + getSentMessages().size()).isTrue(); Message message = getSentMessages().get(index); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - assertNotNull(accessor); + assertThat(accessor).isNotNull(); return accessor; } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompClientSupportTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompClientSupportTests.java index ca6018f947d..9beff04582a 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompClientSupportTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompClientSupportTests.java @@ -18,11 +18,8 @@ package org.springframework.messaging.simp.stomp; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link StompClientSupport}. @@ -47,24 +44,24 @@ public class StompClientSupportTests { @Test public void defaultHeartbeatValue() throws Exception { - assertArrayEquals(new long[] {10000, 10000}, this.stompClient.getDefaultHeartbeat()); + assertThat(this.stompClient.getDefaultHeartbeat()).isEqualTo(new long[] {10000, 10000}); } @Test public void isDefaultHeartbeatEnabled() throws Exception { - assertArrayEquals(new long[] {10000, 10000}, this.stompClient.getDefaultHeartbeat()); - assertTrue(this.stompClient.isDefaultHeartbeatEnabled()); + assertThat(this.stompClient.getDefaultHeartbeat()).isEqualTo(new long[] {10000, 10000}); + assertThat(this.stompClient.isDefaultHeartbeatEnabled()).isTrue(); this.stompClient.setDefaultHeartbeat(new long[] {0, 0}); - assertFalse(this.stompClient.isDefaultHeartbeatEnabled()); + assertThat(this.stompClient.isDefaultHeartbeatEnabled()).isFalse(); } @Test public void processConnectHeadersDefault() throws Exception { StompHeaders connectHeaders = this.stompClient.processConnectHeaders(null); - assertNotNull(connectHeaders); - assertArrayEquals(new long[] {10000, 10000}, connectHeaders.getHeartbeat()); + assertThat(connectHeaders).isNotNull(); + assertThat(connectHeaders.getHeartbeat()).isEqualTo(new long[] {10000, 10000}); } @Test @@ -74,8 +71,8 @@ public class StompClientSupportTests { connectHeaders.setHeartbeat(new long[] {15000, 15000}); connectHeaders = this.stompClient.processConnectHeaders(connectHeaders); - assertNotNull(connectHeaders); - assertArrayEquals(new long[] {15000, 15000}, connectHeaders.getHeartbeat()); + assertThat(connectHeaders).isNotNull(); + assertThat(connectHeaders.getHeartbeat()).isEqualTo(new long[] {15000, 15000}); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompCommandTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompCommandTests.java index d6f9d86b6c6..9e66fb4e277 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompCommandTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompCommandTests.java @@ -25,8 +25,7 @@ import org.junit.Test; import org.springframework.messaging.simp.SimpMessageType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -66,35 +65,35 @@ public class StompCommandTests { if (simp == null) { simp = SimpMessageType.OTHER; } - assertSame(simp, stompCommand.getMessageType()); + assertThat(stompCommand.getMessageType()).isSameAs(simp); } } @Test public void requiresDestination() throws Exception { for (StompCommand stompCommand : StompCommand.values()) { - assertEquals(destinationRequired.contains(stompCommand), stompCommand.requiresDestination()); + assertThat(stompCommand.requiresDestination()).isEqualTo(destinationRequired.contains(stompCommand)); } } @Test public void requiresSubscriptionId() throws Exception { for (StompCommand stompCommand : StompCommand.values()) { - assertEquals(subscriptionIdRequired.contains(stompCommand), stompCommand.requiresSubscriptionId()); + assertThat(stompCommand.requiresSubscriptionId()).isEqualTo(subscriptionIdRequired.contains(stompCommand)); } } @Test public void requiresContentLength() throws Exception { for (StompCommand stompCommand : StompCommand.values()) { - assertEquals(contentLengthRequired.contains(stompCommand), stompCommand.requiresContentLength()); + assertThat(stompCommand.requiresContentLength()).isEqualTo(contentLengthRequired.contains(stompCommand)); } } @Test public void isBodyAllowed() throws Exception { for (StompCommand stompCommand : StompCommand.values()) { - assertEquals(bodyAllowed.contains(stompCommand), stompCommand.isBodyAllowed()); + assertThat(stompCommand.isBodyAllowed()).isEqualTo(bodyAllowed.contains(stompCommand)); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompDecoderTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompDecoderTests.java index b7c92868fc7..bf520856151 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompDecoderTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompDecoderTests.java @@ -26,9 +26,8 @@ import org.springframework.messaging.Message; import org.springframework.messaging.simp.SimpMessageType; import org.springframework.util.InvalidMimeTypeException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * Test fixture for {@link StompDecoder}. @@ -46,9 +45,9 @@ public class StompDecoderTests { Message frame = decode("DISCONNECT\r\n\r\n\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); - assertEquals(StompCommand.DISCONNECT, headers.getCommand()); - assertEquals(0, headers.toNativeHeaderMap().size()); - assertEquals(0, frame.getPayload().length); + assertThat(headers.getCommand()).isEqualTo(StompCommand.DISCONNECT); + assertThat(headers.toNativeHeaderMap().size()).isEqualTo(0); + assertThat(frame.getPayload().length).isEqualTo(0); } @Test @@ -56,9 +55,9 @@ public class StompDecoderTests { Message frame = decode("DISCONNECT\n\n\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); - assertEquals(StompCommand.DISCONNECT, headers.getCommand()); - assertEquals(0, headers.toNativeHeaderMap().size()); - assertEquals(0, frame.getPayload().length); + assertThat(headers.getCommand()).isEqualTo(StompCommand.DISCONNECT); + assertThat(headers.toNativeHeaderMap().size()).isEqualTo(0); + assertThat(frame.getPayload().length).isEqualTo(0); } @Test @@ -69,13 +68,13 @@ public class StompDecoderTests { Message frame = decode("CONNECT\n" + accept + host + "\n\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); - assertEquals(StompCommand.CONNECT, headers.getCommand()); + assertThat(headers.getCommand()).isEqualTo(StompCommand.CONNECT); - assertEquals(2, headers.toNativeHeaderMap().size()); - assertEquals("1.1", headers.getFirstNativeHeader("accept-version")); - assertEquals("github.org", headers.getHost()); + assertThat(headers.toNativeHeaderMap().size()).isEqualTo(2); + assertThat(headers.getFirstNativeHeader("accept-version")).isEqualTo("1.1"); + assertThat(headers.getHost()).isEqualTo("github.org"); - assertEquals(0, frame.getPayload().length); + assertThat(frame.getPayload().length).isEqualTo(0); } @Test @@ -83,13 +82,13 @@ public class StompDecoderTests { Message frame = decode("SEND\ndestination:test\n\nThe body of the message\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); - assertEquals(StompCommand.SEND, headers.getCommand()); + assertThat(headers.getCommand()).isEqualTo(StompCommand.SEND); - assertEquals(headers.toNativeHeaderMap().toString(), 1, headers.toNativeHeaderMap().size()); - assertEquals("test", headers.getDestination()); + assertThat(headers.toNativeHeaderMap().size()).as(headers.toNativeHeaderMap().toString()).isEqualTo(1); + assertThat(headers.getDestination()).isEqualTo("test"); String bodyText = new String(frame.getPayload()); - assertEquals("The body of the message", bodyText); + assertThat(bodyText).isEqualTo("The body of the message"); } @Test @@ -97,13 +96,13 @@ public class StompDecoderTests { Message message = decode("SEND\ncontent-length:23\n\nThe body of the message\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); - assertEquals(StompCommand.SEND, headers.getCommand()); + assertThat(headers.getCommand()).isEqualTo(StompCommand.SEND); - assertEquals(1, headers.toNativeHeaderMap().size()); - assertEquals(Integer.valueOf(23), headers.getContentLength()); + assertThat(headers.toNativeHeaderMap().size()).isEqualTo(1); + assertThat(headers.getContentLength()).isEqualTo(Integer.valueOf(23)); String bodyText = new String(message.getPayload()); - assertEquals("The body of the message", bodyText); + assertThat(bodyText).isEqualTo("The body of the message"); } // SPR-11528 @@ -113,13 +112,13 @@ public class StompDecoderTests { Message message = decode("SEND\ncontent-length:-1\n\nThe body of the message\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); - assertEquals(StompCommand.SEND, headers.getCommand()); + assertThat(headers.getCommand()).isEqualTo(StompCommand.SEND); - assertEquals(1, headers.toNativeHeaderMap().size()); - assertEquals(Integer.valueOf(-1), headers.getContentLength()); + assertThat(headers.toNativeHeaderMap().size()).isEqualTo(1); + assertThat(headers.getContentLength()).isEqualTo(Integer.valueOf(-1)); String bodyText = new String(message.getPayload()); - assertEquals("The body of the message", bodyText); + assertThat(bodyText).isEqualTo("The body of the message"); } @Test @@ -127,13 +126,13 @@ public class StompDecoderTests { Message frame = decode("SEND\ncontent-length:0\n\n\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); - assertEquals(StompCommand.SEND, headers.getCommand()); + assertThat(headers.getCommand()).isEqualTo(StompCommand.SEND); - assertEquals(1, headers.toNativeHeaderMap().size()); - assertEquals(Integer.valueOf(0), headers.getContentLength()); + assertThat(headers.toNativeHeaderMap().size()).isEqualTo(1); + assertThat(headers.getContentLength()).isEqualTo(Integer.valueOf(0)); String bodyText = new String(frame.getPayload()); - assertEquals("", bodyText); + assertThat(bodyText).isEqualTo(""); } @Test @@ -141,13 +140,13 @@ public class StompDecoderTests { Message frame = decode("SEND\ncontent-length:23\n\nThe b\0dy \0f the message\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); - assertEquals(StompCommand.SEND, headers.getCommand()); + assertThat(headers.getCommand()).isEqualTo(StompCommand.SEND); - assertEquals(1, headers.toNativeHeaderMap().size()); - assertEquals(Integer.valueOf(23), headers.getContentLength()); + assertThat(headers.toNativeHeaderMap().size()).isEqualTo(1); + assertThat(headers.getContentLength()).isEqualTo(Integer.valueOf(23)); String bodyText = new String(frame.getPayload()); - assertEquals("The b\0dy \0f the message", bodyText); + assertThat(bodyText).isEqualTo("The b\0dy \0f the message"); } @Test @@ -155,10 +154,10 @@ public class StompDecoderTests { Message frame = decode("DISCONNECT\na\\c\\r\\n\\\\b:alpha\\cbravo\\r\\n\\\\\n\n\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); - assertEquals(StompCommand.DISCONNECT, headers.getCommand()); + assertThat(headers.getCommand()).isEqualTo(StompCommand.DISCONNECT); - assertEquals(1, headers.toNativeHeaderMap().size()); - assertEquals("alpha:bravo\r\n\\", headers.getFirstNativeHeader("a:\r\n\\b")); + assertThat(headers.toNativeHeaderMap().size()).isEqualTo(1); + assertThat(headers.getFirstNativeHeader("a:\r\n\\b")).isEqualTo("alpha:bravo\r\n\\"); } @Test @@ -175,9 +174,9 @@ public class StompDecoderTests { final List> messages = decoder.decode(buffer); - assertEquals(2, messages.size()); - assertEquals(StompCommand.SEND, StompHeaderAccessor.wrap(messages.get(0)).getCommand()); - assertEquals(StompCommand.DISCONNECT, StompHeaderAccessor.wrap(messages.get(1)).getCommand()); + assertThat(messages.size()).isEqualTo(2); + assertThat(StompHeaderAccessor.wrap(messages.get(0)).getCommand()).isEqualTo(StompCommand.SEND); + assertThat(StompHeaderAccessor.wrap(messages.get(1)).getCommand()).isEqualTo(StompCommand.DISCONNECT); } // SPR-13111 @@ -190,13 +189,13 @@ public class StompDecoderTests { Message frame = decode("CONNECT\n" + accept + valuelessKey + "\n\0"); StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame); - assertEquals(StompCommand.CONNECT, headers.getCommand()); + assertThat(headers.getCommand()).isEqualTo(StompCommand.CONNECT); - assertEquals(2, headers.toNativeHeaderMap().size()); - assertEquals("1.1", headers.getFirstNativeHeader("accept-version")); - assertEquals("", headers.getFirstNativeHeader("key")); + assertThat(headers.toNativeHeaderMap().size()).isEqualTo(2); + assertThat(headers.getFirstNativeHeader("accept-version")).isEqualTo("1.1"); + assertThat(headers.getFirstNativeHeader("key")).isEqualTo(""); - assertEquals(0, frame.getPayload().length); + assertThat(frame.getPayload().length).isEqualTo(0); } @Test @@ -248,14 +247,14 @@ public class StompDecoderTests { final List> messages = decoder.decode(buffer); - assertEquals(1, messages.size()); - assertEquals(SimpMessageType.HEARTBEAT, StompHeaderAccessor.wrap(messages.get(0)).getMessageType()); + assertThat(messages.size()).isEqualTo(1); + assertThat(StompHeaderAccessor.wrap(messages.get(0)).getMessageType()).isEqualTo(SimpMessageType.HEARTBEAT); } private void assertIncompleteDecode(String partialFrame) { ByteBuffer buffer = ByteBuffer.wrap(partialFrame.getBytes()); - assertNull(decode(buffer)); - assertEquals(0, buffer.position()); + assertThat(decode(buffer)).isNull(); + assertThat(buffer.position()).isEqualTo(0); } private Message decode(String stompFrame) { diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompEncoderTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompEncoderTests.java index 76626c3096c..2e6f421d3b9 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompEncoderTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompEncoderTests.java @@ -21,8 +21,7 @@ import org.junit.Test; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link StompEncoder}. @@ -40,7 +39,7 @@ public class StompEncoderTests { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT); Message frame = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); - assertEquals("DISCONNECT\n\n\0", new String(encoder.encode(frame))); + assertThat(new String(encoder.encode(frame))).isEqualTo("DISCONNECT\n\n\0"); } @Test @@ -51,9 +50,8 @@ public class StompEncoderTests { Message frame = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); String frameString = new String(encoder.encode(frame)); - assertTrue( - "CONNECT\naccept-version:1.2\nhost:github.org\n\n\0".equals(frameString) || - "CONNECT\nhost:github.org\naccept-version:1.2\n\n\0".equals(frameString)); + assertThat("CONNECT\naccept-version:1.2\nhost:github.org\n\n\0".equals(frameString) || + "CONNECT\nhost:github.org\naccept-version:1.2\n\n\0".equals(frameString)).isTrue(); } @Test @@ -62,8 +60,7 @@ public class StompEncoderTests { headers.addNativeHeader("a:\r\n\\b", "alpha:bravo\r\n\\"); Message frame = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()); - assertEquals("DISCONNECT\na\\c\\r\\n\\\\b:alpha\\cbravo\\r\\n\\\\\n\n\0", - new String(encoder.encode(frame))); + assertThat(new String(encoder.encode(frame))).isEqualTo("DISCONNECT\na\\c\\r\\n\\\\b:alpha\\cbravo\\r\\n\\\\\n\n\0"); } @Test @@ -73,8 +70,7 @@ public class StompEncoderTests { Message frame = MessageBuilder.createMessage( "Message body".getBytes(), headers.getMessageHeaders()); - assertEquals("SEND\na:alpha\ncontent-length:12\n\nMessage body\0", - new String(encoder.encode(frame))); + assertThat(new String(encoder.encode(frame))).isEqualTo("SEND\na:alpha\ncontent-length:12\n\nMessage body\0"); } @Test @@ -84,8 +80,7 @@ public class StompEncoderTests { Message frame = MessageBuilder.createMessage( "Message body".getBytes(), headers.getMessageHeaders()); - assertEquals("SEND\ncontent-length:12\n\nMessage body\0", - new String(encoder.encode(frame))); + assertThat(new String(encoder.encode(frame))).isEqualTo("SEND\ncontent-length:12\n\nMessage body\0"); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java index b3133c1ee71..5c0d825bb36 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java @@ -37,10 +37,6 @@ import org.springframework.util.MimeTypeUtils; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; /** * Unit tests for {@link StompHeaderAccessor}. @@ -53,10 +49,10 @@ public class StompHeaderAccessorTests { @Test public void createWithCommand() { StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED); - assertEquals(StompCommand.CONNECTED, accessor.getCommand()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.CONNECTED); accessor = StompHeaderAccessor.create(StompCommand.CONNECTED, new LinkedMultiValueMap<>()); - assertEquals(StompCommand.CONNECTED, accessor.getCommand()); + assertThat(accessor.getCommand()).isEqualTo(StompCommand.CONNECTED); } @Test @@ -67,10 +63,10 @@ public class StompHeaderAccessorTests { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE, extHeaders); - assertEquals(StompCommand.SUBSCRIBE, headers.getCommand()); - assertEquals(SimpMessageType.SUBSCRIBE, headers.getMessageType()); - assertEquals("/d", headers.getDestination()); - assertEquals("s1", headers.getSubscriptionId()); + assertThat(headers.getCommand()).isEqualTo(StompCommand.SUBSCRIBE); + assertThat(headers.getMessageType()).isEqualTo(SimpMessageType.SUBSCRIBE); + assertThat(headers.getDestination()).isEqualTo("/d"); + assertThat(headers.getSubscriptionId()).isEqualTo("s1"); } @Test @@ -80,9 +76,9 @@ public class StompHeaderAccessorTests { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.UNSUBSCRIBE, extHeaders); - assertEquals(StompCommand.UNSUBSCRIBE, headers.getCommand()); - assertEquals(SimpMessageType.UNSUBSCRIBE, headers.getMessageType()); - assertEquals("s1", headers.getSubscriptionId()); + assertThat(headers.getCommand()).isEqualTo(StompCommand.UNSUBSCRIBE); + assertThat(headers.getMessageType()).isEqualTo(SimpMessageType.UNSUBSCRIBE); + assertThat(headers.getSubscriptionId()).isEqualTo("s1"); } @Test @@ -94,9 +90,9 @@ public class StompHeaderAccessorTests { StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE, extHeaders); - assertEquals(StompCommand.MESSAGE, headers.getCommand()); - assertEquals(SimpMessageType.MESSAGE, headers.getMessageType()); - assertEquals("s1", headers.getSubscriptionId()); + assertThat(headers.getCommand()).isEqualTo(StompCommand.MESSAGE); + assertThat(headers.getMessageType()).isEqualTo(SimpMessageType.MESSAGE); + assertThat(headers.getSubscriptionId()).isEqualTo("s1"); } @Test @@ -107,16 +103,16 @@ public class StompHeaderAccessorTests { StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.STOMP, extHeaders); - assertEquals(StompCommand.STOMP, headerAccessor.getCommand()); - assertEquals(SimpMessageType.CONNECT, headerAccessor.getMessageType()); - assertNotNull(headerAccessor.getHeader("stompCredentials")); - assertEquals("joe", headerAccessor.getLogin()); - assertEquals("joe123", headerAccessor.getPasscode()); + assertThat(headerAccessor.getCommand()).isEqualTo(StompCommand.STOMP); + assertThat(headerAccessor.getMessageType()).isEqualTo(SimpMessageType.CONNECT); + assertThat(headerAccessor.getHeader("stompCredentials")).isNotNull(); + assertThat(headerAccessor.getLogin()).isEqualTo("joe"); + assertThat(headerAccessor.getPasscode()).isEqualTo("joe123"); assertThat(headerAccessor.toString()).contains("passcode=[PROTECTED]"); Map> output = headerAccessor.toNativeHeaderMap(); - assertEquals("joe", output.get(StompHeaderAccessor.STOMP_LOGIN_HEADER).get(0)); - assertEquals("PROTECTED", output.get(StompHeaderAccessor.STOMP_PASSCODE_HEADER).get(0)); + assertThat(output.get(StompHeaderAccessor.STOMP_LOGIN_HEADER).get(0)).isEqualTo("joe"); + assertThat(output.get(StompHeaderAccessor.STOMP_PASSCODE_HEADER).get(0)).isEqualTo("PROTECTED"); } @Test @@ -127,9 +123,9 @@ public class StompHeaderAccessorTests { Map> actual = headers.toNativeHeaderMap(); - assertEquals(2, actual.size()); - assertEquals("s1", actual.get(StompHeaderAccessor.STOMP_ID_HEADER).get(0)); - assertEquals("/d", actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0)); + assertThat(actual.size()).isEqualTo(2); + assertThat(actual.get(StompHeaderAccessor.STOMP_ID_HEADER).get(0)).isEqualTo("s1"); + assertThat(actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0)).isEqualTo("/d"); } @Test @@ -139,8 +135,8 @@ public class StompHeaderAccessorTests { Map> actual = headers.toNativeHeaderMap(); - assertEquals(1, actual.size()); - assertEquals("s1", actual.get(StompHeaderAccessor.STOMP_ID_HEADER).get(0)); + assertThat(actual.size()).isEqualTo(1); + assertThat(actual.get(StompHeaderAccessor.STOMP_ID_HEADER).get(0)).isEqualTo("s1"); } @Test @@ -153,11 +149,11 @@ public class StompHeaderAccessorTests { Map> actual = headers.toNativeHeaderMap(); - assertEquals(actual.toString(), 4, actual.size()); - assertEquals("s1", actual.get(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER).get(0)); - assertEquals("/d", actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0)); - assertEquals("application/json", actual.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER).get(0)); - assertNotNull("message-id was not created", actual.get(StompHeaderAccessor.STOMP_MESSAGE_ID_HEADER).get(0)); + assertThat(actual.size()).as(actual.toString()).isEqualTo(4); + assertThat(actual.get(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER).get(0)).isEqualTo("s1"); + assertThat(actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0)).isEqualTo("/d"); + assertThat(actual.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER).get(0)).isEqualTo("application/json"); + assertThat(actual.get(StompHeaderAccessor.STOMP_MESSAGE_ID_HEADER).get(0)).as("message-id was not created").isNotNull(); } @Test @@ -169,7 +165,7 @@ public class StompHeaderAccessorTests { StompHeaderAccessor stompHeaderAccessor = StompHeaderAccessor.wrap(message); Map> map = stompHeaderAccessor.toNativeHeaderMap(); - assertEquals("application/atom+xml", map.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER).get(0)); + assertThat(map.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER).get(0)).isEqualTo("application/atom+xml"); } @Test @@ -182,7 +178,7 @@ public class StompHeaderAccessorTests { Message message = MessageBuilder.createMessage(new byte[0], headerAccessor.getMessageHeaders()); byte[] bytes = new StompEncoder().encode(message); - assertEquals("CONNECT\nlogin:joe\npasscode:joe123\n\n\0", new String(bytes, "UTF-8")); + assertThat(new String(bytes, "UTF-8")).isEqualTo("CONNECT\nlogin:joe\npasscode:joe123\n\n\0"); } @Test @@ -197,11 +193,11 @@ public class StompHeaderAccessorTests { headers.setNativeHeader("accountId", accountId.toLowerCase()); Map> actual = headers.toNativeHeaderMap(); - assertEquals(3, actual.size()); + assertThat(actual.size()).isEqualTo(3); - assertEquals("s1", actual.get(StompHeaderAccessor.STOMP_ID_HEADER).get(0)); - assertEquals("/d", actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0)); - assertNotNull("abc123", actual.get("accountId").get(0)); + assertThat(actual.get(StompHeaderAccessor.STOMP_ID_HEADER).get(0)).isEqualTo("s1"); + assertThat(actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0)).isEqualTo("/d"); + assertThat(actual.get("accountId").get(0)).as("abc123").isNotNull(); } @Test @@ -209,8 +205,8 @@ public class StompHeaderAccessorTests { StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.SEND); MessageHeaders headers = headerAccessor.getMessageHeaders(); - assertNull(headers.getId()); - assertNull(headers.getTimestamp()); + assertThat((Object) headers.getId()).isNull(); + assertThat((Object) headers.getTimestamp()).isNull(); } @Test @@ -222,8 +218,8 @@ public class StompHeaderAccessorTests { StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.SEND); headerInitializer.initHeaders(headerAccessor); - assertNotNull(headerAccessor.getMessageHeaders().getId()); - assertNotNull(headerAccessor.getMessageHeaders().getTimestamp()); + assertThat(headerAccessor.getMessageHeaders().getId()).isNotNull(); + assertThat(headerAccessor.getMessageHeaders().getTimestamp()).isNotNull(); } @Test @@ -231,7 +227,7 @@ public class StompHeaderAccessorTests { StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.CONNECT); Message message = MessageBuilder.createMessage(new byte[0], headerAccessor.getMessageHeaders()); - assertSame(headerAccessor, MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class)); + assertThat(MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class)).isSameAs(headerAccessor); } @Test @@ -241,7 +237,7 @@ public class StompHeaderAccessorTests { accessor.setContentType(MimeTypeUtils.APPLICATION_JSON); accessor.setSessionId("123"); String actual = accessor.getShortLogMessage("payload".getBytes(StandardCharsets.UTF_8)); - assertEquals("SEND /foo session=123 application/json payload=payload", actual); + assertThat(actual).isEqualTo("SEND /foo session=123 application/json payload=payload"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 80; i++) { @@ -249,7 +245,7 @@ public class StompHeaderAccessorTests { } final String payload = sb.toString() + " > 80"; actual = accessor.getShortLogMessage(payload.getBytes(StandardCharsets.UTF_8)); - assertEquals("SEND /foo session=123 application/json payload=" + sb + "...(truncated)", actual); + assertThat(actual).isEqualTo(("SEND /foo session=123 application/json payload=" + sb + "...(truncated)")); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/user/DefaultUserDestinationResolverTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/user/DefaultUserDestinationResolverTests.java index 29e39dc3a74..defb90ca692 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/user/DefaultUserDestinationResolverTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/user/DefaultUserDestinationResolverTests.java @@ -28,8 +28,7 @@ import org.springframework.messaging.simp.TestPrincipal; import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -65,11 +64,11 @@ public class DefaultUserDestinationResolverTests { Message message = createMessage(SimpMessageType.SUBSCRIBE, user, "123", sourceDestination); UserDestinationResult actual = this.resolver.resolveDestination(message); - assertEquals(sourceDestination, actual.getSourceDestination()); - assertEquals(1, actual.getTargetDestinations().size()); - assertEquals("/queue/foo-user123", actual.getTargetDestinations().iterator().next()); - assertEquals(sourceDestination, actual.getSubscribeDestination()); - assertEquals(user.getName(), actual.getUser()); + assertThat(actual.getSourceDestination()).isEqualTo(sourceDestination); + assertThat(actual.getTargetDestinations().size()).isEqualTo(1); + assertThat(actual.getTargetDestinations().iterator().next()).isEqualTo("/queue/foo-user123"); + assertThat(actual.getSubscribeDestination()).isEqualTo(sourceDestination); + assertThat(actual.getUser()).isEqualTo(user.getName()); } @Test // SPR-14044 @@ -81,9 +80,9 @@ public class DefaultUserDestinationResolverTests { Message message = createMessage(SimpMessageType.SUBSCRIBE, user, "123", destination); UserDestinationResult actual = this.resolver.resolveDestination(message); - assertEquals(1, actual.getTargetDestinations().size()); - assertEquals("jms.queue.call-user123", actual.getTargetDestinations().iterator().next()); - assertEquals(destination, actual.getSubscribeDestination()); + assertThat(actual.getTargetDestinations().size()).isEqualTo(1); + assertThat(actual.getTargetDestinations().iterator().next()).isEqualTo("jms.queue.call-user123"); + assertThat(actual.getSubscribeDestination()).isEqualTo(destination); } @Test // SPR-11325 @@ -97,8 +96,8 @@ public class DefaultUserDestinationResolverTests { Message message = createMessage(SimpMessageType.SUBSCRIBE, user, "456", "/user/queue/foo"); UserDestinationResult actual = this.resolver.resolveDestination(message); - assertEquals(1, actual.getTargetDestinations().size()); - assertEquals("/queue/foo-user456", actual.getTargetDestinations().iterator().next()); + assertThat(actual.getTargetDestinations().size()).isEqualTo(1); + assertThat(actual.getTargetDestinations().iterator().next()).isEqualTo("/queue/foo-user456"); } @Test @@ -107,11 +106,11 @@ public class DefaultUserDestinationResolverTests { Message message = createMessage(SimpMessageType.SUBSCRIBE, null, "123", sourceDestination); UserDestinationResult actual = this.resolver.resolveDestination(message); - assertEquals(sourceDestination, actual.getSourceDestination()); - assertEquals(1, actual.getTargetDestinations().size()); - assertEquals("/queue/foo-user" + "123", actual.getTargetDestinations().iterator().next()); - assertEquals(sourceDestination, actual.getSubscribeDestination()); - assertNull(actual.getUser()); + assertThat(actual.getSourceDestination()).isEqualTo(sourceDestination); + assertThat(actual.getTargetDestinations().size()).isEqualTo(1); + assertThat(actual.getTargetDestinations().iterator().next()).isEqualTo(("/queue/foo-user" + "123")); + assertThat(actual.getSubscribeDestination()).isEqualTo(sourceDestination); + assertThat(actual.getUser()).isNull(); } @Test @@ -120,8 +119,8 @@ public class DefaultUserDestinationResolverTests { Message message = createMessage(SimpMessageType.UNSUBSCRIBE, user, "123", "/user/queue/foo"); UserDestinationResult actual = this.resolver.resolveDestination(message); - assertEquals(1, actual.getTargetDestinations().size()); - assertEquals("/queue/foo-user123", actual.getTargetDestinations().iterator().next()); + assertThat(actual.getTargetDestinations().size()).isEqualTo(1); + assertThat(actual.getTargetDestinations().iterator().next()).isEqualTo("/queue/foo-user123"); } @Test @@ -131,11 +130,11 @@ public class DefaultUserDestinationResolverTests { Message message = createMessage(SimpMessageType.MESSAGE, user, "123", sourceDestination); UserDestinationResult actual = this.resolver.resolveDestination(message); - assertEquals(sourceDestination, actual.getSourceDestination()); - assertEquals(1, actual.getTargetDestinations().size()); - assertEquals("/queue/foo-user123", actual.getTargetDestinations().iterator().next()); - assertEquals("/user/queue/foo", actual.getSubscribeDestination()); - assertEquals(user.getName(), actual.getUser()); + assertThat(actual.getSourceDestination()).isEqualTo(sourceDestination); + assertThat(actual.getTargetDestinations().size()).isEqualTo(1); + assertThat(actual.getTargetDestinations().iterator().next()).isEqualTo("/queue/foo-user123"); + assertThat(actual.getSubscribeDestination()).isEqualTo("/user/queue/foo"); + assertThat(actual.getUser()).isEqualTo(user.getName()); } @Test // SPR-14044 @@ -147,9 +146,9 @@ public class DefaultUserDestinationResolverTests { Message message = createMessage(SimpMessageType.MESSAGE, user, "123", destination); UserDestinationResult actual = this.resolver.resolveDestination(message); - assertEquals(1, actual.getTargetDestinations().size()); - assertEquals("jms.queue.call-user123", actual.getTargetDestinations().iterator().next()); - assertEquals("/user/jms.queue.call", actual.getSubscribeDestination()); + assertThat(actual.getTargetDestinations().size()).isEqualTo(1); + assertThat(actual.getTargetDestinations().iterator().next()).isEqualTo("jms.queue.call-user123"); + assertThat(actual.getSubscribeDestination()).isEqualTo("/user/jms.queue.call"); } @Test // SPR-12444 @@ -166,11 +165,11 @@ public class DefaultUserDestinationResolverTests { UserDestinationResult actual = this.resolver.resolveDestination(message); - assertEquals(sourceDestination, actual.getSourceDestination()); - assertEquals(1, actual.getTargetDestinations().size()); - assertEquals("/queue/foo-user456", actual.getTargetDestinations().iterator().next()); - assertEquals("/user/queue/foo", actual.getSubscribeDestination()); - assertEquals(otherUser.getName(), actual.getUser()); + assertThat(actual.getSourceDestination()).isEqualTo(sourceDestination); + assertThat(actual.getTargetDestinations().size()).isEqualTo(1); + assertThat(actual.getTargetDestinations().iterator().next()).isEqualTo("/queue/foo-user456"); + assertThat(actual.getSubscribeDestination()).isEqualTo("/user/queue/foo"); + assertThat(actual.getUser()).isEqualTo(otherUser.getName()); } @Test @@ -186,8 +185,8 @@ public class DefaultUserDestinationResolverTests { Message message = createMessage(SimpMessageType.MESSAGE, new TestPrincipal("joe"), null, destination); UserDestinationResult actual = this.resolver.resolveDestination(message); - assertEquals(1, actual.getTargetDestinations().size()); - assertEquals("/queue/foo-useropenid123", actual.getTargetDestinations().iterator().next()); + assertThat(actual.getTargetDestinations().size()).isEqualTo(1); + assertThat(actual.getTargetDestinations().iterator().next()).isEqualTo("/queue/foo-useropenid123"); } @Test @@ -196,11 +195,11 @@ public class DefaultUserDestinationResolverTests { Message message = createMessage(SimpMessageType.MESSAGE, null, "123", sourceDestination); UserDestinationResult actual = this.resolver.resolveDestination(message); - assertEquals(sourceDestination, actual.getSourceDestination()); - assertEquals(1, actual.getTargetDestinations().size()); - assertEquals("/queue/foo-user123", actual.getTargetDestinations().iterator().next()); - assertEquals("/user/queue/foo", actual.getSubscribeDestination()); - assertNull(actual.getUser()); + assertThat(actual.getSourceDestination()).isEqualTo(sourceDestination); + assertThat(actual.getTargetDestinations().size()).isEqualTo(1); + assertThat(actual.getTargetDestinations().iterator().next()).isEqualTo("/queue/foo-user123"); + assertThat(actual.getSubscribeDestination()).isEqualTo("/user/queue/foo"); + assertThat(actual.getUser()).isNull(); } @Test @@ -210,22 +209,22 @@ public class DefaultUserDestinationResolverTests { TestPrincipal user = new TestPrincipal("joe"); Message message = createMessage(SimpMessageType.MESSAGE, user, "123", null); UserDestinationResult actual = this.resolver.resolveDestination(message); - assertNull(actual); + assertThat(actual).isNull(); // not a user destination message = createMessage(SimpMessageType.MESSAGE, user, "123", "/queue/foo"); actual = this.resolver.resolveDestination(message); - assertNull(actual); + assertThat(actual).isNull(); // subscribe + not a user destination message = createMessage(SimpMessageType.SUBSCRIBE, user, "123", "/queue/foo"); actual = this.resolver.resolveDestination(message); - assertNull(actual); + assertThat(actual).isNull(); // no match on message type message = createMessage(SimpMessageType.CONNECT, user, "123", "user/joe/queue/foo"); actual = this.resolver.resolveDestination(message); - assertNull(actual); + assertThat(actual).isNull(); } private Message createMessage(SimpMessageType type, Principal user, String sessionId, String destination) { diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/user/MultiServerUserRegistryTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/user/MultiServerUserRegistryTests.java index c38aeca2a2a..d4b155fa92f 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/user/MultiServerUserRegistryTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/user/MultiServerUserRegistryTests.java @@ -31,10 +31,6 @@ import org.springframework.messaging.converter.MappingJackson2MessageConverter; import org.springframework.messaging.converter.MessageConverter; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -68,8 +64,8 @@ public class MultiServerUserRegistryTests { given(this.localRegistry.getUserCount()).willReturn(1); given(this.localRegistry.getUser("joe")).willReturn(user); - assertEquals(1, this.registry.getUserCount()); - assertSame(user, this.registry.getUser("joe")); + assertThat(this.registry.getUserCount()).isEqualTo(1); + assertThat(this.registry.getUser("joe")).isSameAs(user); } @Test @@ -87,20 +83,20 @@ public class MultiServerUserRegistryTests { // Add remote registry this.registry.addRemoteRegistryDto(message, this.converter, 20000); - assertEquals(1, this.registry.getUserCount()); + assertThat(this.registry.getUserCount()).isEqualTo(1); SimpUser user = this.registry.getUser("joe"); - assertNotNull(user); - assertTrue(user.hasSessions()); - assertEquals(1, user.getSessions().size()); + assertThat(user).isNotNull(); + assertThat(user.hasSessions()).isTrue(); + assertThat(user.getSessions().size()).isEqualTo(1); SimpSession session = user.getSession("remote-sess"); - assertNotNull(session); - assertEquals("remote-sess", session.getId()); - assertSame(user, session.getUser()); - assertEquals(1, session.getSubscriptions().size()); + assertThat(session).isNotNull(); + assertThat(session.getId()).isEqualTo("remote-sess"); + assertThat(session.getUser()).isSameAs(user); + assertThat(session.getSubscriptions().size()).isEqualTo(1); SimpSubscription subscription = session.getSubscriptions().iterator().next(); - assertEquals("remote-sub", subscription.getId()); - assertSame(session, subscription.getSession()); - assertEquals("/remote-dest", subscription.getDestination()); + assertThat(subscription.getId()).isEqualTo("remote-sub"); + assertThat(subscription.getSession()).isSameAs(session); + assertThat(subscription.getDestination()).isEqualTo("/remote-dest"); } @Test @@ -126,14 +122,14 @@ public class MultiServerUserRegistryTests { // Add remote registry this.registry.addRemoteRegistryDto(message, this.converter, 20000); - assertEquals(3, this.registry.getUserCount()); + assertThat(this.registry.getUserCount()).isEqualTo(3); Set matches = this.registry.findSubscriptions(s -> s.getDestination().equals("/match")); - assertEquals(2, matches.size()); + assertThat(matches.size()).isEqualTo(2); Iterator iterator = matches.iterator(); Set sessionIds = new HashSet<>(2); sessionIds.add(iterator.next().getSession().getId()); sessionIds.add(iterator.next().getSession().getId()); - assertEquals(new HashSet<>(Arrays.asList("sess1", "sess2")), sessionIds); + assertThat(sessionIds).isEqualTo(new HashSet<>(Arrays.asList("sess1", "sess2"))); } @Test // SPR-13800 @@ -157,19 +153,19 @@ public class MultiServerUserRegistryTests { this.registry.addRemoteRegistryDto(message, this.converter, 20000); - assertEquals(1, this.registry.getUserCount()); + assertThat(this.registry.getUserCount()).isEqualTo(1); SimpUser user = this.registry.getUsers().iterator().next(); - assertTrue(user.hasSessions()); - assertEquals(2, user.getSessions().size()); + assertThat(user.hasSessions()).isTrue(); + assertThat(user.getSessions().size()).isEqualTo(2); assertThat(user.getSessions()).containsExactlyInAnyOrder(localSession, remoteSession); - assertSame(localSession, user.getSession("sess123")); - assertEquals(remoteSession, user.getSession("sess456")); + assertThat(user.getSession("sess123")).isSameAs(localSession); + assertThat(user.getSession("sess456")).isEqualTo(remoteSession); user = this.registry.getUser("joe"); - assertEquals(2, user.getSessions().size()); + assertThat(user.getSessions().size()).isEqualTo(2); assertThat(user.getSessions()).containsExactlyInAnyOrder(localSession, remoteSession); - assertSame(localSession, user.getSession("sess123")); - assertEquals(remoteSession, user.getSession("sess456")); + assertThat(user.getSession("sess123")).isSameAs(localSession); + assertThat(user.getSession("sess456")).isEqualTo(remoteSession); } @Test @@ -186,9 +182,9 @@ public class MultiServerUserRegistryTests { this.registry.addRemoteRegistryDto(message, this.converter, -1); - assertEquals(1, this.registry.getUserCount()); + assertThat(this.registry.getUserCount()).isEqualTo(1); this.registry.purgeExpiredRegistries(); - assertEquals(0, this.registry.getUserCount()); + assertThat(this.registry.getUserCount()).isEqualTo(0); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/user/UserDestinationMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/user/UserDestinationMessageHandlerTests.java index 4ee1b470e53..f23a3c7f4ad 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/user/UserDestinationMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/user/UserDestinationMessageHandlerTests.java @@ -33,9 +33,7 @@ import org.springframework.messaging.simp.stomp.StompCommand; import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.messaging.support.MessageBuilder; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -74,7 +72,7 @@ public class UserDestinationMessageHandlerTests { Mockito.verify(this.brokerChannel).send(captor.capture()); Message message = captor.getValue(); - assertEquals("/queue/foo-user123", SimpMessageHeaderAccessor.getDestination(message.getHeaders())); + assertThat(SimpMessageHeaderAccessor.getDestination(message.getHeaders())).isEqualTo("/queue/foo-user123"); } @Test @@ -86,7 +84,7 @@ public class UserDestinationMessageHandlerTests { Mockito.verify(this.brokerChannel).send(captor.capture()); Message message = captor.getValue(); - assertEquals("/queue/foo-user123", SimpMessageHeaderAccessor.getDestination(message.getHeaders())); + assertThat(SimpMessageHeaderAccessor.getDestination(message.getHeaders())).isEqualTo("/queue/foo-user123"); } @Test @@ -101,8 +99,8 @@ public class UserDestinationMessageHandlerTests { Mockito.verify(this.brokerChannel).send(captor.capture()); SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.wrap(captor.getValue()); - assertEquals("/queue/foo-user123", accessor.getDestination()); - assertEquals("/user/queue/foo", accessor.getFirstNativeHeader(ORIGINAL_DESTINATION)); + assertThat(accessor.getDestination()).isEqualTo("/queue/foo-user123"); + assertThat(accessor.getFirstNativeHeader(ORIGINAL_DESTINATION)).isEqualTo("/user/queue/foo"); } @Test @@ -116,8 +114,8 @@ public class UserDestinationMessageHandlerTests { Message message = captor.getValue(); SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.wrap(message); - assertEquals("/topic/unresolved", accessor.getDestination()); - assertEquals("/user/joe/queue/foo", accessor.getFirstNativeHeader(ORIGINAL_DESTINATION)); + assertThat(accessor.getDestination()).isEqualTo("/topic/unresolved"); + assertThat(accessor.getFirstNativeHeader(ORIGINAL_DESTINATION)).isEqualTo("/user/joe/queue/foo"); // Should ignore our own broadcast to brokerChannel @@ -145,12 +143,12 @@ public class UserDestinationMessageHandlerTests { ArgumentCaptor captor = ArgumentCaptor.forClass(Message.class); Mockito.verify(this.brokerChannel).send(captor.capture()); - assertNotNull(captor.getValue()); + assertThat(captor.getValue()).isNotNull(); SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(captor.getValue()); - assertEquals("/queue/foo-user123", headers.getDestination()); - assertEquals("/user/queue/foo", headers.getFirstNativeHeader(ORIGINAL_DESTINATION)); - assertEquals("customHeaderValue", headers.getFirstNativeHeader("customHeader")); - assertArrayEquals(payload, (byte[]) captor.getValue().getPayload()); + assertThat(headers.getDestination()).isEqualTo("/queue/foo-user123"); + assertThat(headers.getFirstNativeHeader(ORIGINAL_DESTINATION)).isEqualTo("/user/queue/foo"); + assertThat(headers.getFirstNativeHeader("customHeader")).isEqualTo("customHeaderValue"); + assertThat((byte[]) captor.getValue().getPayload()).isEqualTo(payload); } @Test diff --git a/spring-messaging/src/test/java/org/springframework/messaging/simp/user/UserRegistryMessageHandlerTests.java b/spring-messaging/src/test/java/org/springframework/messaging/simp/user/UserRegistryMessageHandlerTests.java index 9559e91247b..8b5788b1afa 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/simp/user/UserRegistryMessageHandlerTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/simp/user/UserRegistryMessageHandlerTests.java @@ -38,8 +38,7 @@ import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.messaging.simp.broker.BrokerAvailabilityEvent; import org.springframework.scheduling.TaskScheduler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -89,7 +88,7 @@ public class UserRegistryMessageHandlerTests { @Test public void brokerAvailableEvent() throws Exception { Runnable runnable = getUserRegistryTask(); - assertNotNull(runnable); + assertThat(runnable).isNotNull(); } @SuppressWarnings("unchecked") @@ -126,15 +125,15 @@ public class UserRegistryMessageHandlerTests { verify(this.brokerChannel).send(captor.capture()); Message message = captor.getValue(); - assertNotNull(message); + assertThat(message).isNotNull(); MessageHeaders headers = message.getHeaders(); - assertEquals("/topic/simp-user-registry", SimpMessageHeaderAccessor.getDestination(headers)); + assertThat(SimpMessageHeaderAccessor.getDestination(headers)).isEqualTo("/topic/simp-user-registry"); MultiServerUserRegistry remoteRegistry = new MultiServerUserRegistry(mock(SimpUserRegistry.class)); remoteRegistry.addRemoteRegistryDto(message, this.converter, 20000); - assertEquals(2, remoteRegistry.getUserCount()); - assertNotNull(remoteRegistry.getUser("joe")); - assertNotNull(remoteRegistry.getUser("jane")); + assertThat(remoteRegistry.getUserCount()).isEqualTo(2); + assertThat(remoteRegistry.getUser("joe")).isNotNull(); + assertThat(remoteRegistry.getUser("jane")).isNotNull(); } @Test @@ -156,9 +155,9 @@ public class UserRegistryMessageHandlerTests { this.handler.handleMessage(message); - assertEquals(2, remoteRegistry.getUserCount()); - assertNotNull(this.multiServerRegistry.getUser("joe")); - assertNotNull(this.multiServerRegistry.getUser("jane")); + assertThat(remoteRegistry.getUserCount()).isEqualTo(2); + assertThat(this.multiServerRegistry.getUser("joe")).isNotNull(); + assertThat(this.multiServerRegistry.getUser("jane")).isNotNull(); } @Test @@ -169,11 +168,11 @@ public class UserRegistryMessageHandlerTests { given(this.localRegistry.getUserCount()).willReturn(1); given(this.localRegistry.getUsers()).willReturn(Collections.singleton(simpUser)); - assertEquals(1, this.multiServerRegistry.getUserCount()); + assertThat(this.multiServerRegistry.getUserCount()).isEqualTo(1); Message message = this.converter.toMessage(this.multiServerRegistry.getLocalRegistryDto(), null); this.multiServerRegistry.addRemoteRegistryDto(message, this.converter, 20000); - assertEquals(1, this.multiServerRegistry.getUserCount()); + assertThat(this.multiServerRegistry.getUserCount()).isEqualTo(1); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/support/ChannelInterceptorTests.java b/spring-messaging/src/test/java/org/springframework/messaging/support/ChannelInterceptorTests.java index e0ad7a5606a..caeac9086df 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/support/ChannelInterceptorTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/support/ChannelInterceptorTests.java @@ -29,11 +29,7 @@ import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessagingException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -64,12 +60,12 @@ public class ChannelInterceptorTests { this.channel.addInterceptor(interceptor); this.channel.send(MessageBuilder.withPayload("test").build()); - assertEquals(1, this.messageHandler.getMessages().size()); + assertThat(this.messageHandler.getMessages().size()).isEqualTo(1); Message result = this.messageHandler.getMessages().get(0); - assertNotNull(result); - assertSame(expected, result); - assertTrue(interceptor.wasAfterCompletionInvoked()); + assertThat(result).isNotNull(); + assertThat(result).isSameAs(expected); + assertThat(interceptor.wasAfterCompletionInvoked()).isTrue(); } @Test @@ -81,11 +77,11 @@ public class ChannelInterceptorTests { Message message = MessageBuilder.withPayload("test").build(); this.channel.send(message); - assertEquals(1, interceptor1.getCounter().get()); - assertEquals(1, interceptor2.getCounter().get()); - assertEquals(0, this.messageHandler.getMessages().size()); - assertTrue(interceptor1.wasAfterCompletionInvoked()); - assertFalse(interceptor2.wasAfterCompletionInvoked()); + assertThat(interceptor1.getCounter().get()).isEqualTo(1); + assertThat(interceptor2.getCounter().get()).isEqualTo(1); + assertThat(this.messageHandler.getMessages().size()).isEqualTo(0); + assertThat(interceptor1.wasAfterCompletionInvoked()).isTrue(); + assertThat(interceptor2.wasAfterCompletionInvoked()).isFalse(); } @Test @@ -104,15 +100,15 @@ public class ChannelInterceptorTests { completionInvoked.set(true); } private void assertInput(Message message, MessageChannel channel, boolean sent) { - assertNotNull(message); - assertNotNull(channel); - assertSame(ChannelInterceptorTests.this.channel, channel); - assertTrue(sent); + assertThat(message).isNotNull(); + assertThat(channel).isNotNull(); + assertThat(channel).isSameAs(ChannelInterceptorTests.this.channel); + assertThat(sent).isTrue(); } }); this.channel.send(MessageBuilder.withPayload("test").build()); - assertTrue(preSendInvoked.get()); - assertTrue(completionInvoked.get()); + assertThat(preSendInvoked.get()).isTrue(); + assertThat(completionInvoked.get()).isTrue(); } @Test @@ -137,15 +133,15 @@ public class ChannelInterceptorTests { completionInvoked.set(true); } private void assertInput(Message message, MessageChannel channel, boolean sent) { - assertNotNull(message); - assertNotNull(channel); - assertSame(testChannel, channel); - assertFalse(sent); + assertThat(message).isNotNull(); + assertThat(channel).isNotNull(); + assertThat(channel).isSameAs(testChannel); + assertThat(sent).isFalse(); } }); testChannel.send(MessageBuilder.withPayload("test").build()); - assertTrue(preSendInvoked.get()); - assertTrue(completionInvoked.get()); + assertThat(preSendInvoked.get()).isTrue(); + assertThat(completionInvoked.get()).isTrue(); } @Test @@ -164,10 +160,10 @@ public class ChannelInterceptorTests { testChannel.send(MessageBuilder.withPayload("test").build()); } catch (Exception ex) { - assertEquals("Simulated exception", ex.getCause().getMessage()); + assertThat(ex.getCause().getMessage()).isEqualTo("Simulated exception"); } - assertTrue(interceptor1.wasAfterCompletionInvoked()); - assertTrue(interceptor2.wasAfterCompletionInvoked()); + assertThat(interceptor1.wasAfterCompletionInvoked()).isTrue(); + assertThat(interceptor2.wasAfterCompletionInvoked()).isTrue(); } @Test @@ -181,10 +177,10 @@ public class ChannelInterceptorTests { this.channel.send(MessageBuilder.withPayload("test").build()); } catch (Exception ex) { - assertEquals("Simulated exception", ex.getCause().getMessage()); + assertThat(ex.getCause().getMessage()).isEqualTo("Simulated exception"); } - assertTrue(interceptor1.wasAfterCompletionInvoked()); - assertFalse(interceptor2.wasAfterCompletionInvoked()); + assertThat(interceptor1.wasAfterCompletionInvoked()).isTrue(); + assertThat(interceptor2.wasAfterCompletionInvoked()).isFalse(); } @@ -219,7 +215,7 @@ public class ChannelInterceptorTests { @Override public Message preSend(Message message, MessageChannel channel) { - assertNotNull(message); + assertThat(message).isNotNull(); counter.incrementAndGet(); return message; } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/support/ExecutorSubscribableChannelTests.java b/spring-messaging/src/test/java/org/springframework/messaging/support/ExecutorSubscribableChannelTests.java index 02a0f296834..a79cf4d2472 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/support/ExecutorSubscribableChannelTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/support/ExecutorSubscribableChannelTests.java @@ -33,10 +33,6 @@ import org.springframework.messaging.MessageHandler; import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -85,8 +81,8 @@ public class ExecutorSubscribableChannelTests { this.channel.subscribe(this.handler); this.channel.send(this.message); verify(this.handler).handleMessage(this.message); - assertEquals(1, interceptor.getCounter().get()); - assertTrue(interceptor.wasAfterHandledInvoked()); + assertThat(interceptor.getCounter().get()).isEqualTo(1); + assertThat(interceptor.wasAfterHandledInvoked()).isTrue(); } @Test @@ -101,8 +97,8 @@ public class ExecutorSubscribableChannelTests { verify(this.handler, never()).handleMessage(this.message); this.runnableCaptor.getValue().run(); verify(this.handler).handleMessage(this.message); - assertEquals(1, interceptor.getCounter().get()); - assertTrue(interceptor.wasAfterHandledInvoked()); + assertThat(interceptor.getCounter().get()).isEqualTo(1); + assertThat(interceptor.wasAfterHandledInvoked()).isTrue(); } @Test @@ -155,8 +151,8 @@ public class ExecutorSubscribableChannelTests { this.channel.subscribe(this.handler); this.channel.send(this.message); verify(this.handler).handleMessage(expected); - assertEquals(1, interceptor.getCounter().get()); - assertTrue(interceptor.wasAfterHandledInvoked()); + assertThat(interceptor.getCounter().get()).isEqualTo(1); + assertThat(interceptor.wasAfterHandledInvoked()).isTrue(); } @Test @@ -168,9 +164,9 @@ public class ExecutorSubscribableChannelTests { this.channel.subscribe(this.handler); this.channel.send(this.message); verifyNoMoreInteractions(this.handler); - assertEquals(1, interceptor1.getCounter().get()); - assertEquals(1, interceptor2.getCounter().get()); - assertTrue(interceptor1.wasAfterHandledInvoked()); + assertThat(interceptor1.getCounter().get()).isEqualTo(1); + assertThat(interceptor2.getCounter().get()).isEqualTo(1); + assertThat(interceptor1.wasAfterHandledInvoked()).isTrue(); } @Test @@ -184,11 +180,11 @@ public class ExecutorSubscribableChannelTests { this.channel.send(this.message); } catch (MessageDeliveryException actual) { - assertSame(expected, actual.getCause()); + assertThat(actual.getCause()).isSameAs(expected); } verify(this.handler).handleMessage(this.message); - assertEquals(1, interceptor.getCounter().get()); - assertTrue(interceptor.wasAfterHandledInvoked()); + assertThat(interceptor.getCounter().get()).isEqualTo(1); + assertThat(interceptor.wasAfterHandledInvoked()).isTrue(); } @@ -208,7 +204,7 @@ public class ExecutorSubscribableChannelTests { @Override public Message beforeHandle(Message message, MessageChannel channel, MessageHandler handler) { - assertNotNull(message); + assertThat(message).isNotNull(); counter.incrementAndGet(); return message; } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/support/MessageBuilderTests.java b/spring-messaging/src/test/java/org/springframework/messaging/support/MessageBuilderTests.java index 86877179532..ff9c4050c9e 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/support/MessageBuilderTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/support/MessageBuilderTests.java @@ -27,13 +27,9 @@ import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.util.IdGenerator; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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.assertNull; -import static org.junit.Assert.assertSame; /** * @author Mark Fisher @@ -44,7 +40,7 @@ public class MessageBuilderTests { @Test public void testSimpleMessageCreation() { Message message = MessageBuilder.withPayload("foo").build(); - assertEquals("foo", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -53,8 +49,8 @@ public class MessageBuilderTests { .setHeader("foo", "bar") .setHeader("count", 123) .build(); - assertEquals("bar", message.getHeaders().get("foo", String.class)); - assertEquals(new Integer(123), message.getHeaders().get("count", Integer.class)); + assertThat(message.getHeaders().get("foo", String.class)).isEqualTo("bar"); + assertThat(message.getHeaders().get("count", Integer.class)).isEqualTo(new Integer(123)); } @Test @@ -68,12 +64,12 @@ public class MessageBuilderTests { .setHeader("foo", "42") .setHeaderIfAbsent("bar", "99") .build(); - assertEquals("test1", message1.getPayload()); - assertEquals("test2", message2.getPayload()); - assertEquals("1", message1.getHeaders().get("foo")); - assertEquals("42", message2.getHeaders().get("foo")); - assertEquals("2", message1.getHeaders().get("bar")); - assertEquals("2", message2.getHeaders().get("bar")); + assertThat(message1.getPayload()).isEqualTo("test1"); + assertThat(message2.getPayload()).isEqualTo("test2"); + assertThat(message1.getHeaders().get("foo")).isEqualTo("1"); + assertThat(message2.getHeaders().get("foo")).isEqualTo("42"); + assertThat(message1.getHeaders().get("bar")).isEqualTo("2"); + assertThat(message2.getHeaders().get("bar")).isEqualTo("2"); } @Test @@ -98,8 +94,8 @@ public class MessageBuilderTests { .setHeader("foo", 123) .copyHeadersIfAbsent(message1.getHeaders()) .build(); - assertEquals("test2", message2.getPayload()); - assertEquals(123, message2.getHeaders().get("foo")); + assertThat(message2.getPayload()).isEqualTo("test2"); + assertThat(message2.getHeaders().get("foo")).isEqualTo(123); } @Test @@ -107,8 +103,8 @@ public class MessageBuilderTests { Message message1 = MessageBuilder.withPayload("test") .setHeader("foo", "bar").build(); Message message2 = MessageBuilder.fromMessage(message1).build(); - assertEquals("test", message2.getPayload()); - assertEquals("bar", message2.getHeaders().get("foo")); + assertThat(message2.getPayload()).isEqualTo("test"); + assertThat(message2.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -116,8 +112,8 @@ public class MessageBuilderTests { Message message1 = MessageBuilder.withPayload("test") .setHeader("foo", "bar").build(); Message message2 = MessageBuilder.fromMessage(message1).setHeader("another", 1).build(); - assertEquals("bar", message2.getHeaders().get("foo")); - assertNotSame(message1.getHeaders().getId(), message2.getHeaders().getId()); + assertThat(message2.getHeaders().get("foo")).isEqualTo("bar"); + assertThat(message2.getHeaders().getId()).isNotSameAs(message1.getHeaders().getId()); } @Test @@ -127,7 +123,7 @@ public class MessageBuilderTests { Message message2 = MessageBuilder.fromMessage(message1) .removeHeader("foo") .build(); - assertFalse(message2.getHeaders().containsKey("foo")); + assertThat(message2.getHeaders().containsKey("foo")).isFalse(); } @Test @@ -137,28 +133,28 @@ public class MessageBuilderTests { Message message2 = MessageBuilder.fromMessage(message1) .setHeader("foo", null) .build(); - assertFalse(message2.getHeaders().containsKey("foo")); + assertThat(message2.getHeaders().containsKey("foo")).isFalse(); } @Test public void testNotModifiedSameMessage() throws Exception { Message original = MessageBuilder.withPayload("foo").build(); Message result = MessageBuilder.fromMessage(original).build(); - assertEquals(original, result); + assertThat(result).isEqualTo(original); } @Test public void testContainsHeaderNotModifiedSameMessage() throws Exception { Message original = MessageBuilder.withPayload("foo").setHeader("bar", 42).build(); Message result = MessageBuilder.fromMessage(original).build(); - assertEquals(original, result); + assertThat(result).isEqualTo(original); } @Test public void testSameHeaderValueAddedNotModifiedSameMessage() throws Exception { Message original = MessageBuilder.withPayload("foo").setHeader("bar", 42).build(); Message result = MessageBuilder.fromMessage(original).setHeader("bar", 42).build(); - assertEquals(original, result); + assertThat(result).isEqualTo(original); } @Test @@ -173,7 +169,7 @@ public class MessageBuilderTests { newHeaders.put("b", "xyz"); newHeaders.put("c", current); Message result = MessageBuilder.fromMessage(original).copyHeaders(newHeaders).build(); - assertEquals(original, result); + assertThat(result).isEqualTo(original); } @Test @@ -184,8 +180,8 @@ public class MessageBuilderTests { Message message = MessageBuilder.createMessage("payload", headers); accessor.setHeader("foo", "bar"); - assertEquals("bar", headers.get("foo")); - assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)); + assertThat(headers.get("foo")).isEqualTo("bar"); + assertThat(MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)).isSameAs(accessor); } @Test @@ -198,7 +194,7 @@ public class MessageBuilderTests { accessor.setHeader("foo", "bar")) .withMessageContaining("Already immutable"); - assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)); + assertThat(MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)).isSameAs(accessor); } @Test @@ -211,8 +207,8 @@ public class MessageBuilderTests { } }); Message message = MessageBuilder.createMessage("foo", headerAccessor.getMessageHeaders()); - assertNull(message.getHeaders().getId()); - assertNull(message.getHeaders().getTimestamp()); + assertThat(message.getHeaders().getId()).isNull(); + assertThat(message.getHeaders().getTimestamp()).isNull(); } @Test @@ -229,8 +225,8 @@ public class MessageBuilderTests { headerAccessor.setHeader("foo", "bar3"); Message message3 = messageBuilder.build(); - assertEquals("bar1", message1.getHeaders().get("foo")); - assertEquals("bar2", message2.getHeaders().get("foo")); - assertEquals("bar3", message3.getHeaders().get("foo")); + assertThat(message1.getHeaders().get("foo")).isEqualTo("bar1"); + assertThat(message2.getHeaders().get("foo")).isEqualTo("bar2"); + assertThat(message3.getHeaders().get("foo")).isEqualTo("bar3"); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java b/spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java index b0dd5440189..0d20a605ea6 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/support/MessageHeaderAccessorTests.java @@ -31,13 +31,6 @@ import org.springframework.util.SerializationTestUtils; import static org.assertj.core.api.Assertions.assertThat; 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.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Test fixture for {@link MessageHeaderAccessor}. @@ -51,7 +44,7 @@ public class MessageHeaderAccessorTests { @Test public void newEmptyHeaders() { MessageHeaderAccessor accessor = new MessageHeaderAccessor(); - assertEquals(0, accessor.toMap().size()); + assertThat(accessor.toMap().size()).isEqualTo(0); } @Test @@ -64,9 +57,9 @@ public class MessageHeaderAccessorTests { MessageHeaderAccessor accessor = new MessageHeaderAccessor(message); MessageHeaders actual = accessor.getMessageHeaders(); - assertEquals(3, actual.size()); - assertEquals("bar", actual.get("foo")); - assertEquals("baz", actual.get("bar")); + assertThat(actual.size()).isEqualTo(3); + assertThat(actual.get("foo")).isEqualTo("bar"); + assertThat(actual.get("bar")).isEqualTo("baz"); } @Test @@ -82,10 +75,10 @@ public class MessageHeaderAccessorTests { accessor.setHeader("foo", "BAR"); MessageHeaders actual = accessor.getMessageHeaders(); - assertEquals(3, actual.size()); - assertNotEquals(message.getHeaders().getId(), actual.getId()); - assertEquals("BAR", actual.get("foo")); - assertEquals("baz", actual.get("bar")); + assertThat(actual.size()).isEqualTo(3); + assertThat(actual.getId()).isNotEqualTo(message.getHeaders().getId()); + assertThat(actual.get("foo")).isEqualTo("BAR"); + assertThat(actual.get("bar")).isEqualTo("baz"); } @Test @@ -94,7 +87,7 @@ public class MessageHeaderAccessorTests { MessageHeaderAccessor accessor = new MessageHeaderAccessor(message); accessor.removeHeader("foo"); Map headers = accessor.toMap(); - assertFalse(headers.containsKey("foo")); + assertThat(headers.containsKey("foo")).isFalse(); } @Test @@ -103,7 +96,7 @@ public class MessageHeaderAccessorTests { MessageHeaderAccessor accessor = new MessageHeaderAccessor(message); accessor.removeHeader("foo"); Map headers = accessor.toMap(); - assertFalse(headers.containsKey("foo")); + assertThat(headers.containsKey("foo")).isFalse(); } @Test @@ -117,9 +110,9 @@ public class MessageHeaderAccessorTests { accessor.removeHeaders("fo*"); MessageHeaders actual = accessor.getMessageHeaders(); - assertEquals(2, actual.size()); - assertNull(actual.get("foo")); - assertEquals("baz", actual.get("bar")); + assertThat(actual.size()).isEqualTo(2); + assertThat(actual.get("foo")).isNull(); + assertThat(actual.get("bar")).isEqualTo("baz"); } @Test @@ -135,9 +128,9 @@ public class MessageHeaderAccessorTests { accessor.copyHeaders(map2); MessageHeaders actual = accessor.getMessageHeaders(); - assertEquals(3, actual.size()); - assertEquals("BAR", actual.get("foo")); - assertEquals("baz", actual.get("bar")); + assertThat(actual.size()).isEqualTo(3); + assertThat(actual.get("foo")).isEqualTo("BAR"); + assertThat(actual.get("bar")).isEqualTo("baz"); } @Test @@ -153,9 +146,9 @@ public class MessageHeaderAccessorTests { accessor.copyHeadersIfAbsent(map2); MessageHeaders actual = accessor.getMessageHeaders(); - assertEquals(3, actual.size()); - assertEquals("bar", actual.get("foo")); - assertEquals("baz", actual.get("bar")); + assertThat(actual.size()).isEqualTo(3); + assertThat(actual.get("foo")).isEqualTo("bar"); + assertThat(actual.get("bar")).isEqualTo("baz"); } @Test @@ -164,8 +157,8 @@ public class MessageHeaderAccessorTests { headers.copyHeaders(null); headers.copyHeadersIfAbsent(null); - assertEquals(1, headers.getMessageHeaders().size()); - assertEquals(Collections.singleton("id"), headers.getMessageHeaders().keySet()); + assertThat(headers.getMessageHeaders().size()).isEqualTo(1); + assertThat(headers.getMessageHeaders().keySet()).isEqualTo(Collections.singleton("id")); } @Test @@ -181,13 +174,13 @@ public class MessageHeaderAccessorTests { accessor.setHeader("foo", "bar3"); Map map3 = accessor.toMap(); - assertEquals(1, map1.size()); - assertEquals(1, map2.size()); - assertEquals(1, map3.size()); + assertThat(map1.size()).isEqualTo(1); + assertThat(map2.size()).isEqualTo(1); + assertThat(map3.size()).isEqualTo(1); - assertEquals("bar1", map1.get("foo")); - assertEquals("bar2", map2.get("foo")); - assertEquals("bar3", map3.get("foo")); + assertThat(map1.get("foo")).isEqualTo("bar1"); + assertThat(map2.get("foo")).isEqualTo("bar2"); + assertThat(map3.get("foo")).isEqualTo("bar3"); } @Test @@ -200,8 +193,8 @@ public class MessageHeaderAccessorTests { accessor.setHeader("foo", "baz"); - assertEquals("baz", headers.get("foo")); - assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)); + assertThat(headers.get("foo")).isEqualTo("baz"); + assertThat(MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)).isSameAs(accessor); } @Test @@ -219,15 +212,15 @@ public class MessageHeaderAccessorTests { accessor.setHeader("foo", "baz")) .withMessageContaining("Already immutable"); - assertEquals("bar", headers.get("foo")); - assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)); + assertThat(headers.get("foo")).isEqualTo("bar"); + assertThat(MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)).isSameAs(accessor); } @Test public void getAccessor() { MessageHeaderAccessor expected = new MessageHeaderAccessor(); Message message = MessageBuilder.createMessage("payload", expected.getMessageHeaders()); - assertSame(expected, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)); + assertThat(MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class)).isSameAs(expected); } @Test @@ -237,9 +230,9 @@ public class MessageHeaderAccessorTests { Message message = MessageBuilder.createMessage("payload", expected.getMessageHeaders()); MessageHeaderAccessor actual = MessageHeaderAccessor.getMutableAccessor(message); - assertNotNull(actual); - assertTrue(actual.isMutable()); - assertSame(expected, actual); + assertThat(actual).isNotNull(); + assertThat(actual.isMutable()).isTrue(); + assertThat(actual).isSameAs(expected); } @Test @@ -247,8 +240,8 @@ public class MessageHeaderAccessorTests { Message message = MessageBuilder.withPayload("payload").build(); MessageHeaderAccessor actual = MessageHeaderAccessor.getMutableAccessor(message); - assertNotNull(actual); - assertTrue(actual.isMutable()); + assertThat(actual).isNotNull(); + assertThat(actual.isMutable()).isTrue(); } @Test @@ -257,22 +250,22 @@ public class MessageHeaderAccessorTests { Message message = MessageBuilder.createMessage("payload", expected.getMessageHeaders()); MessageHeaderAccessor actual = MessageHeaderAccessor.getMutableAccessor(message); - assertNotNull(actual); - assertTrue(actual.isMutable()); - assertEquals(TestMessageHeaderAccessor.class, actual.getClass()); + assertThat(actual).isNotNull(); + assertThat(actual.isMutable()).isTrue(); + assertThat(actual.getClass()).isEqualTo(TestMessageHeaderAccessor.class); } @Test public void timestampEnabled() { MessageHeaderAccessor accessor = new MessageHeaderAccessor(); accessor.setEnableTimestamp(true); - assertNotNull(accessor.getMessageHeaders().getTimestamp()); + assertThat(accessor.getMessageHeaders().getTimestamp()).isNotNull(); } @Test public void timestampDefaultBehavior() { MessageHeaderAccessor accessor = new MessageHeaderAccessor(); - assertNull(accessor.getMessageHeaders().getTimestamp()); + assertThat((Object) accessor.getMessageHeaders().getTimestamp()).isNull(); } @Test @@ -280,13 +273,13 @@ public class MessageHeaderAccessorTests { final UUID id = new UUID(0L, 23L); MessageHeaderAccessor accessor = new MessageHeaderAccessor(); accessor.setIdGenerator(() -> id); - assertSame(id, accessor.getMessageHeaders().getId()); + assertThat(accessor.getMessageHeaders().getId()).isSameAs(id); } @Test public void idGeneratorDefaultBehavior() { MessageHeaderAccessor accessor = new MessageHeaderAccessor(); - assertNotNull(accessor.getMessageHeaders().getId()); + assertThat(accessor.getMessageHeaders().getId()).isNotNull(); } @@ -298,16 +291,16 @@ public class MessageHeaderAccessorTests { accessor.setLeaveMutable(true); MessageHeaders headers = accessor.getMessageHeaders(); - assertNull(headers.getId()); - assertNull(headers.getTimestamp()); + assertThat((Object) headers.getId()).isNull(); + assertThat((Object) headers.getTimestamp()).isNull(); final UUID id = new UUID(0L, 23L); accessor.setIdGenerator(() -> id); accessor.setEnableTimestamp(true); accessor.setImmutable(); - assertSame(id, accessor.getMessageHeaders().getId()); - assertNotNull(headers.getTimestamp()); + assertThat(accessor.getMessageHeaders().getId()).isSameAs(id); + assertThat(headers.getTimestamp()).isNotNull(); } @Test @@ -316,14 +309,14 @@ public class MessageHeaderAccessorTests { accessor.setContentType(MimeTypeUtils.TEXT_PLAIN); String expected = "headers={contentType=text/plain} payload=p"; - assertEquals(expected, accessor.getShortLogMessage("p")); - assertEquals(expected, accessor.getShortLogMessage("p".getBytes(StandardCharsets.UTF_8))); - assertEquals(expected, accessor.getShortLogMessage(new Object() { + assertThat(accessor.getShortLogMessage("p")).isEqualTo(expected); + assertThat(accessor.getShortLogMessage("p".getBytes(StandardCharsets.UTF_8))).isEqualTo(expected); + assertThat(accessor.getShortLogMessage(new Object() { @Override public String toString() { return "p"; } - })); + })).isEqualTo(expected); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 80; i++) { @@ -332,10 +325,10 @@ public class MessageHeaderAccessorTests { final String payload = sb.toString() + " > 80"; String actual = accessor.getShortLogMessage(payload); - assertEquals("headers={contentType=text/plain} payload=" + sb + "...(truncated)", actual); + assertThat(actual).isEqualTo("headers={contentType=text/plain} payload=" + sb + "...(truncated)"); actual = accessor.getShortLogMessage(payload.getBytes(StandardCharsets.UTF_8)); - assertEquals("headers={contentType=text/plain} payload=" + sb + "...(truncated)", actual); + assertThat(actual).isEqualTo("headers={contentType=text/plain} payload=" + sb + "...(truncated)"); actual = accessor.getShortLogMessage(new Object() { @Override @@ -352,14 +345,14 @@ public class MessageHeaderAccessorTests { accessor.setContentType(MimeTypeUtils.TEXT_PLAIN); String expected = "headers={contentType=text/plain} payload=p"; - assertEquals(expected, accessor.getDetailedLogMessage("p")); - assertEquals(expected, accessor.getDetailedLogMessage("p".getBytes(StandardCharsets.UTF_8))); - assertEquals(expected, accessor.getDetailedLogMessage(new Object() { + assertThat(accessor.getDetailedLogMessage("p")).isEqualTo(expected); + assertThat(accessor.getDetailedLogMessage("p".getBytes(StandardCharsets.UTF_8))).isEqualTo(expected); + assertThat(accessor.getDetailedLogMessage(new Object() { @Override public String toString() { return "p"; } - })); + })).isEqualTo(expected); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 80; i++) { @@ -368,10 +361,10 @@ public class MessageHeaderAccessorTests { final String payload = sb.toString() + " > 80"; String actual = accessor.getDetailedLogMessage(payload); - assertEquals("headers={contentType=text/plain} payload=" + sb + " > 80", actual); + assertThat(actual).isEqualTo("headers={contentType=text/plain} payload=" + sb + " > 80"); actual = accessor.getDetailedLogMessage(payload.getBytes(StandardCharsets.UTF_8)); - assertEquals("headers={contentType=text/plain} payload=" + sb + " > 80", actual); + assertThat(actual).isEqualTo("headers={contentType=text/plain} payload=" + sb + " > 80"); actual = accessor.getDetailedLogMessage(new Object() { @Override @@ -379,7 +372,7 @@ public class MessageHeaderAccessorTests { return payload; } }); - assertEquals("headers={contentType=text/plain} payload=" + sb + " > 80", actual); + assertThat(actual).isEqualTo("headers={contentType=text/plain} payload=" + sb + " > 80"); } @Test @@ -392,9 +385,9 @@ public class MessageHeaderAccessorTests { message = new GenericMessage<>(message.getPayload(), mutableAccessor.getMessageHeaders()); Message output = (Message) SerializationTestUtils.serializeAndDeserialize(message); - assertEquals("test", output.getPayload()); - assertEquals("bar", output.getHeaders().get("foo")); - assertNotNull(output.getHeaders().get(MessageHeaders.CONTENT_TYPE)); + assertThat(output.getPayload()).isEqualTo("test"); + assertThat(output.getHeaders().get("foo")).isEqualTo("bar"); + assertThat(output.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isNotNull(); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/support/NativeMessageHeaderAccessorTests.java b/spring-messaging/src/test/java/org/springframework/messaging/support/NativeMessageHeaderAccessorTests.java index 8fa2ed5fd66..bcb131577ce 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/support/NativeMessageHeaderAccessorTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/support/NativeMessageHeaderAccessorTests.java @@ -28,11 +28,8 @@ import org.springframework.messaging.Message; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; /** * Test fixture for {@link NativeMessageHeaderAccessor}. @@ -50,10 +47,10 @@ public class NativeMessageHeaderAccessorTests { NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(inputNativeHeaders); Map actual = headerAccessor.toMap(); - assertEquals(actual.toString(), 1, actual.size()); - assertNotNull(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); - assertEquals(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); - assertNotSame(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); + assertThat(actual.size()).as(actual.toString()).isEqualTo(1); + assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNotNull(); + assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isEqualTo(inputNativeHeaders); + assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNotSameAs(inputNativeHeaders); } @Test @@ -70,11 +67,11 @@ public class NativeMessageHeaderAccessorTests { NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(message); Map actual = headerAccessor.toMap(); - assertEquals(2, actual.size()); - assertEquals("b", actual.get("a")); - assertNotNull(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); - assertEquals(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); - assertNotSame(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); + assertThat(actual.size()).isEqualTo(2); + assertThat(actual.get("a")).isEqualTo("b"); + assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNotNull(); + assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isEqualTo(inputNativeHeaders); + assertThat(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNotSameAs(inputNativeHeaders); } @Test @@ -82,10 +79,10 @@ public class NativeMessageHeaderAccessorTests { NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor((Message) null); Map actual = headerAccessor.toMap(); - assertEquals(0, actual.size()); + assertThat(actual.size()).isEqualTo(0); Map> actualNativeHeaders = headerAccessor.toNativeHeaderMap(); - assertEquals(Collections.emptyMap(), actualNativeHeaders); + assertThat(actualNativeHeaders).isEqualTo(Collections.emptyMap()); } @Test @@ -107,16 +104,16 @@ public class NativeMessageHeaderAccessorTests { Map actual = headerAccessor.toMap(); - assertEquals(2, actual.size()); - assertEquals("B", actual.get("a")); + assertThat(actual.size()).isEqualTo(2); + assertThat(actual.get("a")).isEqualTo("B"); @SuppressWarnings("unchecked") Map> actualNativeHeaders = (Map>) actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS); - assertNotNull(actualNativeHeaders); - assertEquals(Arrays.asList("BAR"), actualNativeHeaders.get("foo")); - assertEquals(Arrays.asList("baz"), actualNativeHeaders.get("bar")); + assertThat(actualNativeHeaders).isNotNull(); + assertThat(actualNativeHeaders.get("foo")).isEqualTo(Arrays.asList("BAR")); + assertThat(actualNativeHeaders.get("bar")).isEqualTo(Arrays.asList("baz")); } @Test @@ -127,7 +124,7 @@ public class NativeMessageHeaderAccessorTests { NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders); headers.setNativeHeader("foo", "baz"); - assertEquals(Arrays.asList("baz"), headers.getNativeHeader("foo")); + assertThat(headers.getNativeHeader("foo")).isEqualTo(Arrays.asList("baz")); } @Test @@ -138,7 +135,7 @@ public class NativeMessageHeaderAccessorTests { NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders); headers.setNativeHeader("foo", null); - assertNull(headers.getNativeHeader("foo")); + assertThat(headers.getNativeHeader("foo")).isNull(); } @Test @@ -146,7 +143,7 @@ public class NativeMessageHeaderAccessorTests { NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(); headerAccessor.setNativeHeader("foo", "baz"); - assertEquals(Arrays.asList("baz"), headerAccessor.getNativeHeader("foo")); + assertThat(headerAccessor.getNativeHeader("foo")).isEqualTo(Arrays.asList("baz")); } @Test @@ -154,8 +151,8 @@ public class NativeMessageHeaderAccessorTests { NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(); headerAccessor.setNativeHeader("foo", null); - assertNull(headerAccessor.getNativeHeader("foo")); - assertNull(headerAccessor.getMessageHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); + assertThat(headerAccessor.getNativeHeader("foo")).isNull(); + assertThat(headerAccessor.getMessageHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNull(); } @Test @@ -177,7 +174,7 @@ public class NativeMessageHeaderAccessorTests { NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders); headers.addNativeHeader("foo", "baz"); - assertEquals(Arrays.asList("bar", "baz"), headers.getNativeHeader("foo")); + assertThat(headers.getNativeHeader("foo")).isEqualTo(Arrays.asList("bar", "baz")); } @Test @@ -188,7 +185,7 @@ public class NativeMessageHeaderAccessorTests { NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders); headers.addNativeHeader("foo", null); - assertEquals(Arrays.asList("bar"), headers.getNativeHeader("foo")); + assertThat(headers.getNativeHeader("foo")).isEqualTo(Arrays.asList("bar")); } @Test @@ -196,7 +193,7 @@ public class NativeMessageHeaderAccessorTests { NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(); headerAccessor.addNativeHeader("foo", "bar"); - assertEquals(Arrays.asList("bar"), headerAccessor.getNativeHeader("foo")); + assertThat(headerAccessor.getNativeHeader("foo")).isEqualTo(Arrays.asList("bar")); } @Test @@ -204,8 +201,8 @@ public class NativeMessageHeaderAccessorTests { NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(); headerAccessor.addNativeHeader("foo", null); - assertNull(headerAccessor.getNativeHeader("foo")); - assertNull(headerAccessor.getMessageHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS)); + assertThat(headerAccessor.getNativeHeader("foo")).isNull(); + assertThat(headerAccessor.getMessageHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS)).isNull(); } @Test diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractContainerEntityManagerFactoryIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractContainerEntityManagerFactoryIntegrationTests.java index 213a82db9b6..e010ff7e995 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractContainerEntityManagerFactoryIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractContainerEntityManagerFactoryIntegrationTests.java @@ -29,12 +29,9 @@ import org.springframework.orm.jpa.domain.DriversLicense; import org.springframework.orm.jpa.domain.Person; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; /** * Integration tests for LocalContainerEntityManagerFactoryBean. @@ -48,16 +45,17 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests @Test public void testEntityManagerFactoryImplementsEntityManagerFactoryInfo() { - assertTrue("Must have introduced config interface", entityManagerFactory instanceof EntityManagerFactoryInfo); + boolean condition = entityManagerFactory instanceof EntityManagerFactoryInfo; + assertThat(condition).as("Must have introduced config interface").isTrue(); EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) entityManagerFactory; - assertEquals("Person", emfi.getPersistenceUnitName()); - assertNotNull("PersistenceUnitInfo must be available", emfi.getPersistenceUnitInfo()); - assertNotNull("Raw EntityManagerFactory must be available", emfi.getNativeEntityManagerFactory()); + assertThat(emfi.getPersistenceUnitName()).isEqualTo("Person"); + assertThat(emfi.getPersistenceUnitInfo()).as("PersistenceUnitInfo must be available").isNotNull(); + assertThat(emfi.getNativeEntityManagerFactory()).as("Raw EntityManagerFactory must be available").isNotNull(); } @Test public void testStateClean() { - assertEquals("Should be no people from previous transactions", 0, countRowsInTable("person")); + assertThat(countRowsInTable("person")).as("Should be no people from previous transactions").isEqualTo(0); } @Test @@ -77,20 +75,19 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests @Test public void testJdbcTx2() { - assertEquals("Any previous tx must have been rolled back", 0, countRowsInTable("person")); + assertThat(countRowsInTable("person")).as("Any previous tx must have been rolled back").isEqualTo(0); executeSqlScript("/org/springframework/orm/jpa/insertPerson.sql"); } @Test - @SuppressWarnings("unchecked") public void testEntityManagerProxyIsProxy() { - assertTrue(Proxy.isProxyClass(sharedEntityManager.getClass())); + assertThat(Proxy.isProxyClass(sharedEntityManager.getClass())).isTrue(); Query q = sharedEntityManager.createQuery("select p from Person as p"); q.getResultList(); - assertTrue("Should be open to start with", sharedEntityManager.isOpen()); + assertThat(sharedEntityManager.isOpen()).as("Should be open to start with").isTrue(); sharedEntityManager.close(); - assertTrue("Close should have been silently ignored", sharedEntityManager.isOpen()); + assertThat(sharedEntityManager.isOpen()).as("Close should have been silently ignored").isTrue(); } @Test @@ -127,10 +124,10 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests startNewTransaction(); sharedEntityManager.clear(); Person newTony = entityManagerFactory.createEntityManager().getReference(Person.class, tony.getId()); - assertNotSame(newTony, tony); + assertThat(tony).isNotSameAs(newTony); endTransaction(); - assertNotNull(newTony.getDriversLicense()); + assertThat(newTony.getDriversLicense()).isNotNull(); newTony.getDriversLicense().getSerialNumber(); } @@ -146,12 +143,12 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests String firstName = "Tony"; insertPerson(firstName); - assertTrue(Proxy.isProxyClass(sharedEntityManager.getClass())); + assertThat(Proxy.isProxyClass(sharedEntityManager.getClass())).isTrue(); Query q = sharedEntityManager.createQuery("select p from Person as p"); List people = q.getResultList(); - assertEquals(1, people.size()); - assertEquals(firstName, people.get(0).getFirstName()); + assertThat(people.size()).isEqualTo(1); + assertThat(people.get(0).getFirstName()).isEqualTo(firstName); } protected void insertPerson(String firstName) { @@ -171,14 +168,14 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests } protected void testInstantiateAndSave(EntityManager em) { - assertEquals("Should be no people from previous transactions", 0, countRowsInTable("person")); + assertThat(countRowsInTable("person")).as("Should be no people from previous transactions").isEqualTo(0); Person p = new Person(); p.setFirstName("Tony"); p.setLastName("Blair"); em.persist(p); em.flush(); - assertEquals("1 row must have been inserted", 1, countRowsInTable("person")); + assertThat(countRowsInTable("person")).as("1 row must have been inserted").isEqualTo(1); } @Test @@ -187,7 +184,7 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests EntityManager em = entityManagerFactory.createEntityManager(); Query q = em.createQuery("select p from Person as p"); List people = q.getResultList(); - assertEquals(0, people.size()); + assertThat(people.size()).isEqualTo(0); assertThatExceptionOfType(NoResultException.class).isThrownBy( q::getSingleResult); } @@ -200,7 +197,7 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests EntityManager em = entityManagerFactory.createEntityManager(); Query q = em.createQuery("select p from Person as p"); List people = q.getResultList(); - assertEquals(0, people.size()); + assertThat(people.size()).isEqualTo(0); assertThatExceptionOfType(NoResultException.class).isThrownBy( q::getSingleResult); } @@ -211,7 +208,7 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests Query q = this.sharedEntityManager.createQuery("select p from Person as p"); q.setFlushMode(FlushModeType.AUTO); List people = q.getResultList(); - assertEquals(0, people.size()); + assertThat(people.size()).isEqualTo(0); assertThatExceptionOfType(NoResultException.class).isThrownBy( q::getSingleResult); } @@ -225,7 +222,7 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests Query q = em.createQuery("select p from Person as p"); q.setFlushMode(FlushModeType.AUTO); List people = q.getResultList(); - assertEquals(0, people.size()); + assertThat(people.size()).isEqualTo(0); assertThatExceptionOfType(Exception.class).isThrownBy(() -> q.getSingleResult()) .withMessageContaining("closed"); @@ -240,8 +237,8 @@ public abstract class AbstractContainerEntityManagerFactoryIntegrationTests @Test public void testCanSerializeProxies() throws Exception { - assertNotNull(SerializationTestUtils.serializeAndDeserialize(entityManagerFactory)); - assertNotNull(SerializationTestUtils.serializeAndDeserialize(sharedEntityManager)); + assertThat(SerializationTestUtils.serializeAndDeserialize(entityManagerFactory)).isNotNull(); + assertThat(SerializationTestUtils.serializeAndDeserialize(sharedEntityManager)).isNotNull(); } } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java index ff02ecefbe0..e6c80d23ba4 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java @@ -25,9 +25,7 @@ import org.junit.Before; import org.springframework.transaction.support.TransactionSynchronizationManager; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -49,21 +47,21 @@ public abstract class AbstractEntityManagerFactoryBeanTests { @After public void tearDown() throws Exception { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } protected void checkInvariants(AbstractEntityManagerFactoryBean demf) { - assertTrue(EntityManagerFactory.class.isAssignableFrom(demf.getObjectType())); + assertThat(EntityManagerFactory.class.isAssignableFrom(demf.getObjectType())).isTrue(); Object gotObject = demf.getObject(); - assertTrue("Object created by factory implements EntityManagerFactoryInfo", - gotObject instanceof EntityManagerFactoryInfo); + boolean condition = gotObject instanceof EntityManagerFactoryInfo; + assertThat(condition).as("Object created by factory implements EntityManagerFactoryInfo").isTrue(); EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) demf.getObject(); - assertSame("Successive invocations of getObject() return same object", emfi, demf.getObject()); - assertSame(emfi, demf.getObject()); - assertSame(emfi.getNativeEntityManagerFactory(), mockEmf); + assertThat(demf.getObject()).as("Successive invocations of getObject() return same object").isSameAs(emfi); + assertThat(demf.getObject()).isSameAs(emfi); + assertThat(mockEmf).isSameAs(emfi.getNativeEntityManagerFactory()); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryIntegrationTests.java index 2744207042b..ebbb7fb53c8 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryIntegrationTests.java @@ -38,8 +38,7 @@ import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -110,10 +109,10 @@ public abstract class AbstractEntityManagerFactoryIntegrationTests { endTransaction(); } - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } @AfterClass diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java index 280acb0eac8..4bef06a7137 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java @@ -26,11 +26,8 @@ import org.junit.Test; import org.springframework.orm.jpa.domain.Person; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * An application-managed entity manager can join an existing transaction, @@ -46,14 +43,14 @@ public class ApplicationManagedEntityManagerIntegrationTests extends AbstractEnt @SuppressWarnings("unchecked") public void testEntityManagerProxyIsProxy() { EntityManager em = entityManagerFactory.createEntityManager(); - assertTrue(Proxy.isProxyClass(em.getClass())); + assertThat(Proxy.isProxyClass(em.getClass())).isTrue(); Query q = em.createQuery("select p from Person as p"); List people = q.getResultList(); - assertNotNull(people); + assertThat(people).isNotNull(); - assertTrue("Should be open to start with", em.isOpen()); + assertThat(em.isOpen()).as("Should be open to start with").isTrue(); em.close(); - assertFalse("Close should work on application managed EM", em.isOpen()); + assertThat(em.isOpen()).as("Close should work on application managed EM").isFalse(); } @Test @@ -92,12 +89,12 @@ public class ApplicationManagedEntityManagerIntegrationTests extends AbstractEnt em.persist(p); em.flush(); - assertEquals("1 row must have been inserted", 1, countRowsInTable(em, "person")); + assertThat(countRowsInTable(em, "person")).as("1 row must have been inserted").isEqualTo(1); } @Test public void testStateClean() { - assertEquals("Should be no people from previous transactions", 0, countRowsInTable("person")); + assertThat(countRowsInTable("person")).as("Should be no people from previous transactions").isEqualTo(0); } @Test @@ -108,27 +105,27 @@ public class ApplicationManagedEntityManagerIntegrationTests extends AbstractEnt doInstantiateAndSave(em); endTransaction(); - assertFalse(em.getTransaction().isActive()); + assertThat(em.getTransaction().isActive()).isFalse(); startNewTransaction(); // Call any method: should cause automatic tx invocation - assertFalse(em.contains(new Person())); + assertThat(em.contains(new Person())).isFalse(); - assertFalse(em.getTransaction().isActive()); + assertThat(em.getTransaction().isActive()).isFalse(); em.joinTransaction(); - assertTrue(em.getTransaction().isActive()); + assertThat(em.getTransaction().isActive()).isTrue(); doInstantiateAndSave(em); setComplete(); endTransaction(); // Should rollback - assertEquals("Tx must have committed back", 1, countRowsInTable(em, "person")); + assertThat(countRowsInTable(em, "person")).as("Tx must have committed back").isEqualTo(1); // Now clean up the database startNewTransaction(); em.joinTransaction(); deleteAllPeopleUsingEntityManager(em); - assertEquals("People have been killed", 0, countRowsInTable(em, "person")); + assertThat(countRowsInTable(em, "person")).as("People have been killed").isEqualTo(0); setComplete(); } @@ -142,7 +139,7 @@ public class ApplicationManagedEntityManagerIntegrationTests extends AbstractEnt em.joinTransaction(); doInstantiateAndSave(em); endTransaction(); // Should rollback - assertEquals("Tx must have been rolled back", 0, countRowsInTable(em, "person")); + assertThat(countRowsInTable(em, "person")).as("Tx must have been rolled back").isEqualTo(0); } @Test @@ -153,7 +150,7 @@ public class ApplicationManagedEntityManagerIntegrationTests extends AbstractEnt setComplete(); endTransaction(); // Should rollback - assertEquals("Tx must have committed back", 1, countRowsInTable(em, "person")); + assertThat(countRowsInTable(em, "person")).as("Tx must have committed back").isEqualTo(1); // Now clean up the database deleteFromTables("person"); diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/ContainerManagedEntityManagerIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/ContainerManagedEntityManagerIntegrationTests.java index 14353877fcc..5c7342dc0b6 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/ContainerManagedEntityManagerIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/ContainerManagedEntityManagerIntegrationTests.java @@ -30,14 +30,9 @@ import org.springframework.dao.DataAccessException; import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.orm.jpa.domain.Person; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Integration tests using in-memory database for container-managed JPA @@ -59,32 +54,32 @@ public class ContainerManagedEntityManagerIntegrationTests extends AbstractEntit @Test public void testExceptionTranslationWithDialectFoundOnEntityManagerFactoryBean() throws Exception { - assertNotNull("Dialect must have been set", entityManagerFactoryBean.getJpaDialect()); + assertThat(entityManagerFactoryBean.getJpaDialect()).as("Dialect must have been set").isNotNull(); doTestExceptionTranslationWithDialectFound(entityManagerFactoryBean); } protected void doTestExceptionTranslationWithDialectFound(PersistenceExceptionTranslator pet) throws Exception { RuntimeException in1 = new RuntimeException("in1"); PersistenceException in2 = new PersistenceException(); - assertNull("No translation here", pet.translateExceptionIfPossible(in1)); + assertThat(pet.translateExceptionIfPossible(in1)).as("No translation here").isNull(); DataAccessException dex = pet.translateExceptionIfPossible(in2); - assertNotNull(dex); - assertSame(in2, dex.getCause()); + assertThat(dex).isNotNull(); + assertThat(dex.getCause()).isSameAs(in2); } @Test @SuppressWarnings("unchecked") public void testEntityManagerProxyIsProxy() { EntityManager em = createContainerManagedEntityManager(); - assertTrue(Proxy.isProxyClass(em.getClass())); + assertThat(Proxy.isProxyClass(em.getClass())).isTrue(); Query q = em.createQuery("select p from Person as p"); List people = q.getResultList(); - assertTrue(people.isEmpty()); + assertThat(people.isEmpty()).isTrue(); - assertTrue("Should be open to start with", em.isOpen()); + assertThat(em.isOpen()).as("Should be open to start with").isTrue(); assertThatIllegalStateException().as("Close should not work on container managed EM").isThrownBy( em::close); - assertTrue(em.isOpen()); + assertThat(em.isOpen()).isTrue(); } // This would be legal, at least if not actually _starting_ a tx @@ -117,7 +112,7 @@ public class ContainerManagedEntityManagerIntegrationTests extends AbstractEntit } protected void doInstantiateAndSave(EntityManager em) { - assertEquals("Should be no people from previous transactions", 0, countRowsInTable(em, "person")); + assertThat(countRowsInTable(em, "person")).as("Should be no people from previous transactions").isEqualTo(0); Person p = new Person(); p.setFirstName("Tony"); @@ -125,7 +120,7 @@ public class ContainerManagedEntityManagerIntegrationTests extends AbstractEntit em.persist(p); em.flush(); - assertEquals("1 row must have been inserted", 1, countRowsInTable(em, "person")); + assertThat(countRowsInTable(em, "person")).as("1 row must have been inserted").isEqualTo(1); } @Test @@ -138,13 +133,13 @@ public class ContainerManagedEntityManagerIntegrationTests extends AbstractEntit startNewTransaction(); // Call any method: should cause automatic tx invocation - assertFalse(em.contains(new Person())); + assertThat(em.contains(new Person())).isFalse(); //assertTrue(em.getTransaction().isActive()); doInstantiateAndSave(em); setComplete(); endTransaction(); // Should rollback - assertEquals("Tx must have committed back", 1, countRowsInTable(em, "person")); + assertThat(countRowsInTable(em, "person")).as("Tx must have committed back").isEqualTo(1); // Now clean up the database deleteFromTables("person"); @@ -155,7 +150,7 @@ public class ContainerManagedEntityManagerIntegrationTests extends AbstractEntit EntityManager em = createContainerManagedEntityManager(); doInstantiateAndSave(em); endTransaction(); // Should rollback - assertEquals("Tx must have been rolled back", 0, countRowsInTable(em, "person")); + assertThat(countRowsInTable(em, "person")).as("Tx must have been rolled back").isEqualTo(0); } @Test @@ -164,7 +159,7 @@ public class ContainerManagedEntityManagerIntegrationTests extends AbstractEntit doInstantiateAndSave(em); setComplete(); endTransaction(); // Should rollback - assertEquals("Tx must have committed back", 1, countRowsInTable(em, "person")); + assertThat(countRowsInTable(em, "person")).as("Tx must have committed back").isEqualTo(1); // Now clean up the database deleteFromTables("person"); diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java index 9222f4cd368..364df9bda1d 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java @@ -26,8 +26,8 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.DefaultTransactionDefinition; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -61,8 +61,6 @@ public class DefaultJpaDialectTests { @Test public void testTranslateException() { OptimisticLockException ex = new OptimisticLockException(); - assertEquals( - EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex).getCause(), - dialect.translateExceptionIfPossible(ex).getCause()); + assertThat(dialect.translateExceptionIfPossible(ex).getCause()).isEqualTo(EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex).getCause()); } } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java index 201e7d697ec..68faca24708 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java @@ -35,10 +35,8 @@ import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -62,8 +60,8 @@ public class EntityManagerFactoryUtilsTests { EntityManagerFactory factory = mock(EntityManagerFactory.class); // no tx active - assertNull(EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null)); - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertThat(EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null)).isNull(); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); } @Test @@ -76,30 +74,32 @@ public class EntityManagerFactoryUtilsTests { given(factory.createEntityManager()).willReturn(manager); // no tx active - assertSame(manager, EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null)); - assertSame(manager, ((EntityManagerHolder)TransactionSynchronizationManager.unbindResource(factory)).getEntityManager()); + assertThat(EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null)).isSameAs(manager); + assertThat(((EntityManagerHolder) TransactionSynchronizationManager.unbindResource(factory)).getEntityManager()).isSameAs(manager); } finally { TransactionSynchronizationManager.clearSynchronization(); } - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); } @Test public void testTranslatesIllegalStateException() { IllegalStateException ise = new IllegalStateException(); DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ise); - assertSame(ise, dex.getCause()); - assertTrue(dex instanceof InvalidDataAccessApiUsageException); + assertThat(dex.getCause()).isSameAs(ise); + boolean condition = dex instanceof InvalidDataAccessApiUsageException; + assertThat(condition).isTrue(); } @Test public void testTranslatesIllegalArgumentException() { IllegalArgumentException iae = new IllegalArgumentException(); DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(iae); - assertSame(iae, dex.getCause()); - assertTrue(dex instanceof InvalidDataAccessApiUsageException); + assertThat(dex.getCause()).isSameAs(iae); + boolean condition = dex instanceof InvalidDataAccessApiUsageException; + assertThat(condition).isTrue(); } /** @@ -108,9 +108,7 @@ public class EntityManagerFactoryUtilsTests { @Test public void testDoesNotTranslateUnfamiliarException() { UnsupportedOperationException userRuntimeException = new UnsupportedOperationException(); - assertNull( - "Exception should not be wrapped", - EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(userRuntimeException)); + assertThat(EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(userRuntimeException)).as("Exception should not be wrapped").isNull(); } /* @@ -121,33 +119,26 @@ public class EntityManagerFactoryUtilsTests { @SuppressWarnings("serial") public void testConvertJpaPersistenceException() { EntityNotFoundException entityNotFound = new EntityNotFoundException(); - assertSame(JpaObjectRetrievalFailureException.class, - EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass()); + assertThat(EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass()).isSameAs(JpaObjectRetrievalFailureException.class); NoResultException noResult = new NoResultException(); - assertSame(EmptyResultDataAccessException.class, - EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass()); + assertThat(EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass()).isSameAs(EmptyResultDataAccessException.class); NonUniqueResultException nonUniqueResult = new NonUniqueResultException(); - assertSame(IncorrectResultSizeDataAccessException.class, - EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass()); + assertThat(EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass()).isSameAs(IncorrectResultSizeDataAccessException.class); OptimisticLockException optimisticLock = new OptimisticLockException(); - assertSame(JpaOptimisticLockingFailureException.class, - EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass()); + assertThat(EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass()).isSameAs(JpaOptimisticLockingFailureException.class); EntityExistsException entityExists = new EntityExistsException("foo"); - assertSame(DataIntegrityViolationException.class, - EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass()); + assertThat(EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass()).isSameAs(DataIntegrityViolationException.class); TransactionRequiredException transactionRequired = new TransactionRequiredException("foo"); - assertSame(InvalidDataAccessApiUsageException.class, - EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass()); + assertThat(EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass()).isSameAs(InvalidDataAccessApiUsageException.class); PersistenceException unknown = new PersistenceException() { }; - assertSame(JpaSystemException.class, - EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass()); + assertThat(EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass()).isSameAs(JpaSystemException.class); } } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java index 2cfae41b798..7e07ce41020 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java @@ -37,10 +37,8 @@ import org.springframework.transaction.support.TransactionSynchronizationAdapter import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -82,10 +80,10 @@ public class JpaTransactionManagerTests { @After public void verifyTransactionSynchronizationManagerState() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } @@ -96,21 +94,25 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); return l; } }); - assertSame(l, result); + assertThat(result).isSameAs(l); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(tx).commit(); verify(manager).flush(); @@ -126,27 +128,32 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); try { Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); return l; } }); - assertSame(l, result); + assertThat(result).isSameAs(l); } catch (TransactionSystemException tse) { // expected - assertTrue(tse.getCause() instanceof RollbackException); + boolean condition = tse.getCause() instanceof RollbackException; + assertThat(condition).isTrue(); } - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(manager).flush(); verify(manager).close(); @@ -160,21 +167,25 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory); throw new RuntimeException("some exception"); } })).withMessage("some exception"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(tx).rollback(); verify(manager).close(); @@ -187,21 +198,25 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory); throw new RuntimeException("some exception"); } })); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(manager).close(); } @@ -214,13 +229,15 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); status.setRollbackOnly(); @@ -229,8 +246,10 @@ public class JpaTransactionManagerTests { } }); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(manager).flush(); verify(tx).rollback(); @@ -244,13 +263,15 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); return tt.execute(new TransactionCallback() { @Override @@ -262,8 +283,10 @@ public class JpaTransactionManagerTests { } }); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(manager).flush(); verify(tx).commit(); @@ -278,14 +301,16 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); return tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { @@ -296,8 +321,10 @@ public class JpaTransactionManagerTests { } })); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(tx).setRollbackOnly(); verify(tx).rollback(); @@ -314,14 +341,16 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); return tt.execute(new TransactionCallback() { @Override @@ -335,8 +364,10 @@ public class JpaTransactionManagerTests { })) .withCauseInstanceOf(RollbackException.class); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(manager).flush(); verify(tx).setRollbackOnly(); @@ -354,13 +385,15 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); return tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { @@ -370,10 +403,12 @@ public class JpaTransactionManagerTests { }); } }); - assertSame(l, result); + assertThat(result).isSameAs(l); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(manager).flush(); verify(manager, times(2)).close(); @@ -389,8 +424,10 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); @@ -400,7 +437,7 @@ public class JpaTransactionManagerTests { public Object doInTransaction(TransactionStatus status) { EntityManagerFactoryUtils.getTransactionalEntityManager(factory); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); return tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { @@ -410,14 +447,16 @@ public class JpaTransactionManagerTests { }); } }); - assertSame(l, result); + assertThat(result).isSameAs(l); } finally { TransactionSynchronizationManager.unbindResource(factory); } - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(tx, times(2)).begin(); verify(tx, times(2)).commit(); @@ -434,13 +473,15 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertFalse(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); TransactionTemplate tt2 = new TransactionTemplate(tm); tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); return tt2.execute(new TransactionCallback() { @@ -452,10 +493,12 @@ public class JpaTransactionManagerTests { }); } }); - assertSame(l, result); + assertThat(result).isSameAs(l); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(tx).commit(); verify(manager).flush(); @@ -473,15 +516,17 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { EntityManagerFactoryUtils.getTransactionalEntityManager(factory); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); TransactionTemplate tt2 = new TransactionTemplate(tm); tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); return tt2.execute(new TransactionCallback() { @@ -493,10 +538,12 @@ public class JpaTransactionManagerTests { }); } }); - assertSame(l, result); + assertThat(result).isSameAs(l); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(tx).commit(); verify(manager).flush(); @@ -515,8 +562,10 @@ public class JpaTransactionManagerTests { given(manager2.getTransaction()).willReturn(tx2); given(manager2.isOpen()).willReturn(true); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); tt.execute(new TransactionCallback() { @Override @@ -538,8 +587,10 @@ public class JpaTransactionManagerTests { } }); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(tx).commit(); verify(tx2).begin(); @@ -559,23 +610,29 @@ public class JpaTransactionManagerTests { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(!status.isNewTransaction()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).isTrue(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); return l; } }); - assertSame(l, result); + assertThat(result).isSameAs(l); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(manager).flush(); verify(manager).close(); @@ -587,23 +644,29 @@ public class JpaTransactionManagerTests { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(!status.isNewTransaction()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).isTrue(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); status.setRollbackOnly(); return null; } }); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(manager).flush(); verify(manager).close(); @@ -616,24 +679,27 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition2).isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).isTrue(); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); try { Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory); return l; } }); - assertSame(l, result); + assertThat(result).isSameAs(l); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); } finally { TransactionSynchronizationManager.unbindResource(factory); @@ -648,24 +714,27 @@ public class JpaTransactionManagerTests { given(manager.getTransaction()).willReturn(tx); given(tx.isActive()).willReturn(true); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition2).isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).isTrue(); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); try { tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory); status.setRollbackOnly(); return null; } }); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); } finally { TransactionSynchronizationManager.unbindResource(factory); @@ -683,25 +752,29 @@ public class JpaTransactionManagerTests { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition2).isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).isTrue(); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); try { Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(!status.isNewTransaction()); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).isTrue(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); return l; } }); - assertSame(l, result); + assertThat(result).isSameAs(l); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); } finally { TransactionSynchronizationManager.unbindResource(factory); @@ -714,25 +787,29 @@ public class JpaTransactionManagerTests { public void testTransactionRollbackWithPreboundAndPropagationSupports() { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition2 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition2).isTrue(); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).isTrue(); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); try { tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(!status.isNewTransaction()); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + boolean condition = !status.isNewTransaction(); + assertThat(condition).isTrue(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); status.setRollbackOnly(); return null; } }); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); } finally { TransactionSynchronizationManager.unbindResource(factory); @@ -762,19 +839,23 @@ public class JpaTransactionManagerTests { public void testTransactionFlush() { given(manager.getTransaction()).willReturn(tx); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition3 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition3).isTrue(); + boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition2).isTrue(); tt.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); status.flush(); } }); - assertTrue(!TransactionSynchronizationManager.hasResource(factory)); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); + boolean condition1 = !TransactionSynchronizationManager.hasResource(factory); + assertThat(condition1).isTrue(); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); verify(tx).commit(); verify(manager).flush(); diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java index 995c8cd3980..f47ff67f992 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java @@ -39,15 +39,9 @@ import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.interceptor.DefaultTransactionAttribute; 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.assertThatIllegalArgumentException; -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; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -77,31 +71,31 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM public void testExceptionTranslationWithNoDialect() throws Exception { LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); cefb.getObject(); - assertNull("No dialect set", cefb.getJpaDialect()); + assertThat(cefb.getJpaDialect()).as("No dialect set").isNull(); RuntimeException in1 = new RuntimeException("in1"); PersistenceException in2 = new PersistenceException(); - assertNull("No translation here", cefb.translateExceptionIfPossible(in1)); + assertThat(cefb.translateExceptionIfPossible(in1)).as("No translation here").isNull(); DataAccessException dex = cefb.translateExceptionIfPossible(in2); - assertNotNull(dex); - assertSame(in2, dex.getCause()); + assertThat(dex).isNotNull(); + assertThat(dex.getCause()).isSameAs(in2); } @Test public void testEntityManagerFactoryIsProxied() throws Exception { LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); EntityManagerFactory emf = cefb.getObject(); - assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject()); + assertThat(cefb.getObject()).as("EntityManagerFactory reference must be cached after init").isSameAs(emf); - assertNotSame("EMF must be proxied", mockEmf, emf); - assertTrue(emf.equals(emf)); + assertThat(emf).as("EMF must be proxied").isNotSameAs(mockEmf); + assertThat(emf.equals(emf)).isTrue(); DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.setSerializationId("emf-bf"); bf.registerSingleton("emf", cefb); cefb.setBeanFactory(bf); cefb.setBeanName("emf"); - assertNotNull(SerializationTestUtils.serializeAndDeserialize(emf)); + assertThat(SerializationTestUtils.serializeAndDeserialize(emf)).isNotNull(); } @Test @@ -113,11 +107,11 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); EntityManagerFactory emf = cefb.getObject(); - assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject()); + assertThat(cefb.getObject()).as("EntityManagerFactory reference must be cached after init").isSameAs(emf); - assertNotSame("EMF must be proxied", mockEmf, emf); + assertThat(emf).as("EMF must be proxied").isNotSameAs(mockEmf); EntityManager em = emf.createEntityManager(); - assertFalse(em.contains(testEntity)); + assertThat(em.contains(testEntity)).isFalse(); cefb.destroy(); @@ -148,12 +142,12 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute()); EntityManagerFactory emf = cefb.getObject(); - assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject()); + assertThat(cefb.getObject()).as("EntityManagerFactory reference must be cached after init").isSameAs(emf); - assertNotSame("EMF must be proxied", mockEmf, emf); + assertThat(emf).as("EMF must be proxied").isNotSameAs(mockEmf); EntityManager em = emf.createEntityManager(); em.joinTransaction(); - assertFalse(em.contains(testEntity)); + assertThat(em.contains(testEntity)).isFalse(); jpatm.commit(txStatus); @@ -190,12 +184,12 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute()); EntityManagerFactory emf = cefb.getObject(); - assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject()); + assertThat(cefb.getObject()).as("EntityManagerFactory reference must be cached after init").isSameAs(emf); - assertNotSame("EMF must be proxied", mockEmf, emf); + assertThat(emf).as("EMF must be proxied").isNotSameAs(mockEmf); EntityManager em = emf.createEntityManager(); em.joinTransaction(); - assertFalse(em.contains(testEntity)); + assertThat(em.contains(testEntity)).isFalse(); assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> jpatm.commit(txStatus)); @@ -230,12 +224,12 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute()); EntityManagerFactory emf = cefb.getObject(); - assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject()); + assertThat(cefb.getObject()).as("EntityManagerFactory reference must be cached after init").isSameAs(emf); - assertNotSame("EMF must be proxied", mockEmf, emf); + assertThat(emf).as("EMF must be proxied").isNotSameAs(mockEmf); EntityManager em = emf.createEntityManager(); em.joinTransaction(); - assertFalse(em.contains(testEntity)); + assertThat(em.contains(testEntity)).isFalse(); jpatm.commit(txStatus); @@ -277,9 +271,9 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM containerEmfb.setPersistenceXmlLocation(persistenceXml); containerEmfb.afterPropertiesSet(); - assertEquals(entityManagerName, actualPui.getPersistenceUnitName()); + assertThat(actualPui.getPersistenceUnitName()).isEqualTo(entityManagerName); if (props != null) { - assertEquals(props, actualProps); + assertThat((Object) actualProps).isEqualTo(props); } //checkInvariants(containerEmfb); diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java index 53182df9180..ea113cefec4 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java @@ -26,8 +26,7 @@ import javax.persistence.spi.ProviderUtil; import org.junit.After; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; /** @@ -73,9 +72,9 @@ public class LocalEntityManagerFactoryBeanTests extends AbstractEntityManagerFac } lemfb.afterPropertiesSet(); - assertSame(entityManagerName, actualName); + assertThat(actualName).isSameAs(entityManagerName); if (props != null) { - assertEquals(props, actualProps); + assertThat((Object) actualProps).isEqualTo(props); } checkInvariants(lemfb); diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/SharedEntityManagerCreatorTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/SharedEntityManagerCreatorTests.java index ec1fbabfe0b..440402cacb5 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/SharedEntityManagerCreatorTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/SharedEntityManagerCreatorTests.java @@ -30,7 +30,6 @@ import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.willReturn; import static org.mockito.Mockito.mock; @@ -184,10 +183,10 @@ public class SharedEntityManagerCreatorTests { spq.registerStoredProcedureParameter(1, Number.class, ParameterMode.IN); spq.registerStoredProcedureParameter(2, Object.class, ParameterMode.INOUT); spq.execute(); - assertEquals("y", spq.getOutputParameterValue(0)); + assertThat(spq.getOutputParameterValue(0)).isEqualTo("y"); assertThatIllegalArgumentException().isThrownBy(() -> spq.getOutputParameterValue(1)); - assertEquals("z", spq.getOutputParameterValue(2)); + assertThat(spq.getOutputParameterValue(2)).isEqualTo("z"); verify(query).registerStoredProcedureParameter(0, String.class, ParameterMode.OUT); verify(query).registerStoredProcedureParameter(1, Number.class, ParameterMode.IN); @@ -215,10 +214,10 @@ public class SharedEntityManagerCreatorTests { spq.registerStoredProcedureParameter("b", Number.class, ParameterMode.IN); spq.registerStoredProcedureParameter("c", Object.class, ParameterMode.INOUT); spq.execute(); - assertEquals("y", spq.getOutputParameterValue("a")); + assertThat(spq.getOutputParameterValue("a")).isEqualTo("y"); assertThatIllegalArgumentException().isThrownBy(() -> spq.getOutputParameterValue("b")); - assertEquals("z", spq.getOutputParameterValue("c")); + assertThat(spq.getOutputParameterValue("c")).isEqualTo("z"); verify(query).registerStoredProcedureParameter("a", String.class, ParameterMode.OUT); verify(query).registerStoredProcedureParameter("b", Number.class, ParameterMode.IN); diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/eclipselink/EclipseLinkEntityManagerFactoryIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/eclipselink/EclipseLinkEntityManagerFactoryIntegrationTests.java index 9882437f0c1..4e9b94c7477 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/eclipselink/EclipseLinkEntityManagerFactoryIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/eclipselink/EclipseLinkEntityManagerFactoryIntegrationTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrationTests; import org.springframework.orm.jpa.EntityManagerFactoryInfo; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * EclipseLink-specific JPA tests. @@ -35,14 +34,15 @@ public class EclipseLinkEntityManagerFactoryIntegrationTests extends AbstractCon @Test public void testCanCastNativeEntityManagerFactoryToEclipseLinkEntityManagerFactoryImpl() { EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) entityManagerFactory; - assertTrue(emfi.getNativeEntityManagerFactory().getClass().getName().endsWith("EntityManagerFactoryImpl")); + assertThat(emfi.getNativeEntityManagerFactory().getClass().getName().endsWith("EntityManagerFactoryImpl")).isTrue(); } @Test public void testCanCastSharedEntityManagerProxyToEclipseLinkEntityManager() { - assertTrue(sharedEntityManager instanceof JpaEntityManager); + boolean condition = sharedEntityManager instanceof JpaEntityManager; + assertThat(condition).isTrue(); JpaEntityManager eclipselinkEntityManager = (JpaEntityManager) sharedEntityManager; - assertNotNull(eclipselinkEntityManager.getActiveSession()); + assertThat(eclipselinkEntityManager.getActiveSession()).isNotNull(); } } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateEntityManagerFactoryIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateEntityManagerFactoryIntegrationTests.java index 3823ec48e00..2a8f3986be6 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateEntityManagerFactoryIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateEntityManagerFactoryIntegrationTests.java @@ -29,9 +29,7 @@ import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrat import org.springframework.orm.jpa.EntityManagerFactoryInfo; import org.springframework.orm.jpa.EntityManagerProxy; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Hibernate-specific JPA tests. @@ -52,37 +50,45 @@ public class HibernateEntityManagerFactoryIntegrationTests extends AbstractConta @Test public void testCanCastNativeEntityManagerFactoryToHibernateEntityManagerFactoryImpl() { EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) entityManagerFactory; - assertTrue(emfi.getNativeEntityManagerFactory() instanceof org.hibernate.jpa.HibernateEntityManagerFactory); - assertTrue(emfi.getNativeEntityManagerFactory() instanceof SessionFactory); // as of Hibernate 5.2 + boolean condition1 = emfi.getNativeEntityManagerFactory() instanceof org.hibernate.jpa.HibernateEntityManagerFactory; + assertThat(condition1).isTrue(); + // as of Hibernate 5.2 + boolean condition = emfi.getNativeEntityManagerFactory() instanceof SessionFactory; + assertThat(condition).isTrue(); } @Test public void testCanCastSharedEntityManagerProxyToHibernateEntityManager() { - assertTrue(sharedEntityManager instanceof org.hibernate.jpa.HibernateEntityManager); - assertTrue(((EntityManagerProxy) sharedEntityManager).getTargetEntityManager() instanceof Session); // as of Hibernate 5.2 + boolean condition1 = sharedEntityManager instanceof org.hibernate.jpa.HibernateEntityManager; + assertThat(condition1).isTrue(); + // as of Hibernate 5.2 + boolean condition = ((EntityManagerProxy) sharedEntityManager).getTargetEntityManager() instanceof Session; + assertThat(condition).isTrue(); } @Test public void testCanUnwrapAopProxy() { EntityManager em = entityManagerFactory.createEntityManager(); EntityManager proxy = ProxyFactory.getProxy(EntityManager.class, new SingletonTargetSource(em)); - assertTrue(em instanceof org.hibernate.jpa.HibernateEntityManager); - assertFalse(proxy instanceof org.hibernate.jpa.HibernateEntityManager); - assertTrue(proxy.unwrap(org.hibernate.jpa.HibernateEntityManager.class) != null); - assertSame(em, proxy.unwrap(org.hibernate.jpa.HibernateEntityManager.class)); - assertSame(em.getDelegate(), proxy.getDelegate()); + boolean condition = em instanceof org.hibernate.jpa.HibernateEntityManager; + assertThat(condition).isTrue(); + boolean condition1 = proxy instanceof org.hibernate.jpa.HibernateEntityManager; + assertThat(condition1).isFalse(); + assertThat(proxy.unwrap(org.hibernate.jpa.HibernateEntityManager.class) != null).isTrue(); + assertThat(proxy.unwrap(org.hibernate.jpa.HibernateEntityManager.class)).isSameAs(em); + assertThat(proxy.getDelegate()).isSameAs(em.getDelegate()); } @Test // SPR-16956 public void testReadOnly() { - assertSame(FlushMode.AUTO, sharedEntityManager.unwrap(Session.class).getHibernateFlushMode()); - assertFalse(sharedEntityManager.unwrap(Session.class).isDefaultReadOnly()); + assertThat(sharedEntityManager.unwrap(Session.class).getHibernateFlushMode()).isSameAs(FlushMode.AUTO); + assertThat(sharedEntityManager.unwrap(Session.class).isDefaultReadOnly()).isFalse(); endTransaction(); this.transactionDefinition.setReadOnly(true); startNewTransaction(); - assertSame(FlushMode.MANUAL, sharedEntityManager.unwrap(Session.class).getHibernateFlushMode()); - assertTrue(sharedEntityManager.unwrap(Session.class).isDefaultReadOnly()); + assertThat(sharedEntityManager.unwrap(Session.class).getHibernateFlushMode()).isSameAs(FlushMode.MANUAL); + assertThat(sharedEntityManager.unwrap(Session.class).isDefaultReadOnly()).isTrue(); } } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateMultiEntityManagerFactoryIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateMultiEntityManagerFactoryIntegrationTests.java index 9ba162e021f..684cbeda5ae 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateMultiEntityManagerFactoryIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateMultiEntityManagerFactoryIntegrationTests.java @@ -25,10 +25,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrationTests; import org.springframework.orm.jpa.EntityManagerFactoryInfo; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * Hibernate-specific JPA tests with multiple EntityManagerFactory instances. @@ -50,11 +48,12 @@ public class HibernateMultiEntityManagerFactoryIntegrationTests extends Abstract @Test public void testEntityManagerFactoryImplementsEntityManagerFactoryInfo() { - assertTrue("Must have introduced config interface", this.entityManagerFactory instanceof EntityManagerFactoryInfo); + boolean condition = this.entityManagerFactory instanceof EntityManagerFactoryInfo; + assertThat(condition).as("Must have introduced config interface").isTrue(); EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) this.entityManagerFactory; - assertEquals("Drivers", emfi.getPersistenceUnitName()); - assertNotNull("PersistenceUnitInfo must be available", emfi.getPersistenceUnitInfo()); - assertNotNull("Raw EntityManagerFactory must be available", emfi.getNativeEntityManagerFactory()); + assertThat(emfi.getPersistenceUnitName()).isEqualTo("Drivers"); + assertThat(emfi.getPersistenceUnitInfo()).as("PersistenceUnitInfo must be available").isNotNull(); + assertThat(emfi.getNativeEntityManagerFactory()).as("Raw EntityManagerFactory must be available").isNotNull(); } @Test diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactoryIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactoryIntegrationTests.java index 33cdb43120e..787c7b757c3 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactoryIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactoryIntegrationTests.java @@ -29,10 +29,7 @@ import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrat import org.springframework.orm.jpa.EntityManagerFactoryInfo; import org.springframework.orm.jpa.domain.Person; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Hibernate-specific JPA tests with native SessionFactory setup and getCurrentSession interaction. @@ -58,7 +55,8 @@ public class HibernateNativeEntityManagerFactoryIntegrationTests extends Abstrac @Test public void testEntityManagerFactoryImplementsEntityManagerFactoryInfo() { - assertFalse("Must not have introduced config interface", entityManagerFactory instanceof EntityManagerFactoryInfo); + boolean condition = entityManagerFactory instanceof EntityManagerFactoryInfo; + assertThat(condition).as("Must not have introduced config interface").isFalse(); } @Test @@ -68,9 +66,9 @@ public class HibernateNativeEntityManagerFactoryIntegrationTests extends Abstrac insertPerson(firstName); List people = sharedEntityManager.createQuery("select p from Person as p").getResultList(); - assertEquals(1, people.size()); - assertEquals(firstName, people.get(0).getFirstName()); - assertSame(applicationContext, people.get(0).postLoaded); + assertThat(people.size()).isEqualTo(1); + assertThat(people.get(0).getFirstName()).isEqualTo(firstName); + assertThat(people.get(0).postLoaded).isSameAs(applicationContext); } @Test @@ -81,21 +79,21 @@ public class HibernateNativeEntityManagerFactoryIntegrationTests extends Abstrac Query q = sessionFactory.getCurrentSession().createQuery("select p from Person as p"); List people = q.getResultList(); - assertEquals(1, people.size()); - assertEquals(firstName, people.get(0).getFirstName()); - assertSame(applicationContext, people.get(0).postLoaded); + assertThat(people.size()).isEqualTo(1); + assertThat(people.get(0).getFirstName()).isEqualTo(firstName); + assertThat(people.get(0).postLoaded).isSameAs(applicationContext); } @Test // SPR-16956 public void testReadOnly() { - assertSame(FlushMode.AUTO, sessionFactory.getCurrentSession().getHibernateFlushMode()); - assertFalse(sessionFactory.getCurrentSession().isDefaultReadOnly()); + assertThat(sessionFactory.getCurrentSession().getHibernateFlushMode()).isSameAs(FlushMode.AUTO); + assertThat(sessionFactory.getCurrentSession().isDefaultReadOnly()).isFalse(); endTransaction(); this.transactionDefinition.setReadOnly(true); startNewTransaction(); - assertSame(FlushMode.MANUAL, sessionFactory.getCurrentSession().getHibernateFlushMode()); - assertTrue(sessionFactory.getCurrentSession().isDefaultReadOnly()); + assertThat(sessionFactory.getCurrentSession().getHibernateFlushMode()).isSameAs(FlushMode.MANUAL); + assertThat(sessionFactory.getCurrentSession().isDefaultReadOnly()).isTrue(); } } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTests.java index 1c0a5099ad3..8004adb75b0 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTests.java @@ -35,12 +35,8 @@ import org.springframework.orm.jpa.hibernate.beans.MultiplePrototypesInSpringCon import org.springframework.orm.jpa.hibernate.beans.NoDefinitionInSpringContextTestBean; import org.springframework.orm.jpa.hibernate.beans.SinglePrototypeInSpringContextTestBean; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; /** * Hibernate-specific SpringBeanContainer integration tests. @@ -75,96 +71,96 @@ public class HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTe @Test public void testCanRetrieveBeanByTypeWithJpaCompliantOptions() { BeanContainer beanContainer = getBeanContainer(); - assertNotNull(beanContainer); + assertThat(beanContainer).isNotNull(); ContainedBean bean = beanContainer.getBean( SinglePrototypeInSpringContextTestBean.class, JpaLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE ); - assertNotNull(bean); + assertThat(bean).isNotNull(); SinglePrototypeInSpringContextTestBean instance = bean.getBeanInstance(); - assertNotNull(instance); - assertSame(applicationContext, instance.getApplicationContext()); + assertThat(instance).isNotNull(); + assertThat(instance.getApplicationContext()).isSameAs(applicationContext); } @Test public void testCanRetrieveBeanByNameWithJpaCompliantOptions() { BeanContainer beanContainer = getBeanContainer(); - assertNotNull(beanContainer); + assertThat(beanContainer).isNotNull(); ContainedBean bean = beanContainer.getBean( "multiple-1", MultiplePrototypesInSpringContextTestBean.class, JpaLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE ); - assertNotNull(bean); + assertThat(bean).isNotNull(); MultiplePrototypesInSpringContextTestBean instance = bean.getBeanInstance(); - assertNotNull(instance); - assertEquals("multiple-1", instance.getName()); - assertSame(applicationContext, instance.getApplicationContext()); + assertThat(instance).isNotNull(); + assertThat(instance.getName()).isEqualTo("multiple-1"); + assertThat(instance.getApplicationContext()).isSameAs(applicationContext); } @Test public void testCanRetrieveBeanByTypeWithNativeOptions() { BeanContainer beanContainer = getBeanContainer(); - assertNotNull(beanContainer); + assertThat(beanContainer).isNotNull(); ContainedBean bean = beanContainer.getBean( SinglePrototypeInSpringContextTestBean.class, NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE ); - assertNotNull(bean); + assertThat(bean).isNotNull(); SinglePrototypeInSpringContextTestBean instance = bean.getBeanInstance(); - assertNotNull(instance); - assertEquals("single", instance.getName()); - assertSame(applicationContext, instance.getApplicationContext()); + assertThat(instance).isNotNull(); + assertThat(instance.getName()).isEqualTo("single"); + assertThat(instance.getApplicationContext()).isSameAs(applicationContext); ContainedBean bean2 = beanContainer.getBean( SinglePrototypeInSpringContextTestBean.class, NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE ); - assertNotNull(bean2); + assertThat(bean2).isNotNull(); SinglePrototypeInSpringContextTestBean instance2 = bean2.getBeanInstance(); - assertNotNull(instance2); + assertThat(instance2).isNotNull(); // Due to the lifecycle options, and because the bean has the "prototype" scope, we should not return the same instance - assertNotSame(instance, instance2); + assertThat(instance2).isNotSameAs(instance); } @Test public void testCanRetrieveBeanByNameWithNativeOptions() { BeanContainer beanContainer = getBeanContainer(); - assertNotNull(beanContainer); + assertThat(beanContainer).isNotNull(); ContainedBean bean = beanContainer.getBean( "multiple-1", MultiplePrototypesInSpringContextTestBean.class, NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE ); - assertNotNull(bean); + assertThat(bean).isNotNull(); MultiplePrototypesInSpringContextTestBean instance = bean.getBeanInstance(); - assertNotNull(instance); - assertEquals("multiple-1", instance.getName()); - assertSame(applicationContext, instance.getApplicationContext()); + assertThat(instance).isNotNull(); + assertThat(instance.getName()).isEqualTo("multiple-1"); + assertThat(instance.getApplicationContext()).isSameAs(applicationContext); ContainedBean bean2 = beanContainer.getBean( "multiple-1", MultiplePrototypesInSpringContextTestBean.class, NativeLifecycleOptions.INSTANCE, IneffectiveBeanInstanceProducer.INSTANCE ); - assertNotNull(bean2); + assertThat(bean2).isNotNull(); MultiplePrototypesInSpringContextTestBean instance2 = bean2.getBeanInstance(); - assertNotNull(instance2); + assertThat(instance2).isNotNull(); // Due to the lifecycle options, and because the bean has the "prototype" scope, we should not return the same instance - assertNotSame(instance, instance2); + assertThat(instance2).isNotSameAs(instance); } @Test public void testCanRetrieveFallbackBeanByTypeWithJpaCompliantOptions() { BeanContainer beanContainer = getBeanContainer(); - assertNotNull(beanContainer); + assertThat(beanContainer).isNotNull(); NoDefinitionInSpringContextTestBeanInstanceProducer fallbackProducer = new NoDefinitionInSpringContextTestBeanInstanceProducer(); ContainedBean bean = beanContainer.getBean( @@ -172,20 +168,20 @@ public class HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTe JpaLifecycleOptions.INSTANCE, fallbackProducer ); - assertEquals(1, fallbackProducer.currentUnnamedInstantiationCount()); - assertEquals(0, fallbackProducer.currentNamedInstantiationCount()); + assertThat(fallbackProducer.currentUnnamedInstantiationCount()).isEqualTo(1); + assertThat(fallbackProducer.currentNamedInstantiationCount()).isEqualTo(0); - assertNotNull(bean); + assertThat(bean).isNotNull(); NoDefinitionInSpringContextTestBean instance = bean.getBeanInstance(); - assertNotNull(instance); - assertEquals(BeanSource.FALLBACK, instance.getSource()); - assertNull(instance.getApplicationContext()); + assertThat(instance).isNotNull(); + assertThat(instance.getSource()).isEqualTo(BeanSource.FALLBACK); + assertThat(instance.getApplicationContext()).isNull(); } @Test public void testCanRetrieveFallbackBeanByNameWithJpaCompliantOptions() { BeanContainer beanContainer = getBeanContainer(); - assertNotNull(beanContainer); + assertThat(beanContainer).isNotNull(); NoDefinitionInSpringContextTestBeanInstanceProducer fallbackProducer = new NoDefinitionInSpringContextTestBeanInstanceProducer(); ContainedBean bean = beanContainer.getBean( @@ -193,21 +189,21 @@ public class HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTe JpaLifecycleOptions.INSTANCE, fallbackProducer ); - assertEquals(0, fallbackProducer.currentUnnamedInstantiationCount()); - assertEquals(1, fallbackProducer.currentNamedInstantiationCount()); + assertThat(fallbackProducer.currentUnnamedInstantiationCount()).isEqualTo(0); + assertThat(fallbackProducer.currentNamedInstantiationCount()).isEqualTo(1); - assertNotNull(bean); + assertThat(bean).isNotNull(); NoDefinitionInSpringContextTestBean instance = bean.getBeanInstance(); - assertNotNull(instance); - assertEquals(BeanSource.FALLBACK, instance.getSource()); - assertEquals("some name", instance.getName()); - assertNull(instance.getApplicationContext()); + assertThat(instance).isNotNull(); + assertThat(instance.getSource()).isEqualTo(BeanSource.FALLBACK); + assertThat(instance.getName()).isEqualTo("some name"); + assertThat(instance.getApplicationContext()).isNull(); } @Test public void testCanRetrieveFallbackBeanByTypeWithNativeOptions() { BeanContainer beanContainer = getBeanContainer(); - assertNotNull(beanContainer); + assertThat(beanContainer).isNotNull(); NoDefinitionInSpringContextTestBeanInstanceProducer fallbackProducer = new NoDefinitionInSpringContextTestBeanInstanceProducer(); ContainedBean bean = beanContainer.getBean( @@ -215,20 +211,20 @@ public class HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTe NativeLifecycleOptions.INSTANCE, fallbackProducer ); - assertEquals(1, fallbackProducer.currentUnnamedInstantiationCount()); - assertEquals(0, fallbackProducer.currentNamedInstantiationCount()); + assertThat(fallbackProducer.currentUnnamedInstantiationCount()).isEqualTo(1); + assertThat(fallbackProducer.currentNamedInstantiationCount()).isEqualTo(0); - assertNotNull(bean); + assertThat(bean).isNotNull(); NoDefinitionInSpringContextTestBean instance = bean.getBeanInstance(); - assertNotNull(instance); - assertEquals(BeanSource.FALLBACK, instance.getSource()); - assertNull(instance.getApplicationContext()); + assertThat(instance).isNotNull(); + assertThat(instance.getSource()).isEqualTo(BeanSource.FALLBACK); + assertThat(instance.getApplicationContext()).isNull(); } @Test public void testCanRetrieveFallbackBeanByNameWithNativeOptions() { BeanContainer beanContainer = getBeanContainer(); - assertNotNull(beanContainer); + assertThat(beanContainer).isNotNull(); NoDefinitionInSpringContextTestBeanInstanceProducer fallbackProducer = new NoDefinitionInSpringContextTestBeanInstanceProducer(); ContainedBean bean = beanContainer.getBean( @@ -236,15 +232,15 @@ public class HibernateNativeEntityManagerFactorySpringBeanContainerIntegrationTe NativeLifecycleOptions.INSTANCE, fallbackProducer ); - assertEquals(0, fallbackProducer.currentUnnamedInstantiationCount()); - assertEquals(1, fallbackProducer.currentNamedInstantiationCount()); + assertThat(fallbackProducer.currentUnnamedInstantiationCount()).isEqualTo(0); + assertThat(fallbackProducer.currentNamedInstantiationCount()).isEqualTo(1); - assertNotNull(bean); + assertThat(bean).isNotNull(); NoDefinitionInSpringContextTestBean instance = bean.getBeanInstance(); - assertNotNull(instance); - assertEquals(BeanSource.FALLBACK, instance.getSource()); - assertEquals("some name", instance.getName()); - assertNull(instance.getApplicationContext()); + assertThat(instance).isNotNull(); + assertThat(instance.getSource()).isEqualTo(BeanSource.FALLBACK); + assertThat(instance.getName()).isEqualTo("some name"); + assertThat(instance.getApplicationContext()).isNull(); } @Test diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java index f2e16a0b662..c46deddb0e5 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java @@ -36,13 +36,8 @@ import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup; import org.springframework.jdbc.datasource.lookup.MapDataSourceLookup; import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Unit and integration tests for the JPA XML resource parsing support. @@ -60,15 +55,15 @@ public class PersistenceXmlParsingTests { String resource = "/org/springframework/orm/jpa/META-INF/persistence.xml"; PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource); - assertNotNull(info); - assertEquals(1, info.length); - assertEquals("OrderManagement", info[0].getPersistenceUnitName()); + assertThat(info).isNotNull(); + assertThat(info.length).isEqualTo(1); + assertThat(info[0].getPersistenceUnitName()).isEqualTo("OrderManagement"); - assertEquals(2, info[0].getJarFileUrls().size()); - assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0)); - assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1)); + assertThat(info[0].getJarFileUrls().size()).isEqualTo(2); + assertThat(info[0].getJarFileUrls().get(0)).isEqualTo(new ClassPathResource("order.jar").getURL()); + assertThat(info[0].getJarFileUrls().get(1)).isEqualTo(new ClassPathResource("order-supplemental.jar").getURL()); - assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses()); + assertThat(info[0].excludeUnlistedClasses()).as("Exclude unlisted should default false in 1.0.").isFalse(); } @Test @@ -78,11 +73,11 @@ public class PersistenceXmlParsingTests { String resource = "/org/springframework/orm/jpa/persistence-example1.xml"; PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource); - assertNotNull(info); - assertEquals(1, info.length); - assertEquals("OrderManagement", info[0].getPersistenceUnitName()); + assertThat(info).isNotNull(); + assertThat(info.length).isEqualTo(1); + assertThat(info[0].getPersistenceUnitName()).isEqualTo("OrderManagement"); - assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses()); + assertThat(info[0].excludeUnlistedClasses()).as("Exclude unlisted should default false in 1.0.").isFalse(); } @Test @@ -92,16 +87,16 @@ public class PersistenceXmlParsingTests { String resource = "/org/springframework/orm/jpa/persistence-example2.xml"; PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource); - assertNotNull(info); - assertEquals(1, info.length); + assertThat(info).isNotNull(); + assertThat(info.length).isEqualTo(1); - assertEquals("OrderManagement2", info[0].getPersistenceUnitName()); + assertThat(info[0].getPersistenceUnitName()).isEqualTo("OrderManagement2"); - assertEquals(1, info[0].getMappingFileNames().size()); - assertEquals("mappings.xml", info[0].getMappingFileNames().get(0)); - assertEquals(0, info[0].getProperties().keySet().size()); + assertThat(info[0].getMappingFileNames().size()).isEqualTo(1); + assertThat(info[0].getMappingFileNames().get(0)).isEqualTo("mappings.xml"); + assertThat(info[0].getProperties().keySet().size()).isEqualTo(0); - assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses()); + assertThat(info[0].excludeUnlistedClasses()).as("Exclude unlisted should default false in 1.0.").isFalse(); } @Test @@ -111,19 +106,19 @@ public class PersistenceXmlParsingTests { String resource = "/org/springframework/orm/jpa/persistence-example3.xml"; PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource); - assertNotNull(info); - assertEquals(1, info.length); - assertEquals("OrderManagement3", info[0].getPersistenceUnitName()); + assertThat(info).isNotNull(); + assertThat(info.length).isEqualTo(1); + assertThat(info[0].getPersistenceUnitName()).isEqualTo("OrderManagement3"); - assertEquals(2, info[0].getJarFileUrls().size()); - assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0)); - assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1)); + assertThat(info[0].getJarFileUrls().size()).isEqualTo(2); + assertThat(info[0].getJarFileUrls().get(0)).isEqualTo(new ClassPathResource("order.jar").getURL()); + assertThat(info[0].getJarFileUrls().get(1)).isEqualTo(new ClassPathResource("order-supplemental.jar").getURL()); - assertEquals(0, info[0].getProperties().keySet().size()); - assertNull(info[0].getJtaDataSource()); - assertNull(info[0].getNonJtaDataSource()); + assertThat(info[0].getProperties().keySet().size()).isEqualTo(0); + assertThat(info[0].getJtaDataSource()).isNull(); + assertThat(info[0].getNonJtaDataSource()).isNull(); - assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses()); + assertThat(info[0].excludeUnlistedClasses()).as("Exclude unlisted should default false in 1.0.").isFalse(); } @Test @@ -137,22 +132,22 @@ public class PersistenceXmlParsingTests { String resource = "/org/springframework/orm/jpa/persistence-example4.xml"; PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource); - assertNotNull(info); - assertEquals(1, info.length); - assertEquals("OrderManagement4", info[0].getPersistenceUnitName()); + assertThat(info).isNotNull(); + assertThat(info.length).isEqualTo(1); + assertThat(info[0].getPersistenceUnitName()).isEqualTo("OrderManagement4"); - assertEquals(1, info[0].getMappingFileNames().size()); - assertEquals("order-mappings.xml", info[0].getMappingFileNames().get(0)); + assertThat(info[0].getMappingFileNames().size()).isEqualTo(1); + assertThat(info[0].getMappingFileNames().get(0)).isEqualTo("order-mappings.xml"); - assertEquals(3, info[0].getManagedClassNames().size()); - assertEquals("com.acme.Order", info[0].getManagedClassNames().get(0)); - assertEquals("com.acme.Customer", info[0].getManagedClassNames().get(1)); - assertEquals("com.acme.Item", info[0].getManagedClassNames().get(2)); + assertThat(info[0].getManagedClassNames().size()).isEqualTo(3); + assertThat(info[0].getManagedClassNames().get(0)).isEqualTo("com.acme.Order"); + assertThat(info[0].getManagedClassNames().get(1)).isEqualTo("com.acme.Customer"); + assertThat(info[0].getManagedClassNames().get(2)).isEqualTo("com.acme.Item"); - assertTrue("Exclude unlisted should be true when no value.", info[0].excludeUnlistedClasses()); + assertThat(info[0].excludeUnlistedClasses()).as("Exclude unlisted should be true when no value.").isTrue(); - assertSame(PersistenceUnitTransactionType.RESOURCE_LOCAL, info[0].getTransactionType()); - assertEquals(0, info[0].getProperties().keySet().size()); + assertThat(info[0].getTransactionType()).isSameAs(PersistenceUnitTransactionType.RESOURCE_LOCAL); + assertThat(info[0].getProperties().keySet().size()).isEqualTo(0); builder.clear(); } @@ -164,22 +159,22 @@ public class PersistenceXmlParsingTests { String resource = "/org/springframework/orm/jpa/persistence-example5.xml"; PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource); - assertNotNull(info); - assertEquals(1, info.length); - assertEquals("OrderManagement5", info[0].getPersistenceUnitName()); + assertThat(info).isNotNull(); + assertThat(info.length).isEqualTo(1); + assertThat(info[0].getPersistenceUnitName()).isEqualTo("OrderManagement5"); - assertEquals(2, info[0].getMappingFileNames().size()); - assertEquals("order1.xml", info[0].getMappingFileNames().get(0)); - assertEquals("order2.xml", info[0].getMappingFileNames().get(1)); + assertThat(info[0].getMappingFileNames().size()).isEqualTo(2); + assertThat(info[0].getMappingFileNames().get(0)).isEqualTo("order1.xml"); + assertThat(info[0].getMappingFileNames().get(1)).isEqualTo("order2.xml"); - assertEquals(2, info[0].getJarFileUrls().size()); - assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0)); - assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1)); + assertThat(info[0].getJarFileUrls().size()).isEqualTo(2); + assertThat(info[0].getJarFileUrls().get(0)).isEqualTo(new ClassPathResource("order.jar").getURL()); + assertThat(info[0].getJarFileUrls().get(1)).isEqualTo(new ClassPathResource("order-supplemental.jar").getURL()); - assertEquals("com.acme.AcmePersistence", info[0].getPersistenceProviderClassName()); - assertEquals(0, info[0].getProperties().keySet().size()); + assertThat(info[0].getPersistenceProviderClassName()).isEqualTo("com.acme.AcmePersistence"); + assertThat(info[0].getProperties().keySet().size()).isEqualTo(0); - assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses()); + assertThat(info[0].excludeUnlistedClasses()).as("Exclude unlisted should default false in 1.0.").isFalse(); } @Test @@ -196,53 +191,53 @@ public class PersistenceXmlParsingTests { new PathMatchingResourcePatternResolver(), dataSourceLookup); PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource); - assertEquals(2, info.length); + assertThat(info.length).isEqualTo(2); PersistenceUnitInfo pu1 = info[0]; - assertEquals("pu1", pu1.getPersistenceUnitName()); + assertThat(pu1.getPersistenceUnitName()).isEqualTo("pu1"); - assertEquals("com.acme.AcmePersistence", pu1.getPersistenceProviderClassName()); + assertThat(pu1.getPersistenceProviderClassName()).isEqualTo("com.acme.AcmePersistence"); - assertEquals(1, pu1.getMappingFileNames().size()); - assertEquals("ormap2.xml", pu1.getMappingFileNames().get(0)); + assertThat(pu1.getMappingFileNames().size()).isEqualTo(1); + assertThat(pu1.getMappingFileNames().get(0)).isEqualTo("ormap2.xml"); - assertEquals(1, pu1.getJarFileUrls().size()); - assertEquals(new ClassPathResource("order.jar").getURL(), pu1.getJarFileUrls().get(0)); + assertThat(pu1.getJarFileUrls().size()).isEqualTo(1); + assertThat(pu1.getJarFileUrls().get(0)).isEqualTo(new ClassPathResource("order.jar").getURL()); - assertFalse(pu1.excludeUnlistedClasses()); + assertThat(pu1.excludeUnlistedClasses()).isFalse(); - assertSame(PersistenceUnitTransactionType.RESOURCE_LOCAL, pu1.getTransactionType()); + assertThat(pu1.getTransactionType()).isSameAs(PersistenceUnitTransactionType.RESOURCE_LOCAL); Properties props = pu1.getProperties(); - assertEquals(2, props.keySet().size()); - assertEquals("on", props.getProperty("com.acme.persistence.sql-logging")); - assertEquals("bar", props.getProperty("foo")); + assertThat(props.keySet().size()).isEqualTo(2); + assertThat(props.getProperty("com.acme.persistence.sql-logging")).isEqualTo("on"); + assertThat(props.getProperty("foo")).isEqualTo("bar"); - assertNull(pu1.getNonJtaDataSource()); + assertThat(pu1.getNonJtaDataSource()).isNull(); - assertSame(ds, pu1.getJtaDataSource()); + assertThat(pu1.getJtaDataSource()).isSameAs(ds); - assertFalse("Exclude unlisted should default false in 1.0.", pu1.excludeUnlistedClasses()); + assertThat(pu1.excludeUnlistedClasses()).as("Exclude unlisted should default false in 1.0.").isFalse(); PersistenceUnitInfo pu2 = info[1]; - assertSame(PersistenceUnitTransactionType.JTA, pu2.getTransactionType()); - assertEquals("com.acme.AcmePersistence", pu2.getPersistenceProviderClassName()); + assertThat(pu2.getTransactionType()).isSameAs(PersistenceUnitTransactionType.JTA); + assertThat(pu2.getPersistenceProviderClassName()).isEqualTo("com.acme.AcmePersistence"); - assertEquals(1, pu2.getMappingFileNames().size()); - assertEquals("order2.xml", pu2.getMappingFileNames().get(0)); + assertThat(pu2.getMappingFileNames().size()).isEqualTo(1); + assertThat(pu2.getMappingFileNames().get(0)).isEqualTo("order2.xml"); // the following assertions fail only during coverage runs // assertEquals(1, pu2.getJarFileUrls().size()); // assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), pu2.getJarFileUrls().get(0)); - assertTrue(pu2.excludeUnlistedClasses()); + assertThat(pu2.excludeUnlistedClasses()).isTrue(); - assertNull(pu2.getJtaDataSource()); - assertEquals(ds, pu2.getNonJtaDataSource()); + assertThat(pu2.getJtaDataSource()).isNull(); + assertThat(pu2.getNonJtaDataSource()).isEqualTo(ds); - assertTrue("Exclude unlisted should be true when no value.", pu2.excludeUnlistedClasses()); + assertThat(pu2.excludeUnlistedClasses()).as("Exclude unlisted should be true when no value.").isTrue(); } @Test @@ -251,11 +246,11 @@ public class PersistenceXmlParsingTests { new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup()); String resource = "/org/springframework/orm/jpa/persistence-example6.xml"; PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource); - assertEquals(1, info.length); - assertEquals("pu", info[0].getPersistenceUnitName()); - assertEquals(0, info[0].getProperties().keySet().size()); + assertThat(info.length).isEqualTo(1); + assertThat(info[0].getPersistenceUnitName()).isEqualTo("pu"); + assertThat(info[0].getProperties().keySet().size()).isEqualTo(0); - assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses()); + assertThat(info[0].excludeUnlistedClasses()).as("Exclude unlisted should default false in 1.0.").isFalse(); } @Ignore // not doing schema parsing anymore for JPA 2.0 compatibility @@ -281,10 +276,10 @@ public class PersistenceXmlParsingTests { @Test public void testPersistenceUnitRootUrl() throws Exception { URL url = PersistenceUnitReader.determinePersistenceUnitRootUrl(new ClassPathResource("/org/springframework/orm/jpa/persistence-no-schema.xml")); - assertNull(url); + assertThat(url).isNull(); url = PersistenceUnitReader.determinePersistenceUnitRootUrl(new ClassPathResource("/org/springframework/orm/jpa/META-INF/persistence.xml")); - assertTrue("the containing folder should have been returned", url.toString().endsWith("/org/springframework/orm/jpa")); + assertThat(url.toString().endsWith("/org/springframework/orm/jpa")).as("the containing folder should have been returned").isTrue(); } @Test @@ -293,9 +288,9 @@ public class PersistenceXmlParsingTests { String newRoot = "jar:" + archive.getURL().toExternalForm() + "!/META-INF/persist.xml"; Resource insideArchive = new UrlResource(newRoot); // make sure the location actually exists - assertTrue(insideArchive.exists()); + assertThat(insideArchive.exists()).isTrue(); URL url = PersistenceUnitReader.determinePersistenceUnitRootUrl(insideArchive); - assertTrue("the archive location should have been returned", archive.getURL().sameFile(url)); + assertThat(archive.getURL().sameFile(url)).as("the archive location should have been returned").isTrue(); } @Test @@ -305,28 +300,28 @@ public class PersistenceXmlParsingTests { String resource = "/org/springframework/orm/jpa/persistence-exclude-1.0.xml"; PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource); - assertNotNull(info); - assertEquals("The number of persistence units is incorrect.", 4, info.length); + assertThat(info).isNotNull(); + assertThat(info.length).as("The number of persistence units is incorrect.").isEqualTo(4); PersistenceUnitInfo noExclude = info[0]; - assertNotNull("noExclude should not be null.", noExclude); - assertEquals("noExclude name is not correct.", "NoExcludeElement", noExclude.getPersistenceUnitName()); - assertFalse("Exclude unlisted should default false in 1.0.", noExclude.excludeUnlistedClasses()); + assertThat(noExclude).as("noExclude should not be null.").isNotNull(); + assertThat(noExclude.getPersistenceUnitName()).as("noExclude name is not correct.").isEqualTo("NoExcludeElement"); + assertThat(noExclude.excludeUnlistedClasses()).as("Exclude unlisted should default false in 1.0.").isFalse(); PersistenceUnitInfo emptyExclude = info[1]; - assertNotNull("emptyExclude should not be null.", emptyExclude); - assertEquals("emptyExclude name is not correct.", "EmptyExcludeElement", emptyExclude.getPersistenceUnitName()); - assertTrue("emptyExclude should be true.", emptyExclude.excludeUnlistedClasses()); + assertThat(emptyExclude).as("emptyExclude should not be null.").isNotNull(); + assertThat(emptyExclude.getPersistenceUnitName()).as("emptyExclude name is not correct.").isEqualTo("EmptyExcludeElement"); + assertThat(emptyExclude.excludeUnlistedClasses()).as("emptyExclude should be true.").isTrue(); PersistenceUnitInfo trueExclude = info[2]; - assertNotNull("trueExclude should not be null.", trueExclude); - assertEquals("trueExclude name is not correct.", "TrueExcludeElement", trueExclude.getPersistenceUnitName()); - assertTrue("trueExclude should be true.", trueExclude.excludeUnlistedClasses()); + assertThat(trueExclude).as("trueExclude should not be null.").isNotNull(); + assertThat(trueExclude.getPersistenceUnitName()).as("trueExclude name is not correct.").isEqualTo("TrueExcludeElement"); + assertThat(trueExclude.excludeUnlistedClasses()).as("trueExclude should be true.").isTrue(); PersistenceUnitInfo falseExclude = info[3]; - assertNotNull("falseExclude should not be null.", falseExclude); - assertEquals("falseExclude name is not correct.", "FalseExcludeElement", falseExclude.getPersistenceUnitName()); - assertFalse("falseExclude should be false.", falseExclude.excludeUnlistedClasses()); + assertThat(falseExclude).as("falseExclude should not be null.").isNotNull(); + assertThat(falseExclude.getPersistenceUnitName()).as("falseExclude name is not correct.").isEqualTo("FalseExcludeElement"); + assertThat(falseExclude.excludeUnlistedClasses()).as("falseExclude should be false.").isFalse(); } @Test @@ -336,28 +331,28 @@ public class PersistenceXmlParsingTests { String resource = "/org/springframework/orm/jpa/persistence-exclude-2.0.xml"; PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource); - assertNotNull(info); - assertEquals("The number of persistence units is incorrect.", 4, info.length); + assertThat(info).isNotNull(); + assertThat(info.length).as("The number of persistence units is incorrect.").isEqualTo(4); PersistenceUnitInfo noExclude = info[0]; - assertNotNull("noExclude should not be null.", noExclude); - assertEquals("noExclude name is not correct.", "NoExcludeElement", noExclude.getPersistenceUnitName()); - assertFalse("Exclude unlisted still defaults to false in 2.0.", noExclude.excludeUnlistedClasses()); + assertThat(noExclude).as("noExclude should not be null.").isNotNull(); + assertThat(noExclude.getPersistenceUnitName()).as("noExclude name is not correct.").isEqualTo("NoExcludeElement"); + assertThat(noExclude.excludeUnlistedClasses()).as("Exclude unlisted still defaults to false in 2.0.").isFalse(); PersistenceUnitInfo emptyExclude = info[1]; - assertNotNull("emptyExclude should not be null.", emptyExclude); - assertEquals("emptyExclude name is not correct.", "EmptyExcludeElement", emptyExclude.getPersistenceUnitName()); - assertTrue("emptyExclude should be true.", emptyExclude.excludeUnlistedClasses()); + assertThat(emptyExclude).as("emptyExclude should not be null.").isNotNull(); + assertThat(emptyExclude.getPersistenceUnitName()).as("emptyExclude name is not correct.").isEqualTo("EmptyExcludeElement"); + assertThat(emptyExclude.excludeUnlistedClasses()).as("emptyExclude should be true.").isTrue(); PersistenceUnitInfo trueExclude = info[2]; - assertNotNull("trueExclude should not be null.", trueExclude); - assertEquals("trueExclude name is not correct.", "TrueExcludeElement", trueExclude.getPersistenceUnitName()); - assertTrue("trueExclude should be true.", trueExclude.excludeUnlistedClasses()); + assertThat(trueExclude).as("trueExclude should not be null.").isNotNull(); + assertThat(trueExclude.getPersistenceUnitName()).as("trueExclude name is not correct.").isEqualTo("TrueExcludeElement"); + assertThat(trueExclude.excludeUnlistedClasses()).as("trueExclude should be true.").isTrue(); PersistenceUnitInfo falseExclude = info[3]; - assertNotNull("falseExclude should not be null.", falseExclude); - assertEquals("falseExclude name is not correct.", "FalseExcludeElement", falseExclude.getPersistenceUnitName()); - assertFalse("falseExclude should be false.", falseExclude.excludeUnlistedClasses()); + assertThat(falseExclude).as("falseExclude should not be null.").isNotNull(); + assertThat(falseExclude.getPersistenceUnitName()).as("falseExclude name is not correct.").isEqualTo("FalseExcludeElement"); + assertThat(falseExclude.excludeUnlistedClasses()).as("falseExclude should be false.").isFalse(); } } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java index 96130cfdd91..8ee732a57af 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java @@ -48,10 +48,7 @@ import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.StaticWebApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -93,10 +90,10 @@ public class OpenEntityManagerInViewTests { @After public void tearDown() throws Exception { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } @Test @@ -108,7 +105,7 @@ public class OpenEntityManagerInViewTests { MockHttpServletRequest request = new MockHttpServletRequest(sc); interceptor.preHandle(new ServletWebRequest(request)); - assertTrue(TransactionSynchronizationManager.hasResource(this.factory)); + assertThat(TransactionSynchronizationManager.hasResource(this.factory)).isTrue(); // check that further invocations simply participate interceptor.preHandle(new ServletWebRequest(request)); @@ -125,12 +122,12 @@ public class OpenEntityManagerInViewTests { interceptor.afterCompletion(new ServletWebRequest(request), null); interceptor.postHandle(new ServletWebRequest(request), null); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); given(manager.isOpen()).willReturn(true); interceptor.afterCompletion(new ServletWebRequest(request), null); - assertFalse(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); verify(manager).close(); } @@ -146,7 +143,7 @@ public class OpenEntityManagerInViewTests { given(factory.createEntityManager()).willReturn(this.manager); interceptor.preHandle(this.webRequest); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.webRequest); @@ -160,12 +157,12 @@ public class OpenEntityManagerInViewTests { }); interceptor.afterConcurrentHandlingStarted(this.webRequest); - assertFalse(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); // Async dispatch thread interceptor.preHandle(this.webRequest); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); asyncManager.clearConcurrentResult(); @@ -184,12 +181,12 @@ public class OpenEntityManagerInViewTests { interceptor.afterCompletion(new ServletWebRequest(request), null); interceptor.postHandle(this.webRequest, null); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); given(this.manager.isOpen()).willReturn(true); interceptor.afterCompletion(this.webRequest, null); - assertFalse(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); verify(this.manager).close(); } @@ -205,7 +202,7 @@ public class OpenEntityManagerInViewTests { given(this.factory.createEntityManager()).willReturn(this.manager); interceptor.preHandle(this.webRequest); - assertTrue(TransactionSynchronizationManager.hasResource(this.factory)); + assertThat(TransactionSynchronizationManager.hasResource(this.factory)).isTrue(); AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); @@ -219,7 +216,7 @@ public class OpenEntityManagerInViewTests { }); interceptor.afterConcurrentHandlingStarted(this.webRequest); - assertFalse(TransactionSynchronizationManager.hasResource(this.factory)); + assertThat(TransactionSynchronizationManager.hasResource(this.factory)).isFalse(); // Async request timeout @@ -247,7 +244,7 @@ public class OpenEntityManagerInViewTests { given(this.factory.createEntityManager()).willReturn(this.manager); interceptor.preHandle(this.webRequest); - assertTrue(TransactionSynchronizationManager.hasResource(this.factory)); + assertThat(TransactionSynchronizationManager.hasResource(this.factory)).isTrue(); AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); @@ -261,7 +258,7 @@ public class OpenEntityManagerInViewTests { }); interceptor.afterConcurrentHandlingStarted(this.webRequest); - assertFalse(TransactionSynchronizationManager.hasResource(this.factory)); + assertThat(TransactionSynchronizationManager.hasResource(this.factory)).isFalse(); // Async request timeout @@ -310,7 +307,7 @@ public class OpenEntityManagerInViewTests { final FilterChain filterChain = new FilterChain() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); servletRequest.setAttribute("invoked", Boolean.TRUE); } }; @@ -319,19 +316,19 @@ public class OpenEntityManagerInViewTests { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { - assertTrue(TransactionSynchronizationManager.hasResource(factory2)); + assertThat(TransactionSynchronizationManager.hasResource(factory2)).isTrue(); filter.doFilter(servletRequest, servletResponse, filterChain); } }; FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2); - assertFalse(TransactionSynchronizationManager.hasResource(factory)); - assertFalse(TransactionSynchronizationManager.hasResource(factory2)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse(); filter2.doFilter(request, response, filterChain3); - assertFalse(TransactionSynchronizationManager.hasResource(factory)); - assertFalse(TransactionSynchronizationManager.hasResource(factory2)); - assertNotNull(request.getAttribute("invoked")); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse(); + assertThat(request.getAttribute("invoked")).isNotNull(); verify(manager).close(); verify(manager2).close(); @@ -371,7 +368,7 @@ public class OpenEntityManagerInViewTests { final FilterChain filterChain = new FilterChain() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) { - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); servletRequest.setAttribute("invoked", Boolean.TRUE); count.incrementAndGet(); } @@ -383,7 +380,7 @@ public class OpenEntityManagerInViewTests { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { - assertTrue(TransactionSynchronizationManager.hasResource(factory2)); + assertThat(TransactionSynchronizationManager.hasResource(factory2)).isTrue(); filter.doFilter(servletRequest, servletResponse, filterChain); count2.incrementAndGet(); } @@ -404,14 +401,14 @@ public class OpenEntityManagerInViewTests { } }); - assertFalse(TransactionSynchronizationManager.hasResource(factory)); - assertFalse(TransactionSynchronizationManager.hasResource(factory2)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse(); filter2.doFilter(this.request, this.response, filterChain3); - assertFalse(TransactionSynchronizationManager.hasResource(factory)); - assertFalse(TransactionSynchronizationManager.hasResource(factory2)); - assertEquals(1, count.get()); - assertEquals(1, count2.get()); - assertNotNull(request.getAttribute("invoked")); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse(); + assertThat(count.get()).isEqualTo(1); + assertThat(count2.get()).isEqualTo(1); + assertThat(request.getAttribute("invoked")).isNotNull(); verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); @@ -422,13 +419,13 @@ public class OpenEntityManagerInViewTests { reset(asyncWebRequest); given(asyncWebRequest.isAsyncStarted()).willReturn(false); - assertFalse(TransactionSynchronizationManager.hasResource(factory)); - assertFalse(TransactionSynchronizationManager.hasResource(factory2)); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse(); filter.doFilter(this.request, this.response, filterChain3); - assertFalse(TransactionSynchronizationManager.hasResource(factory)); - assertFalse(TransactionSynchronizationManager.hasResource(factory2)); - assertEquals(2, count.get()); - assertEquals(2, count2.get()); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse(); + assertThat(count.get()).isEqualTo(2); + assertThat(count2.get()).isEqualTo(2); verify(this.manager).close(); verify(manager2).close(); diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceContextTransactionTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceContextTransactionTests.java index 5f89e0efe66..4c4c054caad 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceContextTransactionTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceContextTransactionTests.java @@ -33,8 +33,7 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -80,16 +79,16 @@ public class PersistenceContextTransactionTests { }; pabpp.postProcessProperties(null, bean, "bean"); - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } @After public void clear() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionIntegrationTests.java index abed80dcfe1..2cf1bd2b5fd 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionIntegrationTests.java @@ -23,7 +23,7 @@ import org.springframework.orm.jpa.AbstractEntityManagerFactoryIntegrationTests; import org.springframework.orm.jpa.support.PersistenceInjectionTests.DefaultPublicPersistenceContextSetter; import org.springframework.orm.jpa.support.PersistenceInjectionTests.DefaultPublicPersistenceUnitSetterNamedPerson; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -41,12 +41,12 @@ public class PersistenceInjectionIntegrationTests extends AbstractEntityManagerF @Test public void testDefaultPersistenceContextSetterInjection() { - assertNotNull(defaultSetterInjected.getEntityManager()); + assertThat(defaultSetterInjected.getEntityManager()).isNotNull(); } @Test public void testSetterInjectionOfNamedPersistenceContext() { - assertNotNull(namedSetterInjected.getEntityManagerFactory()); + assertThat(namedSetterInjected.getEntityManagerFactory()).isNotNull(); } } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java index f1e036f314e..13f9d0f0f76 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java @@ -48,10 +48,8 @@ import org.springframework.tests.mock.jndi.ExpectedLookupTemplate; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -84,11 +82,11 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPrivatePersistenceContextField.class.getName()); FactoryBeanWithPersistenceContextField bean2 = (FactoryBeanWithPersistenceContextField) gac.getBean( "&" + FactoryBeanWithPersistenceContextField.class.getName()); - assertNotNull(bean.em); - assertNotNull(bean2.em); + assertThat(bean.em).isNotNull(); + assertThat(bean2.em).isNotNull(); - assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em)); - assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean2.em)); + assertThat(SerializationTestUtils.serializeAndDeserialize(bean.em)).isNotNull(); + assertThat(SerializationTestUtils.serializeAndDeserialize(bean2.em)).isNotNull(); } @Test @@ -103,7 +101,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultVendorSpecificPrivatePersistenceContextField bean = (DefaultVendorSpecificPrivatePersistenceContextField) gac.getBean(DefaultVendorSpecificPrivatePersistenceContextField.class.getName()); - assertNotNull(bean.em); + assertThat(bean.em).isNotNull(); } @Test @@ -121,7 +119,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean( DefaultPublicPersistenceContextSetter.class.getName()); - assertNotNull(bean.em); + assertThat(bean.em).isNotNull(); } @Test @@ -141,7 +139,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT SpecificPublicPersistenceContextSetter bean = (SpecificPublicPersistenceContextSetter) gac.getBean( SpecificPublicPersistenceContextSetter.class.getName()); - assertNotNull(bean.getEntityManager()); + assertThat(bean.getEntityManager()).isNotNull(); bean.getEntityManager().flush(); verify(mockEm2).getTransaction(); verify(mockEm2).flush(); @@ -160,11 +158,11 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPrivatePersistenceContextField existingBean1 = new DefaultPrivatePersistenceContextField(); gac.getAutowireCapableBeanFactory().autowireBean(existingBean1); - assertNotNull(existingBean1.em); + assertThat(existingBean1.em).isNotNull(); DefaultPublicPersistenceContextSetter existingBean2 = new DefaultPublicPersistenceContextSetter(); gac.getAutowireCapableBeanFactory().autowireBean(existingBean2); - assertNotNull(existingBean2.em); + assertThat(existingBean2.em).isNotNull(); } @Test @@ -186,12 +184,12 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean( DefaultPublicPersistenceContextSetter.class.getName()); - assertNotNull(bean.em); - assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em)); + assertThat(bean.em).isNotNull(); + assertThat(SerializationTestUtils.serializeAndDeserialize(bean.em)).isNotNull(); SimpleMapScope serialized = (SimpleMapScope) SerializationTestUtils.serializeAndDeserialize(myScope); serialized.close(); - assertTrue(DummyInvocationHandler.closed); + assertThat(DummyInvocationHandler.closed).isTrue(); DummyInvocationHandler.closed = false; } @@ -217,8 +215,8 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean( DefaultPublicPersistenceContextSetter.class.getName()); - assertNotNull(bean.em); - assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em)); + assertThat(bean.em).isNotNull(); + assertThat(SerializationTestUtils.serializeAndDeserialize(bean.em)).isNotNull(); } @Test @@ -236,7 +234,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean( DefaultPublicPersistenceContextSetter.class.getName()); - assertSame(mockEm2, bean.em); + assertThat(bean.em).isSameAs(mockEm2); } @Test @@ -251,7 +249,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPrivatePersistenceUnitField bean = (DefaultPrivatePersistenceUnitField) gac.getBean( DefaultPrivatePersistenceUnitField.class.getName()); - assertSame(mockEmf, bean.emf); + assertThat(bean.emf).isSameAs(mockEmf); } @Test @@ -266,7 +264,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPublicPersistenceUnitSetter bean = (DefaultPublicPersistenceUnitSetter) gac.getBean( DefaultPublicPersistenceUnitSetter.class.getName()); - assertSame(mockEmf, bean.emf); + assertThat(bean.emf).isSameAs(mockEmf); } @Test @@ -284,7 +282,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPublicPersistenceUnitSetter bean = (DefaultPublicPersistenceUnitSetter) gac.getBean( DefaultPublicPersistenceUnitSetter.class.getName()); - assertSame(mockEmf2, bean.emf); + assertThat(bean.emf).isSameAs(mockEmf2); } @Test @@ -308,8 +306,8 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT gac.getBean(DefaultPublicPersistenceUnitSetter.class.getName()); DefaultPublicPersistenceUnitSetterNamedPerson bean2 = (DefaultPublicPersistenceUnitSetterNamedPerson) gac.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName()); - assertSame(mockEmf, bean.emf); - assertSame(mockEmf2, bean2.emf); + assertThat(bean.emf).isSameAs(mockEmf); + assertThat(bean2.emf).isSameAs(mockEmf2); } @Test @@ -333,8 +331,8 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT gac.getBean(DefaultPublicPersistenceUnitSetter.class.getName()); DefaultPublicPersistenceUnitSetterNamedPerson bean2 = (DefaultPublicPersistenceUnitSetterNamedPerson) gac.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName()); - assertSame(mockEmf, bean.emf); - assertSame(mockEmf2, bean2.emf); + assertThat(bean.emf).isSameAs(mockEmf); + assertThat(bean2.emf).isSameAs(mockEmf2); } @Test @@ -374,10 +372,10 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT bf.getBean(DefaultPrivatePersistenceContextField.class.getName()); DefaultPublicPersistenceContextSetter bean4 = (DefaultPublicPersistenceContextSetter) bf.getBean(DefaultPublicPersistenceContextSetter.class.getName()); - assertSame(mockEmf, bean.emf); - assertSame(mockEmf2, bean2.emf); - assertNotNull(bean3.em); - assertNotNull(bean4.em); + assertThat(bean.emf).isSameAs(mockEmf); + assertThat(bean2.emf).isSameAs(mockEmf2); + assertThat(bean3.em).isNotNull(); + assertThat(bean4.em).isNotNull(); } @Test @@ -406,8 +404,8 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT bf.getBean(DefaultPublicPersistenceUnitSetter.class.getName()); DefaultPublicPersistenceUnitSetterNamedPerson bean2 = (DefaultPublicPersistenceUnitSetterNamedPerson) bf.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName()); - assertSame(mockEmf, bean.emf); - assertSame(mockEmf2, bean2.emf); + assertThat(bean.emf).isSameAs(mockEmf); + assertThat(bean2.emf).isSameAs(mockEmf2); } @Test @@ -431,8 +429,8 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT bf.getBean(DefaultPublicPersistenceUnitSetter.class.getName()); DefaultPublicPersistenceUnitSetterNamedPerson bean2 = (DefaultPublicPersistenceUnitSetterNamedPerson) bf.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName()); - assertSame(mockEmf, bean.emf); - assertSame(mockEmf, bean2.emf); + assertThat(bean.emf).isSameAs(mockEmf); + assertThat(bean2.emf).isSameAs(mockEmf); } @Test @@ -470,9 +468,9 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT bf.getBean(DefaultPrivatePersistenceContextFieldNamedPerson.class.getName()); DefaultPublicPersistenceContextSetter bean3 = (DefaultPublicPersistenceContextSetter) bf.getBean(DefaultPublicPersistenceContextSetter.class.getName()); - assertSame(mockEm, bean1.em); - assertSame(mockEm2, bean2.em); - assertSame(mockEm3, bean3.em); + assertThat(bean1.em).isSameAs(mockEm); + assertThat(bean2.em).isSameAs(mockEm2); + assertThat(bean3.em).isSameAs(mockEm3); } @Test @@ -511,9 +509,9 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT bf.getBean(DefaultPrivatePersistenceContextFieldNamedPerson.class.getName()); DefaultPublicPersistenceContextSetter bean3 = (DefaultPublicPersistenceContextSetter) bf.getBean(DefaultPublicPersistenceContextSetter.class.getName()); - assertSame(mockEm, bean1.em); - assertSame(mockEm2, bean2.em); - assertSame(mockEm3, bean3.em); + assertThat(bean1.em).isSameAs(mockEm); + assertThat(bean2.em).isSameAs(mockEm2); + assertThat(bean3.em).isSameAs(mockEm3); } @Test @@ -544,8 +542,8 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT bf.getBean(DefaultPrivatePersistenceContextField.class.getName()); DefaultPublicPersistenceContextSetter bean2 = (DefaultPublicPersistenceContextSetter) bf.getBean(DefaultPublicPersistenceContextSetter.class.getName()); - assertSame(mockEm, bean1.em); - assertSame(mockEm2, bean2.em); + assertThat(bean1.em).isSameAs(mockEm); + assertThat(bean2.em).isSameAs(mockEm2); } @Test @@ -577,7 +575,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT PersistenceAnnotationBeanPostProcessor pabpp = new MockPersistenceAnnotationBeanPostProcessor(); DefaultPrivatePersistenceContextFieldExtended dppcf = new DefaultPrivatePersistenceContextFieldExtended(); pabpp.postProcessProperties(null, dppcf, "bean"); - assertNotNull(dppcf.em); + assertThat(dppcf.em).isNotNull(); } @Test @@ -591,7 +589,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPrivatePersistenceContextFieldExtendedWithProps dppcf = new DefaultPrivatePersistenceContextFieldExtendedWithProps(); pabpp.postProcessProperties(null, dppcf, "bean"); - assertNotNull(dppcf.em); + assertThat(dppcf.em).isNotNull(); } @Test @@ -608,8 +606,8 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT new DefaultPrivatePersistenceContextFieldWithProperties(); pabpp.postProcessProperties(null, transactionalField, "bean"); - assertNotNull(transactionalField.em); - assertNotNull(transactionalField.em.getDelegate()); + assertThat(transactionalField.em).isNotNull(); + assertThat(transactionalField.em.getDelegate()).isNotNull(); verify(em).close(); } @@ -636,14 +634,14 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT pabpp.postProcessProperties(null, transactionalFieldWithProperties, "bean1"); pabpp.postProcessProperties(null, transactionalField, "bean2"); - assertNotNull(transactionalFieldWithProperties.em); - assertNotNull(transactionalField.em); + assertThat(transactionalFieldWithProperties.em).isNotNull(); + assertThat(transactionalField.em).isNotNull(); // the EM w/ properties will be created - assertNotNull(transactionalFieldWithProperties.em.getDelegate()); + assertThat(transactionalFieldWithProperties.em.getDelegate()).isNotNull(); // bind em to the thread now since it's created try { TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em)); - assertNotNull(transactionalField.em.getDelegate()); + assertThat(transactionalField.em.getDelegate()).isNotNull(); verify(em).close(); } finally { @@ -669,14 +667,14 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT pabpp.postProcessProperties(null, transactionalFieldWithProperties, "bean1"); pabpp.postProcessProperties(null, transactionalField, "bean2"); - assertNotNull(transactionalFieldWithProperties.em); - assertNotNull(transactionalField.em); + assertThat(transactionalFieldWithProperties.em).isNotNull(); + assertThat(transactionalField.em).isNotNull(); // the EM w/o properties will be created - assertNotNull(transactionalField.em.getDelegate()); + assertThat(transactionalField.em.getDelegate()).isNotNull(); // bind em to the thread now since it's created try { TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em)); - assertNotNull(transactionalFieldWithProperties.em.getDelegate()); + assertThat(transactionalFieldWithProperties.em.getDelegate()).isNotNull(); verify(em).close(); } finally { diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java index 3ecca6d8079..2bae2217219 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java @@ -25,10 +25,8 @@ import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.orm.jpa.EntityManagerProxy; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -54,27 +52,28 @@ public class SharedEntityManagerFactoryTests { proxyFactoryBean.setEntityManagerFactory(mockEmf); proxyFactoryBean.afterPropertiesSet(); - assertTrue(EntityManager.class.isAssignableFrom(proxyFactoryBean.getObjectType())); - assertTrue(proxyFactoryBean.isSingleton()); + assertThat(EntityManager.class.isAssignableFrom(proxyFactoryBean.getObjectType())).isTrue(); + assertThat(proxyFactoryBean.isSingleton()).isTrue(); EntityManager proxy = proxyFactoryBean.getObject(); - assertSame(proxy, proxyFactoryBean.getObject()); - assertFalse(proxy.contains(o)); + assertThat(proxyFactoryBean.getObject()).isSameAs(proxy); + assertThat(proxy.contains(o)).isFalse(); - assertTrue(proxy instanceof EntityManagerProxy); + boolean condition = proxy instanceof EntityManagerProxy; + assertThat(condition).isTrue(); EntityManagerProxy emProxy = (EntityManagerProxy) proxy; assertThatIllegalStateException().as("outside of transaction").isThrownBy( emProxy::getTargetEntityManager); TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(mockEm)); try { - assertSame(mockEm, emProxy.getTargetEntityManager()); + assertThat(emProxy.getTargetEntityManager()).isSameAs(mockEm); } finally { TransactionSynchronizationManager.unbindResource(mockEmf); } - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); verify(mockEm).contains(o); verify(mockEm).close(); } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java index b956a3f6f94..fc3e19a3046 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java @@ -39,7 +39,6 @@ import org.springframework.tests.XmlContent; import org.springframework.util.xml.StaxUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; /** * @author Arjen Poutsma @@ -95,7 +94,8 @@ public abstract class AbstractMarshallerTests { DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); DOMResult domResult = new DOMResult(); marshaller.marshal(flights, domResult); - assertTrue("DOMResult does not contain a Document", domResult.getNode() instanceof Document); + boolean condition = domResult.getNode() instanceof Document; + assertThat(condition).as("DOMResult does not contain a Document").isTrue(); Document result = (Document) domResult.getNode(); Document expected = builder.newDocument(); Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights"); diff --git a/spring-oxm/src/test/java/org/springframework/oxm/AbstractUnmarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/AbstractUnmarshallerTests.java index 40930dcdd5a..c756f043e38 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/AbstractUnmarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/AbstractUnmarshallerTests.java @@ -40,7 +40,7 @@ import org.xml.sax.XMLReader; import org.springframework.util.xml.StaxUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -146,11 +146,9 @@ public abstract class AbstractUnmarshallerTests { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING)); streamReader.nextTag(); // skip to flights - assertEquals("Invalid element", new QName("http://samples.springframework.org/flight", "flights"), - streamReader.getName()); + assertThat(streamReader.getName()).as("Invalid element").isEqualTo(new QName("http://samples.springframework.org/flight", "flights")); streamReader.nextTag(); // skip to flight - assertEquals("Invalid element", new QName("http://samples.springframework.org/flight", "flight"), - streamReader.getName()); + assertThat(streamReader.getName()).as("Invalid element").isEqualTo(new QName("http://samples.springframework.org/flight", "flight")); Source source = StaxUtils.createStaxSource(streamReader); Object flight = unmarshaller.unmarshal(source); testFlight(flight); diff --git a/spring-oxm/src/test/java/org/springframework/oxm/config/OxmNamespaceHandlerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/config/OxmNamespaceHandlerTests.java index 38f26c955fc..6aacdba3743 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/config/OxmNamespaceHandlerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/config/OxmNamespaceHandlerTests.java @@ -22,7 +22,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.oxm.jaxb.Jaxb2Marshaller; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests the {@link OxmNamespaceHandler} class. @@ -40,13 +40,13 @@ public class OxmNamespaceHandlerTests { @Test public void jaxb2ContextPathMarshaller() { Jaxb2Marshaller jaxb2Marshaller = applicationContext.getBean("jaxb2ContextPathMarshaller", Jaxb2Marshaller.class); - assertNotNull(jaxb2Marshaller); + assertThat(jaxb2Marshaller).isNotNull(); } @Test public void jaxb2ClassesToBeBoundMarshaller() { Jaxb2Marshaller jaxb2Marshaller = applicationContext.getBean("jaxb2ClassesMarshaller", Jaxb2Marshaller.class); - assertNotNull(jaxb2Marshaller); + assertThat(jaxb2Marshaller).isNotNull(); } } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java index 2d3782d12de..6a74339b4b0 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java @@ -59,9 +59,6 @@ import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; @@ -196,32 +193,29 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTests", - marshaller.supports(method.getGenericReturnType())); + assertThat(marshaller.supports(method.getGenericReturnType())).as("Jaxb2Marshaller does not support JAXBElement").isTrue(); marshaller.setSupportJaxbElementClass(true); JAXBElement flightTypeJAXBElement = new JAXBElement<>(new QName("https://springframework.org", "flight"), FlightType.class, new FlightType()); - assertTrue("Jaxb2Marshaller does not support JAXBElement", marshaller.supports(flightTypeJAXBElement.getClass())); + assertThat(marshaller.supports(flightTypeJAXBElement.getClass())).as("Jaxb2Marshaller does not support JAXBElement").isTrue(); - assertFalse("Jaxb2Marshaller supports class not in context path", marshaller.supports(DummyRootElement.class)); - assertFalse("Jaxb2Marshaller supports type not in context path", marshaller.supports((Type)DummyRootElement.class)); + assertThat(marshaller.supports(DummyRootElement.class)).as("Jaxb2Marshaller supports class not in context path").isFalse(); + assertThat(marshaller.supports((Type)DummyRootElement.class)).as("Jaxb2Marshaller supports type not in context path").isFalse(); method = getClass().getDeclaredMethod("createDummyRootElement"); - assertFalse("Jaxb2Marshaller supports JAXBElement not in context path", - marshaller.supports(method.getGenericReturnType())); + assertThat(marshaller.supports(method.getGenericReturnType())).as("Jaxb2Marshaller supports JAXBElement not in context path").isFalse(); - assertFalse("Jaxb2Marshaller supports class not in context path", marshaller.supports(DummyType.class)); - assertFalse("Jaxb2Marshaller supports type not in context path", marshaller.supports((Type)DummyType.class)); + assertThat(marshaller.supports(DummyType.class)).as("Jaxb2Marshaller supports class not in context path").isFalse(); + assertThat(marshaller.supports((Type)DummyType.class)).as("Jaxb2Marshaller supports type not in context path").isFalse(); method = getClass().getDeclaredMethod("createDummyType"); - assertFalse("Jaxb2Marshaller supports JAXBElement not in context path", - marshaller.supports(method.getGenericReturnType())); + assertThat(marshaller.supports(method.getGenericReturnType())).as("Jaxb2Marshaller supports JAXBElement not in context path").isFalse(); testSupportsPrimitives(); testSupportsStandardClasses(); @@ -233,8 +227,7 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTests", - marshaller.supports(returnType)); + assertThat(marshaller.supports(returnType)).as("Jaxb2Marshaller does not support JAXBElement<" + method.getName().substring(9) + ">").isTrue(); try { // make sure the marshalling does not result in errors Object returnValue = method.invoke(primitives); @@ -258,8 +251,7 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTests", - marshaller.supports(returnType)); + assertThat(marshaller.supports(returnType)).as("Jaxb2Marshaller does not support JAXBElement<" + method.getName().substring(13) + ">").isTrue(); try { // make sure the marshalling does not result in errors Object returnValue = method.invoke(standardClasses); @@ -282,11 +274,11 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTests 0); + assertThat(writer.toString().length() > 0).as("No XML written").isTrue(); verify(mimeContainer, times(3)).addAttachment(isA(String.class), isA(DataHandler.class)); } @@ -341,8 +333,8 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTests 0); - assertNotNull("datahandler property not set", object.getSwaDataHandler()); + assertThat(object.getBytes()).as("bytes property not set").isNotNull(); + assertThat(object.getBytes().length > 0).as("bytes property not set").isTrue(); + assertThat(object.getSwaDataHandler()).as("datahandler property not set").isNotNull(); } @Test @@ -133,8 +132,7 @@ public class Jaxb2UnmarshallerTests extends AbstractUnmarshallerTeststest")); JAXBElement airplane = (JAXBElement) unmarshaller.unmarshal(source); - assertEquals("Unmarshalling via explicit @XmlRegistry tag should return correct type", - "test", airplane.getValue().getName()); + assertThat(airplane.getValue().getName()).as("Unmarshalling via explicit @XmlRegistry tag should return correct type").isEqualTo("test"); } @Test diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java index 356c3824a46..6777076f330 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java @@ -27,8 +27,6 @@ import org.springframework.tests.XmlContent; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; /** @@ -90,8 +88,7 @@ public class JibxMarshallerTests extends AbstractMarshallerTests marshaller.setStandalone(Boolean.TRUE); StringWriter writer = new StringWriter(); marshaller.marshal(flights, new StreamResult(writer)); - assertTrue("Encoding and standalone not set", - writer.toString().startsWith("")); + assertThat(writer.toString().startsWith("")).as("Encoding and standalone not set").isTrue(); } @Test @@ -100,15 +97,14 @@ public class JibxMarshallerTests extends AbstractMarshallerTests marshaller.setDocTypeSystemId("flights.dtd"); StringWriter writer = new StringWriter(); marshaller.marshal(flights, new StreamResult(writer)); - assertTrue("doc type not written", - writer.toString().contains("")); + assertThat(writer.toString().contains("")).as("doc type not written").isTrue(); } @Test public void supports() throws Exception { - assertTrue("JibxMarshaller does not support Flights", marshaller.supports(Flights.class)); - assertTrue("JibxMarshaller does not support FlightType", marshaller.supports(FlightType.class)); - assertFalse("JibxMarshaller supports illegal type", marshaller.supports(getClass())); + assertThat(marshaller.supports(Flights.class)).as("JibxMarshaller does not support Flights").isTrue(); + assertThat(marshaller.supports(FlightType.class)).as("JibxMarshaller does not support FlightType").isTrue(); + assertThat(marshaller.supports(getClass())).as("JibxMarshaller supports illegal type").isFalse(); } } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxUnmarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxUnmarshallerTests.java index a914829ef08..dad6e158c9f 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxUnmarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxUnmarshallerTests.java @@ -24,8 +24,7 @@ import org.junit.Test; import org.springframework.oxm.AbstractUnmarshallerTests; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; /** @@ -61,16 +60,16 @@ public class JibxUnmarshallerTests extends AbstractUnmarshallerTestsAQI="); Reader reader = new StringReader(writer.toString()); byte[] bufResult = (byte[]) marshaller.unmarshal(new StreamSource(reader)); - assertTrue("Invalid result", Arrays.equals(buf, bufResult)); + assertThat(Arrays.equals(buf, bufResult)).as("Invalid result").isTrue(); } @Test @@ -314,12 +311,12 @@ public class XStreamMarshallerTests { marshaller.setStreamDriver(new JettisonMappedXmlDriver()); Writer writer = new StringWriter(); marshaller.marshal(flight, new StreamResult(writer)); - assertEquals("Invalid result", "{\"flight\":{\"flightNumber\":42}}", writer.toString()); + assertThat(writer.toString()).as("Invalid result").isEqualTo("{\"flight\":{\"flightNumber\":42}}"); Object o = marshaller.unmarshal(new StreamSource(new StringReader(writer.toString()))); - assertTrue("Unmarshalled object is not Flights", o instanceof Flight); + assertThat(o instanceof Flight).as("Unmarshalled object is not Flights").isTrue(); Flight unflight = (Flight) o; - assertNotNull("Flight is null", unflight); - assertEquals("Number is invalid", 42L, unflight.getFlightNumber()); + assertThat(unflight).as("Flight is null").isNotNull(); + assertThat(unflight.getFlightNumber()).as("Number is invalid").isEqualTo(42L); } @Test @@ -335,7 +332,7 @@ public class XStreamMarshallerTests { Writer writer = new StringWriter(); marshaller.marshal(flight, new StreamResult(writer)); - assertEquals("Invalid result", "{\"flightNumber\": 42}", writer.toString()); + assertThat(writer.toString()).as("Invalid result").isEqualTo("{\"flightNumber\": 42}"); } @Test @@ -354,17 +351,17 @@ public class XStreamMarshallerTests { private static void assertXpathExists(String xPathExpression, String inXMLString){ Source source = Input.fromString(inXMLString).build(); Iterable nodes = new JAXPXPathEngine().selectNodes(xPathExpression, source); - assertTrue("Expecting to find matches for Xpath " + xPathExpression, count(nodes) > 0); + assertThat(count(nodes) > 0).as("Expecting to find matches for Xpath " + xPathExpression).isTrue(); } private static void assertXpathNotExists(String xPathExpression, String inXMLString){ Source source = Input.fromString(inXMLString).build(); Iterable nodes = new JAXPXPathEngine().selectNodes(xPathExpression, source); - assertEquals("Should be zero matches for Xpath " + xPathExpression, 0, count(nodes)); + assertThat(count(nodes)).as("Should be zero matches for Xpath " + xPathExpression).isEqualTo(0); } private static int count(Iterable nodes) { - assertNotNull(nodes); + assertThat(nodes).isNotNull(); AtomicInteger count = new AtomicInteger(); nodes.forEach(n -> count.incrementAndGet()); return count.get(); diff --git a/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamUnmarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamUnmarshallerTests.java index 05b2dd7eeaf..cc7787811f1 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamUnmarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamUnmarshallerTests.java @@ -35,9 +35,7 @@ import org.xml.sax.InputSource; import org.springframework.util.xml.StaxUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -57,10 +55,11 @@ public class XStreamUnmarshallerTests { } private void testFlight(Object o) { - assertTrue("Unmarshalled object is not Flights", o instanceof Flight); + boolean condition = o instanceof Flight; + assertThat(condition).as("Unmarshalled object is not Flights").isTrue(); Flight flight = (Flight) o; - assertNotNull("Flight is null", flight); - assertEquals("Number is invalid", 42L, flight.getFlightNumber()); + assertThat(flight).as("Flight is null").isNotNull(); + assertThat(flight.getFlightNumber()).as("Number is invalid").isEqualTo(42L); } @Test diff --git a/spring-test/src/test/java/org/springframework/mock/http/server/reactive/MockServerHttpRequestTests.java b/spring-test/src/test/java/org/springframework/mock/http/server/reactive/MockServerHttpRequestTests.java index b8fbe75fd06..3e29bec482d 100644 --- a/spring-test/src/test/java/org/springframework/mock/http/server/reactive/MockServerHttpRequestTests.java +++ b/spring-test/src/test/java/org/springframework/mock/http/server/reactive/MockServerHttpRequestTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import org.springframework.http.HttpCookie; import org.springframework.http.HttpHeaders; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link MockServerHttpRequest}. @@ -40,10 +40,9 @@ public class MockServerHttpRequestTests { MockServerHttpRequest request = MockServerHttpRequest.get("/") .cookie(foo11, foo12, foo21, foo22).build(); - assertEquals(Arrays.asList(foo11, foo12), request.getCookies().get("foo1")); - assertEquals(Arrays.asList(foo21, foo22), request.getCookies().get("foo2")); - assertEquals(Arrays.asList("foo1=bar1", "foo1=bar2", "foo2=baz1", "foo2=baz2"), - request.getHeaders().get(HttpHeaders.COOKIE)); + assertThat(request.getCookies().get("foo1")).isEqualTo(Arrays.asList(foo11, foo12)); + assertThat(request.getCookies().get("foo2")).isEqualTo(Arrays.asList(foo21, foo22)); + assertThat(request.getHeaders().get(HttpHeaders.COOKIE)).isEqualTo(Arrays.asList("foo1=bar1", "foo1=bar2", "foo2=baz1", "foo2=baz2")); } @Test @@ -53,8 +52,7 @@ public class MockServerHttpRequestTests { .queryParam("name B", "value B1") .build(); - assertEquals("/foo%20bar?a=b&name%20A=value%20A1&name%20A=value%20A2&name%20B=value%20B1", - request.getURI().toString()); + assertThat(request.getURI().toString()).isEqualTo("/foo%20bar?a=b&name%20A=value%20A1&name%20A=value%20A2&name%20B=value%20B1"); } } diff --git a/spring-test/src/test/java/org/springframework/mock/http/server/reactive/MockServerHttpResponseTests.java b/spring-test/src/test/java/org/springframework/mock/http/server/reactive/MockServerHttpResponseTests.java index 6ca6fa0dad3..2eb73f8f40e 100644 --- a/spring-test/src/test/java/org/springframework/mock/http/server/reactive/MockServerHttpResponseTests.java +++ b/spring-test/src/test/java/org/springframework/mock/http/server/reactive/MockServerHttpResponseTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseCookie; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link MockServerHttpResponse}. @@ -46,8 +46,7 @@ public class MockServerHttpResponseTests { response.applyCookies(); - assertEquals(Arrays.asList("foo1=bar1", "foo1=bar2", "foo2=baz1", "foo2=baz2"), - response.getHeaders().get(HttpHeaders.SET_COOKIE)); + assertThat(response.getHeaders().get(HttpHeaders.SET_COOKIE)).isEqualTo(Arrays.asList("foo1=bar1", "foo1=bar2", "foo2=baz1", "foo2=baz2")); } } diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockCookieTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockCookieTests.java index 24105f0297b..5d18b338325 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockCookieTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockCookieTests.java @@ -18,11 +18,8 @@ package org.springframework.mock.web; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link MockCookie}. @@ -39,12 +36,12 @@ public class MockCookieTests { MockCookie cookie = new MockCookie("SESSION", "123"); assertCookie(cookie, "SESSION", "123"); - assertNull(cookie.getDomain()); - assertEquals(-1, cookie.getMaxAge()); - assertNull(cookie.getPath()); - assertFalse(cookie.isHttpOnly()); - assertFalse(cookie.getSecure()); - assertNull(cookie.getSameSite()); + assertThat(cookie.getDomain()).isNull(); + assertThat(cookie.getMaxAge()).isEqualTo(-1); + assertThat(cookie.getPath()).isNull(); + assertThat(cookie.isHttpOnly()).isFalse(); + assertThat(cookie.getSecure()).isFalse(); + assertThat(cookie.getSameSite()).isNull(); } @Test @@ -52,7 +49,7 @@ public class MockCookieTests { MockCookie cookie = new MockCookie("SESSION", "123"); cookie.setSameSite("Strict"); - assertEquals("Strict", cookie.getSameSite()); + assertThat(cookie.getSameSite()).isEqualTo("Strict"); } @Test @@ -70,17 +67,17 @@ public class MockCookieTests { "SESSION=123; Domain=example.com; Max-Age=60; Path=/; Secure; HttpOnly; SameSite=Lax"); assertCookie(cookie, "SESSION", "123"); - assertEquals("example.com", cookie.getDomain()); - assertEquals(60, cookie.getMaxAge()); - assertEquals("/", cookie.getPath()); - assertTrue(cookie.getSecure()); - assertTrue(cookie.isHttpOnly()); - assertEquals("Lax", cookie.getSameSite()); + assertThat(cookie.getDomain()).isEqualTo("example.com"); + assertThat(cookie.getMaxAge()).isEqualTo(60); + assertThat(cookie.getPath()).isEqualTo("/"); + assertThat(cookie.getSecure()).isTrue(); + assertThat(cookie.isHttpOnly()).isTrue(); + assertThat(cookie.getSameSite()).isEqualTo("Lax"); } private void assertCookie(MockCookie cookie, String name, String value) { - assertEquals(name, cookie.getName()); - assertEquals(value, cookie.getValue()); + assertThat(cookie.getName()).isEqualTo(name); + assertThat(cookie.getValue()).isEqualTo(value); } @Test @@ -112,12 +109,12 @@ public class MockCookieTests { "SESSION=123; domain=example.com; max-age=60; path=/; secure; httponly; samesite=Lax"); assertCookie(cookie, "SESSION", "123"); - assertEquals("example.com", cookie.getDomain()); - assertEquals(60, cookie.getMaxAge()); - assertEquals("/", cookie.getPath()); - assertTrue(cookie.getSecure()); - assertTrue(cookie.isHttpOnly()); - assertEquals("Lax", cookie.getSameSite()); + assertThat(cookie.getDomain()).isEqualTo("example.com"); + assertThat(cookie.getMaxAge()).isEqualTo(60); + assertThat(cookie.getPath()).isEqualTo("/"); + assertThat(cookie.getSecure()).isTrue(); + assertThat(cookie.isHttpOnly()).isTrue(); + assertThat(cookie.getSameSite()).isEqualTo("Lax"); } } diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java index 9fc2a953f59..eee25d18ae8 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java @@ -31,7 +31,6 @@ 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.assertThatIllegalStateException; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -112,8 +111,8 @@ public class MockFilterChainTests { chain.doFilter(this.request, this.response); - assertTrue(filter1.invoked); - assertTrue(filter2.invoked); + assertThat(filter1.invoked).isTrue(); + assertThat(filter2.invoked).isTrue(); verify(servlet).service(this.request, this.response); diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java index 6f5bc2fa634..2cb9c63d913 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java @@ -35,13 +35,9 @@ import org.springframework.http.HttpHeaders; import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link MockHttpServletRequest}. @@ -63,44 +59,44 @@ public class MockHttpServletRequestTests { @Test public void protocolAndScheme() { - assertEquals(MockHttpServletRequest.DEFAULT_PROTOCOL, request.getProtocol()); - assertEquals(MockHttpServletRequest.DEFAULT_SCHEME, request.getScheme()); + assertThat(request.getProtocol()).isEqualTo(MockHttpServletRequest.DEFAULT_PROTOCOL); + assertThat(request.getScheme()).isEqualTo(MockHttpServletRequest.DEFAULT_SCHEME); request.setProtocol("HTTP/2.0"); request.setScheme("https"); - assertEquals("HTTP/2.0", request.getProtocol()); - assertEquals("https", request.getScheme()); + assertThat(request.getProtocol()).isEqualTo("HTTP/2.0"); + assertThat(request.getScheme()).isEqualTo("https"); } @Test public void setContentAndGetInputStream() throws IOException { byte[] bytes = "body".getBytes(Charset.defaultCharset()); request.setContent(bytes); - assertEquals(bytes.length, request.getContentLength()); - assertEquals("body", StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset())); + assertThat(request.getContentLength()).isEqualTo(bytes.length); + assertThat(StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset())).isEqualTo("body"); request.setContent(bytes); - assertEquals(bytes.length, request.getContentLength()); - assertEquals("body", StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset())); + assertThat(request.getContentLength()).isEqualTo(bytes.length); + assertThat(StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset())).isEqualTo("body"); } @Test public void setContentAndGetReader() throws IOException { byte[] bytes = "body".getBytes(Charset.defaultCharset()); request.setContent(bytes); - assertEquals(bytes.length, request.getContentLength()); - assertEquals("body", FileCopyUtils.copyToString(request.getReader())); + assertThat(request.getContentLength()).isEqualTo(bytes.length); + assertThat(FileCopyUtils.copyToString(request.getReader())).isEqualTo("body"); request.setContent(bytes); - assertEquals(bytes.length, request.getContentLength()); - assertEquals("body", FileCopyUtils.copyToString(request.getReader())); + assertThat(request.getContentLength()).isEqualTo(bytes.length); + assertThat(FileCopyUtils.copyToString(request.getReader())).isEqualTo("body"); } @Test public void setContentAndGetContentAsByteArray() { byte[] bytes = "request body".getBytes(); request.setContent(bytes); - assertEquals(bytes.length, request.getContentLength()); - assertEquals(bytes, request.getContentAsByteArray()); + assertThat(request.getContentLength()).isEqualTo(bytes.length); + assertThat(request.getContentAsByteArray()).isEqualTo(bytes); } @Test @@ -116,29 +112,29 @@ public class MockHttpServletRequestTests { byte[] bytes = palindrome.getBytes("UTF-16"); request.setCharacterEncoding("UTF-16"); request.setContent(bytes); - assertEquals(bytes.length, request.getContentLength()); - assertEquals(palindrome, request.getContentAsString()); + assertThat(request.getContentLength()).isEqualTo(bytes.length); + assertThat(request.getContentAsString()).isEqualTo(palindrome); } @Test public void noContent() throws IOException { - assertEquals(-1, request.getContentLength()); - assertEquals(-1, request.getInputStream().read()); - assertNull(request.getContentAsByteArray()); + assertThat(request.getContentLength()).isEqualTo(-1); + assertThat(request.getInputStream().read()).isEqualTo(-1); + assertThat(request.getContentAsByteArray()).isNull(); } @Test // SPR-16505 public void getReaderTwice() throws IOException { byte[] bytes = "body".getBytes(Charset.defaultCharset()); request.setContent(bytes); - assertSame(request.getReader(), request.getReader()); + assertThat(request.getReader()).isSameAs(request.getReader()); } @Test // SPR-16505 public void getInputStreamTwice() throws IOException { byte[] bytes = "body".getBytes(Charset.defaultCharset()); request.setContent(bytes); - assertSame(request.getInputStream(), request.getInputStream()); + assertThat(request.getInputStream()).isSameAs(request.getInputStream()); } @Test // SPR-16499 @@ -161,63 +157,63 @@ public class MockHttpServletRequestTests { public void setContentType() { String contentType = "test/plain"; request.setContentType(contentType); - assertEquals(contentType, request.getContentType()); - assertEquals(contentType, request.getHeader(HttpHeaders.CONTENT_TYPE)); - assertNull(request.getCharacterEncoding()); + assertThat(request.getContentType()).isEqualTo(contentType); + assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo(contentType); + assertThat(request.getCharacterEncoding()).isNull(); } @Test public void setContentTypeUTF8() { String contentType = "test/plain;charset=UTF-8"; request.setContentType(contentType); - assertEquals(contentType, request.getContentType()); - assertEquals(contentType, request.getHeader(HttpHeaders.CONTENT_TYPE)); - assertEquals("UTF-8", request.getCharacterEncoding()); + assertThat(request.getContentType()).isEqualTo(contentType); + assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo(contentType); + assertThat(request.getCharacterEncoding()).isEqualTo("UTF-8"); } @Test public void contentTypeHeader() { String contentType = "test/plain"; request.addHeader(HttpHeaders.CONTENT_TYPE, contentType); - assertEquals(contentType, request.getContentType()); - assertEquals(contentType, request.getHeader(HttpHeaders.CONTENT_TYPE)); - assertNull(request.getCharacterEncoding()); + assertThat(request.getContentType()).isEqualTo(contentType); + assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo(contentType); + assertThat(request.getCharacterEncoding()).isNull(); } @Test public void contentTypeHeaderUTF8() { String contentType = "test/plain;charset=UTF-8"; request.addHeader(HttpHeaders.CONTENT_TYPE, contentType); - assertEquals(contentType, request.getContentType()); - assertEquals(contentType, request.getHeader(HttpHeaders.CONTENT_TYPE)); - assertEquals("UTF-8", request.getCharacterEncoding()); + assertThat(request.getContentType()).isEqualTo(contentType); + assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo(contentType); + assertThat(request.getCharacterEncoding()).isEqualTo("UTF-8"); } @Test // SPR-12677 public void setContentTypeHeaderWithMoreComplexCharsetSyntax() { String contentType = "test/plain;charset=\"utf-8\";foo=\"charset=bar\";foocharset=bar;foo=bar"; request.addHeader(HttpHeaders.CONTENT_TYPE, contentType); - assertEquals(contentType, request.getContentType()); - assertEquals(contentType, request.getHeader(HttpHeaders.CONTENT_TYPE)); - assertEquals("UTF-8", request.getCharacterEncoding()); + assertThat(request.getContentType()).isEqualTo(contentType); + assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo(contentType); + assertThat(request.getCharacterEncoding()).isEqualTo("UTF-8"); } @Test public void setContentTypeThenCharacterEncoding() { request.setContentType("test/plain"); request.setCharacterEncoding("UTF-8"); - assertEquals("test/plain", request.getContentType()); - assertEquals("test/plain;charset=UTF-8", request.getHeader(HttpHeaders.CONTENT_TYPE)); - assertEquals("UTF-8", request.getCharacterEncoding()); + assertThat(request.getContentType()).isEqualTo("test/plain"); + assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo("test/plain;charset=UTF-8"); + assertThat(request.getCharacterEncoding()).isEqualTo("UTF-8"); } @Test public void setCharacterEncodingThenContentType() { request.setCharacterEncoding("UTF-8"); request.setContentType("test/plain"); - assertEquals("test/plain", request.getContentType()); - assertEquals("test/plain;charset=UTF-8", request.getHeader(HttpHeaders.CONTENT_TYPE)); - assertEquals("UTF-8", request.getCharacterEncoding()); + assertThat(request.getContentType()).isEqualTo("test/plain"); + assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo("test/plain;charset=UTF-8"); + assertThat(request.getCharacterEncoding()).isEqualTo("UTF-8"); } @Test @@ -225,7 +221,7 @@ public class MockHttpServletRequestTests { String headerName = "Header1"; request.addHeader(headerName, "value1"); Enumeration requestHeaders = request.getHeaderNames(); - assertEquals("HTTP header casing not being preserved", headerName, requestHeaders.nextElement()); + assertThat(requestHeaders.nextElement()).as("HTTP header casing not being preserved").isEqualTo(headerName); } @Test @@ -237,13 +233,13 @@ public class MockHttpServletRequestTests { params.put("key3", new String[] { "value3A", "value3B" }); request.setParameters(params); String[] values1 = request.getParameterValues("key1"); - assertEquals(1, values1.length); - assertEquals("newValue1", request.getParameter("key1")); - assertEquals("value2", request.getParameter("key2")); + assertThat(values1.length).isEqualTo(1); + assertThat(request.getParameter("key1")).isEqualTo("newValue1"); + assertThat(request.getParameter("key2")).isEqualTo("value2"); String[] values3 = request.getParameterValues("key3"); - assertEquals(2, values3.length); - assertEquals("value3A", values3[0]); - assertEquals("value3B", values3[1]); + assertThat(values3.length).isEqualTo(2); + assertThat(values3[0]).isEqualTo("value3A"); + assertThat(values3[1]).isEqualTo("value3B"); } @Test @@ -255,14 +251,14 @@ public class MockHttpServletRequestTests { params.put("key3", new String[] { "value3A", "value3B" }); request.addParameters(params); String[] values1 = request.getParameterValues("key1"); - assertEquals(2, values1.length); - assertEquals("value1", values1[0]); - assertEquals("newValue1", values1[1]); - assertEquals("value2", request.getParameter("key2")); + assertThat(values1.length).isEqualTo(2); + assertThat(values1[0]).isEqualTo("value1"); + assertThat(values1[1]).isEqualTo("newValue1"); + assertThat(request.getParameter("key2")).isEqualTo("value2"); String[] values3 = request.getParameterValues("key3"); - assertEquals(2, values3.length); - assertEquals("value3A", values3[0]); - assertEquals("value3B", values3[1]); + assertThat(values3.length).isEqualTo(2); + assertThat(values3[0]).isEqualTo("value3A"); + assertThat(values3[1]).isEqualTo("value3B"); } @Test @@ -272,9 +268,9 @@ public class MockHttpServletRequestTests { params.put("key2", "value2"); params.put("key3", new String[] { "value3A", "value3B" }); request.addParameters(params); - assertEquals(3, request.getParameterMap().size()); + assertThat(request.getParameterMap().size()).isEqualTo(3); request.removeAllParameters(); - assertEquals(0, request.getParameterMap().size()); + assertThat(request.getParameterMap().size()).isEqualTo(0); } @Test @@ -286,17 +282,17 @@ public class MockHttpServletRequestTests { Cookie[] cookies = request.getCookies(); List cookieHeaders = Collections.list(request.getHeaders("Cookie")); - assertEquals(2, cookies.length); - assertEquals("foo", cookies[0].getName()); - assertEquals("bar", cookies[0].getValue()); - assertEquals("baz", cookies[1].getName()); - assertEquals("qux", cookies[1].getValue()); - assertEquals(Arrays.asList("foo=bar", "baz=qux"), cookieHeaders); + assertThat(cookies.length).isEqualTo(2); + assertThat(cookies[0].getName()).isEqualTo("foo"); + assertThat(cookies[0].getValue()).isEqualTo("bar"); + assertThat(cookies[1].getName()).isEqualTo("baz"); + assertThat(cookies[1].getValue()).isEqualTo("qux"); + assertThat(cookieHeaders).isEqualTo(Arrays.asList("foo=bar", "baz=qux")); } @Test public void noCookies() { - assertNull(request.getCookies()); + assertThat(request.getCookies()).isNull(); } @Test @@ -307,8 +303,8 @@ public class MockHttpServletRequestTests { Locale.setDefault(newDefaultLocale); // Create the request after changing the default locale. MockHttpServletRequest request = new MockHttpServletRequest(); - assertFalse(newDefaultLocale.equals(request.getLocale())); - assertEquals(Locale.ENGLISH, request.getLocale()); + assertThat(newDefaultLocale.equals(request.getLocale())).isFalse(); + assertThat(request.getLocale()).isEqualTo(Locale.ENGLISH); } finally { Locale.setDefault(originalDefaultLocale); @@ -332,7 +328,7 @@ public class MockHttpServletRequestTests { List preferredLocales = Arrays.asList(Locale.ITALY, Locale.CHINA); request.setPreferredLocales(preferredLocales); assertEqualEnumerations(Collections.enumeration(preferredLocales), request.getLocales()); - assertEquals("it-it, zh-cn", request.getHeader(HttpHeaders.ACCEPT_LANGUAGE)); + assertThat(request.getHeader(HttpHeaders.ACCEPT_LANGUAGE)).isEqualTo("it-it, zh-cn"); } @Test @@ -340,80 +336,80 @@ public class MockHttpServletRequestTests { String headerValue = "fr-ch, fr;q=0.9, en-*;q=0.8, de;q=0.7, *;q=0.5"; request.addHeader("Accept-Language", headerValue); List actual = Collections.list(request.getLocales()); - assertEquals(Arrays.asList(Locale.forLanguageTag("fr-ch"), Locale.forLanguageTag("fr"), - Locale.forLanguageTag("en"), Locale.forLanguageTag("de")), actual); - assertEquals(headerValue, request.getHeader("Accept-Language")); + assertThat(actual).isEqualTo(Arrays.asList(Locale.forLanguageTag("fr-ch"), Locale.forLanguageTag("fr"), + Locale.forLanguageTag("en"), Locale.forLanguageTag("de"))); + assertThat(request.getHeader("Accept-Language")).isEqualTo(headerValue); } @Test public void invalidAcceptLanguageHeader() { request.addHeader("Accept-Language", "en_US"); - assertEquals(Locale.ENGLISH, request.getLocale()); - assertEquals("en_US", request.getHeader("Accept-Language")); + assertThat(request.getLocale()).isEqualTo(Locale.ENGLISH); + assertThat(request.getHeader("Accept-Language")).isEqualTo("en_US"); } @Test public void emptyAcceptLanguageHeader() { request.addHeader("Accept-Language", ""); - assertEquals(Locale.ENGLISH, request.getLocale()); - assertEquals("", request.getHeader("Accept-Language")); + assertThat(request.getLocale()).isEqualTo(Locale.ENGLISH); + assertThat(request.getHeader("Accept-Language")).isEqualTo(""); } @Test public void getServerNameWithDefaultName() { - assertEquals("localhost", request.getServerName()); + assertThat(request.getServerName()).isEqualTo("localhost"); } @Test public void getServerNameWithCustomName() { request.setServerName("example.com"); - assertEquals("example.com", request.getServerName()); + assertThat(request.getServerName()).isEqualTo("example.com"); } @Test public void getServerNameViaHostHeaderWithoutPort() { String testServer = "test.server"; request.addHeader(HOST, testServer); - assertEquals(testServer, request.getServerName()); + assertThat(request.getServerName()).isEqualTo(testServer); } @Test public void getServerNameViaHostHeaderWithPort() { String testServer = "test.server"; request.addHeader(HOST, testServer + ":8080"); - assertEquals(testServer, request.getServerName()); + assertThat(request.getServerName()).isEqualTo(testServer); } @Test public void getServerNameViaHostHeaderAsIpv6AddressWithoutPort() { String ipv6Address = "[2001:db8:0:1]"; request.addHeader(HOST, ipv6Address); - assertEquals("2001:db8:0:1", request.getServerName()); + assertThat(request.getServerName()).isEqualTo("2001:db8:0:1"); } @Test public void getServerNameViaHostHeaderAsIpv6AddressWithPort() { String ipv6Address = "[2001:db8:0:1]:8081"; request.addHeader(HOST, ipv6Address); - assertEquals("2001:db8:0:1", request.getServerName()); + assertThat(request.getServerName()).isEqualTo("2001:db8:0:1"); } @Test public void getServerPortWithDefaultPort() { - assertEquals(80, request.getServerPort()); + assertThat(request.getServerPort()).isEqualTo(80); } @Test public void getServerPortWithCustomPort() { request.setServerPort(8080); - assertEquals(8080, request.getServerPort()); + assertThat(request.getServerPort()).isEqualTo(8080); } @Test public void getServerPortViaHostHeaderAsIpv6AddressWithoutPort() { String testServer = "[2001:db8:0:1]"; request.addHeader(HOST, testServer); - assertEquals(80, request.getServerPort()); + assertThat(request.getServerPort()).isEqualTo(80); } @Test @@ -421,14 +417,14 @@ public class MockHttpServletRequestTests { String testServer = "[2001:db8:0:1]"; int testPort = 9999; request.addHeader(HOST, testServer + ":" + testPort); - assertEquals(testPort, request.getServerPort()); + assertThat(request.getServerPort()).isEqualTo(testPort); } @Test public void getServerPortViaHostHeaderWithoutPort() { String testServer = "test.server"; request.addHeader(HOST, testServer); - assertEquals(80, request.getServerPort()); + assertThat(request.getServerPort()).isEqualTo(80); } @Test @@ -436,25 +432,25 @@ public class MockHttpServletRequestTests { String testServer = "test.server"; int testPort = 9999; request.addHeader(HOST, testServer + ":" + testPort); - assertEquals(testPort, request.getServerPort()); + assertThat(request.getServerPort()).isEqualTo(testPort); } @Test public void getRequestURL() { request.setServerPort(8080); request.setRequestURI("/path"); - assertEquals("http://localhost:8080/path", request.getRequestURL().toString()); + assertThat(request.getRequestURL().toString()).isEqualTo("http://localhost:8080/path"); request.setScheme("https"); request.setServerName("example.com"); request.setServerPort(8443); - assertEquals("https://example.com:8443/path", request.getRequestURL().toString()); + assertThat(request.getRequestURL().toString()).isEqualTo("https://example.com:8443/path"); } @Test public void getRequestURLWithDefaults() { StringBuffer requestURL = request.getRequestURL(); - assertEquals("http://localhost", requestURL.toString()); + assertThat(requestURL.toString()).isEqualTo("http://localhost"); } @Test // SPR-16138 @@ -462,7 +458,7 @@ public class MockHttpServletRequestTests { String testServer = "test.server"; request.addHeader(HOST, testServer); StringBuffer requestURL = request.getRequestURL(); - assertEquals("http://" + testServer, requestURL.toString()); + assertThat(requestURL.toString()).isEqualTo(("http://" + testServer)); } @Test // SPR-16138 @@ -470,14 +466,14 @@ public class MockHttpServletRequestTests { String testServer = "test.server:9999"; request.addHeader(HOST, testServer); StringBuffer requestURL = request.getRequestURL(); - assertEquals("http://" + testServer, requestURL.toString()); + assertThat(requestURL.toString()).isEqualTo(("http://" + testServer)); } @Test public void getRequestURLWithNullRequestUri() { request.setRequestURI(null); StringBuffer requestURL = request.getRequestURL(); - assertEquals("http://localhost", requestURL.toString()); + assertThat(requestURL.toString()).isEqualTo("http://localhost"); } @Test @@ -485,78 +481,78 @@ public class MockHttpServletRequestTests { request.setScheme("https"); request.setServerPort(443); StringBuffer requestURL = request.getRequestURL(); - assertEquals("https://localhost", requestURL.toString()); + assertThat(requestURL.toString()).isEqualTo("https://localhost"); } @Test public void getRequestURLWithNegativePort() { request.setServerPort(-99); StringBuffer requestURL = request.getRequestURL(); - assertEquals("http://localhost", requestURL.toString()); + assertThat(requestURL.toString()).isEqualTo("http://localhost"); } @Test public void isSecureWithHttpSchemeAndSecureFlagIsFalse() { - assertFalse(request.isSecure()); + assertThat(request.isSecure()).isFalse(); request.setScheme("http"); request.setSecure(false); - assertFalse(request.isSecure()); + assertThat(request.isSecure()).isFalse(); } @Test public void isSecureWithHttpSchemeAndSecureFlagIsTrue() { - assertFalse(request.isSecure()); + assertThat(request.isSecure()).isFalse(); request.setScheme("http"); request.setSecure(true); - assertTrue(request.isSecure()); + assertThat(request.isSecure()).isTrue(); } @Test public void isSecureWithHttpsSchemeAndSecureFlagIsFalse() { - assertFalse(request.isSecure()); + assertThat(request.isSecure()).isFalse(); request.setScheme("https"); request.setSecure(false); - assertTrue(request.isSecure()); + assertThat(request.isSecure()).isTrue(); } @Test public void isSecureWithHttpsSchemeAndSecureFlagIsTrue() { - assertFalse(request.isSecure()); + assertThat(request.isSecure()).isFalse(); request.setScheme("https"); request.setSecure(true); - assertTrue(request.isSecure()); + assertThat(request.isSecure()).isTrue(); } @Test public void httpHeaderDate() { Date date = new Date(); request.addHeader(HttpHeaders.IF_MODIFIED_SINCE, date); - assertEquals(date.getTime(), request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)); + assertThat(request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)).isEqualTo(date.getTime()); } @Test public void httpHeaderTimestamp() { long timestamp = new Date().getTime(); request.addHeader(HttpHeaders.IF_MODIFIED_SINCE, timestamp); - assertEquals(timestamp, request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)); + assertThat(request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)).isEqualTo(timestamp); } @Test public void httpHeaderRfcFormattedDate() { request.addHeader(HttpHeaders.IF_MODIFIED_SINCE, "Tue, 21 Jul 2015 10:00:00 GMT"); - assertEquals(1437472800000L, request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)); + assertThat(request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)).isEqualTo(1437472800000L); } @Test public void httpHeaderFirstVariantFormattedDate() { request.addHeader(HttpHeaders.IF_MODIFIED_SINCE, "Tue, 21-Jul-15 10:00:00 GMT"); - assertEquals(1437472800000L, request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)); + assertThat(request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)).isEqualTo(1437472800000L); } @Test public void httpHeaderSecondVariantFormattedDate() { request.addHeader(HttpHeaders.IF_MODIFIED_SINCE, "Tue Jul 21 10:00:00 2015"); - assertEquals(1437472800000L, request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)); + assertThat(request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)).isEqualTo(1437472800000L); } @Test @@ -569,8 +565,9 @@ public class MockHttpServletRequestTests { private void assertEqualEnumerations(Enumeration enum1, Enumeration enum2) { int count = 0; while (enum1.hasMoreElements()) { - assertTrue("enumerations must be equal in length", enum2.hasMoreElements()); - assertEquals("enumeration element #" + ++count, enum1.nextElement(), enum2.nextElement()); + assertThat(enum2.hasMoreElements()).as("enumerations must be equal in length").isTrue(); + String message = "enumeration element #" + ++count; + assertThat(enum2.nextElement()).as(message).isEqualTo(enum1.nextElement()); } } diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java index a27964246d9..1c36c1f3be3 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java @@ -27,12 +27,8 @@ import org.junit.Test; import org.springframework.http.HttpHeaders; import org.springframework.web.util.WebUtils; +import static org.assertj.core.api.Assertions.assertThat; 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; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link MockHttpServletResponse}. @@ -54,102 +50,102 @@ public class MockHttpServletResponseTests { public void setContentType() { String contentType = "test/plain"; response.setContentType(contentType); - assertEquals(contentType, response.getContentType()); - assertEquals(contentType, response.getHeader("Content-Type")); - assertEquals(WebUtils.DEFAULT_CHARACTER_ENCODING, response.getCharacterEncoding()); + assertThat(response.getContentType()).isEqualTo(contentType); + assertThat(response.getHeader("Content-Type")).isEqualTo(contentType); + assertThat(response.getCharacterEncoding()).isEqualTo(WebUtils.DEFAULT_CHARACTER_ENCODING); } @Test public void setContentTypeUTF8() { String contentType = "test/plain;charset=UTF-8"; response.setContentType(contentType); - assertEquals("UTF-8", response.getCharacterEncoding()); - assertEquals(contentType, response.getContentType()); - assertEquals(contentType, response.getHeader("Content-Type")); + assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8"); + assertThat(response.getContentType()).isEqualTo(contentType); + assertThat(response.getHeader("Content-Type")).isEqualTo(contentType); } @Test public void contentTypeHeader() { String contentType = "test/plain"; response.addHeader("Content-Type", contentType); - assertEquals(contentType, response.getContentType()); - assertEquals(contentType, response.getHeader("Content-Type")); - assertEquals(WebUtils.DEFAULT_CHARACTER_ENCODING, response.getCharacterEncoding()); + assertThat(response.getContentType()).isEqualTo(contentType); + assertThat(response.getHeader("Content-Type")).isEqualTo(contentType); + assertThat(response.getCharacterEncoding()).isEqualTo(WebUtils.DEFAULT_CHARACTER_ENCODING); response = new MockHttpServletResponse(); response.setHeader("Content-Type", contentType); - assertEquals(contentType, response.getContentType()); - assertEquals(contentType, response.getHeader("Content-Type")); - assertEquals(WebUtils.DEFAULT_CHARACTER_ENCODING, response.getCharacterEncoding()); + assertThat(response.getContentType()).isEqualTo(contentType); + assertThat(response.getHeader("Content-Type")).isEqualTo(contentType); + assertThat(response.getCharacterEncoding()).isEqualTo(WebUtils.DEFAULT_CHARACTER_ENCODING); } @Test public void contentTypeHeaderUTF8() { String contentType = "test/plain;charset=UTF-8"; response.setHeader("Content-Type", contentType); - assertEquals(contentType, response.getContentType()); - assertEquals(contentType, response.getHeader("Content-Type")); - assertEquals("UTF-8", response.getCharacterEncoding()); + assertThat(response.getContentType()).isEqualTo(contentType); + assertThat(response.getHeader("Content-Type")).isEqualTo(contentType); + assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8"); response = new MockHttpServletResponse(); response.addHeader("Content-Type", contentType); - assertEquals(contentType, response.getContentType()); - assertEquals(contentType, response.getHeader("Content-Type")); - assertEquals("UTF-8", response.getCharacterEncoding()); + assertThat(response.getContentType()).isEqualTo(contentType); + assertThat(response.getHeader("Content-Type")).isEqualTo(contentType); + assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8"); } @Test // SPR-12677 public void contentTypeHeaderWithMoreComplexCharsetSyntax() { String contentType = "test/plain;charset=\"utf-8\";foo=\"charset=bar\";foocharset=bar;foo=bar"; response.setHeader("Content-Type", contentType); - assertEquals(contentType, response.getContentType()); - assertEquals(contentType, response.getHeader("Content-Type")); - assertEquals("UTF-8", response.getCharacterEncoding()); + assertThat(response.getContentType()).isEqualTo(contentType); + assertThat(response.getHeader("Content-Type")).isEqualTo(contentType); + assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8"); response = new MockHttpServletResponse(); response.addHeader("Content-Type", contentType); - assertEquals(contentType, response.getContentType()); - assertEquals(contentType, response.getHeader("Content-Type")); - assertEquals("UTF-8", response.getCharacterEncoding()); + assertThat(response.getContentType()).isEqualTo(contentType); + assertThat(response.getHeader("Content-Type")).isEqualTo(contentType); + assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8"); } @Test public void setContentTypeThenCharacterEncoding() { response.setContentType("test/plain"); response.setCharacterEncoding("UTF-8"); - assertEquals("test/plain", response.getContentType()); - assertEquals("test/plain;charset=UTF-8", response.getHeader("Content-Type")); - assertEquals("UTF-8", response.getCharacterEncoding()); + assertThat(response.getContentType()).isEqualTo("test/plain"); + assertThat(response.getHeader("Content-Type")).isEqualTo("test/plain;charset=UTF-8"); + assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8"); } @Test public void setCharacterEncodingThenContentType() { response.setCharacterEncoding("UTF-8"); response.setContentType("test/plain"); - assertEquals("test/plain", response.getContentType()); - assertEquals("test/plain;charset=UTF-8", response.getHeader("Content-Type")); - assertEquals("UTF-8", response.getCharacterEncoding()); + assertThat(response.getContentType()).isEqualTo("test/plain"); + assertThat(response.getHeader("Content-Type")).isEqualTo("test/plain;charset=UTF-8"); + assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8"); } @Test public void contentLength() { response.setContentLength(66); - assertEquals(66, response.getContentLength()); - assertEquals("66", response.getHeader("Content-Length")); + assertThat(response.getContentLength()).isEqualTo(66); + assertThat(response.getHeader("Content-Length")).isEqualTo("66"); } @Test public void contentLengthHeader() { response.addHeader("Content-Length", "66"); - assertEquals(66, response.getContentLength()); - assertEquals("66", response.getHeader("Content-Length")); + assertThat(response.getContentLength()).isEqualTo(66); + assertThat(response.getHeader("Content-Length")).isEqualTo("66"); } @Test public void contentLengthIntHeader() { response.addIntHeader("Content-Length", 66); - assertEquals(66, response.getContentLength()); - assertEquals("66", response.getHeader("Content-Length")); + assertThat(response.getContentLength()).isEqualTo(66); + assertThat(response.getHeader("Content-Length")).isEqualTo("66"); } @Test @@ -157,9 +153,9 @@ public class MockHttpServletResponseTests { final String headerName = "Header1"; response.addHeader(headerName, "value1"); Collection responseHeaders = response.getHeaderNames(); - assertNotNull(responseHeaders); - assertEquals(1, responseHeaders.size()); - assertEquals("HTTP header casing not being preserved", headerName, responseHeaders.iterator().next()); + assertThat(responseHeaders).isNotNull(); + assertThat(responseHeaders.size()).isEqualTo(1); + assertThat(responseHeaders.iterator().next()).as("HTTP header casing not being preserved").isEqualTo(headerName); } @Test @@ -173,151 +169,151 @@ public class MockHttpServletResponseTests { response.addCookie(cookie); - assertEquals("foo=bar; Path=/path; Domain=example.com; " + + assertThat(response.getHeader(HttpHeaders.SET_COOKIE)).isEqualTo(("foo=bar; Path=/path; Domain=example.com; " + "Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; " + - "Secure; HttpOnly", response.getHeader(HttpHeaders.SET_COOKIE)); + "Secure; HttpOnly")); } @Test public void servletOutputStreamCommittedWhenBufferSizeExceeded() throws IOException { - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); response.getOutputStream().write('X'); - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); int size = response.getBufferSize(); response.getOutputStream().write(new byte[size]); - assertTrue(response.isCommitted()); - assertEquals(size + 1, response.getContentAsByteArray().length); + assertThat(response.isCommitted()).isTrue(); + assertThat(response.getContentAsByteArray().length).isEqualTo((size + 1)); } @Test public void servletOutputStreamCommittedOnFlushBuffer() throws IOException { - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); response.getOutputStream().write('X'); - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); response.flushBuffer(); - assertTrue(response.isCommitted()); - assertEquals(1, response.getContentAsByteArray().length); + assertThat(response.isCommitted()).isTrue(); + assertThat(response.getContentAsByteArray().length).isEqualTo(1); } @Test public void servletWriterCommittedWhenBufferSizeExceeded() throws IOException { - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); response.getWriter().write("X"); - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); int size = response.getBufferSize(); char[] data = new char[size]; Arrays.fill(data, 'p'); response.getWriter().write(data); - assertTrue(response.isCommitted()); - assertEquals(size + 1, response.getContentAsByteArray().length); + assertThat(response.isCommitted()).isTrue(); + assertThat(response.getContentAsByteArray().length).isEqualTo((size + 1)); } @Test public void servletOutputStreamCommittedOnOutputStreamFlush() throws IOException { - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); response.getOutputStream().write('X'); - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); response.getOutputStream().flush(); - assertTrue(response.isCommitted()); - assertEquals(1, response.getContentAsByteArray().length); + assertThat(response.isCommitted()).isTrue(); + assertThat(response.getContentAsByteArray().length).isEqualTo(1); } @Test public void servletWriterCommittedOnWriterFlush() throws IOException { - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); response.getWriter().write("X"); - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); response.getWriter().flush(); - assertTrue(response.isCommitted()); - assertEquals(1, response.getContentAsByteArray().length); + assertThat(response.isCommitted()).isTrue(); + assertThat(response.getContentAsByteArray().length).isEqualTo(1); } @Test // SPR-16683 public void servletWriterCommittedOnWriterClose() throws IOException { - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); response.getWriter().write("X"); - assertFalse(response.isCommitted()); + assertThat(response.isCommitted()).isFalse(); response.getWriter().close(); - assertTrue(response.isCommitted()); - assertEquals(1, response.getContentAsByteArray().length); + assertThat(response.isCommitted()).isTrue(); + assertThat(response.getContentAsByteArray().length).isEqualTo(1); } @Test public void servletWriterAutoFlushedForString() throws IOException { response.getWriter().write("X"); - assertEquals("X", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("X"); } @Test public void servletWriterAutoFlushedForChar() throws IOException { response.getWriter().write('X'); - assertEquals("X", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("X"); } @Test public void servletWriterAutoFlushedForCharArray() throws IOException { response.getWriter().write("XY".toCharArray()); - assertEquals("XY", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("XY"); } @Test public void sendRedirect() throws IOException { String redirectUrl = "/redirect"; response.sendRedirect(redirectUrl); - assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus()); - assertEquals(redirectUrl, response.getHeader("Location")); - assertEquals(redirectUrl, response.getRedirectedUrl()); - assertTrue(response.isCommitted()); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_MOVED_TEMPORARILY); + assertThat(response.getHeader("Location")).isEqualTo(redirectUrl); + assertThat(response.getRedirectedUrl()).isEqualTo(redirectUrl); + assertThat(response.isCommitted()).isTrue(); } @Test public void locationHeaderUpdatesGetRedirectedUrl() { String redirectUrl = "/redirect"; response.setHeader("Location", redirectUrl); - assertEquals(redirectUrl, response.getRedirectedUrl()); + assertThat(response.getRedirectedUrl()).isEqualTo(redirectUrl); } @Test public void setDateHeader() { response.setDateHeader("Last-Modified", 1437472800000L); - assertEquals("Tue, 21 Jul 2015 10:00:00 GMT", response.getHeader("Last-Modified")); + assertThat(response.getHeader("Last-Modified")).isEqualTo("Tue, 21 Jul 2015 10:00:00 GMT"); } @Test public void addDateHeader() { response.addDateHeader("Last-Modified", 1437472800000L); response.addDateHeader("Last-Modified", 1437472801000L); - assertEquals("Tue, 21 Jul 2015 10:00:00 GMT", response.getHeaders("Last-Modified").get(0)); - assertEquals("Tue, 21 Jul 2015 10:00:01 GMT", response.getHeaders("Last-Modified").get(1)); + assertThat(response.getHeaders("Last-Modified").get(0)).isEqualTo("Tue, 21 Jul 2015 10:00:00 GMT"); + assertThat(response.getHeaders("Last-Modified").get(1)).isEqualTo("Tue, 21 Jul 2015 10:00:01 GMT"); } @Test public void getDateHeader() { long time = 1437472800000L; response.setDateHeader("Last-Modified", time); - assertEquals("Tue, 21 Jul 2015 10:00:00 GMT", response.getHeader("Last-Modified")); - assertEquals(time, response.getDateHeader("Last-Modified")); + assertThat(response.getHeader("Last-Modified")).isEqualTo("Tue, 21 Jul 2015 10:00:00 GMT"); + assertThat(response.getDateHeader("Last-Modified")).isEqualTo(time); } @Test public void getInvalidDateHeader() { response.setHeader("Last-Modified", "invalid"); - assertEquals("invalid", response.getHeader("Last-Modified")); + assertThat(response.getHeader("Last-Modified")).isEqualTo("invalid"); assertThatIllegalArgumentException().isThrownBy(() -> response.getDateHeader("Last-Modified")); } @Test // SPR-16160 public void getNonExistentDateHeader() { - assertNull(response.getHeader("Last-Modified")); - assertEquals(-1, response.getDateHeader("Last-Modified")); + assertThat(response.getHeader("Last-Modified")).isNull(); + assertThat(response.getDateHeader("Last-Modified")).isEqualTo(-1); } @Test // SPR-10414 public void modifyStatusAfterSendError() throws IOException { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_OK); - assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_NOT_FOUND); } @Test // SPR-10414 @@ -325,21 +321,22 @@ public class MockHttpServletResponseTests { public void modifyStatusMessageAfterSendError() throws IOException { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Server Error"); - assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_NOT_FOUND); } @Test public void setCookieHeaderValid() { response.addHeader(HttpHeaders.SET_COOKIE, "SESSION=123; Path=/; Secure; HttpOnly; SameSite=Lax"); Cookie cookie = response.getCookie("SESSION"); - assertNotNull(cookie); - assertTrue(cookie instanceof MockCookie); - assertEquals("SESSION", cookie.getName()); - assertEquals("123", cookie.getValue()); - assertEquals("/", cookie.getPath()); - assertTrue(cookie.getSecure()); - assertTrue(cookie.isHttpOnly()); - assertEquals("Lax", ((MockCookie) cookie).getSameSite()); + assertThat(cookie).isNotNull(); + boolean condition = cookie instanceof MockCookie; + assertThat(condition).isTrue(); + assertThat(cookie.getName()).isEqualTo("SESSION"); + assertThat(cookie.getValue()).isEqualTo("123"); + assertThat(cookie.getPath()).isEqualTo("/"); + assertThat(cookie.getSecure()).isTrue(); + assertThat(cookie.isHttpOnly()).isTrue(); + assertThat(((MockCookie) cookie).getSameSite()).isEqualTo("Lax"); } @Test @@ -354,9 +351,8 @@ public class MockHttpServletResponseTests { response.addCookie(mockCookie); - assertEquals("SESSION=123; Path=/; Domain=example.com; Max-Age=0; " + - "Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; HttpOnly; SameSite=Lax", - response.getHeader(HttpHeaders.SET_COOKIE)); + assertThat(response.getHeader(HttpHeaders.SET_COOKIE)).isEqualTo(("SESSION=123; Path=/; Domain=example.com; Max-Age=0; " + + "Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; HttpOnly; SameSite=Lax")); } } diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockHttpSessionTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpSessionTests.java index f2f00cd6dd3..54f4f551a0e 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockHttpSessionTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockHttpSessionTests.java @@ -22,10 +22,8 @@ import javax.servlet.http.HttpSessionBindingListener; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for {@link MockHttpSession}. @@ -41,9 +39,9 @@ public class MockHttpSessionTests { @Test public void invalidateOnce() { - assertFalse(session.isInvalid()); + assertThat(session.isInvalid()).isFalse(); session.invalidate(); - assertTrue(session.isInvalid()); + assertThat(session.isInvalid()).isTrue(); } @Test @@ -137,7 +135,7 @@ public class MockHttpSessionTests { session.setAttribute(bindingListenerName, bindingListener); - assertEquals(bindingListener.getCounter(), 1); + assertThat(1).isEqualTo(bindingListener.getCounter()); } @Test @@ -148,7 +146,7 @@ public class MockHttpSessionTests { session.setAttribute(bindingListenerName, bindingListener); session.removeAttribute(bindingListenerName); - assertEquals(bindingListener.getCounter(), 0); + assertThat(0).isEqualTo(bindingListener.getCounter()); } @Test @@ -159,7 +157,7 @@ public class MockHttpSessionTests { session.setAttribute(bindingListenerName, bindingListener); session.setAttribute(bindingListenerName, bindingListener); - assertEquals(bindingListener.getCounter(), 1); + assertThat(1).isEqualTo(bindingListener.getCounter()); } @Test @@ -171,8 +169,8 @@ public class MockHttpSessionTests { session.setAttribute(bindingListenerName, bindingListener1); session.setAttribute(bindingListenerName, bindingListener2); - assertEquals(bindingListener1.getCounter(), 0); - assertEquals(bindingListener2.getCounter(), 1); + assertThat(0).isEqualTo(bindingListener1.getCounter()); + assertThat(1).isEqualTo(bindingListener2.getCounter()); } private static class CountingHttpSessionBindingListener diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockMultipartHttpServletRequestTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockMultipartHttpServletRequestTests.java index 90c62e31e8c..fd2f0bcd352 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockMultipartHttpServletRequestTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockMultipartHttpServletRequestTests.java @@ -32,10 +32,7 @@ import org.springframework.util.ObjectUtils; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -45,10 +42,10 @@ public class MockMultipartHttpServletRequestTests { @Test public void mockMultipartHttpServletRequestWithByteArray() throws IOException { MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); - assertFalse(request.getFileNames().hasNext()); - assertNull(request.getFile("file1")); - assertNull(request.getFile("file2")); - assertTrue(request.getFileMap().isEmpty()); + assertThat(request.getFileNames().hasNext()).isFalse(); + assertThat(request.getFile("file1")).isNull(); + assertThat(request.getFile("file2")).isNull(); + assertThat(request.getFileMap().isEmpty()).isTrue(); request.addFile(new MockMultipartFile("file1", "myContent1".getBytes())); request.addFile(new MockMultipartFile("file2", "myOrigFilename", "text/plain", "myContent2".getBytes())); @@ -70,29 +67,29 @@ public class MockMultipartHttpServletRequestTests { while (fileIter.hasNext()) { fileNames.add(fileIter.next()); } - assertEquals(2, fileNames.size()); - assertTrue(fileNames.contains("file1")); - assertTrue(fileNames.contains("file2")); + assertThat(fileNames.size()).isEqualTo(2); + assertThat(fileNames.contains("file1")).isTrue(); + assertThat(fileNames.contains("file2")).isTrue(); MultipartFile file1 = request.getFile("file1"); MultipartFile file2 = request.getFile("file2"); Map fileMap = request.getFileMap(); List fileMapKeys = new LinkedList<>(fileMap.keySet()); - assertEquals(2, fileMapKeys.size()); - assertEquals(file1, fileMap.get("file1")); - assertEquals(file2, fileMap.get("file2")); + assertThat(fileMapKeys.size()).isEqualTo(2); + assertThat(fileMap.get("file1")).isEqualTo(file1); + assertThat(fileMap.get("file2")).isEqualTo(file2); - assertEquals("file1", file1.getName()); - assertEquals("", file1.getOriginalFilename()); - assertNull(file1.getContentType()); - assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(), file1.getBytes())); - assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(), - FileCopyUtils.copyToByteArray(file1.getInputStream()))); - assertEquals("file2", file2.getName()); - assertEquals("myOrigFilename", file2.getOriginalFilename()); - assertEquals("text/plain", file2.getContentType()); - assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(), file2.getBytes())); - assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(), - FileCopyUtils.copyToByteArray(file2.getInputStream()))); + assertThat(file1.getName()).isEqualTo("file1"); + assertThat(file1.getOriginalFilename()).isEqualTo(""); + assertThat(file1.getContentType()).isNull(); + assertThat(ObjectUtils.nullSafeEquals("myContent1".getBytes(), file1.getBytes())).isTrue(); + assertThat(ObjectUtils.nullSafeEquals("myContent1".getBytes(), + FileCopyUtils.copyToByteArray(file1.getInputStream()))).isTrue(); + assertThat(file2.getName()).isEqualTo("file2"); + assertThat(file2.getOriginalFilename()).isEqualTo("myOrigFilename"); + assertThat(file2.getContentType()).isEqualTo("text/plain"); + assertThat(ObjectUtils.nullSafeEquals("myContent2".getBytes(), file2.getBytes())).isTrue(); + assertThat(ObjectUtils.nullSafeEquals("myContent2".getBytes(), + FileCopyUtils.copyToByteArray(file2.getInputStream()))).isTrue(); } } diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockPageContextTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockPageContextTests.java index d3153b9905d..757dac5edd7 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockPageContextTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockPageContextTests.java @@ -20,8 +20,7 @@ import javax.servlet.jsp.PageContext; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for the {@code MockPageContext} class. @@ -39,10 +38,10 @@ public class MockPageContextTests { @Test public void setAttributeWithNoScopeUsesPageScope() throws Exception { ctx.setAttribute(key, value); - assertEquals(value, ctx.getAttribute(key, PageContext.PAGE_SCOPE)); - assertNull(ctx.getAttribute(key, PageContext.APPLICATION_SCOPE)); - assertNull(ctx.getAttribute(key, PageContext.REQUEST_SCOPE)); - assertNull(ctx.getAttribute(key, PageContext.SESSION_SCOPE)); + assertThat(ctx.getAttribute(key, PageContext.PAGE_SCOPE)).isEqualTo(value); + assertThat(ctx.getAttribute(key, PageContext.APPLICATION_SCOPE)).isNull(); + assertThat(ctx.getAttribute(key, PageContext.REQUEST_SCOPE)).isNull(); + assertThat(ctx.getAttribute(key, PageContext.SESSION_SCOPE)).isNull(); } @Test @@ -50,10 +49,10 @@ public class MockPageContextTests { ctx.setAttribute(key, value, PageContext.APPLICATION_SCOPE); ctx.removeAttribute(key); - assertNull(ctx.getAttribute(key, PageContext.PAGE_SCOPE)); - assertNull(ctx.getAttribute(key, PageContext.APPLICATION_SCOPE)); - assertNull(ctx.getAttribute(key, PageContext.REQUEST_SCOPE)); - assertNull(ctx.getAttribute(key, PageContext.SESSION_SCOPE)); + assertThat(ctx.getAttribute(key, PageContext.PAGE_SCOPE)).isNull(); + assertThat(ctx.getAttribute(key, PageContext.APPLICATION_SCOPE)).isNull(); + assertThat(ctx.getAttribute(key, PageContext.REQUEST_SCOPE)).isNull(); + assertThat(ctx.getAttribute(key, PageContext.SESSION_SCOPE)).isNull(); } } diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockServletContextTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockServletContextTests.java index e5d75ad77a9..56220127d03 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockServletContextTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockServletContextTests.java @@ -26,11 +26,7 @@ import org.junit.Test; import org.springframework.http.MediaType; -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.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -46,27 +42,27 @@ public class MockServletContextTests { @Test public void listFiles() { Set paths = sc.getResourcePaths("/web"); - assertNotNull(paths); - assertTrue(paths.contains("/web/MockServletContextTests.class")); + assertThat(paths).isNotNull(); + assertThat(paths.contains("/web/MockServletContextTests.class")).isTrue(); } @Test public void listSubdirectories() { Set paths = sc.getResourcePaths("/"); - assertNotNull(paths); - assertTrue(paths.contains("/web/")); + assertThat(paths).isNotNull(); + assertThat(paths.contains("/web/")).isTrue(); } @Test public void listNonDirectory() { Set paths = sc.getResourcePaths("/web/MockServletContextTests.class"); - assertNull(paths); + assertThat(paths).isNull(); } @Test public void listInvalidPath() { Set paths = sc.getResourcePaths("/web/invalid"); - assertNull(paths); + assertThat(paths).isNull(); } @Test @@ -74,15 +70,15 @@ public class MockServletContextTests { MockServletContext sc2 = new MockServletContext(); sc.setContextPath("/"); sc.registerContext("/second", sc2); - assertSame(sc, sc.getContext("/")); - assertSame(sc2, sc.getContext("/second")); + assertThat(sc.getContext("/")).isSameAs(sc); + assertThat(sc.getContext("/second")).isSameAs(sc2); } @Test public void getMimeType() { - assertEquals("text/html", sc.getMimeType("test.html")); - assertEquals("image/gif", sc.getMimeType("test.gif")); - assertNull(sc.getMimeType("test.foobar")); + assertThat(sc.getMimeType("test.html")).isEqualTo("text/html"); + assertThat(sc.getMimeType("test.gif")).isEqualTo("image/gif"); + assertThat(sc.getMimeType("test.foobar")).isNull(); } /** @@ -92,69 +88,69 @@ public class MockServletContextTests { @Test public void getMimeTypeWithCustomConfiguredType() { sc.addMimeType("enigma", new MediaType("text", "enigma")); - assertEquals("text/enigma", sc.getMimeType("filename.enigma")); + assertThat(sc.getMimeType("filename.enigma")).isEqualTo("text/enigma"); } @Test public void servletVersion() { - assertEquals(3, sc.getMajorVersion()); - assertEquals(1, sc.getMinorVersion()); - assertEquals(3, sc.getEffectiveMajorVersion()); - assertEquals(1, sc.getEffectiveMinorVersion()); + assertThat(sc.getMajorVersion()).isEqualTo(3); + assertThat(sc.getMinorVersion()).isEqualTo(1); + assertThat(sc.getEffectiveMajorVersion()).isEqualTo(3); + assertThat(sc.getEffectiveMinorVersion()).isEqualTo(1); sc.setMajorVersion(4); sc.setMinorVersion(0); sc.setEffectiveMajorVersion(4); sc.setEffectiveMinorVersion(0); - assertEquals(4, sc.getMajorVersion()); - assertEquals(0, sc.getMinorVersion()); - assertEquals(4, sc.getEffectiveMajorVersion()); - assertEquals(0, sc.getEffectiveMinorVersion()); + assertThat(sc.getMajorVersion()).isEqualTo(4); + assertThat(sc.getMinorVersion()).isEqualTo(0); + assertThat(sc.getEffectiveMajorVersion()).isEqualTo(4); + assertThat(sc.getEffectiveMinorVersion()).isEqualTo(0); } @Test public void registerAndUnregisterNamedDispatcher() throws Exception { final String name = "test-servlet"; final String url = "/test"; - assertNull(sc.getNamedDispatcher(name)); + assertThat(sc.getNamedDispatcher(name)).isNull(); sc.registerNamedDispatcher(name, new MockRequestDispatcher(url)); RequestDispatcher namedDispatcher = sc.getNamedDispatcher(name); - assertNotNull(namedDispatcher); + assertThat(namedDispatcher).isNotNull(); MockHttpServletResponse response = new MockHttpServletResponse(); namedDispatcher.forward(new MockHttpServletRequest(sc), response); - assertEquals(url, response.getForwardedUrl()); + assertThat(response.getForwardedUrl()).isEqualTo(url); sc.unregisterNamedDispatcher(name); - assertNull(sc.getNamedDispatcher(name)); + assertThat(sc.getNamedDispatcher(name)).isNull(); } @Test public void getNamedDispatcherForDefaultServlet() throws Exception { final String name = "default"; RequestDispatcher namedDispatcher = sc.getNamedDispatcher(name); - assertNotNull(namedDispatcher); + assertThat(namedDispatcher).isNotNull(); MockHttpServletResponse response = new MockHttpServletResponse(); namedDispatcher.forward(new MockHttpServletRequest(sc), response); - assertEquals(name, response.getForwardedUrl()); + assertThat(response.getForwardedUrl()).isEqualTo(name); } @Test public void setDefaultServletName() throws Exception { final String originalDefault = "default"; final String newDefault = "test"; - assertNotNull(sc.getNamedDispatcher(originalDefault)); + assertThat(sc.getNamedDispatcher(originalDefault)).isNotNull(); sc.setDefaultServletName(newDefault); - assertEquals(newDefault, sc.getDefaultServletName()); - assertNull(sc.getNamedDispatcher(originalDefault)); + assertThat(sc.getDefaultServletName()).isEqualTo(newDefault); + assertThat(sc.getNamedDispatcher(originalDefault)).isNull(); RequestDispatcher namedDispatcher = sc.getNamedDispatcher(newDefault); - assertNotNull(namedDispatcher); + assertThat(namedDispatcher).isNotNull(); MockHttpServletResponse response = new MockHttpServletResponse(); namedDispatcher.forward(new MockHttpServletRequest(sc), response); - assertEquals(newDefault, response.getForwardedUrl()); + assertThat(response.getForwardedUrl()).isEqualTo(newDefault); } /** @@ -162,7 +158,7 @@ public class MockServletContextTests { */ @Test public void getServletRegistration() { - assertNull(sc.getServletRegistration("servlet")); + assertThat(sc.getServletRegistration("servlet")).isNull(); } /** @@ -171,8 +167,8 @@ public class MockServletContextTests { @Test public void getServletRegistrations() { Map servletRegistrations = sc.getServletRegistrations(); - assertNotNull(servletRegistrations); - assertEquals(0, servletRegistrations.size()); + assertThat(servletRegistrations).isNotNull(); + assertThat(servletRegistrations.size()).isEqualTo(0); } /** @@ -180,7 +176,7 @@ public class MockServletContextTests { */ @Test public void getFilterRegistration() { - assertNull(sc.getFilterRegistration("filter")); + assertThat(sc.getFilterRegistration("filter")).isNull(); } /** @@ -189,8 +185,8 @@ public class MockServletContextTests { @Test public void getFilterRegistrations() { Map filterRegistrations = sc.getFilterRegistrations(); - assertNotNull(filterRegistrations); - assertEquals(0, filterRegistrations.size()); + assertThat(filterRegistrations).isNotNull(); + assertThat(filterRegistrations.size()).isEqualTo(0); } } diff --git a/spring-test/src/test/java/org/springframework/test/annotation/ProfileValueUtilsTests.java b/spring-test/src/test/java/org/springframework/test/annotation/ProfileValueUtilsTests.java index dee476ff097..0e55bf94e65 100644 --- a/spring-test/src/test/java/org/springframework/test/annotation/ProfileValueUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/annotation/ProfileValueUtilsTests.java @@ -23,8 +23,7 @@ import java.lang.reflect.Method; import org.junit.BeforeClass; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ProfileValueUtils}. @@ -48,39 +47,35 @@ public class ProfileValueUtilsTests { } private void assertClassIsEnabled(Class testClass) throws Exception { - assertTrue("Test class [" + testClass + "] should be enabled.", - ProfileValueUtils.isTestEnabledInThisEnvironment(testClass)); + assertThat(ProfileValueUtils.isTestEnabledInThisEnvironment(testClass)).as("Test class [" + testClass + "] should be enabled.").isTrue(); } private void assertClassIsDisabled(Class testClass) throws Exception { - assertFalse("Test class [" + testClass + "] should be disabled.", - ProfileValueUtils.isTestEnabledInThisEnvironment(testClass)); + assertThat(ProfileValueUtils.isTestEnabledInThisEnvironment(testClass)).as("Test class [" + testClass + "] should be disabled.").isFalse(); } private void assertMethodIsEnabled(String methodName, Class testClass) throws Exception { Method testMethod = testClass.getMethod(methodName); - assertTrue("Test method [" + testMethod + "] should be enabled.", - ProfileValueUtils.isTestEnabledInThisEnvironment(testMethod, testClass)); + assertThat(ProfileValueUtils.isTestEnabledInThisEnvironment(testMethod, testClass)).as("Test method [" + testMethod + "] should be enabled.").isTrue(); } private void assertMethodIsDisabled(String methodName, Class testClass) throws Exception { Method testMethod = testClass.getMethod(methodName); - assertFalse("Test method [" + testMethod + "] should be disabled.", - ProfileValueUtils.isTestEnabledInThisEnvironment(testMethod, testClass)); + assertThat(ProfileValueUtils.isTestEnabledInThisEnvironment(testMethod, testClass)).as("Test method [" + testMethod + "] should be disabled.").isFalse(); } private void assertMethodIsEnabled(ProfileValueSource profileValueSource, String methodName, Class testClass) throws Exception { Method testMethod = testClass.getMethod(methodName); - assertTrue("Test method [" + testMethod + "] should be enabled for ProfileValueSource [" + profileValueSource - + "].", ProfileValueUtils.isTestEnabledInThisEnvironment(profileValueSource, testMethod, testClass)); + assertThat(ProfileValueUtils.isTestEnabledInThisEnvironment(profileValueSource, testMethod, testClass)).as("Test method [" + testMethod + "] should be enabled for ProfileValueSource [" + profileValueSource + + "].").isTrue(); } private void assertMethodIsDisabled(ProfileValueSource profileValueSource, String methodName, Class testClass) throws Exception { Method testMethod = testClass.getMethod(methodName); - assertFalse("Test method [" + testMethod + "] should be disabled for ProfileValueSource [" + profileValueSource - + "].", ProfileValueUtils.isTestEnabledInThisEnvironment(profileValueSource, testMethod, testClass)); + assertThat(ProfileValueUtils.isTestEnabledInThisEnvironment(profileValueSource, testMethod, testClass)).as("Test method [" + testMethod + "] should be disabled for ProfileValueSource [" + profileValueSource + + "].").isFalse(); } // ------------------------------------------------------------------- diff --git a/spring-test/src/test/java/org/springframework/test/context/BootstrapUtilsTests.java b/spring-test/src/test/java/org/springframework/test/context/BootstrapUtilsTests.java index 06613c51fb4..132a0ab70ef 100644 --- a/spring-test/src/test/java/org/springframework/test/context/BootstrapUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/BootstrapUtilsTests.java @@ -25,9 +25,8 @@ import org.springframework.test.context.support.DefaultTestContextBootstrapper; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.context.web.WebTestContextBootstrapper; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper; @@ -102,8 +101,8 @@ public class BootstrapUtilsTests { private void assertBootstrapper(Class testClass, Class expectedBootstrapper) { BootstrapContext bootstrapContext = BootstrapTestUtils.buildBootstrapContext(testClass, delegate); TestContextBootstrapper bootstrapper = resolveTestContextBootstrapper(bootstrapContext); - assertNotNull(bootstrapper); - assertEquals(expectedBootstrapper, bootstrapper.getClass()); + assertThat(bootstrapper).isNotNull(); + assertThat(bootstrapper.getClass()).isEqualTo(expectedBootstrapper); } // ------------------------------------------------------------------- diff --git a/spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java b/spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java index a2acde1250d..446da181d35 100644 --- a/spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java @@ -35,8 +35,6 @@ import org.springframework.test.annotation.DirtiesContext.HierarchyMode; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Integration tests that verify proper behavior of {@link DirtiesContext @DirtiesContext} @@ -91,22 +89,22 @@ public class ContextHierarchyDirtiesContextTests { JUnitCore jUnitCore = new JUnitCore(); Result result = jUnitCore.run(testClass); - assertTrue("all tests passed", result.wasSuccessful()); + assertThat(result.wasSuccessful()).as("all tests passed").isTrue(); assertThat(ContextHierarchyDirtiesContextTests.context).isNotNull(); ConfigurableApplicationContext bazContext = (ConfigurableApplicationContext) ContextHierarchyDirtiesContextTests.context; - assertEquals("baz", ContextHierarchyDirtiesContextTests.baz); + assertThat(ContextHierarchyDirtiesContextTests.baz).isEqualTo("baz"); assertThat(bazContext.isActive()).isEqualTo(isBazContextActive); ConfigurableApplicationContext barContext = (ConfigurableApplicationContext) bazContext.getParent(); assertThat(barContext).isNotNull(); - assertEquals("bar", ContextHierarchyDirtiesContextTests.bar); + assertThat(ContextHierarchyDirtiesContextTests.bar).isEqualTo("bar"); assertThat(barContext.isActive()).isEqualTo(isBarContextActive); ConfigurableApplicationContext fooContext = (ConfigurableApplicationContext) barContext.getParent(); assertThat(fooContext).isNotNull(); - assertEquals("foo", ContextHierarchyDirtiesContextTests.foo); + assertThat(ContextHierarchyDirtiesContextTests.foo).isEqualTo("foo"); assertThat(fooContext.isActive()).isEqualTo(isFooContextActive); } diff --git a/spring-test/src/test/java/org/springframework/test/context/MergedContextConfigurationTests.java b/spring-test/src/test/java/org/springframework/test/context/MergedContextConfigurationTests.java index f67c5bf6efa..90e76ca2edf 100644 --- a/spring-test/src/test/java/org/springframework/test/context/MergedContextConfigurationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/MergedContextConfigurationTests.java @@ -27,8 +27,7 @@ import org.springframework.context.support.GenericApplicationContext; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.test.context.support.GenericXmlContextLoader; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -56,14 +55,14 @@ public class MergedContextConfigurationTests { public void hashCodeWithNulls() { MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(null, null, null, null, null); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(null, null, null, null, null); - assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode()); } @Test public void hashCodeWithNullArrays() { MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), null, null, null, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), null, null, null, loader); - assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode()); } @Test @@ -72,7 +71,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); - assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode()); } @Test @@ -81,7 +80,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, new AnnotationConfigContextLoader()); - assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode()); } @Test @@ -91,7 +90,7 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); - assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode()); } @Test @@ -102,7 +101,7 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations2, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); - assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode()); } @Test @@ -112,7 +111,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, classes, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, classes, EMPTY_STRING_ARRAY, loader); - assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode()); } @Test @@ -123,7 +122,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, classes1, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, classes2, EMPTY_STRING_ARRAY, loader); - assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode()); } @Test @@ -133,7 +132,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles, loader); - assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode()); } @Test @@ -144,7 +143,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles1, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader); - assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode()); } @Test @@ -155,7 +154,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles1, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader); - assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode()); } @Test @@ -166,7 +165,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles1, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader); - assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode()); } @Test @@ -185,7 +184,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader); - assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode()); } @Test @@ -202,7 +201,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader); - assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode()); } /** @@ -217,7 +216,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent); - assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode()); } /** @@ -234,29 +233,29 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent1); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent2); - assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode()); } @Test public void equalsBasics() { MergedContextConfiguration mergedConfig = new MergedContextConfiguration(null, null, null, null, null); - assertEquals(mergedConfig, mergedConfig); - assertNotEquals(mergedConfig, null); - assertNotEquals(mergedConfig, 1); + assertThat(mergedConfig).isEqualTo(mergedConfig); + assertThat(mergedConfig).isNotEqualTo(null); + assertThat(mergedConfig).isNotEqualTo(1); } @Test public void equalsWithNulls() { MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(null, null, null, null, null); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(null, null, null, null, null); - assertEquals(mergedConfig1, mergedConfig2); + assertThat(mergedConfig2).isEqualTo(mergedConfig1); } @Test public void equalsWithNullArrays() { MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), null, null, null, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), null, null, null, loader); - assertEquals(mergedConfig1, mergedConfig2); + assertThat(mergedConfig2).isEqualTo(mergedConfig1); } @Test @@ -265,7 +264,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); - assertEquals(mergedConfig1, mergedConfig2); + assertThat(mergedConfig2).isEqualTo(mergedConfig1); } @Test @@ -274,8 +273,8 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, new AnnotationConfigContextLoader()); - assertNotEquals(mergedConfig1, mergedConfig2); - assertNotEquals(mergedConfig2, mergedConfig1); + assertThat(mergedConfig2).isNotEqualTo(mergedConfig1); + assertThat(mergedConfig1).isNotEqualTo(mergedConfig2); } @Test @@ -285,7 +284,7 @@ public class MergedContextConfigurationTests { locations, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); - assertEquals(mergedConfig1, mergedConfig2); + assertThat(mergedConfig2).isEqualTo(mergedConfig1); } @Test @@ -296,8 +295,8 @@ public class MergedContextConfigurationTests { locations1, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations2, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); - assertNotEquals(mergedConfig1, mergedConfig2); - assertNotEquals(mergedConfig2, mergedConfig1); + assertThat(mergedConfig2).isNotEqualTo(mergedConfig1); + assertThat(mergedConfig1).isNotEqualTo(mergedConfig2); } @Test @@ -307,7 +306,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, classes, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, classes, EMPTY_STRING_ARRAY, loader); - assertEquals(mergedConfig1, mergedConfig2); + assertThat(mergedConfig2).isEqualTo(mergedConfig1); } @Test @@ -318,8 +317,8 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, classes1, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, classes2, EMPTY_STRING_ARRAY, loader); - assertNotEquals(mergedConfig1, mergedConfig2); - assertNotEquals(mergedConfig2, mergedConfig1); + assertThat(mergedConfig2).isNotEqualTo(mergedConfig1); + assertThat(mergedConfig1).isNotEqualTo(mergedConfig2); } @Test @@ -329,7 +328,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles, loader); - assertEquals(mergedConfig1, mergedConfig2); + assertThat(mergedConfig2).isEqualTo(mergedConfig1); } @Test @@ -340,7 +339,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles1, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader); - assertNotEquals(mergedConfig1, mergedConfig2); + assertThat(mergedConfig2).isNotEqualTo(mergedConfig1); } @Test @@ -351,7 +350,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles1, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader); - assertEquals(mergedConfig1, mergedConfig2); + assertThat(mergedConfig2).isEqualTo(mergedConfig1); } @Test @@ -362,8 +361,8 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles1, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader); - assertNotEquals(mergedConfig1, mergedConfig2); - assertNotEquals(mergedConfig2, mergedConfig1); + assertThat(mergedConfig2).isNotEqualTo(mergedConfig1); + assertThat(mergedConfig1).isNotEqualTo(mergedConfig2); } @Test @@ -382,7 +381,7 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader); - assertEquals(mergedConfig1, mergedConfig2); + assertThat(mergedConfig2).isEqualTo(mergedConfig1); } @Test @@ -399,8 +398,8 @@ public class MergedContextConfigurationTests { EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader); - assertNotEquals(mergedConfig1, mergedConfig2); - assertNotEquals(mergedConfig2, mergedConfig1); + assertThat(mergedConfig2).isNotEqualTo(mergedConfig1); + assertThat(mergedConfig1).isNotEqualTo(mergedConfig2); } /** @@ -413,7 +412,7 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, null, null, customizers, loader, null, null); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, null, null, customizers, loader, null, null); - assertEquals(mergedConfig1, mergedConfig2); + assertThat(mergedConfig2).isEqualTo(mergedConfig1); } /** @@ -428,8 +427,8 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, null, null, customizers1, loader, null, null); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, null, null, customizers2, loader, null, null); - assertNotEquals(mergedConfig1, mergedConfig2); - assertNotEquals(mergedConfig2, mergedConfig1); + assertThat(mergedConfig2).isNotEqualTo(mergedConfig1); + assertThat(mergedConfig1).isNotEqualTo(mergedConfig2); } /** @@ -444,8 +443,8 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent); - assertEquals(mergedConfig1, mergedConfig2); - assertEquals(mergedConfig2, mergedConfig1); + assertThat(mergedConfig2).isEqualTo(mergedConfig1); + assertThat(mergedConfig1).isEqualTo(mergedConfig2); } /** @@ -462,8 +461,8 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent1); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent2); - assertNotEquals(mergedConfig1, mergedConfig2); - assertNotEquals(mergedConfig2, mergedConfig1); + assertThat(mergedConfig2).isNotEqualTo(mergedConfig1); + assertThat(mergedConfig1).isNotEqualTo(mergedConfig2); } diff --git a/spring-test/src/test/java/org/springframework/test/context/TestContextConcurrencyTests.java b/spring-test/src/test/java/org/springframework/test/context/TestContextConcurrencyTests.java index 39f507c336c..c4b7d5f7718 100644 --- a/spring-test/src/test/java/org/springframework/test/context/TestContextConcurrencyTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/TestContextConcurrencyTests.java @@ -27,7 +27,6 @@ import org.junit.Test; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toCollection; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Integration tests that verify proper concurrency support between a @@ -77,7 +76,7 @@ public class TestContextConcurrencyTests { }); assertThat(actualMethods).isEqualTo(expectedMethods); }); - assertEquals(0, tcm.getTestContext().attributeNames().length); + assertThat(tcm.getTestContext().attributeNames().length).isEqualTo(0); } @@ -131,7 +130,7 @@ public class TestContextConcurrencyTests { @Override public void afterTestMethod(TestContext testContext) throws Exception { - assertEquals(this.methodName.get(), testContext.getAttribute("method")); + assertThat(testContext.getAttribute("method")).isEqualTo(this.methodName.get()); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/TestContextManagerSuppressedExceptionsTests.java b/spring-test/src/test/java/org/springframework/test/context/TestContextManagerSuppressedExceptionsTests.java index d2d35361688..934f7ddee5d 100644 --- a/spring-test/src/test/java/org/springframework/test/context/TestContextManagerSuppressedExceptionsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/TestContextManagerSuppressedExceptionsTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; /** * JUnit 4 based unit tests for {@link TestContextManager}, which verify proper @@ -55,7 +54,7 @@ public class TestContextManagerSuppressedExceptionsTests { private void test(String useCase, Class testClass, Callback callback) throws Exception { TestContextManager testContextManager = new TestContextManager(testClass); - assertEquals("Registered TestExecutionListeners", 2, testContextManager.getTestExecutionListeners().size()); + assertThat(testContextManager.getTestExecutionListeners().size()).as("Registered TestExecutionListeners").isEqualTo(2); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> { Method testMethod = getClass().getMethod("toString"); diff --git a/spring-test/src/test/java/org/springframework/test/context/TestContextManagerTests.java b/spring-test/src/test/java/org/springframework/test/context/TestContextManagerTests.java index 3d889c26503..cfdb2314a51 100644 --- a/spring-test/src/test/java/org/springframework/test/context/TestContextManagerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/TestContextManagerTests.java @@ -23,7 +23,7 @@ import java.util.List; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit 4 based unit test for {@link TestContextManager}, which verifies proper @@ -53,7 +53,7 @@ public class TestContextManagerTests { @Test public void listenerExecutionOrder() throws Exception { // @formatter:off - assertEquals("Registered TestExecutionListeners", 3, this.testContextManager.getTestExecutionListeners().size()); + assertThat(this.testContextManager.getTestExecutionListeners().size()).as("Registered TestExecutionListeners").isEqualTo(3); this.testContextManager.beforeTestMethod(this, this.testMethod); assertExecutionOrder("beforeTestMethod", @@ -104,8 +104,7 @@ public class TestContextManagerTests { } private static void assertExecutionOrder(String usageContext, String... expectedBeforeTestMethodCalls) { - assertEquals("execution order (" + usageContext + ") ==>", Arrays.asList(expectedBeforeTestMethodCalls), - executionOrder); + assertThat(executionOrder).as("execution order (" + usageContext + ") ==>").isEqualTo(Arrays.asList(expectedBeforeTestMethodCalls)); } diff --git a/spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java b/spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java index 50d73299d8a..af0a3b14dbb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java @@ -35,8 +35,8 @@ import org.springframework.test.context.web.ServletTestExecutionListener; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; import static org.springframework.test.context.TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS; /** @@ -182,14 +182,12 @@ public class TestExecutionListenersTests { private void assertRegisteredListeners(Class testClass, List> expected) { TestContextManager testContextManager = new TestContextManager(testClass); - assertEquals("TELs registered for " + testClass.getSimpleName(), names(expected), - names(classes(testContextManager))); + assertThat(names(classes(testContextManager))).as("TELs registered for " + testClass.getSimpleName()).isEqualTo(names(expected)); } private void assertNumRegisteredListeners(Class testClass, int expected) { TestContextManager testContextManager = new TestContextManager(testClass); - assertEquals("Num registered TELs for " + testClass, expected, - testContextManager.getTestExecutionListeners().size()); + assertThat(testContextManager.getTestExecutionListeners().size()).as("Num registered TELs for " + testClass).isEqualTo(expected); } diff --git a/spring-test/src/test/java/org/springframework/test/context/cache/ClassLevelDirtiesContextTestNGTests.java b/spring-test/src/test/java/org/springframework/test/context/cache/ClassLevelDirtiesContextTestNGTests.java index 8ed47b4a7b5..bf6d9761206 100644 --- a/spring-test/src/test/java/org/springframework/test/context/cache/ClassLevelDirtiesContextTestNGTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/cache/ClassLevelDirtiesContextTestNGTests.java @@ -38,7 +38,7 @@ import org.springframework.test.context.support.DirtiesContextTestExecutionListe import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.springframework.test.context.testng.TrackingTestNGTestListener; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.cache.ContextCacheTestUtils.assertContextCacheStatistics; import static org.springframework.test.context.cache.ContextCacheTestUtils.resetContextCache; @@ -148,12 +148,9 @@ public class ClassLevelDirtiesContextTestNGTests { testNG.setVerbose(0); testNG.run(); - assertEquals("Failures for test class [" + testClass + "].", expectedTestFailureCount, - listener.testFailureCount); - assertEquals("Tests started for test class [" + testClass + "].", expectedTestStartedCount, - listener.testStartCount); - assertEquals("Successful tests for test class [" + testClass + "].", expectedTestFinishedCount, - listener.testSuccessCount); + assertThat(listener.testFailureCount).as("Failures for test class [" + testClass + "].").isEqualTo(expectedTestFailureCount); + assertThat(listener.testStartCount).as("Tests started for test class [" + testClass + "].").isEqualTo(expectedTestStartedCount); + assertThat(listener.testSuccessCount).as("Successful tests for test class [" + testClass + "].").isEqualTo(expectedTestFinishedCount); } private void assertBehaviorForCleanTestCase() { diff --git a/spring-test/src/test/java/org/springframework/test/context/cache/ClassLevelDirtiesContextTests.java b/spring-test/src/test/java/org/springframework/test/context/cache/ClassLevelDirtiesContextTests.java index 7f0108c6636..d0f86311f16 100644 --- a/spring-test/src/test/java/org/springframework/test/context/cache/ClassLevelDirtiesContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/cache/ClassLevelDirtiesContextTests.java @@ -35,7 +35,7 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution import org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.cache.ContextCacheTestUtils.assertContextCacheStatistics; import static org.springframework.test.context.cache.ContextCacheTestUtils.resetContextCache; import static org.springframework.test.context.junit4.JUnitTestingUtils.runTestsAndAssertCounters; @@ -170,7 +170,7 @@ public class ClassLevelDirtiesContextTests { protected void assertApplicationContextWasAutowired() { - assertNotNull("The application context should have been autowired.", this.applicationContext); + assertThat(this.applicationContext).as("The application context should have been autowired.").isNotNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheTestUtils.java b/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheTestUtils.java index ba7554e9d58..ef6256a8d12 100644 --- a/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheTestUtils.java +++ b/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheTestUtils.java @@ -16,7 +16,7 @@ package org.springframework.test.context.cache; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Collection of utility methods for testing scenarios involving the @@ -60,12 +60,9 @@ public class ContextCacheTestUtils { public static final void assertContextCacheStatistics(ContextCache contextCache, String usageScenario, int expectedSize, int expectedHitCount, int expectedMissCount) { - assertEquals("Verifying number of contexts in cache (" + usageScenario + ").", expectedSize, - contextCache.size()); - assertEquals("Verifying number of cache hits (" + usageScenario + ").", expectedHitCount, - contextCache.getHitCount()); - assertEquals("Verifying number of cache misses (" + usageScenario + ").", expectedMissCount, - contextCache.getMissCount()); + assertThat(contextCache.size()).as("Verifying number of contexts in cache (" + usageScenario + ").").isEqualTo(expectedSize); + assertThat(contextCache.getHitCount()).as("Verifying number of cache hits (" + usageScenario + ").").isEqualTo(expectedHitCount); + assertThat(contextCache.getMissCount()).as("Verifying number of cache misses (" + usageScenario + ").").isEqualTo(expectedMissCount); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheTests.java b/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheTests.java index 9cdcca41d51..82b7aa19754 100644 --- a/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheTests.java @@ -32,8 +32,7 @@ import org.springframework.test.context.TestContextTestUtils; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.test.util.ReflectionTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.cache.ContextCacheTestUtils.assertContextCacheStatistics; /** @@ -58,7 +57,7 @@ public class ContextCacheTests { } private void assertParentContextCount(int expected) { - assertEquals("parent context count", expected, contextCache.getParentContextCount()); + assertThat(contextCache.getParentContextCount()).as("parent context count").isEqualTo(expected); } private MergedContextConfiguration getMergedContextConfiguration(TestContext testContext) { @@ -71,7 +70,7 @@ public class ContextCacheTests { } private void loadCtxAndAssertStats(Class testClass, int expectedSize, int expectedHitCount, int expectedMissCount) { - assertNotNull(loadContext(testClass)); + assertThat(loadContext(testClass)).isNotNull(); assertContextCacheStatistics(contextCache, testClass.getName(), expectedSize, expectedHitCount, expectedMissCount); } diff --git a/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheUtilsTests.java b/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheUtilsTests.java index a348f056671..257f7710a89 100644 --- a/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheUtilsTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import org.springframework.core.SpringProperties; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.cache.ContextCache.DEFAULT_MAX_CONTEXT_CACHE_SIZE; import static org.springframework.test.context.cache.ContextCache.MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME; import static org.springframework.test.context.cache.ContextCacheUtils.retrieveMaxCacheSize; @@ -68,23 +68,23 @@ public class ContextCacheUtilsTests { @Test public void retrieveMaxCacheSizeFromSystemProperty() { System.setProperty(MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME, "42"); - assertEquals(42, retrieveMaxCacheSize()); + assertThat(retrieveMaxCacheSize()).isEqualTo(42); } @Test public void retrieveMaxCacheSizeFromSystemPropertyContainingWhitespace() { System.setProperty(MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME, "42\t"); - assertEquals(42, retrieveMaxCacheSize()); + assertThat(retrieveMaxCacheSize()).isEqualTo(42); } @Test public void retrieveMaxCacheSizeFromSpringProperty() { SpringProperties.setProperty(MAX_CONTEXT_CACHE_SIZE_PROPERTY_NAME, "99"); - assertEquals(99, retrieveMaxCacheSize()); + assertThat(retrieveMaxCacheSize()).isEqualTo(99); } private static void assertDefaultValue() { - assertEquals(DEFAULT_MAX_CONTEXT_CACHE_SIZE, retrieveMaxCacheSize()); + assertThat(retrieveMaxCacheSize()).isEqualTo(DEFAULT_MAX_CONTEXT_CACHE_SIZE); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/cache/LruContextCacheTests.java b/spring-test/src/test/java/org/springframework/test/context/cache/LruContextCacheTests.java index dc7ec0f3d42..dd7c3e18588 100644 --- a/spring-test/src/test/java/org/springframework/test/context/cache/LruContextCacheTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/cache/LruContextCacheTests.java @@ -28,8 +28,8 @@ import org.springframework.test.util.ReflectionTestUtils; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -71,8 +71,8 @@ public class LruContextCacheTests { @Test public void maxCacheSizeOne() { DefaultContextCache cache = new DefaultContextCache(1); - assertEquals(0, cache.size()); - assertEquals(1, cache.getMaxSize()); + assertThat(cache.size()).isEqualTo(0); + assertThat(cache.getMaxSize()).isEqualTo(1); cache.put(fooConfig, fooContext); assertCacheContents(cache, "Foo"); @@ -90,8 +90,8 @@ public class LruContextCacheTests { @Test public void maxCacheSizeThree() { DefaultContextCache cache = new DefaultContextCache(3); - assertEquals(0, cache.size()); - assertEquals(3, cache.getMaxSize()); + assertThat(cache.size()).isEqualTo(0); + assertThat(cache.getMaxSize()).isEqualTo(3); cache.put(fooConfig, fooContext); assertCacheContents(cache, "Foo"); @@ -171,7 +171,7 @@ public class LruContextCacheTests { .collect(toList()); // @formatter:on - assertEquals(asList(expectedNames), actualNames); + assertThat(actualNames).isEqualTo(asList(expectedNames)); } diff --git a/spring-test/src/test/java/org/springframework/test/context/cache/MethodLevelDirtiesContextTests.java b/spring-test/src/test/java/org/springframework/test/context/cache/MethodLevelDirtiesContextTests.java index 9ffe991756f..4a2a7a893aa 100644 --- a/spring-test/src/test/java/org/springframework/test/context/cache/MethodLevelDirtiesContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/cache/MethodLevelDirtiesContextTests.java @@ -34,9 +34,7 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution import org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.annotation.DirtiesContext.MethodMode.BEFORE_METHOD; /** @@ -101,13 +99,13 @@ public class MethodLevelDirtiesContextTests { } private void performAssertions(int expectedContextCreationCount) throws Exception { - assertNotNull("context must not be null", this.context); - assertTrue("context must be active", this.context.isActive()); + assertThat(this.context).as("context must not be null").isNotNull(); + assertThat(this.context.isActive()).as("context must be active").isTrue(); - assertNotNull("count must not be null", this.count); - assertEquals("count: ", expectedContextCreationCount, this.count.intValue()); + assertThat(this.count).as("count must not be null").isNotNull(); + assertThat(this.count.intValue()).as("count: ").isEqualTo(expectedContextCreationCount); - assertEquals("context creation count: ", expectedContextCreationCount, contextCount.get()); + assertThat(contextCount.get()).as("context creation count: ").isEqualTo(expectedContextCreationCount); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/cache/SpringRunnerContextCacheTests.java b/spring-test/src/test/java/org/springframework/test/context/cache/SpringRunnerContextCacheTests.java index 8303f571eaa..df687faf811 100644 --- a/spring-test/src/test/java/org/springframework/test/context/cache/SpringRunnerContextCacheTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/cache/SpringRunnerContextCacheTests.java @@ -32,9 +32,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.cache.ContextCacheTestUtils.assertContextCacheStatistics; import static org.springframework.test.context.cache.ContextCacheTestUtils.resetContextCache; @@ -77,25 +75,23 @@ public class SpringRunnerContextCacheTests { @DirtiesContext public void dirtyContext() { assertContextCacheStatistics("dirtyContext()", 1, 0, 1); - assertNotNull("The application context should have been autowired.", this.applicationContext); + assertThat(this.applicationContext).as("The application context should have been autowired.").isNotNull(); SpringRunnerContextCacheTests.dirtiedApplicationContext = this.applicationContext; } @Test public void verifyContextDirty() { assertContextCacheStatistics("verifyContextWasDirtied()", 1, 0, 2); - assertNotNull("The application context should have been autowired.", this.applicationContext); - assertNotSame("The application context should have been 'dirtied'.", - SpringRunnerContextCacheTests.dirtiedApplicationContext, this.applicationContext); + assertThat(this.applicationContext).as("The application context should have been autowired.").isNotNull(); + assertThat(this.applicationContext).as("The application context should have been 'dirtied'.").isNotSameAs(SpringRunnerContextCacheTests.dirtiedApplicationContext); SpringRunnerContextCacheTests.dirtiedApplicationContext = this.applicationContext; } @Test public void verifyContextNotDirty() { assertContextCacheStatistics("verifyContextWasNotDirtied()", 1, 1, 2); - assertNotNull("The application context should have been autowired.", this.applicationContext); - assertSame("The application context should NOT have been 'dirtied'.", - SpringRunnerContextCacheTests.dirtiedApplicationContext, this.applicationContext); + assertThat(this.applicationContext).as("The application context should have been autowired.").isNotNull(); + assertThat(this.applicationContext).as("The application context should NOT have been 'dirtied'.").isSameAs(SpringRunnerContextCacheTests.dirtiedApplicationContext); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests.java index 942ce3ceb46..b8f378ce980 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests.java @@ -24,8 +24,7 @@ import org.springframework.test.context.ContextLoader; import org.springframework.test.context.junit4.PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests which verify that the same custom {@link ContextLoader} can @@ -51,11 +50,11 @@ public class ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLo @Test public void verifyExtendedAnnotationAutowiredFields() { - assertNotNull("The dog field should have been autowired.", this.dog); - assertEquals("Fido", this.dog.getName()); + assertThat(this.dog).as("The dog field should have been autowired.").isNotNull(); + assertThat(this.dog.getName()).isEqualTo("Fido"); - assertNotNull("The testString2 field should have been autowired.", this.testString2); - assertEquals("Test String #2", this.testString2); + assertThat(this.testString2).as("The testString2 field should have been autowired.").isNotNull(); + assertThat(this.testString2).isEqualTo("Test String #2"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests.java index a10bef21eaf..627c812f0e4 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests.java @@ -25,8 +25,7 @@ import org.springframework.test.context.junit4.PropertiesBasedSpringJUnit4ClassR import org.springframework.test.context.support.GenericPropertiesContextLoader; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests which verify that the same custom {@link ContextLoader} can @@ -52,11 +51,11 @@ public class ContextConfigurationWithPropertiesExtendingPropertiesTests extends @Test public void verifyExtendedAnnotationAutowiredFields() { - assertNotNull("The dog field should have been autowired.", this.dog); - assertEquals("Fido", this.dog.getName()); + assertThat(this.dog).as("The dog field should have been autowired.").isNotNull(); + assertThat(this.dog.getName()).isEqualTo("Fido"); - assertNotNull("The testString2 field should have been autowired.", this.testString2); - assertEquals("Test String #2", this.testString2); + assertThat(this.testString2).as("The testString2 field should have been autowired.").isNotNull(); + assertThat(this.testString2).isEqualTo("Test String #2"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ActiveProfilesInterfaceTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ActiveProfilesInterfaceTests.java index 3e0ae608851..e30db8a7dc1 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ActiveProfilesInterfaceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ActiveProfilesInterfaceTests.java @@ -26,8 +26,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.tests.sample.beans.Employee; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -42,8 +41,8 @@ public class ActiveProfilesInterfaceTests implements ActiveProfilesTestInterface @Test public void profileFromTestInterface() { - assertNotNull(employee); - assertEquals("dev", employee.getName()); + assertThat(employee).isNotNull(); + assertThat(employee.getName()).isEqualTo("dev"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/BootstrapWithInterfaceTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/BootstrapWithInterfaceTests.java index 686301d121d..8cb2ae15310 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/BootstrapWithInterfaceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/BootstrapWithInterfaceTests.java @@ -22,7 +22,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -37,7 +37,7 @@ public class BootstrapWithInterfaceTests implements BootstrapWithTestInterface { @Test public void injectedBean() { - assertEquals("foo", foo); + assertThat(foo).isEqualTo("foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ContextConfigurationInterfaceTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ContextConfigurationInterfaceTests.java index e11702f1ef6..17594448cb1 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ContextConfigurationInterfaceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ContextConfigurationInterfaceTests.java @@ -23,8 +23,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.tests.sample.beans.Employee; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -39,8 +38,8 @@ public class ContextConfigurationInterfaceTests implements ContextConfigurationT @Test public void profileFromTestInterface() { - assertNotNull(employee); - assertEquals("Dilbert", employee.getName()); + assertThat(employee).isNotNull(); + assertThat(employee.getName()).isEqualTo("Dilbert"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ContextHierarchyInterfaceTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ContextHierarchyInterfaceTests.java index 9a70192f8c3..21d24c366c6 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ContextHierarchyInterfaceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ContextHierarchyInterfaceTests.java @@ -23,9 +23,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -49,12 +47,12 @@ public class ContextHierarchyInterfaceTests implements ContextHierarchyTestInter @Test public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNotNull("parent ApplicationContext", context.getParent()); - assertNull("grandparent ApplicationContext", context.getParent().getParent()); - assertEquals("foo", foo); - assertEquals("bar", bar); - assertEquals("baz-child", baz); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNotNull(); + assertThat(context.getParent().getParent()).as("grandparent ApplicationContext").isNull(); + assertThat(foo).isEqualTo("foo"); + assertThat(bar).isEqualTo("bar"); + assertThat(baz).isEqualTo("baz-child"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/DirtiesContextInterfaceTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/DirtiesContextInterfaceTests.java index 5c68570e786..73195564f1a 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/DirtiesContextInterfaceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/DirtiesContextInterfaceTests.java @@ -32,7 +32,7 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution import org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.cache.ContextCacheTestUtils.assertContextCacheStatistics; import static org.springframework.test.context.cache.ContextCacheTestUtils.resetContextCache; import static org.springframework.test.context.junit4.JUnitTestingUtils.runTestsAndAssertCounters; @@ -92,7 +92,7 @@ public class DirtiesContextInterfaceTests { @Test public void verifyContextWasAutowired() { - assertNotNull("The application context should have been autowired.", this.applicationContext); + assertThat(this.applicationContext).as("The application context should have been autowired.").isNotNull(); } diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/SqlConfigInterfaceTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/SqlConfigInterfaceTests.java index b7ecdf53763..5998734353f 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/SqlConfigInterfaceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/SqlConfigInterfaceTests.java @@ -22,7 +22,7 @@ import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.SqlConfig; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -40,7 +40,7 @@ public class SqlConfigInterfaceTests extends AbstractTransactionalJUnit4SpringCo } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/WebAppConfigurationInterfaceTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/WebAppConfigurationInterfaceTests.java index 4cd9a3d491f..e470c55f575 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/WebAppConfigurationInterfaceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/WebAppConfigurationInterfaceTests.java @@ -23,7 +23,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -38,7 +38,7 @@ public class WebAppConfigurationInterfaceTests implements WebAppConfigurationTes @Test public void wacLoaded() { - assertNotNull(wac); + assertThat(wac).isNotNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/env/ApplicationPropertyOverridePropertiesFileTestPropertySourceTests.java b/spring-test/src/test/java/org/springframework/test/context/env/ApplicationPropertyOverridePropertiesFileTestPropertySourceTests.java index 588a7731e01..c4dca5e9e8c 100644 --- a/spring-test/src/test/java/org/springframework/test/context/env/ApplicationPropertyOverridePropertiesFileTestPropertySourceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/env/ApplicationPropertyOverridePropertiesFileTestPropertySourceTests.java @@ -27,7 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link TestPropertySource @TestPropertySource} @@ -50,7 +50,7 @@ public class ApplicationPropertyOverridePropertiesFileTestPropertySourceTests { @Test public void verifyPropertiesAreAvailableInEnvironment() { - assertEquals("test override", env.getProperty("explicit")); + assertThat(env.getProperty("explicit")).isEqualTo("test override"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/env/DefaultPropertiesFileDetectionTestPropertySourceTests.java b/spring-test/src/test/java/org/springframework/test/context/env/DefaultPropertiesFileDetectionTestPropertySourceTests.java index 649ba3af459..801d95da355 100644 --- a/spring-test/src/test/java/org/springframework/test/context/env/DefaultPropertiesFileDetectionTestPropertySourceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/env/DefaultPropertiesFileDetectionTestPropertySourceTests.java @@ -26,7 +26,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify detection of a default properties file @@ -51,7 +51,7 @@ public class DefaultPropertiesFileDetectionTestPropertySourceTests { } protected void assertEnvironmentValue(String key, String expected) { - assertEquals("Value of key [" + key + "].", expected, env.getProperty(key)); + assertThat(env.getProperty(key)).as("Value of key [" + key + "].").isEqualTo(expected); } diff --git a/spring-test/src/test/java/org/springframework/test/context/env/ExplicitPropertiesFileTestPropertySourceTests.java b/spring-test/src/test/java/org/springframework/test/context/env/ExplicitPropertiesFileTestPropertySourceTests.java index 4b93b0c6b27..3b1cff95988 100644 --- a/spring-test/src/test/java/org/springframework/test/context/env/ExplicitPropertiesFileTestPropertySourceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/env/ExplicitPropertiesFileTestPropertySourceTests.java @@ -26,7 +26,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link TestPropertySource @TestPropertySource} @@ -47,8 +47,8 @@ public class ExplicitPropertiesFileTestPropertySourceTests { @Test public void verifyPropertiesAreAvailableInEnvironment() { String userHomeKey = "user.home"; - assertEquals(System.getProperty(userHomeKey), env.getProperty(userHomeKey)); - assertEquals("enigma", env.getProperty("explicit")); + assertThat(env.getProperty(userHomeKey)).isEqualTo(System.getProperty(userHomeKey)); + assertThat(env.getProperty("explicit")).isEqualTo("enigma"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesOverridePropertiesFilesTestPropertySourceTests.java b/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesOverridePropertiesFilesTestPropertySourceTests.java index 38aba5deb5a..e4126646366 100644 --- a/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesOverridePropertiesFilesTestPropertySourceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesOverridePropertiesFilesTestPropertySourceTests.java @@ -27,7 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link TestPropertySource @TestPropertySource} support with @@ -50,8 +50,8 @@ public class InlinedPropertiesOverridePropertiesFilesTestPropertySourceTests { @Test public void inlinedPropertyOverridesValueFromPropertiesFile() { - assertEquals("inlined", env.getProperty("explicit")); - assertEquals("inlined", this.explicit); + assertThat(env.getProperty("explicit")).isEqualTo("inlined"); + assertThat(this.explicit).isEqualTo("inlined"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesTestPropertySourceTests.java b/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesTestPropertySourceTests.java index f36150344be..ad2a4263dba 100644 --- a/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesTestPropertySourceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/env/InlinedPropertiesTestPropertySourceTests.java @@ -28,7 +28,6 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertArrayEquals; import static org.springframework.test.context.support.TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME; /** @@ -74,7 +73,7 @@ public class InlinedPropertiesTestPropertySourceTests { "key.value.1", "key.value.2", "key.value.3" }; EnumerablePropertySource eps = (EnumerablePropertySource) env.getPropertySources().get( INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); - assertArrayEquals(expectedPropertyNames, eps.getPropertyNames()); + assertThat(eps.getPropertyNames()).isEqualTo(expectedPropertyNames); } diff --git a/spring-test/src/test/java/org/springframework/test/context/env/MergedPropertiesFilesOverriddenByInlinedPropertiesTestPropertySourceTests.java b/spring-test/src/test/java/org/springframework/test/context/env/MergedPropertiesFilesOverriddenByInlinedPropertiesTestPropertySourceTests.java index 5263321be2f..fd2c74b3049 100644 --- a/spring-test/src/test/java/org/springframework/test/context/env/MergedPropertiesFilesOverriddenByInlinedPropertiesTestPropertySourceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/env/MergedPropertiesFilesOverriddenByInlinedPropertiesTestPropertySourceTests.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.springframework.test.context.TestPropertySource; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for overriding properties from @@ -37,13 +37,13 @@ public class MergedPropertiesFilesOverriddenByInlinedPropertiesTestPropertySourc @Test @Override public void verifyPropertiesAreAvailableInEnvironment() { - assertEquals("inlined", env.getProperty("explicit")); + assertThat(env.getProperty("explicit")).isEqualTo("inlined"); } @Test @Override public void verifyExtendedPropertiesAreAvailableInEnvironment() { - assertEquals("inlined2", env.getProperty("extended")); + assertThat(env.getProperty("extended")).isEqualTo("inlined2"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/env/MergedPropertiesFilesTestPropertySourceTests.java b/spring-test/src/test/java/org/springframework/test/context/env/MergedPropertiesFilesTestPropertySourceTests.java index fc3129b65fa..92e22251064 100644 --- a/spring-test/src/test/java/org/springframework/test/context/env/MergedPropertiesFilesTestPropertySourceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/env/MergedPropertiesFilesTestPropertySourceTests.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.springframework.test.context.TestPropertySource; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for contributing additional properties @@ -35,7 +35,7 @@ public class MergedPropertiesFilesTestPropertySourceTests extends @Test public void verifyExtendedPropertiesAreAvailableInEnvironment() { - assertEquals(42, env.getProperty("extended", Integer.class).intValue()); + assertThat(env.getProperty("extended", Integer.class).intValue()).isEqualTo(42); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/env/SystemPropertyOverridePropertiesFileTestPropertySourceTests.java b/spring-test/src/test/java/org/springframework/test/context/env/SystemPropertyOverridePropertiesFileTestPropertySourceTests.java index 53985994ca7..42a0a6c7ff7 100644 --- a/spring-test/src/test/java/org/springframework/test/context/env/SystemPropertyOverridePropertiesFileTestPropertySourceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/env/SystemPropertyOverridePropertiesFileTestPropertySourceTests.java @@ -28,7 +28,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link TestPropertySource @TestPropertySource} @@ -61,7 +61,7 @@ public class SystemPropertyOverridePropertiesFileTestPropertySourceTests { @Test public void verifyPropertiesAreAvailableInEnvironment() { - assertEquals("enigma", env.getProperty(KEY)); + assertThat(env.getProperty(KEY)).isEqualTo("enigma"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/expression/ExpressionUsageTests.java b/spring-test/src/test/java/org/springframework/test/context/expression/ExpressionUsageTests.java index e567d0df1ce..f5cdb57a3da 100644 --- a/spring-test/src/test/java/org/springframework/test/context/expression/ExpressionUsageTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/expression/ExpressionUsageTests.java @@ -26,7 +26,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Andy Clement @@ -52,18 +52,18 @@ public class ExpressionUsageTests { @Test public void testSpr5906() throws Exception { // verify the property values have been evaluated as expressions - assertEquals("Dave", props.getProperty("user.name")); - assertEquals("Andy", props.getProperty("username")); + assertThat(props.getProperty("user.name")).isEqualTo("Dave"); + assertThat(props.getProperty("username")).isEqualTo("Andy"); // verify the property keys have been evaluated as expressions - assertEquals("exists", props.getProperty("Dave")); - assertEquals("exists also", props.getProperty("Andy")); + assertThat(props.getProperty("Dave")).isEqualTo("exists"); + assertThat(props.getProperty("Andy")).isEqualTo("exists also"); } @Test public void testSpr5847() throws Exception { - assertEquals("Andy", andy2.getName()); - assertEquals("Andy", andy.getName()); + assertThat(andy2.getName()).isEqualTo("Andy"); + assertThat(andy.getName()).isEqualTo("Andy"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/groovy/DefaultScriptDetectionGroovySpringContextTests.java b/spring-test/src/test/java/org/springframework/test/context/groovy/DefaultScriptDetectionGroovySpringContextTests.java index cef7f6d4402..012080a2307 100644 --- a/spring-test/src/test/java/org/springframework/test/context/groovy/DefaultScriptDetectionGroovySpringContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/groovy/DefaultScriptDetectionGroovySpringContextTests.java @@ -25,8 +25,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration test class that verifies proper detection of a default @@ -53,13 +52,13 @@ public class DefaultScriptDetectionGroovySpringContextTests { @Test public final void verifyAnnotationAutowiredFields() { - assertNotNull("The employee field should have been autowired.", this.employee); - assertEquals("Dilbert", this.employee.getName()); + assertThat(this.employee).as("The employee field should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("Dilbert"); - assertNotNull("The pet field should have been autowired.", this.pet); - assertEquals("Dogbert", this.pet.getName()); + assertThat(this.pet).as("The pet field should have been autowired.").isNotNull(); + assertThat(this.pet.getName()).isEqualTo("Dogbert"); - assertEquals("The foo field should have been autowired.", "Foo", this.foo); + assertThat(this.foo).as("The foo field should have been autowired.").isEqualTo("Foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/groovy/DefaultScriptDetectionXmlSupersedesGroovySpringContextTests.java b/spring-test/src/test/java/org/springframework/test/context/groovy/DefaultScriptDetectionXmlSupersedesGroovySpringContextTests.java index 7481af64bbb..65c2054fd79 100644 --- a/spring-test/src/test/java/org/springframework/test/context/groovy/DefaultScriptDetectionXmlSupersedesGroovySpringContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/groovy/DefaultScriptDetectionXmlSupersedesGroovySpringContextTests.java @@ -23,7 +23,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration test class that verifies proper detection of a default @@ -42,7 +42,7 @@ public class DefaultScriptDetectionXmlSupersedesGroovySpringContextTests { @Test public final void foo() { - assertEquals("The foo field should have been autowired.", "Foo", this.foo); + assertThat(this.foo).as("The foo field should have been autowired.").isEqualTo("Foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/groovy/GroovyControlGroupTests.java b/spring-test/src/test/java/org/springframework/test/context/groovy/GroovyControlGroupTests.java index d1fc22d949a..96f9aa0b624 100644 --- a/spring-test/src/test/java/org/springframework/test/context/groovy/GroovyControlGroupTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/groovy/GroovyControlGroupTests.java @@ -23,8 +23,7 @@ import org.springframework.context.support.GenericGroovyApplicationContext; import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Simple integration test to verify the expected functionality of @@ -47,19 +46,19 @@ public class GroovyControlGroupTests { ApplicationContext ctx = new GenericGroovyApplicationContext(getClass(), "context.groovy"); String foo = ctx.getBean("foo", String.class); - assertEquals("Foo", foo); + assertThat(foo).isEqualTo("Foo"); String bar = ctx.getBean("bar", String.class); - assertEquals("Bar", bar); + assertThat(bar).isEqualTo("Bar"); Pet pet = ctx.getBean(Pet.class); - assertNotNull("pet", pet); - assertEquals("Dogbert", pet.getName()); + assertThat(pet).as("pet").isNotNull(); + assertThat(pet.getName()).isEqualTo("Dogbert"); Employee employee = ctx.getBean(Employee.class); - assertNotNull("employee", employee); - assertEquals("Dilbert", employee.getName()); - assertEquals("???", employee.getCompany()); + assertThat(employee).as("employee").isNotNull(); + assertThat(employee.getName()).isEqualTo("Dilbert"); + assertThat(employee.getCompany()).isEqualTo("???"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/groovy/GroovySpringContextTests.java b/spring-test/src/test/java/org/springframework/test/context/groovy/GroovySpringContextTests.java index 1c93c449f13..9e6b9d05448 100644 --- a/spring-test/src/test/java/org/springframework/test/context/groovy/GroovySpringContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/groovy/GroovySpringContextTests.java @@ -30,10 +30,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for loading an {@code ApplicationContext} from a @@ -90,38 +87,37 @@ public class GroovySpringContextTests implements BeanNameAware, InitializingBean @Test public void verifyBeanNameSet() { - assertTrue("The bean name of this test instance should have been set to the fully qualified class name " + - "due to BeanNameAware semantics.", this.beanName.startsWith(getClass().getName())); + assertThat(this.beanName.startsWith(getClass().getName())).as("The bean name of this test instance should have been set to the fully qualified class name " + + "due to BeanNameAware semantics.").isTrue(); } @Test public void verifyBeanInitialized() { - assertTrue("This test bean should have been initialized due to InitializingBean semantics.", - this.beanInitialized); + assertThat(this.beanInitialized).as("This test bean should have been initialized due to InitializingBean semantics.").isTrue(); } @Test public void verifyAnnotationAutowiredFields() { - assertNull("The nonrequiredLong property should NOT have been autowired.", this.nonrequiredLong); - assertNotNull("The application context should have been autowired.", this.applicationContext); - assertNotNull("The pet field should have been autowired.", this.pet); - assertEquals("Dogbert", this.pet.getName()); + assertThat(this.nonrequiredLong).as("The nonrequiredLong property should NOT have been autowired.").isNull(); + assertThat(this.applicationContext).as("The application context should have been autowired.").isNotNull(); + assertThat(this.pet).as("The pet field should have been autowired.").isNotNull(); + assertThat(this.pet.getName()).isEqualTo("Dogbert"); } @Test public void verifyAnnotationAutowiredMethods() { - assertNotNull("The employee setter method should have been autowired.", this.employee); - assertEquals("Dilbert", this.employee.getName()); + assertThat(this.employee).as("The employee setter method should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("Dilbert"); } @Test public void verifyResourceAnnotationWiredFields() { - assertEquals("The foo field should have been wired via @Resource.", "Foo", this.foo); + assertThat(this.foo).as("The foo field should have been wired via @Resource.").isEqualTo("Foo"); } @Test public void verifyResourceAnnotationWiredMethods() { - assertEquals("The bar method should have been wired via @Resource.", "Bar", this.bar); + assertThat(this.bar).as("The bar method should have been wired via @Resource.").isEqualTo("Bar"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/groovy/MixedXmlAndGroovySpringContextTests.java b/spring-test/src/test/java/org/springframework/test/context/groovy/MixedXmlAndGroovySpringContextTests.java index 4ecfe45f221..ab735b61434 100644 --- a/spring-test/src/test/java/org/springframework/test/context/groovy/MixedXmlAndGroovySpringContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/groovy/MixedXmlAndGroovySpringContextTests.java @@ -25,8 +25,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration test class that verifies proper support for mixing XML @@ -55,14 +54,14 @@ public class MixedXmlAndGroovySpringContextTests { @Test public final void verifyAnnotationAutowiredFields() { - assertNotNull("The employee field should have been autowired.", this.employee); - assertEquals("Dilbert", this.employee.getName()); + assertThat(this.employee).as("The employee field should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("Dilbert"); - assertNotNull("The pet field should have been autowired.", this.pet); - assertEquals("Dogbert", this.pet.getName()); + assertThat(this.pet).as("The pet field should have been autowired.").isNotNull(); + assertThat(this.pet.getName()).isEqualTo("Dogbert"); - assertEquals("The foo field should have been autowired.", "Groovy Foo", this.foo); - assertEquals("The bar field should have been autowired.", "XML Bar", this.bar); + assertThat(this.foo).as("The foo field should have been autowired.").isEqualTo("Groovy Foo"); + assertThat(this.bar).as("The bar field should have been autowired.").isEqualTo("XML Bar"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/meta/MetaHierarchyLevelOneTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/meta/MetaHierarchyLevelOneTests.java index 137b21052a9..ad22376c3f0 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/meta/MetaHierarchyLevelOneTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/meta/MetaHierarchyLevelOneTests.java @@ -22,7 +22,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -38,7 +38,7 @@ public class MetaHierarchyLevelOneTests { @Test public void foo() { - assertEquals("Dev Foo", foo); + assertThat(foo).isEqualTo("Dev Foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/meta/MetaHierarchyLevelTwoTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/meta/MetaHierarchyLevelTwoTests.java index ad2a898be69..f1760442af5 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/meta/MetaHierarchyLevelTwoTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/meta/MetaHierarchyLevelTwoTests.java @@ -26,9 +26,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -58,14 +56,14 @@ public class MetaHierarchyLevelTwoTests extends MetaHierarchyLevelOneTests { @Test public void bar() { - assertEquals("Prod Bar", bar); + assertThat(bar).isEqualTo("Prod Bar"); } @Test public void contextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNotNull("parent ApplicationContext", context.getParent()); - assertNull("grandparent ApplicationContext", context.getParent().getParent()); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNotNull(); + assertThat(context.getParent().getParent()).as("grandparent ApplicationContext").isNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelOneTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelOneTests.java index a497794e62f..72f4b934513 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelOneTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelOneTests.java @@ -28,9 +28,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -88,12 +86,12 @@ public class ClassHierarchyWithMergedConfigLevelOneTests { @Test public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNotNull("parent ApplicationContext", context.getParent()); - assertNull("grandparent ApplicationContext", context.getParent().getParent()); - assertEquals("parent", parent); - assertEquals("parent + user", user); - assertEquals("from UserConfig", beanFromUserConfig); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNotNull(); + assertThat(context.getParent().getParent()).as("grandparent ApplicationContext").isNull(); + assertThat(parent).isEqualTo("parent"); + assertThat(user).isEqualTo("parent + user"); + assertThat(beanFromUserConfig).isEqualTo("from UserConfig"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelTwoTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelTwoTests.java index c9a2b961616..7293632f5b4 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelTwoTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelTwoTests.java @@ -26,7 +26,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -57,7 +57,7 @@ public class ClassHierarchyWithMergedConfigLevelTwoTests extends ClassHierarchyW @Override public void loadContextHierarchy() { super.loadContextHierarchy(); - assertEquals("parent + user + order", order); + assertThat(order).isEqualTo("parent + user + order"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithOverriddenConfigLevelTwoTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithOverriddenConfigLevelTwoTests.java index 7eb8a244ea5..8e69789f3ca 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithOverriddenConfigLevelTwoTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithOverriddenConfigLevelTwoTests.java @@ -26,9 +26,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -64,13 +62,13 @@ public class ClassHierarchyWithOverriddenConfigLevelTwoTests extends ClassHierar @Test @Override public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNotNull("parent ApplicationContext", context.getParent()); - assertNull("grandparent ApplicationContext", context.getParent().getParent()); - assertEquals("parent", parent); - assertEquals("parent + test user", user); - assertEquals("from TestUserConfig", beanFromTestUserConfig); - assertNull("Bean from UserConfig should not be present.", beanFromUserConfig); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNotNull(); + assertThat(context.getParent().getParent()).as("grandparent ApplicationContext").isNull(); + assertThat(parent).isEqualTo("parent"); + assertThat(user).isEqualTo("parent + test user"); + assertThat(beanFromTestUserConfig).isEqualTo("from TestUserConfig"); + assertThat(beanFromUserConfig).as("Bean from UserConfig should not be present.").isNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/DirtiesContextWithContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/DirtiesContextWithContextHierarchyTests.java index 9c2eaceb697..ad7e4319351 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/DirtiesContextWithContextHierarchyTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/DirtiesContextWithContextHierarchyTests.java @@ -32,9 +32,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for {@link DirtiesContext.HierarchyMode} @@ -99,28 +97,28 @@ public class DirtiesContextWithContextHierarchyTests { } private void assertCleanParentContext() { - assertEquals("foo", foo.toString()); + assertThat(foo.toString()).isEqualTo("foo"); } private void assertCleanChildContext() { - assertEquals("baz-child", baz.toString()); + assertThat(baz.toString()).isEqualTo("baz-child"); } private void assertDirtyParentContext() { - assertEquals("oof", foo.toString()); + assertThat(foo.toString()).isEqualTo("oof"); } private void assertDirtyChildContext() { - assertEquals("dlihc-zab", baz.toString()); + assertThat(baz.toString()).isEqualTo("dlihc-zab"); } // ------------------------------------------------------------------------- @Before public void verifyContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNotNull("parent ApplicationContext", context.getParent()); - assertNull("grandparent ApplicationContext", context.getParent().getParent()); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNotNull(); + assertThat(context.getParent().getParent()).as("grandparent ApplicationContext").isNull(); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithSingleLevelContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithSingleLevelContextHierarchyTests.java index e5c1099f631..ecc833fb13b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithSingleLevelContextHierarchyTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithSingleLevelContextHierarchyTests.java @@ -27,9 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -58,9 +56,9 @@ public class SingleTestClassWithSingleLevelContextHierarchyTests { @Test public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNull("parent ApplicationContext", context.getParent()); - assertEquals("foo", foo); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNull(); + assertThat(foo).isEqualTo("foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests.java index 250e0380178..bd9e61b10a0 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests.java @@ -27,9 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -71,12 +69,12 @@ public class SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests @Test public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNotNull("parent ApplicationContext", context.getParent()); - assertNull("grandparent ApplicationContext", context.getParent().getParent()); - assertEquals("foo", foo); - assertEquals("bar", bar); - assertEquals("baz-child", baz); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNotNull(); + assertThat(context.getParent().getParent()).as("grandparent ApplicationContext").isNull(); + assertThat(foo).isEqualTo("foo"); + assertThat(bar).isEqualTo("bar"); + assertThat(baz).isEqualTo("baz-child"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyTests.java index 75c62c0c8ca..39592972fa4 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyTests.java @@ -27,9 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -85,12 +83,12 @@ public class SingleTestClassWithTwoLevelContextHierarchyTests { @Test public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNotNull("parent ApplicationContext", context.getParent()); - assertNull("grandparent ApplicationContext", context.getParent().getParent()); - assertEquals("foo", foo); - assertEquals("bar", bar); - assertEquals("baz-child", baz); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNotNull(); + assertThat(context.getParent().getParent()).as("grandparent ApplicationContext").isNull(); + assertThat(foo).isEqualTo("foo"); + assertThat(bar).isEqualTo("bar"); + assertThat(baz).isEqualTo("baz-child"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSubclassTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSubclassTests.java index b0c5ce1ddad..0c238717daa 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSubclassTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSubclassTests.java @@ -27,9 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -66,10 +64,10 @@ public class TestHierarchyLevelOneWithBareContextConfigurationInSubclassTests { @Test public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNull("parent ApplicationContext", context.getParent()); - assertEquals("foo-level-1", foo); - assertEquals("bar", bar); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNull(); + assertThat(foo).isEqualTo("foo-level-1"); + assertThat(bar).isEqualTo("bar"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSuperclassTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSuperclassTests.java index d14e432a9eb..cbcab54b39b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSuperclassTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSuperclassTests.java @@ -26,9 +26,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -65,10 +63,10 @@ public class TestHierarchyLevelOneWithBareContextConfigurationInSuperclassTests @Test public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNull("parent ApplicationContext", context.getParent()); - assertEquals("foo-level-1", foo); - assertEquals("bar", bar); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNull(); + assertThat(foo).isEqualTo("foo-level-1"); + assertThat(bar).isEqualTo("bar"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithSingleLevelContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithSingleLevelContextHierarchyTests.java index 278ccdb5ed2..e84ce142b58 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithSingleLevelContextHierarchyTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithSingleLevelContextHierarchyTests.java @@ -27,9 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -66,10 +64,10 @@ public class TestHierarchyLevelOneWithSingleLevelContextHierarchyTests { @Test public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNull("parent ApplicationContext", context.getParent()); - assertEquals("foo-level-1", foo); - assertEquals("bar", bar); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNull(); + assertThat(foo).isEqualTo("foo-level-1"); + assertThat(bar).isEqualTo("bar"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSubclassTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSubclassTests.java index f65cada3f9d..b29da741813 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSubclassTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSubclassTests.java @@ -26,9 +26,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -70,12 +68,12 @@ public class TestHierarchyLevelTwoWithBareContextConfigurationInSubclassTests ex @Test @Override public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNotNull("parent ApplicationContext", context.getParent()); - assertNull("grandparent ApplicationContext", context.getParent().getParent()); - assertEquals("foo-level-2", foo); - assertEquals("bar", bar); - assertEquals("baz", baz); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNotNull(); + assertThat(context.getParent().getParent()).as("grandparent ApplicationContext").isNull(); + assertThat(foo).isEqualTo("foo-level-2"); + assertThat(bar).isEqualTo("bar"); + assertThat(baz).isEqualTo("baz"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSuperclassTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSuperclassTests.java index 54eee746669..34518a62f52 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSuperclassTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSuperclassTests.java @@ -27,9 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -71,12 +69,12 @@ public class TestHierarchyLevelTwoWithBareContextConfigurationInSuperclassTests @Test @Override public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNotNull("parent ApplicationContext", context.getParent()); - assertNull("grandparent ApplicationContext", context.getParent().getParent()); - assertEquals("foo-level-2", foo); - assertEquals("bar", bar); - assertEquals("baz", baz); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNotNull(); + assertThat(context.getParent().getParent()).as("grandparent ApplicationContext").isNull(); + assertThat(foo).isEqualTo("foo-level-2"); + assertThat(bar).isEqualTo("bar"); + assertThat(baz).isEqualTo("baz"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests.java index d30d738c3cf..537168dda6f 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests.java @@ -25,9 +25,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -54,12 +52,12 @@ public class TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigT @Test @Override public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNotNull("parent ApplicationContext", context.getParent()); - assertNull("grandparent ApplicationContext", context.getParent().getParent()); - assertEquals("foo-level-2", foo); - assertEquals("bar", bar); - assertEquals("baz", baz); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNotNull(); + assertThat(context.getParent().getParent()).as("grandparent ApplicationContext").isNull(); + assertThat(foo).isEqualTo("foo-level-2"); + assertThat(bar).isEqualTo("bar"); + assertThat(baz).isEqualTo("baz"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyTests.java index fc1702f2b35..00ac6a4ac9a 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyTests.java @@ -27,8 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -70,11 +69,11 @@ public class TestHierarchyLevelTwoWithSingleLevelContextHierarchyTests extends @Test @Override public void loadContextHierarchy() { - assertNotNull("child ApplicationContext", context); - assertNotNull("parent ApplicationContext", context.getParent()); - assertEquals("foo-level-2", foo); - assertEquals("bar", bar); - assertEquals("baz", baz); + assertThat(context).as("child ApplicationContext").isNotNull(); + assertThat(context.getParent()).as("parent ApplicationContext").isNotNull(); + assertThat(foo).isEqualTo("foo-level-2"); + assertThat(bar).isEqualTo("bar"); + assertThat(baz).isEqualTo("baz"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/ControllerIntegrationTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/ControllerIntegrationTests.java index 7c177b524cb..55dca366c10 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/ControllerIntegrationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/ControllerIntegrationTests.java @@ -33,11 +33,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -85,23 +81,24 @@ public class ControllerIntegrationTests { @Test public void verifyRootWacSupport() { - assertEquals("foo", foo); - assertEquals("bar", bar); + assertThat(foo).isEqualTo("foo"); + assertThat(bar).isEqualTo("bar"); ApplicationContext parent = wac.getParent(); - assertNotNull(parent); - assertTrue(parent instanceof WebApplicationContext); + assertThat(parent).isNotNull(); + boolean condition = parent instanceof WebApplicationContext; + assertThat(condition).isTrue(); WebApplicationContext root = (WebApplicationContext) parent; - assertFalse(root.getBeansOfType(String.class).containsKey("bar")); + assertThat(root.getBeansOfType(String.class).containsKey("bar")).isFalse(); ServletContext childServletContext = wac.getServletContext(); - assertNotNull(childServletContext); + assertThat(childServletContext).isNotNull(); ServletContext rootServletContext = root.getServletContext(); - assertNotNull(rootServletContext); - assertSame(childServletContext, rootServletContext); + assertThat(rootServletContext).isNotNull(); + assertThat(rootServletContext).isSameAs(childServletContext); - assertSame(root, rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); - assertSame(root, childServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); + assertThat(rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isSameAs(root); + assertThat(childServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isSameAs(root); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests.java index aa42080dd83..411ca7fbe60 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests.java @@ -27,11 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -70,27 +66,27 @@ public class DispatcherWacRootWacEarTests extends RootWacEarTests { @Test public void verifyDispatcherWacConfig() { ApplicationContext parent = wac.getParent(); - assertNotNull(parent); - assertTrue(parent instanceof WebApplicationContext); + assertThat(parent).isNotNull(); + boolean condition = parent instanceof WebApplicationContext; + assertThat(condition).isTrue(); ApplicationContext grandParent = parent.getParent(); - assertNotNull(grandParent); - assertFalse(grandParent instanceof WebApplicationContext); + assertThat(grandParent).isNotNull(); + boolean condition1 = grandParent instanceof WebApplicationContext; + assertThat(condition1).isFalse(); ServletContext dispatcherServletContext = wac.getServletContext(); - assertNotNull(dispatcherServletContext); + assertThat(dispatcherServletContext).isNotNull(); ServletContext rootServletContext = ((WebApplicationContext) parent).getServletContext(); - assertNotNull(rootServletContext); - assertSame(dispatcherServletContext, rootServletContext); + assertThat(rootServletContext).isNotNull(); + assertThat(rootServletContext).isSameAs(dispatcherServletContext); - assertSame(parent, - rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); - assertSame(parent, - dispatcherServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); + assertThat(rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isSameAs(parent); + assertThat(dispatcherServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isSameAs(parent); - assertEquals("ear", ear); - assertEquals("root", root); - assertEquals("dispatcher", dispatcher); + assertThat(ear).isEqualTo("ear"); + assertThat(root).isEqualTo("root"); + assertThat(dispatcher).isEqualTo("dispatcher"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/EarTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/EarTests.java index f0d66602675..ab86ca71851 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/EarTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/EarTests.java @@ -27,9 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -60,9 +58,10 @@ public class EarTests { @Test public void verifyEarConfig() { - assertFalse(context instanceof WebApplicationContext); - assertNull(context.getParent()); - assertEquals("ear", ear); + boolean condition = context instanceof WebApplicationContext; + assertThat(condition).isFalse(); + assertThat(context.getParent()).isNull(); + assertThat(ear).isEqualTo("ear"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/RootWacEarTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/RootWacEarTests.java index ed112cc446c..27ff8d5e317 100644 --- a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/RootWacEarTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/RootWacEarTests.java @@ -28,9 +28,7 @@ import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -72,10 +70,11 @@ public class RootWacEarTests extends EarTests { @Test public void verifyRootWacConfig() { ApplicationContext parent = wac.getParent(); - assertNotNull(parent); - assertFalse(parent instanceof WebApplicationContext); - assertEquals("ear", ear); - assertEquals("root", root); + assertThat(parent).isNotNull(); + boolean condition = parent instanceof WebApplicationContext; + assertThat(condition).isFalse(); + assertThat(ear).isEqualTo("ear"); + assertThat(root).isEqualTo("root"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/ComposedAnnotationSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/ComposedAnnotationSqlScriptsTests.java index 4c284802082..b2195dc34bf 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/ComposedAnnotationSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/ComposedAnnotationSqlScriptsTests.java @@ -27,7 +27,7 @@ import org.springframework.test.context.jdbc.Sql.ExecutionPhase; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import static java.lang.annotation.RetentionPolicy.RUNTIME; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD; /** @@ -48,7 +48,7 @@ public class ComposedAnnotationSqlScriptsTests extends AbstractTransactionalJUni executionPhase = BEFORE_TEST_METHOD ) public void composedSqlAnnotation() { - assertEquals("Number of rows in the 'user' table.", 1, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(1); } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/CustomScriptSyntaxSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/CustomScriptSyntaxSqlScriptsTests.java index 6e06e4e4248..e15313f4cdc 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/CustomScriptSyntaxSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/CustomScriptSyntaxSqlScriptsTests.java @@ -22,7 +22,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for custom SQL script syntax @@ -44,7 +44,7 @@ public class CustomScriptSyntaxSqlScriptsTests extends AbstractTransactionalJUni } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/DataSourceOnlySqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/DataSourceOnlySqlScriptsTests.java index a743d94862a..947e3b0d9ef 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/DataSourceOnlySqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/DataSourceOnlySqlScriptsTests.java @@ -33,7 +33,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.jdbc.JdbcTestUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -74,8 +74,7 @@ public class DataSourceOnlySqlScriptsTests { } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, - JdbcTestUtils.countRowsInTable(jdbcTemplate, "user")); + assertThat(JdbcTestUtils.countRowsInTable(jdbcTemplate, "user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/DefaultScriptDetectionSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/DefaultScriptDetectionSqlScriptsTests.java index f88e753d9c2..dec72528bfb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/DefaultScriptDetectionSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/DefaultScriptDetectionSqlScriptsTests.java @@ -22,7 +22,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for default SQL script detection. @@ -47,7 +47,7 @@ public class DefaultScriptDetectionSqlScriptsTests extends AbstractTransactional } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/GlobalCustomScriptSyntaxSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/GlobalCustomScriptSyntaxSqlScriptsTests.java index bd4382eb072..17038cb48d3 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/GlobalCustomScriptSyntaxSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/GlobalCustomScriptSyntaxSqlScriptsTests.java @@ -22,7 +22,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Modified copy of {@link CustomScriptSyntaxSqlScriptsTests} with @@ -44,7 +44,7 @@ public class GlobalCustomScriptSyntaxSqlScriptsTests extends AbstractTransaction } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/InferredDataSourceSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/InferredDataSourceSqlScriptsTests.java index 7ccfbb86ebf..8282d8f4ad5 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/InferredDataSourceSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/InferredDataSourceSqlScriptsTests.java @@ -35,7 +35,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.PlatformTransactionManager; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -77,7 +77,7 @@ public class InferredDataSourceSqlScriptsTests { Collections.sort(expected); List actual = jdbcTemplate.queryForList("select name from user", String.class); Collections.sort(actual); - assertEquals("Users in database;", expected, actual); + assertThat(actual).as("Users in database;").isEqualTo(expected); } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/InferredDataSourceTransactionalSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/InferredDataSourceTransactionalSqlScriptsTests.java index 2a4087f84af..fdc58a524a3 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/InferredDataSourceTransactionalSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/InferredDataSourceTransactionalSqlScriptsTests.java @@ -36,7 +36,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -80,7 +80,7 @@ public class InferredDataSourceTransactionalSqlScriptsTests { Collections.sort(expected); List actual = jdbcTemplate.queryForList("select name from user", String.class); Collections.sort(actual); - assertEquals("Users in database;", expected, actual); + assertThat(actual).as("Users in database;").isEqualTo(expected); } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/IsolatedTransactionModeSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/IsolatedTransactionModeSqlScriptsTests.java index 81782d45e52..1cbcc35bedb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/IsolatedTransactionModeSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/IsolatedTransactionModeSqlScriptsTests.java @@ -25,7 +25,7 @@ import org.springframework.test.context.junit4.AbstractTransactionalJUnit4Spring import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Transactional integration tests that verify commit semantics for @@ -55,7 +55,7 @@ public class IsolatedTransactionModeSqlScriptsTests extends AbstractTransactiona } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/MergedSqlConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/MergedSqlConfigTests.java index f6b315d11f9..10a34ed2705 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/MergedSqlConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/MergedSqlConfigTests.java @@ -20,8 +20,7 @@ import java.lang.reflect.Method; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.jdbc.datasource.init.ScriptUtils.DEFAULT_BLOCK_COMMENT_END_DELIMITER; import static org.springframework.jdbc.datasource.init.ScriptUtils.DEFAULT_BLOCK_COMMENT_START_DELIMITER; import static org.springframework.jdbc.datasource.init.ScriptUtils.DEFAULT_COMMENT_PREFIX; @@ -41,17 +40,16 @@ import static org.springframework.test.context.jdbc.SqlConfig.TransactionMode.IS public class MergedSqlConfigTests { private void assertDefaults(MergedSqlConfig cfg) { - assertNotNull(cfg); - assertEquals("dataSource", "", cfg.getDataSource()); - assertEquals("transactionManager", "", cfg.getTransactionManager()); - assertEquals("transactionMode", INFERRED, cfg.getTransactionMode()); - assertEquals("encoding", "", cfg.getEncoding()); - assertEquals("separator", DEFAULT_STATEMENT_SEPARATOR, cfg.getSeparator()); - assertEquals("commentPrefix", DEFAULT_COMMENT_PREFIX, cfg.getCommentPrefix()); - assertEquals("blockCommentStartDelimiter", DEFAULT_BLOCK_COMMENT_START_DELIMITER, - cfg.getBlockCommentStartDelimiter()); - assertEquals("blockCommentEndDelimiter", DEFAULT_BLOCK_COMMENT_END_DELIMITER, cfg.getBlockCommentEndDelimiter()); - assertEquals("errorMode", FAIL_ON_ERROR, cfg.getErrorMode()); + assertThat(cfg).isNotNull(); + assertThat(cfg.getDataSource()).as("dataSource").isEqualTo(""); + assertThat(cfg.getTransactionManager()).as("transactionManager").isEqualTo(""); + assertThat(cfg.getTransactionMode()).as("transactionMode").isEqualTo(INFERRED); + assertThat(cfg.getEncoding()).as("encoding").isEqualTo(""); + assertThat(cfg.getSeparator()).as("separator").isEqualTo(DEFAULT_STATEMENT_SEPARATOR); + assertThat(cfg.getCommentPrefix()).as("commentPrefix").isEqualTo(DEFAULT_COMMENT_PREFIX); + assertThat(cfg.getBlockCommentStartDelimiter()).as("blockCommentStartDelimiter").isEqualTo(DEFAULT_BLOCK_COMMENT_START_DELIMITER); + assertThat(cfg.getBlockCommentEndDelimiter()).as("blockCommentEndDelimiter").isEqualTo(DEFAULT_BLOCK_COMMENT_END_DELIMITER); + assertThat(cfg.getErrorMode()).as("errorMode").isEqualTo(FAIL_ON_ERROR); } @Test @@ -75,16 +73,16 @@ public class MergedSqlConfigTests { Method method = getClass().getMethod("localConfigMethodWithCustomValues"); SqlConfig localSqlConfig = method.getAnnotation(Sql.class).config(); MergedSqlConfig cfg = new MergedSqlConfig(localSqlConfig, getClass()); - assertNotNull(cfg); - assertEquals("dataSource", "ds", cfg.getDataSource()); - assertEquals("transactionManager", "txMgr", cfg.getTransactionManager()); - assertEquals("transactionMode", ISOLATED, cfg.getTransactionMode()); - assertEquals("encoding", "enigma", cfg.getEncoding()); - assertEquals("separator", "\n", cfg.getSeparator()); - assertEquals("commentPrefix", "`", cfg.getCommentPrefix()); - assertEquals("blockCommentStartDelimiter", "<<", cfg.getBlockCommentStartDelimiter()); - assertEquals("blockCommentEndDelimiter", ">>", cfg.getBlockCommentEndDelimiter()); - assertEquals("errorMode", IGNORE_FAILED_DROPS, cfg.getErrorMode()); + assertThat(cfg).isNotNull(); + assertThat(cfg.getDataSource()).as("dataSource").isEqualTo("ds"); + assertThat(cfg.getTransactionManager()).as("transactionManager").isEqualTo("txMgr"); + assertThat(cfg.getTransactionMode()).as("transactionMode").isEqualTo(ISOLATED); + assertThat(cfg.getEncoding()).as("encoding").isEqualTo("enigma"); + assertThat(cfg.getSeparator()).as("separator").isEqualTo("\n"); + assertThat(cfg.getCommentPrefix()).as("commentPrefix").isEqualTo("`"); + assertThat(cfg.getBlockCommentStartDelimiter()).as("blockCommentStartDelimiter").isEqualTo("<<"); + assertThat(cfg.getBlockCommentEndDelimiter()).as("blockCommentEndDelimiter").isEqualTo(">>"); + assertThat(cfg.getErrorMode()).as("errorMode").isEqualTo(IGNORE_FAILED_DROPS); } @Test @@ -92,8 +90,8 @@ public class MergedSqlConfigTests { Method method = getClass().getMethod("localConfigMethodWithContinueOnError"); SqlConfig localSqlConfig = method.getAnnotation(Sql.class).config(); MergedSqlConfig cfg = new MergedSqlConfig(localSqlConfig, getClass()); - assertNotNull(cfg); - assertEquals("errorMode", CONTINUE_ON_ERROR, cfg.getErrorMode()); + assertThat(cfg).isNotNull(); + assertThat(cfg.getErrorMode()).as("errorMode").isEqualTo(CONTINUE_ON_ERROR); } @Test @@ -101,8 +99,8 @@ public class MergedSqlConfigTests { Method method = getClass().getMethod("localConfigMethodWithIgnoreFailedDrops"); SqlConfig localSqlConfig = method.getAnnotation(Sql.class).config(); MergedSqlConfig cfg = new MergedSqlConfig(localSqlConfig, getClass()); - assertNotNull(cfg); - assertEquals("errorMode", IGNORE_FAILED_DROPS, cfg.getErrorMode()); + assertThat(cfg).isNotNull(); + assertThat(cfg.getErrorMode()).as("errorMode").isEqualTo(IGNORE_FAILED_DROPS); } @Test @@ -110,17 +108,16 @@ public class MergedSqlConfigTests { Method method = GlobalConfigClass.class.getMethod("globalConfigMethod"); SqlConfig localSqlConfig = method.getAnnotation(Sql.class).config(); MergedSqlConfig cfg = new MergedSqlConfig(localSqlConfig, GlobalConfigClass.class); - assertNotNull(cfg); - assertEquals("dataSource", "", cfg.getDataSource()); - assertEquals("transactionManager", "", cfg.getTransactionManager()); - assertEquals("transactionMode", INFERRED, cfg.getTransactionMode()); - assertEquals("encoding", "global", cfg.getEncoding()); - assertEquals("separator", "\n", cfg.getSeparator()); - assertEquals("commentPrefix", DEFAULT_COMMENT_PREFIX, cfg.getCommentPrefix()); - assertEquals("blockCommentStartDelimiter", DEFAULT_BLOCK_COMMENT_START_DELIMITER, - cfg.getBlockCommentStartDelimiter()); - assertEquals("blockCommentEndDelimiter", DEFAULT_BLOCK_COMMENT_END_DELIMITER, cfg.getBlockCommentEndDelimiter()); - assertEquals("errorMode", IGNORE_FAILED_DROPS, cfg.getErrorMode()); + assertThat(cfg).isNotNull(); + assertThat(cfg.getDataSource()).as("dataSource").isEqualTo(""); + assertThat(cfg.getTransactionManager()).as("transactionManager").isEqualTo(""); + assertThat(cfg.getTransactionMode()).as("transactionMode").isEqualTo(INFERRED); + assertThat(cfg.getEncoding()).as("encoding").isEqualTo("global"); + assertThat(cfg.getSeparator()).as("separator").isEqualTo("\n"); + assertThat(cfg.getCommentPrefix()).as("commentPrefix").isEqualTo(DEFAULT_COMMENT_PREFIX); + assertThat(cfg.getBlockCommentStartDelimiter()).as("blockCommentStartDelimiter").isEqualTo(DEFAULT_BLOCK_COMMENT_START_DELIMITER); + assertThat(cfg.getBlockCommentEndDelimiter()).as("blockCommentEndDelimiter").isEqualTo(DEFAULT_BLOCK_COMMENT_END_DELIMITER); + assertThat(cfg.getErrorMode()).as("errorMode").isEqualTo(IGNORE_FAILED_DROPS); } @Test @@ -129,17 +126,16 @@ public class MergedSqlConfigTests { SqlConfig localSqlConfig = method.getAnnotation(Sql.class).config(); MergedSqlConfig cfg = new MergedSqlConfig(localSqlConfig, GlobalConfigClass.class); - assertNotNull(cfg); - assertEquals("dataSource", "", cfg.getDataSource()); - assertEquals("transactionManager", "", cfg.getTransactionManager()); - assertEquals("transactionMode", INFERRED, cfg.getTransactionMode()); - assertEquals("encoding", "local", cfg.getEncoding()); - assertEquals("separator", "@@", cfg.getSeparator()); - assertEquals("commentPrefix", DEFAULT_COMMENT_PREFIX, cfg.getCommentPrefix()); - assertEquals("blockCommentStartDelimiter", DEFAULT_BLOCK_COMMENT_START_DELIMITER, - cfg.getBlockCommentStartDelimiter()); - assertEquals("blockCommentEndDelimiter", DEFAULT_BLOCK_COMMENT_END_DELIMITER, cfg.getBlockCommentEndDelimiter()); - assertEquals("errorMode", CONTINUE_ON_ERROR, cfg.getErrorMode()); + assertThat(cfg).isNotNull(); + assertThat(cfg.getDataSource()).as("dataSource").isEqualTo(""); + assertThat(cfg.getTransactionManager()).as("transactionManager").isEqualTo(""); + assertThat(cfg.getTransactionMode()).as("transactionMode").isEqualTo(INFERRED); + assertThat(cfg.getEncoding()).as("encoding").isEqualTo("local"); + assertThat(cfg.getSeparator()).as("separator").isEqualTo("@@"); + assertThat(cfg.getCommentPrefix()).as("commentPrefix").isEqualTo(DEFAULT_COMMENT_PREFIX); + assertThat(cfg.getBlockCommentStartDelimiter()).as("blockCommentStartDelimiter").isEqualTo(DEFAULT_BLOCK_COMMENT_START_DELIMITER); + assertThat(cfg.getBlockCommentEndDelimiter()).as("blockCommentEndDelimiter").isEqualTo(DEFAULT_BLOCK_COMMENT_END_DELIMITER); + assertThat(cfg.getErrorMode()).as("errorMode").isEqualTo(CONTINUE_ON_ERROR); } // ------------------------------------------------------------------------- diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/MetaAnnotationSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/MetaAnnotationSqlScriptsTests.java index 3771e294a3e..08e4f1ab6a0 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/MetaAnnotationSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/MetaAnnotationSqlScriptsTests.java @@ -27,7 +27,7 @@ import org.springframework.test.context.junit4.AbstractTransactionalJUnit4Spring import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for using {@link Sql @Sql} and @@ -53,7 +53,7 @@ public class MetaAnnotationSqlScriptsTests extends AbstractTransactionalJUnit4Sp } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/MultipleDataSourcesAndTransactionManagersSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/MultipleDataSourcesAndTransactionManagersSqlScriptsTests.java index 8e5eaf1149d..a6df1097716 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/MultipleDataSourcesAndTransactionManagersSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/MultipleDataSourcesAndTransactionManagersSqlScriptsTests.java @@ -35,7 +35,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.PlatformTransactionManager; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link Sql @Sql} that verify support for multiple @@ -76,7 +76,7 @@ public class MultipleDataSourcesAndTransactionManagersSqlScriptsTests { Collections.sort(expected); List actual = jdbcTemplate.queryForList("select name from user", String.class); Collections.sort(actual); - assertEquals("Users in database;", expected, actual); + assertThat(actual).as("Users in database;").isEqualTo(expected); } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/MultipleDataSourcesAndTransactionManagersTransactionalSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/MultipleDataSourcesAndTransactionManagersTransactionalSqlScriptsTests.java index 12bd1583fa8..54e9e644c22 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/MultipleDataSourcesAndTransactionManagersTransactionalSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/MultipleDataSourcesAndTransactionManagersTransactionalSqlScriptsTests.java @@ -36,7 +36,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Exact copy of {@link MultipleDataSourcesAndTransactionManagersSqlScriptsTests}, @@ -77,7 +77,7 @@ public class MultipleDataSourcesAndTransactionManagersTransactionalSqlScriptsTes Collections.sort(expected); List actual = jdbcTemplate.queryForList("select name from user", String.class); Collections.sort(actual); - assertEquals("Users in database;", expected, actual); + assertThat(actual).as("Users in database;").isEqualTo(expected); } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/NonTransactionalSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/NonTransactionalSqlScriptsTests.java index 176674b8b71..0baa49f44d8 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/NonTransactionalSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/NonTransactionalSqlScriptsTests.java @@ -30,7 +30,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.jdbc.JdbcTestUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests which verify that scripts executed via {@link Sql @Sql} @@ -68,8 +68,7 @@ public class NonTransactionalSqlScriptsTests { } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, - JdbcTestUtils.countRowsInTable(jdbcTemplate, "user")); + assertThat(JdbcTestUtils.countRowsInTable(jdbcTemplate, "user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/PopulatedSchemaTransactionalSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/PopulatedSchemaTransactionalSqlScriptsTests.java index a1e0c7a4dc2..f309c9359fd 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/PopulatedSchemaTransactionalSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/PopulatedSchemaTransactionalSqlScriptsTests.java @@ -24,7 +24,7 @@ import org.springframework.test.context.junit4.AbstractTransactionalJUnit4Spring import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Transactional integration tests that verify rollback semantics for @@ -50,7 +50,7 @@ public class PopulatedSchemaTransactionalSqlScriptsTests extends AbstractTransac } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/PrimaryDataSourceTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/PrimaryDataSourceTests.java index efb1d057fdc..ae81a0d0cb0 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/PrimaryDataSourceTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/PrimaryDataSourceTests.java @@ -33,7 +33,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.test.transaction.TransactionTestUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that ensure that primary data sources are @@ -82,8 +82,7 @@ public class PrimaryDataSourceTests { @Sql("data.sql") public void dataSourceTest() { TransactionTestUtils.assertInTransaction(false); - assertEquals("Number of rows in the 'user' table.", 1, - JdbcTestUtils.countRowsInTable(this.jdbcTemplate, "user")); + assertThat(JdbcTestUtils.countRowsInTable(this.jdbcTemplate, "user")).as("Number of rows in the 'user' table.").isEqualTo(1); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/RepeatableSqlAnnotationSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/RepeatableSqlAnnotationSqlScriptsTests.java index faa5aec0f44..c1b827a1b10 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/RepeatableSqlAnnotationSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/RepeatableSqlAnnotationSqlScriptsTests.java @@ -26,7 +26,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * This is a copy of {@link TransactionalSqlScriptsTests} that verifies proper @@ -59,7 +59,7 @@ public class RepeatableSqlAnnotationSqlScriptsTests extends AbstractTransactiona } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalAfterTestMethodSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalAfterTestMethodSqlScriptsTests.java index 386d4aa6e16..c87bf73584d 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalAfterTestMethodSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalAfterTestMethodSqlScriptsTests.java @@ -29,8 +29,8 @@ import org.springframework.test.context.jdbc.Sql.ExecutionPhase; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.transaction.AfterTransaction; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; /** @@ -76,7 +76,7 @@ public class TransactionalAfterTestMethodSqlScriptsTests extends AbstractTransac } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalInlinedStatementsSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalInlinedStatementsSqlScriptsTests.java index be1b7791218..7bddde408fa 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalInlinedStatementsSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalInlinedStatementsSqlScriptsTests.java @@ -31,7 +31,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Transactional integration tests for {@link Sql @Sql} support with @@ -80,7 +80,7 @@ public class TransactionalInlinedStatementsSqlScriptsTests { } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalSqlScriptsTests.java b/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalSqlScriptsTests.java index 40b9a5ae2ae..a36cc180bc3 100644 --- a/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalSqlScriptsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalSqlScriptsTests.java @@ -31,7 +31,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Transactional integration tests for {@link Sql @Sql} support. @@ -73,7 +73,7 @@ public class TransactionalSqlScriptsTests { } protected void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table.", expected, countRowsInTable("user")); + assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/BeforeAndAfterTransactionAnnotationTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/BeforeAndAfterTransactionAnnotationTests.java index 46743fe8073..dc6a459bb8b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/BeforeAndAfterTransactionAnnotationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/BeforeAndAfterTransactionAnnotationTests.java @@ -33,7 +33,7 @@ import org.springframework.test.context.transaction.BeforeTransaction; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -72,12 +72,9 @@ public class BeforeAndAfterTransactionAnnotationTests extends AbstractTransactio @AfterClass public static void afterClass() { - assertEquals("Verifying the final number of rows in the person table after all tests.", 3, - countRowsInPersonTable(jdbcTemplate)); - assertEquals("Verifying the total number of calls to beforeTransaction().", 2, - BeforeAndAfterTransactionAnnotationTests.numBeforeTransactionCalls); - assertEquals("Verifying the total number of calls to afterTransaction().", 2, - BeforeAndAfterTransactionAnnotationTests.numAfterTransactionCalls); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the final number of rows in the person table after all tests.").isEqualTo(3); + assertThat(BeforeAndAfterTransactionAnnotationTests.numBeforeTransactionCalls).as("Verifying the total number of calls to beforeTransaction().").isEqualTo(2); + assertThat(BeforeAndAfterTransactionAnnotationTests.numAfterTransactionCalls).as("Verifying the total number of calls to afterTransaction().").isEqualTo(2); } @BeforeTransaction @@ -86,7 +83,7 @@ public class BeforeAndAfterTransactionAnnotationTests extends AbstractTransactio this.inTransaction = true; BeforeAndAfterTransactionAnnotationTests.numBeforeTransactionCalls++; clearPersonTable(jdbcTemplate); - assertEquals("Adding yoda", 1, addPerson(jdbcTemplate, YODA)); + assertThat(addPerson(jdbcTemplate, YODA)).as("Adding yoda").isEqualTo(1); } @AfterTransaction @@ -94,16 +91,16 @@ public class BeforeAndAfterTransactionAnnotationTests extends AbstractTransactio assertInTransaction(false); this.inTransaction = false; BeforeAndAfterTransactionAnnotationTests.numAfterTransactionCalls++; - assertEquals("Deleting yoda", 1, deletePerson(jdbcTemplate, YODA)); - assertEquals("Verifying the number of rows in the person table after a transactional test method.", 0, - countRowsInPersonTable(jdbcTemplate)); + assertThat(deletePerson(jdbcTemplate, YODA)).as("Deleting yoda").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table after a transactional test method.").isEqualTo(0); } @Before public void before() { assertShouldBeInTransaction(); - assertEquals("Verifying the number of rows in the person table before a test method.", (this.inTransaction ? 1 - : 0), countRowsInPersonTable(jdbcTemplate)); + long expected = (this.inTransaction ? 1 + : 0); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table before a test method.").isEqualTo(expected); } private void assertShouldBeInTransaction() { @@ -119,29 +116,26 @@ public class BeforeAndAfterTransactionAnnotationTests extends AbstractTransactio @Test public void transactionalMethod1() { assertInTransaction(true); - assertEquals("Adding jane", 1, addPerson(jdbcTemplate, JANE)); - assertEquals("Verifying the number of rows in the person table within transactionalMethod1().", 2, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, JANE)).as("Adding jane").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table within transactionalMethod1().").isEqualTo(2); } @Test public void transactionalMethod2() { assertInTransaction(true); - assertEquals("Adding jane", 1, addPerson(jdbcTemplate, JANE)); - assertEquals("Adding sue", 1, addPerson(jdbcTemplate, SUE)); - assertEquals("Verifying the number of rows in the person table within transactionalMethod2().", 3, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, JANE)).as("Adding jane").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, SUE)).as("Adding sue").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table within transactionalMethod2().").isEqualTo(3); } @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void nonTransactionalMethod() { assertInTransaction(false); - assertEquals("Adding luke", 1, addPerson(jdbcTemplate, LUKE)); - assertEquals("Adding leia", 1, addPerson(jdbcTemplate, LEIA)); - assertEquals("Adding yoda", 1, addPerson(jdbcTemplate, YODA)); - assertEquals("Verifying the number of rows in the person table without a transaction.", 3, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, LUKE)).as("Adding luke").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, LEIA)).as("Adding leia").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, YODA)).as("Adding yoda").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table without a transaction.").isEqualTo(3); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/ClassLevelDisabledSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/ClassLevelDisabledSpringRunnerTests.java index 59c1875d845..78e1ed3c043 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/ClassLevelDisabledSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/ClassLevelDisabledSpringRunnerTests.java @@ -24,7 +24,7 @@ import org.springframework.test.context.TestContext; import org.springframework.test.context.TestExecutionListener; import org.springframework.test.context.TestExecutionListeners; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; /** * @author Juergen Hoeller diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/ClassLevelTransactionalSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/ClassLevelTransactionalSpringRunnerTests.java index 5ce7b297fbc..b533c0c2f13 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/ClassLevelTransactionalSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/ClassLevelTransactionalSpringRunnerTests.java @@ -33,7 +33,7 @@ import org.springframework.test.context.transaction.TransactionalTestExecutionLi import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -70,37 +70,33 @@ public class ClassLevelTransactionalSpringRunnerTests extends AbstractTransactio @AfterClass public static void verifyFinalTestData() { - assertEquals("Verifying the final number of rows in the person table after all tests.", 4, - countRowsInPersonTable(jdbcTemplate)); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the final number of rows in the person table after all tests.").isEqualTo(4); } @Before public void verifyInitialTestData() { clearPersonTable(jdbcTemplate); - assertEquals("Adding bob", 1, addPerson(jdbcTemplate, BOB)); - assertEquals("Verifying the initial number of rows in the person table.", 1, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, BOB)).as("Adding bob").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the initial number of rows in the person table.").isEqualTo(1); } @Test public void modifyTestDataWithinTransaction() { assertInTransaction(true); - assertEquals("Deleting bob", 1, deletePerson(jdbcTemplate, BOB)); - assertEquals("Adding jane", 1, addPerson(jdbcTemplate, JANE)); - assertEquals("Adding sue", 1, addPerson(jdbcTemplate, SUE)); - assertEquals("Verifying the number of rows in the person table within a transaction.", 2, - countRowsInPersonTable(jdbcTemplate)); + assertThat(deletePerson(jdbcTemplate, BOB)).as("Deleting bob").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, JANE)).as("Adding jane").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, SUE)).as("Adding sue").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table within a transaction.").isEqualTo(2); } @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void modifyTestDataWithoutTransaction() { assertInTransaction(false); - assertEquals("Adding luke", 1, addPerson(jdbcTemplate, LUKE)); - assertEquals("Adding leia", 1, addPerson(jdbcTemplate, LEIA)); - assertEquals("Adding yoda", 1, addPerson(jdbcTemplate, YODA)); - assertEquals("Verifying the number of rows in the person table without a transaction.", 4, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, LUKE)).as("Adding luke").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, LEIA)).as("Adding leia").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, YODA)).as("Adding yoda").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table without a transaction.").isEqualTo(4); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests.java index 04de0a43b38..b7c241e0239 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests.java @@ -33,10 +33,7 @@ import org.springframework.tests.sample.beans.Pet; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; import static org.springframework.test.transaction.TransactionTestUtils.inTransaction; @@ -96,28 +93,26 @@ public class ConcreteTransactionalJUnit4SpringContextTests extends AbstractTrans @Before public void setUp() { - assertEquals("Verifying the number of rows in the person table before a test method.", - (inTransaction() ? 2 : 1), countRowsInPersonTable()); + long expected = (inTransaction() ? 2 : 1); + assertThat(countRowsInPersonTable()).as("Verifying the number of rows in the person table before a test method.").isEqualTo(expected); } @After public void tearDown() { - assertEquals("Verifying the number of rows in the person table after a test method.", - (inTransaction() ? 4 : 1), countRowsInPersonTable()); + long expected = (inTransaction() ? 4 : 1); + assertThat(countRowsInPersonTable()).as("Verifying the number of rows in the person table after a test method.").isEqualTo(expected); } @BeforeTransaction public void beforeTransaction() { - assertEquals("Verifying the number of rows in the person table before a transactional test method.", - 1, countRowsInPersonTable()); - assertEquals("Adding yoda", 1, addPerson(YODA)); + assertThat(countRowsInPersonTable()).as("Verifying the number of rows in the person table before a transactional test method.").isEqualTo(1); + assertThat(addPerson(YODA)).as("Adding yoda").isEqualTo(1); } @AfterTransaction public void afterTransaction() { - assertEquals("Deleting yoda", 1, deletePerson(YODA)); - assertEquals("Verifying the number of rows in the person table after a transactional test method.", - 1, countRowsInPersonTable()); + assertThat(deletePerson(YODA)).as("Deleting yoda").isEqualTo(1); + assertThat(countRowsInPersonTable()).as("Verifying the number of rows in the person table after a transactional test method.").isEqualTo(1); } @@ -125,64 +120,61 @@ public class ConcreteTransactionalJUnit4SpringContextTests extends AbstractTrans @Transactional(propagation = Propagation.NOT_SUPPORTED) public void verifyBeanNameSet() { assertInTransaction(false); - assertTrue("The bean name of this test instance should have been set to the fully qualified class name " + - "due to BeanNameAware semantics.", this.beanName.startsWith(getClass().getName())); + assertThat(this.beanName.startsWith(getClass().getName())).as("The bean name of this test instance should have been set to the fully qualified class name " + + "due to BeanNameAware semantics.").isTrue(); } @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void verifyApplicationContext() { assertInTransaction(false); - assertNotNull("The application context should have been set due to ApplicationContextAware semantics.", - super.applicationContext); + assertThat(super.applicationContext).as("The application context should have been set due to ApplicationContextAware semantics.").isNotNull(); } @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void verifyBeanInitialized() { assertInTransaction(false); - assertTrue("This test bean should have been initialized due to InitializingBean semantics.", - this.beanInitialized); + assertThat(this.beanInitialized).as("This test bean should have been initialized due to InitializingBean semantics.").isTrue(); } @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void verifyAnnotationAutowiredFields() { assertInTransaction(false); - assertNull("The nonrequiredLong property should NOT have been autowired.", this.nonrequiredLong); - assertNotNull("The pet field should have been autowired.", this.pet); - assertEquals("Fido", this.pet.getName()); + assertThat(this.nonrequiredLong).as("The nonrequiredLong property should NOT have been autowired.").isNull(); + assertThat(this.pet).as("The pet field should have been autowired.").isNotNull(); + assertThat(this.pet.getName()).isEqualTo("Fido"); } @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void verifyAnnotationAutowiredMethods() { assertInTransaction(false); - assertNotNull("The employee setter method should have been autowired.", this.employee); - assertEquals("John Smith", this.employee.getName()); + assertThat(this.employee).as("The employee setter method should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("John Smith"); } @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void verifyResourceAnnotationWiredFields() { assertInTransaction(false); - assertEquals("The foo field should have been wired via @Resource.", "Foo", this.foo); + assertThat(this.foo).as("The foo field should have been wired via @Resource.").isEqualTo("Foo"); } @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void verifyResourceAnnotationWiredMethods() { assertInTransaction(false); - assertEquals("The bar method should have been wired via @Resource.", "Bar", this.bar); + assertThat(this.bar).as("The bar method should have been wired via @Resource.").isEqualTo("Bar"); } @Test public void modifyTestDataWithinTransaction() { assertInTransaction(true); - assertEquals("Adding jane", 1, addPerson(JANE)); - assertEquals("Adding sue", 1, addPerson(SUE)); - assertEquals("Verifying the number of rows in the person table in modifyTestDataWithinTransaction().", - 4, countRowsInPersonTable()); + assertThat(addPerson(JANE)).as("Adding jane").isEqualTo(1); + assertThat(addPerson(SUE)).as("Adding sue").isEqualTo(1); + assertThat(countRowsInPersonTable()).as("Verifying the number of rows in the person table in modifyTestDataWithinTransaction().").isEqualTo(4); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/ContextCustomizerSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/ContextCustomizerSpringRunnerTests.java index b93e77dcbad..f4cba2cb6bd 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/ContextCustomizerSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/ContextCustomizerSpringRunnerTests.java @@ -29,7 +29,7 @@ import org.springframework.test.context.junit4.ContextCustomizerSpringRunnerTest import org.springframework.test.context.support.DefaultTestContextBootstrapper; import static java.util.Collections.singletonList; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit 4 based integration test which verifies support of @@ -48,7 +48,7 @@ public class ContextCustomizerSpringRunnerTests { @Test public void injectedBean() { - assertEquals("foo", foo); + assertThat(foo).isEqualTo("foo"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/CustomDefaultContextLoaderClassSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/CustomDefaultContextLoaderClassSpringRunnerTests.java index 44a4448e415..34a6bd298c0 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/CustomDefaultContextLoaderClassSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/CustomDefaultContextLoaderClassSpringRunnerTests.java @@ -27,8 +27,7 @@ import org.springframework.test.context.support.DefaultTestContextBootstrapper; import org.springframework.test.context.support.GenericPropertiesContextLoader; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests which verify that a subclass of {@link DefaultTestContextBootstrapper} @@ -52,11 +51,11 @@ public class CustomDefaultContextLoaderClassSpringRunnerTests { @Test public void verifyAnnotationAutowiredFields() { - assertNotNull("The cat field should have been autowired.", this.cat); - assertEquals("Garfield", this.cat.getName()); + assertThat(this.cat).as("The cat field should have been autowired.").isNotNull(); + assertThat(this.cat.getName()).isEqualTo("Garfield"); - assertNotNull("The testString field should have been autowired.", this.testString); - assertEquals("Test String", this.testString); + assertThat(this.testString).as("The testString field should have been autowired.").isNotNull(); + assertThat(this.testString).isEqualTo("Test String"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/DefaultRollbackFalseRollbackAnnotationTransactionalTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/DefaultRollbackFalseRollbackAnnotationTransactionalTests.java index 35b5ac75579..cceaa26f42b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/DefaultRollbackFalseRollbackAnnotationTransactionalTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/DefaultRollbackFalseRollbackAnnotationTransactionalTests.java @@ -29,7 +29,7 @@ import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -63,25 +63,22 @@ public class DefaultRollbackFalseRollbackAnnotationTransactionalTests extends Ab @Before public void verifyInitialTestData() { clearPersonTable(jdbcTemplate); - assertEquals("Adding bob", 1, addPerson(jdbcTemplate, BOB)); - assertEquals("Verifying the initial number of rows in the person table.", 1, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, BOB)).as("Adding bob").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the initial number of rows in the person table.").isEqualTo(1); } @Test public void modifyTestDataWithinTransaction() { assertInTransaction(true); - assertEquals("Deleting bob", 1, deletePerson(jdbcTemplate, BOB)); - assertEquals("Adding jane", 1, addPerson(jdbcTemplate, JANE)); - assertEquals("Adding sue", 1, addPerson(jdbcTemplate, SUE)); - assertEquals("Verifying the number of rows in the person table within a transaction.", 2, - countRowsInPersonTable(jdbcTemplate)); + assertThat(deletePerson(jdbcTemplate, BOB)).as("Deleting bob").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, JANE)).as("Adding jane").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, SUE)).as("Adding sue").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table within a transaction.").isEqualTo(2); } @AfterClass public static void verifyFinalTestData() { - assertEquals("Verifying the final number of rows in the person table after all tests.", 2, - countRowsInPersonTable(jdbcTemplate)); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the final number of rows in the person table after all tests.").isEqualTo(2); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/DefaultRollbackTrueRollbackAnnotationTransactionalTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/DefaultRollbackTrueRollbackAnnotationTransactionalTests.java index 1aa97a59c98..388664b8671 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/DefaultRollbackTrueRollbackAnnotationTransactionalTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/DefaultRollbackTrueRollbackAnnotationTransactionalTests.java @@ -29,7 +29,7 @@ import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -65,24 +65,21 @@ public class DefaultRollbackTrueRollbackAnnotationTransactionalTests extends Abs @Before public void verifyInitialTestData() { originalNumRows = clearPersonTable(jdbcTemplate); - assertEquals("Adding bob", 1, addPerson(jdbcTemplate, BOB)); - assertEquals("Verifying the initial number of rows in the person table.", 1, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, BOB)).as("Adding bob").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the initial number of rows in the person table.").isEqualTo(1); } @Test(timeout = 1000) public void modifyTestDataWithinTransaction() { assertInTransaction(true); - assertEquals("Adding jane", 1, addPerson(jdbcTemplate, JANE)); - assertEquals("Adding sue", 1, addPerson(jdbcTemplate, SUE)); - assertEquals("Verifying the number of rows in the person table within a transaction.", 3, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, JANE)).as("Adding jane").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, SUE)).as("Adding sue").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table within a transaction.").isEqualTo(3); } @AfterClass public static void verifyFinalTestData() { - assertEquals("Verifying the final number of rows in the person table after all tests.", originalNumRows, - countRowsInPersonTable(jdbcTemplate)); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the final number of rows in the person table after all tests.").isEqualTo(originalNumRows); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/EnabledAndIgnoredSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/EnabledAndIgnoredSpringRunnerTests.java index 872ddb18d86..14f7d09f712 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/EnabledAndIgnoredSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/EnabledAndIgnoredSpringRunnerTests.java @@ -27,8 +27,8 @@ import org.springframework.test.annotation.ProfileValueSource; import org.springframework.test.annotation.ProfileValueSourceConfiguration; import org.springframework.test.context.TestExecutionListeners; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * Verifies proper handling of JUnit's {@link Ignore @Ignore} and Spring's @@ -64,7 +64,7 @@ public class EnabledAndIgnoredSpringRunnerTests { @AfterClass public static void verifyNumTestsExecuted() { - assertEquals("Verifying the number of tests executed.", 3, numTestsExecuted); + assertThat(numTestsExecuted).as("Verifying the number of tests executed.").isEqualTo(3); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/FailingBeforeAndAfterMethodsSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/FailingBeforeAndAfterMethodsSpringRunnerTests.java index 0dd87fcbb72..a7ceffe12d7 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/FailingBeforeAndAfterMethodsSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/FailingBeforeAndAfterMethodsSpringRunnerTests.java @@ -32,7 +32,7 @@ import org.springframework.test.context.transaction.BeforeTransaction; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ClassUtils; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.springframework.test.context.junit4.JUnitTestingUtils.runTestsAndAssertCounters; /** diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/FailingBeforeAndAfterMethodsTestNGTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/FailingBeforeAndAfterMethodsTestNGTests.java index 58e2a02727d..916365eae36 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/FailingBeforeAndAfterMethodsTestNGTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/FailingBeforeAndAfterMethodsTestNGTests.java @@ -35,7 +35,7 @@ import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; import org.springframework.util.ClassUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests which verify that 'before' and 'after' @@ -104,11 +104,10 @@ public class FailingBeforeAndAfterMethodsTestNGTests { String name = this.clazz.getSimpleName(); - assertEquals("tests started for [" + name + "] ==> ", this.expectedTestStartCount, listener.testStartCount); - assertEquals("successful tests for [" + name + "] ==> ", this.expectedTestSuccessCount, listener.testSuccessCount); - assertEquals("failed tests for [" + name + "] ==> ", this.expectedFailureCount, listener.testFailureCount); - assertEquals("failed configurations for [" + name + "] ==> ", - this.expectedFailedConfigurationsCount, listener.failedConfigurationsCount); + assertThat(listener.testStartCount).as("tests started for [" + name + "] ==> ").isEqualTo(this.expectedTestStartCount); + assertThat(listener.testSuccessCount).as("successful tests for [" + name + "] ==> ").isEqualTo(this.expectedTestSuccessCount); + assertThat(listener.testFailureCount).as("failed tests for [" + name + "] ==> ").isEqualTo(this.expectedFailureCount); + assertThat(listener.failedConfigurationsCount).as("failed configurations for [" + name + "] ==> ").isEqualTo(this.expectedFailedConfigurationsCount); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/MethodLevelTransactionalSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/MethodLevelTransactionalSpringRunnerTests.java index fcee84688f4..739de585724 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/MethodLevelTransactionalSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/MethodLevelTransactionalSpringRunnerTests.java @@ -33,7 +33,7 @@ import org.springframework.test.context.support.DirtiesContextTestExecutionListe import org.springframework.test.context.transaction.TransactionalTestExecutionListener; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -72,37 +72,33 @@ public class MethodLevelTransactionalSpringRunnerTests extends AbstractTransacti @AfterClass public static void verifyFinalTestData() { - assertEquals("Verifying the final number of rows in the person table after all tests.", 4, - countRowsInPersonTable(jdbcTemplate)); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the final number of rows in the person table after all tests.").isEqualTo(4); } @Before public void verifyInitialTestData() { clearPersonTable(jdbcTemplate); - assertEquals("Adding bob", 1, addPerson(jdbcTemplate, BOB)); - assertEquals("Verifying the initial number of rows in the person table.", 1, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, BOB)).as("Adding bob").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the initial number of rows in the person table.").isEqualTo(1); } @Test @Transactional("transactionManager2") public void modifyTestDataWithinTransaction() { assertInTransaction(true); - assertEquals("Deleting bob", 1, deletePerson(jdbcTemplate, BOB)); - assertEquals("Adding jane", 1, addPerson(jdbcTemplate, JANE)); - assertEquals("Adding sue", 1, addPerson(jdbcTemplate, SUE)); - assertEquals("Verifying the number of rows in the person table within a transaction.", 2, - countRowsInPersonTable(jdbcTemplate)); + assertThat(deletePerson(jdbcTemplate, BOB)).as("Deleting bob").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, JANE)).as("Adding jane").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, SUE)).as("Adding sue").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table within a transaction.").isEqualTo(2); } @Test public void modifyTestDataWithoutTransaction() { assertInTransaction(false); - assertEquals("Adding luke", 1, addPerson(jdbcTemplate, LUKE)); - assertEquals("Adding leia", 1, addPerson(jdbcTemplate, LEIA)); - assertEquals("Adding yoda", 1, addPerson(jdbcTemplate, YODA)); - assertEquals("Verifying the number of rows in the person table without a transaction.", 4, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, LUKE)).as("Adding luke").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, LEIA)).as("Adding leia").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, YODA)).as("Adding yoda").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table without a transaction.").isEqualTo(4); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/OptionalContextConfigurationSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/OptionalContextConfigurationSpringRunnerTests.java index 6d540f1a245..71bced98d41 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/OptionalContextConfigurationSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/OptionalContextConfigurationSpringRunnerTests.java @@ -24,7 +24,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit 4 based integration test which verifies that @@ -43,7 +43,7 @@ public class OptionalContextConfigurationSpringRunnerTests { @Test public void contextConfigurationAnnotationIsOptional() { - assertEquals("foo", foo); + assertThat(foo).isEqualTo("foo"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests.java index 8a0facf4a09..52465a73590 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests.java @@ -36,8 +36,7 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Simple JUnit 4 based integration test which demonstrates how to use JUnit's @@ -93,18 +92,16 @@ public class ParameterizedDependencyInjectionTests { invocationCount.incrementAndGet(); // Verifying dependency injection: - assertNotNull("The pet field should have been autowired.", this.pet); + assertThat(this.pet).as("The pet field should have been autowired.").isNotNull(); // Verifying 'parameterized' support: Employee employee = this.applicationContext.getBean(this.employeeBeanName, Employee.class); - assertEquals("Name of the employee configured as bean [" + this.employeeBeanName + "].", this.employeeName, - employee.getName()); + assertThat(employee.getName()).as("Name of the employee configured as bean [" + this.employeeBeanName + "].").isEqualTo(this.employeeName); } @AfterClass public static void verifyNumParameterizedRuns() { - assertEquals("Number of times the parameterized test method was executed.", employeeData().length, - invocationCount.get()); + assertThat(invocationCount.get()).as("Number of times the parameterized test method was executed.").isEqualTo(employeeData().length); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java index 222b33cb278..536f4123b9d 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java @@ -27,8 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.support.GenericPropertiesContextLoader; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** *

@@ -68,11 +67,11 @@ public class PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests { @Test public void verifyAnnotationAutowiredFields() { - assertNotNull("The cat field should have been autowired.", this.cat); - assertEquals("Garfield", this.cat.getName()); + assertThat(this.cat).as("The cat field should have been autowired.").isNotNull(); + assertThat(this.cat.getName()).isEqualTo("Garfield"); - assertNotNull("The testString field should have been autowired.", this.testString); - assertEquals("Test String", this.testString); + assertThat(this.testString).as("The testString field should have been autowired.").isNotNull(); + assertThat(this.testString).isEqualTo("Test String"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java index 854f16b623c..7dc81e5360e 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java @@ -33,7 +33,7 @@ import org.springframework.test.annotation.Timed; import org.springframework.test.context.TestExecutionListeners; import org.springframework.util.ClassUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.junit4.JUnitTestingUtils.runTestsAndAssertCounters; /** @@ -92,7 +92,7 @@ public class RepeatedSpringRunnerTests { runTestsAndAssertCounters(getRunnerClass(), this.testClass, expectedStartedCount, expectedFailureCount, expectedFinishedCount, 0, 0); - assertEquals("invocations for [" + testClass + "]:", expectedInvocationCount, invocationCount.get()); + assertThat(invocationCount.get()).as("invocations for [" + testClass + "]:").isEqualTo(expectedInvocationCount); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackFalseRollbackAnnotationTransactionalTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackFalseRollbackAnnotationTransactionalTests.java index 214783f060d..303cfa24f41 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackFalseRollbackAnnotationTransactionalTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackFalseRollbackAnnotationTransactionalTests.java @@ -26,7 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.annotation.Rollback; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -56,9 +56,8 @@ public class RollbackOverrideDefaultRollbackFalseRollbackAnnotationTransactional @Override public void verifyInitialTestData() { originalNumRows = clearPersonTable(jdbcTemplate); - assertEquals("Adding bob", 1, addPerson(jdbcTemplate, BOB)); - assertEquals("Verifying the initial number of rows in the person table.", 1, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, BOB)).as("Adding bob").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the initial number of rows in the person table.").isEqualTo(1); } @Test @@ -66,17 +65,15 @@ public class RollbackOverrideDefaultRollbackFalseRollbackAnnotationTransactional @Override public void modifyTestDataWithinTransaction() { assertInTransaction(true); - assertEquals("Deleting bob", 1, deletePerson(jdbcTemplate, BOB)); - assertEquals("Adding jane", 1, addPerson(jdbcTemplate, JANE)); - assertEquals("Adding sue", 1, addPerson(jdbcTemplate, SUE)); - assertEquals("Verifying the number of rows in the person table within a transaction.", 2, - countRowsInPersonTable(jdbcTemplate)); + assertThat(deletePerson(jdbcTemplate, BOB)).as("Deleting bob").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, JANE)).as("Adding jane").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, SUE)).as("Adding sue").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table within a transaction.").isEqualTo(2); } @AfterClass public static void verifyFinalTestData() { - assertEquals("Verifying the final number of rows in the person table after all tests.", originalNumRows, - countRowsInPersonTable(jdbcTemplate)); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the final number of rows in the person table after all tests.").isEqualTo(originalNumRows); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackFalseTransactionalTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackFalseTransactionalTests.java index f0ac551a577..c87e89f7979 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackFalseTransactionalTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackFalseTransactionalTests.java @@ -26,7 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.annotation.Rollback; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -56,9 +56,8 @@ public class RollbackOverrideDefaultRollbackFalseTransactionalTests @Override public void verifyInitialTestData() { originalNumRows = clearPersonTable(jdbcTemplate); - assertEquals("Adding bob", 1, addPerson(jdbcTemplate, BOB)); - assertEquals("Verifying the initial number of rows in the person table.", 1, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, BOB)).as("Adding bob").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the initial number of rows in the person table.").isEqualTo(1); } @Test @@ -66,17 +65,15 @@ public class RollbackOverrideDefaultRollbackFalseTransactionalTests @Override public void modifyTestDataWithinTransaction() { assertInTransaction(true); - assertEquals("Deleting bob", 1, deletePerson(jdbcTemplate, BOB)); - assertEquals("Adding jane", 1, addPerson(jdbcTemplate, JANE)); - assertEquals("Adding sue", 1, addPerson(jdbcTemplate, SUE)); - assertEquals("Verifying the number of rows in the person table within a transaction.", 2, - countRowsInPersonTable(jdbcTemplate)); + assertThat(deletePerson(jdbcTemplate, BOB)).as("Deleting bob").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, JANE)).as("Adding jane").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, SUE)).as("Adding sue").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table within a transaction.").isEqualTo(2); } @AfterClass public static void verifyFinalTestData() { - assertEquals("Verifying the final number of rows in the person table after all tests.", originalNumRows, - countRowsInPersonTable(jdbcTemplate)); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the final number of rows in the person table after all tests.").isEqualTo(originalNumRows); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackTrueRollbackAnnotationTransactionalTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackTrueRollbackAnnotationTransactionalTests.java index 36bcff6803d..2386f1c0a4b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackTrueRollbackAnnotationTransactionalTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackTrueRollbackAnnotationTransactionalTests.java @@ -26,7 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.annotation.Rollback; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -55,9 +55,8 @@ public class RollbackOverrideDefaultRollbackTrueRollbackAnnotationTransactionalT @Override public void verifyInitialTestData() { clearPersonTable(jdbcTemplate); - assertEquals("Adding bob", 1, addPerson(jdbcTemplate, BOB)); - assertEquals("Verifying the initial number of rows in the person table.", 1, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, BOB)).as("Adding bob").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the initial number of rows in the person table.").isEqualTo(1); } @Test @@ -65,16 +64,14 @@ public class RollbackOverrideDefaultRollbackTrueRollbackAnnotationTransactionalT @Override public void modifyTestDataWithinTransaction() { assertInTransaction(true); - assertEquals("Adding jane", 1, addPerson(jdbcTemplate, JANE)); - assertEquals("Adding sue", 1, addPerson(jdbcTemplate, SUE)); - assertEquals("Verifying the number of rows in the person table within a transaction.", 3, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, JANE)).as("Adding jane").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, SUE)).as("Adding sue").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table within a transaction.").isEqualTo(3); } @AfterClass public static void verifyFinalTestData() { - assertEquals("Verifying the final number of rows in the person table after all tests.", 3, - countRowsInPersonTable(jdbcTemplate)); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the final number of rows in the person table after all tests.").isEqualTo(3); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackTrueTransactionalTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackTrueTransactionalTests.java index 97591718900..b57faf9d764 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackTrueTransactionalTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/RollbackOverrideDefaultRollbackTrueTransactionalTests.java @@ -26,7 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.annotation.Rollback; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -53,9 +53,8 @@ public class RollbackOverrideDefaultRollbackTrueTransactionalTests @Override public void verifyInitialTestData() { clearPersonTable(jdbcTemplate); - assertEquals("Adding bob", 1, addPerson(jdbcTemplate, BOB)); - assertEquals("Verifying the initial number of rows in the person table.", 1, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, BOB)).as("Adding bob").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the initial number of rows in the person table.").isEqualTo(1); } @Test @@ -63,16 +62,14 @@ public class RollbackOverrideDefaultRollbackTrueTransactionalTests @Override public void modifyTestDataWithinTransaction() { assertInTransaction(true); - assertEquals("Adding jane", 1, addPerson(jdbcTemplate, JANE)); - assertEquals("Adding sue", 1, addPerson(jdbcTemplate, SUE)); - assertEquals("Verifying the number of rows in the person table within a transaction.", 3, - countRowsInPersonTable(jdbcTemplate)); + assertThat(addPerson(jdbcTemplate, JANE)).as("Adding jane").isEqualTo(1); + assertThat(addPerson(jdbcTemplate, SUE)).as("Adding sue").isEqualTo(1); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the number of rows in the person table within a transaction.").isEqualTo(3); } @AfterClass public static void verifyFinalTestData() { - assertEquals("Verifying the final number of rows in the person table after all tests.", 3, - countRowsInPersonTable(jdbcTemplate)); + assertThat(countRowsInPersonTable(jdbcTemplate)).as("Verifying the final number of rows in the person table after all tests.").isEqualTo(3); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit47ClassRunnerRuleTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit47ClassRunnerRuleTests.java index dff5efe4613..07776e89856 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit47ClassRunnerRuleTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit47ClassRunnerRuleTests.java @@ -23,7 +23,7 @@ import org.junit.runner.RunWith; import org.springframework.test.context.TestExecutionListeners; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Verifies support for JUnit 4.7 {@link Rule Rules} in conjunction with the @@ -44,11 +44,11 @@ public class SpringJUnit47ClassRunnerRuleTests { @Test public void testA() { - assertEquals("testA", name.getMethodName()); + assertThat(name.getMethodName()).isEqualTo("testA"); } @Test public void testB() { - assertEquals("testB", name.getMethodName()); + assertThat(name.getMethodName()).isEqualTo("testB"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java index 9d49706e9fc..c5af71596e5 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java @@ -37,11 +37,7 @@ import org.springframework.test.context.support.GenericXmlContextLoader; import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.Pet; -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.assertj.core.api.Assertions.assertThat; /** * SpringJUnit4ClassRunnerAppCtxTests serves as a proof of concept @@ -168,66 +164,63 @@ public class SpringJUnit4ClassRunnerAppCtxTests implements ApplicationContextAwa @Test public void verifyBeanNameSet() { - assertTrue("The bean name of this test instance should have been set due to BeanNameAware semantics.", - this.beanName.startsWith(getClass().getName())); + assertThat(this.beanName.startsWith(getClass().getName())).as("The bean name of this test instance should have been set due to BeanNameAware semantics.").isTrue(); } @Test public void verifyApplicationContextSet() { - assertNotNull("The application context should have been set due to ApplicationContextAware semantics.", - this.applicationContext); + assertThat(this.applicationContext).as("The application context should have been set due to ApplicationContextAware semantics.").isNotNull(); } @Test public void verifyBeanInitialized() { - assertTrue("This test bean should have been initialized due to InitializingBean semantics.", - this.beanInitialized); + assertThat(this.beanInitialized).as("This test bean should have been initialized due to InitializingBean semantics.").isTrue(); } @Test public void verifyAnnotationAutowiredAndInjectedFields() { - assertNull("The nonrequiredLong field should NOT have been autowired.", this.nonrequiredLong); - assertEquals("The quux field should have been autowired via @Autowired and @Qualifier.", "Quux", this.quux); - assertEquals("The namedFoo field should have been injected via @Inject and @Named.", "Quux", this.namedQuux); - assertSame("@Autowired/@Qualifier and @Inject/@Named quux should be the same object.", this.quux, this.namedQuux); + assertThat(this.nonrequiredLong).as("The nonrequiredLong field should NOT have been autowired.").isNull(); + assertThat(this.quux).as("The quux field should have been autowired via @Autowired and @Qualifier.").isEqualTo("Quux"); + assertThat(this.namedQuux).as("The namedFoo field should have been injected via @Inject and @Named.").isEqualTo("Quux"); + assertThat(this.namedQuux).as("@Autowired/@Qualifier and @Inject/@Named quux should be the same object.").isSameAs(this.quux); - assertNotNull("The pet field should have been autowired.", this.autowiredPet); - assertNotNull("The pet field should have been injected.", this.injectedPet); - assertEquals("Fido", this.autowiredPet.getName()); - assertEquals("Fido", this.injectedPet.getName()); - assertSame("@Autowired and @Inject pet should be the same object.", this.autowiredPet, this.injectedPet); + assertThat(this.autowiredPet).as("The pet field should have been autowired.").isNotNull(); + assertThat(this.injectedPet).as("The pet field should have been injected.").isNotNull(); + assertThat(this.autowiredPet.getName()).isEqualTo("Fido"); + assertThat(this.injectedPet.getName()).isEqualTo("Fido"); + assertThat(this.injectedPet).as("@Autowired and @Inject pet should be the same object.").isSameAs(this.autowiredPet); } @Test public void verifyAnnotationAutowiredMethods() { - assertNotNull("The employee setter method should have been autowired.", this.employee); - assertEquals("John Smith", this.employee.getName()); + assertThat(this.employee).as("The employee setter method should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("John Smith"); } @Test public void verifyAutowiredAtValueFields() { - assertNotNull("Literal @Value field should have been autowired", this.literalFieldValue); - assertNotNull("SpEL @Value field should have been autowired.", this.spelFieldValue); - assertEquals("enigma", this.literalFieldValue); - assertEquals(Boolean.TRUE, this.spelFieldValue); + assertThat(this.literalFieldValue).as("Literal @Value field should have been autowired").isNotNull(); + assertThat(this.spelFieldValue).as("SpEL @Value field should have been autowired.").isNotNull(); + assertThat(this.literalFieldValue).isEqualTo("enigma"); + assertThat(this.spelFieldValue).isEqualTo(Boolean.TRUE); } @Test public void verifyAutowiredAtValueMethods() { - assertNotNull("Literal @Value method parameter should have been autowired.", this.literalParameterValue); - assertNotNull("SpEL @Value method parameter should have been autowired.", this.spelParameterValue); - assertEquals("enigma", this.literalParameterValue); - assertEquals(Boolean.TRUE, this.spelParameterValue); + assertThat(this.literalParameterValue).as("Literal @Value method parameter should have been autowired.").isNotNull(); + assertThat(this.spelParameterValue).as("SpEL @Value method parameter should have been autowired.").isNotNull(); + assertThat(this.literalParameterValue).isEqualTo("enigma"); + assertThat(this.spelParameterValue).isEqualTo(Boolean.TRUE); } @Test public void verifyResourceAnnotationInjectedFields() { - assertEquals("The foo field should have been injected via @Resource.", "Foo", this.foo); + assertThat(this.foo).as("The foo field should have been injected via @Resource.").isEqualTo("Foo"); } @Test public void verifyResourceAnnotationInjectedMethods() { - assertEquals("The bar method should have been wired via @Resource.", "Bar", this.bar); + assertThat(this.bar).as("The bar method should have been wired via @Resource.").isEqualTo("Bar"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerTests.java index 832a19705cc..63f937aad2c 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerTests.java @@ -25,8 +25,8 @@ import org.junit.runners.model.FrameworkMethod; import org.springframework.test.annotation.Timed; import org.springframework.test.context.TestContextManager; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link SpringJUnit4ClassRunner}. @@ -62,7 +62,7 @@ public class SpringJUnit4ClassRunnerTests { SpringJUnit4ClassRunner runner = new SpringJUnit4ClassRunner(getClass()); long timeout = runner.getSpringTimeout(new FrameworkMethod(getClass().getDeclaredMethod( "springTimeoutWithMetaAnnotation"))); - assertEquals(10, timeout); + assertThat(timeout).isEqualTo(10); } @Test @@ -70,7 +70,7 @@ public class SpringJUnit4ClassRunnerTests { SpringJUnit4ClassRunner runner = new SpringJUnit4ClassRunner(getClass()); long timeout = runner.getSpringTimeout(new FrameworkMethod(getClass().getDeclaredMethod( "springTimeoutWithMetaAnnotationAndOverride"))); - assertEquals(42, timeout); + assertThat(timeout).isEqualTo(42); } // ------------------------------------------------------------------------- diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/StandardJUnit4FeaturesTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/StandardJUnit4FeaturesTests.java index 52ffbfbec75..2c79b734343 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/StandardJUnit4FeaturesTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/StandardJUnit4FeaturesTests.java @@ -23,9 +23,8 @@ import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.junit.Assume.assumeTrue; /** @@ -68,7 +67,7 @@ public class StandardJUnit4FeaturesTests { @Test public void alwaysSucceeds() { - assertTrue(true); + assertThat(true).isTrue(); } @Test(expected = IndexOutOfBoundsException.class) @@ -94,7 +93,7 @@ public class StandardJUnit4FeaturesTests { @Test public void verifyBeforeAnnotation() { - assertEquals(1, this.beforeCounter); + assertThat(this.beforeCounter).isEqualTo(1); } @Test @@ -102,7 +101,7 @@ public class StandardJUnit4FeaturesTests { // Instead of testing for equality to 1, we just assert that the value // was incremented at least once, since this test class may serve as a // parent class to other tests in a suite, etc. - assertTrue(StandardJUnit4FeaturesTests.staticBeforeCounter > 0); + assertThat(StandardJUnit4FeaturesTests.staticBeforeCounter > 0).isTrue(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/InitializerConfiguredViaMetaAnnotationTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/InitializerConfiguredViaMetaAnnotationTests.java index ab09ae0b7c9..1be693f8871 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/InitializerConfiguredViaMetaAnnotationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/InitializerConfiguredViaMetaAnnotationTests.java @@ -35,7 +35,7 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.aci.annotation.InitializerConfiguredViaMetaAnnotationTests.ComposedContextConfiguration; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration test that demonstrates how to register one or more {@code @Configuration} @@ -67,9 +67,9 @@ public class InitializerConfiguredViaMetaAnnotationTests { @Test public void beansFromInitializerAndComposedAnnotation() { - assertEquals(2, strings.size()); - assertEquals("foo", foo); - assertEquals("bar", bar); + assertThat(strings.size()).isEqualTo(2); + assertThat(foo).isEqualTo("foo"); + assertThat(bar).isEqualTo("bar"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/InitializerWithoutConfigFilesOrClassesTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/InitializerWithoutConfigFilesOrClassesTests.java index e97e2891e38..7919028b199 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/InitializerWithoutConfigFilesOrClassesTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/InitializerWithoutConfigFilesOrClassesTests.java @@ -27,7 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.aci.annotation.InitializerWithoutConfigFilesOrClassesTests.EntireAppInitializer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration test that verifies support for {@link ApplicationContextInitializer @@ -47,7 +47,7 @@ public class InitializerWithoutConfigFilesOrClassesTests { @Test public void foo() { - assertEquals("foo", foo); + assertThat(foo).isEqualTo("foo"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/MergedInitializersAnnotationConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/MergedInitializersAnnotationConfigTests.java index b0598782a49..7201c632ba2 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/MergedInitializersAnnotationConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/MergedInitializersAnnotationConfigTests.java @@ -22,7 +22,7 @@ import org.springframework.context.ApplicationContextInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.aci.DevProfileInitializer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for {@link ApplicationContextInitializer @@ -38,8 +38,8 @@ public class MergedInitializersAnnotationConfigTests extends SingleInitializerAn @Override @Test public void activeBeans() { - assertEquals("foo", foo); - assertEquals("foo", bar); - assertEquals("dev profile config", baz); + assertThat(foo).isEqualTo("foo"); + assertThat(bar).isEqualTo("foo"); + assertThat(baz).isEqualTo("dev profile config"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/MultipleInitializersAnnotationConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/MultipleInitializersAnnotationConfigTests.java index c4345411d25..412e98c6e08 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/MultipleInitializersAnnotationConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/MultipleInitializersAnnotationConfigTests.java @@ -26,7 +26,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.aci.DevProfileInitializer; import org.springframework.test.context.junit4.aci.FooBarAliasInitializer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for {@link ApplicationContextInitializer @@ -47,9 +47,9 @@ public class MultipleInitializersAnnotationConfigTests { @Test public void activeBeans() { - assertEquals("foo", foo); - assertEquals("foo", bar); - assertEquals("dev profile config", baz); + assertThat(foo).isEqualTo("foo"); + assertThat(bar).isEqualTo("foo"); + assertThat(baz).isEqualTo("dev profile config"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/OrderedInitializersAnnotationConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/OrderedInitializersAnnotationConfigTests.java index ec071711317..75b0b600004 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/OrderedInitializersAnnotationConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/OrderedInitializersAnnotationConfigTests.java @@ -35,7 +35,7 @@ import org.springframework.test.context.junit4.aci.annotation.OrderedInitializer import org.springframework.test.context.junit4.aci.annotation.OrderedInitializersAnnotationConfigTests.OrderedOneInitializer; import org.springframework.test.context.junit4.aci.annotation.OrderedInitializersAnnotationConfigTests.OrderedTwoInitializer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify that any {@link ApplicationContextInitializer @@ -65,9 +65,9 @@ public class OrderedInitializersAnnotationConfigTests { @Test public void activeBeans() { - assertEquals(PROFILE_GLOBAL, foo); - assertEquals(PROFILE_GLOBAL, bar); - assertEquals(PROFILE_TWO, baz); + assertThat(foo).isEqualTo(PROFILE_GLOBAL); + assertThat(bar).isEqualTo(PROFILE_GLOBAL); + assertThat(baz).isEqualTo(PROFILE_TWO); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/OverriddenInitializersAnnotationConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/OverriddenInitializersAnnotationConfigTests.java index 529e12fd904..6f270188ec1 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/OverriddenInitializersAnnotationConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/OverriddenInitializersAnnotationConfigTests.java @@ -22,8 +22,7 @@ import org.springframework.context.ApplicationContextInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.aci.DevProfileInitializer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for {@link ApplicationContextInitializer @@ -39,8 +38,8 @@ public class OverriddenInitializersAnnotationConfigTests extends SingleInitializ @Test @Override public void activeBeans() { - assertEquals("foo", foo); - assertNull(bar); - assertEquals("dev profile config", baz); + assertThat(foo).isEqualTo("foo"); + assertThat(bar).isNull(); + assertThat(baz).isEqualTo("dev profile config"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/PropertySourcesInitializerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/PropertySourcesInitializerTests.java index df994d4d2b0..53accb9cba3 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/PropertySourcesInitializerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/PropertySourcesInitializerTests.java @@ -30,7 +30,7 @@ import org.springframework.mock.env.MockPropertySource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify that a {@link PropertySource} can be set via a @@ -67,7 +67,7 @@ public class PropertySourcesInitializerTests { @Test public void customPropertySourceConfiguredViaContextInitializer() { - assertEquals("foo", enigma); + assertThat(enigma).isEqualTo("foo"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/SingleInitializerAnnotationConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/SingleInitializerAnnotationConfigTests.java index 7e22f7c0e20..44956eb010d 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/SingleInitializerAnnotationConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/SingleInitializerAnnotationConfigTests.java @@ -26,7 +26,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.aci.FooBarAliasInitializer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for {@link ApplicationContextInitializer @@ -53,9 +53,9 @@ public class SingleInitializerAnnotationConfigTests { @Test public void activeBeans() { - assertEquals("foo", foo); - assertEquals("foo", bar); - assertEquals("global config", baz); + assertThat(foo).isEqualTo("foo"); + assertThat(bar).isEqualTo("foo"); + assertThat(baz).isEqualTo("global config"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/xml/MultipleInitializersXmlConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/xml/MultipleInitializersXmlConfigTests.java index b57911c2139..e5ad01d8fb8 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/aci/xml/MultipleInitializersXmlConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/aci/xml/MultipleInitializersXmlConfigTests.java @@ -26,7 +26,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.aci.DevProfileInitializer; import org.springframework.test.context.junit4.aci.FooBarAliasInitializer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for {@link ApplicationContextInitializer @@ -46,9 +46,9 @@ public class MultipleInitializersXmlConfigTests { @Test public void activeBeans() { - assertEquals("foo", foo); - assertEquals("foo", bar); - assertEquals("dev profile config", baz); + assertThat(foo).isEqualTo("foo"); + assertThat(bar).isEqualTo("foo"); + assertThat(baz).isEqualTo("dev profile config"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java index f81d9e56350..2c481468524 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java @@ -23,8 +23,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.tests.sample.beans.Employee; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -56,8 +55,8 @@ public class BeanOverridingDefaultConfigClassesInheritedTests extends DefaultCon @Test @Override public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee should have been autowired.", this.employee); - assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName()); + assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).as("The employee bean should have been overridden.").isEqualTo("Yoda"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingExplicitConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingExplicitConfigClassesInheritedTests.java index bd18e4a6d55..31fb3d0ecfc 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingExplicitConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingExplicitConfigClassesInheritedTests.java @@ -20,8 +20,7 @@ import org.junit.Test; import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -39,8 +38,8 @@ public class BeanOverridingExplicitConfigClassesInheritedTests extends ExplicitC @Test @Override public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee should have been autowired.", this.employee); - assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName()); + assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).as("The employee bean should have been overridden.").isEqualTo("Yoda"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java index 459b1885481..364a4b8d898 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java @@ -27,8 +27,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.tests.sample.beans.Employee; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -64,8 +63,8 @@ public class DefaultConfigClassesBaseTests { @Test public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee field should have been autowired.", this.employee); - assertEquals("John Smith", this.employee.getName()); + assertThat(this.employee).as("The employee field should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("John Smith"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java index 58805644574..8b04b99baa3 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java @@ -24,8 +24,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -56,8 +55,8 @@ public class DefaultConfigClassesInheritedTests extends DefaultConfigClassesBase @Test public void verifyPetSetFromExtendedContextConfig() { - assertNotNull("The pet should have been autowired.", this.pet); - assertEquals("Fido", this.pet.getName()); + assertThat(this.pet).as("The pet should have been autowired.").isNotNull(); + assertThat(this.pet.getName()).isEqualTo("Fido"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.java index bd290df2edd..70f22f16b66 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.java @@ -24,8 +24,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.support.DelegatingSmartContextLoader; import org.springframework.tests.sample.beans.Employee; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -56,8 +55,8 @@ public class DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests exten @Test @Override public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee should have been autowired.", this.employee); - assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName()); + assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).as("The employee bean should have been overridden.").isEqualTo("Yoda"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests.java index 40147fe1213..4be240ce7e3 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests.java @@ -21,8 +21,7 @@ import org.junit.Test; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.support.DelegatingSmartContextLoader; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -39,8 +38,8 @@ public class DefaultLoaderBeanOverridingExplicitConfigClassesInheritedTests exte @Test @Override public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee should have been autowired.", this.employee); - assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName()); + assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).as("The employee bean should have been overridden.").isEqualTo("Yoda"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesBaseTests.java index 3aaf5f283ab..487b23239eb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesBaseTests.java @@ -27,8 +27,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DelegatingSmartContextLoader; import org.springframework.tests.sample.beans.Employee; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -63,8 +62,8 @@ public class DefaultLoaderDefaultConfigClassesBaseTests { @Test public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee field should have been autowired.", this.employee); - assertEquals("John Smith", this.employee.getName()); + assertThat(this.employee).as("The employee field should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("John Smith"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesInheritedTests.java index 0cae18905c0..9781667959b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesInheritedTests.java @@ -25,8 +25,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.support.DelegatingSmartContextLoader; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -55,8 +54,8 @@ public class DefaultLoaderDefaultConfigClassesInheritedTests extends DefaultLoad @Test public void verifyPetSetFromExtendedContextConfig() { - assertNotNull("The pet should have been autowired.", this.pet); - assertEquals("Fido", this.pet.getName()); + assertThat(this.pet).as("The pet should have been autowired.").isNotNull(); + assertThat(this.pet.getName()).isEqualTo("Fido"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesBaseTests.java index cb26c5476c8..551a055ec6d 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesBaseTests.java @@ -25,8 +25,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DelegatingSmartContextLoader; import org.springframework.tests.sample.beans.Employee; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -46,8 +45,8 @@ public class DefaultLoaderExplicitConfigClassesBaseTests { @Test public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee should have been autowired.", this.employee); - assertEquals("John Smith", this.employee.getName()); + assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("John Smith"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesInheritedTests.java index 79b8fd82d4a..d81e7a9fd7b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesInheritedTests.java @@ -25,8 +25,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DelegatingSmartContextLoader; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -46,8 +45,8 @@ public class DefaultLoaderExplicitConfigClassesInheritedTests extends DefaultLoa @Test public void verifyPetSetFromExtendedContextConfig() { - assertNotNull("The pet should have been autowired.", this.pet); - assertEquals("Fido", this.pet.getName()); + assertThat(this.pet).as("The pet should have been autowired.").isNotNull(); + assertThat(this.pet.getName()).isEqualTo("Fido"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java index d53934eca6c..0ebdc22ef9a 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java @@ -25,8 +25,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.tests.sample.beans.Employee; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -47,8 +46,8 @@ public class ExplicitConfigClassesBaseTests { @Test public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee should have been autowired.", this.employee); - assertEquals("John Smith", this.employee.getName()); + assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("John Smith"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java index cf4f5f3c24e..53397d5ffc9 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java @@ -25,8 +25,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for configuration classes in @@ -48,8 +47,8 @@ public class ExplicitConfigClassesInheritedTests extends ExplicitConfigClassesBa @Test public void verifyPetSetFromExtendedContextConfig() { - assertNotNull("The pet should have been autowired.", this.pet); - assertEquals("Fido", this.pet.getName()); + assertThat(this.pet).as("The pet should have been autowired.").isNotNull(); + assertThat(this.pet.getName()).isEqualTo("Fido"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfigTests.java index 3b6b41a0dca..d48627f60f1 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfigTests.java @@ -22,7 +22,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for meta-annotation attribute override support, relying on @@ -41,6 +41,6 @@ public class ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfigTests { @Test public void foo() { - assertEquals("Resolver Foo", foo); + assertThat(foo).isEqualTo("Resolver Foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfigWithOverridesTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfigWithOverridesTests.java index ad363614bdf..70be2085016 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfigWithOverridesTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfigWithOverridesTests.java @@ -26,7 +26,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.test.context.ActiveProfilesResolver; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for meta-annotation attribute override support, overriding @@ -45,7 +45,7 @@ public class ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfigWithOver @Test public void foo() { - assertEquals("Local Dev Foo", foo); + assertThat(foo).isEqualTo("Local Dev Foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesMetaConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesMetaConfigTests.java index 063add59fd8..469870028ec 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesMetaConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesMetaConfigTests.java @@ -25,7 +25,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for meta-annotation attribute override support, demonstrating @@ -66,6 +66,6 @@ public class ConfigClassesAndProfilesMetaConfigTests { @Test public void foo() { - assertEquals("Local Dev Foo", foo); + assertThat(foo).isEqualTo("Local Dev Foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesWithCustomDefaultsMetaConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesWithCustomDefaultsMetaConfigTests.java index c5594387b7a..f6a8bf102b2 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesWithCustomDefaultsMetaConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesWithCustomDefaultsMetaConfigTests.java @@ -22,7 +22,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for meta-annotation attribute override support, relying on @@ -41,6 +41,6 @@ public class ConfigClassesAndProfilesWithCustomDefaultsMetaConfigTests { @Test public void foo() { - assertEquals("Dev Foo", foo); + assertThat(foo).isEqualTo("Dev Foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesWithCustomDefaultsMetaConfigWithOverridesTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesWithCustomDefaultsMetaConfigWithOverridesTests.java index 616b970435b..e3cbf9cbeef 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesWithCustomDefaultsMetaConfigWithOverridesTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesWithCustomDefaultsMetaConfigWithOverridesTests.java @@ -25,8 +25,7 @@ import org.springframework.test.context.junit4.annotation.PojoAndStringConfig; import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for meta-annotation attribute override support, overriding @@ -52,18 +51,18 @@ public class ConfigClassesAndProfilesWithCustomDefaultsMetaConfigWithOverridesTe @Test public void verifyEmployee() { - assertNotNull("The employee should have been autowired.", this.employee); - assertEquals("John Smith", this.employee.getName()); + assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("John Smith"); } @Test public void verifyPet() { - assertNotNull("The pet should have been autowired.", this.pet); - assertEquals("Fido", this.pet.getName()); + assertThat(this.pet).as("The pet should have been autowired.").isNotNull(); + assertThat(this.pet.getName()).isEqualTo("Fido"); } @Test public void verifyFoo() { - assertEquals("Production Foo", this.foo); + assertThat(this.foo).isEqualTo("Production Foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/MetaMetaConfigDefaultsTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/MetaMetaConfigDefaultsTests.java index 617b2a76fb4..65fe0c5da30 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/MetaMetaConfigDefaultsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/MetaMetaConfigDefaultsTests.java @@ -22,7 +22,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for meta-meta-annotation support, relying on default attribute @@ -42,6 +42,6 @@ public class MetaMetaConfigDefaultsTests { @Test public void foo() { - assertEquals("Production Foo", foo); + assertThat(foo).isEqualTo("Production Foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/hybrid/HybridContextLoaderTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/hybrid/HybridContextLoaderTests.java index 225a55bc7e8..6ebd008b74f 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/hybrid/HybridContextLoaderTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/hybrid/HybridContextLoaderTests.java @@ -26,7 +26,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.SmartContextLoader; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for hybrid {@link SmartContextLoader} implementations that @@ -68,14 +68,14 @@ public class HybridContextLoaderTests { @Test public void verifyContentsOfHybridApplicationContext() { - assertEquals("XML", fooFromXml); - assertEquals("Java", fooFromJava); + assertThat(fooFromXml).isEqualTo("XML"); + assertThat(fooFromJava).isEqualTo("Java"); // Note: the XML bean definition for "enigma" always wins since // ConfigurationClassBeanDefinitionReader.isOverriddenByExistingDefinition() // lets XML bean definitions override those "discovered" later via an // @Bean method. - assertEquals("enigma from XML", enigma); + assertThat(enigma).isEqualTo("enigma from XML"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/nested/NestedTestsWithSpringRulesTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/nested/NestedTestsWithSpringRulesTests.java index 2602ca80288..5da148af5d0 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/nested/NestedTestsWithSpringRulesTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/nested/NestedTestsWithSpringRulesTests.java @@ -28,8 +28,7 @@ import org.springframework.test.context.junit4.nested.NestedTestsWithSpringRules import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit 4 based integration tests for nested test classes that are @@ -50,7 +49,7 @@ public class NestedTestsWithSpringRulesTests extends SpringRuleConfigurer { @Test public void topLevelTest() { - assertEquals("foo", foo); + assertThat(foo).isEqualTo("foo"); } @@ -69,8 +68,8 @@ public class NestedTestsWithSpringRulesTests extends SpringRuleConfigurer { // // assertEquals("foo", foo); - assertNull("@Autowired field in enclosing instance should be null.", foo); - assertEquals("bar", bar); + assertThat(foo).as("@Autowired field in enclosing instance should be null.").isNull(); + assertThat(bar).isEqualTo("bar"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/orm/HibernateSessionFlushingTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/orm/HibernateSessionFlushingTests.java index bf1be54d122..b9dc1e15bf6 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/orm/HibernateSessionFlushingTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/orm/HibernateSessionFlushingTests.java @@ -32,9 +32,8 @@ import org.springframework.test.context.junit4.orm.domain.Person; import org.springframework.test.context.junit4.orm.service.PersonService; import org.springframework.transaction.annotation.Transactional; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -62,18 +61,18 @@ public class HibernateSessionFlushingTests extends AbstractTransactionalJUnit4Sp @Before public void setup() { assertInTransaction(true); - assertNotNull("PersonService should have been autowired.", personService); - assertNotNull("SessionFactory should have been autowired.", sessionFactory); + assertThat(personService).as("PersonService should have been autowired.").isNotNull(); + assertThat(sessionFactory).as("SessionFactory should have been autowired.").isNotNull(); } @Test public void findSam() { Person sam = personService.findByName(SAM); - assertNotNull("Should be able to find Sam", sam); + assertThat(sam).as("Should be able to find Sam").isNotNull(); DriversLicense driversLicense = sam.getDriversLicense(); - assertNotNull("Sam's driver's license should not be null", driversLicense); - assertEquals("Verifying Sam's driver's license number", Long.valueOf(1234), driversLicense.getNumber()); + assertThat(driversLicense).as("Sam's driver's license should not be null").isNotNull(); + assertThat(driversLicense.getNumber()).as("Verifying Sam's driver's license number").isEqualTo(Long.valueOf(1234)); } @Test // SPR-16956 @@ -85,7 +84,7 @@ public class HibernateSessionFlushingTests extends AbstractTransactionalJUnit4Sp Session session = sessionFactory.getCurrentSession(); session.flush(); session.refresh(sam); - assertEquals("Sam", sam.getName()); + assertThat(sam.getName()).isEqualTo("Sam"); } @Test @@ -94,9 +93,9 @@ public class HibernateSessionFlushingTests extends AbstractTransactionalJUnit4Sp Person juergen = new Person(JUERGEN, driversLicense); int numRows = countRowsInTable("person"); personService.save(juergen); - assertEquals("Verifying number of rows in the 'person' table.", numRows + 1, countRowsInTable("person")); - assertNotNull("Should be able to save and retrieve Juergen", personService.findByName(JUERGEN)); - assertNotNull("Juergen's ID should have been set", juergen.getId()); + assertThat(countRowsInTable("person")).as("Verifying number of rows in the 'person' table.").isEqualTo((numRows + 1)); + assertThat(personService.findByName(JUERGEN)).as("Should be able to save and retrieve Juergen").isNotNull(); + assertThat(juergen.getId()).as("Juergen's ID should have been set").isNotNull(); } @Test @@ -130,7 +129,7 @@ public class HibernateSessionFlushingTests extends AbstractTransactionalJUnit4Sp private void updateSamWithNullDriversLicense() { Person sam = personService.findByName(SAM); - assertNotNull("Should be able to find Sam", sam); + assertThat(sam).as("Should be able to find Sam").isNotNull(); sam.setDriversLicense(null); personService.save(sam); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileAnnotationConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileAnnotationConfigTests.java index a49906c75b4..e9696e7b921 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileAnnotationConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileAnnotationConfigTests.java @@ -26,9 +26,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -47,13 +45,13 @@ public class DefaultProfileAnnotationConfigTests { @Test public void pet() { - assertNotNull(pet); - assertEquals("Fido", pet.getName()); + assertThat(pet).isNotNull(); + assertThat(pet.getName()).isEqualTo("Fido"); } @Test public void employee() { - assertNull("employee bean should not be created for the default profile", employee); + assertThat(employee).as("employee bean should not be created for the default profile").isNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DevProfileAnnotationConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DevProfileAnnotationConfigTests.java index b4326ff2a5a..36aa83b1147 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DevProfileAnnotationConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DevProfileAnnotationConfigTests.java @@ -20,8 +20,7 @@ import org.junit.Test; import org.springframework.test.context.ActiveProfiles; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -33,8 +32,8 @@ public class DevProfileAnnotationConfigTests extends DefaultProfileAnnotationCon @Test @Override public void employee() { - assertNotNull("employee bean should be loaded for the 'dev' profile", employee); - assertEquals("John Smith", employee.getName()); + assertThat(employee).as("employee bean should be loaded for the 'dev' profile").isNotNull(); + assertThat(employee.getName()).isEqualTo("John Smith"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileAnnotationConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileAnnotationConfigTests.java index 0785c084b39..9260774a976 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileAnnotationConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileAnnotationConfigTests.java @@ -25,9 +25,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -46,13 +44,13 @@ public class DefaultProfileAnnotationConfigTests { @Test public void pet() { - assertNotNull(pet); - assertEquals("Fido", pet.getName()); + assertThat(pet).isNotNull(); + assertThat(pet.getName()).isEqualTo("Fido"); } @Test public void employee() { - assertNull("employee bean should not be created for the default profile", employee); + assertThat(employee).as("employee bean should not be created for the default profile").isNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DevProfileAnnotationConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DevProfileAnnotationConfigTests.java index 490b3ff6e13..0eb24078af1 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DevProfileAnnotationConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DevProfileAnnotationConfigTests.java @@ -20,8 +20,7 @@ import org.junit.Test; import org.springframework.test.context.ActiveProfiles; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -33,8 +32,8 @@ public class DevProfileAnnotationConfigTests extends DefaultProfileAnnotationCon @Test @Override public void employee() { - assertNotNull("employee bean should be loaded for the 'dev' profile", employee); - assertEquals("John Smith", employee.getName()); + assertThat(employee).as("employee bean should be loaded for the 'dev' profile").isNotNull(); + assertThat(employee.getName()).isEqualTo("John Smith"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/resolver/ClassNameActiveProfilesResolverTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/resolver/ClassNameActiveProfilesResolverTests.java index 61777045e1a..6c71af3fbdf 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/resolver/ClassNameActiveProfilesResolverTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/resolver/ClassNameActiveProfilesResolverTests.java @@ -28,7 +28,7 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Michail Nikolaev @@ -51,8 +51,8 @@ public class ClassNameActiveProfilesResolverTests { @Test public void test() { - assertTrue(Arrays.asList(applicationContext.getEnvironment().getActiveProfiles()).contains( - getClass().getSimpleName().toLowerCase())); + assertThat(Arrays.asList(applicationContext.getEnvironment().getActiveProfiles()).contains( + getClass().getSimpleName().toLowerCase())).isTrue(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests.java index 6fc9fe1e961..2e4bde73603 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests.java @@ -25,9 +25,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -46,13 +44,13 @@ public class DefaultProfileXmlConfigTests { @Test public void pet() { - assertNotNull(pet); - assertEquals("Fido", pet.getName()); + assertThat(pet).isNotNull(); + assertThat(pet.getName()).isEqualTo("Fido"); } @Test public void employee() { - assertNull("employee bean should not be created for the default profile", employee); + assertThat(employee).as("employee bean should not be created for the default profile").isNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DevProfileXmlConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DevProfileXmlConfigTests.java index df4b9d2d938..b79ef637ed5 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DevProfileXmlConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DevProfileXmlConfigTests.java @@ -20,8 +20,7 @@ import org.junit.Test; import org.springframework.test.context.ActiveProfiles; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -33,8 +32,8 @@ public class DevProfileXmlConfigTests extends DefaultProfileXmlConfigTests { @Test @Override public void employee() { - assertNotNull("employee bean should be loaded for the 'dev' profile", employee); - assertEquals("John Smith", employee.getName()); + assertThat(employee).as("employee bean should be loaded for the 'dev' profile").isNotNull(); + assertThat(employee.getName()).isEqualTo("John Smith"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/AutowiredRuleTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/AutowiredRuleTests.java index 23c0a96e852..654fed92f62 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/AutowiredRuleTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/AutowiredRuleTests.java @@ -27,8 +27,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for an issue raised in https://jira.spring.io/browse/SPR-15927. @@ -50,7 +49,7 @@ public class AutowiredRuleTests { @Test public void test() { - assertNotNull("TestRule should have been @Autowired", autowiredTestRule); + assertThat(autowiredTestRule).as("TestRule should have been @Autowired").isNotNull(); // Rationale for the following assertion: // @@ -58,7 +57,7 @@ public class AutowiredRuleTests { // ignores the null value, and at a later point in time Spring injects the rule // from the ApplicationContext and overrides the null field value. But that's too // late: JUnit never sees the rule supplied by Spring via dependency injection. - assertFalse("@Autowired TestRule should NOT have been applied", autowiredTestRule.applied); + assertThat(autowiredTestRule.applied).as("@Autowired TestRule should NOT have been applied").isFalse(); } @Configuration diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/BaseAppCtxRuleTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/BaseAppCtxRuleTests.java index 2295d4356f1..2c7fad66218 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/BaseAppCtxRuleTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/BaseAppCtxRuleTests.java @@ -25,7 +25,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Base class for integration tests involving Spring {@code ApplicationContexts} @@ -55,7 +55,7 @@ public class BaseAppCtxRuleTests { @Test public void foo() { - assertEquals("foo", foo); + assertThat(foo).isEqualTo("foo"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/FailingBeforeAndAfterMethodsSpringRuleTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/FailingBeforeAndAfterMethodsSpringRuleTests.java index 9b8025ccd21..fe12ee7756f 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/FailingBeforeAndAfterMethodsSpringRuleTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/FailingBeforeAndAfterMethodsSpringRuleTests.java @@ -32,7 +32,7 @@ import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; /** * This class is an extension of {@link FailingBeforeAndAfterMethodsSpringRunnerTests} diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/ParameterizedSpringRuleTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/ParameterizedSpringRuleTests.java index 7196eae14ac..1a361193f19 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/ParameterizedSpringRuleTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/ParameterizedSpringRuleTests.java @@ -34,8 +34,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.tests.sample.beans.Employee; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration test which demonstrates how to use JUnit's {@link Parameterized} @@ -86,18 +85,16 @@ public class ParameterizedSpringRuleTests { invocationCount.incrementAndGet(); // Verifying dependency injection: - assertNotNull("The pet field should have been autowired.", this.pet); + assertThat(this.pet).as("The pet field should have been autowired.").isNotNull(); // Verifying 'parameterized' support: Employee employee = this.applicationContext.getBean(this.employeeBeanName, Employee.class); - assertEquals("Name of the employee configured as bean [" + this.employeeBeanName + "].", this.employeeName, - employee.getName()); + assertThat(employee.getName()).as("Name of the employee configured as bean [" + this.employeeBeanName + "].").isEqualTo(this.employeeName); } @AfterClass public static void verifyNumParameterizedRuns() { - assertEquals("Number of times the parameterized test method was executed.", employeeData().length, - invocationCount.get()); + assertThat(invocationCount.get()).as("Number of times the parameterized test method was executed.").isEqualTo(employeeData().length); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/Subclass1AppCtxRuleTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/Subclass1AppCtxRuleTests.java index c0b17da4390..148e0471af0 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/Subclass1AppCtxRuleTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/Subclass1AppCtxRuleTests.java @@ -23,7 +23,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Subclass #1 of {@link BaseAppCtxRuleTests}. @@ -40,7 +40,7 @@ public class Subclass1AppCtxRuleTests extends BaseAppCtxRuleTests { @Test public void bar() { - assertEquals("bar", bar); + assertThat(bar).isEqualTo("bar"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/Subclass2AppCtxRuleTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/Subclass2AppCtxRuleTests.java index 923139d085f..24bbb138993 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/Subclass2AppCtxRuleTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/Subclass2AppCtxRuleTests.java @@ -23,7 +23,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Subclass #2 of {@link BaseAppCtxRuleTests}. @@ -40,7 +40,7 @@ public class Subclass2AppCtxRuleTests extends BaseAppCtxRuleTests { @Test public void baz() { - assertEquals("baz", baz); + assertThat(baz).isEqualTo("baz"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/TimedSpringRuleTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/TimedSpringRuleTests.java index 9fc6a73db4e..68b29e8d830 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/rules/TimedSpringRuleTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/rules/TimedSpringRuleTests.java @@ -25,7 +25,7 @@ import org.junit.runners.JUnit4; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.TimedSpringRunnerTests; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; /** * This class is an extension of {@link TimedSpringRunnerTests} diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingDefaultLocationsInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingDefaultLocationsInheritedTests.java index f9114b5fb0f..f33a0c4fcbc 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingDefaultLocationsInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingDefaultLocationsInheritedTests.java @@ -20,8 +20,7 @@ import org.junit.Test; import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit 4 based integration test for verifying support for the @@ -39,7 +38,7 @@ public class BeanOverridingDefaultLocationsInheritedTests extends DefaultLocatio @Test @Override public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee should have been autowired.", this.employee); - assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName()); + assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).as("The employee bean should have been overridden.").isEqualTo("Yoda"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingExplicitLocationsInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingExplicitLocationsInheritedTests.java index 4744ba66372..99b9bb881ff 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingExplicitLocationsInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingExplicitLocationsInheritedTests.java @@ -20,8 +20,7 @@ import org.junit.Test; import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit 4 based integration test for verifying support for the @@ -39,7 +38,7 @@ public class BeanOverridingExplicitLocationsInheritedTests extends ExplicitLocat @Test @Override public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee should have been autowired.", this.employee); - assertEquals("The employee bean should have been overridden.", "Yoda", this.employee.getName()); + assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).as("The employee bean should have been overridden.").isEqualTo("Yoda"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests.java index fb444de7c4f..bb7d1830fb5 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests.java @@ -24,8 +24,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.tests.sample.beans.Employee; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit 4 based integration test for verifying support for the @@ -47,7 +46,7 @@ public class DefaultLocationsBaseTests { @Test public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee should have been autowired.", this.employee); - assertEquals("John Smith", this.employee.getName()); + assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("John Smith"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests.java index 43287dcdae4..8152d1c52a5 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests.java @@ -22,8 +22,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit 4 based integration test for verifying support for the @@ -44,7 +43,7 @@ public class DefaultLocationsInheritedTests extends DefaultLocationsBaseTests { @Test public void verifyPetSetFromExtendedContextConfig() { - assertNotNull("The pet should have been autowired.", this.pet); - assertEquals("Fido", this.pet.getName()); + assertThat(this.pet).as("The pet should have been autowired.").isNotNull(); + assertThat(this.pet.getName()).isEqualTo("Fido"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsBaseTests.java index 9d4a9562d76..3d3e8cc20a5 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsBaseTests.java @@ -24,8 +24,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.tests.sample.beans.Employee; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit 4 based integration test for verifying support for the @@ -47,7 +46,7 @@ public class ExplicitLocationsBaseTests { @Test public void verifyEmployeeSetFromBaseContextConfig() { - assertNotNull("The employee should have been autowired.", this.employee); - assertEquals("John Smith", this.employee.getName()); + assertThat(this.employee).as("The employee should have been autowired.").isNotNull(); + assertThat(this.employee.getName()).isEqualTo("John Smith"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsInheritedTests.java index 04c87bed932..bcef27f2c88 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsInheritedTests.java @@ -22,8 +22,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.tests.sample.beans.Pet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit 4 based integration test for verifying support for the @@ -44,7 +43,7 @@ public class ExplicitLocationsInheritedTests extends ExplicitLocationsBaseTests @Test public void verifyPetSetFromExtendedContextConfig() { - assertNotNull("The pet should have been autowired.", this.pet); - assertEquals("Fido", this.pet.getName()); + assertThat(this.pet).as("The pet should have been autowired.").isNotNull(); + assertThat(this.pet.getName()).isEqualTo("Fido"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr4868/Jsr250LifecycleTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr4868/Jsr250LifecycleTests.java index af3c16c5120..11e4d9e8696 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr4868/Jsr250LifecycleTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr4868/Jsr250LifecycleTests.java @@ -34,7 +34,7 @@ import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that investigate the applicability of JSR-250 lifecycle @@ -107,13 +107,13 @@ public class Jsr250LifecycleTests { @Test public void test1() { logger.info("test1()"); - assertNotNull(lifecycleBean); + assertThat(lifecycleBean).isNotNull(); } @Test public void test2() { logger.info("test2()"); - assertNotNull(lifecycleBean); + assertThat(lifecycleBean).isNotNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass1.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass1.java index 073e7183f8f..4726b44119b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass1.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass1.java @@ -27,7 +27,7 @@ import org.springframework.context.annotation.ImportResource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * This name of this class intentionally does not end with "Test" or "Tests" @@ -54,7 +54,7 @@ public class TestClass1 { @Test public void dummyTest() { - assertNotNull(dataSource); + assertThat(dataSource).isNotNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass2.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass2.java index b99ad031c30..2b0c99398d5 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass2.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass2.java @@ -27,7 +27,7 @@ import org.springframework.context.annotation.ImportResource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * This name of this class intentionally does not end with "Test" or "Tests" @@ -54,7 +54,7 @@ public class TestClass2 { @Test public void dummyTest() { - assertNotNull(dataSource); + assertThat(dataSource).isNotNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass3.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass3.java index ca7e5e4e9e9..953ee8e471d 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass3.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass3.java @@ -27,7 +27,7 @@ import org.springframework.context.annotation.ImportResource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * This name of this class intentionally does not end with "Test" or "Tests" @@ -53,7 +53,7 @@ public class TestClass3 { @Test public void dummyTest() { - assertNotNull(dataSource); + assertThat(dataSource).isNotNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass4.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass4.java index 9fb2c5aa5b4..4f4f76f4bb7 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass4.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/TestClass4.java @@ -27,7 +27,7 @@ import org.springframework.context.annotation.ImportResource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * This name of this class intentionally does not end with "Test" or "Tests" @@ -53,7 +53,7 @@ public class TestClass4 { @Test public void dummyTest() { - assertNotNull(dataSource); + assertThat(dataSource).isNotNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java index d49ae5e8ca8..5726f882b71 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java @@ -34,8 +34,7 @@ import org.springframework.test.context.transaction.BeforeTransaction; import org.springframework.tests.sample.beans.Employee; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; import static org.springframework.test.transaction.TransactionTestUtils.inTransaction; @@ -89,18 +88,17 @@ public abstract class AbstractTransactionalAnnotatedConfigClassTests { } protected void assertNumRowsInPersonTable(int expectedNumRows, String testState) { - assertEquals("the number of rows in the person table (" + testState + ").", expectedNumRows, - countRowsInTable("person")); + assertThat(countRowsInTable("person")).as("the number of rows in the person table (" + testState + ").").isEqualTo(expectedNumRows); } protected void assertAddPerson(final String name) { - assertEquals("Adding '" + name + "'", 1, createPerson(name)); + assertThat(createPerson(name)).as("Adding '" + name + "'").isEqualTo(1); } @Test public void autowiringFromConfigClass() { - assertNotNull("The employee should have been autowired.", employee); - assertEquals("John Smith", employee.getName()); + assertThat(employee).as("The employee should have been autowired.").isNotNull(); + assertThat(employee.getName()).isEqualTo("John Smith"); } @BeforeTransaction @@ -130,7 +128,7 @@ public abstract class AbstractTransactionalAnnotatedConfigClassTests { @AfterTransaction public void afterTransaction() { - assertEquals("Deleting yoda", 1, deletePerson(YODA)); + assertThat(deletePerson(YODA)).as("Deleting yoda").isEqualTo(1); assertNumRowsInPersonTable(0, "after a transactional test method"); } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AnnotatedConfigClassesWithoutAtConfigurationTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AnnotatedConfigClassesWithoutAtConfigurationTests.java index e419dbabd2f..8420cfd5bcb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AnnotatedConfigClassesWithoutAtConfigurationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AnnotatedConfigClassesWithoutAtConfigurationTests.java @@ -29,10 +29,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * This set of tests refutes the claims made in @@ -78,7 +75,7 @@ public class AnnotatedConfigClassesWithoutAtConfigurationTests { // enigma() method, not a CGLIB proxied version, since these methods // are essentially factory bean methods. LifecycleBean bean = new LifecycleBean(enigma()); - assertFalse(bean.isInitialized()); + assertThat(bean.isInitialized()).isFalse(); return bean; } } @@ -93,12 +90,12 @@ public class AnnotatedConfigClassesWithoutAtConfigurationTests { @Test public void testSPR_9051() throws Exception { - assertNotNull(enigma); - assertNotNull(lifecycleBean); - assertTrue(lifecycleBean.isInitialized()); + assertThat(enigma).isNotNull(); + assertThat(lifecycleBean).isNotNull(); + assertThat(lifecycleBean.isInitialized()).isTrue(); Set names = new HashSet<>(); names.add(enigma.toString()); names.add(lifecycleBean.getName()); - assertEquals(names, new HashSet<>(Arrays.asList("enigma #1", "enigma #2"))); + assertThat(new HashSet<>(Arrays.asList("enigma #1", "enigma #2"))).isEqualTo(names); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AtBeanLiteModeScopeTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AtBeanLiteModeScopeTests.java index 90c961b1e4c..811ae9d0700 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AtBeanLiteModeScopeTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AtBeanLiteModeScopeTests.java @@ -27,11 +27,7 @@ import org.springframework.context.annotation.Scope; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify proper scoping of beans created in @@ -52,7 +48,7 @@ public class AtBeanLiteModeScopeTests { @Bean public LifecycleBean singleton() { LifecycleBean bean = new LifecycleBean("singleton"); - assertFalse(bean.isInitialized()); + assertThat(bean.isInitialized()).isFalse(); return bean; } @@ -60,7 +56,7 @@ public class AtBeanLiteModeScopeTests { @Scope("prototype") public LifecycleBean prototype() { LifecycleBean bean = new LifecycleBean("prototype"); - assertFalse(bean.isInitialized()); + assertThat(bean.isInitialized()).isFalse(); return bean; } } @@ -80,26 +76,26 @@ public class AtBeanLiteModeScopeTests { @Test public void singletonLiteBean() { - assertNotNull(injectedSingletonBean); - assertTrue(injectedSingletonBean.isInitialized()); + assertThat(injectedSingletonBean).isNotNull(); + assertThat(injectedSingletonBean.isInitialized()).isTrue(); LifecycleBean retrievedSingletonBean = applicationContext.getBean("singleton", LifecycleBean.class); - assertNotNull(retrievedSingletonBean); - assertTrue(retrievedSingletonBean.isInitialized()); + assertThat(retrievedSingletonBean).isNotNull(); + assertThat(retrievedSingletonBean.isInitialized()).isTrue(); - assertSame(injectedSingletonBean, retrievedSingletonBean); + assertThat(retrievedSingletonBean).isSameAs(injectedSingletonBean); } @Test public void prototypeLiteBean() { - assertNotNull(injectedPrototypeBean); - assertTrue(injectedPrototypeBean.isInitialized()); + assertThat(injectedPrototypeBean).isNotNull(); + assertThat(injectedPrototypeBean.isInitialized()).isTrue(); LifecycleBean retrievedPrototypeBean = applicationContext.getBean("prototype", LifecycleBean.class); - assertNotNull(retrievedPrototypeBean); - assertTrue(retrievedPrototypeBean.isInitialized()); + assertThat(retrievedPrototypeBean).isNotNull(); + assertThat(retrievedPrototypeBean.isInitialized()).isTrue(); - assertNotSame(injectedPrototypeBean, retrievedPrototypeBean); + assertThat(retrievedPrototypeBean).isNotSameAs(injectedPrototypeBean); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassWithAtConfigurationTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassWithAtConfigurationTests.java index e9903aa5148..6ed5f85359e 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassWithAtConfigurationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassWithAtConfigurationTests.java @@ -28,7 +28,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.tests.sample.beans.Employee; import org.springframework.transaction.PlatformTransactionManager; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Concrete implementation of {@link AbstractTransactionalAnnotatedConfigClassTests} @@ -80,7 +80,7 @@ public class TransactionalAnnotatedConfigClassWithAtConfigurationTests extends @Before public void compareDataSources() throws Exception { // NOTE: the two DataSource instances ARE the same! - assertSame(dataSourceFromTxManager, dataSourceViaInjection); + assertThat(dataSourceViaInjection).isSameAs(dataSourceFromTxManager); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassesWithoutAtConfigurationTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassesWithoutAtConfigurationTests.java index b950d53f751..2b6b6d575b2 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassesWithoutAtConfigurationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassesWithoutAtConfigurationTests.java @@ -31,8 +31,7 @@ import org.springframework.test.context.transaction.TransactionalTestExecutionLi import org.springframework.tests.sample.beans.Employee; import org.springframework.transaction.PlatformTransactionManager; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Concrete implementation of {@link AbstractTransactionalAnnotatedConfigClassTests} @@ -107,7 +106,7 @@ public class TransactionalAnnotatedConfigClassesWithoutAtConfigurationTests exte @Before public void compareDataSources() throws Exception { // NOTE: the two DataSource instances are NOT the same! - assertNotSame(dataSourceFromTxManager, dataSourceViaInjection); + assertThat(dataSourceViaInjection).isNotSameAs(dataSourceFromTxManager); } /** @@ -121,7 +120,7 @@ public class TransactionalAnnotatedConfigClassesWithoutAtConfigurationTests exte @AfterTransaction @Override public void afterTransaction() { - assertEquals("Deleting yoda", 1, deletePerson(YODA)); + assertThat(deletePerson(YODA)).as("Deleting yoda").isEqualTo(1); // NOTE: We would actually expect that there are now ZERO entries in the // person table, since the transaction is rolled back by the framework; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9604/LookUpTxMgrViaTransactionManagementConfigurerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9604/LookUpTxMgrViaTransactionManagementConfigurerTests.java index ef16aac637b..732275e3842 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9604/LookUpTxMgrViaTransactionManagementConfigurerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9604/LookUpTxMgrViaTransactionManagementConfigurerTests.java @@ -30,7 +30,7 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.TransactionManagementConfigurer; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify the behavior requested in @@ -76,28 +76,28 @@ public class LookUpTxMgrViaTransactionManagementConfigurerTests { @Test public void transactionalTest() { - assertEquals(1, txManager1.begun); - assertEquals(1, txManager1.inflight); - assertEquals(0, txManager1.commits); - assertEquals(0, txManager1.rollbacks); + assertThat(txManager1.begun).isEqualTo(1); + assertThat(txManager1.inflight).isEqualTo(1); + assertThat(txManager1.commits).isEqualTo(0); + assertThat(txManager1.rollbacks).isEqualTo(0); - assertEquals(0, txManager2.begun); - assertEquals(0, txManager2.inflight); - assertEquals(0, txManager2.commits); - assertEquals(0, txManager2.rollbacks); + assertThat(txManager2.begun).isEqualTo(0); + assertThat(txManager2.inflight).isEqualTo(0); + assertThat(txManager2.commits).isEqualTo(0); + assertThat(txManager2.rollbacks).isEqualTo(0); } @AfterTransaction public void afterTransaction() { - assertEquals(1, txManager1.begun); - assertEquals(0, txManager1.inflight); - assertEquals(0, txManager1.commits); - assertEquals(1, txManager1.rollbacks); + assertThat(txManager1.begun).isEqualTo(1); + assertThat(txManager1.inflight).isEqualTo(0); + assertThat(txManager1.commits).isEqualTo(0); + assertThat(txManager1.rollbacks).isEqualTo(1); - assertEquals(0, txManager2.begun); - assertEquals(0, txManager2.inflight); - assertEquals(0, txManager2.commits); - assertEquals(0, txManager2.rollbacks); + assertThat(txManager2.begun).isEqualTo(0); + assertThat(txManager2.inflight).isEqualTo(0); + assertThat(txManager2.commits).isEqualTo(0); + assertThat(txManager2.rollbacks).isEqualTo(0); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpNonexistentTxMgrTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpNonexistentTxMgrTests.java index 7e9372a7fb8..e32f9117b28 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpNonexistentTxMgrTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpNonexistentTxMgrTests.java @@ -26,7 +26,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify the behavior requested in @@ -52,9 +52,9 @@ public class LookUpNonexistentTxMgrTests { @Test public void nonTransactionalTest() { - assertEquals(0, txManager.begun); - assertEquals(0, txManager.inflight); - assertEquals(0, txManager.commits); - assertEquals(0, txManager.rollbacks); + assertThat(txManager.begun).isEqualTo(0); + assertThat(txManager.inflight).isEqualTo(0); + assertThat(txManager.commits).isEqualTo(0); + assertThat(txManager.rollbacks).isEqualTo(0); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndDefaultNameTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndDefaultNameTests.java index 1907a33b07c..a832dd62157 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndDefaultNameTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndDefaultNameTests.java @@ -29,7 +29,7 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify the behavior requested in @@ -68,18 +68,18 @@ public class LookUpTxMgrByTypeAndDefaultNameTests { @Test public void transactionalTest() { - assertEquals(1, txManager1.begun); - assertEquals(1, txManager1.inflight); - assertEquals(0, txManager1.commits); - assertEquals(0, txManager1.rollbacks); + assertThat(txManager1.begun).isEqualTo(1); + assertThat(txManager1.inflight).isEqualTo(1); + assertThat(txManager1.commits).isEqualTo(0); + assertThat(txManager1.rollbacks).isEqualTo(0); } @AfterTransaction public void afterTransaction() { - assertEquals(1, txManager1.begun); - assertEquals(0, txManager1.inflight); - assertEquals(0, txManager1.commits); - assertEquals(1, txManager1.rollbacks); + assertThat(txManager1.begun).isEqualTo(1); + assertThat(txManager1.inflight).isEqualTo(0); + assertThat(txManager1.commits).isEqualTo(0); + assertThat(txManager1.rollbacks).isEqualTo(1); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndNameTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndNameTests.java index 4fc54b4cd89..544158a6710 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndNameTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndNameTests.java @@ -29,7 +29,7 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify the behavior requested in @@ -68,18 +68,18 @@ public class LookUpTxMgrByTypeAndNameTests { @Test public void transactionalTest() { - assertEquals(1, txManager1.begun); - assertEquals(1, txManager1.inflight); - assertEquals(0, txManager1.commits); - assertEquals(0, txManager1.rollbacks); + assertThat(txManager1.begun).isEqualTo(1); + assertThat(txManager1.inflight).isEqualTo(1); + assertThat(txManager1.commits).isEqualTo(0); + assertThat(txManager1.rollbacks).isEqualTo(0); } @AfterTransaction public void afterTransaction() { - assertEquals(1, txManager1.begun); - assertEquals(0, txManager1.inflight); - assertEquals(0, txManager1.commits); - assertEquals(1, txManager1.rollbacks); + assertThat(txManager1.begun).isEqualTo(1); + assertThat(txManager1.inflight).isEqualTo(0); + assertThat(txManager1.commits).isEqualTo(0); + assertThat(txManager1.rollbacks).isEqualTo(1); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtClassLevelTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtClassLevelTests.java index f6be9bf7f71..5823fc4f188 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtClassLevelTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtClassLevelTests.java @@ -29,7 +29,7 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify the behavior requested in @@ -68,18 +68,18 @@ public class LookUpTxMgrByTypeAndQualifierAtClassLevelTests { @Test public void transactionalTest() { - assertEquals(1, txManager1.begun); - assertEquals(1, txManager1.inflight); - assertEquals(0, txManager1.commits); - assertEquals(0, txManager1.rollbacks); + assertThat(txManager1.begun).isEqualTo(1); + assertThat(txManager1.inflight).isEqualTo(1); + assertThat(txManager1.commits).isEqualTo(0); + assertThat(txManager1.rollbacks).isEqualTo(0); } @AfterTransaction public void afterTransaction() { - assertEquals(1, txManager1.begun); - assertEquals(0, txManager1.inflight); - assertEquals(0, txManager1.commits); - assertEquals(1, txManager1.rollbacks); + assertThat(txManager1.begun).isEqualTo(1); + assertThat(txManager1.inflight).isEqualTo(0); + assertThat(txManager1.commits).isEqualTo(0); + assertThat(txManager1.rollbacks).isEqualTo(1); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtMethodLevelTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtMethodLevelTests.java index 3e81e0906b2..9c576c82463 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtMethodLevelTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtMethodLevelTests.java @@ -29,7 +29,7 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify the behavior requested in @@ -68,18 +68,18 @@ public class LookUpTxMgrByTypeAndQualifierAtMethodLevelTests { @Transactional("txManager1") @Test public void transactionalTest() { - assertEquals(1, txManager1.begun); - assertEquals(1, txManager1.inflight); - assertEquals(0, txManager1.commits); - assertEquals(0, txManager1.rollbacks); + assertThat(txManager1.begun).isEqualTo(1); + assertThat(txManager1.inflight).isEqualTo(1); + assertThat(txManager1.commits).isEqualTo(0); + assertThat(txManager1.rollbacks).isEqualTo(0); } @AfterTransaction public void afterTransaction() { - assertEquals(1, txManager1.begun); - assertEquals(0, txManager1.inflight); - assertEquals(0, txManager1.commits); - assertEquals(1, txManager1.rollbacks); + assertThat(txManager1.begun).isEqualTo(1); + assertThat(txManager1.inflight).isEqualTo(0); + assertThat(txManager1.commits).isEqualTo(0); + assertThat(txManager1.rollbacks).isEqualTo(1); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeTests.java index 8b0f4b2a3b4..ebbab9f6103 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeTests.java @@ -29,7 +29,7 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify the behavior requested in @@ -61,18 +61,18 @@ public class LookUpTxMgrByTypeTests { @Test public void transactionalTest() { - assertEquals(1, txManager.begun); - assertEquals(1, txManager.inflight); - assertEquals(0, txManager.commits); - assertEquals(0, txManager.rollbacks); + assertThat(txManager.begun).isEqualTo(1); + assertThat(txManager.inflight).isEqualTo(1); + assertThat(txManager.commits).isEqualTo(0); + assertThat(txManager.rollbacks).isEqualTo(0); } @AfterTransaction public void afterTransaction() { - assertEquals(1, txManager.begun); - assertEquals(0, txManager.inflight); - assertEquals(0, txManager.commits); - assertEquals(1, txManager.rollbacks); + assertThat(txManager.begun).isEqualTo(1); + assertThat(txManager.inflight).isEqualTo(0); + assertThat(txManager.commits).isEqualTo(0); + assertThat(txManager.rollbacks).isEqualTo(1); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/support/AbstractContextConfigurationUtilsTests.java b/spring-test/src/test/java/org/springframework/test/context/support/AbstractContextConfigurationUtilsTests.java index 51b9bf0562c..27f00f35114 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/AbstractContextConfigurationUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/AbstractContextConfigurationUtilsTests.java @@ -38,10 +38,7 @@ import org.springframework.test.context.MergedContextConfiguration; import org.springframework.test.context.TestContextBootstrapper; import org.springframework.test.context.web.WebAppConfiguration; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Abstract base class for tests involving {@link ContextLoaderUtils}, @@ -71,11 +68,11 @@ abstract class AbstractContextConfigurationUtilsTests { String[] expectedLocations, Class[] expectedClasses, Class expectedContextLoaderClass, boolean expectedInheritLocations) { - assertEquals("declaring class", expectedDeclaringClass, attributes.getDeclaringClass()); - assertArrayEquals("locations", expectedLocations, attributes.getLocations()); - assertArrayEquals("classes", expectedClasses, attributes.getClasses()); - assertEquals("inherit locations", expectedInheritLocations, attributes.isInheritLocations()); - assertEquals("context loader", expectedContextLoaderClass, attributes.getContextLoaderClass()); + assertThat(attributes.getDeclaringClass()).as("declaring class").isEqualTo(expectedDeclaringClass); + assertThat(attributes.getLocations()).as("locations").isEqualTo(expectedLocations); + assertThat(attributes.getClasses()).as("classes").isEqualTo(expectedClasses); + assertThat(attributes.isInheritLocations()).as("inherit locations").isEqualTo(expectedInheritLocations); + assertThat(attributes.getContextLoaderClass()).as("context loader").isEqualTo(expectedContextLoaderClass); } void assertMergedConfig(MergedContextConfiguration mergedConfig, Class expectedTestClass, @@ -94,21 +91,21 @@ abstract class AbstractContextConfigurationUtilsTests { Set>> expectedInitializerClasses, Class expectedContextLoaderClass) { - assertNotNull(mergedConfig); - assertEquals(expectedTestClass, mergedConfig.getTestClass()); - assertNotNull(mergedConfig.getLocations()); - assertArrayEquals(expectedLocations, mergedConfig.getLocations()); - assertNotNull(mergedConfig.getClasses()); - assertArrayEquals(expectedClasses, mergedConfig.getClasses()); - assertNotNull(mergedConfig.getActiveProfiles()); + assertThat(mergedConfig).isNotNull(); + assertThat(mergedConfig.getTestClass()).isEqualTo(expectedTestClass); + assertThat(mergedConfig.getLocations()).isNotNull(); + assertThat(mergedConfig.getLocations()).isEqualTo(expectedLocations); + assertThat(mergedConfig.getClasses()).isNotNull(); + assertThat(mergedConfig.getClasses()).isEqualTo(expectedClasses); + assertThat(mergedConfig.getActiveProfiles()).isNotNull(); if (expectedContextLoaderClass == null) { - assertNull(mergedConfig.getContextLoader()); + assertThat(mergedConfig.getContextLoader()).isNull(); } else { - assertEquals(expectedContextLoaderClass, mergedConfig.getContextLoader().getClass()); + assertThat(mergedConfig.getContextLoader().getClass()).isEqualTo(expectedContextLoaderClass); } - assertNotNull(mergedConfig.getContextInitializerClasses()); - assertEquals(expectedInitializerClasses, mergedConfig.getContextInitializerClasses()); + assertThat(mergedConfig.getContextInitializerClasses()).isNotNull(); + assertThat(mergedConfig.getContextInitializerClasses()).isEqualTo(expectedInitializerClasses); } @SafeVarargs diff --git a/spring-test/src/test/java/org/springframework/test/context/support/ActiveProfilesUtilsTests.java b/spring-test/src/test/java/org/springframework/test/context/support/ActiveProfilesUtilsTests.java index 8f85911bed1..24440187170 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/ActiveProfilesUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/ActiveProfilesUtilsTests.java @@ -31,9 +31,9 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfilesResolver; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertArrayEquals; import static org.springframework.test.context.support.ActiveProfilesUtils.resolveActiveProfiles; /** @@ -47,7 +47,7 @@ import static org.springframework.test.context.support.ActiveProfilesUtils.resol public class ActiveProfilesUtilsTests extends AbstractContextConfigurationUtilsTests { private void assertResolvedProfiles(Class testClass, String... expected) { - assertArrayEquals(expected, resolveActiveProfiles(testClass)); + assertThat(resolveActiveProfiles(testClass)).isEqualTo(expected); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderTests.java b/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderTests.java index ece4954c0ef..3aa9a4b2dd9 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderTests.java @@ -20,9 +20,8 @@ import org.junit.Test; import org.springframework.test.context.MergedContextConfiguration; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Unit tests for {@link AnnotationConfigContextLoader}. @@ -53,47 +52,47 @@ public class AnnotationConfigContextLoaderTests { @Test public void detectDefaultConfigurationClassesForAnnotatedInnerClass() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(ContextConfigurationInnerClassTestCase.class); - assertNotNull(configClasses); - assertEquals("annotated static ContextConfiguration should be considered.", 1, configClasses.length); + assertThat(configClasses).isNotNull(); + assertThat(configClasses.length).as("annotated static ContextConfiguration should be considered.").isEqualTo(1); configClasses = contextLoader.detectDefaultConfigurationClasses(AnnotatedFooConfigInnerClassTestCase.class); - assertNotNull(configClasses); - assertEquals("annotated static FooConfig should be considered.", 1, configClasses.length); + assertThat(configClasses).isNotNull(); + assertThat(configClasses.length).as("annotated static FooConfig should be considered.").isEqualTo(1); } @Test public void detectDefaultConfigurationClassesForMultipleAnnotatedInnerClasses() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(MultipleStaticConfigurationClassesTestCase.class); - assertNotNull(configClasses); - assertEquals("multiple annotated static classes should be considered.", 2, configClasses.length); + assertThat(configClasses).isNotNull(); + assertThat(configClasses.length).as("multiple annotated static classes should be considered.").isEqualTo(2); } @Test public void detectDefaultConfigurationClassesForNonAnnotatedInnerClass() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(PlainVanillaFooConfigInnerClassTestCase.class); - assertNotNull(configClasses); - assertEquals("non-annotated static FooConfig should NOT be considered.", 0, configClasses.length); + assertThat(configClasses).isNotNull(); + assertThat(configClasses.length).as("non-annotated static FooConfig should NOT be considered.").isEqualTo(0); } @Test public void detectDefaultConfigurationClassesForFinalAnnotatedInnerClass() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(FinalConfigInnerClassTestCase.class); - assertNotNull(configClasses); - assertEquals("final annotated static Config should NOT be considered.", 0, configClasses.length); + assertThat(configClasses).isNotNull(); + assertThat(configClasses.length).as("final annotated static Config should NOT be considered.").isEqualTo(0); } @Test public void detectDefaultConfigurationClassesForPrivateAnnotatedInnerClass() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(PrivateConfigInnerClassTestCase.class); - assertNotNull(configClasses); - assertEquals("private annotated inner classes should NOT be considered.", 0, configClasses.length); + assertThat(configClasses).isNotNull(); + assertThat(configClasses.length).as("private annotated inner classes should NOT be considered.").isEqualTo(0); } @Test public void detectDefaultConfigurationClassesForNonStaticAnnotatedInnerClass() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(NonStaticConfigInnerClassesTestCase.class); - assertNotNull(configClasses); - assertEquals("non-static annotated inner classes should NOT be considered.", 0, configClasses.length); + assertThat(configClasses).isNotNull(); + assertThat(configClasses.length).as("non-static annotated inner classes should NOT be considered.").isEqualTo(0); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtilsTests.java b/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtilsTests.java index bf9685fb395..c75625191d0 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtilsTests.java @@ -25,10 +25,8 @@ import org.junit.Test; import org.springframework.context.annotation.Configuration; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.springframework.test.context.support.AnnotationConfigContextLoaderUtils.detectDefaultConfigurationClasses; /** @@ -48,22 +46,22 @@ public class AnnotationConfigContextLoaderUtilsTests { @Test public void detectDefaultConfigurationClassesWithoutConfigurationClass() { Class[] configClasses = detectDefaultConfigurationClasses(NoConfigTestCase.class); - assertNotNull(configClasses); - assertEquals(0, configClasses.length); + assertThat(configClasses).isNotNull(); + assertThat(configClasses.length).isEqualTo(0); } @Test public void detectDefaultConfigurationClassesWithExplicitConfigurationAnnotation() { Class[] configClasses = detectDefaultConfigurationClasses(ExplicitConfigTestCase.class); - assertNotNull(configClasses); - assertArrayEquals(new Class[] { ExplicitConfigTestCase.Config.class }, configClasses); + assertThat(configClasses).isNotNull(); + assertThat(configClasses).isEqualTo(new Class[] { ExplicitConfigTestCase.Config.class }); } @Test public void detectDefaultConfigurationClassesWithConfigurationMetaAnnotation() { Class[] configClasses = detectDefaultConfigurationClasses(MetaAnnotatedConfigTestCase.class); - assertNotNull(configClasses); - assertArrayEquals(new Class[] { MetaAnnotatedConfigTestCase.Config.class }, configClasses); + assertThat(configClasses).isNotNull(); + assertThat(configClasses).isEqualTo(new Class[] { MetaAnnotatedConfigTestCase.Config.class }); } diff --git a/spring-test/src/test/java/org/springframework/test/context/support/BootstrapTestUtilsMergedConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/support/BootstrapTestUtilsMergedConfigTests.java index df7c51eae9e..6d6d0652ddb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/BootstrapTestUtilsMergedConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/BootstrapTestUtilsMergedConfigTests.java @@ -30,9 +30,8 @@ import org.springframework.test.context.MergedContextConfiguration; import org.springframework.test.context.web.WebDelegatingSmartContextLoader; import org.springframework.test.context.web.WebMergedContextConfiguration; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; /** * Unit tests for {@link BootstrapTestUtils} involving {@link MergedContextConfiguration}. @@ -124,10 +123,10 @@ public class BootstrapTestUtilsMergedConfigTests extends AbstractContextConfigur WebMergedContextConfiguration webMergedConfig = (WebMergedContextConfiguration) buildMergedContextConfiguration(webTestClass); MergedContextConfiguration standardMergedConfig = buildMergedContextConfiguration(standardTestClass); - assertEquals(webMergedConfig, webMergedConfig); - assertEquals(standardMergedConfig, standardMergedConfig); - assertNotEquals(standardMergedConfig, webMergedConfig); - assertNotEquals(webMergedConfig, standardMergedConfig); + assertThat(webMergedConfig).isEqualTo(webMergedConfig); + assertThat(standardMergedConfig).isEqualTo(standardMergedConfig); + assertThat(webMergedConfig).isNotEqualTo(standardMergedConfig); + assertThat(standardMergedConfig).isNotEqualTo(webMergedConfig); assertMergedConfig(webMergedConfig, webTestClass, EMPTY_STRING_ARRAY, array(FooConfig.class), WebDelegatingSmartContextLoader.class); diff --git a/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsConfigurationAttributesTests.java b/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsConfigurationAttributesTests.java index e4cede4ef40..5a82f43fac4 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsConfigurationAttributesTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsConfigurationAttributesTests.java @@ -25,9 +25,8 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfigurationAttributes; import org.springframework.test.context.ContextLoader; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.springframework.test.context.support.ContextLoaderUtils.resolveContextConfigurationAttributes; /** @@ -72,8 +71,8 @@ public class ContextLoaderUtilsConfigurationAttributesTests extends AbstractCont public void resolveConfigAttributesWithBareAnnotations() { Class testClass = BareAnnotations.class; List attributesList = resolveContextConfigurationAttributes(testClass); - assertNotNull(attributesList); - assertEquals(1, attributesList.size()); + assertThat(attributesList).isNotNull(); + assertThat(attributesList.size()).isEqualTo(1); assertAttributes(attributesList.get(0), testClass, EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, ContextLoader.class, true); } @@ -81,8 +80,8 @@ public class ContextLoaderUtilsConfigurationAttributesTests extends AbstractCont @Test public void resolveConfigAttributesWithLocalAnnotationAndLocations() { List attributesList = resolveContextConfigurationAttributes(LocationsFoo.class); - assertNotNull(attributesList); - assertEquals(1, attributesList.size()); + assertThat(attributesList).isNotNull(); + assertThat(attributesList.size()).isEqualTo(1); assertLocationsFooAttributes(attributesList.get(0)); } @@ -90,8 +89,8 @@ public class ContextLoaderUtilsConfigurationAttributesTests extends AbstractCont public void resolveConfigAttributesWithMetaAnnotationAndLocations() { Class testClass = MetaLocationsFoo.class; List attributesList = resolveContextConfigurationAttributes(testClass); - assertNotNull(attributesList); - assertEquals(1, attributesList.size()); + assertThat(attributesList).isNotNull(); + assertThat(attributesList.size()).isEqualTo(1); assertAttributes(attributesList.get(0), testClass, new String[] {"/foo.xml"}, EMPTY_CLASS_ARRAY, ContextLoader.class, true); } @@ -100,8 +99,8 @@ public class ContextLoaderUtilsConfigurationAttributesTests extends AbstractCont public void resolveConfigAttributesWithMetaAnnotationAndLocationsAndOverrides() { Class testClass = MetaLocationsFooWithOverrides.class; List attributesList = resolveContextConfigurationAttributes(testClass); - assertNotNull(attributesList); - assertEquals(1, attributesList.size()); + assertThat(attributesList).isNotNull(); + assertThat(attributesList.size()).isEqualTo(1); assertAttributes(attributesList.get(0), testClass, new String[] {"/foo.xml"}, EMPTY_CLASS_ARRAY, ContextLoader.class, true); } @@ -110,8 +109,8 @@ public class ContextLoaderUtilsConfigurationAttributesTests extends AbstractCont public void resolveConfigAttributesWithMetaAnnotationAndLocationsAndOverriddenAttributes() { Class testClass = MetaLocationsFooWithOverriddenAttributes.class; List attributesList = resolveContextConfigurationAttributes(testClass); - assertNotNull(attributesList); - assertEquals(1, attributesList.size()); + assertThat(attributesList).isNotNull(); + assertThat(attributesList.size()).isEqualTo(1); assertAttributes(attributesList.get(0), testClass, new String[] {"foo1.xml", "foo2.xml"}, EMPTY_CLASS_ARRAY, ContextLoader.class, true); } @@ -120,8 +119,8 @@ public class ContextLoaderUtilsConfigurationAttributesTests extends AbstractCont public void resolveConfigAttributesWithMetaAnnotationAndLocationsInClassHierarchy() { Class testClass = MetaLocationsBar.class; List attributesList = resolveContextConfigurationAttributes(testClass); - assertNotNull(attributesList); - assertEquals(2, attributesList.size()); + assertThat(attributesList).isNotNull(); + assertThat(attributesList.size()).isEqualTo(2); assertAttributes(attributesList.get(0), testClass, new String[] {"/bar.xml"}, EMPTY_CLASS_ARRAY, ContextLoader.class, true); assertAttributes(attributesList.get(1), @@ -131,16 +130,16 @@ public class ContextLoaderUtilsConfigurationAttributesTests extends AbstractCont @Test public void resolveConfigAttributesWithLocalAnnotationAndClasses() { List attributesList = resolveContextConfigurationAttributes(ClassesFoo.class); - assertNotNull(attributesList); - assertEquals(1, attributesList.size()); + assertThat(attributesList).isNotNull(); + assertThat(attributesList.size()).isEqualTo(1); assertClassesFooAttributes(attributesList.get(0)); } @Test public void resolveConfigAttributesWithLocalAndInheritedAnnotationsAndLocations() { List attributesList = resolveContextConfigurationAttributes(LocationsBar.class); - assertNotNull(attributesList); - assertEquals(2, attributesList.size()); + assertThat(attributesList).isNotNull(); + assertThat(attributesList.size()).isEqualTo(2); assertLocationsBarAttributes(attributesList.get(0)); assertLocationsFooAttributes(attributesList.get(1)); } @@ -148,8 +147,8 @@ public class ContextLoaderUtilsConfigurationAttributesTests extends AbstractCont @Test public void resolveConfigAttributesWithLocalAndInheritedAnnotationsAndClasses() { List attributesList = resolveContextConfigurationAttributes(ClassesBar.class); - assertNotNull(attributesList); - assertEquals(2, attributesList.size()); + assertThat(attributesList).isNotNull(); + assertThat(attributesList.size()).isEqualTo(2); assertClassesBarAttributes(attributesList.get(0)); assertClassesFooAttributes(attributesList.get(1)); } @@ -161,8 +160,8 @@ public class ContextLoaderUtilsConfigurationAttributesTests extends AbstractCont @Test public void resolveConfigAttributesWithLocationsAndClasses() { List attributesList = resolveContextConfigurationAttributes(LocationsAndClasses.class); - assertNotNull(attributesList); - assertEquals(1, attributesList.size()); + assertThat(attributesList).isNotNull(); + assertThat(attributesList.size()).isEqualTo(1); } diff --git a/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java index c69acbccd68..fbd20fe923a 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java @@ -33,9 +33,6 @@ import org.springframework.test.context.ContextLoader; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.springframework.test.context.support.ContextLoaderUtils.GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX; import static org.springframework.test.context.support.ContextLoaderUtils.buildContextHierarchyMap; import static org.springframework.test.context.support.ContextLoaderUtils.resolveContextHierarchyAttributes; @@ -69,18 +66,18 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf @Test public void resolveContextHierarchyAttributesForSingleTestClassWithImplicitSingleLevelContextHierarchy() { List> hierarchyAttributes = resolveContextHierarchyAttributes(BareAnnotations.class); - assertEquals(1, hierarchyAttributes.size()); + assertThat(hierarchyAttributes.size()).isEqualTo(1); List configAttributesList = hierarchyAttributes.get(0); - assertEquals(1, configAttributesList.size()); + assertThat(configAttributesList.size()).isEqualTo(1); debugConfigAttributes(configAttributesList); } @Test public void resolveContextHierarchyAttributesForSingleTestClassWithSingleLevelContextHierarchy() { List> hierarchyAttributes = resolveContextHierarchyAttributes(SingleTestClassWithSingleLevelContextHierarchy.class); - assertEquals(1, hierarchyAttributes.size()); + assertThat(hierarchyAttributes.size()).isEqualTo(1); List configAttributesList = hierarchyAttributes.get(0); - assertEquals(1, configAttributesList.size()); + assertThat(configAttributesList.size()).isEqualTo(1); debugConfigAttributes(configAttributesList); } @@ -88,11 +85,11 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf public void resolveContextHierarchyAttributesForSingleTestClassWithSingleLevelContextHierarchyFromMetaAnnotation() { Class testClass = SingleTestClassWithSingleLevelContextHierarchyFromMetaAnnotation.class; List> hierarchyAttributes = resolveContextHierarchyAttributes(testClass); - assertEquals(1, hierarchyAttributes.size()); + assertThat(hierarchyAttributes.size()).isEqualTo(1); List configAttributesList = hierarchyAttributes.get(0); - assertNotNull(configAttributesList); - assertEquals(1, configAttributesList.size()); + assertThat(configAttributesList).isNotNull(); + assertThat(configAttributesList.size()).isEqualTo(1); debugConfigAttributes(configAttributesList); assertAttributes(configAttributesList.get(0), testClass, new String[] { "A.xml" }, EMPTY_CLASS_ARRAY, ContextLoader.class, true); @@ -102,11 +99,11 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf public void resolveContextHierarchyAttributesForSingleTestClassWithTripleLevelContextHierarchy() { Class testClass = SingleTestClassWithTripleLevelContextHierarchy.class; List> hierarchyAttributes = resolveContextHierarchyAttributes(testClass); - assertEquals(1, hierarchyAttributes.size()); + assertThat(hierarchyAttributes.size()).isEqualTo(1); List configAttributesList = hierarchyAttributes.get(0); - assertNotNull(configAttributesList); - assertEquals(3, configAttributesList.size()); + assertThat(configAttributesList).isNotNull(); + assertThat(configAttributesList.size()).isEqualTo(3); debugConfigAttributes(configAttributesList); assertAttributes(configAttributesList.get(0), testClass, new String[] { "A.xml" }, EMPTY_CLASS_ARRAY, ContextLoader.class, true); @@ -119,33 +116,32 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf @Test public void resolveContextHierarchyAttributesForTestClassHierarchyWithSingleLevelContextHierarchies() { List> hierarchyAttributes = resolveContextHierarchyAttributes(TestClass3WithSingleLevelContextHierarchy.class); - assertEquals(3, hierarchyAttributes.size()); + assertThat(hierarchyAttributes.size()).isEqualTo(3); List configAttributesListClassLevel1 = hierarchyAttributes.get(0); debugConfigAttributes(configAttributesListClassLevel1); - assertEquals(1, configAttributesListClassLevel1.size()); + assertThat(configAttributesListClassLevel1.size()).isEqualTo(1); assertThat(configAttributesListClassLevel1.get(0).getLocations()[0]).isEqualTo("one.xml"); List configAttributesListClassLevel2 = hierarchyAttributes.get(1); debugConfigAttributes(configAttributesListClassLevel2); - assertEquals(1, configAttributesListClassLevel2.size()); - assertArrayEquals(new String[] { "two-A.xml", "two-B.xml" }, - configAttributesListClassLevel2.get(0).getLocations()); + assertThat(configAttributesListClassLevel2.size()).isEqualTo(1); + assertThat(configAttributesListClassLevel2.get(0).getLocations()).isEqualTo(new String[] { "two-A.xml", "two-B.xml" }); List configAttributesListClassLevel3 = hierarchyAttributes.get(2); debugConfigAttributes(configAttributesListClassLevel3); - assertEquals(1, configAttributesListClassLevel3.size()); + assertThat(configAttributesListClassLevel3.size()).isEqualTo(1); assertThat(configAttributesListClassLevel3.get(0).getLocations()[0]).isEqualTo("three.xml"); } @Test public void resolveContextHierarchyAttributesForTestClassHierarchyWithSingleLevelContextHierarchiesAndMetaAnnotations() { List> hierarchyAttributes = resolveContextHierarchyAttributes(TestClass3WithSingleLevelContextHierarchyFromMetaAnnotation.class); - assertEquals(3, hierarchyAttributes.size()); + assertThat(hierarchyAttributes.size()).isEqualTo(3); List configAttributesListClassLevel1 = hierarchyAttributes.get(0); debugConfigAttributes(configAttributesListClassLevel1); - assertEquals(1, configAttributesListClassLevel1.size()); + assertThat(configAttributesListClassLevel1.size()).isEqualTo(1); assertThat(configAttributesListClassLevel1.get(0).getLocations()[0]).isEqualTo("A.xml"); assertAttributes(configAttributesListClassLevel1.get(0), TestClass1WithSingleLevelContextHierarchyFromMetaAnnotation.class, new String[] { "A.xml" }, @@ -153,9 +149,8 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf List configAttributesListClassLevel2 = hierarchyAttributes.get(1); debugConfigAttributes(configAttributesListClassLevel2); - assertEquals(1, configAttributesListClassLevel2.size()); - assertArrayEquals(new String[] { "B-one.xml", "B-two.xml" }, - configAttributesListClassLevel2.get(0).getLocations()); + assertThat(configAttributesListClassLevel2.size()).isEqualTo(1); + assertThat(configAttributesListClassLevel2.get(0).getLocations()).isEqualTo(new String[] { "B-one.xml", "B-two.xml" }); assertAttributes(configAttributesListClassLevel2.get(0), TestClass2WithSingleLevelContextHierarchyFromMetaAnnotation.class, new String[] { "B-one.xml", @@ -163,7 +158,7 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf List configAttributesListClassLevel3 = hierarchyAttributes.get(2); debugConfigAttributes(configAttributesListClassLevel3); - assertEquals(1, configAttributesListClassLevel3.size()); + assertThat(configAttributesListClassLevel3.size()).isEqualTo(1); assertThat(configAttributesListClassLevel3.get(0).getLocations()[0]).isEqualTo("C.xml"); assertAttributes(configAttributesListClassLevel3.get(0), TestClass3WithSingleLevelContextHierarchyFromMetaAnnotation.class, new String[] { "C.xml" }, @@ -171,17 +166,17 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf } private void assertOneTwo(List> hierarchyAttributes) { - assertEquals(2, hierarchyAttributes.size()); + assertThat(hierarchyAttributes.size()).isEqualTo(2); List configAttributesListClassLevel1 = hierarchyAttributes.get(0); List configAttributesListClassLevel2 = hierarchyAttributes.get(1); debugConfigAttributes(configAttributesListClassLevel1); debugConfigAttributes(configAttributesListClassLevel2); - assertEquals(1, configAttributesListClassLevel1.size()); + assertThat(configAttributesListClassLevel1.size()).isEqualTo(1); assertThat(configAttributesListClassLevel1.get(0).getLocations()[0]).isEqualTo("one.xml"); - assertEquals(1, configAttributesListClassLevel2.size()); + assertThat(configAttributesListClassLevel2.size()).isEqualTo(1); assertThat(configAttributesListClassLevel2.get(0).getLocations()[0]).isEqualTo("two.xml"); } @@ -208,23 +203,23 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf @Test public void resolveContextHierarchyAttributesForTestClassHierarchyWithMultiLevelContextHierarchies() { List> hierarchyAttributes = resolveContextHierarchyAttributes(TestClass3WithMultiLevelContextHierarchy.class); - assertEquals(3, hierarchyAttributes.size()); + assertThat(hierarchyAttributes.size()).isEqualTo(3); List configAttributesListClassLevel1 = hierarchyAttributes.get(0); debugConfigAttributes(configAttributesListClassLevel1); - assertEquals(2, configAttributesListClassLevel1.size()); + assertThat(configAttributesListClassLevel1.size()).isEqualTo(2); assertThat(configAttributesListClassLevel1.get(0).getLocations()[0]).isEqualTo("1-A.xml"); assertThat(configAttributesListClassLevel1.get(1).getLocations()[0]).isEqualTo("1-B.xml"); List configAttributesListClassLevel2 = hierarchyAttributes.get(1); debugConfigAttributes(configAttributesListClassLevel2); - assertEquals(2, configAttributesListClassLevel2.size()); + assertThat(configAttributesListClassLevel2.size()).isEqualTo(2); assertThat(configAttributesListClassLevel2.get(0).getLocations()[0]).isEqualTo("2-A.xml"); assertThat(configAttributesListClassLevel2.get(1).getLocations()[0]).isEqualTo("2-B.xml"); List configAttributesListClassLevel3 = hierarchyAttributes.get(2); debugConfigAttributes(configAttributesListClassLevel3); - assertEquals(3, configAttributesListClassLevel3.size()); + assertThat(configAttributesListClassLevel3.size()).isEqualTo(3); assertThat(configAttributesListClassLevel3.get(0).getLocations()[0]).isEqualTo("3-A.xml"); assertThat(configAttributesListClassLevel3.get(1).getLocations()[0]).isEqualTo("3-B.xml"); assertThat(configAttributesListClassLevel3.get(2).getLocations()[0]).isEqualTo("3-C.xml"); @@ -347,7 +342,7 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf assertThat(alphaConfig.get(0).getInitializers().length).isEqualTo(0); assertThat(alphaConfig.get(1).getLocations().length).isEqualTo(0); assertThat(alphaConfig.get(1).getInitializers().length).isEqualTo(1); - assertEquals(DummyApplicationContextInitializer.class, alphaConfig.get(1).getInitializers()[0]); + assertThat(alphaConfig.get(1).getInitializers()[0]).isEqualTo(DummyApplicationContextInitializer.class); List betaConfig = map.get("beta"); assertThat(betaConfig).hasSize(2); @@ -356,7 +351,7 @@ public class ContextLoaderUtilsContextHierarchyTests extends AbstractContextConf assertThat(betaConfig.get(0).getInitializers().length).isEqualTo(0); assertThat(betaConfig.get(1).getLocations().length).isEqualTo(0); assertThat(betaConfig.get(1).getInitializers().length).isEqualTo(1); - assertEquals(DummyApplicationContextInitializer.class, betaConfig.get(1).getInitializers()[0]); + assertThat(betaConfig.get(1).getInitializers()[0]).isEqualTo(DummyApplicationContextInitializer.class); } diff --git a/spring-test/src/test/java/org/springframework/test/context/support/CustomizedGenericXmlContextLoaderTests.java b/spring-test/src/test/java/org/springframework/test/context/support/CustomizedGenericXmlContextLoaderTests.java index 9752f9e4677..56f39e16288 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/CustomizedGenericXmlContextLoaderTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/CustomizedGenericXmlContextLoaderTests.java @@ -20,8 +20,7 @@ import org.junit.Test; import org.springframework.context.support.GenericApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit test which verifies that extensions of @@ -47,12 +46,12 @@ public class CustomizedGenericXmlContextLoaderTests { @Override protected void customizeContext(GenericApplicationContext context) { - assertFalse("The context should not yet have been refreshed.", context.isActive()); + assertThat(context.isActive()).as("The context should not yet have been refreshed.").isFalse(); builder.append(expectedContents); } }.loadContext("classpath:/org/springframework/test/context/support/CustomizedGenericXmlContextLoaderTests-context.xml"); - assertEquals("customizeContext() should have been called.", expectedContents, builder.toString()); + assertThat(builder.toString()).as("customizeContext() should have been called.").isEqualTo(expectedContents); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/support/DelegatingSmartContextLoaderTests.java b/spring-test/src/test/java/org/springframework/test/context/support/DelegatingSmartContextLoaderTests.java index c96a8fab5d8..7f301cc8e9e 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/DelegatingSmartContextLoaderTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/DelegatingSmartContextLoaderTests.java @@ -27,13 +27,10 @@ import org.springframework.test.context.ContextLoader; import org.springframework.test.context.MergedContextConfiguration; import org.springframework.util.ObjectUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link DelegatingSmartContextLoader}. @@ -50,7 +47,7 @@ public class DelegatingSmartContextLoaderTests { private static void assertEmpty(Object[] array) { - assertTrue(ObjectUtils.isEmpty(array)); + assertThat(ObjectUtils.isEmpty(array)).isTrue(); } // --- SmartContextLoader - processContextConfiguration() ------------------ @@ -60,7 +57,7 @@ public class DelegatingSmartContextLoaderTests { ContextConfigurationAttributes configAttributes = new ContextConfigurationAttributes( XmlTestCase.class, EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, true, null, true, ContextLoader.class); loader.processContextConfiguration(configAttributes); - assertEquals(1, configAttributes.getLocations().length); + assertThat(configAttributes.getLocations().length).isEqualTo(1); assertEmpty(configAttributes.getClasses()); } @@ -69,7 +66,7 @@ public class DelegatingSmartContextLoaderTests { ContextConfigurationAttributes configAttributes = new ContextConfigurationAttributes( ConfigClassTestCase.class, EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, true, null, true, ContextLoader.class); loader.processContextConfiguration(configAttributes); - assertEquals(1, configAttributes.getClasses().length); + assertThat(configAttributes.getClasses().length).isEqualTo(1); assertEmpty(configAttributes.getLocations()); } @@ -89,7 +86,7 @@ public class DelegatingSmartContextLoaderTests { ContextConfigurationAttributes configAttributes = new ContextConfigurationAttributes( getClass(), locations, EMPTY_CLASS_ARRAY, true, null, true, ContextLoader.class); loader.processContextConfiguration(configAttributes); - assertArrayEquals(locations, configAttributes.getLocations()); + assertThat(configAttributes.getLocations()).isEqualTo(locations); assertEmpty(configAttributes.getClasses()); } @@ -99,7 +96,7 @@ public class DelegatingSmartContextLoaderTests { ContextConfigurationAttributes configAttributes = new ContextConfigurationAttributes( getClass(), EMPTY_STRING_ARRAY, classes, true, null, true, ContextLoader.class); loader.processContextConfiguration(configAttributes); - assertArrayEquals(classes, configAttributes.getClasses()); + assertThat(configAttributes.getClasses()).isEqualTo(classes); assertEmpty(configAttributes.getLocations()); } @@ -138,9 +135,10 @@ public class DelegatingSmartContextLoaderTests { throws Exception { ApplicationContext applicationContext = loader.loadContext(mergedConfig); - assertNotNull(applicationContext); - assertEquals("foo", applicationContext.getBean(String.class)); - assertTrue(applicationContext instanceof ConfigurableApplicationContext); + assertThat(applicationContext).isNotNull(); + assertThat(applicationContext.getBean(String.class)).isEqualTo("foo"); + boolean condition = applicationContext instanceof ConfigurableApplicationContext; + assertThat(condition).isTrue(); ((ConfigurableApplicationContext) applicationContext).close(); } diff --git a/spring-test/src/test/java/org/springframework/test/context/support/GenericXmlContextLoaderResourceLocationsTests.java b/spring-test/src/test/java/org/springframework/test/context/support/GenericXmlContextLoaderResourceLocationsTests.java index d5250ac670e..9a0f6369f62 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/GenericXmlContextLoaderResourceLocationsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/GenericXmlContextLoaderResourceLocationsTests.java @@ -32,7 +32,7 @@ import org.springframework.test.context.ContextLoader; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; -import static org.junit.Assert.assertArrayEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit 4 based unit test which verifies proper @@ -135,8 +135,7 @@ public class GenericXmlContextLoaderResourceLocationsTests { logger.debug("Processed locations: " + ObjectUtils.nullSafeToString(processedLocations)); } - assertArrayEquals("Verifying locations for test [" + this.testClass + "].", this.expectedLocations, - processedLocations); + assertThat(processedLocations).as("Verifying locations for test [" + this.testClass + "].").isEqualTo(this.expectedLocations); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/support/TestConstructorUtilsTests.java b/spring-test/src/test/java/org/springframework/test/context/support/TestConstructorUtilsTests.java index 99734c5d794..8904ad18611 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/TestConstructorUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/TestConstructorUtilsTests.java @@ -24,8 +24,7 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.TestConstructor; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link TestConstructorUtils}. @@ -69,12 +68,12 @@ public class TestConstructorUtilsTests { private void assertAutowirable(Class testClass) throws NoSuchMethodException { Constructor constructor = testClass.getDeclaredConstructor(); - assertTrue(TestConstructorUtils.isAutowirableConstructor(constructor, testClass)); + assertThat(TestConstructorUtils.isAutowirableConstructor(constructor, testClass)).isTrue(); } private void assertNotAutowirable(Class testClass) throws NoSuchMethodException { Constructor constructor = testClass.getDeclaredConstructor(); - assertFalse(TestConstructorUtils.isAutowirableConstructor(constructor, testClass)); + assertThat(TestConstructorUtils.isAutowirableConstructor(constructor, testClass)).isFalse(); } private void setGlobalFlag() { diff --git a/spring-test/src/test/java/org/springframework/test/context/support/TestPropertySourceUtilsTests.java b/spring-test/src/test/java/org/springframework/test/context/support/TestPropertySourceUtilsTests.java index 3737ed50002..9df2b646329 100644 --- a/spring-test/src/test/java/org/springframework/test/context/support/TestPropertySourceUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/support/TestPropertySourceUtilsTests.java @@ -30,12 +30,10 @@ import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.env.MockPropertySource; import org.springframework.test.context.TestPropertySource; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -160,7 +158,7 @@ public class TestPropertySourceUtilsTests { MutablePropertySources propertySources = environment.getPropertySources(); propertySources.remove(MockPropertySource.MOCK_PROPERTIES_PROPERTY_SOURCE_NAME); - assertEquals(0, propertySources.size()); + assertThat(propertySources.size()).isEqualTo(0); String pair = "key = value"; ByteArrayResource resource = new ByteArrayResource(pair.getBytes(), "from inlined property: " + pair); @@ -168,8 +166,8 @@ public class TestPropertySourceUtilsTests { given(resourceLoader.getResource(anyString())).willReturn(resource); addPropertiesFilesToEnvironment(environment, resourceLoader, FOO_LOCATIONS); - assertEquals(1, propertySources.size()); - assertEquals("value", environment.getProperty("key")); + assertThat(propertySources.size()).isEqualTo(1); + assertThat(environment.getProperty("key")).isEqualTo("value"); } @Test @@ -220,10 +218,10 @@ public class TestPropertySourceUtilsTests { ConfigurableEnvironment environment = new MockEnvironment(); MutablePropertySources propertySources = environment.getPropertySources(); propertySources.remove(MockPropertySource.MOCK_PROPERTIES_PROPERTY_SOURCE_NAME); - assertEquals(0, propertySources.size()); + assertThat(propertySources.size()).isEqualTo(0); addInlinedPropertiesToEnvironment(environment, asArray(" ")); - assertEquals(1, propertySources.size()); - assertEquals(0, ((Map) propertySources.iterator().next().getSource()).size()); + assertThat(propertySources.size()).isEqualTo(1); + assertThat(((Map) propertySources.iterator().next().getSource()).size()).isEqualTo(0); } @Test @@ -238,9 +236,9 @@ public class TestPropertySourceUtilsTests { String[] expectedProperties) { MergedTestPropertySources mergedPropertySources = buildMergedTestPropertySources(testClass); - assertNotNull(mergedPropertySources); - assertArrayEquals(expectedLocations, mergedPropertySources.getLocations()); - assertArrayEquals(expectedProperties, mergedPropertySources.getProperties()); + assertThat(mergedPropertySources).isNotNull(); + assertThat(mergedPropertySources.getLocations()).isEqualTo(expectedLocations); + assertThat(mergedPropertySources.getProperties()).isEqualTo(expectedProperties); } diff --git a/spring-test/src/test/java/org/springframework/test/context/testng/transaction/programmatic/ProgrammaticTxMgmtTestNGTests.java b/spring-test/src/test/java/org/springframework/test/context/testng/transaction/programmatic/ProgrammaticTxMgmtTestNGTests.java index 3ee5a4d1385..41b5fd3944b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/testng/transaction/programmatic/ProgrammaticTxMgmtTestNGTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/testng/transaction/programmatic/ProgrammaticTxMgmtTestNGTests.java @@ -40,10 +40,8 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -98,7 +96,7 @@ public class ProgrammaticTxMgmtTestNGTests extends AbstractTransactionalTestNGSp @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void isActiveWithNonExistentTransactionContext() { - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); } @Test(expectedExceptions = IllegalStateException.class) @@ -139,17 +137,17 @@ public class ProgrammaticTxMgmtTestNGTests extends AbstractTransactionalTestNGSp @Test public void commitTxAndStartNewTx() { assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); assertUsers("Dilbert"); deleteFromTables("user"); assertUsers(); // Commit TestTransaction.flagForCommit(); - assertFalse(TestTransaction.isFlaggedForRollback()); + assertThat(TestTransaction.isFlaggedForRollback()).isFalse(); TestTransaction.end(); assertInTransaction(false); - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); assertUsers(); executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false); @@ -157,22 +155,22 @@ public class ProgrammaticTxMgmtTestNGTests extends AbstractTransactionalTestNGSp TestTransaction.start(); assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); } @Test public void commitTxButDoNotStartNewTx() { assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); assertUsers("Dilbert"); deleteFromTables("user"); assertUsers(); // Commit TestTransaction.flagForCommit(); - assertFalse(TestTransaction.isFlaggedForRollback()); + assertThat(TestTransaction.isFlaggedForRollback()).isFalse(); TestTransaction.end(); - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); assertInTransaction(false); assertUsers(); @@ -183,23 +181,23 @@ public class ProgrammaticTxMgmtTestNGTests extends AbstractTransactionalTestNGSp @Test public void rollbackTxAndStartNewTx() { assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); assertUsers("Dilbert"); deleteFromTables("user"); assertUsers(); // Rollback (automatically) - assertTrue(TestTransaction.isFlaggedForRollback()); + assertThat(TestTransaction.isFlaggedForRollback()).isTrue(); TestTransaction.end(); - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); assertInTransaction(false); assertUsers("Dilbert"); // Start new transaction with default rollback semantics TestTransaction.start(); assertInTransaction(true); - assertTrue(TestTransaction.isFlaggedForRollback()); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isFlaggedForRollback()).isTrue(); + assertThat(TestTransaction.isActive()).isTrue(); executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false); assertUsers("Dilbert", "Dogbert"); @@ -208,15 +206,15 @@ public class ProgrammaticTxMgmtTestNGTests extends AbstractTransactionalTestNGSp @Test public void rollbackTxButDoNotStartNewTx() { assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); assertUsers("Dilbert"); deleteFromTables("user"); assertUsers(); // Rollback (automatically) - assertTrue(TestTransaction.isFlaggedForRollback()); + assertThat(TestTransaction.isFlaggedForRollback()).isTrue(); TestTransaction.end(); - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); assertInTransaction(false); assertUsers("Dilbert"); } @@ -225,24 +223,24 @@ public class ProgrammaticTxMgmtTestNGTests extends AbstractTransactionalTestNGSp @Commit public void rollbackTxAndStartNewTxWithDefaultCommitSemantics() { assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); assertUsers("Dilbert"); deleteFromTables("user"); assertUsers(); // Rollback TestTransaction.flagForRollback(); - assertTrue(TestTransaction.isFlaggedForRollback()); + assertThat(TestTransaction.isFlaggedForRollback()).isTrue(); TestTransaction.end(); - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); assertInTransaction(false); assertUsers("Dilbert"); // Start new transaction with default commit semantics TestTransaction.start(); assertInTransaction(true); - assertFalse(TestTransaction.isFlaggedForRollback()); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isFlaggedForRollback()).isFalse(); + assertThat(TestTransaction.isActive()).isTrue(); executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false); assertUsers("Dilbert", "Dogbert"); @@ -255,7 +253,7 @@ public class ProgrammaticTxMgmtTestNGTests extends AbstractTransactionalTestNGSp Collections.sort(expected); List actual = jdbcTemplate.queryForList("select name from user", String.class); Collections.sort(actual); - assertEquals("Users in database;", expected, actual); + assertThat(actual).as("Users in database;").isEqualTo(expected); } diff --git a/spring-test/src/test/java/org/springframework/test/context/testng/web/ServletTestExecutionListenerTestNGIntegrationTests.java b/spring-test/src/test/java/org/springframework/test/context/testng/web/ServletTestExecutionListenerTestNGIntegrationTests.java index 65c37734ba5..270f307c453 100644 --- a/spring-test/src/test/java/org/springframework/test/context/testng/web/ServletTestExecutionListenerTestNGIntegrationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/testng/web/ServletTestExecutionListenerTestNGIntegrationTests.java @@ -28,7 +28,7 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * TestNG-based integration tests for {@link ServletTestExecutionListener}. @@ -72,8 +72,7 @@ public class ServletTestExecutionListenerTestNGIntegrationTests extends Abstract } private void assertInjectedServletRequestEqualsRequestInRequestContextHolder() { - assertEquals("Injected ServletRequest must be stored in the RequestContextHolder", servletRequest, - ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()); + assertThat(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()).as("Injected ServletRequest must be stored in the RequestContextHolder").isEqualTo(servletRequest); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/testng/web/TestNGSpringContextWebTests.java b/spring-test/src/test/java/org/springframework/test/context/testng/web/TestNGSpringContextWebTests.java index 1ab95283351..6a4e7975614 100644 --- a/spring-test/src/test/java/org/springframework/test/context/testng/web/TestNGSpringContextWebTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/testng/web/TestNGSpringContextWebTests.java @@ -35,9 +35,7 @@ import org.springframework.web.context.ServletContextAware; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.ServletWebRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * TestNG-based integration tests that verify support for loading a @@ -91,31 +89,30 @@ public class TestNGSpringContextWebTests extends AbstractTestNGSpringContextTest @Test void basicWacFeatures() throws Exception { - assertNotNull("ServletContext should be set in the WAC.", wac.getServletContext()); + assertThat(wac.getServletContext()).as("ServletContext should be set in the WAC.").isNotNull(); - assertNotNull("ServletContext should have been set via ServletContextAware.", servletContext); + assertThat(servletContext).as("ServletContext should have been set via ServletContextAware.").isNotNull(); - assertNotNull("ServletContext should have been autowired from the WAC.", mockServletContext); - assertNotNull("MockHttpServletRequest should have been autowired from the WAC.", request); - assertNotNull("MockHttpServletResponse should have been autowired from the WAC.", response); - assertNotNull("MockHttpSession should have been autowired from the WAC.", session); - assertNotNull("ServletWebRequest should have been autowired from the WAC.", webRequest); + assertThat(mockServletContext).as("ServletContext should have been autowired from the WAC.").isNotNull(); + assertThat(request).as("MockHttpServletRequest should have been autowired from the WAC.").isNotNull(); + assertThat(response).as("MockHttpServletResponse should have been autowired from the WAC.").isNotNull(); + assertThat(session).as("MockHttpSession should have been autowired from the WAC.").isNotNull(); + assertThat(webRequest).as("ServletWebRequest should have been autowired from the WAC.").isNotNull(); Object rootWac = mockServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); - assertNotNull("Root WAC must be stored in the ServletContext as: " - + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, rootWac); - assertSame("test WAC and Root WAC in ServletContext must be the same object.", wac, rootWac); - assertSame("ServletContext instances must be the same object.", mockServletContext, wac.getServletContext()); - assertSame("ServletContext in the WAC and in the mock request", mockServletContext, request.getServletContext()); + assertThat(rootWac).as("Root WAC must be stored in the ServletContext as: " + + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE).isNotNull(); + assertThat(rootWac).as("test WAC and Root WAC in ServletContext must be the same object.").isSameAs(wac); + assertThat(wac.getServletContext()).as("ServletContext instances must be the same object.").isSameAs(mockServletContext); + assertThat(request.getServletContext()).as("ServletContext in the WAC and in the mock request").isSameAs(mockServletContext); - assertEquals("Getting real path for ServletContext resource.", - new File("src/main/webapp/index.jsp").getCanonicalPath(), mockServletContext.getRealPath("index.jsp")); + assertThat(mockServletContext.getRealPath("index.jsp")).as("Getting real path for ServletContext resource.").isEqualTo(new File("src/main/webapp/index.jsp").getCanonicalPath()); } @Test void fooEnigmaAutowired() { - assertEquals("enigma", foo); + assertThat(foo).isEqualTo("enigma"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/transaction/PrimaryTransactionManagerTests.java b/spring-test/src/test/java/org/springframework/test/context/transaction/PrimaryTransactionManagerTests.java index 03163e13e9e..940c4c3ea16 100644 --- a/spring-test/src/test/java/org/springframework/test/context/transaction/PrimaryTransactionManagerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/transaction/PrimaryTransactionManagerTests.java @@ -39,7 +39,7 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that ensure that primary transaction managers @@ -85,8 +85,7 @@ public final class PrimaryTransactionManagerTests { } private void assertNumUsers(int expected) { - assertEquals("Number of rows in the 'user' table", expected, - JdbcTestUtils.countRowsInTable(this.jdbcTemplate, "user")); + assertThat(JdbcTestUtils.countRowsInTable(this.jdbcTemplate, "user")).as("Number of rows in the 'user' table").isEqualTo(expected); } diff --git a/spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java b/spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java index 66a10939552..caeb9c10d6c 100644 --- a/spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java @@ -34,10 +34,8 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.SimpleTransactionStatus; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED; @@ -83,7 +81,7 @@ public class TransactionalTestExecutionListenerTests { given(testContext.getTestInstance()).willReturn(instance); given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("transactionalTest")); - assertFalse("callback should not have been invoked", instance.invoked()); + assertThat(instance.invoked()).as("callback should not have been invoked").isFalse(); TransactionContextHolder.removeCurrentTransactionContext(); assertThatIllegalStateException().isThrownBy(() -> @@ -221,10 +219,10 @@ public class TransactionalTestExecutionListenerTests { given(testContext.getTestInstance()).willReturn(instance); given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("transactionalTest")); - assertFalse("callback should not have been invoked", instance.invoked()); + assertThat(instance.invoked()).as("callback should not have been invoked").isFalse(); TransactionContextHolder.removeCurrentTransactionContext(); listener.beforeTestMethod(testContext); - assertEquals(invokedInTx, instance.invoked()); + assertThat(instance.invoked()).isEqualTo(invokedInTx); } private void assertBeforeTestMethodWithNonTransactionalTestMethod(Class clazz) throws Exception { @@ -233,10 +231,10 @@ public class TransactionalTestExecutionListenerTests { given(testContext.getTestInstance()).willReturn(instance); given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("nonTransactionalTest")); - assertFalse("callback should not have been invoked", instance.invoked()); + assertThat(instance.invoked()).as("callback should not have been invoked").isFalse(); TransactionContextHolder.removeCurrentTransactionContext(); listener.beforeTestMethod(testContext); - assertFalse("callback should not have been invoked", instance.invoked()); + assertThat(instance.invoked()).as("callback should not have been invoked").isFalse(); } private void assertAfterTestMethod(Class clazz) throws Exception { @@ -251,12 +249,12 @@ public class TransactionalTestExecutionListenerTests { given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("transactionalTest")); given(tm.getTransaction(BDDMockito.any(TransactionDefinition.class))).willReturn(new SimpleTransactionStatus()); - assertFalse("callback should not have been invoked", instance.invoked()); + assertThat(instance.invoked()).as("callback should not have been invoked").isFalse(); TransactionContextHolder.removeCurrentTransactionContext(); listener.beforeTestMethod(testContext); - assertFalse("callback should not have been invoked", instance.invoked()); + assertThat(instance.invoked()).as("callback should not have been invoked").isFalse(); listener.afterTestMethod(testContext); - assertTrue("callback should have been invoked", instance.invoked()); + assertThat(instance.invoked()).as("callback should have been invoked").isTrue(); } private void assertAfterTestMethodWithNonTransactionalTestMethod(Class clazz) throws Exception { @@ -265,17 +263,17 @@ public class TransactionalTestExecutionListenerTests { given(testContext.getTestInstance()).willReturn(instance); given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("nonTransactionalTest")); - assertFalse("callback should not have been invoked", instance.invoked()); + assertThat(instance.invoked()).as("callback should not have been invoked").isFalse(); TransactionContextHolder.removeCurrentTransactionContext(); listener.beforeTestMethod(testContext); listener.afterTestMethod(testContext); - assertFalse("callback should not have been invoked", instance.invoked()); + assertThat(instance.invoked()).as("callback should not have been invoked").isFalse(); } private void assertIsRollback(Class clazz, boolean rollback) throws Exception { BDDMockito.> given(testContext.getTestClass()).willReturn(clazz); given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("test")); - assertEquals(rollback, listener.isRollback(testContext)); + assertThat(listener.isRollback(testContext)).isEqualTo(rollback); } diff --git a/spring-test/src/test/java/org/springframework/test/context/transaction/ejb/AbstractEjbTxDaoTests.java b/spring-test/src/test/java/org/springframework/test/context/transaction/ejb/AbstractEjbTxDaoTests.java index 36c2f57729c..2f1f0f13420 100644 --- a/spring-test/src/test/java/org/springframework/test/context/transaction/ejb/AbstractEjbTxDaoTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/transaction/ejb/AbstractEjbTxDaoTests.java @@ -30,7 +30,7 @@ import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.transaction.ejb.dao.TestEntityDao; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Abstract base class for all tests involving EJB transaction support in the @@ -56,13 +56,13 @@ public abstract class AbstractEjbTxDaoTests extends AbstractTransactionalJUnit4S @Test public void test1InitialState() { int count = dao.getCount(TEST_NAME); - assertEquals("New TestEntity should have count=0.", 0, count); + assertThat(count).as("New TestEntity should have count=0.").isEqualTo(0); } @Test public void test2IncrementCount1() { int count = dao.incrementCount(TEST_NAME); - assertEquals("Expected count=1 after first increment.", 1, count); + assertThat(count).as("Expected count=1 after first increment.").isEqualTo(1); } /** @@ -73,10 +73,10 @@ public abstract class AbstractEjbTxDaoTests extends AbstractTransactionalJUnit4S @Test public void test3IncrementCount2() { int count = dao.getCount(TEST_NAME); - assertEquals("Expected count=1 after test2IncrementCount1().", 1, count); + assertThat(count).as("Expected count=1 after test2IncrementCount1().").isEqualTo(1); count = dao.incrementCount(TEST_NAME); - assertEquals("Expected count=2 now.", 2, count); + assertThat(count).as("Expected count=2 now.").isEqualTo(2); } @After diff --git a/spring-test/src/test/java/org/springframework/test/context/transaction/ejb/RollbackForRequiredEjbTxDaoTests.java b/spring-test/src/test/java/org/springframework/test/context/transaction/ejb/RollbackForRequiredEjbTxDaoTests.java index 351e9a85541..b7788323b61 100644 --- a/spring-test/src/test/java/org/springframework/test/context/transaction/ejb/RollbackForRequiredEjbTxDaoTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/transaction/ejb/RollbackForRequiredEjbTxDaoTests.java @@ -23,7 +23,7 @@ import org.junit.runners.MethodSorters; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Extension of {@link CommitForRequiredEjbTxDaoTests} which sets the default @@ -72,10 +72,10 @@ public class RollbackForRequiredEjbTxDaoTests extends CommitForRequiredEjbTxDaoT // participate in the existing transaction (if present), which in this case is the // transaction managed by the TestContext framework which will be rolled back // after each test method. - assertEquals("Expected count=0 after test2IncrementCount1().", 0, count); + assertThat(count).as("Expected count=0 after test2IncrementCount1().").isEqualTo(0); count = dao.incrementCount(TEST_NAME); - assertEquals("Expected count=1 now.", 1, count); + assertThat(count).as("Expected count=1 now.").isEqualTo(1); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/transaction/programmatic/ProgrammaticTxMgmtTests.java b/spring-test/src/test/java/org/springframework/test/context/transaction/programmatic/ProgrammaticTxMgmtTests.java index 05651d3f069..ea286f9bd8b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/transaction/programmatic/ProgrammaticTxMgmtTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/transaction/programmatic/ProgrammaticTxMgmtTests.java @@ -47,10 +47,8 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.springframework.test.transaction.TransactionTestUtils.assertInTransaction; /** @@ -116,7 +114,7 @@ public class ProgrammaticTxMgmtTests { @Test @Transactional(propagation = Propagation.NOT_SUPPORTED) public void isActiveWithNonExistentTransactionContext() { - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); } @Test(expected = IllegalStateException.class) @@ -157,17 +155,17 @@ public class ProgrammaticTxMgmtTests { @Test public void commitTxAndStartNewTx() { assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); assertUsers("Dilbert"); deleteFromTables("user"); assertUsers(); // Commit TestTransaction.flagForCommit(); - assertFalse(TestTransaction.isFlaggedForRollback()); + assertThat(TestTransaction.isFlaggedForRollback()).isFalse(); TestTransaction.end(); assertInTransaction(false); - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); assertUsers(); executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false); @@ -175,22 +173,22 @@ public class ProgrammaticTxMgmtTests { TestTransaction.start(); assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); } @Test public void commitTxButDoNotStartNewTx() { assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); assertUsers("Dilbert"); deleteFromTables("user"); assertUsers(); // Commit TestTransaction.flagForCommit(); - assertFalse(TestTransaction.isFlaggedForRollback()); + assertThat(TestTransaction.isFlaggedForRollback()).isFalse(); TestTransaction.end(); - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); assertInTransaction(false); assertUsers(); @@ -201,23 +199,23 @@ public class ProgrammaticTxMgmtTests { @Test public void rollbackTxAndStartNewTx() { assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); assertUsers("Dilbert"); deleteFromTables("user"); assertUsers(); // Rollback (automatically) - assertTrue(TestTransaction.isFlaggedForRollback()); + assertThat(TestTransaction.isFlaggedForRollback()).isTrue(); TestTransaction.end(); - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); assertInTransaction(false); assertUsers("Dilbert"); // Start new transaction with default rollback semantics TestTransaction.start(); assertInTransaction(true); - assertTrue(TestTransaction.isFlaggedForRollback()); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isFlaggedForRollback()).isTrue(); + assertThat(TestTransaction.isActive()).isTrue(); executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false); assertUsers("Dilbert", "Dogbert"); @@ -226,15 +224,15 @@ public class ProgrammaticTxMgmtTests { @Test public void rollbackTxButDoNotStartNewTx() { assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); assertUsers("Dilbert"); deleteFromTables("user"); assertUsers(); // Rollback (automatically) - assertTrue(TestTransaction.isFlaggedForRollback()); + assertThat(TestTransaction.isFlaggedForRollback()).isTrue(); TestTransaction.end(); - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); assertInTransaction(false); assertUsers("Dilbert"); } @@ -243,24 +241,24 @@ public class ProgrammaticTxMgmtTests { @Commit public void rollbackTxAndStartNewTxWithDefaultCommitSemantics() { assertInTransaction(true); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isTrue(); assertUsers("Dilbert"); deleteFromTables("user"); assertUsers(); // Rollback TestTransaction.flagForRollback(); - assertTrue(TestTransaction.isFlaggedForRollback()); + assertThat(TestTransaction.isFlaggedForRollback()).isTrue(); TestTransaction.end(); - assertFalse(TestTransaction.isActive()); + assertThat(TestTransaction.isActive()).isFalse(); assertInTransaction(false); assertUsers("Dilbert"); // Start new transaction with default commit semantics TestTransaction.start(); assertInTransaction(true); - assertFalse(TestTransaction.isFlaggedForRollback()); - assertTrue(TestTransaction.isActive()); + assertThat(TestTransaction.isFlaggedForRollback()).isFalse(); + assertThat(TestTransaction.isActive()).isTrue(); executeSqlScript("classpath:/org/springframework/test/context/jdbc/data-add-dogbert.sql", false); assertUsers("Dilbert", "Dogbert"); @@ -282,7 +280,7 @@ public class ProgrammaticTxMgmtTests { Collections.sort(expected); List actual = jdbcTemplate.queryForList("select name from user", String.class); Collections.sort(actual); - assertEquals("Users in database;", expected, actual); + assertThat(actual).as("Users in database;").isEqualTo(expected); } // ------------------------------------------------------------------------- diff --git a/spring-test/src/test/java/org/springframework/test/context/web/AbstractBasicWacTests.java b/spring-test/src/test/java/org/springframework/test/context/web/AbstractBasicWacTests.java index de564e52c39..ea5c1628827 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/AbstractBasicWacTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/AbstractBasicWacTests.java @@ -32,9 +32,7 @@ import org.springframework.web.context.ServletContextAware; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.ServletWebRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -75,25 +73,24 @@ public abstract class AbstractBasicWacTests implements ServletContextAware { @Test public void basicWacFeatures() throws Exception { - assertNotNull("ServletContext should be set in the WAC.", wac.getServletContext()); + assertThat(wac.getServletContext()).as("ServletContext should be set in the WAC.").isNotNull(); - assertNotNull("ServletContext should have been set via ServletContextAware.", servletContext); + assertThat(servletContext).as("ServletContext should have been set via ServletContextAware.").isNotNull(); - assertNotNull("ServletContext should have been autowired from the WAC.", mockServletContext); - assertNotNull("MockHttpServletRequest should have been autowired from the WAC.", request); - assertNotNull("MockHttpServletResponse should have been autowired from the WAC.", response); - assertNotNull("MockHttpSession should have been autowired from the WAC.", session); - assertNotNull("ServletWebRequest should have been autowired from the WAC.", webRequest); + assertThat(mockServletContext).as("ServletContext should have been autowired from the WAC.").isNotNull(); + assertThat(request).as("MockHttpServletRequest should have been autowired from the WAC.").isNotNull(); + assertThat(response).as("MockHttpServletResponse should have been autowired from the WAC.").isNotNull(); + assertThat(session).as("MockHttpSession should have been autowired from the WAC.").isNotNull(); + assertThat(webRequest).as("ServletWebRequest should have been autowired from the WAC.").isNotNull(); Object rootWac = mockServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); - assertNotNull("Root WAC must be stored in the ServletContext as: " - + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, rootWac); - assertSame("test WAC and Root WAC in ServletContext must be the same object.", wac, rootWac); - assertSame("ServletContext instances must be the same object.", mockServletContext, wac.getServletContext()); - assertSame("ServletContext in the WAC and in the mock request", mockServletContext, request.getServletContext()); + assertThat(rootWac).as("Root WAC must be stored in the ServletContext as: " + + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE).isNotNull(); + assertThat(rootWac).as("test WAC and Root WAC in ServletContext must be the same object.").isSameAs(wac); + assertThat(wac.getServletContext()).as("ServletContext instances must be the same object.").isSameAs(mockServletContext); + assertThat(request.getServletContext()).as("ServletContext in the WAC and in the mock request").isSameAs(mockServletContext); - assertEquals("Getting real path for ServletContext resource.", - new File("src/main/webapp/index.jsp").getCanonicalPath(), mockServletContext.getRealPath("index.jsp")); + assertThat(mockServletContext.getRealPath("index.jsp")).as("Getting real path for ServletContext resource.").isEqualTo(new File("src/main/webapp/index.jsp").getCanonicalPath()); } diff --git a/spring-test/src/test/java/org/springframework/test/context/web/BasicAnnotationConfigWacTests.java b/spring-test/src/test/java/org/springframework/test/context/web/BasicAnnotationConfigWacTests.java index 806e7f415ef..d0c72e11e6a 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/BasicAnnotationConfigWacTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/BasicAnnotationConfigWacTests.java @@ -23,8 +23,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -52,13 +51,13 @@ public class BasicAnnotationConfigWacTests extends AbstractBasicWacTests { @Test public void fooEnigmaAutowired() { - assertEquals("enigma", foo); + assertThat(foo).isEqualTo("enigma"); } @Test public void servletContextAwareBeanProcessed() { - assertNotNull(servletContextAwareBean); - assertNotNull(servletContextAwareBean.servletContext); + assertThat(servletContextAwareBean).isNotNull(); + assertThat(servletContextAwareBean.servletContext).isNotNull(); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/web/BasicGroovyWacTests.java b/spring-test/src/test/java/org/springframework/test/context/web/BasicGroovyWacTests.java index ac78f21ffa9..69239d026ca 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/BasicGroovyWacTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/BasicGroovyWacTests.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -33,7 +33,7 @@ public class BasicGroovyWacTests extends AbstractBasicWacTests { @Test public void groovyFooAutowired() { - assertEquals("Groovy Foo", foo); + assertThat(foo).isEqualTo("Groovy Foo"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/web/BasicXmlWacTests.java b/spring-test/src/test/java/org/springframework/test/context/web/BasicXmlWacTests.java index dd7533262f1..c1e9ecb368c 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/BasicXmlWacTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/BasicXmlWacTests.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sam Brannen @@ -31,7 +31,7 @@ public class BasicXmlWacTests extends AbstractBasicWacTests { @Test public void fooBarAutowired() { - assertEquals("bar", foo); + assertThat(foo).isEqualTo("bar"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/web/JUnit4SpringContextWebTests.java b/spring-test/src/test/java/org/springframework/test/context/web/JUnit4SpringContextWebTests.java index 97a48eb1f78..1e1d5862244 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/JUnit4SpringContextWebTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/JUnit4SpringContextWebTests.java @@ -34,9 +34,7 @@ import org.springframework.web.context.ServletContextAware; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.ServletWebRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit-based integration tests that verify support for loading a @@ -90,31 +88,30 @@ public class JUnit4SpringContextWebTests extends AbstractJUnit4SpringContextTest @Test public void basicWacFeatures() throws Exception { - assertNotNull("ServletContext should be set in the WAC.", wac.getServletContext()); + assertThat(wac.getServletContext()).as("ServletContext should be set in the WAC.").isNotNull(); - assertNotNull("ServletContext should have been set via ServletContextAware.", servletContext); + assertThat(servletContext).as("ServletContext should have been set via ServletContextAware.").isNotNull(); - assertNotNull("ServletContext should have been autowired from the WAC.", mockServletContext); - assertNotNull("MockHttpServletRequest should have been autowired from the WAC.", request); - assertNotNull("MockHttpServletResponse should have been autowired from the WAC.", response); - assertNotNull("MockHttpSession should have been autowired from the WAC.", session); - assertNotNull("ServletWebRequest should have been autowired from the WAC.", webRequest); + assertThat(mockServletContext).as("ServletContext should have been autowired from the WAC.").isNotNull(); + assertThat(request).as("MockHttpServletRequest should have been autowired from the WAC.").isNotNull(); + assertThat(response).as("MockHttpServletResponse should have been autowired from the WAC.").isNotNull(); + assertThat(session).as("MockHttpSession should have been autowired from the WAC.").isNotNull(); + assertThat(webRequest).as("ServletWebRequest should have been autowired from the WAC.").isNotNull(); Object rootWac = mockServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); - assertNotNull("Root WAC must be stored in the ServletContext as: " - + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, rootWac); - assertSame("test WAC and Root WAC in ServletContext must be the same object.", wac, rootWac); - assertSame("ServletContext instances must be the same object.", mockServletContext, wac.getServletContext()); - assertSame("ServletContext in the WAC and in the mock request", mockServletContext, request.getServletContext()); + assertThat(rootWac).as("Root WAC must be stored in the ServletContext as: " + + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE).isNotNull(); + assertThat(rootWac).as("test WAC and Root WAC in ServletContext must be the same object.").isSameAs(wac); + assertThat(wac.getServletContext()).as("ServletContext instances must be the same object.").isSameAs(mockServletContext); + assertThat(request.getServletContext()).as("ServletContext in the WAC and in the mock request").isSameAs(mockServletContext); - assertEquals("Getting real path for ServletContext resource.", - new File("src/main/webapp/index.jsp").getCanonicalPath(), mockServletContext.getRealPath("index.jsp")); + assertThat(mockServletContext.getRealPath("index.jsp")).as("Getting real path for ServletContext resource.").isEqualTo(new File("src/main/webapp/index.jsp").getCanonicalPath()); } @Test public void fooEnigmaAutowired() { - assertEquals("enigma", foo); + assertThat(foo).isEqualTo("enigma"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/web/MetaAnnotationConfigWacTests.java b/spring-test/src/test/java/org/springframework/test/context/web/MetaAnnotationConfigWacTests.java index ebee044a545..2954dfc5b3d 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/MetaAnnotationConfigWacTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/MetaAnnotationConfigWacTests.java @@ -27,9 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration test that verifies meta-annotation support for {@link WebAppConfiguration} @@ -55,23 +53,22 @@ public class MetaAnnotationConfigWacTests { @Test public void fooEnigmaAutowired() { - assertEquals("enigma", foo); + assertThat(foo).isEqualTo("enigma"); } @Test public void basicWacFeatures() throws Exception { - assertNotNull("ServletContext should be set in the WAC.", wac.getServletContext()); + assertThat(wac.getServletContext()).as("ServletContext should be set in the WAC.").isNotNull(); - assertNotNull("ServletContext should have been autowired from the WAC.", mockServletContext); + assertThat(mockServletContext).as("ServletContext should have been autowired from the WAC.").isNotNull(); Object rootWac = mockServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); - assertNotNull("Root WAC must be stored in the ServletContext as: " - + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, rootWac); - assertSame("test WAC and Root WAC in ServletContext must be the same object.", wac, rootWac); - assertSame("ServletContext instances must be the same object.", mockServletContext, wac.getServletContext()); + assertThat(rootWac).as("Root WAC must be stored in the ServletContext as: " + + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE).isNotNull(); + assertThat(rootWac).as("test WAC and Root WAC in ServletContext must be the same object.").isSameAs(wac); + assertThat(wac.getServletContext()).as("ServletContext instances must be the same object.").isSameAs(mockServletContext); - assertEquals("Getting real path for ServletContext resource.", - new File("src/main/webapp/index.jsp").getCanonicalPath(), mockServletContext.getRealPath("index.jsp")); + assertThat(mockServletContext.getRealPath("index.jsp")).as("Getting real path for ServletContext resource.").isEqualTo(new File("src/main/webapp/index.jsp").getCanonicalPath()); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests.java b/spring-test/src/test/java/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests.java index 293d14d66d4..457bb260da2 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests.java @@ -27,9 +27,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.tests.sample.beans.TestBean; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that verify support for request and session scoped beans @@ -58,26 +56,26 @@ public class RequestAndSessionScopedBeansWacTests { final String beanName = "requestScopedTestBean"; final String contextPath = "/path"; - assertNull(request.getAttribute(beanName)); + assertThat(request.getAttribute(beanName)).isNull(); request.setContextPath(contextPath); TestBean testBean = wac.getBean(beanName, TestBean.class); - assertEquals(contextPath, testBean.getName()); - assertSame(testBean, request.getAttribute(beanName)); - assertSame(testBean, wac.getBean(beanName, TestBean.class)); + assertThat(testBean.getName()).isEqualTo(contextPath); + assertThat(request.getAttribute(beanName)).isSameAs(testBean); + assertThat(wac.getBean(beanName, TestBean.class)).isSameAs(testBean); } @Test public void sessionScope() throws Exception { final String beanName = "sessionScopedTestBean"; - assertNull(session.getAttribute(beanName)); + assertThat(session.getAttribute(beanName)).isNull(); TestBean testBean = wac.getBean(beanName, TestBean.class); - assertSame(testBean, session.getAttribute(beanName)); - assertSame(testBean, wac.getBean(beanName, TestBean.class)); + assertThat(session.getAttribute(beanName)).isSameAs(testBean); + assertThat(wac.getBean(beanName, TestBean.class)).isSameAs(testBean); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/web/ServletTestExecutionListenerJUnitIntegrationTests.java b/spring-test/src/test/java/org/springframework/test/context/web/ServletTestExecutionListenerJUnitIntegrationTests.java index 90fa475c2f8..f1acb92aa7d 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/ServletTestExecutionListenerJUnitIntegrationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/ServletTestExecutionListenerJUnitIntegrationTests.java @@ -27,7 +27,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit-based integration tests for {@link ServletTestExecutionListener}. @@ -72,8 +72,7 @@ public class ServletTestExecutionListenerJUnitIntegrationTests { } private void assertInjectedServletRequestEqualsRequestInRequestContextHolder() { - assertEquals("Injected ServletRequest must be stored in the RequestContextHolder", servletRequest, - ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()); + assertThat(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()).as("Injected ServletRequest must be stored in the RequestContextHolder").isEqualTo(servletRequest); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/web/ServletTestExecutionListenerTests.java b/spring-test/src/test/java/org/springframework/test/context/web/ServletTestExecutionListenerTests.java index 8d9ecfd6588..b2b3488d9b2 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/ServletTestExecutionListenerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/ServletTestExecutionListenerTests.java @@ -30,8 +30,7 @@ import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletWebRequest; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -173,26 +172,26 @@ public class ServletTestExecutionListenerTests { private RequestAttributes assertRequestAttributesExist() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); - assertNotNull("request attributes should exist", requestAttributes); + assertThat(requestAttributes).as("request attributes should exist").isNotNull(); return requestAttributes; } private void assertRequestAttributesDoNotExist() { - assertNull("request attributes should not exist", RequestContextHolder.getRequestAttributes()); + assertThat(RequestContextHolder.getRequestAttributes()).as("request attributes should not exist").isNull(); } private void assertSetUpOutsideOfStelAttributeExists() { RequestAttributes requestAttributes = assertRequestAttributesExist(); Object setUpOutsideOfStel = requestAttributes.getAttribute(SET_UP_OUTSIDE_OF_STEL, RequestAttributes.SCOPE_REQUEST); - assertNotNull(SET_UP_OUTSIDE_OF_STEL + " should exist as a request attribute", setUpOutsideOfStel); + assertThat(setUpOutsideOfStel).as(SET_UP_OUTSIDE_OF_STEL + " should exist as a request attribute").isNotNull(); } private void assertSetUpOutsideOfStelAttributeDoesNotExist() { RequestAttributes requestAttributes = assertRequestAttributesExist(); Object setUpOutsideOfStel = requestAttributes.getAttribute(SET_UP_OUTSIDE_OF_STEL, RequestAttributes.SCOPE_REQUEST); - assertNull(SET_UP_OUTSIDE_OF_STEL + " should NOT exist as a request attribute", setUpOutsideOfStel); + assertThat(setUpOutsideOfStel).as(SET_UP_OUTSIDE_OF_STEL + " should NOT exist as a request attribute").isNull(); } private void assertWebAppConfigTestCase() throws Exception { diff --git a/spring-test/src/test/java/org/springframework/test/context/web/WebAppConfigurationBootstrapWithTests.java b/spring-test/src/test/java/org/springframework/test/context/web/WebAppConfigurationBootstrapWithTests.java index 7d94c145981..73bf25dc844 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/WebAppConfigurationBootstrapWithTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/WebAppConfigurationBootstrapWithTests.java @@ -29,8 +29,7 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfigurationBootstrapWithTests.CustomWebTestContextBootstrapper; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * JUnit-based integration tests that verify support for loading a @@ -54,8 +53,8 @@ public class WebAppConfigurationBootstrapWithTests { public void webApplicationContextIsLoaded() { // from: src/test/webapp/resources/Spring.js Resource resource = wac.getResource("/resources/Spring.js"); - assertNotNull(resource); - assertTrue(resource.exists()); + assertThat(resource).isNotNull(); + assertThat(resource.exists()).isTrue(); } diff --git a/spring-test/src/test/java/org/springframework/test/context/web/socket/WebSocketServletServerContainerFactoryBeanTests.java b/spring-test/src/test/java/org/springframework/test/context/web/socket/WebSocketServletServerContainerFactoryBeanTests.java index f6e71bfd22e..1d580d3a35b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/socket/WebSocketServletServerContainerFactoryBeanTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/socket/WebSocketServletServerContainerFactoryBeanTests.java @@ -29,7 +29,7 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests that validate support for {@link ServletServerContainerFactoryBean} @@ -49,7 +49,7 @@ public class WebSocketServletServerContainerFactoryBeanTests { @Test public void servletServerContainerFactoryBeanSupport() { - assertEquals(42, serverContainer.getDefaultMaxTextMessageBufferSize()); + assertThat(serverContainer.getDefaultMaxTextMessageBufferSize()).isEqualTo(42); } diff --git a/spring-test/src/test/java/org/springframework/test/util/AopTestUtilsTests.java b/spring-test/src/test/java/org/springframework/test/util/AopTestUtilsTests.java index 1b919e7d312..a124770192d 100644 --- a/spring-test/src/test/java/org/springframework/test/util/AopTestUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/util/AopTestUtilsTests.java @@ -23,9 +23,6 @@ import org.springframework.aop.support.AopUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.springframework.test.util.AopTestUtils.getTargetObject; import static org.springframework.test.util.AopTestUtils.getUltimateTargetObject; @@ -49,31 +46,31 @@ public class AopTestUtilsTests { @Test public void getTargetObjectForNonProxiedObject() { Foo target = getTargetObject(foo); - assertSame(foo, target); + assertThat(target).isSameAs(foo); } @Test public void getTargetObjectWrappedInSingleJdkDynamicProxy() { Foo target = getTargetObject(jdkProxy(foo)); - assertSame(foo, target); + assertThat(target).isSameAs(foo); } @Test public void getTargetObjectWrappedInSingleCglibProxy() { Foo target = getTargetObject(cglibProxy(foo)); - assertSame(foo, target); + assertThat(target).isSameAs(foo); } @Test public void getTargetObjectWrappedInDoubleJdkDynamicProxy() { Foo target = getTargetObject(jdkProxy(jdkProxy(foo))); - assertNotSame(foo, target); + assertThat(target).isNotSameAs(foo); } @Test public void getTargetObjectWrappedInDoubleCglibProxy() { Foo target = getTargetObject(cglibProxy(cglibProxy(foo))); - assertNotSame(foo, target); + assertThat(target).isNotSameAs(foo); } @Test @@ -85,43 +82,43 @@ public class AopTestUtilsTests { @Test public void getUltimateTargetObjectForNonProxiedObject() { Foo target = getUltimateTargetObject(foo); - assertSame(foo, target); + assertThat(target).isSameAs(foo); } @Test public void getUltimateTargetObjectWrappedInSingleJdkDynamicProxy() { Foo target = getUltimateTargetObject(jdkProxy(foo)); - assertSame(foo, target); + assertThat(target).isSameAs(foo); } @Test public void getUltimateTargetObjectWrappedInSingleCglibProxy() { Foo target = getUltimateTargetObject(cglibProxy(foo)); - assertSame(foo, target); + assertThat(target).isSameAs(foo); } @Test public void getUltimateTargetObjectWrappedInDoubleJdkDynamicProxy() { Foo target = getUltimateTargetObject(jdkProxy(jdkProxy(foo))); - assertSame(foo, target); + assertThat(target).isSameAs(foo); } @Test public void getUltimateTargetObjectWrappedInDoubleCglibProxy() { Foo target = getUltimateTargetObject(cglibProxy(cglibProxy(foo))); - assertSame(foo, target); + assertThat(target).isSameAs(foo); } @Test public void getUltimateTargetObjectWrappedInCglibProxyWrappedInJdkDynamicProxy() { Foo target = getUltimateTargetObject(jdkProxy(cglibProxy(foo))); - assertSame(foo, target); + assertThat(target).isSameAs(foo); } @Test public void getUltimateTargetObjectWrappedInCglibProxyWrappedInDoubleJdkDynamicProxy() { Foo target = getUltimateTargetObject(jdkProxy(jdkProxy(cglibProxy(foo)))); - assertSame(foo, target); + assertThat(target).isSameAs(foo); } private Foo jdkProxy(Foo foo) { @@ -129,7 +126,7 @@ public class AopTestUtilsTests { pf.setTarget(foo); pf.addInterface(Foo.class); Foo proxy = (Foo) pf.getProxy(); - assertTrue("Proxy is a JDK dynamic proxy", AopUtils.isJdkDynamicProxy(proxy)); + assertThat(AopUtils.isJdkDynamicProxy(proxy)).as("Proxy is a JDK dynamic proxy").isTrue(); assertThat(proxy).isInstanceOf(Foo.class); return proxy; } @@ -139,7 +136,7 @@ public class AopTestUtilsTests { pf.setTarget(foo); pf.setProxyTargetClass(true); Foo proxy = (Foo) pf.getProxy(); - assertTrue("Proxy is a CGLIB proxy", AopUtils.isCglibProxy(proxy)); + assertThat(AopUtils.isCglibProxy(proxy)).as("Proxy is a CGLIB proxy").isTrue(); assertThat(proxy).isInstanceOf(FooImpl.class); return proxy; } diff --git a/spring-test/src/test/java/org/springframework/test/util/MetaAnnotationUtilsTests.java b/spring-test/src/test/java/org/springframework/test/util/MetaAnnotationUtilsTests.java index ae480c3fdbc..f07624edb36 100644 --- a/spring-test/src/test/java/org/springframework/test/util/MetaAnnotationUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/util/MetaAnnotationUtilsTests.java @@ -34,10 +34,7 @@ import org.springframework.test.util.MetaAnnotationUtils.AnnotationDescriptor; import org.springframework.test.util.MetaAnnotationUtils.UntypedAnnotationDescriptor; import org.springframework.transaction.annotation.Transactional; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptor; import static org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptorForTypes; @@ -66,13 +63,13 @@ public class MetaAnnotationUtilsTests { Class declaringClass, String name, Class composedAnnotationType) { AnnotationDescriptor descriptor = findAnnotationDescriptor(startClass, Component.class); - assertNotNull("AnnotationDescriptor should not be null", descriptor); - assertEquals("rootDeclaringClass", rootDeclaringClass, descriptor.getRootDeclaringClass()); - assertEquals("declaringClass", declaringClass, descriptor.getDeclaringClass()); - assertEquals("annotationType", Component.class, descriptor.getAnnotationType()); - assertEquals("component name", name, descriptor.getAnnotation().value()); - assertNotNull("composedAnnotation should not be null", descriptor.getComposedAnnotation()); - assertEquals("composedAnnotationType", composedAnnotationType, descriptor.getComposedAnnotationType()); + assertThat(descriptor).as("AnnotationDescriptor should not be null").isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).as("rootDeclaringClass").isEqualTo(rootDeclaringClass); + assertThat(descriptor.getDeclaringClass()).as("declaringClass").isEqualTo(declaringClass); + assertThat(descriptor.getAnnotationType()).as("annotationType").isEqualTo(Component.class); + assertThat(descriptor.getAnnotation().value()).as("component name").isEqualTo(name); + assertThat(descriptor.getComposedAnnotation()).as("composedAnnotation should not be null").isNotNull(); + assertThat(descriptor.getComposedAnnotationType()).as("composedAnnotationType").isEqualTo(composedAnnotationType); } private void assertAtComponentOnComposedAnnotationForMultipleCandidateTypes( @@ -98,28 +95,26 @@ public class MetaAnnotationUtilsTests { UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes( startClass, Service.class, annotationType, Order.class, Transactional.class); - assertNotNull("UntypedAnnotationDescriptor should not be null", descriptor); - assertEquals("rootDeclaringClass", rootDeclaringClass, descriptor.getRootDeclaringClass()); - assertEquals("declaringClass", declaringClass, descriptor.getDeclaringClass()); - assertEquals("annotationType", annotationType, descriptor.getAnnotationType()); - assertEquals("component name", name, ((Component) descriptor.getAnnotation()).value()); - assertNotNull("composedAnnotation should not be null", descriptor.getComposedAnnotation()); - assertEquals("composedAnnotationType", composedAnnotationType, descriptor.getComposedAnnotationType()); + assertThat(descriptor).as("UntypedAnnotationDescriptor should not be null").isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).as("rootDeclaringClass").isEqualTo(rootDeclaringClass); + assertThat(descriptor.getDeclaringClass()).as("declaringClass").isEqualTo(declaringClass); + assertThat(descriptor.getAnnotationType()).as("annotationType").isEqualTo(annotationType); + assertThat(((Component) descriptor.getAnnotation()).value()).as("component name").isEqualTo(name); + assertThat(descriptor.getComposedAnnotation()).as("composedAnnotation should not be null").isNotNull(); + assertThat(descriptor.getComposedAnnotationType()).as("composedAnnotationType").isEqualTo(composedAnnotationType); } @Test public void findAnnotationDescriptorWithNoAnnotationPresent() { - assertNull(findAnnotationDescriptor(NonAnnotatedInterface.class, Transactional.class)); - assertNull(findAnnotationDescriptor(NonAnnotatedClass.class, Transactional.class)); + assertThat(findAnnotationDescriptor(NonAnnotatedInterface.class, Transactional.class)).isNull(); + assertThat(findAnnotationDescriptor(NonAnnotatedClass.class, Transactional.class)).isNull(); } @Test public void findAnnotationDescriptorWithInheritedAnnotationOnClass() { // Note: @Transactional is inherited - assertEquals(InheritedAnnotationClass.class, - findAnnotationDescriptor(InheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()); - assertEquals(InheritedAnnotationClass.class, - findAnnotationDescriptor(SubInheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()); + assertThat(findAnnotationDescriptor(InheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()).isEqualTo(InheritedAnnotationClass.class); + assertThat(findAnnotationDescriptor(SubInheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()).isEqualTo(InheritedAnnotationClass.class); } @Test @@ -129,31 +124,29 @@ public class MetaAnnotationUtilsTests { AnnotationDescriptor descriptor = findAnnotationDescriptor(InheritedAnnotationInterface.class, Transactional.class); - assertNotNull(descriptor); - assertEquals(InheritedAnnotationInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(InheritedAnnotationInterface.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); descriptor = findAnnotationDescriptor(SubInheritedAnnotationInterface.class, Transactional.class); - assertNotNull(descriptor); - assertEquals(SubInheritedAnnotationInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(InheritedAnnotationInterface.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubInheritedAnnotationInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); descriptor = findAnnotationDescriptor(SubSubInheritedAnnotationInterface.class, Transactional.class); - assertNotNull(descriptor); - assertEquals(SubSubInheritedAnnotationInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(InheritedAnnotationInterface.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubSubInheritedAnnotationInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); } @Test public void findAnnotationDescriptorForNonInheritedAnnotationOnClass() { // Note: @Order is not inherited. - assertEquals(NonInheritedAnnotationClass.class, - findAnnotationDescriptor(NonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()); - assertEquals(NonInheritedAnnotationClass.class, - findAnnotationDescriptor(SubNonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()); + assertThat(findAnnotationDescriptor(NonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationClass.class); + assertThat(findAnnotationDescriptor(SubNonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationClass.class); } @Test @@ -163,16 +156,16 @@ public class MetaAnnotationUtilsTests { AnnotationDescriptor descriptor = findAnnotationDescriptor(NonInheritedAnnotationInterface.class, Order.class); - assertNotNull(descriptor); - assertEquals(NonInheritedAnnotationInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(NonInheritedAnnotationInterface.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); descriptor = findAnnotationDescriptor(SubNonInheritedAnnotationInterface.class, Order.class); - assertNotNull(descriptor); - assertEquals(SubNonInheritedAnnotationInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(NonInheritedAnnotationInterface.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubNonInheritedAnnotationInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); } @Test @@ -186,10 +179,10 @@ public class MetaAnnotationUtilsTests { AnnotationDescriptor descriptor = findAnnotationDescriptor( HasLocalAndMetaComponentAnnotation.class, annotationType); - assertEquals(HasLocalAndMetaComponentAnnotation.class, descriptor.getRootDeclaringClass()); - assertEquals(annotationType, descriptor.getAnnotationType()); - assertNull(descriptor.getComposedAnnotation()); - assertNull(descriptor.getComposedAnnotationType()); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(HasLocalAndMetaComponentAnnotation.class); + assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType); + assertThat(descriptor.getComposedAnnotation()).isNull(); + assertThat(descriptor.getComposedAnnotationType()).isNull(); } @Test @@ -203,11 +196,11 @@ public class MetaAnnotationUtilsTests { AnnotationDescriptor descriptor = findAnnotationDescriptor(ClassWithMetaAnnotatedInterface.class, Component.class); - assertNotNull(descriptor); - assertEquals(ClassWithMetaAnnotatedInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(Meta1.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); - assertEquals(Meta1.class, descriptor.getComposedAnnotation().annotationType()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(ClassWithMetaAnnotatedInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(Meta1.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); + assertThat(descriptor.getComposedAnnotation().annotationType()).isEqualTo(Meta1.class); } @Test @@ -215,15 +208,14 @@ public class MetaAnnotationUtilsTests { AnnotationDescriptor descriptor = findAnnotationDescriptor( MetaAnnotatedAndSuperAnnotatedContextConfigClass.class, ContextConfiguration.class); - assertNotNull("AnnotationDescriptor should not be null", descriptor); - assertEquals("rootDeclaringClass", MetaAnnotatedAndSuperAnnotatedContextConfigClass.class, descriptor.getRootDeclaringClass()); - assertEquals("declaringClass", MetaConfig.class, descriptor.getDeclaringClass()); - assertEquals("annotationType", ContextConfiguration.class, descriptor.getAnnotationType()); - assertNotNull("composedAnnotation should not be null", descriptor.getComposedAnnotation()); - assertEquals("composedAnnotationType", MetaConfig.class, descriptor.getComposedAnnotationType()); + assertThat(descriptor).as("AnnotationDescriptor should not be null").isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).as("rootDeclaringClass").isEqualTo(MetaAnnotatedAndSuperAnnotatedContextConfigClass.class); + assertThat(descriptor.getDeclaringClass()).as("declaringClass").isEqualTo(MetaConfig.class); + assertThat(descriptor.getAnnotationType()).as("annotationType").isEqualTo(ContextConfiguration.class); + assertThat(descriptor.getComposedAnnotation()).as("composedAnnotation should not be null").isNotNull(); + assertThat(descriptor.getComposedAnnotationType()).as("composedAnnotationType").isEqualTo(MetaConfig.class); - assertArrayEquals("configured classes", new Class[] {String.class}, - descriptor.getAnnotationAttributes().getClassArray("classes")); + assertThat(descriptor.getAnnotationAttributes().getClassArray("classes")).as("configured classes").isEqualTo(new Class[] {String.class}); } @Test @@ -263,7 +255,7 @@ public class MetaAnnotationUtilsTests { // InheritedAnnotationClass is NOT annotated or meta-annotated with @Component AnnotationDescriptor descriptor = findAnnotationDescriptor( InheritedAnnotationClass.class, Component.class); - assertNull("Should not find @Component on InheritedAnnotationClass", descriptor); + assertThat(descriptor).as("Should not find @Component on InheritedAnnotationClass").isNull(); } /** @@ -273,7 +265,7 @@ public class MetaAnnotationUtilsTests { public void findAnnotationDescriptorOnMetaCycleAnnotatedClassWithMissingTargetMetaAnnotation() { AnnotationDescriptor descriptor = findAnnotationDescriptor( MetaCycleAnnotatedClass.class, Component.class); - assertNull("Should not find @Component on MetaCycleAnnotatedClass", descriptor); + assertThat(descriptor).as("Should not find @Component on MetaCycleAnnotatedClass").isNull(); } // ------------------------------------------------------------------------- @@ -281,19 +273,16 @@ public class MetaAnnotationUtilsTests { @Test @SuppressWarnings("unchecked") public void findAnnotationDescriptorForTypesWithNoAnnotationPresent() { - assertNull(findAnnotationDescriptorForTypes(NonAnnotatedInterface.class, Transactional.class, Component.class)); - assertNull(findAnnotationDescriptorForTypes(NonAnnotatedClass.class, Transactional.class, Order.class)); + assertThat(findAnnotationDescriptorForTypes(NonAnnotatedInterface.class, Transactional.class, Component.class)).isNull(); + assertThat(findAnnotationDescriptorForTypes(NonAnnotatedClass.class, Transactional.class, Order.class)).isNull(); } @Test @SuppressWarnings("unchecked") public void findAnnotationDescriptorForTypesWithInheritedAnnotationOnClass() { // Note: @Transactional is inherited - assertEquals(InheritedAnnotationClass.class, - findAnnotationDescriptorForTypes(InheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()); - assertEquals( - InheritedAnnotationClass.class, - findAnnotationDescriptorForTypes(SubInheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()); + assertThat(findAnnotationDescriptorForTypes(InheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()).isEqualTo(InheritedAnnotationClass.class); + assertThat(findAnnotationDescriptorForTypes(SubInheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()).isEqualTo(InheritedAnnotationClass.class); } @Test @@ -304,32 +293,30 @@ public class MetaAnnotationUtilsTests { UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(InheritedAnnotationInterface.class, Transactional.class); - assertNotNull(descriptor); - assertEquals(InheritedAnnotationInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(InheritedAnnotationInterface.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); descriptor = findAnnotationDescriptorForTypes(SubInheritedAnnotationInterface.class, Transactional.class); - assertNotNull(descriptor); - assertEquals(SubInheritedAnnotationInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(InheritedAnnotationInterface.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubInheritedAnnotationInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); descriptor = findAnnotationDescriptorForTypes(SubSubInheritedAnnotationInterface.class, Transactional.class); - assertNotNull(descriptor); - assertEquals(SubSubInheritedAnnotationInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(InheritedAnnotationInterface.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubSubInheritedAnnotationInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); } @Test @SuppressWarnings("unchecked") public void findAnnotationDescriptorForTypesForNonInheritedAnnotationOnClass() { // Note: @Order is not inherited. - assertEquals(NonInheritedAnnotationClass.class, - findAnnotationDescriptorForTypes(NonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()); - assertEquals(NonInheritedAnnotationClass.class, - findAnnotationDescriptorForTypes(SubNonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()); + assertThat(findAnnotationDescriptorForTypes(NonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationClass.class); + assertThat(findAnnotationDescriptorForTypes(SubNonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationClass.class); } @Test @@ -340,16 +327,16 @@ public class MetaAnnotationUtilsTests { UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(NonInheritedAnnotationInterface.class, Order.class); - assertNotNull(descriptor); - assertEquals(NonInheritedAnnotationInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(NonInheritedAnnotationInterface.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); descriptor = findAnnotationDescriptorForTypes(SubNonInheritedAnnotationInterface.class, Order.class); - assertNotNull(descriptor); - assertEquals(SubNonInheritedAnnotationInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(NonInheritedAnnotationInterface.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubNonInheritedAnnotationInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); } @Test @@ -358,10 +345,10 @@ public class MetaAnnotationUtilsTests { Class annotationType = Component.class; UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes( HasLocalAndMetaComponentAnnotation.class, Transactional.class, annotationType, Order.class); - assertEquals(HasLocalAndMetaComponentAnnotation.class, descriptor.getRootDeclaringClass()); - assertEquals(annotationType, descriptor.getAnnotationType()); - assertNull(descriptor.getComposedAnnotation()); - assertNull(descriptor.getComposedAnnotationType()); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(HasLocalAndMetaComponentAnnotation.class); + assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType); + assertThat(descriptor.getComposedAnnotation()).isNull(); + assertThat(descriptor.getComposedAnnotationType()).isNull(); } @Test @@ -379,14 +366,13 @@ public class MetaAnnotationUtilsTests { UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(startClass, Service.class, ContextConfiguration.class, Order.class, Transactional.class); - assertNotNull(descriptor); - assertEquals(startClass, descriptor.getRootDeclaringClass()); - assertEquals(annotationType, descriptor.getAnnotationType()); - assertArrayEquals(new Class[] {}, ((ContextConfiguration) descriptor.getAnnotation()).value()); - assertArrayEquals(new Class[] {MetaConfig.DevConfig.class, MetaConfig.ProductionConfig.class}, - descriptor.getAnnotationAttributes().getClassArray("classes")); - assertNotNull(descriptor.getComposedAnnotation()); - assertEquals(MetaConfig.class, descriptor.getComposedAnnotationType()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(startClass); + assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType); + assertThat(((ContextConfiguration) descriptor.getAnnotation()).value()).isEqualTo(new Class[] {}); + assertThat(descriptor.getAnnotationAttributes().getClassArray("classes")).isEqualTo(new Class[] {MetaConfig.DevConfig.class, MetaConfig.ProductionConfig.class}); + assertThat(descriptor.getComposedAnnotation()).isNotNull(); + assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaConfig.class); } @Test @@ -398,14 +384,13 @@ public class MetaAnnotationUtilsTests { UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes( startClass, Service.class, ContextConfiguration.class, Order.class, Transactional.class); - assertNotNull(descriptor); - assertEquals(startClass, descriptor.getRootDeclaringClass()); - assertEquals(annotationType, descriptor.getAnnotationType()); - assertArrayEquals(new Class[] {}, ((ContextConfiguration) descriptor.getAnnotation()).value()); - assertArrayEquals(new Class[] {MetaAnnotationUtilsTests.class}, - descriptor.getAnnotationAttributes().getClassArray("classes")); - assertNotNull(descriptor.getComposedAnnotation()); - assertEquals(MetaConfig.class, descriptor.getComposedAnnotationType()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(startClass); + assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType); + assertThat(((ContextConfiguration) descriptor.getAnnotation()).value()).isEqualTo(new Class[] {}); + assertThat(descriptor.getAnnotationAttributes().getClassArray("classes")).isEqualTo(new Class[] {MetaAnnotationUtilsTests.class}); + assertThat(descriptor.getComposedAnnotation()).isNotNull(); + assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaConfig.class); } @Test @@ -422,11 +407,11 @@ public class MetaAnnotationUtilsTests { UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes( ClassWithMetaAnnotatedInterface.class, Service.class, Component.class, Order.class, Transactional.class); - assertNotNull(descriptor); - assertEquals(ClassWithMetaAnnotatedInterface.class, descriptor.getRootDeclaringClass()); - assertEquals(Meta1.class, descriptor.getDeclaringClass()); - assertEquals(rawAnnotation, descriptor.getAnnotation()); - assertEquals(Meta1.class, descriptor.getComposedAnnotation().annotationType()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(ClassWithMetaAnnotatedInterface.class); + assertThat(descriptor.getDeclaringClass()).isEqualTo(Meta1.class); + assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation); + assertThat(descriptor.getComposedAnnotation().annotationType()).isEqualTo(Meta1.class); } @Test @@ -472,7 +457,7 @@ public class MetaAnnotationUtilsTests { // @Service, or @Order, but it is annotated with @Transactional. UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes( InheritedAnnotationClass.class, Service.class, Component.class, Order.class); - assertNull("Should not find @Component on InheritedAnnotationClass", descriptor); + assertThat(descriptor).as("Should not find @Component on InheritedAnnotationClass").isNull(); } /** @@ -483,7 +468,7 @@ public class MetaAnnotationUtilsTests { public void findAnnotationDescriptorForTypesOnMetaCycleAnnotatedClassWithMissingTargetMetaAnnotation() { UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes( MetaCycleAnnotatedClass.class, Service.class, Component.class, Order.class); - assertNull("Should not find @Component on MetaCycleAnnotatedClass", descriptor); + assertThat(descriptor).as("Should not find @Component on MetaCycleAnnotatedClass").isNull(); } diff --git a/spring-test/src/test/java/org/springframework/test/util/OverriddenMetaAnnotationAttributesTests.java b/spring-test/src/test/java/org/springframework/test/util/OverriddenMetaAnnotationAttributesTests.java index b3da3795f8f..8c9ebd9dd37 100644 --- a/spring-test/src/test/java/org/springframework/test/util/OverriddenMetaAnnotationAttributesTests.java +++ b/spring-test/src/test/java/org/springframework/test/util/OverriddenMetaAnnotationAttributesTests.java @@ -25,11 +25,7 @@ import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.util.MetaAnnotationUtils.AnnotationDescriptor; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptor; /** @@ -49,15 +45,15 @@ public class OverriddenMetaAnnotationAttributesTests { Class declaringClass = MetaValueConfigTestCase.class; AnnotationDescriptor descriptor = findAnnotationDescriptor(declaringClass, ContextConfiguration.class); - assertNotNull(descriptor); - assertEquals(declaringClass, descriptor.getRootDeclaringClass()); - assertEquals(MetaValueConfig.class, descriptor.getComposedAnnotationType()); - assertEquals(ContextConfiguration.class, descriptor.getAnnotationType()); - assertNotNull(descriptor.getComposedAnnotation()); - assertEquals(MetaValueConfig.class, descriptor.getComposedAnnotationType()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass); + assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class); + assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class); + assertThat(descriptor.getComposedAnnotation()).isNotNull(); + assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class); // direct access to annotation value: - assertArrayEquals(new String[] { "foo.xml" }, descriptor.getAnnotation().value()); + assertThat(descriptor.getAnnotation().value()).isEqualTo(new String[] { "foo.xml" }); } @Test @@ -65,15 +61,15 @@ public class OverriddenMetaAnnotationAttributesTests { Class declaringClass = OverriddenMetaValueConfigTestCase.class; AnnotationDescriptor descriptor = findAnnotationDescriptor(declaringClass, ContextConfiguration.class); - assertNotNull(descriptor); - assertEquals(declaringClass, descriptor.getRootDeclaringClass()); - assertEquals(MetaValueConfig.class, descriptor.getComposedAnnotationType()); - assertEquals(ContextConfiguration.class, descriptor.getAnnotationType()); - assertNotNull(descriptor.getComposedAnnotation()); - assertEquals(MetaValueConfig.class, descriptor.getComposedAnnotationType()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass); + assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class); + assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class); + assertThat(descriptor.getComposedAnnotation()).isNotNull(); + assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class); // direct access to annotation value: - assertArrayEquals(new String[] { "foo.xml" }, descriptor.getAnnotation().value()); + assertThat(descriptor.getAnnotation().value()).isEqualTo(new String[] { "foo.xml" }); // overridden attribute: AnnotationAttributes attributes = descriptor.getAnnotationAttributes(); @@ -81,7 +77,7 @@ public class OverriddenMetaAnnotationAttributesTests { // NOTE: we would like to be able to override the 'value' attribute; however, // Spring currently does not allow overrides for the 'value' attribute. // See SPR-11393 for related discussions. - assertArrayEquals(new String[] { "foo.xml" }, attributes.getStringArray("value")); + assertThat(attributes.getStringArray("value")).isEqualTo(new String[] { "foo.xml" }); } @Test @@ -89,16 +85,16 @@ public class OverriddenMetaAnnotationAttributesTests { Class declaringClass = MetaLocationsConfigTestCase.class; AnnotationDescriptor descriptor = findAnnotationDescriptor(declaringClass, ContextConfiguration.class); - assertNotNull(descriptor); - assertEquals(declaringClass, descriptor.getRootDeclaringClass()); - assertEquals(MetaLocationsConfig.class, descriptor.getComposedAnnotationType()); - assertEquals(ContextConfiguration.class, descriptor.getAnnotationType()); - assertNotNull(descriptor.getComposedAnnotation()); - assertEquals(MetaLocationsConfig.class, descriptor.getComposedAnnotationType()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass); + assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class); + assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class); + assertThat(descriptor.getComposedAnnotation()).isNotNull(); + assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class); // direct access to annotation attributes: - assertArrayEquals(new String[] { "foo.xml" }, descriptor.getAnnotation().locations()); - assertFalse(descriptor.getAnnotation().inheritLocations()); + assertThat(descriptor.getAnnotation().locations()).isEqualTo(new String[] { "foo.xml" }); + assertThat(descriptor.getAnnotation().inheritLocations()).isFalse(); } @Test @@ -106,21 +102,21 @@ public class OverriddenMetaAnnotationAttributesTests { Class declaringClass = OverriddenMetaLocationsConfigTestCase.class; AnnotationDescriptor descriptor = findAnnotationDescriptor(declaringClass, ContextConfiguration.class); - assertNotNull(descriptor); - assertEquals(declaringClass, descriptor.getRootDeclaringClass()); - assertEquals(MetaLocationsConfig.class, descriptor.getComposedAnnotationType()); - assertEquals(ContextConfiguration.class, descriptor.getAnnotationType()); - assertNotNull(descriptor.getComposedAnnotation()); - assertEquals(MetaLocationsConfig.class, descriptor.getComposedAnnotationType()); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass); + assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class); + assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class); + assertThat(descriptor.getComposedAnnotation()).isNotNull(); + assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class); // direct access to annotation attributes: - assertArrayEquals(new String[] { "foo.xml" }, descriptor.getAnnotation().locations()); - assertFalse(descriptor.getAnnotation().inheritLocations()); + assertThat(descriptor.getAnnotation().locations()).isEqualTo(new String[] { "foo.xml" }); + assertThat(descriptor.getAnnotation().inheritLocations()).isFalse(); // overridden attributes: AnnotationAttributes attributes = descriptor.getAnnotationAttributes(); - assertArrayEquals(new String[] { "bar.xml" }, attributes.getStringArray("locations")); - assertTrue(attributes.getBoolean("inheritLocations")); + assertThat(attributes.getStringArray("locations")).isEqualTo(new String[] { "bar.xml" }); + assertThat(attributes.getBoolean("inheritLocations")).isTrue(); } diff --git a/spring-test/src/test/java/org/springframework/test/util/ReflectionTestUtilsTests.java b/spring-test/src/test/java/org/springframework/test/util/ReflectionTestUtilsTests.java index 5c4568309a4..5a5c9fe5cce 100644 --- a/spring-test/src/test/java/org/springframework/test/util/ReflectionTestUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/util/ReflectionTestUtilsTests.java @@ -28,12 +28,9 @@ import org.springframework.test.util.subpackage.Person; import org.springframework.test.util.subpackage.PersonEntity; import org.springframework.test.util.subpackage.StaticFields; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.springframework.test.util.ReflectionTestUtils.getField; import static org.springframework.test.util.ReflectionTestUtils.invokeGetterMethod; import static org.springframework.test.util.ReflectionTestUtils.invokeMethod; @@ -121,7 +118,7 @@ public class ReflectionTestUtilsTests { ProxyFactory pf = new ProxyFactory(this.person); pf.addInterface(Person.class); Person proxy = (Person) pf.getProxy(); - assertTrue("Proxy is a JDK dynamic proxy", AopUtils.isJdkDynamicProxy(proxy)); + assertThat(AopUtils.isJdkDynamicProxy(proxy)).as("Proxy is a JDK dynamic proxy").isTrue(); assertSetFieldAndGetFieldBehaviorForProxy(proxy, this.person); } @@ -130,7 +127,7 @@ public class ReflectionTestUtilsTests { ProxyFactory pf = new ProxyFactory(this.person); pf.setProxyTargetClass(true); Person proxy = (Person) pf.getProxy(); - assertTrue("Proxy is a CGLIB proxy", AopUtils.isCglibProxy(proxy)); + assertThat(AopUtils.isCglibProxy(proxy)).as("Proxy is a CGLIB proxy").isTrue(); assertSetFieldAndGetFieldBehaviorForProxy(proxy, this.person); } @@ -144,32 +141,32 @@ public class ReflectionTestUtilsTests { setField(person, "favoriteNumber", PI, Number.class); // Get reflectively - assertEquals(Long.valueOf(99), getField(person, "id")); - assertEquals("Tom", getField(person, "name")); - assertEquals(Integer.valueOf(42), getField(person, "age")); - assertEquals("blue", getField(person, "eyeColor")); - assertEquals(Boolean.TRUE, getField(person, "likesPets")); - assertEquals(PI, getField(person, "favoriteNumber")); + assertThat(getField(person, "id")).isEqualTo(Long.valueOf(99)); + assertThat(getField(person, "name")).isEqualTo("Tom"); + assertThat(getField(person, "age")).isEqualTo(Integer.valueOf(42)); + assertThat(getField(person, "eyeColor")).isEqualTo("blue"); + assertThat(getField(person, "likesPets")).isEqualTo(Boolean.TRUE); + assertThat(getField(person, "favoriteNumber")).isEqualTo(PI); // Get directly - assertEquals("ID (private field in a superclass)", 99, person.getId()); - assertEquals("name (protected field)", "Tom", person.getName()); - assertEquals("age (private field)", 42, person.getAge()); - assertEquals("eye color (package private field)", "blue", person.getEyeColor()); - assertEquals("'likes pets' flag (package private boolean field)", true, person.likesPets()); - assertEquals("'favorite number' (package field)", PI, person.getFavoriteNumber()); + assertThat(person.getId()).as("ID (private field in a superclass)").isEqualTo(99); + assertThat(person.getName()).as("name (protected field)").isEqualTo("Tom"); + assertThat(person.getAge()).as("age (private field)").isEqualTo(42); + assertThat(person.getEyeColor()).as("eye color (package private field)").isEqualTo("blue"); + assertThat(person.likesPets()).as("'likes pets' flag (package private boolean field)").isEqualTo(true); + assertThat(person.getFavoriteNumber()).as("'favorite number' (package field)").isEqualTo(PI); } private static void assertSetFieldAndGetFieldBehaviorForProxy(Person proxy, Person target) { assertSetFieldAndGetFieldBehavior(proxy); // Get directly from Target - assertEquals("ID (private field in a superclass)", 99, target.getId()); - assertEquals("name (protected field)", "Tom", target.getName()); - assertEquals("age (private field)", 42, target.getAge()); - assertEquals("eye color (package private field)", "blue", target.getEyeColor()); - assertEquals("'likes pets' flag (package private boolean field)", true, target.likesPets()); - assertEquals("'favorite number' (package field)", PI, target.getFavoriteNumber()); + assertThat(target.getId()).as("ID (private field in a superclass)").isEqualTo(99); + assertThat(target.getName()).as("name (protected field)").isEqualTo("Tom"); + assertThat(target.getAge()).as("age (private field)").isEqualTo(42); + assertThat(target.getEyeColor()).as("eye color (package private field)").isEqualTo("blue"); + assertThat(target.likesPets()).as("'likes pets' flag (package private boolean field)").isEqualTo(true); + assertThat(target.getFavoriteNumber()).as("'favorite number' (package field)").isEqualTo(PI); } @Test @@ -178,18 +175,18 @@ public class ReflectionTestUtilsTests { setField(person, "name", "Tom"); setField(person, "eyeColor", "blue", String.class); setField(person, "favoriteNumber", PI, Number.class); - assertNotNull(person.getName()); - assertNotNull(person.getEyeColor()); - assertNotNull(person.getFavoriteNumber()); + assertThat(person.getName()).isNotNull(); + assertThat(person.getEyeColor()).isNotNull(); + assertThat(person.getFavoriteNumber()).isNotNull(); // Set to null setField(person, "name", null, String.class); setField(person, "eyeColor", null, String.class); setField(person, "favoriteNumber", null, Number.class); - assertNull("name (protected field)", person.getName()); - assertNull("eye color (package private field)", person.getEyeColor()); - assertNull("'favorite number' (package field)", person.getFavoriteNumber()); + assertThat(person.getName()).as("name (protected field)").isNull(); + assertThat(person.getEyeColor()).as("eye color (package private field)").isNull(); + assertThat(person.getFavoriteNumber()).as("'favorite number' (package field)").isNull(); } @Test @@ -215,8 +212,8 @@ public class ReflectionTestUtilsTests { setField(StaticFields.class, "publicField", "xxx"); setField(StaticFields.class, "privateField", "yyy"); - assertEquals("public static field", "xxx", StaticFields.publicField); - assertEquals("private static field", "yyy", StaticFields.getPrivateField()); + assertThat(StaticFields.publicField).as("public static field").isEqualTo("xxx"); + assertThat(StaticFields.getPrivateField()).as("private static field").isEqualTo("yyy"); } @Test @@ -224,8 +221,8 @@ public class ReflectionTestUtilsTests { setField(StaticFields.class, "publicField", "xxx", String.class); setField(StaticFields.class, "privateField", "yyy", String.class); - assertEquals("public static field", "xxx", StaticFields.publicField); - assertEquals("private static field", "yyy", StaticFields.getPrivateField()); + assertThat(StaticFields.publicField).as("public static field").isEqualTo("xxx"); + assertThat(StaticFields.getPrivateField()).as("private static field").isEqualTo("yyy"); } @Test @@ -234,21 +231,21 @@ public class ReflectionTestUtilsTests { setField(staticFields, null, "publicField", "xxx", null); setField(staticFields, null, "privateField", "yyy", null); - assertEquals("public static field", "xxx", StaticFields.publicField); - assertEquals("private static field", "yyy", StaticFields.getPrivateField()); + assertThat(StaticFields.publicField).as("public static field").isEqualTo("xxx"); + assertThat(StaticFields.getPrivateField()).as("private static field").isEqualTo("yyy"); } @Test public void getStaticFieldViaClass() throws Exception { - assertEquals("public static field", "public", getField(StaticFields.class, "publicField")); - assertEquals("private static field", "private", getField(StaticFields.class, "privateField")); + assertThat(getField(StaticFields.class, "publicField")).as("public static field").isEqualTo("public"); + assertThat(getField(StaticFields.class, "privateField")).as("private static field").isEqualTo("private"); } @Test public void getStaticFieldViaInstance() throws Exception { StaticFields staticFields = new StaticFields(); - assertEquals("public static field", "public", getField(staticFields, "publicField")); - assertEquals("private static field", "private", getField(staticFields, "privateField")); + assertThat(getField(staticFields, "publicField")).as("public static field").isEqualTo("public"); + assertThat(getField(staticFields, "privateField")).as("private static field").isEqualTo("private"); } @Test @@ -260,19 +257,19 @@ public class ReflectionTestUtilsTests { invokeSetterMethod(person, "setLikesPets", Boolean.FALSE, boolean.class); invokeSetterMethod(person, "setFavoriteNumber", Integer.valueOf(42), Number.class); - assertEquals("ID (protected method in a superclass)", 1, person.getId()); - assertEquals("name (private method)", "Jerry", person.getName()); - assertEquals("age (protected method)", 33, person.getAge()); - assertEquals("eye color (package private method)", "green", person.getEyeColor()); - assertEquals("'likes pets' flag (protected method for a boolean)", false, person.likesPets()); - assertEquals("'favorite number' (protected method for a Number)", Integer.valueOf(42), person.getFavoriteNumber()); + assertThat(person.getId()).as("ID (protected method in a superclass)").isEqualTo(1); + assertThat(person.getName()).as("name (private method)").isEqualTo("Jerry"); + assertThat(person.getAge()).as("age (protected method)").isEqualTo(33); + assertThat(person.getEyeColor()).as("eye color (package private method)").isEqualTo("green"); + assertThat(person.likesPets()).as("'likes pets' flag (protected method for a boolean)").isEqualTo(false); + assertThat(person.getFavoriteNumber()).as("'favorite number' (protected method for a Number)").isEqualTo(Integer.valueOf(42)); - assertEquals(Long.valueOf(1), invokeGetterMethod(person, "getId")); - assertEquals("Jerry", invokeGetterMethod(person, "getName")); - assertEquals(Integer.valueOf(33), invokeGetterMethod(person, "getAge")); - assertEquals("green", invokeGetterMethod(person, "getEyeColor")); - assertEquals(Boolean.FALSE, invokeGetterMethod(person, "likesPets")); - assertEquals(Integer.valueOf(42), invokeGetterMethod(person, "getFavoriteNumber")); + assertThat(invokeGetterMethod(person, "getId")).isEqualTo(Long.valueOf(1)); + assertThat(invokeGetterMethod(person, "getName")).isEqualTo("Jerry"); + assertThat(invokeGetterMethod(person, "getAge")).isEqualTo(Integer.valueOf(33)); + assertThat(invokeGetterMethod(person, "getEyeColor")).isEqualTo("green"); + assertThat(invokeGetterMethod(person, "likesPets")).isEqualTo(Boolean.FALSE); + assertThat(invokeGetterMethod(person, "getFavoriteNumber")).isEqualTo(Integer.valueOf(42)); } @Test @@ -284,19 +281,19 @@ public class ReflectionTestUtilsTests { invokeSetterMethod(person, "likesPets", Boolean.TRUE); invokeSetterMethod(person, "favoriteNumber", PI, Number.class); - assertEquals("ID (protected method in a superclass)", 99, person.getId()); - assertEquals("name (private method)", "Tom", person.getName()); - assertEquals("age (protected method)", 42, person.getAge()); - assertEquals("eye color (package private method)", "blue", person.getEyeColor()); - assertEquals("'likes pets' flag (protected method for a boolean)", true, person.likesPets()); - assertEquals("'favorite number' (protected method for a Number)", PI, person.getFavoriteNumber()); + assertThat(person.getId()).as("ID (protected method in a superclass)").isEqualTo(99); + assertThat(person.getName()).as("name (private method)").isEqualTo("Tom"); + assertThat(person.getAge()).as("age (protected method)").isEqualTo(42); + assertThat(person.getEyeColor()).as("eye color (package private method)").isEqualTo("blue"); + assertThat(person.likesPets()).as("'likes pets' flag (protected method for a boolean)").isEqualTo(true); + assertThat(person.getFavoriteNumber()).as("'favorite number' (protected method for a Number)").isEqualTo(PI); - assertEquals(Long.valueOf(99), invokeGetterMethod(person, "id")); - assertEquals("Tom", invokeGetterMethod(person, "name")); - assertEquals(Integer.valueOf(42), invokeGetterMethod(person, "age")); - assertEquals("blue", invokeGetterMethod(person, "eyeColor")); - assertEquals(Boolean.TRUE, invokeGetterMethod(person, "likesPets")); - assertEquals(PI, invokeGetterMethod(person, "favoriteNumber")); + assertThat(invokeGetterMethod(person, "id")).isEqualTo(Long.valueOf(99)); + assertThat(invokeGetterMethod(person, "name")).isEqualTo("Tom"); + assertThat(invokeGetterMethod(person, "age")).isEqualTo(Integer.valueOf(42)); + assertThat(invokeGetterMethod(person, "eyeColor")).isEqualTo("blue"); + assertThat(invokeGetterMethod(person, "likesPets")).isEqualTo(Boolean.TRUE); + assertThat(invokeGetterMethod(person, "favoriteNumber")).isEqualTo(PI); } @Test @@ -305,9 +302,9 @@ public class ReflectionTestUtilsTests { invokeSetterMethod(person, "eyeColor", null, String.class); invokeSetterMethod(person, "favoriteNumber", null, Number.class); - assertNull("name (private method)", person.getName()); - assertNull("eye color (package private method)", person.getEyeColor()); - assertNull("'favorite number' (protected method for a Number)", person.getFavoriteNumber()); + assertThat(person.getName()).as("name (private method)").isNull(); + assertThat(person.getEyeColor()).as("eye color (package private method)").isNull(); + assertThat(person.getFavoriteNumber()).as("'favorite number' (protected method for a Number)").isNull(); } @Test @@ -332,7 +329,7 @@ public class ReflectionTestUtilsTests { public void invokeMethodWithAutoboxingAndUnboxing() { // IntelliJ IDEA 11 won't accept int assignment here Integer difference = invokeMethod(component, "subtract", 5, 2); - assertEquals("subtract(5, 2)", 3, difference.intValue()); + assertThat(difference.intValue()).as("subtract(5, 2)").isEqualTo(3); } @Test @@ -340,25 +337,25 @@ public class ReflectionTestUtilsTests { public void invokeMethodWithPrimitiveVarArgs() { // IntelliJ IDEA 11 won't accept int assignment here Integer sum = invokeMethod(component, "add", 1, 2, 3, 4); - assertEquals("add(1,2,3,4)", 10, sum.intValue()); + assertThat(sum.intValue()).as("add(1,2,3,4)").isEqualTo(10); } @Test public void invokeMethodWithPrimitiveVarArgsAsSingleArgument() { // IntelliJ IDEA 11 won't accept int assignment here Integer sum = invokeMethod(component, "add", new int[] { 1, 2, 3, 4 }); - assertEquals("add(1,2,3,4)", 10, sum.intValue()); + assertThat(sum.intValue()).as("add(1,2,3,4)").isEqualTo(10); } @Test public void invokeMethodSimulatingLifecycleEvents() { - assertNull("number", component.getNumber()); - assertNull("text", component.getText()); + assertThat(component.getNumber()).as("number").isNull(); + assertThat(component.getText()).as("text").isNull(); // Simulate autowiring a configuration method invokeMethod(component, "configure", Integer.valueOf(42), "enigma"); - assertEquals("number should have been configured", Integer.valueOf(42), component.getNumber()); - assertEquals("text should have been configured", "enigma", component.getText()); + assertThat(component.getNumber()).as("number should have been configured").isEqualTo(Integer.valueOf(42)); + assertThat(component.getText()).as("text should have been configured").isEqualTo("enigma"); // Simulate @PostConstruct life-cycle event invokeMethod(component, "init"); @@ -366,8 +363,8 @@ public class ReflectionTestUtilsTests { // Simulate @PreDestroy life-cycle event invokeMethod(component, "destroy"); - assertNull("number", component.getNumber()); - assertNull("text", component.getText()); + assertThat(component.getNumber()).as("number").isNull(); + assertThat(component.getText()).as("text").isNull(); } @Test @@ -401,34 +398,34 @@ public class ReflectionTestUtilsTests { @Test // SPR-14363 public void getFieldOnLegacyEntityWithSideEffectsInToString() { Object collaborator = getField(entity, "collaborator"); - assertNotNull(collaborator); + assertThat(collaborator).isNotNull(); } @Test // SPR-9571 and SPR-14363 public void setFieldOnLegacyEntityWithSideEffectsInToString() { String testCollaborator = "test collaborator"; setField(entity, "collaborator", testCollaborator, Object.class); - assertTrue(entity.toString().contains(testCollaborator)); + assertThat(entity.toString().contains(testCollaborator)).isTrue(); } @Test // SPR-14363 public void invokeMethodOnLegacyEntityWithSideEffectsInToString() { invokeMethod(entity, "configure", Integer.valueOf(42), "enigma"); - assertEquals("number should have been configured", Integer.valueOf(42), entity.getNumber()); - assertEquals("text should have been configured", "enigma", entity.getText()); + assertThat(entity.getNumber()).as("number should have been configured").isEqualTo(Integer.valueOf(42)); + assertThat(entity.getText()).as("text should have been configured").isEqualTo("enigma"); } @Test // SPR-14363 public void invokeGetterMethodOnLegacyEntityWithSideEffectsInToString() { Object collaborator = invokeGetterMethod(entity, "collaborator"); - assertNotNull(collaborator); + assertThat(collaborator).isNotNull(); } @Test // SPR-14363 public void invokeSetterMethodOnLegacyEntityWithSideEffectsInToString() { String testCollaborator = "test collaborator"; invokeSetterMethod(entity, "collaborator", testCollaborator); - assertTrue(entity.toString().contains(testCollaborator)); + assertThat(entity.toString().contains(testCollaborator)).isTrue(); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/DefaultRequestExpectationTests.java b/spring-test/src/test/java/org/springframework/test/web/client/DefaultRequestExpectationTests.java index 02ff9a61746..75bc183d13d 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/DefaultRequestExpectationTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/DefaultRequestExpectationTests.java @@ -24,9 +24,8 @@ import org.junit.Test; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.springframework.http.HttpMethod.GET; import static org.springframework.http.HttpMethod.POST; import static org.springframework.test.web.client.ExpectedCount.once; @@ -63,10 +62,10 @@ public class DefaultRequestExpectationTests { expectation.andRespond(withSuccess()); expectation.incrementAndValidate(); - assertTrue(expectation.hasRemainingCount()); + assertThat(expectation.hasRemainingCount()).isTrue(); expectation.incrementAndValidate(); - assertFalse(expectation.hasRemainingCount()); + assertThat(expectation.hasRemainingCount()).isFalse(); } @Test @@ -75,10 +74,10 @@ public class DefaultRequestExpectationTests { expectation.andRespond(withSuccess()); expectation.incrementAndValidate(); - assertFalse(expectation.isSatisfied()); + assertThat(expectation.isSatisfied()).isFalse(); expectation.incrementAndValidate(); - assertTrue(expectation.isSatisfied()); + assertThat(expectation.isSatisfied()).isTrue(); } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/SimpleRequestExpectationManagerTests.java b/spring-test/src/test/java/org/springframework/test/web/client/SimpleRequestExpectationManagerTests.java index 49bc54df729..a98a1c4dd90 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/SimpleRequestExpectationManagerTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/SimpleRequestExpectationManagerTests.java @@ -26,8 +26,8 @@ import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.mock.http.client.MockClientHttpRequest; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; import static org.springframework.http.HttpMethod.GET; import static org.springframework.http.HttpMethod.POST; import static org.springframework.test.web.client.ExpectedCount.max; @@ -55,8 +55,8 @@ public class SimpleRequestExpectationManagerTests { this.manager.validateRequest(createRequest(GET, "/foo")); } catch (AssertionError error) { - assertEquals("No further requests expected: HTTP GET /foo\n" + - "0 request(s) executed.\n", error.getMessage()); + assertThat(error.getMessage()).isEqualTo(("No further requests expected: HTTP GET /foo\n" + + "0 request(s) executed.\n")); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/UnorderedRequestExpectationManagerTests.java b/spring-test/src/test/java/org/springframework/test/web/client/UnorderedRequestExpectationManagerTests.java index 7ac77dec637..f40c6a60436 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/UnorderedRequestExpectationManagerTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/UnorderedRequestExpectationManagerTests.java @@ -24,8 +24,8 @@ import org.junit.Test; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; import static org.springframework.http.HttpMethod.GET; import static org.springframework.test.web.client.ExpectedCount.max; import static org.springframework.test.web.client.ExpectedCount.min; @@ -51,8 +51,8 @@ public class UnorderedRequestExpectationManagerTests { this.manager.validateRequest(createRequest(GET, "/foo")); } catch (AssertionError error) { - assertEquals("No further requests expected: HTTP GET /foo\n" + - "0 request(s) executed.\n", error.getMessage()); + assertThat(error.getMessage()).isEqualTo(("No further requests expected: HTTP GET /foo\n" + + "0 request(s) executed.\n")); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/response/ResponseCreatorsTests.java b/spring-test/src/test/java/org/springframework/test/web/client/response/ResponseCreatorsTests.java index f3d5e94298f..0586765a649 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/response/ResponseCreatorsTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/response/ResponseCreatorsTests.java @@ -25,10 +25,7 @@ import org.springframework.http.MediaType; import org.springframework.mock.http.client.MockClientHttpResponse; import org.springframework.util.StreamUtils; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for the {@link MockRestResponseCreators} static factory methods. @@ -41,9 +38,9 @@ public class ResponseCreatorsTests { public void success() throws Exception { MockClientHttpResponse response = (MockClientHttpResponse) MockRestResponseCreators.withSuccess().createResponse(null); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertTrue(response.getHeaders().isEmpty()); - assertEquals(0, StreamUtils.copyToByteArray(response.getBody()).length); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().isEmpty()).isTrue(); + assertThat(StreamUtils.copyToByteArray(response.getBody()).length).isEqualTo(0); } @Test @@ -51,9 +48,9 @@ public class ResponseCreatorsTests { DefaultResponseCreator responseCreator = MockRestResponseCreators.withSuccess("foo", MediaType.TEXT_PLAIN); MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertEquals(MediaType.TEXT_PLAIN, response.getHeaders().getContentType()); - assertArrayEquals("foo".getBytes(), StreamUtils.copyToByteArray(response.getBody())); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(StreamUtils.copyToByteArray(response.getBody())).isEqualTo("foo".getBytes()); } @Test @@ -61,9 +58,9 @@ public class ResponseCreatorsTests { DefaultResponseCreator responseCreator = MockRestResponseCreators.withSuccess("foo", null); MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertNull(response.getHeaders().getContentType()); - assertArrayEquals("foo".getBytes(), StreamUtils.copyToByteArray(response.getBody())); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().getContentType()).isNull(); + assertThat(StreamUtils.copyToByteArray(response.getBody())).isEqualTo("foo".getBytes()); } @Test @@ -72,9 +69,9 @@ public class ResponseCreatorsTests { DefaultResponseCreator responseCreator = MockRestResponseCreators.withCreatedEntity(location); MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null); - assertEquals(HttpStatus.CREATED, response.getStatusCode()); - assertEquals(location, response.getHeaders().getLocation()); - assertEquals(0, StreamUtils.copyToByteArray(response.getBody()).length); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); + assertThat(response.getHeaders().getLocation()).isEqualTo(location); + assertThat(StreamUtils.copyToByteArray(response.getBody()).length).isEqualTo(0); } @Test @@ -82,9 +79,9 @@ public class ResponseCreatorsTests { DefaultResponseCreator responseCreator = MockRestResponseCreators.withNoContent(); MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - assertTrue(response.getHeaders().isEmpty()); - assertEquals(0, StreamUtils.copyToByteArray(response.getBody()).length); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); + assertThat(response.getHeaders().isEmpty()).isTrue(); + assertThat(StreamUtils.copyToByteArray(response.getBody()).length).isEqualTo(0); } @Test @@ -92,9 +89,9 @@ public class ResponseCreatorsTests { DefaultResponseCreator responseCreator = MockRestResponseCreators.withBadRequest(); MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null); - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - assertTrue(response.getHeaders().isEmpty()); - assertEquals(0, StreamUtils.copyToByteArray(response.getBody()).length); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(response.getHeaders().isEmpty()).isTrue(); + assertThat(StreamUtils.copyToByteArray(response.getBody()).length).isEqualTo(0); } @Test @@ -102,9 +99,9 @@ public class ResponseCreatorsTests { DefaultResponseCreator responseCreator = MockRestResponseCreators.withUnauthorizedRequest(); MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null); - assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); - assertTrue(response.getHeaders().isEmpty()); - assertEquals(0, StreamUtils.copyToByteArray(response.getBody()).length); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(response.getHeaders().isEmpty()).isTrue(); + assertThat(StreamUtils.copyToByteArray(response.getBody()).length).isEqualTo(0); } @Test @@ -112,9 +109,9 @@ public class ResponseCreatorsTests { DefaultResponseCreator responseCreator = MockRestResponseCreators.withServerError(); MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getHeaders().isEmpty()); - assertEquals(0, StreamUtils.copyToByteArray(response.getBody()).length); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + assertThat(response.getHeaders().isEmpty()).isTrue(); + assertThat(StreamUtils.copyToByteArray(response.getBody()).length).isEqualTo(0); } @Test @@ -122,9 +119,9 @@ public class ResponseCreatorsTests { DefaultResponseCreator responseCreator = MockRestResponseCreators.withStatus(HttpStatus.FORBIDDEN); MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null); - assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); - assertTrue(response.getHeaders().isEmpty()); - assertEquals(0, StreamUtils.copyToByteArray(response.getBody()).length); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(response.getHeaders().isEmpty()).isTrue(); + assertThat(StreamUtils.copyToByteArray(response.getBody()).length).isEqualTo(0); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/samples/MockMvcClientHttpRequestFactoryTests.java b/spring-test/src/test/java/org/springframework/test/web/client/samples/MockMvcClientHttpRequestFactoryTests.java index b1184d71065..3b3c60a4d92 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/samples/MockMvcClientHttpRequestFactoryTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/samples/MockMvcClientHttpRequestFactoryTests.java @@ -40,7 +40,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** @@ -71,7 +71,7 @@ public class MockMvcClientHttpRequestFactoryTests { public void test() throws Exception { RestTemplate template = new RestTemplate(new MockMvcClientHttpRequestFactory(this.mockMvc)); String result = template.getForObject("/foo", String.class); - assertEquals("bar", result); + assertThat(result).isEqualTo("bar"); } @Test @@ -80,7 +80,7 @@ public class MockMvcClientHttpRequestFactoryTests { org.springframework.web.client.AsyncRestTemplate template = new org.springframework.web.client.AsyncRestTemplate( new MockMvcClientHttpRequestFactory(this.mockMvc)); ListenableFuture> entity = template.getForEntity("/foo", String.class); - assertEquals("bar", entity.get().getBody()); + assertThat(entity.get().getBody()).isEqualTo("bar"); } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleAsyncTests.java b/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleAsyncTests.java index 736a0a621bd..c976b1804e5 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleAsyncTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleAsyncTests.java @@ -27,7 +27,7 @@ import org.springframework.test.web.Person; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.util.concurrent.ListenableFuture; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.client.ExpectedCount.manyTimes; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; @@ -137,7 +137,7 @@ public class SampleAsyncTests { this.mockServer.verify(); } catch (AssertionError error) { - assertTrue(error.getMessage(), error.getMessage().contains("2 unsatisfied expectation(s)")); + assertThat(error.getMessage().contains("2 unsatisfied expectation(s)")).as(error.getMessage()).isTrue(); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleTests.java b/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleTests.java index 246c683a7c9..d05d408cb8b 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/samples/SampleTests.java @@ -34,9 +34,8 @@ import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.util.FileCopyUtils; import org.springframework.web.client.RestTemplate; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.springframework.test.web.client.ExpectedCount.manyTimes; import static org.springframework.test.web.client.ExpectedCount.never; import static org.springframework.test.web.client.ExpectedCount.once; @@ -178,7 +177,7 @@ public class SampleTests { this.mockServer.verify(); } catch (AssertionError error) { - assertTrue(error.getMessage(), error.getMessage().contains("2 unsatisfied expectation(s)")); + assertThat(error.getMessage().contains("2 unsatisfied expectation(s)")).as(error.getMessage()).isTrue(); } } @@ -220,7 +219,7 @@ public class SampleTests { ClientHttpResponse response = execution.execute(request, body); byte[] expected = FileCopyUtils.copyToByteArray(this.resource.getInputStream()); byte[] actual = FileCopyUtils.copyToByteArray(response.getBody()); - assertEquals(new String(expected), new String(actual)); + assertThat(new String(actual)).isEqualTo(new String(expected)); return response; } } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/samples/matchers/ContentRequestMatchersIntegrationTests.java b/spring-test/src/test/java/org/springframework/test/web/client/samples/matchers/ContentRequestMatchersIntegrationTests.java index f053a580af4..16c21ddb99f 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/samples/matchers/ContentRequestMatchersIntegrationTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/samples/matchers/ContentRequestMatchersIntegrationTests.java @@ -31,8 +31,8 @@ import org.springframework.test.web.Person; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertTrue; import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; @@ -78,7 +78,7 @@ public class ContentRequestMatchersIntegrationTests { } catch (AssertionError error) { String message = error.getMessage(); - assertTrue(message, message.startsWith("Content type expected:")); + assertThat(message.startsWith("Content type expected:")).as(message).isTrue(); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/DefaultControllerSpecTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/DefaultControllerSpecTests.java index fe8bfa3356e..e4ca95e6828 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/DefaultControllerSpecTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/DefaultControllerSpecTests.java @@ -33,7 +33,7 @@ import org.springframework.web.reactive.config.PathMatchConfigurer; import org.springframework.web.reactive.config.ViewResolverRegistry; import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link DefaultControllerSpec}. @@ -92,13 +92,13 @@ public class DefaultControllerSpecTests { .viewResolvers(viewResolverConsumer) .build(); - assertNotNull(argumentResolverConsumer.getValue()); - assertNotNull(contenTypeResolverConsumer.getValue()); - assertNotNull(corsRegistryConsumer.getValue()); - assertNotNull(formatterConsumer.getValue()); - assertNotNull(codecsConsumer.getValue()); - assertNotNull(pathMatchingConsumer.getValue()); - assertNotNull(viewResolverConsumer.getValue()); + assertThat(argumentResolverConsumer.getValue()).isNotNull(); + assertThat(contenTypeResolverConsumer.getValue()).isNotNull(); + assertThat(corsRegistryConsumer.getValue()).isNotNull(); + assertThat(formatterConsumer.getValue()).isNotNull(); + assertThat(codecsConsumer.getValue()).isNotNull(); + assertThat(pathMatchingConsumer.getValue()).isNotNull(); + assertThat(viewResolverConsumer.getValue()).isNotNull(); } diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/HttpHandlerConnectorTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/HttpHandlerConnectorTests.java index 6b0c175127a..611d6d23747 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/HttpHandlerConnectorTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/HttpHandlerConnectorTests.java @@ -41,7 +41,7 @@ import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link HttpHandlerConnector}. @@ -66,16 +66,16 @@ public class HttpHandlerConnectorTests { }).block(Duration.ofSeconds(5)); MockServerHttpRequest request = (MockServerHttpRequest) handler.getSavedRequest(); - assertEquals(HttpMethod.POST, request.getMethod()); - assertEquals("/custom-path", request.getURI().toString()); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); + assertThat(request.getURI().toString()).isEqualTo("/custom-path"); HttpHeaders headers = request.getHeaders(); - assertEquals(Arrays.asList("h0", "h1"), headers.get("custom-header")); - assertEquals(new HttpCookie("custom-cookie", "c0"), request.getCookies().getFirst("custom-cookie")); - assertEquals(Collections.singletonList("custom-cookie=c0"), headers.get(HttpHeaders.COOKIE)); + assertThat(headers.get("custom-header")).isEqualTo(Arrays.asList("h0", "h1")); + assertThat(request.getCookies().getFirst("custom-cookie")).isEqualTo(new HttpCookie("custom-cookie", "c0")); + assertThat(headers.get(HttpHeaders.COOKIE)).isEqualTo(Collections.singletonList("custom-cookie=c0")); DataBuffer buffer = request.getBody().blockFirst(Duration.ZERO); - assertEquals("Custom body", DataBufferTestUtils.dumpString(buffer, UTF_8)); + assertThat(DataBufferTestUtils.dumpString(buffer, UTF_8)).isEqualTo("Custom body"); } @Test @@ -94,14 +94,14 @@ public class HttpHandlerConnectorTests { .connect(HttpMethod.GET, URI.create("/custom-path"), ReactiveHttpOutputMessage::setComplete) .block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); HttpHeaders headers = response.getHeaders(); - assertEquals(Arrays.asList("h0", "h1"), headers.get("custom-header")); - assertEquals(cookie, response.getCookies().getFirst("custom-cookie")); - assertEquals(Collections.singletonList("custom-cookie=c0"), headers.get(HttpHeaders.SET_COOKIE)); + assertThat(headers.get("custom-header")).isEqualTo(Arrays.asList("h0", "h1")); + assertThat(response.getCookies().getFirst("custom-cookie")).isEqualTo(cookie); + assertThat(headers.get(HttpHeaders.SET_COOKIE)).isEqualTo(Collections.singletonList("custom-cookie=c0")); DataBuffer buffer = response.getBody().blockFirst(Duration.ZERO); - assertEquals("Custom body", DataBufferTestUtils.dumpString(buffer, UTF_8)); + assertThat(DataBufferTestUtils.dumpString(buffer, UTF_8)).isEqualTo("Custom body"); } private DataBuffer toDataBuffer(String body) { diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/MockServerTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/MockServerTests.java index 02309af09e5..517da2a73f3 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/MockServerTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/MockServerTests.java @@ -30,8 +30,7 @@ import org.springframework.http.ResponseCookie; import org.springframework.http.server.reactive.ServerHttpResponse; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Test scenarios involving a mock server. @@ -99,17 +98,17 @@ public class MockServerTests { mutatedBuilder.defaultCookie("baz", "qux"); WebTestClient clientFromMutatedBuilder = mutatedBuilder.build(); - client1.mutate().filters(filters -> assertEquals(1, filters.size())); - client1.mutate().defaultHeaders(headers -> assertEquals(1, headers.size())); - client1.mutate().defaultCookies(cookies -> assertEquals(1, cookies.size())); + client1.mutate().filters(filters -> assertThat(filters.size()).isEqualTo(1)); + client1.mutate().defaultHeaders(headers -> assertThat(headers.size()).isEqualTo(1)); + client1.mutate().defaultCookies(cookies -> assertThat(cookies.size()).isEqualTo(1)); - client2.mutate().filters(filters -> assertEquals(2, filters.size())); - client2.mutate().defaultHeaders(headers -> assertEquals(2, headers.size())); - client2.mutate().defaultCookies(cookies -> assertEquals(2, cookies.size())); + client2.mutate().filters(filters -> assertThat(filters.size()).isEqualTo(2)); + client2.mutate().defaultHeaders(headers -> assertThat(headers.size()).isEqualTo(2)); + client2.mutate().defaultCookies(cookies -> assertThat(cookies.size()).isEqualTo(2)); - clientFromMutatedBuilder.mutate().filters(filters -> assertEquals(2, filters.size())); - clientFromMutatedBuilder.mutate().defaultHeaders(headers -> assertEquals(2, headers.size())); - clientFromMutatedBuilder.mutate().defaultCookies(cookies -> assertEquals(2, cookies.size())); + clientFromMutatedBuilder.mutate().filters(filters -> assertThat(filters.size()).isEqualTo(2)); + clientFromMutatedBuilder.mutate().defaultHeaders(headers -> assertThat(headers.size()).isEqualTo(2)); + clientFromMutatedBuilder.mutate().defaultCookies(cookies -> assertThat(cookies.size()).isEqualTo(2)); } @Test // SPR-16124 @@ -134,8 +133,7 @@ public class MockServerTests { .expectHeader().valueEquals(HttpHeaders.SET_COOKIE, "a=alpha; Path=/pathA", "b=beta; Path=/pathB") .expectBody().isEmpty(); - assertEquals(Arrays.asList("a=alpha", "b=beta"), - result.getRequestHeaders().get(HttpHeaders.COOKIE)); + assertThat(result.getRequestHeaders().get(HttpHeaders.COOKIE)).isEqualTo(Arrays.asList("a=alpha", "b=beta")); } @Test @@ -156,8 +154,8 @@ public class MockServerTests { // Get the raw content without consuming the response body flux.. byte[] bytes = result.getResponseBodyContent(); - assertNotNull(bytes); - assertEquals("body", new String(bytes, UTF_8)); + assertThat(bytes).isNotNull(); + assertThat(new String(bytes, UTF_8)).isEqualTo("body"); } diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/WiretapConnectorTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/WiretapConnectorTests.java index c7f1ee72075..7898697816c 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/WiretapConnectorTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/WiretapConnectorTests.java @@ -34,7 +34,7 @@ import org.springframework.web.reactive.function.client.ExchangeFunction; import org.springframework.web.reactive.function.client.ExchangeFunctions; import static java.time.Duration.ofMillis; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link WiretapConnector}. @@ -59,8 +59,8 @@ public class WiretapConnectorTests { WiretapConnector.Info actual = wiretapConnector.claimRequest("1"); ExchangeResult result = actual.createExchangeResult(Duration.ZERO, null); - assertEquals(HttpMethod.GET, result.getMethod()); - assertEquals("/test", result.getUrl().toString()); + assertThat(result.getMethod()).isEqualTo(HttpMethod.GET); + assertThat(result.getUrl().toString()).isEqualTo("/test"); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ErrorTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ErrorTests.java index 0c745f50534..83d61e8de47 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ErrorTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ErrorTests.java @@ -29,8 +29,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests with error status codes or error conditions. @@ -70,8 +69,8 @@ public class ErrorTests { .expectBody().isEmpty(); byte[] content = result.getRequestBodyContent(); - assertNotNull(content); - assertEquals("{\"name\":\"Dan\"}", new String(content, StandardCharsets.UTF_8)); + assertThat(content).isNotNull(); + assertThat(new String(content, StandardCharsets.UTF_8)).isEqualTo("{\"name\":\"Dan\"}"); } diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ResponseEntityTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ResponseEntityTests.java index 7f616e9f3bc..7a1361cd5a6 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ResponseEntityTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ResponseEntityTests.java @@ -41,7 +41,6 @@ import org.springframework.web.bind.annotation.RestController; import static java.time.Duration.ofMillis; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; import static org.springframework.http.MediaType.TEXT_EVENT_STREAM; /** @@ -83,7 +82,7 @@ public class ResponseEntityTests { .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody(Person.class) - .consumeWith(result -> assertEquals(new Person("John"), result.getResponseBody())); + .consumeWith(result -> assertThat(result.getResponseBody()).isEqualTo(new Person("John"))); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/AbstractWebRequestMatcherTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/AbstractWebRequestMatcherTests.java index 38f4f355bdc..494c156641d 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/AbstractWebRequestMatcherTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/AbstractWebRequestMatcherTests.java @@ -21,8 +21,7 @@ import java.net.URL; import com.gargoylesoftware.htmlunit.WebRequest; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Abstract base class for testing {@link WebRequestMatcher} implementations. @@ -33,11 +32,11 @@ import static org.junit.Assert.assertTrue; public class AbstractWebRequestMatcherTests { protected void assertMatches(WebRequestMatcher matcher, String url) throws MalformedURLException { - assertTrue(matcher.matches(new WebRequest(new URL(url)))); + assertThat(matcher.matches(new WebRequest(new URL(url)))).isTrue(); } protected void assertDoesNotMatch(WebRequestMatcher matcher, String url) throws MalformedURLException { - assertFalse(matcher.matches(new WebRequest(new URL(url)))); + assertThat(matcher.matches(new WebRequest(new URL(url)))).isFalse(); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/webdriver/MockMvcHtmlUnitDriverBuilderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/webdriver/MockMvcHtmlUnitDriverBuilderTests.java index c978f21f33c..882fa4e6bda 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/webdriver/MockMvcHtmlUnitDriverBuilderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/webdriver/MockMvcHtmlUnitDriverBuilderTests.java @@ -42,8 +42,6 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Integration tests for {@link MockMvcHtmlUnitDriverBuilder}. @@ -105,13 +103,13 @@ public class MockMvcHtmlUnitDriverBuilderTests { @Test public void javaScriptEnabledByDefault() { this.driver = MockMvcHtmlUnitDriverBuilder.mockMvcSetup(this.mockMvc).build(); - assertTrue(this.driver.isJavascriptEnabled()); + assertThat(this.driver.isJavascriptEnabled()).isTrue(); } @Test public void javaScriptDisabled() { this.driver = MockMvcHtmlUnitDriverBuilder.mockMvcSetup(this.mockMvc).javascriptEnabled(false).build(); - assertFalse(this.driver.isJavascriptEnabled()); + assertThat(this.driver.isJavascriptEnabled()).isFalse(); } @Test // SPR-14066 diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java index 2b3632b2b43..384ddca574c 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java @@ -46,10 +46,7 @@ import org.springframework.web.servlet.FlashMap; import org.springframework.web.servlet.support.SessionFlashMapManager; import org.springframework.web.util.UriComponentsBuilder; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for building a {@link MockHttpServletRequest} with @@ -75,7 +72,7 @@ public class MockHttpServletRequestBuilderTests { public void method() { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("GET", request.getMethod()); + assertThat(request.getMethod()).isEqualTo("GET"); } @Test @@ -84,13 +81,12 @@ public class MockHttpServletRequestBuilderTests { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, uri); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("https", request.getScheme()); - assertEquals("foo=bar", request.getQueryString()); - assertEquals("java.sun.com", request.getServerName()); - assertEquals(8080, request.getServerPort()); - assertEquals("/javase/6/docs/api/java/util/BitSet.html", request.getRequestURI()); - assertEquals("https://java.sun.com:8080/javase/6/docs/api/java/util/BitSet.html", - request.getRequestURL().toString()); + assertThat(request.getScheme()).isEqualTo("https"); + assertThat(request.getQueryString()).isEqualTo("foo=bar"); + assertThat(request.getServerName()).isEqualTo("java.sun.com"); + assertThat(request.getServerPort()).isEqualTo(8080); + assertThat(request.getRequestURI()).isEqualTo("/javase/6/docs/api/java/util/BitSet.html"); + assertThat(request.getRequestURL().toString()).isEqualTo("https://java.sun.com:8080/javase/6/docs/api/java/util/BitSet.html"); } @Test @@ -98,7 +94,7 @@ public class MockHttpServletRequestBuilderTests { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo bar"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("/foo%20bar", request.getRequestURI()); + assertThat(request.getRequestURI()).isEqualTo("/foo%20bar"); } @Test // SPR-13435 @@ -106,7 +102,7 @@ public class MockHttpServletRequestBuilderTests { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, new URI("/test//currentlyValid/0")); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("/test//currentlyValid/0", request.getRequestURI()); + assertThat(request.getRequestURI()).isEqualTo("/test//currentlyValid/0"); } @Test @@ -114,9 +110,9 @@ public class MockHttpServletRequestBuilderTests { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("", request.getContextPath()); - assertEquals("", request.getServletPath()); - assertEquals("/foo", request.getPathInfo()); + assertThat(request.getContextPath()).isEqualTo(""); + assertThat(request.getServletPath()).isEqualTo(""); + assertThat(request.getPathInfo()).isEqualTo("/foo"); } @Test @@ -125,9 +121,9 @@ public class MockHttpServletRequestBuilderTests { this.builder.contextPath("/travel"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("/travel", request.getContextPath()); - assertEquals("", request.getServletPath()); - assertEquals("/hotels/42", request.getPathInfo()); + assertThat(request.getContextPath()).isEqualTo("/travel"); + assertThat(request.getServletPath()).isEqualTo(""); + assertThat(request.getPathInfo()).isEqualTo("/hotels/42"); } @Test @@ -138,9 +134,9 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("/travel", request.getContextPath()); - assertEquals("/main", request.getServletPath()); - assertEquals("/hotels/42", request.getPathInfo()); + assertThat(request.getContextPath()).isEqualTo("/travel"); + assertThat(request.getServletPath()).isEqualTo("/main"); + assertThat(request.getPathInfo()).isEqualTo("/hotels/42"); } @Test @@ -150,9 +146,9 @@ public class MockHttpServletRequestBuilderTests { this.builder.servletPath("/hotels/42"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("/travel", request.getContextPath()); - assertEquals("/hotels/42", request.getServletPath()); - assertNull(request.getPathInfo()); + assertThat(request.getContextPath()).isEqualTo("/travel"); + assertThat(request.getServletPath()).isEqualTo("/hotels/42"); + assertThat(request.getPathInfo()).isNull(); } @Test @@ -162,9 +158,9 @@ public class MockHttpServletRequestBuilderTests { this.builder.pathInfo(null); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("", request.getContextPath()); - assertEquals("/index.html", request.getServletPath()); - assertNull(request.getPathInfo()); + assertThat(request.getContextPath()).isEqualTo(""); + assertThat(request.getServletPath()).isEqualTo("/index.html"); + assertThat(request.getPathInfo()).isNull(); } @Test // SPR-16453 @@ -172,7 +168,7 @@ public class MockHttpServletRequestBuilderTests { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/hotels 42"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("/travel/hotels 42", request.getPathInfo()); + assertThat(request.getPathInfo()).isEqualTo("/travel/hotels 42"); } @Test @@ -193,7 +189,7 @@ public class MockHttpServletRequestBuilderTests { this.builder.buildRequest(this.servletContext); } catch (IllegalArgumentException ex) { - assertEquals(message, ex.getMessage()); + assertThat(ex.getMessage()).isEqualTo(message); } } @@ -202,7 +198,7 @@ public class MockHttpServletRequestBuilderTests { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo#bar"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("/foo", request.getRequestURI()); + assertThat(request.getRequestURI()).isEqualTo("/foo"); } @Test @@ -212,7 +208,7 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); Map parameterMap = request.getParameterMap(); - assertArrayEquals(new String[] {"bar", "baz"}, parameterMap.get("foo")); + assertThat(parameterMap.get("foo")).isEqualTo(new String[] {"bar", "baz"}); } @Test @@ -222,8 +218,8 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); Map parameterMap = request.getParameterMap(); - assertArrayEquals(new String[] {"bar", "baz"}, parameterMap.get("foo")); - assertEquals("foo=bar&foo=baz", request.getQueryString()); + assertThat(parameterMap.get("foo")).isEqualTo(new String[] {"bar", "baz"}); + assertThat(request.getQueryString()).isEqualTo("foo=bar&foo=baz"); } @Test @@ -232,9 +228,9 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("foo%5B0%5D=bar&foo%5B1%5D=baz", request.getQueryString()); - assertEquals("bar", request.getParameter("foo[0]")); - assertEquals("baz", request.getParameter("foo[1]")); + assertThat(request.getQueryString()).isEqualTo("foo%5B0%5D=bar&foo%5B1%5D=baz"); + assertThat(request.getParameter("foo[0]")).isEqualTo("bar"); + assertThat(request.getParameter("foo[1]")).isEqualTo("baz"); } @Test @@ -243,8 +239,8 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("foo=bar%3Dbaz", request.getQueryString()); - assertEquals("bar=baz", request.getParameter("foo")); + assertThat(request.getQueryString()).isEqualTo("foo=bar%3Dbaz"); + assertThat(request.getParameter("foo")).isEqualTo("bar=baz"); } @Test // SPR-11043 @@ -254,8 +250,8 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); Map parameterMap = request.getParameterMap(); - assertArrayEquals(new String[] {null}, parameterMap.get("foo")); - assertEquals("foo", request.getQueryString()); + assertThat(parameterMap.get("foo")).isEqualTo(new String[] {null}); + assertThat(request.getQueryString()).isEqualTo("foo"); } @Test // SPR-13801 @@ -268,7 +264,7 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertArrayEquals(new String[] {"bar", "baz"}, request.getParameterMap().get("foo")); + assertThat(request.getParameterMap().get("foo")).isEqualTo(new String[] {"bar", "baz"}); } @Test @@ -280,9 +276,9 @@ public class MockHttpServletRequestBuilderTests { .contentType(contentType).content(body.getBytes(StandardCharsets.UTF_8)) .buildRequest(this.servletContext); - assertArrayEquals(new String[] {"value 1"}, request.getParameterMap().get("name 1")); - assertArrayEquals(new String[] {"value A", "value B"}, request.getParameterMap().get("name 2")); - assertArrayEquals(new String[] {null}, request.getParameterMap().get("name 3")); + assertThat(request.getParameterMap().get("name 1")).isEqualTo(new String[] {"value 1"}); + assertThat(request.getParameterMap().get("name 2")).isEqualTo(new String[] {"value A", "value B"}); + assertThat(request.getParameterMap().get("name 3")).isEqualTo(new String[] {null}); } @Test @@ -293,9 +289,9 @@ public class MockHttpServletRequestBuilderTests { List accept = Collections.list(request.getHeaders("Accept")); List result = MediaType.parseMediaTypes(accept.get(0)); - assertEquals(1, accept.size()); - assertEquals("text/html", result.get(0).toString()); - assertEquals("application/xml", result.get(1).toString()); + assertThat(accept.size()).isEqualTo(1); + assertThat(result.get(0).toString()).isEqualTo("text/html"); + assertThat(result.get(1).toString()).isEqualTo("application/xml"); } @Test @@ -306,9 +302,9 @@ public class MockHttpServletRequestBuilderTests { String contentType = request.getContentType(); List contentTypes = Collections.list(request.getHeaders("Content-Type")); - assertEquals("text/html", contentType); - assertEquals(1, contentTypes.size()); - assertEquals("text/html", contentTypes.get(0)); + assertThat(contentType).isEqualTo("text/html"); + assertThat(contentTypes.size()).isEqualTo(1); + assertThat(contentTypes.get(0)).isEqualTo("text/html"); } @Test @@ -319,9 +315,9 @@ public class MockHttpServletRequestBuilderTests { String contentType = request.getContentType(); List contentTypes = Collections.list(request.getHeaders("Content-Type")); - assertEquals("text/html", contentType); - assertEquals(1, contentTypes.size()); - assertEquals("text/html", contentTypes.get(0)); + assertThat(contentType).isEqualTo("text/html"); + assertThat(contentTypes.size()).isEqualTo(1); + assertThat(contentTypes.get(0)).isEqualTo("text/html"); } @Test // SPR-11308 @@ -330,7 +326,7 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); String contentType = request.getContentType(); - assertEquals("text/html", contentType); + assertThat(contentType).isEqualTo("text/html"); } @Test // SPR-11308 @@ -338,7 +334,7 @@ public class MockHttpServletRequestBuilderTests { this.builder.header("Content-Type", MediaType.TEXT_HTML_VALUE, MediaType.ALL_VALUE); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("text/html", request.getContentType()); + assertThat(request.getContentType()).isEqualTo("text/html"); } @Test @@ -349,7 +345,7 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); byte[] result = FileCopyUtils.copyToByteArray(request.getInputStream()); - assertArrayEquals(body, result); + assertThat(result).isEqualTo(body); } @Test @@ -359,9 +355,9 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); List headers = Collections.list(request.getHeaders("foo")); - assertEquals(2, headers.size()); - assertEquals("bar", headers.get(0)); - assertEquals("baz", headers.get(1)); + assertThat(headers.size()).isEqualTo(2); + assertThat(headers.get(0)).isEqualTo("bar"); + assertThat(headers.get(1)).isEqualTo("baz"); } @Test @@ -374,10 +370,10 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); List headers = Collections.list(request.getHeaders("foo")); - assertEquals(2, headers.size()); - assertEquals("bar", headers.get(0)); - assertEquals("baz", headers.get(1)); - assertEquals(MediaType.APPLICATION_JSON.toString(), request.getHeader("Content-Type")); + assertThat(headers.size()).isEqualTo(2); + assertThat(headers.get(0)).isEqualTo("bar"); + assertThat(headers.get(1)).isEqualTo("baz"); + assertThat(request.getHeader("Content-Type")).isEqualTo(MediaType.APPLICATION_JSON.toString()); } @Test @@ -389,17 +385,17 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); Cookie[] cookies = request.getCookies(); - assertEquals(2, cookies.length); - assertEquals("foo", cookies[0].getName()); - assertEquals("bar", cookies[0].getValue()); - assertEquals("baz", cookies[1].getName()); - assertEquals("qux", cookies[1].getValue()); + assertThat(cookies.length).isEqualTo(2); + assertThat(cookies[0].getName()).isEqualTo("foo"); + assertThat(cookies[0].getValue()).isEqualTo("bar"); + assertThat(cookies[1].getName()).isEqualTo("baz"); + assertThat(cookies[1].getValue()).isEqualTo("qux"); } @Test public void noCookies() { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertNull(request.getCookies()); + assertThat(request.getCookies()).isNull(); } @Test @@ -409,7 +405,7 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals(locale, request.getLocale()); + assertThat(request.getLocale()).isEqualTo(locale); } @Test @@ -419,7 +415,7 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals(encoding, request.getCharacterEncoding()); + assertThat(request.getCharacterEncoding()).isEqualTo(encoding); } @Test @@ -427,7 +423,7 @@ public class MockHttpServletRequestBuilderTests { this.builder.requestAttr("foo", "bar"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("bar", request.getAttribute("foo")); + assertThat(request.getAttribute("foo")).isEqualTo("bar"); } @Test @@ -435,7 +431,7 @@ public class MockHttpServletRequestBuilderTests { this.builder.sessionAttr("foo", "bar"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("bar", request.getSession().getAttribute("foo")); + assertThat(request.getSession().getAttribute("foo")).isEqualTo("bar"); } @Test @@ -446,7 +442,7 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals("bar", request.getSession().getAttribute("foo")); + assertThat(request.getSession().getAttribute("foo")).isEqualTo("bar"); } @Test @@ -458,9 +454,9 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals(session, request.getSession()); - assertEquals("bar", request.getSession().getAttribute("foo")); - assertEquals("qux", request.getSession().getAttribute("baz")); + assertThat(request.getSession()).isEqualTo(session); + assertThat(request.getSession().getAttribute("foo")).isEqualTo("bar"); + assertThat(request.getSession().getAttribute("baz")).isEqualTo("qux"); } @Test @@ -469,8 +465,8 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); FlashMap flashMap = new SessionFlashMapManager().retrieveAndUpdate(request, null); - assertNotNull(flashMap); - assertEquals("bar", flashMap.get("foo")); + assertThat((Object) flashMap).isNotNull(); + assertThat(flashMap.get("foo")).isEqualTo("bar"); } @Test @@ -479,7 +475,7 @@ public class MockHttpServletRequestBuilderTests { this.builder.principal(user); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals(user, request.getUserPrincipal()); + assertThat(request.getUserPrincipal()).isEqualTo(user); } @Test // SPR-12945 @@ -497,7 +493,7 @@ public class MockHttpServletRequestBuilderTests { MockHttpServletRequest request = builder.buildRequest(servletContext); request = builder.postProcessRequest(request); - assertEquals(EXPECTED, request.getAttribute(ATTR)); + assertThat(request.getAttribute(ATTR)).isEqualTo(EXPECTED); } @Test // SPR-13719 @@ -507,8 +503,8 @@ public class MockHttpServletRequestBuilderTests { this.builder = new MockHttpServletRequestBuilder(httpMethod, url); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertEquals(httpMethod, request.getMethod()); - assertEquals("/foo/42", request.getPathInfo()); + assertThat(request.getMethod()).isEqualTo(httpMethod); + assertThat(request.getPathInfo()).isEqualTo("/foo/42"); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilderTests.java index 5a63505fa1a..e35a9abe200 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilderTests.java @@ -22,8 +22,7 @@ import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockServletContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rossen Stoyanchev @@ -36,12 +35,12 @@ public class MockMultipartHttpServletRequestBuilderTests { parent.characterEncoding("UTF-8"); Object result = new MockMultipartHttpServletRequestBuilder("/fileUpload").merge(parent); - assertNotNull(result); - assertEquals(MockMultipartHttpServletRequestBuilder.class, result.getClass()); + assertThat(result).isNotNull(); + assertThat(result.getClass()).isEqualTo(MockMultipartHttpServletRequestBuilder.class); MockMultipartHttpServletRequestBuilder builder = (MockMultipartHttpServletRequestBuilder) result; MockHttpServletRequest request = builder.buildRequest(new MockServletContext()); - assertEquals("UTF-8", request.getCharacterEncoding()); + assertThat(request.getCharacterEncoding()).isEqualTo("UTF-8"); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/result/PrintingResultHandlerTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/result/PrintingResultHandlerTests.java index 2b5ad70c89c..996cfe6d4f6 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/result/PrintingResultHandlerTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/result/PrintingResultHandlerTests.java @@ -42,8 +42,7 @@ import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.FlashMap; import org.springframework.web.servlet.ModelAndView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link PrintingResultHandler}. @@ -168,10 +167,10 @@ public class PrintingResultHandlerTests { // Manually validate cookie values since maxAge changes... List cookieValues = this.response.getHeaders("Set-Cookie"); - assertEquals(2, cookieValues.size()); - assertEquals("cookie=cookieValue", cookieValues.get(0)); - assertTrue("Actual: " + cookieValues.get(1), cookieValues.get(1).startsWith( - "enigma=42; Path=/crumbs; Domain=.example.com; Max-Age=1234; Expires=")); + assertThat(cookieValues.size()).isEqualTo(2); + assertThat(cookieValues.get(0)).isEqualTo("cookie=cookieValue"); + assertThat(cookieValues.get(1).startsWith( + "enigma=42; Path=/crumbs; Domain=.example.com; Max-Age=1234; Expires=")).as("Actual: " + cookieValues.get(1)).isTrue(); HttpHeaders headers = new HttpHeaders(); headers.set("header", "headerValue"); @@ -190,17 +189,17 @@ public class PrintingResultHandlerTests { Map> printedValues = this.handler.getPrinter().printedValues; String[] cookies = (String[]) printedValues.get(heading).get("Cookies"); - assertEquals(2, cookies.length); + assertThat(cookies.length).isEqualTo(2); String cookie1 = cookies[0]; String cookie2 = cookies[1]; - assertTrue(cookie1.startsWith("[" + Cookie.class.getSimpleName())); - assertTrue(cookie1.contains("name = 'cookie', value = 'cookieValue'")); - assertTrue(cookie1.endsWith("]")); - assertTrue(cookie2.startsWith("[" + Cookie.class.getSimpleName())); - assertTrue(cookie2.contains("name = 'enigma', value = '42', " + + assertThat(cookie1.startsWith("[" + Cookie.class.getSimpleName())).isTrue(); + assertThat(cookie1.contains("name = 'cookie', value = 'cookieValue'")).isTrue(); + assertThat(cookie1.endsWith("]")).isTrue(); + assertThat(cookie2.startsWith("[" + Cookie.class.getSimpleName())).isTrue(); + assertThat(cookie2.contains("name = 'enigma', value = '42', " + "comment = 'This is a comment', domain = '.example.com', maxAge = 1234, " + - "path = '/crumbs', secure = true, version = 0, httpOnly = true")); - assertTrue(cookie2.endsWith("]")); + "path = '/crumbs', secure = true, version = 0, httpOnly = true")).isTrue(); + assertThat(cookie2.endsWith("]")).isTrue(); } @Test @@ -338,9 +337,8 @@ public class PrintingResultHandlerTests { private void assertValue(String heading, String label, Object value) { Map> printedValues = this.handler.getPrinter().printedValues; - assertTrue("Heading '" + heading + "' not printed", printedValues.containsKey(heading)); - assertEquals("For label '" + label + "' under heading '" + heading + "' =>", value, - printedValues.get(heading).get(label)); + assertThat(printedValues.containsKey(heading)).as("Heading '" + heading + "' not printed").isTrue(); + assertThat(printedValues.get(heading).get(label)).as("For label '" + label + "' under heading '" + heading + "' =>").isEqualTo(value); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/result/StatusResultMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/result/StatusResultMatchersTests.java index 98d117fdad8..4335f8b39fe 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/result/StatusResultMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/result/StatusResultMatchersTests.java @@ -33,7 +33,7 @@ import org.springframework.test.web.servlet.StubMvcResult; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; /** * Tests for {@link StatusResultMatchers}. diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java index e57763750b0..4fa235b97f4 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java @@ -46,9 +46,7 @@ import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.tiles3.TilesConfigurer; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -115,22 +113,23 @@ public class JavaConfigTests { * @see org.springframework.test.context.hierarchies.web.ControllerIntegrationTests#verifyRootWacSupport() */ private void verifyRootWacSupport() { - assertNotNull(personDao); - assertNotNull(personController); + assertThat(personDao).isNotNull(); + assertThat(personController).isNotNull(); ApplicationContext parent = wac.getParent(); - assertNotNull(parent); - assertTrue(parent instanceof WebApplicationContext); + assertThat(parent).isNotNull(); + boolean condition = parent instanceof WebApplicationContext; + assertThat(condition).isTrue(); WebApplicationContext root = (WebApplicationContext) parent; ServletContext childServletContext = wac.getServletContext(); - assertNotNull(childServletContext); + assertThat(childServletContext).isNotNull(); ServletContext rootServletContext = root.getServletContext(); - assertNotNull(rootServletContext); - assertSame(childServletContext, rootServletContext); + assertThat(rootServletContext).isNotNull(); + assertThat(rootServletContext).isSameAs(childServletContext); - assertSame(root, rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); - assertSame(root, childServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); + assertThat(rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isSameAs(root); + assertThat(childServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isSameAs(root); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/HttpOptionsTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/HttpOptionsTests.java index 29d51a6d99a..719362fd0a4 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/HttpOptionsTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/HttpOptionsTests.java @@ -37,7 +37,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; @@ -69,7 +69,7 @@ public class HttpOptionsTests { int initialCount = controller.counter.get(); this.mockMvc.perform(options("/myUrl")).andExpect(status().isOk()); - assertEquals(initialCount + 1, controller.counter.get()); + assertThat(controller.counter.get()).isEqualTo((initialCount + 1)); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/RequestContextHolderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/RequestContextHolderTests.java index c26b1907d88..031bbad4e56 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/RequestContextHolderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/RequestContextHolderTests.java @@ -52,7 +52,6 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; @@ -120,19 +119,19 @@ public class RequestContextHolderTests { @Test public void requestScopedController() throws Exception { - assertTrue("request-scoped controller must be a CGLIB proxy", AopUtils.isCglibProxy(this.requestScopedController)); + assertThat(AopUtils.isCglibProxy(this.requestScopedController)).as("request-scoped controller must be a CGLIB proxy").isTrue(); this.mockMvc.perform(get("/requestScopedController").requestAttr(FROM_MVC_TEST_MOCK, FROM_MVC_TEST_MOCK)); } @Test public void requestScopedService() throws Exception { - assertTrue("request-scoped service must be a CGLIB proxy", AopUtils.isCglibProxy(this.requestScopedService)); + assertThat(AopUtils.isCglibProxy(this.requestScopedService)).as("request-scoped service must be a CGLIB proxy").isTrue(); this.mockMvc.perform(get("/requestScopedService").requestAttr(FROM_MVC_TEST_MOCK, FROM_MVC_TEST_MOCK)); } @Test public void sessionScopedService() throws Exception { - assertTrue("session-scoped service must be a CGLIB proxy", AopUtils.isCglibProxy(this.sessionScopedService)); + assertThat(AopUtils.isCglibProxy(this.sessionScopedService)).as("session-scoped service must be a CGLIB proxy").isTrue(); this.mockMvc.perform(get("/sessionScopedService").requestAttr(FROM_MVC_TEST_MOCK, FROM_MVC_TEST_MOCK)); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java index 320627539f7..0ae30662e79 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java @@ -40,7 +40,7 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -178,7 +178,7 @@ public class AsyncTests { .andExpect(request().asyncStarted()) .andReturn(); - assertTrue(writer.toString().contains("Async started = true")); + assertThat(writer.toString().contains("Async started = true")).isTrue(); writer = new StringWriter(); this.asyncController.onMessage("Joe"); @@ -189,7 +189,7 @@ public class AsyncTests { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}")); - assertTrue(writer.toString().contains("Async started = false")); + assertThat(writer.toString().contains("Async started = false")).isTrue(); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/MultipartControllerTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/MultipartControllerTests.java index 606b0d1c090..afbe3276cd6 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/MultipartControllerTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/MultipartControllerTests.java @@ -45,7 +45,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.multipart.MultipartFile; -import static org.junit.Assert.assertArrayEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; @@ -275,7 +275,7 @@ public class MultipartControllerTests { if (file != null && file.length > 0) { byte[] content = file[0].getBytes(); - assertArrayEquals(content, file[1].getBytes()); + assertThat(file[1].getBytes()).isEqualTo(content); model.addAttribute("fileContent", content); } if (json != null) { @@ -291,7 +291,7 @@ public class MultipartControllerTests { if (file != null && !file.isEmpty()) { byte[] content = file.get(0).getBytes(); - assertArrayEquals(content, file.get(1).getBytes()); + assertThat(file.get(1).getBytes()).isEqualTo(content); model.addAttribute("fileContent", content); } if (json != null) { @@ -319,7 +319,7 @@ public class MultipartControllerTests { if (file.isPresent()) { byte[] content = file.get()[0].getBytes(); - assertArrayEquals(content, file.get()[1].getBytes()); + assertThat(file.get()[1].getBytes()).isEqualTo(content); model.addAttribute("fileContent", content); } model.addAttribute("jsonContent", json); @@ -333,7 +333,7 @@ public class MultipartControllerTests { if (file.isPresent()) { byte[] content = file.get().get(0).getBytes(); - assertArrayEquals(content, file.get().get(1).getBytes()); + assertThat(file.get().get(1).getBytes()).isEqualTo(content); model.addAttribute("fileContent", content); } model.addAttribute("jsonContent", json); diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/HeaderAssertionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/HeaderAssertionTests.java index 5d3131e09b5..18693365927 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/HeaderAssertionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/HeaderAssertionTests.java @@ -34,15 +34,14 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.context.request.WebRequest; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.fail; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.springframework.http.HttpHeaders.IF_MODIFIED_SINCE; import static org.springframework.http.HttpHeaders.LAST_MODIFIED; import static org.springframework.http.HttpHeaders.VARY; @@ -150,7 +149,7 @@ public class HeaderAssertionTests { if (ERROR_MESSAGE.equals(err.getMessage())) { throw err; } - assertEquals("Response does not contain header 'X-Custom-Header'", err.getMessage()); + assertThat(err.getMessage()).isEqualTo("Response does not contain header 'X-Custom-Header'"); } } @@ -215,8 +214,7 @@ public class HeaderAssertionTests { } private void assertMessageContains(AssertionError error, String expected) { - assertTrue("Failure message should contain [" + expected + "], actual is [" + error.getMessage() + "]", - error.getMessage().contains(expected)); + assertThat(error.getMessage().contains(expected)).as("Failure message should contain [" + expected + "], actual is [" + error.getMessage() + "]").isTrue(); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilderTests.java index 87bcb14e0c2..8054d0bc631 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilderTests.java @@ -27,9 +27,8 @@ import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.servlet.DispatcherServlet; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; /** @@ -67,8 +66,7 @@ public class DefaultMockMvcBuilderTests { this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, child); DefaultMockMvcBuilder builder = webAppContextSetup(child); - assertSame(builder.initWebAppContext(), - WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)); + assertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)).isSameAs(builder.initWebAppContext()); } /** @@ -85,8 +83,7 @@ public class DefaultMockMvcBuilderTests { child.setServletContext(this.servletContext); DefaultMockMvcBuilder builder = webAppContextSetup(child); - assertSame(builder.initWebAppContext().getParent(), - WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)); + assertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)).isSameAs(builder.initWebAppContext().getParent()); } /** @@ -97,8 +94,8 @@ public class DefaultMockMvcBuilderTests { StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext); DefaultMockMvcBuilder builder = webAppContextSetup(root); WebApplicationContext wac = builder.initWebAppContext(); - assertSame(root, wac); - assertSame(root, WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)); + assertThat(wac).isSameAs(root); + assertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)).isSameAs(root); } /** @@ -117,10 +114,10 @@ public class DefaultMockMvcBuilderTests { DefaultMockMvcBuilder builder = webAppContextSetup(dispatcher); WebApplicationContext wac = builder.initWebAppContext(); - assertSame(dispatcher, wac); - assertSame(root, wac.getParent()); - assertSame(ear, wac.getParent().getParent()); - assertSame(root, WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)); + assertThat(wac).isSameAs(dispatcher); + assertThat(wac.getParent()).isSameAs(root); + assertThat(wac.getParent().getParent()).isSameAs(ear); + assertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)).isSameAs(root); } /** @@ -135,7 +132,7 @@ public class DefaultMockMvcBuilderTests { MockMvc mvc = builder.build(); DispatcherServlet ds = (DispatcherServlet) new DirectFieldAccessor(mvc) .getPropertyValue("servlet"); - assertEquals("test-id", ds.getContextId()); + assertThat(ds.getContextId()).isEqualTo("test-id"); } @Test @@ -148,7 +145,7 @@ public class DefaultMockMvcBuilderTests { MockMvc mvc = builder.build(); DispatcherServlet ds = (DispatcherServlet) new DirectFieldAccessor(mvc) .getPropertyValue("servlet"); - assertEquals("override-id", ds.getContextId()); + assertThat(ds.getContextId()).isEqualTo("override-id"); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/setup/SharedHttpSessionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/setup/SharedHttpSessionTests.java index 6490b390a10..0ea868a87f1 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/setup/SharedHttpSessionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/setup/SharedHttpSessionTests.java @@ -25,9 +25,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.bind.annotation.GetMapping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.SharedHttpSessionConfigurer.sharedHttpSession; @@ -49,18 +47,18 @@ public class SharedHttpSessionTests { MvcResult result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); HttpSession session = result.getRequest().getSession(false); - assertNotNull(session); - assertEquals(1, session.getAttribute("counter")); + assertThat(session).isNotNull(); + assertThat(session.getAttribute("counter")).isEqualTo(1); result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); session = result.getRequest().getSession(false); - assertNotNull(session); - assertEquals(2, session.getAttribute("counter")); + assertThat(session).isNotNull(); + assertThat(session.getAttribute("counter")).isEqualTo(2); result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); session = result.getRequest().getSession(false); - assertNotNull(session); - assertEquals(3, session.getAttribute("counter")); + assertThat(session).isNotNull(); + assertThat(session.getAttribute("counter")).isEqualTo(3); } @Test @@ -73,18 +71,18 @@ public class SharedHttpSessionTests { MvcResult result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); HttpSession session = result.getRequest().getSession(false); - assertNull(session); + assertThat(session).isNull(); result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); session = result.getRequest().getSession(false); - assertNull(session); + assertThat(session).isNull(); url = "/session"; result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); session = result.getRequest().getSession(false); - assertNotNull(session); - assertEquals(1, session.getAttribute("counter")); + assertThat(session).isNotNull(); + assertThat(session.getAttribute("counter")).isEqualTo(1); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilderTests.java index 4dbe0f610e2..c807e09907b 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilderTests.java @@ -38,10 +38,8 @@ import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Tests for {@link StandaloneMockMvcBuilder} @@ -63,8 +61,8 @@ public class StandaloneMockMvcBuilderTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); HandlerExecutionChain chain = hm.getHandler(request); - assertNotNull(chain); - assertEquals("handleWithPlaceholders", ((HandlerMethod) chain.getHandler()).getMethod().getName()); + assertThat(chain).isNotNull(); + assertThat(((HandlerMethod) chain.getHandler()).getMethod().getName()).isEqualTo("handleWithPlaceholders"); } @Test // SPR-13637 @@ -77,12 +75,12 @@ public class StandaloneMockMvcBuilderTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/persons"); HandlerExecutionChain chain = hm.getHandler(request); - assertNotNull(chain); - assertEquals("persons", ((HandlerMethod) chain.getHandler()).getMethod().getName()); + assertThat(chain).isNotNull(); + assertThat(((HandlerMethod) chain.getHandler()).getMethod().getName()).isEqualTo("persons"); request = new MockHttpServletRequest("GET", "/persons.xml"); chain = hm.getHandler(request); - assertNull(chain); + assertThat(chain).isNull(); } @Test // SPR-12553 @@ -90,7 +88,7 @@ public class StandaloneMockMvcBuilderTests { TestStandaloneMockMvcBuilder builder = new TestStandaloneMockMvcBuilder(new PlaceholderController()); builder.addPlaceholderValue("sys.login.ajax", "/foo"); WebApplicationContext wac = builder.initWebAppContext(); - assertEquals(wac, WebApplicationContextUtils.getRequiredWebApplicationContext(wac.getServletContext())); + assertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(wac.getServletContext())).isEqualTo(wac); } @Test @@ -128,7 +126,7 @@ public class StandaloneMockMvcBuilderTests { builder.build(); SpringHandlerInstantiator instantiator = new SpringHandlerInstantiator(builder.wac.getAutowireCapableBeanFactory()); JsonSerializer serializer = instantiator.serializerInstance(null, null, UnknownSerializer.class); - assertNotNull(serializer); + assertThat(serializer).isNotNull(); } diff --git a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java index 15014bc2172..0480b0e75c5 100644 --- a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java +++ b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java @@ -39,8 +39,6 @@ import org.springframework.stereotype.Repository; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -68,15 +66,15 @@ public class PersistenceExceptionTranslationPostProcessorTests { gac.refresh(); RepositoryInterface shouldNotBeProxied = (RepositoryInterface) gac.getBean("notProxied"); - assertFalse(AopUtils.isAopProxy(shouldNotBeProxied)); + assertThat(AopUtils.isAopProxy(shouldNotBeProxied)).isFalse(); RepositoryInterface shouldBeProxied = (RepositoryInterface) gac.getBean("proxied"); - assertTrue(AopUtils.isAopProxy(shouldBeProxied)); + assertThat(AopUtils.isAopProxy(shouldBeProxied)).isTrue(); RepositoryWithoutInterface rwi = (RepositoryWithoutInterface) gac.getBean("classProxied"); - assertTrue(AopUtils.isAopProxy(rwi)); + assertThat(AopUtils.isAopProxy(rwi)).isTrue(); checkWillTranslateExceptions(rwi); Additional rwi2 = (Additional) gac.getBean("classProxiedAndAdvised"); - assertTrue(AopUtils.isAopProxy(rwi2)); + assertThat(AopUtils.isAopProxy(rwi2)).isTrue(); rwi2.additionalMethod(false); checkWillTranslateExceptions(rwi2); assertThatExceptionOfType(DataAccessResourceFailureException.class).isThrownBy(() -> diff --git a/spring-tx/src/test/java/org/springframework/dao/support/ChainedPersistenceExceptionTranslatorTests.java b/spring-tx/src/test/java/org/springframework/dao/support/ChainedPersistenceExceptionTranslatorTests.java index 857604c9d32..d9b52bc4392 100644 --- a/spring-tx/src/test/java/org/springframework/dao/support/ChainedPersistenceExceptionTranslatorTests.java +++ b/spring-tx/src/test/java/org/springframework/dao/support/ChainedPersistenceExceptionTranslatorTests.java @@ -22,8 +22,7 @@ import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.dao.support.DataAccessUtilsTests.MapPersistenceExceptionTranslator; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -36,7 +35,7 @@ public class ChainedPersistenceExceptionTranslatorTests { ChainedPersistenceExceptionTranslator pet = new ChainedPersistenceExceptionTranslator(); //MapPersistenceExceptionTranslator mpet = new MapPersistenceExceptionTranslator(); RuntimeException in = new RuntimeException("in"); - assertSame(in, DataAccessUtils.translateIfNecessary(in, pet)); + assertThat(DataAccessUtils.translateIfNecessary(in, pet)).isSameAs(in); } @Test @@ -48,30 +47,28 @@ public class ChainedPersistenceExceptionTranslatorTests { mpet1.addTranslation(in1, out1); ChainedPersistenceExceptionTranslator chainedPet1 = new ChainedPersistenceExceptionTranslator(); - assertSame("Should not translate yet", in1, DataAccessUtils.translateIfNecessary(in1, chainedPet1)); + assertThat(DataAccessUtils.translateIfNecessary(in1, chainedPet1)).as("Should not translate yet").isSameAs(in1); chainedPet1.addDelegate(mpet1); - assertSame("Should now translate", out1, DataAccessUtils.translateIfNecessary(in1, chainedPet1)); + assertThat(DataAccessUtils.translateIfNecessary(in1, chainedPet1)).as("Should now translate").isSameAs(out1); // Now add a new translator and verify it wins MapPersistenceExceptionTranslator mpet2 = new MapPersistenceExceptionTranslator(); mpet2.addTranslation(in1, out2); chainedPet1.addDelegate(mpet2); - assertSame("Should still translate the same due to ordering", - out1, DataAccessUtils.translateIfNecessary(in1, chainedPet1)); + assertThat(DataAccessUtils.translateIfNecessary(in1, chainedPet1)).as("Should still translate the same due to ordering").isSameAs(out1); ChainedPersistenceExceptionTranslator chainedPet2 = new ChainedPersistenceExceptionTranslator(); chainedPet2.addDelegate(mpet2); chainedPet2.addDelegate(mpet1); - assertSame("Should translate differently due to ordering", - out2, DataAccessUtils.translateIfNecessary(in1, chainedPet2)); + assertThat(DataAccessUtils.translateIfNecessary(in1, chainedPet2)).as("Should translate differently due to ordering").isSameAs(out2); RuntimeException in2 = new RuntimeException("in2"); OptimisticLockingFailureException out3 = new OptimisticLockingFailureException("out2"); - assertNull(chainedPet2.translateExceptionIfPossible(in2)); + assertThat(chainedPet2.translateExceptionIfPossible(in2)).isNull(); MapPersistenceExceptionTranslator mpet3 = new MapPersistenceExceptionTranslator(); mpet3.addTranslation(in2, out3); chainedPet2.addDelegate(mpet3); - assertSame(out3, chainedPet2.translateExceptionIfPossible(in2)); + assertThat(chainedPet2.translateExceptionIfPossible(in2)).isSameAs(out3); } } diff --git a/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java b/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java index 9d91a21304c..d523469291b 100644 --- a/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java +++ b/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java @@ -33,9 +33,6 @@ import org.springframework.dao.TypeMismatchDataAccessException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; /** * @author Juergen Hoeller @@ -47,7 +44,7 @@ public class DataAccessUtilsTests { public void withEmptyCollection() { Collection col = new HashSet<>(); - assertNull(DataAccessUtils.uniqueResult(col)); + assertThat(DataAccessUtils.uniqueResult(col)).isNull(); assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> DataAccessUtils.requiredUniqueResult(col)) @@ -98,12 +95,12 @@ public class DataAccessUtilsTests { Collection col = new HashSet<>(1); col.add(5); - assertEquals(Integer.valueOf(5), DataAccessUtils.uniqueResult(col)); - assertEquals(Integer.valueOf(5), DataAccessUtils.requiredUniqueResult(col)); - assertEquals(Integer.valueOf(5), DataAccessUtils.objectResult(col, Integer.class)); - assertEquals("5", DataAccessUtils.objectResult(col, String.class)); - assertEquals(5, DataAccessUtils.intResult(col)); - assertEquals(5, DataAccessUtils.longResult(col)); + assertThat(DataAccessUtils.uniqueResult(col)).isEqualTo(Integer.valueOf(5)); + assertThat(DataAccessUtils.requiredUniqueResult(col)).isEqualTo(Integer.valueOf(5)); + assertThat(DataAccessUtils.objectResult(col, Integer.class)).isEqualTo(Integer.valueOf(5)); + assertThat(DataAccessUtils.objectResult(col, String.class)).isEqualTo("5"); + assertThat(DataAccessUtils.intResult(col)).isEqualTo(5); + assertThat(DataAccessUtils.longResult(col)).isEqualTo(5); } @Test @@ -113,12 +110,12 @@ public class DataAccessUtilsTests { col.add(i); col.add(i); - assertEquals(Integer.valueOf(5), DataAccessUtils.uniqueResult(col)); - assertEquals(Integer.valueOf(5), DataAccessUtils.requiredUniqueResult(col)); - assertEquals(Integer.valueOf(5), DataAccessUtils.objectResult(col, Integer.class)); - assertEquals("5", DataAccessUtils.objectResult(col, String.class)); - assertEquals(5, DataAccessUtils.intResult(col)); - assertEquals(5, DataAccessUtils.longResult(col)); + assertThat(DataAccessUtils.uniqueResult(col)).isEqualTo(Integer.valueOf(5)); + assertThat(DataAccessUtils.requiredUniqueResult(col)).isEqualTo(Integer.valueOf(5)); + assertThat(DataAccessUtils.objectResult(col, Integer.class)).isEqualTo(Integer.valueOf(5)); + assertThat(DataAccessUtils.objectResult(col, String.class)).isEqualTo("5"); + assertThat(DataAccessUtils.intResult(col)).isEqualTo(5); + assertThat(DataAccessUtils.longResult(col)).isEqualTo(5); } @Test @@ -138,12 +135,12 @@ public class DataAccessUtilsTests { Collection col = new HashSet<>(1); col.add(5L); - assertEquals(Long.valueOf(5L), DataAccessUtils.uniqueResult(col)); - assertEquals(Long.valueOf(5L), DataAccessUtils.requiredUniqueResult(col)); - assertEquals(Long.valueOf(5L), DataAccessUtils.objectResult(col, Long.class)); - assertEquals("5", DataAccessUtils.objectResult(col, String.class)); - assertEquals(5, DataAccessUtils.intResult(col)); - assertEquals(5, DataAccessUtils.longResult(col)); + assertThat(DataAccessUtils.uniqueResult(col)).isEqualTo(Long.valueOf(5L)); + assertThat(DataAccessUtils.requiredUniqueResult(col)).isEqualTo(Long.valueOf(5L)); + assertThat(DataAccessUtils.objectResult(col, Long.class)).isEqualTo(Long.valueOf(5L)); + assertThat(DataAccessUtils.objectResult(col, String.class)).isEqualTo("5"); + assertThat(DataAccessUtils.intResult(col)).isEqualTo(5); + assertThat(DataAccessUtils.longResult(col)).isEqualTo(5); } @Test @@ -151,9 +148,9 @@ public class DataAccessUtilsTests { Collection col = new HashSet<>(1); col.add("test1"); - assertEquals("test1", DataAccessUtils.uniqueResult(col)); - assertEquals("test1", DataAccessUtils.requiredUniqueResult(col)); - assertEquals("test1", DataAccessUtils.objectResult(col, String.class)); + assertThat(DataAccessUtils.uniqueResult(col)).isEqualTo("test1"); + assertThat(DataAccessUtils.requiredUniqueResult(col)).isEqualTo("test1"); + assertThat(DataAccessUtils.objectResult(col, String.class)).isEqualTo("test1"); assertThatExceptionOfType(TypeMismatchDataAccessException.class).isThrownBy(() -> DataAccessUtils.intResult(col)); @@ -168,10 +165,10 @@ public class DataAccessUtilsTests { Collection col = new HashSet<>(1); col.add(date); - assertEquals(date, DataAccessUtils.uniqueResult(col)); - assertEquals(date, DataAccessUtils.requiredUniqueResult(col)); - assertEquals(date, DataAccessUtils.objectResult(col, Date.class)); - assertEquals(date.toString(), DataAccessUtils.objectResult(col, String.class)); + assertThat(DataAccessUtils.uniqueResult(col)).isEqualTo(date); + assertThat(DataAccessUtils.requiredUniqueResult(col)).isEqualTo(date); + assertThat(DataAccessUtils.objectResult(col, Date.class)).isEqualTo(date); + assertThat(DataAccessUtils.objectResult(col, String.class)).isEqualTo(date.toString()); assertThatExceptionOfType(TypeMismatchDataAccessException.class).isThrownBy(() -> DataAccessUtils.intResult(col)); @@ -184,7 +181,7 @@ public class DataAccessUtilsTests { public void exceptionTranslationWithNoTranslation() { MapPersistenceExceptionTranslator mpet = new MapPersistenceExceptionTranslator(); RuntimeException in = new RuntimeException(); - assertSame(in, DataAccessUtils.translateIfNecessary(in, mpet)); + assertThat(DataAccessUtils.translateIfNecessary(in, mpet)).isSameAs(in); } @Test @@ -193,7 +190,7 @@ public class DataAccessUtilsTests { RuntimeException in = new RuntimeException("in"); InvalidDataAccessApiUsageException out = new InvalidDataAccessApiUsageException("out"); mpet.addTranslation(in, out); - assertSame(out, DataAccessUtils.translateIfNecessary(in, mpet)); + assertThat(DataAccessUtils.translateIfNecessary(in, mpet)).isSameAs(out); } private Consumer sizeRequirements( diff --git a/spring-tx/src/test/java/org/springframework/jca/cci/CciLocalTransactionTests.java b/spring-tx/src/test/java/org/springframework/jca/cci/CciLocalTransactionTests.java index c4ad7f9e9e6..471e0cb8eb5 100644 --- a/spring-tx/src/test/java/org/springframework/jca/cci/CciLocalTransactionTests.java +++ b/spring-tx/src/test/java/org/springframework/jca/cci/CciLocalTransactionTests.java @@ -35,7 +35,7 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -73,7 +73,7 @@ public class CciLocalTransactionTests { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(connectionFactory)); + assertThat(TransactionSynchronizationManager.hasResource(connectionFactory)).as("Has thread connection").isTrue(); CciTemplate ct = new CciTemplate(connectionFactory); ct.execute(interactionSpec, record, record); } @@ -113,7 +113,7 @@ public class CciLocalTransactionTests { tt.execute(new TransactionCallback() { @Override public Void doInTransaction(TransactionStatus status) { - assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(connectionFactory)); + assertThat(TransactionSynchronizationManager.hasResource(connectionFactory)).as("Has thread connection").isTrue(); CciTemplate ct = new CciTemplate(connectionFactory); ct.execute(interactionSpec, record, record); throw new DataRetrievalFailureException("error"); diff --git a/spring-tx/src/test/java/org/springframework/jca/cci/CciTemplateTests.java b/spring-tx/src/test/java/org/springframework/jca/cci/CciTemplateTests.java index 0336961bfc9..f2945ebd96a 100644 --- a/spring-tx/src/test/java/org/springframework/jca/cci/CciTemplateTests.java +++ b/spring-tx/src/test/java/org/springframework/jca/cci/CciTemplateTests.java @@ -40,9 +40,7 @@ import org.springframework.jca.cci.core.InteractionCallback; import org.springframework.jca.cci.core.RecordCreator; import org.springframework.jca.cci.core.RecordExtractor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -128,7 +126,8 @@ public class CciTemplateTests { ct.setOutputRecordCreator(new RecordCreator() { @Override public Record createRecord(RecordFactory recordFactory) { - assertTrue(recordFactory instanceof NotSupportedRecordFactory); + boolean condition = recordFactory instanceof NotSupportedRecordFactory; + assertThat(condition).isTrue(); return outputRecord; } }); @@ -341,7 +340,7 @@ public class CciTemplateTests { CciTemplate ct = new CciTemplate(connectionFactory); ct.setOutputRecordCreator(creator); - assertEquals(obj, ct.execute(interactionSpec, generator, extractor)); + assertThat(ct.execute(interactionSpec, generator, extractor)).isEqualTo(obj); verify(interaction).close(); verify(connection).close(); @@ -534,7 +533,7 @@ public class CciTemplateTests { CciTemplate ct = new CciTemplate(connectionFactory); Record tmpOutputRecord = ct.execute(interactionSpec, inputOutputRecord); - assertNull(tmpOutputRecord); + assertThat(tmpOutputRecord).isNull(); verify(interaction).execute(interactionSpec, inputOutputRecord); verify(interaction).close(); diff --git a/spring-tx/src/test/java/org/springframework/jca/cci/EisOperationTests.java b/spring-tx/src/test/java/org/springframework/jca/cci/EisOperationTests.java index df12b5c7266..9446a240ec6 100644 --- a/spring-tx/src/test/java/org/springframework/jca/cci/EisOperationTests.java +++ b/spring-tx/src/test/java/org/springframework/jca/cci/EisOperationTests.java @@ -30,7 +30,7 @@ import org.springframework.jca.cci.core.RecordCreator; import org.springframework.jca.cci.object.MappingRecordOperation; import org.springframework.jca.cci.object.SimpleRecordOperation; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -139,7 +139,7 @@ public class EisOperationTests { given(interaction.execute(interactionSpec, inputRecord)).willReturn(outputRecord); given(callDetector.callExtractOutputData(outputRecord)).willReturn(outObj); - assertSame(outObj, query.execute(inObj)); + assertThat(query.execute(inObj)).isSameAs(outObj); verify(interaction).close(); verify(connection).close(); } @@ -176,7 +176,7 @@ public class EisOperationTests { given(interaction.execute(interactionSpec, inputRecord, outputRecord)).willReturn(true); given(callDetector.callExtractOutputData(outputRecord)).willReturn(outObj); - assertSame(outObj, query.execute(inObj)); + assertThat(query.execute(inObj)).isSameAs(outObj); verify(interaction).close(); verify(connection).close(); } diff --git a/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java b/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java index dee1eaf8b7d..a44f7303562 100644 --- a/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java +++ b/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java @@ -21,10 +21,8 @@ import javax.resource.spi.ManagedConnectionFactory; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -46,13 +44,13 @@ public class LocalConnectionFactoryBeanTests { @Test public void testIsSingleton() throws Exception { LocalConnectionFactoryBean factory = new LocalConnectionFactoryBean(); - assertTrue(factory.isSingleton()); + assertThat(factory.isSingleton()).isTrue(); } @Test public void testGetObjectTypeIsNullIfConnectionFactoryHasNotBeenConfigured() throws Exception { LocalConnectionFactoryBean factory = new LocalConnectionFactoryBean(); - assertNull(factory.getObjectType()); + assertThat(factory.getObjectType()).isNull(); } @Test @@ -63,7 +61,7 @@ public class LocalConnectionFactoryBeanTests { LocalConnectionFactoryBean factory = new LocalConnectionFactoryBean(); factory.setManagedConnectionFactory(managedConnectionFactory); factory.afterPropertiesSet(); - assertEquals(CONNECTION_FACTORY, factory.getObject()); + assertThat(factory.getObject()).isEqualTo(CONNECTION_FACTORY); } @Test diff --git a/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java index c8eb137b822..e6398450402 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java @@ -30,10 +30,7 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -86,34 +83,37 @@ public class JndiJtaTransactionManagerTests { ptm.afterPropertiesSet(); if (tmFound) { - assertEquals(tm, ptm.getTransactionManager()); + assertThat(ptm.getTransactionManager()).isEqualTo(tm); } else { - assertNull(ptm.getTransactionManager()); + assertThat(ptm.getTransactionManager()).isNull(); } if (defaultUt) { - assertEquals(ut, ptm.getUserTransaction()); + assertThat(ptm.getUserTransaction()).isEqualTo(ut); } else { - assertTrue(ptm.getUserTransaction() instanceof UserTransactionAdapter); + boolean condition = ptm.getUserTransaction() instanceof UserTransactionAdapter; + assertThat(condition).isTrue(); UserTransactionAdapter uta = (UserTransactionAdapter) ptm.getUserTransaction(); - assertEquals(tm, uta.getTransactionManager()); + assertThat(uta.getTransactionManager()).isEqualTo(tm); } TransactionTemplate tt = new TransactionTemplate(ptm); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } }); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); if (defaultUt) { @@ -143,22 +143,24 @@ public class JndiJtaTransactionManagerTests { ptm.setJndiTemplate(jndiTemplate); ptm.afterPropertiesSet(); - assertEquals(ut, ptm.getUserTransaction()); - assertEquals(tm, ptm.getTransactionManager()); + assertThat(ptm.getUserTransaction()).isEqualTo(ut); + assertThat(ptm.getTransactionManager()).isEqualTo(tm); TransactionTemplate tt = new TransactionTemplate(ptm); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } }); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); verify(ut).begin(); verify(ut).commit(); @@ -177,18 +179,19 @@ public class JndiJtaTransactionManagerTests { ptm.setCacheUserTransaction(false); ptm.afterPropertiesSet(); - assertEquals(ut, ptm.getUserTransaction()); + assertThat(ptm.getUserTransaction()).isEqualTo(ut); TransactionTemplate tt = new TransactionTemplate(ptm); - assertEquals(JtaTransactionManager.SYNCHRONIZATION_ALWAYS, ptm.getTransactionSynchronization()); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(ptm.getTransactionSynchronization()).isEqualTo(JtaTransactionManager.SYNCHRONIZATION_ALWAYS); + boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition1).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } }); @@ -197,12 +200,13 @@ public class JndiJtaTransactionManagerTests { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } }); - assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + boolean condition = !TransactionSynchronizationManager.isSynchronizationActive(); + assertThat(condition).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); verify(ut).begin(); verify(ut).commit(); @@ -216,11 +220,11 @@ public class JndiJtaTransactionManagerTests { */ @After public void tearDown() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertNull(TransactionSynchronizationManager.getCurrentTransactionName()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java index 09d23a9c7e3..0d926773133 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java @@ -42,12 +42,7 @@ import org.springframework.transaction.support.TransactionTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.atLeastOnce; @@ -72,23 +67,23 @@ public class JtaTransactionManagerTests { TransactionTemplate tt = new TransactionTemplate(ptm); tt.setName("txName"); - assertEquals(JtaTransactionManager.SYNCHRONIZATION_ALWAYS, ptm.getTransactionSynchronization()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertNull(TransactionSynchronizationManager.getCurrentTransactionName()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(ptm.getTransactionSynchronization()).isEqualTo(JtaTransactionManager.SYNCHRONIZATION_ALWAYS); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); - assertEquals("txName", TransactionSynchronizationManager.getCurrentTransactionName()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isEqualTo("txName"); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertNull(TransactionSynchronizationManager.getCurrentTransactionName()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); verify(ut).begin(); verify(ut).commit(); @@ -108,16 +103,16 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { // something transactional - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).begin(); verify(ut).commit(); @@ -138,14 +133,14 @@ public class JtaTransactionManagerTests { ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_NEVER); ptm.afterPropertiesSet(); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).begin(); verify(ut).commit(); @@ -162,22 +157,22 @@ public class JtaTransactionManagerTests { tt.setTimeout(10); tt.setName("txName"); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertNull(TransactionSynchronizationManager.getCurrentTransactionName()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); - assertEquals("txName", TransactionSynchronizationManager.getCurrentTransactionName()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isEqualTo("txName"); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertNull(TransactionSynchronizationManager.getCurrentTransactionName()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); verify(ut).setTransactionTimeout(10); verify(ut).begin(); @@ -196,16 +191,16 @@ public class JtaTransactionManagerTests { TransactionTemplate tt = new TransactionTemplate(ptm); ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); tt.setTimeout(10); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).setTransactionTimeout(10); verify(ut).begin(); @@ -225,15 +220,15 @@ public class JtaTransactionManagerTests { tt.setTimeout(10); ptm.afterPropertiesSet(); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).setTransactionTimeout(10); verify(ut).begin(); @@ -250,16 +245,16 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).setRollbackOnly(); verify(synch).beforeCompletion(); @@ -275,17 +270,17 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThatIllegalStateException().isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); throw new IllegalStateException("I want a rollback"); } })); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).setRollbackOnly(); verify(synch).beforeCompletion(); @@ -302,16 +297,16 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); } })); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).setRollbackOnly(); verify(synch).beforeCompletion(); @@ -328,16 +323,16 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); ptm.setGlobalRollbackOnParticipationFailure(false); TransactionTemplate tt = new TransactionTemplate(ptm); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).setRollbackOnly(); verify(synch).beforeCompletion(); @@ -353,17 +348,17 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); ptm.setGlobalRollbackOnParticipationFailure(false); TransactionTemplate tt = new TransactionTemplate(ptm); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThatIllegalStateException().isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); throw new IllegalStateException("I want a rollback"); } })); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(synch).beforeCompletion(); verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); @@ -382,17 +377,17 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertNotNull(tx.getSynchronization()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(tx.getSynchronization()).isNotNull(); tx.getSynchronization().beforeCompletion(); tx.getSynchronization().afterCompletion(Status.STATUS_ROLLEDBACK); @@ -411,16 +406,16 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).setRollbackOnly(); verify(synch).beforeCompletion(); @@ -437,15 +432,15 @@ public class JtaTransactionManagerTests { ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_NEVER); ptm.afterPropertiesSet(); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).setRollbackOnly(); } @@ -460,16 +455,16 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).setRollbackOnly(); verify(synch).beforeCompletion(); @@ -486,16 +481,16 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(synch).beforeCompletion(); verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); @@ -512,15 +507,15 @@ public class JtaTransactionManagerTests { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); ptm.afterPropertiesSet(); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } @Test @@ -534,15 +529,15 @@ public class JtaTransactionManagerTests { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); ptm.afterPropertiesSet(); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } @Test @@ -556,15 +551,15 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); status.setRollbackOnly(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(tm).resume(tx); } @@ -584,13 +579,13 @@ public class JtaTransactionManagerTests { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tt.setName("txName"); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertEquals("txName", TransactionSynchronizationManager.getCurrentTransactionName()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isEqualTo("txName"); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); TransactionTemplate tt2 = new TransactionTemplate(ptm); tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); @@ -599,18 +594,18 @@ public class JtaTransactionManagerTests { tt2.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertEquals("txName2", TransactionSynchronizationManager.getCurrentTransactionName()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isEqualTo("txName2"); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); } }); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertEquals("txName", TransactionSynchronizationManager.getCurrentTransactionName()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isEqualTo("txName"); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut, times(2)).begin(); verify(ut, times(2)).commit(); @@ -627,31 +622,31 @@ public class JtaTransactionManagerTests { TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); TransactionTemplate tt2 = new TransactionTemplate(ptm); tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tt2.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); } }); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).begin(); verify(ut).commit(); @@ -668,14 +663,14 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(ut).begin(); verify(ut).commit(); @@ -692,15 +687,15 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); } })); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } @Test @@ -715,15 +710,15 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThatExceptionOfType(CannotCreateTransactionException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); } })); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(tm).resume(tx); } @@ -737,14 +732,14 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(tm); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); } }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(tm).begin(); verify(tm).commit(); @@ -759,14 +754,14 @@ public class JtaTransactionManagerTests { JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThatExceptionOfType(TransactionSuspensionNotSupportedException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { } })); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } @Test @@ -896,7 +891,7 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { - assertTrue("Correct completion status", status == TransactionSynchronization.STATUS_ROLLED_BACK); + assertThat(status == TransactionSynchronization.STATUS_ROLLED_BACK).as("Correct completion status").isTrue(); } }); } @@ -930,7 +925,7 @@ public class JtaTransactionManagerTests { TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); boolean outerTransactionBoundaryReached = false; try { - assertTrue("Is new transaction", ts.isNewTransaction()); + assertThat(ts.isNewTransaction()).as("Is new transaction").isTrue(); TransactionTemplate tt = new TransactionTemplate(tm); tt.execute(new TransactionCallbackWithoutResult() { @@ -940,7 +935,7 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { - assertTrue("Correct completion status", status == TransactionSynchronization.STATUS_ROLLED_BACK); + assertThat(status == TransactionSynchronization.STATUS_ROLLED_BACK).as("Correct completion status").isTrue(); } }); } @@ -985,7 +980,7 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { - assertTrue("Correct completion status", status == TransactionSynchronization.STATUS_UNKNOWN); + assertThat(status == TransactionSynchronization.STATUS_UNKNOWN).as("Correct completion status").isTrue(); } }); } @@ -1012,7 +1007,7 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { - assertTrue("Correct completion status", status == TransactionSynchronization.STATUS_UNKNOWN); + assertThat(status == TransactionSynchronization.STATUS_UNKNOWN).as("Correct completion status").isTrue(); } }); } @@ -1039,7 +1034,7 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { - assertTrue("Correct completion status", status == TransactionSynchronization.STATUS_UNKNOWN); + assertThat(status == TransactionSynchronization.STATUS_UNKNOWN).as("Correct completion status").isTrue(); } }); } @@ -1064,7 +1059,7 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { - assertTrue("Correct completion status", status == TransactionSynchronization.STATUS_UNKNOWN); + assertThat(status == TransactionSynchronization.STATUS_UNKNOWN).as("Correct completion status").isTrue(); } }); status.setRollbackOnly(); @@ -1109,7 +1104,7 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { - assertTrue("Correct completion status", status == TransactionSynchronization.STATUS_UNKNOWN); + assertThat(status == TransactionSynchronization.STATUS_UNKNOWN).as("Correct completion status").isTrue(); } }); } @@ -1124,12 +1119,12 @@ public class JtaTransactionManagerTests { Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); TransactionStatus status = ptm.getTransaction(new DefaultTransactionDefinition()); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); // first commit ptm.commit(status); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); // second commit attempt assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> ptm.commit(status)); @@ -1143,12 +1138,12 @@ public class JtaTransactionManagerTests { given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); TransactionStatus status = ptm.getTransaction(new DefaultTransactionDefinition()); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); // first rollback ptm.rollback(status); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); // second rollback attempt assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> ptm.rollback(status)); @@ -1163,12 +1158,12 @@ public class JtaTransactionManagerTests { given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); TransactionStatus status = ptm.getTransaction(new DefaultTransactionDefinition()); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); // first: rollback ptm.rollback(status); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); // second: commit attempt assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> ptm.commit(status)); @@ -1197,12 +1192,12 @@ public class JtaTransactionManagerTests { */ @After public void tearDown() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertNull(TransactionSynchronizationManager.getCurrentTransactionName()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertNull(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()).isNull(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java b/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java index 0678892d5f7..bad883eebf9 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java @@ -25,13 +25,9 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertNotEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -44,12 +40,12 @@ public class TransactionSupportTests { PlatformTransactionManager tm = new TestTransactionManager(false, true); DefaultTransactionStatus status1 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS)); - assertFalse("Must not have transaction", status1.hasTransaction()); + assertThat(status1.hasTransaction()).as("Must not have transaction").isFalse(); DefaultTransactionStatus status2 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED)); - assertTrue("Must have transaction", status2.hasTransaction()); - assertTrue("Must be new transaction", status2.isNewTransaction()); + assertThat(status2.hasTransaction()).as("Must have transaction").isTrue(); + assertThat(status2.isNewTransaction()).as("Must be new transaction").isTrue(); assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY))); @@ -60,18 +56,21 @@ public class TransactionSupportTests { PlatformTransactionManager tm = new TestTransactionManager(true, true); DefaultTransactionStatus status1 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS)); - assertTrue("Must have transaction", status1.getTransaction() != null); - assertTrue("Must not be new transaction", !status1.isNewTransaction()); + assertThat(status1.getTransaction() != null).as("Must have transaction").isTrue(); + boolean condition2 = !status1.isNewTransaction(); + assertThat(condition2).as("Must not be new transaction").isTrue(); DefaultTransactionStatus status2 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED)); - assertTrue("Must have transaction", status2.getTransaction() != null); - assertTrue("Must not be new transaction", !status2.isNewTransaction()); + assertThat(status2.getTransaction() != null).as("Must have transaction").isTrue(); + boolean condition1 = !status2.isNewTransaction(); + assertThat(condition1).as("Must not be new transaction").isTrue(); DefaultTransactionStatus status3 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY)); - assertTrue("Must have transaction", status3.getTransaction() != null); - assertTrue("Must not be new transaction", !status3.isNewTransaction()); + assertThat(status3.getTransaction() != null).as("Must have transaction").isTrue(); + boolean condition = !status3.isNewTransaction(); + assertThat(condition).as("Must not be new transaction").isTrue(); } @Test @@ -80,10 +79,10 @@ public class TransactionSupportTests { TransactionStatus status = tm.getTransaction(null); tm.commit(status); - assertTrue("triggered begin", tm.begin); - assertTrue("triggered commit", tm.commit); - assertFalse("no rollback", tm.rollback); - assertFalse("no rollbackOnly", tm.rollbackOnly); + assertThat(tm.begin).as("triggered begin").isTrue(); + assertThat(tm.commit).as("triggered commit").isTrue(); + assertThat(tm.rollback).as("no rollback").isFalse(); + assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @Test @@ -92,10 +91,10 @@ public class TransactionSupportTests { TransactionStatus status = tm.getTransaction(null); tm.rollback(status); - assertTrue("triggered begin", tm.begin); - assertFalse("no commit", tm.commit); - assertTrue("triggered rollback", tm.rollback); - assertFalse("no rollbackOnly", tm.rollbackOnly); + assertThat(tm.begin).as("triggered begin").isTrue(); + assertThat(tm.commit).as("no commit").isFalse(); + assertThat(tm.rollback).as("triggered rollback").isTrue(); + assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @Test @@ -105,10 +104,10 @@ public class TransactionSupportTests { status.setRollbackOnly(); tm.commit(status); - assertTrue("triggered begin", tm.begin); - assertFalse("no commit", tm.commit); - assertTrue("triggered rollback", tm.rollback); - assertFalse("no rollbackOnly", tm.rollbackOnly); + assertThat(tm.begin).as("triggered begin").isTrue(); + assertThat(tm.commit).as("no commit").isFalse(); + assertThat(tm.rollback).as("triggered rollback").isTrue(); + assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @Test @@ -117,10 +116,10 @@ public class TransactionSupportTests { TransactionStatus status = tm.getTransaction(null); tm.commit(status); - assertFalse("no begin", tm.begin); - assertFalse("no commit", tm.commit); - assertFalse("no rollback", tm.rollback); - assertFalse("no rollbackOnly", tm.rollbackOnly); + assertThat(tm.begin).as("no begin").isFalse(); + assertThat(tm.commit).as("no commit").isFalse(); + assertThat(tm.rollback).as("no rollback").isFalse(); + assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @Test @@ -129,10 +128,10 @@ public class TransactionSupportTests { TransactionStatus status = tm.getTransaction(null); tm.rollback(status); - assertFalse("no begin", tm.begin); - assertFalse("no commit", tm.commit); - assertFalse("no rollback", tm.rollback); - assertTrue("triggered rollbackOnly", tm.rollbackOnly); + assertThat(tm.begin).as("no begin").isFalse(); + assertThat(tm.commit).as("no commit").isFalse(); + assertThat(tm.rollback).as("no rollback").isFalse(); + assertThat(tm.rollbackOnly).as("triggered rollbackOnly").isTrue(); } @Test @@ -142,10 +141,10 @@ public class TransactionSupportTests { status.setRollbackOnly(); tm.commit(status); - assertFalse("no begin", tm.begin); - assertFalse("no commit", tm.commit); - assertFalse("no rollback", tm.rollback); - assertTrue("triggered rollbackOnly", tm.rollbackOnly); + assertThat(tm.begin).as("no begin").isFalse(); + assertThat(tm.commit).as("no commit").isFalse(); + assertThat(tm.rollback).as("no rollback").isFalse(); + assertThat(tm.rollbackOnly).as("triggered rollbackOnly").isTrue(); } @Test @@ -158,10 +157,10 @@ public class TransactionSupportTests { } }); - assertTrue("triggered begin", tm.begin); - assertTrue("triggered commit", tm.commit); - assertFalse("no rollback", tm.rollback); - assertFalse("no rollbackOnly", tm.rollbackOnly); + assertThat(tm.begin).as("triggered begin").isTrue(); + assertThat(tm.commit).as("triggered commit").isTrue(); + assertThat(tm.rollback).as("no rollback").isFalse(); + assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @Test @@ -174,8 +173,8 @@ public class TransactionSupportTests { } }); - assertSame(template, ptm.getDefinition()); - assertFalse(ptm.getStatus().isRollbackOnly()); + assertThat(ptm.getDefinition()).isSameAs(template); + assertThat(ptm.getStatus().isRollbackOnly()).isFalse(); } @Test @@ -191,10 +190,10 @@ public class TransactionSupportTests { } })) .isSameAs(ex); - assertTrue("triggered begin", tm.begin); - assertFalse("no commit", tm.commit); - assertTrue("triggered rollback", tm.rollback); - assertFalse("no rollbackOnly", tm.rollbackOnly); + assertThat(tm.begin).as("triggered begin").isTrue(); + assertThat(tm.commit).as("no commit").isFalse(); + assertThat(tm.rollback).as("triggered rollback").isTrue(); + assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @SuppressWarnings("serial") @@ -218,10 +217,10 @@ public class TransactionSupportTests { } })) .isSameAs(tex); - assertTrue("triggered begin", tm.begin); - assertFalse("no commit", tm.commit); - assertTrue("triggered rollback", tm.rollback); - assertFalse("no rollbackOnly", tm.rollbackOnly); + assertThat(tm.begin).as("triggered begin").isTrue(); + assertThat(tm.commit).as("no commit").isFalse(); + assertThat(tm.rollback).as("triggered rollback").isTrue(); + assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @Test @@ -235,10 +234,10 @@ public class TransactionSupportTests { throw new Error("Some application error"); } })); - assertTrue("triggered begin", tm.begin); - assertFalse("no commit", tm.commit); - assertTrue("triggered rollback", tm.rollback); - assertFalse("no rollbackOnly", tm.rollbackOnly); + assertThat(tm.begin).as("triggered begin").isTrue(); + assertThat(tm.commit).as("no commit").isFalse(); + assertThat(tm.rollback).as("triggered rollback").isTrue(); + assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @Test @@ -246,28 +245,28 @@ public class TransactionSupportTests { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionTemplate template = new TransactionTemplate(); template.setTransactionManager(tm); - assertTrue("correct transaction manager set", template.getTransactionManager() == tm); + assertThat(template.getTransactionManager() == tm).as("correct transaction manager set").isTrue(); assertThatIllegalArgumentException().isThrownBy(() -> template.setPropagationBehaviorName("TIMEOUT_DEFAULT")); template.setPropagationBehaviorName("PROPAGATION_SUPPORTS"); - assertTrue("Correct propagation behavior set", template.getPropagationBehavior() == TransactionDefinition.PROPAGATION_SUPPORTS); + assertThat(template.getPropagationBehavior() == TransactionDefinition.PROPAGATION_SUPPORTS).as("Correct propagation behavior set").isTrue(); assertThatIllegalArgumentException().isThrownBy(() -> template.setPropagationBehavior(999)); template.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY); - assertTrue("Correct propagation behavior set", template.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY); + assertThat(template.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY).as("Correct propagation behavior set").isTrue(); assertThatIllegalArgumentException().isThrownBy(() -> template.setIsolationLevelName("TIMEOUT_DEFAULT")); template.setIsolationLevelName("ISOLATION_SERIALIZABLE"); - assertTrue("Correct isolation level set", template.getIsolationLevel() == TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(template.getIsolationLevel() == TransactionDefinition.ISOLATION_SERIALIZABLE).as("Correct isolation level set").isTrue(); assertThatIllegalArgumentException().isThrownBy(() -> template.setIsolationLevel(999)); template.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); - assertTrue("Correct isolation level set", template.getIsolationLevel() == TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(template.getIsolationLevel() == TransactionDefinition.ISOLATION_REPEATABLE_READ).as("Correct isolation level set").isTrue(); } @Test @@ -278,16 +277,16 @@ public class TransactionSupportTests { TransactionTemplate template2 = new TransactionTemplate(tm2); TransactionTemplate template3 = new TransactionTemplate(tm2); - assertNotEquals(template1, template2); - assertNotEquals(template1, template3); - assertEquals(template2, template3); + assertThat(template2).isNotEqualTo(template1); + assertThat(template3).isNotEqualTo(template1); + assertThat(template3).isEqualTo(template2); } @After public void clear() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java index 03005d67546..ca2c1dfcdb9 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java @@ -30,10 +30,8 @@ import org.springframework.transaction.interceptor.TransactionAttribute; import org.springframework.transaction.interceptor.TransactionAttributeSource; import org.springframework.transaction.interceptor.TransactionInterceptor; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * @author Rob Harrop @@ -59,7 +57,7 @@ public class TxNamespaceHandlerTests { @Test public void isProxy() { ITestBean bean = getTestBean(); - assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).as("testBean is not a proxy").isTrue(); } @Test @@ -68,21 +66,21 @@ public class TxNamespaceHandlerTests { CallCountingTransactionManager ptm = (CallCountingTransactionManager) context.getBean("transactionManager"); // try with transactional - assertEquals("Should not have any started transactions", 0, ptm.begun); + assertThat(ptm.begun).as("Should not have any started transactions").isEqualTo(0); testBean.getName(); - assertTrue(ptm.lastDefinition.isReadOnly()); - assertEquals("Should have 1 started transaction", 1, ptm.begun); - assertEquals("Should have 1 committed transaction", 1, ptm.commits); + assertThat(ptm.lastDefinition.isReadOnly()).isTrue(); + assertThat(ptm.begun).as("Should have 1 started transaction").isEqualTo(1); + assertThat(ptm.commits).as("Should have 1 committed transaction").isEqualTo(1); // try with non-transaction testBean.haveBirthday(); - assertEquals("Should not have started another transaction", 1, ptm.begun); + assertThat(ptm.begun).as("Should not have started another transaction").isEqualTo(1); // try with exceptional assertThatExceptionOfType(Throwable.class).isThrownBy(() -> testBean.exceptional(new IllegalArgumentException("foo"))); - assertEquals("Should have another started transaction", 2, ptm.begun); - assertEquals("Should have 1 rolled back transaction", 1, ptm.rollbacks); + assertThat(ptm.begun).as("Should have another started transaction").isEqualTo(2); + assertThat(ptm.rollbacks).as("Should have 1 rolled back transaction").isEqualTo(1); } @Test @@ -90,10 +88,10 @@ public class TxNamespaceHandlerTests { TransactionInterceptor txInterceptor = (TransactionInterceptor) context.getBean("txRollbackAdvice"); TransactionAttributeSource txAttrSource = txInterceptor.getTransactionAttributeSource(); TransactionAttribute txAttr = txAttrSource.getTransactionAttribute(getAgeMethod,ITestBean.class); - assertTrue("should be configured to rollback on Exception",txAttr.rollbackOn(new Exception())); + assertThat(txAttr.rollbackOn(new Exception())).as("should be configured to rollback on Exception").isTrue(); txAttr = txAttrSource.getTransactionAttribute(setAgeMethod, ITestBean.class); - assertFalse("should not rollback on RuntimeException",txAttr.rollbackOn(new RuntimeException())); + assertThat(txAttr.rollbackOn(new RuntimeException())).as("should not rollback on RuntimeException").isFalse(); } private ITestBean getTestBean() { diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSourceTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSourceTests.java index 1800b83db4c..db11d054398 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSourceTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSourceTests.java @@ -38,11 +38,7 @@ import org.springframework.transaction.interceptor.TransactionAttribute; import org.springframework.transaction.interceptor.TransactionInterceptor; import org.springframework.util.SerializationTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Colin Sampaleanu @@ -64,7 +60,7 @@ public class AnnotationTransactionAttributeSourceTests { proxyFactory.setTarget(tb); ITestBean1 proxy = (ITestBean1) proxyFactory.getProxy(); proxy.getAge(); - assertEquals(1, ptm.commits); + assertThat(ptm.commits).isEqualTo(1); ITestBean1 serializedProxy = (ITestBean1) SerializationTestUtils.serializeAndDeserialize(proxy); serializedProxy.getAge(); @@ -72,7 +68,7 @@ public class AnnotationTransactionAttributeSourceTests { TransactionInterceptor serializedTi = (TransactionInterceptor) advised.getAdvisors()[0].getAdvice(); CallCountingTransactionManager serializedPtm = (CallCountingTransactionManager) serializedTi.getTransactionManager(); - assertEquals(2, serializedPtm.commits); + assertThat(serializedPtm.commits).isEqualTo(2); } @Test @@ -80,10 +76,10 @@ public class AnnotationTransactionAttributeSourceTests { Method method = Empty.class.getMethod("getAge"); AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource(); - assertNull(atas.getTransactionAttribute(method, null)); + assertThat(atas.getTransactionAttribute(method, null)).isNull(); // Try again in case of caching - assertNull(atas.getTransactionAttribute(method, null)); + assertThat(atas.getTransactionAttribute(method, null)).isNull(); } /** @@ -99,7 +95,7 @@ public class AnnotationTransactionAttributeSourceTests { RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); rbta.getRollbackRules().add(new RollbackRuleAttribute(Exception.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); } /** @@ -119,7 +115,7 @@ public class AnnotationTransactionAttributeSourceTests { RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); rbta.getRollbackRules().add(new RollbackRuleAttribute(Exception.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); } /** @@ -133,7 +129,7 @@ public class AnnotationTransactionAttributeSourceTests { TransactionAttribute actual = atas.getTransactionAttribute(interfaceMethod, TestBean2.class); RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); } /** @@ -146,18 +142,18 @@ public class AnnotationTransactionAttributeSourceTests { AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource(); TransactionAttribute actual = atas.getTransactionAttribute(interfaceMethod, TestBean3.class); - assertEquals(TransactionAttribute.PROPAGATION_REQUIRES_NEW, actual.getPropagationBehavior()); - assertEquals(TransactionAttribute.ISOLATION_REPEATABLE_READ, actual.getIsolationLevel()); - assertEquals(5, actual.getTimeout()); - assertTrue(actual.isReadOnly()); + assertThat(actual.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRES_NEW); + assertThat(actual.getIsolationLevel()).isEqualTo(TransactionAttribute.ISOLATION_REPEATABLE_READ); + assertThat(actual.getTimeout()).isEqualTo(5); + assertThat(actual.isReadOnly()).isTrue(); RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); rbta.getRollbackRules().add(new RollbackRuleAttribute(Exception.class)); rbta.getRollbackRules().add(new NoRollbackRuleAttribute(IOException.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); TransactionAttribute actual2 = atas.getTransactionAttribute(interfaceMethod2, TestBean3.class); - assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, actual2.getPropagationBehavior()); + assertThat(actual2.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); } @Test @@ -171,9 +167,9 @@ public class AnnotationTransactionAttributeSourceTests { rbta.getRollbackRules().add(new RollbackRuleAttribute("java.lang.Exception")); rbta.getRollbackRules().add(new NoRollbackRuleAttribute(IOException.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); - assertTrue(actual.rollbackOn(new Exception())); - assertFalse(actual.rollbackOn(new IOException())); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); + assertThat(actual.rollbackOn(new Exception())).isTrue(); + assertThat(actual.rollbackOn(new IOException())).isFalse(); actual = atas.getTransactionAttribute(method, method.getDeclaringClass()); @@ -181,9 +177,9 @@ public class AnnotationTransactionAttributeSourceTests { rbta.getRollbackRules().add(new RollbackRuleAttribute("java.lang.Exception")); rbta.getRollbackRules().add(new NoRollbackRuleAttribute(IOException.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); - assertTrue(actual.rollbackOn(new Exception())); - assertFalse(actual.rollbackOn(new IOException())); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); + assertThat(actual.rollbackOn(new Exception())).isTrue(); + assertThat(actual.rollbackOn(new IOException())).isFalse(); } /** @@ -200,7 +196,7 @@ public class AnnotationTransactionAttributeSourceTests { RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); rbta.getRollbackRules().add(new RollbackRuleAttribute(Exception.class)); rbta.getRollbackRules().add(new NoRollbackRuleAttribute(IOException.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); } @Test @@ -213,7 +209,7 @@ public class AnnotationTransactionAttributeSourceTests { RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); rbta.getRollbackRules().add(new RollbackRuleAttribute(Exception.class)); rbta.getRollbackRules().add(new NoRollbackRuleAttribute(IOException.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); } @Test @@ -226,7 +222,7 @@ public class AnnotationTransactionAttributeSourceTests { RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); rbta.getRollbackRules().add(new RollbackRuleAttribute(Exception.class)); rbta.getRollbackRules().add(new NoRollbackRuleAttribute(IOException.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); } @Test @@ -239,9 +235,9 @@ public class AnnotationTransactionAttributeSourceTests { RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); rbta.getRollbackRules().add(new RollbackRuleAttribute(Exception.class)); rbta.getRollbackRules().add(new NoRollbackRuleAttribute(IOException.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); - assertTrue(actual.isReadOnly()); + assertThat(actual.isReadOnly()).isTrue(); } @Test @@ -254,9 +250,9 @@ public class AnnotationTransactionAttributeSourceTests { RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); rbta.getRollbackRules().add(new RollbackRuleAttribute(Exception.class)); rbta.getRollbackRules().add(new NoRollbackRuleAttribute(IOException.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); - assertTrue(actual.isReadOnly()); + assertThat(actual.isReadOnly()).isTrue(); } @Test @@ -264,20 +260,20 @@ public class AnnotationTransactionAttributeSourceTests { Method method = TestInterface9.class.getMethod("getAge"); Transactional annotation = AnnotationUtils.findAnnotation(method, Transactional.class); - assertNull("AnnotationUtils.findAnnotation should not find @Transactional for TestBean9.getAge()", annotation); + assertThat(annotation).as("AnnotationUtils.findAnnotation should not find @Transactional for TestBean9.getAge()").isNull(); annotation = AnnotationUtils.findAnnotation(TestBean9.class, Transactional.class); - assertNotNull("AnnotationUtils.findAnnotation failed to find @Transactional for TestBean9", annotation); + assertThat(annotation).as("AnnotationUtils.findAnnotation failed to find @Transactional for TestBean9").isNotNull(); AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource(); TransactionAttribute actual = atas.getTransactionAttribute(method, TestBean9.class); - assertNotNull("Failed to retrieve TransactionAttribute for TestBean9.getAge()", actual); + assertThat(actual).as("Failed to retrieve TransactionAttribute for TestBean9.getAge()").isNotNull(); RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); rbta.getRollbackRules().add(new RollbackRuleAttribute(Exception.class)); rbta.getRollbackRules().add(new NoRollbackRuleAttribute(IOException.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); - assertTrue(actual.isReadOnly()); + assertThat(actual.isReadOnly()).isTrue(); } @Test @@ -285,21 +281,20 @@ public class AnnotationTransactionAttributeSourceTests { Method method = TestInterface10.class.getMethod("getAge"); Transactional annotation = AnnotationUtils.findAnnotation(method, Transactional.class); - assertNotNull("AnnotationUtils.findAnnotation failed to find @Transactional for TestBean10.getAge()", - annotation); + assertThat(annotation).as("AnnotationUtils.findAnnotation failed to find @Transactional for TestBean10.getAge()").isNotNull(); annotation = AnnotationUtils.findAnnotation(TestBean10.class, Transactional.class); - assertNull("AnnotationUtils.findAnnotation should not find @Transactional for TestBean10", annotation); + assertThat(annotation).as("AnnotationUtils.findAnnotation should not find @Transactional for TestBean10").isNull(); AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource(); TransactionAttribute actual = atas.getTransactionAttribute(method, TestBean10.class); - assertNotNull("Failed to retrieve TransactionAttribute for TestBean10.getAge()", actual); + assertThat(actual).as("Failed to retrieve TransactionAttribute for TestBean10.getAge()").isNotNull(); RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); rbta.getRollbackRules().add(new RollbackRuleAttribute(Exception.class)); rbta.getRollbackRules().add(new NoRollbackRuleAttribute(IOException.class)); - assertEquals(rbta.getRollbackRules(), ((RuleBasedTransactionAttribute) actual).getRollbackRules()); + assertThat(((RuleBasedTransactionAttribute) actual).getRollbackRules()).isEqualTo(rbta.getRollbackRules()); - assertTrue(actual.isReadOnly()); + assertThat(actual.isReadOnly()).isTrue(); } @Test @@ -309,9 +304,9 @@ public class AnnotationTransactionAttributeSourceTests { AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource(); TransactionAttribute getAgeAttr = atas.getTransactionAttribute(getAgeMethod, Ejb3AnnotatedBean1.class); - assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, getAgeAttr.getPropagationBehavior()); + assertThat(getAgeAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); TransactionAttribute getNameAttr = atas.getTransactionAttribute(getNameMethod, Ejb3AnnotatedBean1.class); - assertEquals(TransactionAttribute.PROPAGATION_SUPPORTS, getNameAttr.getPropagationBehavior()); + assertThat(getNameAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_SUPPORTS); } @Test @@ -321,9 +316,9 @@ public class AnnotationTransactionAttributeSourceTests { AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource(); TransactionAttribute getAgeAttr = atas.getTransactionAttribute(getAgeMethod, Ejb3AnnotatedBean2.class); - assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, getAgeAttr.getPropagationBehavior()); + assertThat(getAgeAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); TransactionAttribute getNameAttr = atas.getTransactionAttribute(getNameMethod, Ejb3AnnotatedBean2.class); - assertEquals(TransactionAttribute.PROPAGATION_SUPPORTS, getNameAttr.getPropagationBehavior()); + assertThat(getNameAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_SUPPORTS); } @Test @@ -333,9 +328,9 @@ public class AnnotationTransactionAttributeSourceTests { AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource(); TransactionAttribute getAgeAttr = atas.getTransactionAttribute(getAgeMethod, Ejb3AnnotatedBean3.class); - assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, getAgeAttr.getPropagationBehavior()); + assertThat(getAgeAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); TransactionAttribute getNameAttr = atas.getTransactionAttribute(getNameMethod, Ejb3AnnotatedBean3.class); - assertEquals(TransactionAttribute.PROPAGATION_SUPPORTS, getNameAttr.getPropagationBehavior()); + assertThat(getNameAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_SUPPORTS); } @Test @@ -345,9 +340,9 @@ public class AnnotationTransactionAttributeSourceTests { AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource(); TransactionAttribute getAgeAttr = atas.getTransactionAttribute(getAgeMethod, JtaAnnotatedBean1.class); - assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, getAgeAttr.getPropagationBehavior()); + assertThat(getAgeAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); TransactionAttribute getNameAttr = atas.getTransactionAttribute(getNameMethod, JtaAnnotatedBean1.class); - assertEquals(TransactionAttribute.PROPAGATION_SUPPORTS, getNameAttr.getPropagationBehavior()); + assertThat(getNameAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_SUPPORTS); } @Test @@ -357,9 +352,9 @@ public class AnnotationTransactionAttributeSourceTests { AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource(); TransactionAttribute getAgeAttr = atas.getTransactionAttribute(getAgeMethod, JtaAnnotatedBean2.class); - assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, getAgeAttr.getPropagationBehavior()); + assertThat(getAgeAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); TransactionAttribute getNameAttr = atas.getTransactionAttribute(getNameMethod, JtaAnnotatedBean2.class); - assertEquals(TransactionAttribute.PROPAGATION_SUPPORTS, getNameAttr.getPropagationBehavior()); + assertThat(getNameAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_SUPPORTS); } @Test @@ -369,9 +364,9 @@ public class AnnotationTransactionAttributeSourceTests { AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource(); TransactionAttribute getAgeAttr = atas.getTransactionAttribute(getAgeMethod, JtaAnnotatedBean3.class); - assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, getAgeAttr.getPropagationBehavior()); + assertThat(getAgeAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); TransactionAttribute getNameAttr = atas.getTransactionAttribute(getNameMethod, JtaAnnotatedBean3.class); - assertEquals(TransactionAttribute.PROPAGATION_SUPPORTS, getNameAttr.getPropagationBehavior()); + assertThat(getNameAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_SUPPORTS); } @Test @@ -382,10 +377,10 @@ public class AnnotationTransactionAttributeSourceTests { AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource(); TransactionAttribute getAgeAttr = atas.getTransactionAttribute(getAgeMethod, GroovyTestBean.class); - assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, getAgeAttr.getPropagationBehavior()); + assertThat(getAgeAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); TransactionAttribute getNameAttr = atas.getTransactionAttribute(getNameMethod, GroovyTestBean.class); - assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, getNameAttr.getPropagationBehavior()); - assertNull(atas.getTransactionAttribute(getMetaClassMethod, GroovyTestBean.class)); + assertThat(getNameAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); + assertThat(atas.getTransactionAttribute(getMetaClassMethod, GroovyTestBean.class)).isNull(); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java index 08813ed3074..8c1f45a7fd0 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java @@ -24,12 +24,10 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.interceptor.TransactionInterceptor; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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 @@ -335,13 +333,13 @@ public class AnnotationTransactionInterceptorTests { } private void assertGetTransactionAndCommitCount(int expectedCount) { - assertEquals(expectedCount, this.ptm.begun); - assertEquals(expectedCount, this.ptm.commits); + assertThat(this.ptm.begun).isEqualTo(expectedCount); + assertThat(this.ptm.commits).isEqualTo(expectedCount); } private void assertGetTransactionAndRollbackCount(int expectedCount) { - assertEquals(expectedCount, this.ptm.begun); - assertEquals(expectedCount, this.ptm.rollbacks); + assertThat(this.ptm.begun).isEqualTo(expectedCount); + assertThat(this.ptm.rollbacks).isEqualTo(expectedCount); } @@ -349,13 +347,13 @@ public class AnnotationTransactionInterceptorTests { public static class TestClassLevelOnly { public void doSomething() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } public void doSomethingElse() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } } @@ -364,19 +362,19 @@ public class AnnotationTransactionInterceptorTests { public static class TestWithSingleMethodOverride { public void doSomething() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } @Transactional(readOnly = true) public void doSomethingElse() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); } public void doSomethingCompletelyElse() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } } @@ -386,18 +384,18 @@ public class AnnotationTransactionInterceptorTests { @Transactional public void doSomething() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } public void doSomethingElse() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); } public void doSomethingCompletelyElse() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); } } @@ -407,19 +405,19 @@ public class AnnotationTransactionInterceptorTests { @Transactional(readOnly = true) public void doSomething() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); } @Transactional(readOnly = true) public void doSomethingElse() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); } public void doSomethingCompletelyElse() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } } @@ -428,28 +426,28 @@ public class AnnotationTransactionInterceptorTests { public static class TestWithExceptions { public void doSomethingErroneous() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); throw new IllegalStateException(); } public void doSomethingElseErroneous() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); throw new IllegalArgumentException(); } @Transactional public void doSomethingElseWithCheckedException() throws Exception { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); throw new Exception(); } @Transactional(rollbackFor = Exception.class) public void doSomethingElseWithCheckedExceptionAndRollbackRule() throws Exception { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); throw new Exception(); } } @@ -459,27 +457,27 @@ public class AnnotationTransactionInterceptorTests { public static class TestWithVavrTry { public Try doSomething() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); return Try.success("ok"); } public Try doSomethingErroneous() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); return Try.failure(new IllegalStateException()); } public Try doSomethingErroneousWithCheckedException() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); return Try.failure(new Exception()); } @Transactional(rollbackFor = Exception.class) public Try doSomethingErroneousWithCheckedExceptionAndRollbackRule() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); return Try.failure(new Exception()); } } @@ -498,8 +496,8 @@ public class AnnotationTransactionInterceptorTests { void doSomethingElse(); default void doSomethingDefault() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } } @@ -508,14 +506,14 @@ public class AnnotationTransactionInterceptorTests { @Override public void doSomething() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } @Override public void doSomethingElse() { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java index 8d6d0dacc61..d7e52a2dfb2 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java @@ -35,9 +35,8 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.config.TransactionManagementConfigUtils; import org.springframework.transaction.event.TransactionalEventListenerFactory; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Rob Harrop @@ -57,9 +56,9 @@ public class AnnotationTransactionNamespaceHandlerTests { @Test public void isProxy() throws Exception { TransactionalTestBean bean = getTestBean(); - assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).as("testBean is not a proxy").isTrue(); Map services = this.context.getBeansWithAnnotation(Service.class); - assertTrue("Stereotype annotation not visible", services.containsKey("testBean")); + assertThat(services.containsKey("testBean")).as("Stereotype annotation not visible").isTrue(); } @Test @@ -68,21 +67,21 @@ public class AnnotationTransactionNamespaceHandlerTests { CallCountingTransactionManager ptm = (CallCountingTransactionManager) context.getBean("transactionManager"); // try with transactional - assertEquals("Should not have any started transactions", 0, ptm.begun); + assertThat(ptm.begun).as("Should not have any started transactions").isEqualTo(0); testBean.findAllFoos(); - assertEquals("Should have 1 started transaction", 1, ptm.begun); - assertEquals("Should have 1 committed transaction", 1, ptm.commits); + assertThat(ptm.begun).as("Should have 1 started transaction").isEqualTo(1); + assertThat(ptm.commits).as("Should have 1 committed transaction").isEqualTo(1); // try with non-transaction testBean.doSomething(); - assertEquals("Should not have started another transaction", 1, ptm.begun); + assertThat(ptm.begun).as("Should not have started another transaction").isEqualTo(1); // try with exceptional assertThatExceptionOfType(Throwable.class).isThrownBy(() -> testBean.exceptional(new IllegalArgumentException("foo"))) .satisfies(ex -> { - assertEquals("Should have another started transaction", 2, ptm.begun); - assertEquals("Should have 1 rolled back transaction", 1, ptm.rollbacks); + assertThat(ptm.begun).as("Should have another started transaction").isEqualTo(2); + assertThat(ptm.rollbacks).as("Should have 1 rolled back transaction").isEqualTo(1); }); } @@ -91,23 +90,23 @@ public class AnnotationTransactionNamespaceHandlerTests { TransactionalTestBean testBean = getTestBean(); CallCountingTransactionManager ptm = (CallCountingTransactionManager) context.getBean("transactionManager"); - assertEquals("Should not have any started transactions", 0, ptm.begun); + assertThat(ptm.begun).as("Should not have any started transactions").isEqualTo(0); testBean.annotationsOnProtectedAreIgnored(); - assertEquals("Should not have any started transactions", 0, ptm.begun); + assertThat(ptm.begun).as("Should not have any started transactions").isEqualTo(0); } @Test public void mBeanExportAlsoWorks() throws Exception { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - assertEquals("done", - server.invoke(ObjectName.getInstance("test:type=TestBean"), "doSomething", new Object[0], new String[0])); + Object actual = server.invoke(ObjectName.getInstance("test:type=TestBean"), "doSomething", new Object[0], new String[0]); + assertThat(actual).isEqualTo("done"); } @Test public void transactionalEventListenerRegisteredProperly() { - assertTrue(this.context.containsBean(TransactionManagementConfigUtils - .TRANSACTIONAL_EVENT_LISTENER_FACTORY_BEAN_NAME)); - assertEquals(1, this.context.getBeansOfType(TransactionalEventListenerFactory.class).size()); + assertThat(this.context.containsBean(TransactionManagementConfigUtils + .TRANSACTIONAL_EVENT_LISTENER_FACTORY_BEAN_NAME)).isTrue(); + assertThat(this.context.getBeansOfType(TransactionalEventListenerFactory.class).size()).isEqualTo(1); } private TransactionalTestBean getTestBean() { diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java index 1a4ff2ee893..ed0f58aea91 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java @@ -40,8 +40,6 @@ import org.springframework.transaction.event.TransactionalEventListenerFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Tests demonstrating use of @EnableTransactionManagement @Configuration classes. @@ -59,9 +57,9 @@ public class EnableTransactionManagementTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( EnableTxConfig.class, TxManagerConfig.class); TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class); - assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).as("testBean is not a proxy").isTrue(); Map services = ctx.getBeansWithAnnotation(Service.class); - assertTrue("Stereotype annotation not visible", services.containsKey("testBean")); + assertThat(services.containsKey("testBean")).as("Stereotype annotation not visible").isTrue(); ctx.close(); } @@ -70,9 +68,9 @@ public class EnableTransactionManagementTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( InheritedEnableTxConfig.class, TxManagerConfig.class); TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class); - assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).as("testBean is not a proxy").isTrue(); Map services = ctx.getBeansWithAnnotation(Service.class); - assertTrue("Stereotype annotation not visible", services.containsKey("testBean")); + assertThat(services.containsKey("testBean")).as("Stereotype annotation not visible").isTrue(); ctx.close(); } @@ -81,9 +79,9 @@ public class EnableTransactionManagementTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( ParentEnableTxConfig.class, ChildEnableTxConfig.class, TxManagerConfig.class); TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class); - assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); + assertThat(AopUtils.isAopProxy(bean)).as("testBean is not a proxy").isTrue(); Map services = ctx.getBeansWithAnnotation(Service.class); - assertTrue("Stereotype annotation not visible", services.containsKey("testBean")); + assertThat(services.containsKey("testBean")).as("Stereotype annotation not visible").isTrue(); ctx.close(); } @@ -126,8 +124,8 @@ public class EnableTransactionManagementTests { @Test public void transactionalEventListenerRegisteredProperly() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(EnableTxConfig.class); - assertTrue(ctx.containsBean(TransactionManagementConfigUtils.TRANSACTIONAL_EVENT_LISTENER_FACTORY_BEAN_NAME)); - assertEquals(1, ctx.getBeansOfType(TransactionalEventListenerFactory.class).size()); + assertThat(ctx.containsBean(TransactionManagementConfigUtils.TRANSACTIONAL_EVENT_LISTENER_FACTORY_BEAN_NAME)).isTrue(); + assertThat(ctx.getBeansOfType(TransactionalEventListenerFactory.class).size()).isEqualTo(1); ctx.close(); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java b/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java index 6d1b7d19ca9..8f58b2656f8 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java @@ -31,9 +31,7 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.SerializationTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -68,19 +66,19 @@ public class AnnotationDrivenTests { CallCountingTransactionManager tm1 = context.getBean("transactionManager1", CallCountingTransactionManager.class); CallCountingTransactionManager tm2 = context.getBean("transactionManager2", CallCountingTransactionManager.class); TransactionalService service = context.getBean("service", TransactionalService.class); - assertTrue(AopUtils.isCglibProxy(service)); + assertThat(AopUtils.isCglibProxy(service)).isTrue(); service.setSomething("someName"); - assertEquals(1, tm1.commits); - assertEquals(0, tm2.commits); + assertThat(tm1.commits).isEqualTo(1); + assertThat(tm2.commits).isEqualTo(0); service.doSomething(); - assertEquals(1, tm1.commits); - assertEquals(1, tm2.commits); + assertThat(tm1.commits).isEqualTo(1); + assertThat(tm2.commits).isEqualTo(1); service.setSomething("someName"); - assertEquals(2, tm1.commits); - assertEquals(1, tm2.commits); + assertThat(tm1.commits).isEqualTo(2); + assertThat(tm2.commits).isEqualTo(1); service.doSomething(); - assertEquals(2, tm1.commits); - assertEquals(2, tm2.commits); + assertThat(tm1.commits).isEqualTo(2); + assertThat(tm2.commits).isEqualTo(2); } @Test @@ -109,12 +107,12 @@ public class AnnotationDrivenTests { @Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { if (methodInvocation.getMethod().getName().equals("setSomething")) { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); } else { - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } return methodInvocation.proceed(); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/event/ApplicationListenerMethodTransactionalAdapterTests.java b/spring-tx/src/test/java/org/springframework/transaction/event/ApplicationListenerMethodTransactionalAdapterTests.java index 7ac37ec48bb..7d020043c3e 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/event/ApplicationListenerMethodTransactionalAdapterTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/event/ApplicationListenerMethodTransactionalAdapterTests.java @@ -26,8 +26,7 @@ import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.util.ReflectionUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -64,16 +63,15 @@ public class ApplicationListenerMethodTransactionalAdapterTests { } private void assertPhase(Method method, TransactionPhase expected) { - assertNotNull("Method must not be null", method); + assertThat(method).as("Method must not be null").isNotNull(); TransactionalEventListener annotation = AnnotatedElementUtils.findMergedAnnotation(method, TransactionalEventListener.class); - assertEquals("Wrong phase for '" + method + "'", expected, annotation.phase()); + assertThat(annotation.phase()).as("Wrong phase for '" + method + "'").isEqualTo(expected); } private void supportsEventType(boolean match, Method method, ResolvableType eventType) { ApplicationListenerMethodAdapter adapter = createTestInstance(method); - assertEquals("Wrong match for event '" + eventType + "' on " + method, - match, adapter.supportsEventType(eventType)); + assertThat(adapter.supportsEventType(eventType)).as("Wrong match for event '" + eventType + "' on " + method).isEqualTo(match); } private ApplicationListenerMethodTransactionalAdapter createTestInstance(Method m) { diff --git a/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalEventListenerTests.java b/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalEventListenerTests.java index 2accdb03fd1..85cb6ed3066 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalEventListenerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalEventListenerTests.java @@ -46,8 +46,8 @@ import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; import static org.springframework.transaction.event.TransactionPhase.AFTER_COMMIT; import static org.springframework.transaction.event.TransactionPhase.AFTER_COMPLETION; import static org.springframework.transaction.event.TransactionPhase.AFTER_ROLLBACK; @@ -375,16 +375,16 @@ public class TransactionalEventListenerTests { } for (String phase : phases) { List eventsForPhase = getEvents(phase); - assertEquals("Expected no events for phase '" + phase + "' " + - "but got " + eventsForPhase + ":", 0, eventsForPhase.size()); + assertThat(eventsForPhase.size()).as("Expected no events for phase '" + phase + "' " + + "but got " + eventsForPhase + ":").isEqualTo(0); } } public void assertEvents(String phase, Object... expected) { List actual = getEvents(phase); - assertEquals("wrong number of events for phase '" + phase + "'", expected.length, actual.size()); + assertThat(actual.size()).as("wrong number of events for phase '" + phase + "'").isEqualTo(expected.length); for (int i = 0; i < expected.length; i++) { - assertEquals("Wrong event for phase '" + phase + "' at index " + i, expected[i], actual.get(i)); + assertThat(actual.get(i)).as("Wrong event for phase '" + phase + "' at index " + i).isEqualTo(expected[i]); } } @@ -393,8 +393,8 @@ public class TransactionalEventListenerTests { for (Map.Entry> entry : this.events.entrySet()) { size += entry.getValue().size(); } - assertEquals("Wrong number of total events (" + this.events.size() + ") " + - "registered phase(s)", number, size); + assertThat(size).as("Wrong number of total events (" + this.events.size() + ") " + + "registered phase(s)").isEqualTo(number); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractReactiveTransactionAspectTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractReactiveTransactionAspectTests.java index c4e673a80d0..3ffde417f65 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractReactiveTransactionAspectTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractReactiveTransactionAspectTests.java @@ -33,7 +33,6 @@ import org.springframework.transaction.reactive.TransactionContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; -import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -337,8 +336,8 @@ public abstract class AbstractReactiveTransactionAspectTests { Mono.from(itb.setName(name)) .as(StepVerifier::create) .consumeErrorWith(throwable -> { - assertEquals(RuntimeException.class, throwable.getClass()); - assertEquals(ex, throwable.getCause()); + assertThat(throwable.getClass()).isEqualTo(RuntimeException.class); + assertThat(throwable.getCause()).isEqualTo(ex); }) .verify(); diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java index 68584d7f3ca..aa180bb4de8 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java @@ -34,12 +34,9 @@ import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.UnexpectedRollbackException; import org.springframework.transaction.interceptor.TransactionAspectSupport.TransactionInfo; +import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -141,8 +138,8 @@ public abstract class AbstractTransactionAspectTests { itb.getName(); checkTransactionStatus(false); - assertSame(txatt, ptm.getDefinition()); - assertFalse(ptm.getStatus().isRollbackOnly()); + assertThat(ptm.getDefinition()).isSameAs(txatt); + assertThat(ptm.getStatus().isRollbackOnly()).isFalse(); } @Test @@ -162,8 +159,8 @@ public abstract class AbstractTransactionAspectTests { itb.exceptional(new OptimisticLockingFailureException(""))); checkTransactionStatus(false); - assertSame(txatt, ptm.getDefinition()); - assertFalse(ptm.getStatus().isRollbackOnly()); + assertThat(ptm.getDefinition()).isSameAs(txatt); + assertThat(ptm.getStatus().isRollbackOnly()).isFalse(); } /** @@ -239,8 +236,8 @@ public abstract class AbstractTransactionAspectTests { @Override public void exceptional(Throwable t) throws Throwable { TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo(); - assertTrue(ti.hasTransaction()); - assertEquals(spouseName, getSpouse().getName()); + assertThat(ti.hasTransaction()).isTrue(); + assertThat(getSpouse().getName()).isEqualTo(spouseName); } }; TestBean inner = new TestBean() { @@ -248,7 +245,7 @@ public abstract class AbstractTransactionAspectTests { public String getName() { // Assert that we're in the inner proxy TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo(); - assertFalse(ti.hasTransaction()); + assertThat(ti.hasTransaction()).isFalse(); return spouseName; } }; @@ -292,9 +289,9 @@ public abstract class AbstractTransactionAspectTests { @Override public void exceptional(Throwable t) throws Throwable { TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo(); - assertTrue(ti.hasTransaction()); - assertEquals(outerTxatt, ti.getTransactionAttribute()); - assertEquals(spouseName, getSpouse().getName()); + assertThat(ti.hasTransaction()).isTrue(); + assertThat(ti.getTransactionAttribute()).isEqualTo(outerTxatt); + assertThat(getSpouse().getName()).isEqualTo(spouseName); } }; TestBean inner = new TestBean() { @@ -303,8 +300,8 @@ public abstract class AbstractTransactionAspectTests { // Assert that we're in the inner proxy TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo(); // Has nested transaction - assertTrue(ti.hasTransaction()); - assertEquals(innerTxatt, ti.getTransactionAttribute()); + assertThat(ti.hasTransaction()).isTrue(); + assertThat(ti.getTransactionAttribute()).isEqualTo(innerTxatt); return spouseName; } }; @@ -377,7 +374,7 @@ public abstract class AbstractTransactionAspectTests { TransactionAttribute txatt = new DefaultTransactionAttribute() { @Override public boolean rollbackOn(Throwable t) { - assertTrue(t == ex); + assertThat(t == ex).isTrue(); return shouldRollback; } }; @@ -411,10 +408,10 @@ public abstract class AbstractTransactionAspectTests { } catch (Throwable t) { if (rollbackException) { - assertEquals("Caught wrong exception", tex, t); + assertThat(t).as("Caught wrong exception").isEqualTo(tex); } else { - assertEquals("Caught wrong exception", ex, t); + assertThat(t).as("Caught wrong exception").isEqualTo(ex); } } @@ -457,7 +454,7 @@ public abstract class AbstractTransactionAspectTests { ITestBean itb = (ITestBean) advised(tb, ptm, tas); // verification!? - assertTrue(name.equals(itb.getName())); + assertThat(name.equals(itb.getName())).isTrue(); verify(ptm).commit(status); } @@ -493,7 +490,7 @@ public abstract class AbstractTransactionAspectTests { fail("Shouldn't have invoked method"); } catch (CannotCreateTransactionException thrown) { - assertTrue(thrown == ex); + assertThat(thrown == ex).isTrue(); } } @@ -528,11 +525,11 @@ public abstract class AbstractTransactionAspectTests { fail("Shouldn't have succeeded"); } catch (UnexpectedRollbackException thrown) { - assertTrue(thrown == ex); + assertThat(thrown == ex).isTrue(); } // Should have invoked target and changed name - assertTrue(itb.getName() == name); + assertThat(itb.getName() == name).isTrue(); } protected void checkTransactionStatus(boolean expected) { diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java index 47b0c3b3155..b9590307c08 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java @@ -42,11 +42,8 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionStatus; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; @@ -73,8 +70,9 @@ public class BeanFactoryTransactionTests { @Test public void testGetsAreNotTransactionalWithProxyFactory1() { ITestBean testBean = (ITestBean) factory.getBean("proxyFactory1"); - assertTrue("testBean is a dynamic proxy", Proxy.isProxyClass(testBean.getClass())); - assertFalse(testBean instanceof TransactionalProxy); + assertThat(Proxy.isProxyClass(testBean.getClass())).as("testBean is a dynamic proxy").isTrue(); + boolean condition = testBean instanceof TransactionalProxy; + assertThat(condition).isFalse(); doTestGetsAreNotTransactional(testBean); } @@ -82,32 +80,35 @@ public class BeanFactoryTransactionTests { public void testGetsAreNotTransactionalWithProxyFactory2DynamicProxy() { this.factory.preInstantiateSingletons(); ITestBean testBean = (ITestBean) factory.getBean("proxyFactory2DynamicProxy"); - assertTrue("testBean is a dynamic proxy", Proxy.isProxyClass(testBean.getClass())); - assertTrue(testBean instanceof TransactionalProxy); + assertThat(Proxy.isProxyClass(testBean.getClass())).as("testBean is a dynamic proxy").isTrue(); + boolean condition = testBean instanceof TransactionalProxy; + assertThat(condition).isTrue(); doTestGetsAreNotTransactional(testBean); } @Test public void testGetsAreNotTransactionalWithProxyFactory2Cglib() { ITestBean testBean = (ITestBean) factory.getBean("proxyFactory2Cglib"); - assertTrue("testBean is CGLIB advised", AopUtils.isCglibProxy(testBean)); - assertTrue(testBean instanceof TransactionalProxy); + assertThat(AopUtils.isCglibProxy(testBean)).as("testBean is CGLIB advised").isTrue(); + boolean condition = testBean instanceof TransactionalProxy; + assertThat(condition).isTrue(); doTestGetsAreNotTransactional(testBean); } @Test public void testProxyFactory2Lazy() { ITestBean testBean = (ITestBean) factory.getBean("proxyFactory2Lazy"); - assertFalse(factory.containsSingleton("target")); - assertEquals(666, testBean.getAge()); - assertTrue(factory.containsSingleton("target")); + assertThat(factory.containsSingleton("target")).isFalse(); + assertThat(testBean.getAge()).isEqualTo(666); + assertThat(factory.containsSingleton("target")).isTrue(); } @Test public void testCglibTransactionProxyImplementsNoInterfaces() { ImplementsNoInterfaces ini = (ImplementsNoInterfaces) factory.getBean("cglibNoInterfaces"); - assertTrue("testBean is CGLIB advised", AopUtils.isCglibProxy(ini)); - assertTrue(ini instanceof TransactionalProxy); + assertThat(AopUtils.isCglibProxy(ini)).as("testBean is CGLIB advised").isTrue(); + boolean condition = ini instanceof TransactionalProxy; + assertThat(condition).isTrue(); String newName = "Gordon"; // Install facade @@ -115,15 +116,17 @@ public class BeanFactoryTransactionTests { PlatformTransactionManagerFacade.delegate = ptm; ini.setName(newName); - assertEquals(newName, ini.getName()); - assertEquals(2, ptm.commits); + assertThat(ini.getName()).isEqualTo(newName); + assertThat(ptm.commits).isEqualTo(2); } @Test public void testGetsAreNotTransactionalWithProxyFactory3() { ITestBean testBean = (ITestBean) factory.getBean("proxyFactory3"); - assertTrue("testBean is a full proxy", testBean instanceof DerivedTestBean); - assertTrue(testBean instanceof TransactionalProxy); + boolean condition = testBean instanceof DerivedTestBean; + assertThat(condition).as("testBean is a full proxy").isTrue(); + boolean condition1 = testBean instanceof TransactionalProxy; + assertThat(condition1).isTrue(); InvocationCounterPointcut txnCounter = (InvocationCounterPointcut) factory.getBean("txnInvocationCounterPointcut"); InvocationCounterInterceptor preCounter = (InvocationCounterInterceptor) factory.getBean("preInvocationCounterInterceptor"); InvocationCounterInterceptor postCounter = (InvocationCounterInterceptor) factory.getBean("postInvocationCounterInterceptor"); @@ -132,9 +135,9 @@ public class BeanFactoryTransactionTests { postCounter.counter = 0; doTestGetsAreNotTransactional(testBean); // Can't assert it's equal to 4 as the pointcut may be optimized and only invoked once - assertTrue(0 < txnCounter.counter && txnCounter.counter <= 4); - assertEquals(4, preCounter.counter); - assertEquals(4, postCounter.counter); + assertThat(0 < txnCounter.counter && txnCounter.counter <= 4).isTrue(); + assertThat(preCounter.counter).isEqualTo(4); + assertThat(postCounter.counter).isEqualTo(4); } private void doTestGetsAreNotTransactional(final ITestBean testBean) { @@ -142,7 +145,7 @@ public class BeanFactoryTransactionTests { PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); PlatformTransactionManagerFacade.delegate = ptm; - assertTrue("Age should not be " + testBean.getAge(), testBean.getAge() == 666); + assertThat(testBean.getAge() == 666).as("Age should not be " + testBean.getAge()).isTrue(); // Expect no methods verifyZeroInteractions(ptm); @@ -165,7 +168,7 @@ public class BeanFactoryTransactionTests { } @Override public void commit(TransactionStatus status) throws TransactionException { - assertTrue(status == ts); + assertThat(status == ts).isTrue(); } @Override public void rollback(TransactionStatus status) throws TransactionException { @@ -177,13 +180,13 @@ public class BeanFactoryTransactionTests { // TODO same as old age to avoid ordering effect for now int age = 666; testBean.setAge(age); - assertTrue(testBean.getAge() == age); + assertThat(testBean.getAge() == age).isTrue(); } @Test public void testGetBeansOfTypeWithAbstract() { Map beansOfType = factory.getBeansOfType(ITestBean.class, true, true); - assertNotNull(beansOfType); + assertThat(beansOfType).isNotNull(); } /** @@ -208,22 +211,22 @@ public class BeanFactoryTransactionTests { PlatformTransactionManagerFacade.delegate = txMan; TestBean tb = (TestBean) factory.getBean("hotSwapped"); - assertEquals(666, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(666); int newAge = 557; tb.setAge(newAge); - assertEquals(newAge, tb.getAge()); + assertThat(tb.getAge()).isEqualTo(newAge); TestBean target2 = new TestBean(); target2.setAge(65); HotSwappableTargetSource ts = (HotSwappableTargetSource) factory.getBean("swapper"); ts.swap(target2); - assertEquals(target2.getAge(), tb.getAge()); + assertThat(tb.getAge()).isEqualTo(target2.getAge()); tb.setAge(newAge); - assertEquals(newAge, target2.getAge()); + assertThat(target2.getAge()).isEqualTo(newAge); - assertEquals(0, txMan.inflight); - assertEquals(2, txMan.commits); - assertEquals(0, txMan.rollbacks); + assertThat(txMan.inflight).isEqualTo(0); + assertThat(txMan.commits).isEqualTo(2); + assertThat(txMan.rollbacks).isEqualTo(0); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java index 77ff9260389..f7d8235a9fc 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java @@ -24,8 +24,6 @@ import org.springframework.beans.FatalBeanException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Unit tests for the {@link RollbackRuleAttribute} class. @@ -41,19 +39,19 @@ public class RollbackRuleTests { @Test public void foundImmediatelyWithString() { RollbackRuleAttribute rr = new RollbackRuleAttribute(java.lang.Exception.class.getName()); - assertEquals(0, rr.getDepth(new Exception())); + assertThat(rr.getDepth(new Exception())).isEqualTo(0); } @Test public void foundImmediatelyWithClass() { RollbackRuleAttribute rr = new RollbackRuleAttribute(Exception.class); - assertEquals(0, rr.getDepth(new Exception())); + assertThat(rr.getDepth(new Exception())).isEqualTo(0); } @Test public void notFound() { RollbackRuleAttribute rr = new RollbackRuleAttribute(java.io.IOException.class.getName()); - assertEquals(-1, rr.getDepth(new MyRuntimeException(""))); + assertThat(rr.getDepth(new MyRuntimeException(""))).isEqualTo(-1); } @Test @@ -66,10 +64,10 @@ public class RollbackRuleTests { @Test public void alwaysTrueForThrowable() { RollbackRuleAttribute rr = new RollbackRuleAttribute(java.lang.Throwable.class.getName()); - assertTrue(rr.getDepth(new MyRuntimeException("")) > 0); - assertTrue(rr.getDepth(new IOException()) > 0); - assertTrue(rr.getDepth(new FatalBeanException(null,null)) > 0); - assertTrue(rr.getDepth(new RuntimeException()) > 0); + assertThat(rr.getDepth(new MyRuntimeException("")) > 0).isTrue(); + assertThat(rr.getDepth(new IOException()) > 0).isTrue(); + assertThat(rr.getDepth(new FatalBeanException(null,null)) > 0).isTrue(); + assertThat(rr.getDepth(new RuntimeException()) > 0).isTrue(); } @Test diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttributeTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttributeTests.java index 830a3e465f7..19bccddda3a 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttributeTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/RuleBasedTransactionAttributeTests.java @@ -26,8 +26,7 @@ import org.junit.Test; import org.springframework.transaction.TransactionDefinition; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -41,10 +40,10 @@ public class RuleBasedTransactionAttributeTests { @Test public void testDefaultRule() { RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute(); - assertTrue(rta.rollbackOn(new RuntimeException())); - assertTrue(rta.rollbackOn(new MyRuntimeException(""))); - assertFalse(rta.rollbackOn(new Exception())); - assertFalse(rta.rollbackOn(new IOException())); + assertThat(rta.rollbackOn(new RuntimeException())).isTrue(); + assertThat(rta.rollbackOn(new MyRuntimeException(""))).isTrue(); + assertThat(rta.rollbackOn(new Exception())).isFalse(); + assertThat(rta.rollbackOn(new IOException())).isFalse(); } /** @@ -56,11 +55,11 @@ public class RuleBasedTransactionAttributeTests { list.add(new RollbackRuleAttribute(IOException.class.getName())); RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, list); - assertTrue(rta.rollbackOn(new RuntimeException())); - assertTrue(rta.rollbackOn(new MyRuntimeException(""))); - assertFalse(rta.rollbackOn(new Exception())); + assertThat(rta.rollbackOn(new RuntimeException())).isTrue(); + assertThat(rta.rollbackOn(new MyRuntimeException(""))).isTrue(); + assertThat(rta.rollbackOn(new Exception())).isFalse(); // Check that default behaviour is overridden - assertTrue(rta.rollbackOn(new IOException())); + assertThat(rta.rollbackOn(new IOException())).isTrue(); } @Test @@ -70,12 +69,12 @@ public class RuleBasedTransactionAttributeTests { list.add(new RollbackRuleAttribute(IOException.class.getName())); RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, list); - assertTrue(rta.rollbackOn(new RuntimeException())); + assertThat(rta.rollbackOn(new RuntimeException())).isTrue(); // Check default behaviour is overridden - assertFalse(rta.rollbackOn(new MyRuntimeException(""))); - assertFalse(rta.rollbackOn(new Exception())); + assertThat(rta.rollbackOn(new MyRuntimeException(""))).isFalse(); + assertThat(rta.rollbackOn(new Exception())).isFalse(); // Check that default behaviour is overridden - assertTrue(rta.rollbackOn(new IOException())); + assertThat(rta.rollbackOn(new IOException())).isTrue(); } @Test @@ -94,11 +93,11 @@ public class RuleBasedTransactionAttributeTests { } private void doTestRuleForSelectiveRollbackOnChecked(RuleBasedTransactionAttribute rta) { - assertTrue(rta.rollbackOn(new RuntimeException())); + assertThat(rta.rollbackOn(new RuntimeException())).isTrue(); // Check default behaviour is overridden - assertFalse(rta.rollbackOn(new Exception())); + assertThat(rta.rollbackOn(new Exception())).isFalse(); // Check that default behaviour is overridden - assertTrue(rta.rollbackOn(new RemoteException())); + assertThat(rta.rollbackOn(new RemoteException())).isTrue(); } /** @@ -114,10 +113,10 @@ public class RuleBasedTransactionAttributeTests { list.add(new NoRollbackRuleAttribute("IOException")); RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, list); - assertTrue(rta.rollbackOn(new RuntimeException())); - assertTrue(rta.rollbackOn(new Exception())); + assertThat(rta.rollbackOn(new RuntimeException())).isTrue(); + assertThat(rta.rollbackOn(new Exception())).isTrue(); // Check that default behaviour is overridden - assertFalse(rta.rollbackOn(new IOException())); + assertThat(rta.rollbackOn(new IOException())).isFalse(); } @Test @@ -126,11 +125,11 @@ public class RuleBasedTransactionAttributeTests { list.add(new NoRollbackRuleAttribute("Throwable")); RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, list); - assertFalse(rta.rollbackOn(new Throwable())); - assertFalse(rta.rollbackOn(new RuntimeException())); - assertFalse(rta.rollbackOn(new MyRuntimeException(""))); - assertFalse(rta.rollbackOn(new Exception())); - assertFalse(rta.rollbackOn(new IOException())); + assertThat(rta.rollbackOn(new Throwable())).isFalse(); + assertThat(rta.rollbackOn(new RuntimeException())).isFalse(); + assertThat(rta.rollbackOn(new MyRuntimeException(""))).isFalse(); + assertThat(rta.rollbackOn(new Exception())).isFalse(); + assertThat(rta.rollbackOn(new IOException())).isFalse(); } @Test @@ -143,11 +142,11 @@ public class RuleBasedTransactionAttributeTests { tae.setAsText(rta.toString()); rta = (RuleBasedTransactionAttribute) tae.getValue(); - assertFalse(rta.rollbackOn(new Throwable())); - assertFalse(rta.rollbackOn(new RuntimeException())); - assertFalse(rta.rollbackOn(new MyRuntimeException(""))); - assertFalse(rta.rollbackOn(new Exception())); - assertFalse(rta.rollbackOn(new IOException())); + assertThat(rta.rollbackOn(new Throwable())).isFalse(); + assertThat(rta.rollbackOn(new RuntimeException())).isFalse(); + assertThat(rta.rollbackOn(new MyRuntimeException(""))).isFalse(); + assertThat(rta.rollbackOn(new Exception())).isFalse(); + assertThat(rta.rollbackOn(new IOException())).isFalse(); } /** @@ -160,8 +159,8 @@ public class RuleBasedTransactionAttributeTests { list.add(new RollbackRuleAttribute(MyBusinessException.class)); RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, list); - assertTrue(rta.rollbackOn(new MyBusinessException())); - assertFalse(rta.rollbackOn(new MyBusinessWarningException())); + assertThat(rta.rollbackOn(new MyBusinessException())).isTrue(); + assertThat(rta.rollbackOn(new MyBusinessWarningException())).isFalse(); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeEditorTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeEditorTests.java index 0a2365d6c36..dd533f1b9ee 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeEditorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeEditorTests.java @@ -23,12 +23,8 @@ import org.junit.Test; import org.springframework.transaction.TransactionDefinition; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotSame; -import static org.junit.Assert.assertTrue; /** * Tests to check conversion from String to TransactionAttribute. @@ -45,7 +41,7 @@ public class TransactionAttributeEditorTests { TransactionAttributeEditor pe = new TransactionAttributeEditor(); pe.setAsText(null); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); - assertTrue(ta == null); + assertThat(ta == null).isTrue(); } @Test @@ -53,7 +49,7 @@ public class TransactionAttributeEditorTests { TransactionAttributeEditor pe = new TransactionAttributeEditor(); pe.setAsText(""); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); - assertTrue(ta == null); + assertThat(ta == null).isTrue(); } @Test @@ -61,10 +57,11 @@ public class TransactionAttributeEditorTests { TransactionAttributeEditor pe = new TransactionAttributeEditor(); pe.setAsText("PROPAGATION_REQUIRED"); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); - assertTrue(ta != null); - assertTrue(ta.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED); - assertTrue(ta.getIsolationLevel() == TransactionDefinition.ISOLATION_DEFAULT); - assertTrue(!ta.isReadOnly()); + assertThat(ta != null).isTrue(); + assertThat(ta.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED).isTrue(); + assertThat(ta.getIsolationLevel() == TransactionDefinition.ISOLATION_DEFAULT).isTrue(); + boolean condition = !ta.isReadOnly(); + assertThat(condition).isTrue(); } @Test @@ -80,9 +77,9 @@ public class TransactionAttributeEditorTests { TransactionAttributeEditor pe = new TransactionAttributeEditor(); pe.setAsText("PROPAGATION_REQUIRED, ISOLATION_READ_UNCOMMITTED"); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); - assertTrue(ta != null); - assertTrue(ta.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED); - assertTrue(ta.getIsolationLevel() == TransactionDefinition.ISOLATION_READ_UNCOMMITTED); + assertThat(ta != null).isTrue(); + assertThat(ta.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED).isTrue(); + assertThat(ta.getIsolationLevel() == TransactionDefinition.ISOLATION_READ_UNCOMMITTED).isTrue(); } @Test @@ -98,16 +95,17 @@ public class TransactionAttributeEditorTests { TransactionAttributeEditor pe = new TransactionAttributeEditor(); pe.setAsText("PROPAGATION_MANDATORY,ISOLATION_REPEATABLE_READ,timeout_10,-IOException,+MyRuntimeException"); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); - assertNotNull(ta); - assertEquals(TransactionDefinition.PROPAGATION_MANDATORY, ta.getPropagationBehavior()); - assertEquals(TransactionDefinition.ISOLATION_REPEATABLE_READ, ta.getIsolationLevel()); - assertEquals(10, ta.getTimeout()); - assertFalse(ta.isReadOnly()); - assertTrue(ta.rollbackOn(new RuntimeException())); - assertFalse(ta.rollbackOn(new Exception())); + assertThat(ta).isNotNull(); + assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_MANDATORY); + assertThat(ta.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(ta.getTimeout()).isEqualTo(10); + assertThat(ta.isReadOnly()).isFalse(); + assertThat(ta.rollbackOn(new RuntimeException())).isTrue(); + assertThat(ta.rollbackOn(new Exception())).isFalse(); // Check for our bizarre customized rollback rules - assertTrue(ta.rollbackOn(new IOException())); - assertTrue(!ta.rollbackOn(new MyRuntimeException(""))); + assertThat(ta.rollbackOn(new IOException())).isTrue(); + boolean condition = !ta.rollbackOn(new MyRuntimeException("")); + assertThat(condition).isTrue(); } @Test @@ -115,16 +113,16 @@ public class TransactionAttributeEditorTests { TransactionAttributeEditor pe = new TransactionAttributeEditor(); pe.setAsText("+IOException,readOnly,ISOLATION_READ_COMMITTED,-MyRuntimeException,PROPAGATION_SUPPORTS"); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); - assertNotNull(ta); - assertEquals(TransactionDefinition.PROPAGATION_SUPPORTS, ta.getPropagationBehavior()); - assertEquals(TransactionDefinition.ISOLATION_READ_COMMITTED, ta.getIsolationLevel()); - assertEquals(TransactionDefinition.TIMEOUT_DEFAULT, ta.getTimeout()); - assertTrue(ta.isReadOnly()); - assertTrue(ta.rollbackOn(new RuntimeException())); - assertFalse(ta.rollbackOn(new Exception())); + assertThat(ta).isNotNull(); + assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_SUPPORTS); + assertThat(ta.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(ta.getTimeout()).isEqualTo(TransactionDefinition.TIMEOUT_DEFAULT); + assertThat(ta.isReadOnly()).isTrue(); + assertThat(ta.rollbackOn(new RuntimeException())).isTrue(); + assertThat(ta.rollbackOn(new Exception())).isFalse(); // Check for our bizarre customized rollback rules - assertFalse(ta.rollbackOn(new IOException())); - assertTrue(ta.rollbackOn(new MyRuntimeException(""))); + assertThat(ta.rollbackOn(new IOException())).isFalse(); + assertThat(ta.rollbackOn(new MyRuntimeException(""))).isTrue(); } @Test @@ -138,18 +136,18 @@ public class TransactionAttributeEditorTests { TransactionAttributeEditor pe = new TransactionAttributeEditor(); pe.setAsText(source.toString()); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); - assertEquals(ta, source); - assertEquals(TransactionDefinition.PROPAGATION_SUPPORTS, ta.getPropagationBehavior()); - assertEquals(TransactionDefinition.ISOLATION_REPEATABLE_READ, ta.getIsolationLevel()); - assertEquals(10, ta.getTimeout()); - assertTrue(ta.isReadOnly()); - assertTrue(ta.rollbackOn(new RuntimeException())); - assertFalse(ta.rollbackOn(new Exception())); + assertThat(source).isEqualTo(ta); + assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_SUPPORTS); + assertThat(ta.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(ta.getTimeout()).isEqualTo(10); + assertThat(ta.isReadOnly()).isTrue(); + assertThat(ta.rollbackOn(new RuntimeException())).isTrue(); + assertThat(ta.rollbackOn(new Exception())).isFalse(); source.setTimeout(9); - assertNotSame(ta, source); + assertThat(source).isNotSameAs(ta); source.setTimeout(10); - assertEquals(ta, source); + assertThat(source).isEqualTo(ta); } @Test @@ -165,19 +163,19 @@ public class TransactionAttributeEditorTests { TransactionAttributeEditor pe = new TransactionAttributeEditor(); pe.setAsText(source.toString()); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); - assertEquals(ta, source); - assertEquals(TransactionDefinition.PROPAGATION_SUPPORTS, ta.getPropagationBehavior()); - assertEquals(TransactionDefinition.ISOLATION_REPEATABLE_READ, ta.getIsolationLevel()); - assertEquals(10, ta.getTimeout()); - assertTrue(ta.isReadOnly()); - assertTrue(ta.rollbackOn(new IllegalArgumentException())); - assertFalse(ta.rollbackOn(new IllegalStateException())); + assertThat(source).isEqualTo(ta); + assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_SUPPORTS); + assertThat(ta.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(ta.getTimeout()).isEqualTo(10); + assertThat(ta.isReadOnly()).isTrue(); + assertThat(ta.rollbackOn(new IllegalArgumentException())).isTrue(); + assertThat(ta.rollbackOn(new IllegalStateException())).isFalse(); source.getRollbackRules().clear(); - assertNotSame(ta, source); + assertThat(source).isNotSameAs(ta); source.getRollbackRules().add(new RollbackRuleAttribute("IllegalArgumentException")); source.getRollbackRules().add(new NoRollbackRuleAttribute("IllegalStateException")); - assertEquals(ta, source); + assertThat(source).isEqualTo(ta); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java index 0a046363c14..64db541ce67 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java @@ -22,10 +22,8 @@ import org.junit.Test; import org.springframework.transaction.TransactionDefinition; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for {@link TransactionAttributeSourceEditor}. @@ -47,7 +45,7 @@ public class TransactionAttributeSourceEditorTests { TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue(); Method m = Object.class.getMethod("hashCode"); - assertNull(tas.getTransactionAttribute(m, null)); + assertThat(tas.getTransactionAttribute(m, null)).isNull(); } @Test @@ -109,12 +107,12 @@ public class TransactionAttributeSourceEditorTests { private void checkTransactionProperties(TransactionAttributeSource tas, Method method, int propagationBehavior) { TransactionAttribute ta = tas.getTransactionAttribute(method, null); if (propagationBehavior >= 0) { - assertNotNull(ta); - assertEquals(TransactionDefinition.ISOLATION_DEFAULT, ta.getIsolationLevel()); - assertEquals(propagationBehavior, ta.getPropagationBehavior()); + assertThat(ta).isNotNull(); + assertThat(ta.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_DEFAULT); + assertThat(ta.getPropagationBehavior()).isEqualTo(propagationBehavior); } else { - assertNull(ta); + assertThat(ta).isNull(); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceTests.java index e6008316508..50eda6547c5 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceTests.java @@ -23,10 +23,7 @@ import org.junit.Test; import org.springframework.transaction.TransactionDefinition; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for the various {@link TransactionAttributeSource} implementations. @@ -44,13 +41,13 @@ public class TransactionAttributeSourceTests { public void matchAlwaysTransactionAttributeSource() throws Exception { MatchAlwaysTransactionAttributeSource tas = new MatchAlwaysTransactionAttributeSource(); TransactionAttribute ta = tas.getTransactionAttribute(Object.class.getMethod("hashCode"), null); - assertNotNull(ta); - assertTrue(TransactionDefinition.PROPAGATION_REQUIRED == ta.getPropagationBehavior()); + assertThat(ta).isNotNull(); + assertThat(TransactionDefinition.PROPAGATION_REQUIRED == ta.getPropagationBehavior()).isTrue(); tas.setTransactionAttribute(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_SUPPORTS)); ta = tas.getTransactionAttribute(IOException.class.getMethod("getMessage"), IOException.class); - assertNotNull(ta); - assertTrue(TransactionDefinition.PROPAGATION_SUPPORTS == ta.getPropagationBehavior()); + assertThat(ta).isNotNull(); + assertThat(TransactionDefinition.PROPAGATION_SUPPORTS == ta.getPropagationBehavior()).isTrue(); } @Test @@ -60,8 +57,8 @@ public class TransactionAttributeSourceTests { attributes.put("*ashCode", "PROPAGATION_REQUIRED"); tas.setProperties(attributes); TransactionAttribute ta = tas.getTransactionAttribute(Object.class.getMethod("hashCode"), null); - assertNotNull(ta); - assertEquals(TransactionDefinition.PROPAGATION_REQUIRED, ta.getPropagationBehavior()); + assertThat(ta).isNotNull(); + assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); } @Test @@ -71,8 +68,8 @@ public class TransactionAttributeSourceTests { attributes.put("hashCod*", "PROPAGATION_REQUIRED"); tas.setProperties(attributes); TransactionAttribute ta = tas.getTransactionAttribute(Object.class.getMethod("hashCode"), null); - assertNotNull(ta); - assertEquals(TransactionDefinition.PROPAGATION_REQUIRED, ta.getPropagationBehavior()); + assertThat(ta).isNotNull(); + assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); } @Test @@ -83,8 +80,8 @@ public class TransactionAttributeSourceTests { attributes.put("hashCode", "PROPAGATION_MANDATORY"); tas.setProperties(attributes); TransactionAttribute ta = tas.getTransactionAttribute(Object.class.getMethod("hashCode"), null); - assertNotNull(ta); - assertEquals(TransactionDefinition.PROPAGATION_MANDATORY, ta.getPropagationBehavior()); + assertThat(ta).isNotNull(); + assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_MANDATORY); } @Test @@ -94,7 +91,7 @@ public class TransactionAttributeSourceTests { attributes.put("", "PROPAGATION_MANDATORY"); tas.setProperties(attributes); TransactionAttribute ta = tas.getTransactionAttribute(Object.class.getMethod("hashCode"), null); - assertNull(ta); + assertThat(ta).isNull(); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionInterceptorTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionInterceptorTests.java index a62f435bef3..84944c296c3 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionInterceptorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionInterceptorTests.java @@ -31,12 +31,8 @@ import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionStatus; import org.springframework.util.SerializationTestUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -70,9 +66,9 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests protected Object advised(Object target, PlatformTransactionManager ptm, TransactionAttributeSource tas) { TransactionInterceptor ti = new TransactionInterceptor(); ti.setTransactionManager(ptm); - assertEquals(ptm, ti.getTransactionManager()); + assertThat(ti.getTransactionManager()).isEqualTo(ptm); ti.setTransactionAttributeSource(tas); - assertEquals(tas, ti.getTransactionAttributeSource()); + assertThat(ti.getTransactionAttributeSource()).isEqualTo(tas); ProxyFactory pf = new ProxyFactory(target); pf.addAdvice(0, ti); @@ -95,9 +91,10 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests ti = (TransactionInterceptor) SerializationTestUtils.serializeAndDeserialize(ti); // Check that logger survived deserialization - assertNotNull(ti.logger); - assertTrue(ti.getTransactionManager() instanceof SerializableTransactionManager); - assertNotNull(ti.getTransactionAttributeSource()); + assertThat(ti.logger).isNotNull(); + boolean condition = ti.getTransactionManager() instanceof SerializableTransactionManager; + assertThat(condition).isTrue(); + assertThat(ti.getTransactionAttributeSource()).isNotNull(); } @Test @@ -118,11 +115,15 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests ti.setTransactionManager(ptm); ti = (TransactionInterceptor) SerializationTestUtils.serializeAndDeserialize(ti); - assertTrue(ti.getTransactionManager() instanceof SerializableTransactionManager); - assertTrue(ti.getTransactionAttributeSource() instanceof CompositeTransactionAttributeSource); + boolean condition3 = ti.getTransactionManager() instanceof SerializableTransactionManager; + assertThat(condition3).isTrue(); + boolean condition2 = ti.getTransactionAttributeSource() instanceof CompositeTransactionAttributeSource; + assertThat(condition2).isTrue(); CompositeTransactionAttributeSource ctas = (CompositeTransactionAttributeSource) ti.getTransactionAttributeSource(); - assertTrue(ctas.getTransactionAttributeSources()[0] instanceof NameMatchTransactionAttributeSource); - assertTrue(ctas.getTransactionAttributeSources()[1] instanceof NameMatchTransactionAttributeSource); + boolean condition1 = ctas.getTransactionAttributeSources()[0] instanceof NameMatchTransactionAttributeSource; + assertThat(condition1).isTrue(); + boolean condition = ctas.getTransactionAttributeSources()[1] instanceof NameMatchTransactionAttributeSource; + assertThat(condition).isTrue(); } @Test @@ -130,7 +131,7 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); TransactionInterceptor ti = transactionInterceptorWithTransactionManager(transactionManager, null); - assertSame(transactionManager, ti.determineTransactionManager(new DefaultTransactionAttribute())); + assertThat(ti.determineTransactionManager(new DefaultTransactionAttribute())).isSameAs(transactionManager); } @Test @@ -138,7 +139,7 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); TransactionInterceptor ti = transactionInterceptorWithTransactionManager(transactionManager, null); - assertSame(transactionManager, ti.determineTransactionManager(null)); + assertThat(ti.determineTransactionManager(null)).isSameAs(transactionManager); } @Test @@ -146,7 +147,7 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests BeanFactory beanFactory = mock(BeanFactory.class); TransactionInterceptor ti = simpleTransactionInterceptor(beanFactory); - assertNull(ti.determineTransactionManager(null)); + assertThat(ti.determineTransactionManager(null)).isNull(); } @Test @@ -172,7 +173,7 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests DefaultTransactionAttribute attribute = new DefaultTransactionAttribute(); attribute.setQualifier("fooTransactionManager"); - assertSame(fooTransactionManager, ti.determineTransactionManager(attribute)); + assertThat(ti.determineTransactionManager(attribute)).isSameAs(fooTransactionManager); } @Test @@ -187,7 +188,7 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests DefaultTransactionAttribute attribute = new DefaultTransactionAttribute(); attribute.setQualifier("fooTransactionManager"); - assertSame(fooTransactionManager, ti.determineTransactionManager(attribute)); + assertThat(ti.determineTransactionManager(attribute)).isSameAs(fooTransactionManager); } @Test @@ -201,7 +202,7 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests DefaultTransactionAttribute attribute = new DefaultTransactionAttribute(); attribute.setQualifier(""); - assertSame(defaultTransactionManager, ti.determineTransactionManager(attribute)); + assertThat(ti.determineTransactionManager(attribute)).isSameAs(defaultTransactionManager); } @Test @@ -214,11 +215,11 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests DefaultTransactionAttribute attribute = new DefaultTransactionAttribute(); attribute.setQualifier("fooTransactionManager"); PlatformTransactionManager actual = ti.determineTransactionManager(attribute); - assertSame(txManager, actual); + assertThat(actual).isSameAs(txManager); // Call again, should be cached PlatformTransactionManager actual2 = ti.determineTransactionManager(attribute); - assertSame(txManager, actual2); + assertThat(actual2).isSameAs(txManager); verify(beanFactory, times(1)).containsBean("fooTransactionManager"); verify(beanFactory, times(1)).getBean("fooTransactionManager", PlatformTransactionManager.class); } @@ -233,11 +234,11 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests DefaultTransactionAttribute attribute = new DefaultTransactionAttribute(); PlatformTransactionManager actual = ti.determineTransactionManager(attribute); - assertSame(txManager, actual); + assertThat(actual).isSameAs(txManager); // Call again, should be cached PlatformTransactionManager actual2 = ti.determineTransactionManager(attribute); - assertSame(txManager, actual2); + assertThat(actual2).isSameAs(txManager); verify(beanFactory, times(1)).getBean("fooTransactionManager", PlatformTransactionManager.class); } @@ -251,11 +252,11 @@ public class TransactionInterceptorTests extends AbstractTransactionAspectTests DefaultTransactionAttribute attribute = new DefaultTransactionAttribute(); PlatformTransactionManager actual = ti.determineTransactionManager(attribute); - assertSame(txManager, actual); + assertThat(actual).isSameAs(txManager); // Call again, should be cached PlatformTransactionManager actual2 = ti.determineTransactionManager(attribute); - assertSame(txManager, actual2); + assertThat(actual2).isSameAs(txManager); verify(beanFactory, times(1)).getBean(PlatformTransactionManager.class); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java index 56b57197fbf..27a698a7af9 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java @@ -38,9 +38,6 @@ import org.springframework.transaction.support.TransactionSynchronizationManager import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -60,16 +57,16 @@ public class WebSphereUowTransactionManagerTests { ptm.afterPropertiesSet(); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); - assertEquals("result", ptm.execute(definition, new TransactionCallback() { + assertThat(ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } - })); + })).isEqualTo("result"); - assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); - assertFalse(manager.getJoined()); - assertFalse(manager.getRollbackOnly()); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION); + assertThat(manager.getJoined()).isFalse(); + assertThat(manager.getRollbackOnly()).isFalse(); } @Test @@ -88,16 +85,16 @@ public class WebSphereUowTransactionManagerTests { DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); TransactionStatus ts = ptm.getTransaction(definition); ptm.commit(ts); - assertEquals("result", ptm.execute(definition, new TransactionCallback() { + assertThat(ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } - })); + })).isEqualTo("result"); - assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); - assertFalse(manager.getJoined()); - assertFalse(manager.getRollbackOnly()); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION); + assertThat(manager.getJoined()).isFalse(); + assertThat(manager.getRollbackOnly()).isFalse(); verify(ut).begin(); verify(ut).commit(); } @@ -180,35 +177,35 @@ public class WebSphereUowTransactionManagerTests { definition.setPropagationBehavior(propagationBehavior); definition.setReadOnly(true); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals("result", ptm.execute(definition, new TransactionCallback() { + assertThat(ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { if (synchMode == WebSphereUowTransactionManager.SYNCHRONIZATION_ALWAYS) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); } else { - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } return "result"; } - })); + })).isEqualTo("result"); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals(0, manager.getUOWTimeout()); - assertEquals(UOWManager.UOW_TYPE_LOCAL_TRANSACTION, manager.getUOWType()); - assertFalse(manager.getJoined()); - assertFalse(manager.getRollbackOnly()); + assertThat(manager.getUOWTimeout()).isEqualTo(0); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_LOCAL_TRANSACTION); + assertThat(manager.getJoined()).isFalse(); + assertThat(manager.getRollbackOnly()).isFalse(); } @Test @@ -273,35 +270,35 @@ public class WebSphereUowTransactionManagerTests { definition.setPropagationBehavior(propagationBehavior); definition.setReadOnly(true); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals("result", ptm.execute(definition, new TransactionCallback() { + assertThat(ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { if (synchMode != WebSphereUowTransactionManager.SYNCHRONIZATION_NEVER) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); } else { - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); } return "result"; } - })); + })).isEqualTo("result"); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals(0, manager.getUOWTimeout()); - assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); - assertFalse(manager.getJoined()); - assertFalse(manager.getRollbackOnly()); + assertThat(manager.getUOWTimeout()).isEqualTo(0); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION); + assertThat(manager.getJoined()).isFalse(); + assertThat(manager.getRollbackOnly()).isFalse(); } @Test @@ -312,28 +309,28 @@ public class WebSphereUowTransactionManagerTests { definition.setTimeout(10); definition.setReadOnly(true); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals("result", ptm.execute(definition, new TransactionCallback() { + assertThat(ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); return "result"; } - })); + })).isEqualTo("result"); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals(10, manager.getUOWTimeout()); - assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); - assertFalse(manager.getJoined()); - assertFalse(manager.getRollbackOnly()); + assertThat(manager.getUOWTimeout()).isEqualTo(10); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION); + assertThat(manager.getJoined()).isFalse(); + assertThat(manager.getRollbackOnly()).isFalse(); } @Test @@ -348,17 +345,17 @@ public class WebSphereUowTransactionManagerTests { WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); return "result"; } })) @@ -368,11 +365,11 @@ public class WebSphereUowTransactionManagerTests { assertThat(ex.getMostSpecificCause()).isSameAs(rex); }); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals(0, manager.getUOWTimeout()); + assertThat(manager.getUOWTimeout()).isEqualTo(0); } @Test @@ -381,29 +378,29 @@ public class WebSphereUowTransactionManagerTests { WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); throw new OptimisticLockingFailureException(""); } })); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals(0, manager.getUOWTimeout()); - assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); - assertFalse(manager.getJoined()); - assertTrue(manager.getRollbackOnly()); + assertThat(manager.getUOWTimeout()).isEqualTo(0); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION); + assertThat(manager.getJoined()).isFalse(); + assertThat(manager.getRollbackOnly()).isTrue(); } @Test @@ -412,29 +409,29 @@ public class WebSphereUowTransactionManagerTests { WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals("result", ptm.execute(definition, new TransactionCallback() { + assertThat(ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); status.setRollbackOnly(); return "result"; } - })); + })).isEqualTo("result"); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals(0, manager.getUOWTimeout()); - assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); - assertFalse(manager.getJoined()); - assertTrue(manager.getRollbackOnly()); + assertThat(manager.getUOWTimeout()).isEqualTo(0); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION); + assertThat(manager.getJoined()).isFalse(); + assertThat(manager.getRollbackOnly()).isTrue(); } @Test @@ -444,28 +441,28 @@ public class WebSphereUowTransactionManagerTests { WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals("result", ptm.execute(definition, new TransactionCallback() { + assertThat(ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); return "result"; } - })); + })).isEqualTo("result"); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals(0, manager.getUOWTimeout()); - assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); - assertTrue(manager.getJoined()); - assertFalse(manager.getRollbackOnly()); + assertThat(manager.getUOWTimeout()).isEqualTo(0); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION); + assertThat(manager.getJoined()).isTrue(); + assertThat(manager.getRollbackOnly()).isFalse(); } @Test @@ -525,37 +522,37 @@ public class WebSphereUowTransactionManagerTests { definition2.setPropagationBehavior(propagationBehavior); definition2.setReadOnly(true); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals("result", ptm.execute(definition, new TransactionCallback() { + assertThat(ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertEquals("result2", ptm.execute(definition2, new TransactionCallback() { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(ptm.execute(definition2, new TransactionCallback() { @Override - public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + public String doInTransaction(TransactionStatus status1) { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); return "result2"; } - })); + })).isEqualTo("result2"); return "result"; } - })); + })).isEqualTo("result"); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals(0, manager.getUOWTimeout()); - assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); - assertTrue(manager.getJoined()); - assertFalse(manager.getRollbackOnly()); + assertThat(manager.getUOWTimeout()).isEqualTo(0); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION); + assertThat(manager.getJoined()).isTrue(); + assertThat(manager.getRollbackOnly()).isFalse(); } @Test @@ -576,43 +573,42 @@ public class WebSphereUowTransactionManagerTests { definition2.setPropagationBehavior(propagationBehavior); definition2.setReadOnly(true); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals("result", ptm.execute(definition, new TransactionCallback() { + assertThat(ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertEquals("result2", ptm.execute(definition2, new TransactionCallback() { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(ptm.execute(definition2, new TransactionCallback() { @Override - public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertEquals(propagationBehavior == TransactionDefinition.PROPAGATION_REQUIRES_NEW, - TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + public String doInTransaction(TransactionStatus status1) { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isEqualTo((propagationBehavior == TransactionDefinition.PROPAGATION_REQUIRES_NEW)); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); return "result2"; } - })); + })).isEqualTo("result2"); return "result"; } - })); + })).isEqualTo("result"); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals(0, manager.getUOWTimeout()); + assertThat(manager.getUOWTimeout()).isEqualTo(0); if (propagationBehavior == TransactionDefinition.PROPAGATION_REQUIRES_NEW) { - assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION); } else { - assertEquals(UOWManager.UOW_TYPE_LOCAL_TRANSACTION, manager.getUOWType()); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_LOCAL_TRANSACTION); } - assertFalse(manager.getJoined()); - assertFalse(manager.getRollbackOnly()); + assertThat(manager.getJoined()).isFalse(); + assertThat(manager.getRollbackOnly()).isFalse(); } @Test @@ -624,37 +620,37 @@ public class WebSphereUowTransactionManagerTests { definition2.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); definition2.setReadOnly(true); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals("result", ptm.execute(definition, new TransactionCallback() { + assertThat(ptm.execute(definition, new TransactionCallback() { @Override public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertEquals("result2", ptm.execute(definition2, new TransactionCallback() { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(ptm.execute(definition2, new TransactionCallback() { @Override - public String doInTransaction(TransactionStatus status) { - assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + public String doInTransaction(TransactionStatus status1) { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); return "result2"; } - })); + })).isEqualTo("result2"); return "result"; } - })); + })).isEqualTo("result"); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertEquals(0, manager.getUOWTimeout()); - assertEquals(UOWManager.UOW_TYPE_LOCAL_TRANSACTION, manager.getUOWType()); - assertFalse(manager.getJoined()); - assertFalse(manager.getRollbackOnly()); + assertThat(manager.getUOWTimeout()).isEqualTo(0); + assertThat(manager.getUOWType()).isEqualTo(UOWManager.UOW_TYPE_LOCAL_TRANSACTION); + assertThat(manager.getJoined()).isFalse(); + assertThat(manager.getRollbackOnly()).isFalse(); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/reactive/ReactiveTransactionSupportTests.java b/spring-tx/src/test/java/org/springframework/transaction/reactive/ReactiveTransactionSupportTests.java index 1a812aba386..e99d958a70a 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/reactive/ReactiveTransactionSupportTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/reactive/ReactiveTransactionSupportTests.java @@ -27,9 +27,7 @@ import org.springframework.transaction.ReactiveTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.DefaultTransactionDefinition; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for transactional support through {@link ReactiveTestTransactionManager}. @@ -44,16 +42,15 @@ public class ReactiveTransactionSupportTests { tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS)) .subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class) - .as(StepVerifier::create).consumeNextWith(actual -> - assertFalse(actual.hasTransaction()) - ).verifyComplete(); + .as(StepVerifier::create).consumeNextWith(actual -> assertThat(actual.hasTransaction()).isFalse() + ).verifyComplete(); tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED)) .cast(GenericReactiveTransaction.class).subscriberContext(TransactionContextManager.createTransactionContext()) .as(StepVerifier::create).consumeNextWith(actual -> { - assertTrue(actual.hasTransaction()); - assertTrue(actual.isNewTransaction()); - }).verifyComplete(); + assertThat(actual.hasTransaction()).isTrue(); + assertThat(actual.isNewTransaction()).isTrue(); + }).verifyComplete(); tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY)) .subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class) @@ -67,23 +64,23 @@ public class ReactiveTransactionSupportTests { tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS)) .subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class) .as(StepVerifier::create).consumeNextWith(actual -> { - assertNotNull(actual.getTransaction()); - assertFalse(actual.isNewTransaction()); - }).verifyComplete(); + assertThat(actual.getTransaction()).isNotNull(); + assertThat(actual.isNewTransaction()).isFalse(); + }).verifyComplete(); tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED)) .subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class) .as(StepVerifier::create).consumeNextWith(actual -> { - assertNotNull(actual.getTransaction()); - assertFalse(actual.isNewTransaction()); - }).verifyComplete(); + assertThat(actual.getTransaction()).isNotNull(); + assertThat(actual.isNewTransaction()).isFalse(); + }).verifyComplete(); tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY)) .subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class) .as(StepVerifier::create).consumeNextWith(actual -> { - assertNotNull(actual.getTransaction()); - assertFalse(actual.isNewTransaction()); - }).verifyComplete(); + assertThat(actual.getTransaction()).isNotNull(); + assertThat(actual.isNewTransaction()).isFalse(); + }).verifyComplete(); } @Test @@ -207,43 +204,43 @@ public class ReactiveTransactionSupportTests { } private void assertHasBegan(ReactiveTestTransactionManager actual) { - assertTrue("Expected but was was not invoked", actual.begin); + assertThat(actual.begin).as("Expected but was was not invoked").isTrue(); } private void assertHasNotBegan(ReactiveTestTransactionManager actual) { - assertFalse("Expected to not call but was was called", actual.begin); + assertThat(actual.begin).as("Expected to not call but was was called").isFalse(); } private void assertHasCommitted(ReactiveTestTransactionManager actual) { - assertTrue("Expected but was was not invoked", actual.commit); + assertThat(actual.commit).as("Expected but was was not invoked").isTrue(); } private void assertHasNotCommitted(ReactiveTestTransactionManager actual) { - assertFalse("Expected to not call but was was called", actual.commit); + assertThat(actual.commit).as("Expected to not call but was was called").isFalse(); } private void assertHasRolledBack(ReactiveTestTransactionManager actual) { - assertTrue("Expected but was was not invoked", actual.rollback); + assertThat(actual.rollback).as("Expected but was was not invoked").isTrue(); } private void assertHasNoRollback(ReactiveTestTransactionManager actual) { -assertFalse("Expected to not call but was was called", actual.rollback); + assertThat(actual.rollback).as("Expected to not call but was was called").isFalse(); } private void assertHasSetRollbackOnly(ReactiveTestTransactionManager actual) { - assertTrue("Expected but was was not invoked", actual.rollbackOnly); + assertThat(actual.rollbackOnly).as("Expected but was was not invoked").isTrue(); } private void assertHasNotSetRollbackOnly(ReactiveTestTransactionManager actual) { - assertFalse("Expected to not call but was was called", actual.rollbackOnly); + assertThat(actual.rollbackOnly).as("Expected to not call but was was called").isFalse(); } private void assertHasCleanedUp(ReactiveTestTransactionManager actual) { - assertTrue("Expected but was was not invoked", actual.cleanup); + assertThat(actual.cleanup).as("Expected but was was not invoked").isTrue(); } private void assertHasNotCleanedUp(ReactiveTestTransactionManager actual) { - assertFalse("Expected to not call but was was called", actual.cleanup); + assertThat(actual.cleanup).as("Expected to not call but was was called").isFalse(); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/reactive/TransactionalOperatorTests.java b/spring-tx/src/test/java/org/springframework/transaction/reactive/TransactionalOperatorTests.java index 7ddb4011741..f4eea955c4f 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/reactive/TransactionalOperatorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/reactive/TransactionalOperatorTests.java @@ -23,8 +23,7 @@ import reactor.test.StepVerifier; import org.springframework.transaction.support.DefaultTransactionDefinition; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link TransactionalOperator}. @@ -43,8 +42,8 @@ public class TransactionalOperatorTests { .as(StepVerifier::create) .expectNext(true) .verifyComplete(); - assertTrue(tm.commit); - assertFalse(tm.rollback); + assertThat(tm.commit).isTrue(); + assertThat(tm.rollback).isFalse(); } @Test @@ -53,8 +52,8 @@ public class TransactionalOperatorTests { Mono.error(new IllegalStateException()).as(operator::transactional) .as(StepVerifier::create) .verifyError(IllegalStateException.class); - assertFalse(tm.commit); - assertTrue(tm.rollback); + assertThat(tm.commit).isFalse(); + assertThat(tm.rollback).isTrue(); } @Test @@ -64,8 +63,8 @@ public class TransactionalOperatorTests { .as(StepVerifier::create) .expectNextCount(4) .verifyComplete(); - assertTrue(tm.commit); - assertFalse(tm.rollback); + assertThat(tm.commit).isTrue(); + assertThat(tm.rollback).isFalse(); } @Test @@ -74,8 +73,8 @@ public class TransactionalOperatorTests { Flux.error(new IllegalStateException()).as(operator::transactional) .as(StepVerifier::create) .verifyError(IllegalStateException.class); - assertFalse(tm.commit); - assertTrue(tm.rollback); + assertThat(tm.commit).isFalse(); + assertThat(tm.rollback).isTrue(); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java b/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java index cacbe6eda4c..d2030317dc5 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java @@ -25,10 +25,7 @@ import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; import org.springframework.transaction.jta.JtaTransactionManager; import org.springframework.util.SerializationTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -55,13 +52,12 @@ public class JtaTransactionManagerSerializationTests { .serializeAndDeserialize(jtam); // should do client-side lookup - assertNotNull("Logger must survive serialization", - serializedJtatm.logger); - assertTrue("UserTransaction looked up on client", serializedJtatm - .getUserTransaction() == ut2); - assertNull("TransactionManager didn't survive", serializedJtatm - .getTransactionManager()); - assertEquals(true, serializedJtatm.isRollbackOnCommitFailure()); + assertThat(serializedJtatm.logger).as("Logger must survive serialization").isNotNull(); + assertThat(serializedJtatm + .getUserTransaction() == ut2).as("UserTransaction looked up on client").isTrue(); + assertThat(serializedJtatm + .getTransactionManager()).as("TransactionManager didn't survive").isNull(); + assertThat(serializedJtatm.isRollbackOnCommitFailure()).isEqualTo(true); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java b/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java index ef62396a6e0..460030b0870 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java @@ -28,11 +28,8 @@ import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.tests.sample.beans.TestBean; 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.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -74,34 +71,34 @@ public class SimpleTransactionScopeTests { TransactionSynchronizationManager.initSynchronization(); try { bean1 = context.getBean(TestBean.class); - assertSame(bean1, context.getBean(TestBean.class)); + assertThat(context.getBean(TestBean.class)).isSameAs(bean1); bean2 = context.getBean(DerivedTestBean.class); - assertSame(bean2, context.getBean(DerivedTestBean.class)); + assertThat(context.getBean(DerivedTestBean.class)).isSameAs(bean2); context.getBeanFactory().destroyScopedBean("txScopedObject2"); - assertFalse(TransactionSynchronizationManager.hasResource("txScopedObject2")); - assertTrue(bean2.wasDestroyed()); + assertThat(TransactionSynchronizationManager.hasResource("txScopedObject2")).isFalse(); + assertThat(bean2.wasDestroyed()).isTrue(); bean2a = context.getBean(DerivedTestBean.class); - assertSame(bean2a, context.getBean(DerivedTestBean.class)); - assertNotSame(bean2, bean2a); + assertThat(context.getBean(DerivedTestBean.class)).isSameAs(bean2a); + assertThat(bean2a).isNotSameAs(bean2); context.getBeanFactory().getRegisteredScope("tx").remove("txScopedObject2"); - assertFalse(TransactionSynchronizationManager.hasResource("txScopedObject2")); - assertFalse(bean2a.wasDestroyed()); + assertThat(TransactionSynchronizationManager.hasResource("txScopedObject2")).isFalse(); + assertThat(bean2a.wasDestroyed()).isFalse(); bean2b = context.getBean(DerivedTestBean.class); - assertSame(bean2b, context.getBean(DerivedTestBean.class)); - assertNotSame(bean2, bean2b); - assertNotSame(bean2a, bean2b); + assertThat(context.getBean(DerivedTestBean.class)).isSameAs(bean2b); + assertThat(bean2b).isNotSameAs(bean2); + assertThat(bean2b).isNotSameAs(bean2a); } finally { TransactionSynchronizationUtils.triggerAfterCompletion(TransactionSynchronization.STATUS_COMMITTED); TransactionSynchronizationManager.clearSynchronization(); } - assertFalse(bean2a.wasDestroyed()); - assertTrue(bean2b.wasDestroyed()); - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertThat(bean2a.wasDestroyed()).isFalse(); + assertThat(bean2b.wasDestroyed()).isTrue(); + assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> context.getBean(TestBean.class)) @@ -136,26 +133,26 @@ public class SimpleTransactionScopeTests { tt.execute(status -> { TestBean bean1 = context.getBean(TestBean.class); - assertSame(bean1, context.getBean(TestBean.class)); + assertThat(context.getBean(TestBean.class)).isSameAs(bean1); DerivedTestBean bean2 = context.getBean(DerivedTestBean.class); - assertSame(bean2, context.getBean(DerivedTestBean.class)); + assertThat(context.getBean(DerivedTestBean.class)).isSameAs(bean2); context.getBeanFactory().destroyScopedBean("txScopedObject2"); - assertFalse(TransactionSynchronizationManager.hasResource("txScopedObject2")); - assertTrue(bean2.wasDestroyed()); + assertThat(TransactionSynchronizationManager.hasResource("txScopedObject2")).isFalse(); + assertThat(bean2.wasDestroyed()).isTrue(); DerivedTestBean bean2a = context.getBean(DerivedTestBean.class); - assertSame(bean2a, context.getBean(DerivedTestBean.class)); - assertNotSame(bean2, bean2a); + assertThat(context.getBean(DerivedTestBean.class)).isSameAs(bean2a); + assertThat(bean2a).isNotSameAs(bean2); context.getBeanFactory().getRegisteredScope("tx").remove("txScopedObject2"); - assertFalse(TransactionSynchronizationManager.hasResource("txScopedObject2")); - assertFalse(bean2a.wasDestroyed()); + assertThat(TransactionSynchronizationManager.hasResource("txScopedObject2")).isFalse(); + assertThat(bean2a.wasDestroyed()).isFalse(); DerivedTestBean bean2b = context.getBean(DerivedTestBean.class); finallyDestroy.add(bean2b); - assertSame(bean2b, context.getBean(DerivedTestBean.class)); - assertNotSame(bean2, bean2b); - assertNotSame(bean2a, bean2b); + assertThat(context.getBean(DerivedTestBean.class)).isSameAs(bean2b); + assertThat(bean2b).isNotSameAs(bean2); + assertThat(bean2b).isNotSameAs(bean2a); Set immediatelyDestroy = new HashSet<>(); TransactionTemplate tt2 = new TransactionTemplate(tm); @@ -163,19 +160,19 @@ public class SimpleTransactionScopeTests { tt2.execute(status2 -> { DerivedTestBean bean2c = context.getBean(DerivedTestBean.class); immediatelyDestroy.add(bean2c); - assertSame(bean2c, context.getBean(DerivedTestBean.class)); - assertNotSame(bean2, bean2c); - assertNotSame(bean2a, bean2c); - assertNotSame(bean2b, bean2c); + assertThat(context.getBean(DerivedTestBean.class)).isSameAs(bean2c); + assertThat(bean2c).isNotSameAs(bean2); + assertThat(bean2c).isNotSameAs(bean2a); + assertThat(bean2c).isNotSameAs(bean2b); return null; }); - assertTrue(immediatelyDestroy.iterator().next().wasDestroyed()); - assertFalse(bean2b.wasDestroyed()); + assertThat(immediatelyDestroy.iterator().next().wasDestroyed()).isTrue(); + assertThat(bean2b.wasDestroyed()).isFalse(); return null; }); - assertTrue(finallyDestroy.iterator().next().wasDestroyed()); + assertThat(finallyDestroy.iterator().next().wasDestroyed()).isTrue(); } } diff --git a/spring-web/src/test/java/org/springframework/http/ContentDispositionTests.java b/spring-web/src/test/java/org/springframework/http/ContentDispositionTests.java index 9acef2b8d4c..40b04da7fe8 100644 --- a/spring-web/src/test/java/org/springframework/http/ContentDispositionTests.java +++ b/spring-web/src/test/java/org/springframework/http/ContentDispositionTests.java @@ -26,8 +26,8 @@ import org.junit.Test; import org.springframework.util.ReflectionUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link ContentDisposition} @@ -40,45 +40,45 @@ public class ContentDispositionTests { public void parse() { ContentDisposition disposition = ContentDisposition .parse("form-data; name=\"foo\"; filename=\"foo.txt\"; size=123"); - assertEquals(ContentDisposition.builder("form-data") - .name("foo").filename("foo.txt").size(123L).build(), disposition); + assertThat(disposition).isEqualTo(ContentDisposition.builder("form-data") + .name("foo").filename("foo.txt").size(123L).build()); } @Test public void parseType() { ContentDisposition disposition = ContentDisposition.parse("form-data"); - assertEquals(ContentDisposition.builder("form-data").build(), disposition); + assertThat(disposition).isEqualTo(ContentDisposition.builder("form-data").build()); } @Test public void parseUnquotedFilename() { ContentDisposition disposition = ContentDisposition .parse("form-data; filename=unquoted"); - assertEquals(ContentDisposition.builder("form-data").filename("unquoted").build(), disposition); + assertThat(disposition).isEqualTo(ContentDisposition.builder("form-data").filename("unquoted").build()); } @Test // SPR-16091 public void parseFilenameWithSemicolon() { ContentDisposition disposition = ContentDisposition .parse("attachment; filename=\"filename with ; semicolon.txt\""); - assertEquals(ContentDisposition.builder("attachment") - .filename("filename with ; semicolon.txt").build(), disposition); + assertThat(disposition).isEqualTo(ContentDisposition.builder("attachment") + .filename("filename with ; semicolon.txt").build()); } @Test public void parseAndIgnoreEmptyParts() { ContentDisposition disposition = ContentDisposition .parse("form-data; name=\"foo\";; ; filename=\"foo.txt\"; size=123"); - assertEquals(ContentDisposition.builder("form-data") - .name("foo").filename("foo.txt").size(123L).build(), disposition); + assertThat(disposition).isEqualTo(ContentDisposition.builder("form-data") + .name("foo").filename("foo.txt").size(123L).build()); } @Test public void parseEncodedFilename() { ContentDisposition disposition = ContentDisposition .parse("form-data; name=\"name\"; filename*=UTF-8''%E4%B8%AD%E6%96%87.txt"); - assertEquals(ContentDisposition.builder("form-data").name("name") - .filename("中文.txt", StandardCharsets.UTF_8).build(), disposition); + assertThat(disposition).isEqualTo(ContentDisposition.builder("form-data").name("name") + .filename("中文.txt", StandardCharsets.UTF_8).build()); } @Test @@ -106,10 +106,10 @@ public class ContentDispositionTests { "modification-date=\"Tue, 13 Feb 2007 10:15:30 -0500\"; " + "read-date=\"Wed, 14 Feb 2007 10:15:30 -0500\""); DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME; - assertEquals(ContentDisposition.builder("attachment") + assertThat(disposition).isEqualTo(ContentDisposition.builder("attachment") .creationDate(ZonedDateTime.parse("Mon, 12 Feb 2007 10:15:30 -0500", formatter)) .modificationDate(ZonedDateTime.parse("Tue, 13 Feb 2007 10:15:30 -0500", formatter)) - .readDate(ZonedDateTime.parse("Wed, 14 Feb 2007 10:15:30 -0500", formatter)).build(), disposition); + .readDate(ZonedDateTime.parse("Wed, 14 Feb 2007 10:15:30 -0500", formatter)).build()); } @Test @@ -118,23 +118,22 @@ public class ContentDispositionTests { .parse("attachment; creation-date=\"-1\"; modification-date=\"-1\"; " + "read-date=\"Wed, 14 Feb 2007 10:15:30 -0500\""); DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME; - assertEquals(ContentDisposition.builder("attachment") - .readDate(ZonedDateTime.parse("Wed, 14 Feb 2007 10:15:30 -0500", formatter)).build(), disposition); + assertThat(disposition).isEqualTo(ContentDisposition.builder("attachment") + .readDate(ZonedDateTime.parse("Wed, 14 Feb 2007 10:15:30 -0500", formatter)).build()); } @Test public void headerValue() { ContentDisposition disposition = ContentDisposition.builder("form-data") .name("foo").filename("foo.txt").size(123L).build(); - assertEquals("form-data; name=\"foo\"; filename=\"foo.txt\"; size=123", disposition.toString()); + assertThat(disposition.toString()).isEqualTo("form-data; name=\"foo\"; filename=\"foo.txt\"; size=123"); } @Test public void headerValueWithEncodedFilename() { ContentDisposition disposition = ContentDisposition.builder("form-data") .name("name").filename("中文.txt", StandardCharsets.UTF_8).build(); - assertEquals("form-data; name=\"name\"; filename*=UTF-8''%E4%B8%AD%E6%96%87.txt", - disposition.toString()); + assertThat(disposition.toString()).isEqualTo("form-data; name=\"name\"; filename*=UTF-8''%E4%B8%AD%E6%96%87.txt"); } @Test // SPR-14547 @@ -145,10 +144,10 @@ public class ContentDispositionTests { String result = (String)ReflectionUtils.invokeMethod(encode, null, "test.txt", StandardCharsets.US_ASCII); - assertEquals("test.txt", result); + assertThat(result).isEqualTo("test.txt"); result = (String)ReflectionUtils.invokeMethod(encode, null, "中文.txt", StandardCharsets.UTF_8); - assertEquals("UTF-8''%E4%B8%AD%E6%96%87.txt", result); + assertThat(result).isEqualTo("UTF-8''%E4%B8%AD%E6%96%87.txt"); } @Test @@ -167,10 +166,10 @@ public class ContentDispositionTests { ReflectionUtils.makeAccessible(decode); String result = (String)ReflectionUtils.invokeMethod(decode, null, "test.txt"); - assertEquals("test.txt", result); + assertThat(result).isEqualTo("test.txt"); result = (String)ReflectionUtils.invokeMethod(decode, null, "UTF-8''%E4%B8%AD%E6%96%87.txt"); - assertEquals("中文.txt", result); + assertThat(result).isEqualTo("中文.txt"); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/HttpEntityTests.java b/spring-web/src/test/java/org/springframework/http/HttpEntityTests.java index 54f7352ce93..98497a25ded 100644 --- a/spring-web/src/test/java/org/springframework/http/HttpEntityTests.java +++ b/spring-web/src/test/java/org/springframework/http/HttpEntityTests.java @@ -23,10 +23,7 @@ import org.junit.Test; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -37,8 +34,8 @@ public class HttpEntityTests { public void noHeaders() { String body = "foo"; HttpEntity entity = new HttpEntity<>(body); - assertSame(body, entity.getBody()); - assertTrue(entity.getHeaders().isEmpty()); + assertThat(entity.getBody()).isSameAs(body); + assertThat(entity.getHeaders().isEmpty()).isTrue(); } @Test @@ -47,9 +44,9 @@ public class HttpEntityTests { headers.setContentType(MediaType.TEXT_PLAIN); String body = "foo"; HttpEntity entity = new HttpEntity<>(body, headers); - assertEquals(body, entity.getBody()); - assertEquals(MediaType.TEXT_PLAIN, entity.getHeaders().getContentType()); - assertEquals("text/plain", entity.getHeaders().getFirst("Content-Type")); + assertThat(entity.getBody()).isEqualTo(body); + assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(entity.getHeaders().getFirst("Content-Type")).isEqualTo("text/plain"); } @Test @@ -58,9 +55,9 @@ public class HttpEntityTests { map.set("Content-Type", "text/plain"); String body = "foo"; HttpEntity entity = new HttpEntity<>(body, map); - assertEquals(body, entity.getBody()); - assertEquals(MediaType.TEXT_PLAIN, entity.getHeaders().getContentType()); - assertEquals("text/plain", entity.getHeaders().getFirst("Content-Type")); + assertThat(entity.getBody()).isEqualTo(body); + assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(entity.getHeaders().getFirst("Content-Type")).isEqualTo("text/plain"); } @Test @@ -71,19 +68,19 @@ public class HttpEntityTests { MultiValueMap map2 = new LinkedMultiValueMap<>(); map2.set("Content-Type", "application/json"); - assertTrue(new HttpEntity<>().equals(new HttpEntity())); - assertFalse(new HttpEntity<>(map1).equals(new HttpEntity())); - assertFalse(new HttpEntity<>().equals(new HttpEntity(map2))); + assertThat(new HttpEntity<>().equals(new HttpEntity())).isTrue(); + assertThat(new HttpEntity<>(map1).equals(new HttpEntity())).isFalse(); + assertThat(new HttpEntity<>().equals(new HttpEntity(map2))).isFalse(); - assertTrue(new HttpEntity<>(map1).equals(new HttpEntity(map1))); - assertFalse(new HttpEntity<>(map1).equals(new HttpEntity(map2))); + assertThat(new HttpEntity<>(map1).equals(new HttpEntity(map1))).isTrue(); + assertThat(new HttpEntity<>(map1).equals(new HttpEntity(map2))).isFalse(); - assertTrue(new HttpEntity(null, null).equals(new HttpEntity(null, null))); - assertFalse(new HttpEntity<>("foo", null).equals(new HttpEntity(null, null))); - assertFalse(new HttpEntity(null, null).equals(new HttpEntity<>("bar", null))); + assertThat(new HttpEntity(null, null).equals(new HttpEntity(null, null))).isTrue(); + assertThat(new HttpEntity<>("foo", null).equals(new HttpEntity(null, null))).isFalse(); + assertThat(new HttpEntity(null, null).equals(new HttpEntity<>("bar", null))).isFalse(); - assertTrue(new HttpEntity<>("foo", map1).equals(new HttpEntity("foo", map1))); - assertFalse(new HttpEntity<>("foo", map1).equals(new HttpEntity("bar", map1))); + assertThat(new HttpEntity<>("foo", map1).equals(new HttpEntity("foo", map1))).isTrue(); + assertThat(new HttpEntity<>("foo", map1).equals(new HttpEntity("bar", map1))).isFalse(); } @Test @@ -95,15 +92,15 @@ public class HttpEntityTests { ResponseEntity responseEntity = new ResponseEntity<>(body, headers, HttpStatus.OK); ResponseEntity responseEntity2 = new ResponseEntity<>(body, headers, HttpStatus.OK); - assertEquals(body, responseEntity.getBody()); - assertEquals(MediaType.TEXT_PLAIN, responseEntity.getHeaders().getContentType()); - assertEquals("text/plain", responseEntity.getHeaders().getFirst("Content-Type")); - assertEquals("text/plain", responseEntity.getHeaders().getFirst("Content-Type")); + assertThat(responseEntity.getBody()).isEqualTo(body); + assertThat(responseEntity.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(responseEntity.getHeaders().getFirst("Content-Type")).isEqualTo("text/plain"); + assertThat(responseEntity.getHeaders().getFirst("Content-Type")).isEqualTo("text/plain"); - assertFalse(httpEntity.equals(responseEntity)); - assertFalse(responseEntity.equals(httpEntity)); - assertTrue(responseEntity.equals(responseEntity2)); - assertTrue(responseEntity2.equals(responseEntity)); + assertThat(httpEntity.equals(responseEntity)).isFalse(); + assertThat(responseEntity.equals(httpEntity)).isFalse(); + assertThat(responseEntity.equals(responseEntity2)).isTrue(); + assertThat(responseEntity2.equals(responseEntity)).isTrue(); } @Test @@ -115,15 +112,15 @@ public class HttpEntityTests { RequestEntity requestEntity = new RequestEntity<>(body, headers, HttpMethod.GET, new URI("/")); RequestEntity requestEntity2 = new RequestEntity<>(body, headers, HttpMethod.GET, new URI("/")); - assertEquals(body, requestEntity.getBody()); - assertEquals(MediaType.TEXT_PLAIN, requestEntity.getHeaders().getContentType()); - assertEquals("text/plain", requestEntity.getHeaders().getFirst("Content-Type")); - assertEquals("text/plain", requestEntity.getHeaders().getFirst("Content-Type")); + assertThat(requestEntity.getBody()).isEqualTo(body); + assertThat(requestEntity.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(requestEntity.getHeaders().getFirst("Content-Type")).isEqualTo("text/plain"); + assertThat(requestEntity.getHeaders().getFirst("Content-Type")).isEqualTo("text/plain"); - assertFalse(httpEntity.equals(requestEntity)); - assertFalse(requestEntity.equals(httpEntity)); - assertTrue(requestEntity.equals(requestEntity2)); - assertTrue(requestEntity2.equals(requestEntity)); + assertThat(httpEntity.equals(requestEntity)).isFalse(); + assertThat(requestEntity.equals(httpEntity)).isFalse(); + assertThat(requestEntity.equals(requestEntity2)).isTrue(); + assertThat(requestEntity2.equals(requestEntity)).isTrue(); } } diff --git a/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java b/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java index bfcf8ec740b..27a6c1e2f46 100644 --- a/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java +++ b/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java @@ -38,11 +38,6 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; 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; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link org.springframework.http.HttpHeaders}. @@ -88,8 +83,8 @@ public class HttpHeadersTests { mediaTypes.add(mediaType1); mediaTypes.add(mediaType2); headers.setAccept(mediaTypes); - assertEquals("Invalid Accept header", mediaTypes, headers.getAccept()); - assertEquals("Invalid Accept header", "text/html, text/plain", headers.getFirst("Accept")); + assertThat(headers.getAccept()).as("Invalid Accept header").isEqualTo(mediaTypes); + assertThat(headers.getFirst("Accept")).as("Invalid Accept header").isEqualTo("text/html, text/plain"); } @Test // SPR-9655 @@ -97,7 +92,7 @@ public class HttpHeadersTests { headers.add("Accept", "text/html"); headers.add("Accept", "text/plain"); List expected = Arrays.asList(new MediaType("text", "html"), new MediaType("text", "plain")); - assertEquals("Invalid Accept header", expected, headers.getAccept()); + assertThat(headers.getAccept()).as("Invalid Accept header").isEqualTo(expected); } @Test // SPR-14506 @@ -106,7 +101,7 @@ public class HttpHeadersTests { headers.add("Accept", "text/plain,text/csv"); List expected = Arrays.asList(new MediaType("text", "html"), new MediaType("text", "pdf"), new MediaType("text", "plain"), new MediaType("text", "csv")); - assertEquals("Invalid Accept header", expected, headers.getAccept()); + assertThat(headers.getAccept()).as("Invalid Accept header").isEqualTo(expected); } @Test @@ -117,79 +112,78 @@ public class HttpHeadersTests { charsets.add(charset1); charsets.add(charset2); headers.setAcceptCharset(charsets); - assertEquals("Invalid Accept header", charsets, headers.getAcceptCharset()); - assertEquals("Invalid Accept header", "utf-8, iso-8859-1", headers.getFirst("Accept-Charset")); + assertThat(headers.getAcceptCharset()).as("Invalid Accept header").isEqualTo(charsets); + assertThat(headers.getFirst("Accept-Charset")).as("Invalid Accept header").isEqualTo("utf-8, iso-8859-1"); } @Test public void acceptCharsetWildcard() { headers.set("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); - assertEquals("Invalid Accept header", Arrays.asList(StandardCharsets.ISO_8859_1, StandardCharsets.UTF_8), - headers.getAcceptCharset()); + assertThat(headers.getAcceptCharset()).as("Invalid Accept header").isEqualTo(Arrays.asList(StandardCharsets.ISO_8859_1, StandardCharsets.UTF_8)); } @Test public void allow() { EnumSet methods = EnumSet.of(HttpMethod.GET, HttpMethod.POST); headers.setAllow(methods); - assertEquals("Invalid Allow header", methods, headers.getAllow()); - assertEquals("Invalid Allow header", "GET,POST", headers.getFirst("Allow")); + assertThat(headers.getAllow()).as("Invalid Allow header").isEqualTo(methods); + assertThat(headers.getFirst("Allow")).as("Invalid Allow header").isEqualTo("GET,POST"); } @Test public void contentLength() { long length = 42L; headers.setContentLength(length); - assertEquals("Invalid Content-Length header", length, headers.getContentLength()); - assertEquals("Invalid Content-Length header", "42", headers.getFirst("Content-Length")); + assertThat(headers.getContentLength()).as("Invalid Content-Length header").isEqualTo(length); + assertThat(headers.getFirst("Content-Length")).as("Invalid Content-Length header").isEqualTo("42"); } @Test public void contentType() { MediaType contentType = new MediaType("text", "html", StandardCharsets.UTF_8); headers.setContentType(contentType); - assertEquals("Invalid Content-Type header", contentType, headers.getContentType()); - assertEquals("Invalid Content-Type header", "text/html;charset=UTF-8", headers.getFirst("Content-Type")); + assertThat(headers.getContentType()).as("Invalid Content-Type header").isEqualTo(contentType); + assertThat(headers.getFirst("Content-Type")).as("Invalid Content-Type header").isEqualTo("text/html;charset=UTF-8"); } @Test public void location() throws URISyntaxException { URI location = new URI("https://www.example.com/hotels"); headers.setLocation(location); - assertEquals("Invalid Location header", location, headers.getLocation()); - assertEquals("Invalid Location header", "https://www.example.com/hotels", headers.getFirst("Location")); + assertThat(headers.getLocation()).as("Invalid Location header").isEqualTo(location); + assertThat(headers.getFirst("Location")).as("Invalid Location header").isEqualTo("https://www.example.com/hotels"); } @Test public void eTag() { String eTag = "\"v2.6\""; headers.setETag(eTag); - assertEquals("Invalid ETag header", eTag, headers.getETag()); - assertEquals("Invalid ETag header", "\"v2.6\"", headers.getFirst("ETag")); + assertThat(headers.getETag()).as("Invalid ETag header").isEqualTo(eTag); + assertThat(headers.getFirst("ETag")).as("Invalid ETag header").isEqualTo("\"v2.6\""); } @Test public void host() { InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 8080); headers.setHost(host); - assertEquals("Invalid Host header", host, headers.getHost()); - assertEquals("Invalid Host header", "localhost:8080", headers.getFirst("Host")); + assertThat(headers.getHost()).as("Invalid Host header").isEqualTo(host); + assertThat(headers.getFirst("Host")).as("Invalid Host header").isEqualTo("localhost:8080"); } @Test public void hostNoPort() { InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 0); headers.setHost(host); - assertEquals("Invalid Host header", host, headers.getHost()); - assertEquals("Invalid Host header", "localhost", headers.getFirst("Host")); + assertThat(headers.getHost()).as("Invalid Host header").isEqualTo(host); + assertThat(headers.getFirst("Host")).as("Invalid Host header").isEqualTo("localhost"); } @Test public void ipv6Host() { InetSocketAddress host = InetSocketAddress.createUnresolved("[::1]", 0); headers.setHost(host); - assertEquals("Invalid Host header", host, headers.getHost()); - assertEquals("Invalid Host header", "[::1]", headers.getFirst("Host")); + assertThat(headers.getHost()).as("Invalid Host header").isEqualTo(host); + assertThat(headers.getFirst("Host")).as("Invalid Host header").isEqualTo("[::1]"); } @Test @@ -202,8 +196,8 @@ public class HttpHeadersTests { public void ifMatch() { String ifMatch = "\"v2.6\""; headers.setIfMatch(ifMatch); - assertEquals("Invalid If-Match header", ifMatch, headers.getIfMatch().get(0)); - assertEquals("Invalid If-Match header", "\"v2.6\"", headers.getFirst("If-Match")); + assertThat(headers.getIfMatch().get(0)).as("Invalid If-Match header").isEqualTo(ifMatch); + assertThat(headers.getFirst("If-Match")).as("Invalid If-Match header").isEqualTo("\"v2.6\""); } @Test @@ -216,8 +210,8 @@ public class HttpHeadersTests { public void ifMatchMultipleHeaders() { headers.add(HttpHeaders.IF_MATCH, "\"v2,0\""); headers.add(HttpHeaders.IF_MATCH, "W/\"v2,1\", \"v2,2\""); - assertEquals("Invalid If-Match header", "\"v2,0\"", headers.get(HttpHeaders.IF_MATCH).get(0)); - assertEquals("Invalid If-Match header", "W/\"v2,1\", \"v2,2\"", headers.get(HttpHeaders.IF_MATCH).get(1)); + assertThat(headers.get(HttpHeaders.IF_MATCH).get(0)).as("Invalid If-Match header").isEqualTo("\"v2,0\""); + assertThat(headers.get(HttpHeaders.IF_MATCH).get(1)).as("Invalid If-Match header").isEqualTo("W/\"v2,1\", \"v2,2\""); assertThat(headers.getIfMatch()).contains("\"v2,0\"", "W/\"v2,1\"", "\"v2,2\""); } @@ -225,16 +219,16 @@ public class HttpHeadersTests { public void ifNoneMatch() { String ifNoneMatch = "\"v2.6\""; headers.setIfNoneMatch(ifNoneMatch); - assertEquals("Invalid If-None-Match header", ifNoneMatch, headers.getIfNoneMatch().get(0)); - assertEquals("Invalid If-None-Match header", "\"v2.6\"", headers.getFirst("If-None-Match")); + assertThat(headers.getIfNoneMatch().get(0)).as("Invalid If-None-Match header").isEqualTo(ifNoneMatch); + assertThat(headers.getFirst("If-None-Match")).as("Invalid If-None-Match header").isEqualTo("\"v2.6\""); } @Test public void ifNoneMatchWildCard() { String ifNoneMatch = "*"; headers.setIfNoneMatch(ifNoneMatch); - assertEquals("Invalid If-None-Match header", ifNoneMatch, headers.getIfNoneMatch().get(0)); - assertEquals("Invalid If-None-Match header", "*", headers.getFirst("If-None-Match")); + assertThat(headers.getIfNoneMatch().get(0)).as("Invalid If-None-Match header").isEqualTo(ifNoneMatch); + assertThat(headers.getFirst("If-None-Match")).as("Invalid If-None-Match header").isEqualTo("*"); } @Test @@ -246,7 +240,7 @@ public class HttpHeadersTests { ifNoneMatchList.add(ifNoneMatch2); headers.setIfNoneMatch(ifNoneMatchList); assertThat(headers.getIfNoneMatch()).contains("\"v2.6\"", "\"v2.7\"", "\"v2.8\""); - assertEquals("Invalid If-None-Match header", "\"v2.6\", \"v2.7\", \"v2.8\"", headers.getFirst("If-None-Match")); + assertThat(headers.getFirst("If-None-Match")).as("Invalid If-None-Match header").isEqualTo("\"v2.6\", \"v2.7\", \"v2.8\""); } @Test @@ -255,12 +249,12 @@ public class HttpHeadersTests { calendar.setTimeZone(TimeZone.getTimeZone("CET")); long date = calendar.getTimeInMillis(); headers.setDate(date); - assertEquals("Invalid Date header", date, headers.getDate()); - assertEquals("Invalid Date header", "Thu, 18 Dec 2008 10:20:00 GMT", headers.getFirst("date")); + assertThat(headers.getDate()).as("Invalid Date header").isEqualTo(date); + assertThat(headers.getFirst("date")).as("Invalid Date header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); // RFC 850 headers.set("Date", "Thu, 18 Dec 2008 10:20:00 GMT"); - assertEquals("Invalid Date header", date, headers.getDate()); + assertThat(headers.getDate()).as("Invalid Date header").isEqualTo(date); } @Test @@ -278,8 +272,8 @@ public class HttpHeadersTests { calendar.setTimeZone(TimeZone.getTimeZone("CET")); long date = calendar.getTimeInMillis(); headers.setDate(date); - assertEquals("Invalid Date header", "Thu, 18 Dec 2008 10:20:00 GMT", headers.getFirst("date")); - assertEquals("Invalid Date header", date, headers.getDate()); + assertThat(headers.getFirst("date")).as("Invalid Date header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); + assertThat(headers.getDate()).as("Invalid Date header").isEqualTo(date); } finally { Locale.setDefault(defaultLocale); @@ -292,9 +286,8 @@ public class HttpHeadersTests { calendar.setTimeZone(TimeZone.getTimeZone("CET")); long date = calendar.getTimeInMillis(); headers.setLastModified(date); - assertEquals("Invalid Last-Modified header", date, headers.getLastModified()); - assertEquals("Invalid Last-Modified header", "Thu, 18 Dec 2008 10:20:00 GMT", - headers.getFirst("last-modified")); + assertThat(headers.getLastModified()).as("Invalid Last-Modified header").isEqualTo(date); + assertThat(headers.getFirst("last-modified")).as("Invalid Last-Modified header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); } @Test @@ -303,22 +296,22 @@ public class HttpHeadersTests { calendar.setTimeZone(TimeZone.getTimeZone("CET")); long date = calendar.getTimeInMillis(); headers.setExpires(date); - assertEquals("Invalid Expires header", date, headers.getExpires()); - assertEquals("Invalid Expires header", "Thu, 18 Dec 2008 10:20:00 GMT", headers.getFirst("expires")); + assertThat(headers.getExpires()).as("Invalid Expires header").isEqualTo(date); + assertThat(headers.getFirst("expires")).as("Invalid Expires header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); } @Test public void expiresZonedDateTime() { ZonedDateTime zonedDateTime = ZonedDateTime.of(2008, 12, 18, 10, 20, 0, 0, ZoneId.of("GMT")); headers.setExpires(zonedDateTime); - assertEquals("Invalid Expires header", zonedDateTime.toInstant().toEpochMilli(), headers.getExpires()); - assertEquals("Invalid Expires header", "Thu, 18 Dec 2008 10:20:00 GMT", headers.getFirst("expires")); + assertThat(headers.getExpires()).as("Invalid Expires header").isEqualTo(zonedDateTime.toInstant().toEpochMilli()); + assertThat(headers.getFirst("expires")).as("Invalid Expires header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); } @Test // SPR-10648 (example is from INT-3063) public void expiresInvalidDate() { headers.set("Expires", "-1"); - assertEquals(-1, headers.getExpires()); + assertThat(headers.getExpires()).isEqualTo(-1); } @Test @@ -327,68 +320,67 @@ public class HttpHeadersTests { calendar.setTimeZone(TimeZone.getTimeZone("CET")); long date = calendar.getTimeInMillis(); headers.setIfModifiedSince(date); - assertEquals("Invalid If-Modified-Since header", date, headers.getIfModifiedSince()); - assertEquals("Invalid If-Modified-Since header", "Thu, 18 Dec 2008 10:20:00 GMT", - headers.getFirst("if-modified-since")); + assertThat(headers.getIfModifiedSince()).as("Invalid If-Modified-Since header").isEqualTo(date); + assertThat(headers.getFirst("if-modified-since")).as("Invalid If-Modified-Since header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); } @Test // SPR-14144 public void invalidIfModifiedSinceHeader() { headers.set(HttpHeaders.IF_MODIFIED_SINCE, "0"); - assertEquals(-1, headers.getIfModifiedSince()); + assertThat(headers.getIfModifiedSince()).isEqualTo(-1); headers.set(HttpHeaders.IF_MODIFIED_SINCE, "-1"); - assertEquals(-1, headers.getIfModifiedSince()); + assertThat(headers.getIfModifiedSince()).isEqualTo(-1); headers.set(HttpHeaders.IF_MODIFIED_SINCE, "XXX"); - assertEquals(-1, headers.getIfModifiedSince()); + assertThat(headers.getIfModifiedSince()).isEqualTo(-1); } @Test public void pragma() { String pragma = "no-cache"; headers.setPragma(pragma); - assertEquals("Invalid Pragma header", pragma, headers.getPragma()); - assertEquals("Invalid Pragma header", "no-cache", headers.getFirst("pragma")); + assertThat(headers.getPragma()).as("Invalid Pragma header").isEqualTo(pragma); + assertThat(headers.getFirst("pragma")).as("Invalid Pragma header").isEqualTo("no-cache"); } @Test public void cacheControl() { headers.setCacheControl("no-cache"); - assertEquals("Invalid Cache-Control header", "no-cache", headers.getCacheControl()); - assertEquals("Invalid Cache-Control header", "no-cache", headers.getFirst("cache-control")); + assertThat(headers.getCacheControl()).as("Invalid Cache-Control header").isEqualTo("no-cache"); + assertThat(headers.getFirst("cache-control")).as("Invalid Cache-Control header").isEqualTo("no-cache"); } @Test public void cacheControlBuilder() { headers.setCacheControl(CacheControl.noCache()); - assertEquals("Invalid Cache-Control header", "no-cache", headers.getCacheControl()); - assertEquals("Invalid Cache-Control header", "no-cache", headers.getFirst("cache-control")); + assertThat(headers.getCacheControl()).as("Invalid Cache-Control header").isEqualTo("no-cache"); + assertThat(headers.getFirst("cache-control")).as("Invalid Cache-Control header").isEqualTo("no-cache"); } @Test public void cacheControlEmpty() { headers.setCacheControl(CacheControl.empty()); - assertNull("Invalid Cache-Control header", headers.getCacheControl()); - assertNull("Invalid Cache-Control header", headers.getFirst("cache-control")); + assertThat(headers.getCacheControl()).as("Invalid Cache-Control header").isNull(); + assertThat(headers.getFirst("cache-control")).as("Invalid Cache-Control header").isNull(); } @Test public void cacheControlAllValues() { headers.add(HttpHeaders.CACHE_CONTROL, "max-age=1000, public"); headers.add(HttpHeaders.CACHE_CONTROL, "s-maxage=1000"); - assertEquals("max-age=1000, public, s-maxage=1000", headers.getCacheControl()); + assertThat(headers.getCacheControl()).isEqualTo("max-age=1000, public, s-maxage=1000"); } @Test public void contentDisposition() { ContentDisposition disposition = headers.getContentDisposition(); - assertNotNull(disposition); - assertEquals("Invalid Content-Disposition header", ContentDisposition.empty(), headers.getContentDisposition()); + assertThat(disposition).isNotNull(); + assertThat(headers.getContentDisposition()).as("Invalid Content-Disposition header").isEqualTo(ContentDisposition.empty()); disposition = ContentDisposition.builder("attachment").name("foo").filename("foo.txt").size(123L).build(); headers.setContentDisposition(disposition); - assertEquals("Invalid Content-Disposition header", disposition, headers.getContentDisposition()); + assertThat(headers.getContentDisposition()).as("Invalid Content-Disposition header").isEqualTo(disposition); } @Test // SPR-11917 @@ -399,11 +391,11 @@ public class HttpHeadersTests { @Test public void accessControlAllowCredentials() { - assertFalse(headers.getAccessControlAllowCredentials()); + assertThat(headers.getAccessControlAllowCredentials()).isFalse(); headers.setAccessControlAllowCredentials(false); - assertFalse(headers.getAccessControlAllowCredentials()); + assertThat(headers.getAccessControlAllowCredentials()).isFalse(); headers.setAccessControlAllowCredentials(true); - assertTrue(headers.getAccessControlAllowCredentials()); + assertThat(headers.getAccessControlAllowCredentials()).isTrue(); } @Test @@ -412,7 +404,7 @@ public class HttpHeadersTests { assertThat(allowedHeaders).isEmpty(); headers.setAccessControlAllowHeaders(Arrays.asList("header1", "header2")); allowedHeaders = headers.getAccessControlAllowHeaders(); - assertEquals(allowedHeaders, Arrays.asList("header1", "header2")); + assertThat(Arrays.asList("header1", "header2")).isEqualTo(allowedHeaders); } @Test @@ -422,7 +414,7 @@ public class HttpHeadersTests { headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "header1, header2"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "header3"); allowedHeaders = headers.getAccessControlAllowHeaders(); - assertEquals(Arrays.asList("header1", "header2", "header3"), allowedHeaders); + assertThat(allowedHeaders).isEqualTo(Arrays.asList("header1", "header2", "header3")); } @Test @@ -431,14 +423,14 @@ public class HttpHeadersTests { assertThat(allowedMethods).isEmpty(); headers.setAccessControlAllowMethods(Arrays.asList(HttpMethod.GET, HttpMethod.POST)); allowedMethods = headers.getAccessControlAllowMethods(); - assertEquals(allowedMethods, Arrays.asList(HttpMethod.GET, HttpMethod.POST)); + assertThat(Arrays.asList(HttpMethod.GET, HttpMethod.POST)).isEqualTo(allowedMethods); } @Test public void accessControlAllowOrigin() { - assertNull(headers.getAccessControlAllowOrigin()); + assertThat(headers.getAccessControlAllowOrigin()).isNull(); headers.setAccessControlAllowOrigin("*"); - assertEquals("*", headers.getAccessControlAllowOrigin()); + assertThat(headers.getAccessControlAllowOrigin()).isEqualTo("*"); } @Test @@ -447,14 +439,14 @@ public class HttpHeadersTests { assertThat(exposedHeaders).isEmpty(); headers.setAccessControlExposeHeaders(Arrays.asList("header1", "header2")); exposedHeaders = headers.getAccessControlExposeHeaders(); - assertEquals(exposedHeaders, Arrays.asList("header1", "header2")); + assertThat(Arrays.asList("header1", "header2")).isEqualTo(exposedHeaders); } @Test public void accessControlMaxAge() { - assertEquals(-1, headers.getAccessControlMaxAge()); + assertThat(headers.getAccessControlMaxAge()).isEqualTo(-1); headers.setAccessControlMaxAge(3600); - assertEquals(3600, headers.getAccessControlMaxAge()); + assertThat(headers.getAccessControlMaxAge()).isEqualTo(3600); } @Test @@ -463,21 +455,21 @@ public class HttpHeadersTests { assertThat(requestHeaders).isEmpty(); headers.setAccessControlRequestHeaders(Arrays.asList("header1", "header2")); requestHeaders = headers.getAccessControlRequestHeaders(); - assertEquals(requestHeaders, Arrays.asList("header1", "header2")); + assertThat(Arrays.asList("header1", "header2")).isEqualTo(requestHeaders); } @Test public void accessControlRequestMethod() { - assertNull(headers.getAccessControlRequestMethod()); + assertThat(headers.getAccessControlRequestMethod()).isNull(); headers.setAccessControlRequestMethod(HttpMethod.POST); - assertEquals(HttpMethod.POST, headers.getAccessControlRequestMethod()); + assertThat(headers.getAccessControlRequestMethod()).isEqualTo(HttpMethod.POST); } @Test public void acceptLanguage() { String headerValue = "fr-ch, fr;q=0.9, en-*;q=0.8, de;q=0.7, *;q=0.5"; headers.setAcceptLanguage(Locale.LanguageRange.parse(headerValue)); - assertEquals(headerValue, headers.getFirst(HttpHeaders.ACCEPT_LANGUAGE)); + assertThat(headers.getFirst(HttpHeaders.ACCEPT_LANGUAGE)).isEqualTo(headerValue); List expectedRanges = Arrays.asList( new Locale.LanguageRange("fr-ch"), @@ -486,30 +478,30 @@ public class HttpHeadersTests { new Locale.LanguageRange("de", 0.7), new Locale.LanguageRange("*", 0.5) ); - assertEquals(expectedRanges, headers.getAcceptLanguage()); - assertEquals(Locale.forLanguageTag("fr-ch"), headers.getAcceptLanguageAsLocales().get(0)); + assertThat(headers.getAcceptLanguage()).isEqualTo(expectedRanges); + assertThat(headers.getAcceptLanguageAsLocales().get(0)).isEqualTo(Locale.forLanguageTag("fr-ch")); headers.setAcceptLanguageAsLocales(Collections.singletonList(Locale.FRANCE)); - assertEquals(Locale.FRANCE, headers.getAcceptLanguageAsLocales().get(0)); + assertThat(headers.getAcceptLanguageAsLocales().get(0)).isEqualTo(Locale.FRANCE); } @Test // SPR-15603 public void acceptLanguageWithEmptyValue() throws Exception { this.headers.set(HttpHeaders.ACCEPT_LANGUAGE, ""); - assertEquals(Collections.emptyList(), this.headers.getAcceptLanguageAsLocales()); + assertThat(this.headers.getAcceptLanguageAsLocales()).isEqualTo(Collections.emptyList()); } @Test public void contentLanguage() { headers.setContentLanguage(Locale.FRANCE); - assertEquals(Locale.FRANCE, headers.getContentLanguage()); - assertEquals("fr-FR", headers.getFirst(HttpHeaders.CONTENT_LANGUAGE)); + assertThat(headers.getContentLanguage()).isEqualTo(Locale.FRANCE); + assertThat(headers.getFirst(HttpHeaders.CONTENT_LANGUAGE)).isEqualTo("fr-FR"); } @Test public void contentLanguageSerialized() { headers.set(HttpHeaders.CONTENT_LANGUAGE, "de, en_CA"); - assertEquals("Expected one (first) locale", Locale.GERMAN, headers.getContentLanguage()); + assertThat(headers.getContentLanguage()).as("Expected one (first) locale").isEqualTo(Locale.GERMAN); } @Test @@ -529,24 +521,24 @@ public class HttpHeadersTests { ZonedDateTime date = ZonedDateTime.of(2017, 6, 2, 2, 22, 0, 0, ZoneId.of("GMT")); headers.setZonedDateTime(HttpHeaders.DATE, date); assertThat(headers.getFirst(HttpHeaders.DATE)).isEqualTo("Fri, 02 Jun 2017 02:22:00 GMT"); - assertTrue(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)); + assertThat(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)).isTrue(); headers.clear(); headers.add(HttpHeaders.DATE, "Fri, 02 Jun 2017 02:22:00 GMT"); headers.add(HttpHeaders.DATE, "Sat, 18 Dec 2010 10:20:00 GMT"); - assertTrue(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)); - assertEquals(Arrays.asList("Fri, 02 Jun 2017 02:22:00 GMT", - "Sat, 18 Dec 2010 10:20:00 GMT"), headers.get(HttpHeaders.DATE)); + assertThat(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)).isTrue(); + assertThat(headers.get(HttpHeaders.DATE)).isEqualTo(Arrays.asList("Fri, 02 Jun 2017 02:22:00 GMT", + "Sat, 18 Dec 2010 10:20:00 GMT")); // obsolete RFC 850 format headers.clear(); headers.set(HttpHeaders.DATE, "Friday, 02-Jun-17 02:22:00 GMT"); - assertTrue(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)); + assertThat(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)).isTrue(); // ANSI C's asctime() format headers.clear(); headers.set(HttpHeaders.DATE, "Fri Jun 02 02:22:00 2017"); - assertTrue(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)); + assertThat(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)).isTrue(); } @Test @@ -555,10 +547,10 @@ public class HttpHeadersTests { String password = "bar"; headers.setBasicAuth(username, password); String authorization = headers.getFirst(HttpHeaders.AUTHORIZATION); - assertNotNull(authorization); - assertTrue(authorization.startsWith("Basic ")); + assertThat(authorization).isNotNull(); + assertThat(authorization.startsWith("Basic ")).isTrue(); byte[] result = Base64.getDecoder().decode(authorization.substring(6).getBytes(StandardCharsets.ISO_8859_1)); - assertEquals("foo:bar", new String(result, StandardCharsets.ISO_8859_1)); + assertThat(new String(result, StandardCharsets.ISO_8859_1)).isEqualTo("foo:bar"); } @Test @@ -574,7 +566,7 @@ public class HttpHeadersTests { headers.setBearerAuth(token); String authorization = headers.getFirst(HttpHeaders.AUTHORIZATION); - assertEquals("Bearer foo", authorization); + assertThat(authorization).isEqualTo("Bearer foo"); } @Test @@ -582,13 +574,13 @@ public class HttpHeadersTests { String headerName = "MyHeader"; String headerValue = "value"; - assertTrue(headers.isEmpty()); + assertThat(headers.isEmpty()).isTrue(); headers.add(headerName, headerValue); - assertTrue(headers.containsKey(headerName)); + assertThat(headers.containsKey(headerName)).isTrue(); headers.keySet().removeIf(key -> key.equals(headerName)); - assertTrue(headers.isEmpty()); + assertThat(headers.isEmpty()).isTrue(); headers.add(headerName, headerValue); - assertEquals(headerValue, headers.get(headerName).get(0)); + assertThat(headers.get(headerName).get(0)).isEqualTo(headerValue); } @Test @@ -596,13 +588,13 @@ public class HttpHeadersTests { String headerName = "MyHeader"; String headerValue = "value"; - assertTrue(headers.isEmpty()); + assertThat(headers.isEmpty()).isTrue(); headers.add(headerName, headerValue); - assertTrue(headers.containsKey(headerName)); + assertThat(headers.containsKey(headerName)).isTrue(); headers.entrySet().removeIf(entry -> entry.getKey().equals(headerName)); - assertTrue(headers.isEmpty()); + assertThat(headers.isEmpty()).isTrue(); headers.add(headerName, headerValue); - assertEquals(headerValue, headers.get(headerName).get(0)); + assertThat(headers.get(headerName).get(0)).isEqualTo(headerValue); } } diff --git a/spring-web/src/test/java/org/springframework/http/HttpRangeTests.java b/spring-web/src/test/java/org/springframework/http/HttpRangeTests.java index 60ceacbd8e5..fe1d461b0aa 100644 --- a/spring-web/src/test/java/org/springframework/http/HttpRangeTests.java +++ b/spring-web/src/test/java/org/springframework/http/HttpRangeTests.java @@ -27,8 +27,8 @@ import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.support.ResourceRegion; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -61,48 +61,48 @@ public class HttpRangeTests { @Test public void byteRange() { HttpRange range = HttpRange.createByteRange(0, 499); - assertEquals(0, range.getRangeStart(1000)); - assertEquals(499, range.getRangeEnd(1000)); + assertThat(range.getRangeStart(1000)).isEqualTo(0); + assertThat(range.getRangeEnd(1000)).isEqualTo(499); } @Test public void byteRangeWithoutLastPosition() { HttpRange range = HttpRange.createByteRange(9500); - assertEquals(9500, range.getRangeStart(10000)); - assertEquals(9999, range.getRangeEnd(10000)); + assertThat(range.getRangeStart(10000)).isEqualTo(9500); + assertThat(range.getRangeEnd(10000)).isEqualTo(9999); } @Test public void byteRangeOfZeroLength() { HttpRange range = HttpRange.createByteRange(9500, 9500); - assertEquals(9500, range.getRangeStart(10000)); - assertEquals(9500, range.getRangeEnd(10000)); + assertThat(range.getRangeStart(10000)).isEqualTo(9500); + assertThat(range.getRangeEnd(10000)).isEqualTo(9500); } @Test public void suffixRange() { HttpRange range = HttpRange.createSuffixRange(500); - assertEquals(500, range.getRangeStart(1000)); - assertEquals(999, range.getRangeEnd(1000)); + assertThat(range.getRangeStart(1000)).isEqualTo(500); + assertThat(range.getRangeEnd(1000)).isEqualTo(999); } @Test public void suffixRangeShorterThanRepresentation() { HttpRange range = HttpRange.createSuffixRange(500); - assertEquals(0, range.getRangeStart(350)); - assertEquals(349, range.getRangeEnd(350)); + assertThat(range.getRangeStart(350)).isEqualTo(0); + assertThat(range.getRangeEnd(350)).isEqualTo(349); } @Test public void parseRanges() { List ranges = HttpRange.parseRanges("bytes=0-0,500-,-1"); - assertEquals(3, ranges.size()); - assertEquals(0, ranges.get(0).getRangeStart(1000)); - assertEquals(0, ranges.get(0).getRangeEnd(1000)); - assertEquals(500, ranges.get(1).getRangeStart(1000)); - assertEquals(999, ranges.get(1).getRangeEnd(1000)); - assertEquals(999, ranges.get(2).getRangeStart(1000)); - assertEquals(999, ranges.get(2).getRangeEnd(1000)); + assertThat(ranges.size()).isEqualTo(3); + assertThat(ranges.get(0).getRangeStart(1000)).isEqualTo(0); + assertThat(ranges.get(0).getRangeEnd(1000)).isEqualTo(0); + assertThat(ranges.get(1).getRangeStart(1000)).isEqualTo(500); + assertThat(ranges.get(1).getRangeEnd(1000)).isEqualTo(999); + assertThat(ranges.get(2).getRangeStart(1000)).isEqualTo(999); + assertThat(ranges.get(2).getRangeEnd(1000)).isEqualTo(999); } @Test @@ -114,7 +114,7 @@ public class HttpRangeTests { atLimit.append(",").append(i).append("-").append(i + 1); } List ranges = HttpRange.parseRanges(atLimit.toString()); - assertEquals(100, ranges.size()); + assertThat(ranges.size()).isEqualTo(100); // 2. Above limit.. StringBuilder aboveLimit = new StringBuilder("bytes=0-0"); @@ -131,7 +131,7 @@ public class HttpRangeTests { ranges.add(HttpRange.createByteRange(0, 499)); ranges.add(HttpRange.createByteRange(9500)); ranges.add(HttpRange.createSuffixRange(500)); - assertEquals("Invalid Range header", "bytes=0-499, 9500-, -500", HttpRange.toString(ranges)); + assertThat(HttpRange.toString(ranges)).as("Invalid Range header").isEqualTo("bytes=0-499, 9500-, -500"); } @Test @@ -140,9 +140,9 @@ public class HttpRangeTests { ByteArrayResource resource = new ByteArrayResource(bytes); HttpRange range = HttpRange.createByteRange(0, 5); ResourceRegion region = range.toResourceRegion(resource); - assertEquals(resource, region.getResource()); - assertEquals(0L, region.getPosition()); - assertEquals(6L, region.getCount()); + assertThat(region.getResource()).isEqualTo(resource); + assertThat(region.getPosition()).isEqualTo(0L); + assertThat(region.getCount()).isEqualTo(6L); } @Test @@ -163,7 +163,6 @@ public class HttpRangeTests { } @Test - @SuppressWarnings("unchecked") public void toResourceRegionExceptionLength() throws IOException { InputStreamResource resource = mock(InputStreamResource.class); given(resource.contentLength()).willThrow(IOException.class); @@ -180,7 +179,7 @@ public class HttpRangeTests { // 1. Below length List belowLengthRanges = HttpRange.parseRanges("bytes=0-1,2-3"); List regions = HttpRange.toResourceRegions(belowLengthRanges, resource); - assertEquals(2, regions.size()); + assertThat(regions.size()).isEqualTo(2); // 2. At length List atLengthRanges = HttpRange.parseRanges("bytes=0-1,2-4"); diff --git a/spring-web/src/test/java/org/springframework/http/HttpStatusTests.java b/spring-web/src/test/java/org/springframework/http/HttpStatusTests.java index de7bfa64251..59bba7c1c45 100644 --- a/spring-web/src/test/java/org/springframework/http/HttpStatusTests.java +++ b/spring-web/src/test/java/org/springframework/http/HttpStatusTests.java @@ -22,8 +22,7 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** @author Arjen Poutsma */ public class HttpStatusTests { @@ -107,8 +106,8 @@ public class HttpStatusTests { for (Map.Entry entry : statusCodes.entrySet()) { int value = entry.getKey(); HttpStatus status = HttpStatus.valueOf(value); - assertEquals("Invalid value", value, status.value()); - assertEquals("Invalid name for [" + value + "]", entry.getValue(), status.name()); + assertThat(status.value()).as("Invalid value").isEqualTo(value); + assertThat(status.name()).as("Invalid name for [" + value + "]").isEqualTo(entry.getValue()); } } @@ -120,8 +119,8 @@ public class HttpStatusTests { if (value == 302 || value == 413 || value == 414) { continue; } - assertTrue("Map has no value for [" + value + "]", statusCodes.containsKey(value)); - assertEquals("Invalid name for [" + value + "]", statusCodes.get(value), status.name()); + assertThat(statusCodes.containsKey(value)).as("Map has no value for [" + value + "]").isTrue(); + assertThat(status.name()).as("Invalid name for [" + value + "]").isEqualTo(statusCodes.get(value)); } } } diff --git a/spring-web/src/test/java/org/springframework/http/MediaTypeFactoryTests.java b/spring-web/src/test/java/org/springframework/http/MediaTypeFactoryTests.java index d6bc9a6dad0..251995d9a86 100644 --- a/spring-web/src/test/java/org/springframework/http/MediaTypeFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/MediaTypeFactoryTests.java @@ -20,9 +20,7 @@ import org.junit.Test; import org.springframework.core.io.Resource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -31,17 +29,17 @@ public class MediaTypeFactoryTests { @Test public void getMediaType() { - assertEquals(MediaType.APPLICATION_XML, MediaTypeFactory.getMediaType("file.xml").get()); - assertEquals(MediaType.parseMediaType("application/javascript"), MediaTypeFactory.getMediaType("file.js").get()); - assertEquals(MediaType.parseMediaType("text/css"), MediaTypeFactory.getMediaType("file.css").get()); - assertFalse(MediaTypeFactory.getMediaType("file.foobar").isPresent()); + assertThat(MediaTypeFactory.getMediaType("file.xml").get()).isEqualTo(MediaType.APPLICATION_XML); + assertThat(MediaTypeFactory.getMediaType("file.js").get()).isEqualTo(MediaType.parseMediaType("application/javascript")); + assertThat(MediaTypeFactory.getMediaType("file.css").get()).isEqualTo(MediaType.parseMediaType("text/css")); + assertThat(MediaTypeFactory.getMediaType("file.foobar").isPresent()).isFalse(); } @Test public void nullParameter() { - assertFalse(MediaTypeFactory.getMediaType((String) null).isPresent()); - assertFalse(MediaTypeFactory.getMediaType((Resource) null).isPresent()); - assertTrue(MediaTypeFactory.getMediaTypes(null).isEmpty()); + assertThat(MediaTypeFactory.getMediaType((String) null).isPresent()).isFalse(); + assertThat(MediaTypeFactory.getMediaType((Resource) null).isPresent()).isFalse(); + assertThat(MediaTypeFactory.getMediaTypes(null).isEmpty()).isTrue(); } } diff --git a/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java b/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java index 0fb56e18c5e..c136df22526 100644 --- a/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java +++ b/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java @@ -27,13 +27,10 @@ import org.junit.Test; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.support.DefaultConversionService; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.within; /** * @author Arjen Poutsma @@ -45,7 +42,7 @@ public class MediaTypeTests { public void testToString() throws Exception { MediaType mediaType = new MediaType("text", "plain", 0.7); String result = mediaType.toString(); - assertEquals("Invalid toString() returned", "text/plain;q=0.7", result); + assertThat(result).as("Invalid toString() returned").isEqualTo("text/plain;q=0.7"); } @Test @@ -63,16 +60,16 @@ public class MediaTypeTests { @Test public void getDefaultQualityValue() { MediaType mediaType = new MediaType("text", "plain"); - assertEquals("Invalid quality value", 1, mediaType.getQualityValue(), 0D); + assertThat(mediaType.getQualityValue()).as("Invalid quality value").isCloseTo(1D, within(0D)); } @Test public void parseMediaType() throws Exception { String s = "audio/*; q=0.2"; MediaType mediaType = MediaType.parseMediaType(s); - assertEquals("Invalid type", "audio", mediaType.getType()); - assertEquals("Invalid subtype", "*", mediaType.getSubtype()); - assertEquals("Invalid quality factor", 0.2D, mediaType.getQualityValue(), 0D); + assertThat(mediaType.getType()).as("Invalid type").isEqualTo("audio"); + assertThat(mediaType.getSubtype()).as("Invalid subtype").isEqualTo("*"); + assertThat(mediaType.getQualityValue()).as("Invalid quality factor").isCloseTo(0.2D, within(0D)); } @Test @@ -145,21 +142,21 @@ public class MediaTypeTests { public void parseURLConnectionMediaType() throws Exception { String s = "*; q=.2"; MediaType mediaType = MediaType.parseMediaType(s); - assertEquals("Invalid type", "*", mediaType.getType()); - assertEquals("Invalid subtype", "*", mediaType.getSubtype()); - assertEquals("Invalid quality factor", 0.2D, mediaType.getQualityValue(), 0D); + assertThat(mediaType.getType()).as("Invalid type").isEqualTo("*"); + assertThat(mediaType.getSubtype()).as("Invalid subtype").isEqualTo("*"); + assertThat(mediaType.getQualityValue()).as("Invalid quality factor").isCloseTo(0.2D, within(0D)); } @Test public void parseMediaTypes() throws Exception { String s = "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"; List mediaTypes = MediaType.parseMediaTypes(s); - assertNotNull("No media types returned", mediaTypes); - assertEquals("Invalid amount of media types", 4, mediaTypes.size()); + assertThat(mediaTypes).as("No media types returned").isNotNull(); + assertThat(mediaTypes.size()).as("Invalid amount of media types").isEqualTo(4); mediaTypes = MediaType.parseMediaTypes(""); - assertNotNull("No media types returned", mediaTypes); - assertEquals("Invalid amount of media types", 0, mediaTypes.size()); + assertThat(mediaTypes).as("No media types returned").isNotNull(); + assertThat(mediaTypes.size()).as("Invalid amount of media types").isEqualTo(0); } @Test @@ -171,11 +168,11 @@ public class MediaTypeTests { MediaType audioBasic07 = new MediaType("audio", "basic", 0.7); // equal - assertEquals("Invalid comparison result", 0, audioBasic.compareTo(audioBasic)); - assertEquals("Invalid comparison result", 0, audio.compareTo(audio)); - assertEquals("Invalid comparison result", 0, audioBasicLevel.compareTo(audioBasicLevel)); + assertThat(audioBasic.compareTo(audioBasic)).as("Invalid comparison result").isEqualTo(0); + assertThat(audio.compareTo(audio)).as("Invalid comparison result").isEqualTo(0); + assertThat(audioBasicLevel.compareTo(audioBasicLevel)).as("Invalid comparison result").isEqualTo(0); - assertTrue("Invalid comparison result", audioBasicLevel.compareTo(audio) > 0); + assertThat(audioBasicLevel.compareTo(audio) > 0).as("Invalid comparison result").isTrue(); List expected = new ArrayList<>(); expected.add(audio); @@ -192,7 +189,7 @@ public class MediaTypeTests { Collections.sort(result); for (int j = 0; j < result.size(); j++) { - assertSame("Invalid media type at " + j + ", run " + i, expected.get(j), result.get(j)); + assertThat(result.get(j)).as("Invalid media type at " + j + ", run " + i).isSameAs(expected.get(j)); } } } @@ -202,33 +199,33 @@ public class MediaTypeTests { MediaType m1 = MediaType.parseMediaType("text/html; q=0.7; charset=iso-8859-1"); MediaType m2 = MediaType.parseMediaType("text/html; charset=iso-8859-1; q=0.7"); - assertEquals("Media types not equal", m1, m2); - assertEquals("compareTo() not consistent with equals", 0, m1.compareTo(m2)); - assertEquals("compareTo() not consistent with equals", 0, m2.compareTo(m1)); + assertThat(m2).as("Media types not equal").isEqualTo(m1); + assertThat(m1.compareTo(m2)).as("compareTo() not consistent with equals").isEqualTo(0); + assertThat(m2.compareTo(m1)).as("compareTo() not consistent with equals").isEqualTo(0); m1 = MediaType.parseMediaType("text/html; q=0.7; charset=iso-8859-1"); m2 = MediaType.parseMediaType("text/html; Q=0.7; charset=iso-8859-1"); - assertEquals("Media types not equal", m1, m2); - assertEquals("compareTo() not consistent with equals", 0, m1.compareTo(m2)); - assertEquals("compareTo() not consistent with equals", 0, m2.compareTo(m1)); + assertThat(m2).as("Media types not equal").isEqualTo(m1); + assertThat(m1.compareTo(m2)).as("compareTo() not consistent with equals").isEqualTo(0); + assertThat(m2.compareTo(m1)).as("compareTo() not consistent with equals").isEqualTo(0); } @Test public void compareToCaseSensitivity() { MediaType m1 = new MediaType("audio", "basic"); MediaType m2 = new MediaType("Audio", "Basic"); - assertEquals("Invalid comparison result", 0, m1.compareTo(m2)); - assertEquals("Invalid comparison result", 0, m2.compareTo(m1)); + assertThat(m1.compareTo(m2)).as("Invalid comparison result").isEqualTo(0); + assertThat(m2.compareTo(m1)).as("Invalid comparison result").isEqualTo(0); m1 = new MediaType("audio", "basic", Collections.singletonMap("foo", "bar")); m2 = new MediaType("audio", "basic", Collections.singletonMap("Foo", "bar")); - assertEquals("Invalid comparison result", 0, m1.compareTo(m2)); - assertEquals("Invalid comparison result", 0, m2.compareTo(m1)); + assertThat(m1.compareTo(m2)).as("Invalid comparison result").isEqualTo(0); + assertThat(m2.compareTo(m1)).as("Invalid comparison result").isEqualTo(0); m1 = new MediaType("audio", "basic", Collections.singletonMap("foo", "bar")); m2 = new MediaType("audio", "basic", Collections.singletonMap("foo", "Bar")); - assertTrue("Invalid comparison result", m1.compareTo(m2) != 0); - assertTrue("Invalid comparison result", m2.compareTo(m1) != 0); + assertThat(m1.compareTo(m2) != 0).as("Invalid comparison result").isTrue(); + assertThat(m2.compareTo(m1) != 0).as("Invalid comparison result").isTrue(); } @@ -248,43 +245,43 @@ public class MediaTypeTests { Comparator comp = MediaType.SPECIFICITY_COMPARATOR; // equal - assertEquals("Invalid comparison result", 0, comp.compare(audioBasic,audioBasic)); - assertEquals("Invalid comparison result", 0, comp.compare(audio, audio)); - assertEquals("Invalid comparison result", 0, comp.compare(audio07, audio07)); - assertEquals("Invalid comparison result", 0, comp.compare(audio03, audio03)); - assertEquals("Invalid comparison result", 0, comp.compare(audioBasicLevel, audioBasicLevel)); + assertThat(comp.compare(audioBasic, audioBasic)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(audio, audio)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(audio07, audio07)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(audio03, audio03)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(audioBasicLevel, audioBasicLevel)).as("Invalid comparison result").isEqualTo(0); // specific to unspecific - assertTrue("Invalid comparison result", comp.compare(audioBasic, audio) < 0); - assertTrue("Invalid comparison result", comp.compare(audioBasic, all) < 0); - assertTrue("Invalid comparison result", comp.compare(audio, all) < 0); - assertTrue("Invalid comparison result", comp.compare(MediaType.APPLICATION_XHTML_XML, allXml) < 0); + assertThat(comp.compare(audioBasic, audio) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audioBasic, all) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audio, all) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(MediaType.APPLICATION_XHTML_XML, allXml) < 0).as("Invalid comparison result").isTrue(); // unspecific to specific - assertTrue("Invalid comparison result", comp.compare(audio, audioBasic) > 0); - assertTrue("Invalid comparison result", comp.compare(allXml, MediaType.APPLICATION_XHTML_XML) > 0); - assertTrue("Invalid comparison result", comp.compare(all, audioBasic) > 0); - assertTrue("Invalid comparison result", comp.compare(all, audio) > 0); + assertThat(comp.compare(audio, audioBasic) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(allXml, MediaType.APPLICATION_XHTML_XML) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(all, audioBasic) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(all, audio) > 0).as("Invalid comparison result").isTrue(); // qualifiers - assertTrue("Invalid comparison result", comp.compare(audio, audio07) < 0); - assertTrue("Invalid comparison result", comp.compare(audio07, audio) > 0); - assertTrue("Invalid comparison result", comp.compare(audio07, audio03) < 0); - assertTrue("Invalid comparison result", comp.compare(audio03, audio07) > 0); - assertTrue("Invalid comparison result", comp.compare(audio03, all) < 0); - assertTrue("Invalid comparison result", comp.compare(all, audio03) > 0); + assertThat(comp.compare(audio, audio07) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audio07, audio) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audio07, audio03) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audio03, audio07) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audio03, all) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(all, audio03) > 0).as("Invalid comparison result").isTrue(); // other parameters - assertTrue("Invalid comparison result", comp.compare(audioBasic, audioBasicLevel) > 0); - assertTrue("Invalid comparison result", comp.compare(audioBasicLevel, audioBasic) < 0); + assertThat(comp.compare(audioBasic, audioBasicLevel) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audioBasicLevel, audioBasic) < 0).as("Invalid comparison result").isTrue(); // different types - assertEquals("Invalid comparison result", 0, comp.compare(audioBasic, textHtml)); - assertEquals("Invalid comparison result", 0, comp.compare(textHtml, audioBasic)); + assertThat(comp.compare(audioBasic, textHtml)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(textHtml, audioBasic)).as("Invalid comparison result").isEqualTo(0); // different subtypes - assertEquals("Invalid comparison result", 0, comp.compare(audioBasic, audioWave)); - assertEquals("Invalid comparison result", 0, comp.compare(audioWave, audioBasic)); + assertThat(comp.compare(audioBasic, audioWave)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(audioWave, audioBasic)).as("Invalid comparison result").isEqualTo(0); } @Test @@ -312,7 +309,7 @@ public class MediaTypeTests { MediaType.sortBySpecificity(result); for (int j = 0; j < result.size(); j++) { - assertSame("Invalid media type at " + j, expected.get(j), result.get(j)); + assertThat(result.get(j)).as("Invalid media type at " + j).isSameAs(expected.get(j)); } } } @@ -332,7 +329,7 @@ public class MediaTypeTests { MediaType.sortBySpecificity(result); for (int i = 0; i < result.size(); i++) { - assertSame("Invalid media type at " + i, expected.get(i), result.get(i)); + assertThat(result.get(i)).as("Invalid media type at " + i).isSameAs(expected.get(i)); } } @@ -352,43 +349,43 @@ public class MediaTypeTests { Comparator comp = MediaType.QUALITY_VALUE_COMPARATOR; // equal - assertEquals("Invalid comparison result", 0, comp.compare(audioBasic,audioBasic)); - assertEquals("Invalid comparison result", 0, comp.compare(audio, audio)); - assertEquals("Invalid comparison result", 0, comp.compare(audio07, audio07)); - assertEquals("Invalid comparison result", 0, comp.compare(audio03, audio03)); - assertEquals("Invalid comparison result", 0, comp.compare(audioBasicLevel, audioBasicLevel)); + assertThat(comp.compare(audioBasic, audioBasic)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(audio, audio)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(audio07, audio07)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(audio03, audio03)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(audioBasicLevel, audioBasicLevel)).as("Invalid comparison result").isEqualTo(0); // specific to unspecific - assertTrue("Invalid comparison result", comp.compare(audioBasic, audio) < 0); - assertTrue("Invalid comparison result", comp.compare(audioBasic, all) < 0); - assertTrue("Invalid comparison result", comp.compare(audio, all) < 0); - assertTrue("Invalid comparison result", comp.compare(MediaType.APPLICATION_XHTML_XML, allXml) < 0); + assertThat(comp.compare(audioBasic, audio) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audioBasic, all) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audio, all) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(MediaType.APPLICATION_XHTML_XML, allXml) < 0).as("Invalid comparison result").isTrue(); // unspecific to specific - assertTrue("Invalid comparison result", comp.compare(audio, audioBasic) > 0); - assertTrue("Invalid comparison result", comp.compare(all, audioBasic) > 0); - assertTrue("Invalid comparison result", comp.compare(all, audio) > 0); - assertTrue("Invalid comparison result", comp.compare(allXml, MediaType.APPLICATION_XHTML_XML) > 0); + assertThat(comp.compare(audio, audioBasic) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(all, audioBasic) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(all, audio) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(allXml, MediaType.APPLICATION_XHTML_XML) > 0).as("Invalid comparison result").isTrue(); // qualifiers - assertTrue("Invalid comparison result", comp.compare(audio, audio07) < 0); - assertTrue("Invalid comparison result", comp.compare(audio07, audio) > 0); - assertTrue("Invalid comparison result", comp.compare(audio07, audio03) < 0); - assertTrue("Invalid comparison result", comp.compare(audio03, audio07) > 0); - assertTrue("Invalid comparison result", comp.compare(audio03, all) > 0); - assertTrue("Invalid comparison result", comp.compare(all, audio03) < 0); + assertThat(comp.compare(audio, audio07) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audio07, audio) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audio07, audio03) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audio03, audio07) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audio03, all) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(all, audio03) < 0).as("Invalid comparison result").isTrue(); // other parameters - assertTrue("Invalid comparison result", comp.compare(audioBasic, audioBasicLevel) > 0); - assertTrue("Invalid comparison result", comp.compare(audioBasicLevel, audioBasic) < 0); + assertThat(comp.compare(audioBasic, audioBasicLevel) > 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audioBasicLevel, audioBasic) < 0).as("Invalid comparison result").isTrue(); // different types - assertEquals("Invalid comparison result", 0, comp.compare(audioBasic, textHtml)); - assertEquals("Invalid comparison result", 0, comp.compare(textHtml, audioBasic)); + assertThat(comp.compare(audioBasic, textHtml)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(textHtml, audioBasic)).as("Invalid comparison result").isEqualTo(0); // different subtypes - assertEquals("Invalid comparison result", 0, comp.compare(audioBasic, audioWave)); - assertEquals("Invalid comparison result", 0, comp.compare(audioWave, audioBasic)); + assertThat(comp.compare(audioBasic, audioWave)).as("Invalid comparison result").isEqualTo(0); + assertThat(comp.compare(audioWave, audioBasic)).as("Invalid comparison result").isEqualTo(0); } @Test @@ -416,7 +413,7 @@ public class MediaTypeTests { MediaType.sortByQualityValue(result); for (int j = 0; j < result.size(); j++) { - assertSame("Invalid media type at " + j, expected.get(j), result.get(j)); + assertThat(result.get(j)).as("Invalid media type at " + j).isSameAs(expected.get(j)); } } } @@ -436,23 +433,23 @@ public class MediaTypeTests { MediaType.sortBySpecificity(result); for (int i = 0; i < result.size(); i++) { - assertSame("Invalid media type at " + i, expected.get(i), result.get(i)); + assertThat(result.get(i)).as("Invalid media type at " + i).isSameAs(expected.get(i)); } } @Test public void testWithConversionService() { ConversionService conversionService = new DefaultConversionService(); - assertTrue(conversionService.canConvert(String.class, MediaType.class)); + assertThat(conversionService.canConvert(String.class, MediaType.class)).isTrue(); MediaType mediaType = MediaType.parseMediaType("application/xml"); - assertEquals(mediaType, conversionService.convert("application/xml", MediaType.class)); + assertThat(conversionService.convert("application/xml", MediaType.class)).isEqualTo(mediaType); } @Test public void isConcrete() { - assertTrue("text/plain not concrete", MediaType.TEXT_PLAIN.isConcrete()); - assertFalse("*/* concrete", MediaType.ALL.isConcrete()); - assertFalse("text/* concrete", new MediaType("text", "*").isConcrete()); + assertThat(MediaType.TEXT_PLAIN.isConcrete()).as("text/plain not concrete").isTrue(); + assertThat(MediaType.ALL.isConcrete()).as("*/* concrete").isFalse(); + assertThat(new MediaType("text", "*").isConcrete()).as("text/* concrete").isFalse(); } } diff --git a/spring-web/src/test/java/org/springframework/http/RequestEntityTests.java b/spring-web/src/test/java/org/springframework/http/RequestEntityTests.java index 03f59303f21..cc058dab6f9 100644 --- a/spring-web/src/test/java/org/springframework/http/RequestEntityTests.java +++ b/spring-web/src/test/java/org/springframework/http/RequestEntityTests.java @@ -29,10 +29,7 @@ import org.junit.Test; import org.springframework.core.ParameterizedTypeReference; import org.springframework.web.util.UriTemplate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link org.springframework.http.RequestEntity}. @@ -52,11 +49,11 @@ public class RequestEntityTests { RequestEntity.method(HttpMethod.GET, url) .header(headerName, headerValue).body(entity); - assertNotNull(requestEntity); - assertEquals(HttpMethod.GET, requestEntity.getMethod()); - assertTrue(requestEntity.getHeaders().containsKey(headerName)); - assertEquals(headerValue, requestEntity.getHeaders().getFirst(headerName)); - assertEquals(entity, requestEntity.getBody()); + assertThat(requestEntity).isNotNull(); + assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.GET); + assertThat(requestEntity.getHeaders().containsKey(headerName)).isTrue(); + assertThat(requestEntity.getHeaders().getFirst(headerName)).isEqualTo(headerValue); + assertThat(requestEntity.getBody()).isEqualTo(entity); } @Test @@ -71,7 +68,7 @@ public class RequestEntityTests { uri = new UriTemplate(url).expand(host, path); RequestEntity entity = RequestEntity.get(uri).build(); - assertEquals(expected, entity.getUrl()); + assertThat(entity.getUrl()).isEqualTo(expected); Map uriVariables = new HashMap<>(2); uriVariables.put("host", host); @@ -79,7 +76,7 @@ public class RequestEntityTests { uri = new UriTemplate(url).expand(uriVariables); entity = RequestEntity.get(uri).build(); - assertEquals(expected, entity.getUrl()); + assertThat(entity.getUrl()).isEqualTo(expected); } @Test @@ -87,11 +84,11 @@ public class RequestEntityTests { RequestEntity requestEntity = RequestEntity.get(URI.create("https://example.com")).accept( MediaType.IMAGE_GIF, MediaType.IMAGE_JPEG, MediaType.IMAGE_PNG).build(); - assertNotNull(requestEntity); - assertEquals(HttpMethod.GET, requestEntity.getMethod()); - assertTrue(requestEntity.getHeaders().containsKey("Accept")); - assertEquals("image/gif, image/jpeg, image/png", requestEntity.getHeaders().getFirst("Accept")); - assertNull(requestEntity.getBody()); + assertThat(requestEntity).isNotNull(); + assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.GET); + assertThat(requestEntity.getHeaders().containsKey("Accept")).isTrue(); + assertThat(requestEntity.getHeaders().getFirst("Accept")).isEqualTo("image/gif, image/jpeg, image/png"); + assertThat(requestEntity.getBody()).isNull(); } @Test @@ -111,19 +108,19 @@ public class RequestEntityTests { contentType(contentType). build(); - assertNotNull(responseEntity); - assertEquals(HttpMethod.POST, responseEntity.getMethod()); - assertEquals(new URI("https://example.com"), responseEntity.getUrl()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getMethod()).isEqualTo(HttpMethod.POST); + assertThat(responseEntity.getUrl()).isEqualTo(new URI("https://example.com")); HttpHeaders responseHeaders = responseEntity.getHeaders(); - assertEquals("text/plain", responseHeaders.getFirst("Accept")); - assertEquals("utf-8", responseHeaders.getFirst("Accept-Charset")); - assertEquals("Thu, 01 Jan 1970 00:00:12 GMT", responseHeaders.getFirst("If-Modified-Since")); - assertEquals(ifNoneMatch, responseHeaders.getFirst("If-None-Match")); - assertEquals(String.valueOf(contentLength), responseHeaders.getFirst("Content-Length")); - assertEquals(contentType.toString(), responseHeaders.getFirst("Content-Type")); + assertThat(responseHeaders.getFirst("Accept")).isEqualTo("text/plain"); + assertThat(responseHeaders.getFirst("Accept-Charset")).isEqualTo("utf-8"); + assertThat(responseHeaders.getFirst("If-Modified-Since")).isEqualTo("Thu, 01 Jan 1970 00:00:12 GMT"); + assertThat(responseHeaders.getFirst("If-None-Match")).isEqualTo(ifNoneMatch); + assertThat(responseHeaders.getFirst("Content-Length")).isEqualTo(String.valueOf(contentLength)); + assertThat(responseHeaders.getFirst("Content-Type")).isEqualTo(contentType.toString()); - assertNull(responseEntity.getBody()); + assertThat(responseEntity.getBody()).isNull(); } @Test @@ -131,25 +128,25 @@ public class RequestEntityTests { URI url = new URI("https://example.com"); RequestEntity entity = RequestEntity.get(url).build(); - assertEquals(HttpMethod.GET, entity.getMethod()); + assertThat(entity.getMethod()).isEqualTo(HttpMethod.GET); entity = RequestEntity.post(url).build(); - assertEquals(HttpMethod.POST, entity.getMethod()); + assertThat(entity.getMethod()).isEqualTo(HttpMethod.POST); entity = RequestEntity.head(url).build(); - assertEquals(HttpMethod.HEAD, entity.getMethod()); + assertThat(entity.getMethod()).isEqualTo(HttpMethod.HEAD); entity = RequestEntity.options(url).build(); - assertEquals(HttpMethod.OPTIONS, entity.getMethod()); + assertThat(entity.getMethod()).isEqualTo(HttpMethod.OPTIONS); entity = RequestEntity.put(url).build(); - assertEquals(HttpMethod.PUT, entity.getMethod()); + assertThat(entity.getMethod()).isEqualTo(HttpMethod.PUT); entity = RequestEntity.patch(url).build(); - assertEquals(HttpMethod.PATCH, entity.getMethod()); + assertThat(entity.getMethod()).isEqualTo(HttpMethod.PATCH); entity = RequestEntity.delete(url).build(); - assertEquals(HttpMethod.DELETE, entity.getMethod()); + assertThat(entity.getMethod()).isEqualTo(HttpMethod.DELETE); } @@ -160,7 +157,7 @@ public class RequestEntityTests { ParameterizedTypeReference typeReference = new ParameterizedTypeReference>() {}; RequestEntity entity = RequestEntity.post(url).body(body, typeReference.getType()); - assertEquals(typeReference.getType(), entity.getType()); + assertThat(entity.getType()).isEqualTo(typeReference.getType()); } } diff --git a/spring-web/src/test/java/org/springframework/http/ResponseCookieTests.java b/spring-web/src/test/java/org/springframework/http/ResponseCookieTests.java index 4a8d7b70227..1eaf88bfc8a 100644 --- a/spring-web/src/test/java/org/springframework/http/ResponseCookieTests.java +++ b/spring-web/src/test/java/org/springframework/http/ResponseCookieTests.java @@ -21,7 +21,6 @@ import java.time.Duration; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link ResponseCookie}. @@ -31,14 +30,13 @@ public class ResponseCookieTests { @Test public void defaultValues() { - assertEquals("id=1fWa", ResponseCookie.from("id", "1fWa").build().toString()); + assertThat(ResponseCookie.from("id", "1fWa").build().toString()).isEqualTo("id=1fWa"); } @Test public void httpOnlyStrictSecureWithDomainAndPath() { - assertEquals("id=1fWa; Path=/projects; Domain=spring.io; Secure; HttpOnly; SameSite=strict", - ResponseCookie.from("id", "1fWa").domain("spring.io").path("/projects") - .httpOnly(true).secure(true).sameSite("strict").build().toString()); + assertThat(ResponseCookie.from("id", "1fWa").domain("spring.io").path("/projects") + .httpOnly(true).secure(true).sameSite("strict").build().toString()).isEqualTo("id=1fWa; Path=/projects; Domain=spring.io; Secure; HttpOnly; SameSite=strict"); } @Test @@ -59,11 +57,9 @@ public class ResponseCookieTests { @Test public void maxAge0() { - assertEquals("id=1fWa; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT", - ResponseCookie.from("id", "1fWa").maxAge(Duration.ofSeconds(0)).build().toString()); + assertThat(ResponseCookie.from("id", "1fWa").maxAge(Duration.ofSeconds(0)).build().toString()).isEqualTo("id=1fWa; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT"); - assertEquals("id=1fWa; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT", - ResponseCookie.from("id", "1fWa").maxAge(0).build().toString()); + assertThat(ResponseCookie.from("id", "1fWa").maxAge(0).build().toString()).isEqualTo("id=1fWa; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT"); } } diff --git a/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java b/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java index 905fcd5d70f..fbf36362fa0 100644 --- a/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java +++ b/spring-web/src/test/java/org/springframework/http/ResponseEntityTests.java @@ -25,11 +25,6 @@ import java.util.concurrent.TimeUnit; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Arjen Poutsma @@ -48,23 +43,23 @@ public class ResponseEntityTests { ResponseEntity responseEntity = ResponseEntity.status(HttpStatus.OK).header(headerName, headerValue1, headerValue2).body(entity); - assertNotNull(responseEntity); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertTrue(responseEntity.getHeaders().containsKey(headerName)); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(responseEntity.getHeaders().containsKey(headerName)).isTrue(); List list = responseEntity.getHeaders().get(headerName); - assertEquals(2, list.size()); - assertEquals(headerValue1, list.get(0)); - assertEquals(headerValue2, list.get(1)); - assertEquals(entity, responseEntity.getBody()); + assertThat(list.size()).isEqualTo(2); + assertThat(list.get(0)).isEqualTo(headerValue1); + assertThat(list.get(1)).isEqualTo(headerValue2); + assertThat((int) responseEntity.getBody()).isEqualTo((int) entity); } @Test public void okNoBody() { ResponseEntity responseEntity = ResponseEntity.ok().build(); - assertNotNull(responseEntity); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertNull(responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(responseEntity.getBody()).isNull(); } @Test @@ -72,9 +67,9 @@ public class ResponseEntityTests { Integer entity = 42; ResponseEntity responseEntity = ResponseEntity.ok(entity); - assertNotNull(responseEntity); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertEquals(entity, responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat((int) responseEntity.getBody()).isEqualTo((int) entity); } @Test @@ -82,18 +77,18 @@ public class ResponseEntityTests { Integer entity = 42; ResponseEntity responseEntity = ResponseEntity.of(Optional.of(entity)); - assertNotNull(responseEntity); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertEquals(entity, responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat((int) responseEntity.getBody()).isEqualTo((int) entity); } @Test public void ofEmptyOptional() { ResponseEntity responseEntity = ResponseEntity.of(Optional.empty()); - assertNotNull(responseEntity); - assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - assertNull(responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(responseEntity.getBody()).isNull(); } @Test @@ -101,12 +96,11 @@ public class ResponseEntityTests { URI location = new URI("location"); ResponseEntity responseEntity = ResponseEntity.created(location).build(); - assertNotNull(responseEntity); - assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); - assertTrue(responseEntity.getHeaders().containsKey("Location")); - assertEquals(location.toString(), - responseEntity.getHeaders().getFirst("Location")); - assertNull(responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED); + assertThat(responseEntity.getHeaders().containsKey("Location")).isTrue(); + assertThat(responseEntity.getHeaders().getFirst("Location")).isEqualTo(location.toString()); + assertThat(responseEntity.getBody()).isNull(); ResponseEntity.created(location).header("MyResponseHeader", "MyValue").body("Hello World"); } @@ -115,54 +109,54 @@ public class ResponseEntityTests { public void acceptedNoBody() throws URISyntaxException { ResponseEntity responseEntity = ResponseEntity.accepted().build(); - assertNotNull(responseEntity); - assertEquals(HttpStatus.ACCEPTED, responseEntity.getStatusCode()); - assertNull(responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED); + assertThat(responseEntity.getBody()).isNull(); } @Test // SPR-14939 public void acceptedNoBodyWithAlternativeBodyType() throws URISyntaxException { ResponseEntity responseEntity = ResponseEntity.accepted().build(); - assertNotNull(responseEntity); - assertEquals(HttpStatus.ACCEPTED, responseEntity.getStatusCode()); - assertNull(responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED); + assertThat(responseEntity.getBody()).isNull(); } @Test public void noContent() throws URISyntaxException { ResponseEntity responseEntity = ResponseEntity.noContent().build(); - assertNotNull(responseEntity); - assertEquals(HttpStatus.NO_CONTENT, responseEntity.getStatusCode()); - assertNull(responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); + assertThat(responseEntity.getBody()).isNull(); } @Test public void badRequest() throws URISyntaxException { ResponseEntity responseEntity = ResponseEntity.badRequest().build(); - assertNotNull(responseEntity); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - assertNull(responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(responseEntity.getBody()).isNull(); } @Test public void notFound() throws URISyntaxException { ResponseEntity responseEntity = ResponseEntity.notFound().build(); - assertNotNull(responseEntity); - assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - assertNull(responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(responseEntity.getBody()).isNull(); } @Test public void unprocessableEntity() throws URISyntaxException { ResponseEntity responseEntity = ResponseEntity.unprocessableEntity().body("error"); - assertNotNull(responseEntity); - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, responseEntity.getStatusCode()); - assertEquals("error", responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY); + assertThat(responseEntity.getBody()).isEqualTo("error"); } @Test @@ -179,32 +173,30 @@ public class ResponseEntityTests { contentType(contentType). build(); - assertNotNull(responseEntity); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); HttpHeaders responseHeaders = responseEntity.getHeaders(); - assertEquals("GET", responseHeaders.getFirst("Allow")); - assertEquals("Thu, 01 Jan 1970 00:00:12 GMT", - responseHeaders.getFirst("Last-Modified")); - assertEquals(location.toASCIIString(), - responseHeaders.getFirst("Location")); - assertEquals(String.valueOf(contentLength), responseHeaders.getFirst("Content-Length")); - assertEquals(contentType.toString(), responseHeaders.getFirst("Content-Type")); + assertThat(responseHeaders.getFirst("Allow")).isEqualTo("GET"); + assertThat(responseHeaders.getFirst("Last-Modified")).isEqualTo("Thu, 01 Jan 1970 00:00:12 GMT"); + assertThat(responseHeaders.getFirst("Location")).isEqualTo(location.toASCIIString()); + assertThat(responseHeaders.getFirst("Content-Length")).isEqualTo(String.valueOf(contentLength)); + assertThat(responseHeaders.getFirst("Content-Type")).isEqualTo(contentType.toString()); - assertNull(responseEntity.getBody()); + assertThat((Object) responseEntity.getBody()).isNull(); } @Test public void Etagheader() throws URISyntaxException { ResponseEntity responseEntity = ResponseEntity.ok().eTag("\"foo\"").build(); - assertEquals("\"foo\"", responseEntity.getHeaders().getETag()); + assertThat(responseEntity.getHeaders().getETag()).isEqualTo("\"foo\""); responseEntity = ResponseEntity.ok().eTag("foo").build(); - assertEquals("\"foo\"", responseEntity.getHeaders().getETag()); + assertThat(responseEntity.getHeaders().getETag()).isEqualTo("\"foo\""); responseEntity = ResponseEntity.ok().eTag("W/\"foo\"").build(); - assertEquals("W/\"foo\"", responseEntity.getHeaders().getETag()); + assertThat(responseEntity.getHeaders().getETag()).isEqualTo("W/\"foo\""); } @Test @@ -215,10 +207,10 @@ public class ResponseEntityTests { ResponseEntity responseEntity = ResponseEntity.ok().headers(customHeaders).build(); HttpHeaders responseHeaders = responseEntity.getHeaders(); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertEquals(1, responseHeaders.size()); - assertEquals(1, responseHeaders.get("X-CustomHeader").size()); - assertEquals("vale", responseHeaders.getFirst("X-CustomHeader")); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(responseHeaders.size()).isEqualTo(1); + assertThat(responseHeaders.get("X-CustomHeader").size()).isEqualTo(1); + assertThat(responseHeaders.getFirst("X-CustomHeader")).isEqualTo("vale"); } @@ -229,9 +221,9 @@ public class ResponseEntityTests { ResponseEntity responseEntityWithNullHeaders = ResponseEntity.ok().headers(null).build(); - assertEquals(HttpStatus.OK, responseEntityWithEmptyHeaders.getStatusCode()); - assertTrue(responseEntityWithEmptyHeaders.getHeaders().isEmpty()); - assertEquals(responseEntityWithEmptyHeaders.toString(), responseEntityWithNullHeaders.toString()); + assertThat(responseEntityWithEmptyHeaders.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(responseEntityWithEmptyHeaders.getHeaders().isEmpty()).isTrue(); + assertThat(responseEntityWithNullHeaders.toString()).isEqualTo(responseEntityWithEmptyHeaders.toString()); } @Test @@ -243,10 +235,10 @@ public class ResponseEntityTests { .cacheControl(CacheControl.empty()) .body(entity); - assertNotNull(responseEntity); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertFalse(responseEntity.getHeaders().containsKey(HttpHeaders.CACHE_CONTROL)); - assertEquals(entity, responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(responseEntity.getHeaders().containsKey(HttpHeaders.CACHE_CONTROL)).isFalse(); + assertThat((int) responseEntity.getBody()).isEqualTo((int) entity); } @Test @@ -259,10 +251,10 @@ public class ResponseEntityTests { mustRevalidate().proxyRevalidate().sMaxAge(30, TimeUnit.MINUTES)) .body(entity); - assertNotNull(responseEntity); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertTrue(responseEntity.getHeaders().containsKey(HttpHeaders.CACHE_CONTROL)); - assertEquals(entity, responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(responseEntity.getHeaders().containsKey(HttpHeaders.CACHE_CONTROL)).isTrue(); + assertThat((int) responseEntity.getBody()).isEqualTo((int) entity); String cacheControlHeader = responseEntity.getHeaders().getCacheControl(); assertThat(cacheControlHeader).isEqualTo( "max-age=3600, must-revalidate, private, proxy-revalidate, s-maxage=1800"); @@ -277,10 +269,10 @@ public class ResponseEntityTests { .cacheControl(CacheControl.noStore()) .body(entity); - assertNotNull(responseEntity); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertTrue(responseEntity.getHeaders().containsKey(HttpHeaders.CACHE_CONTROL)); - assertEquals(entity, responseEntity.getBody()); + assertThat(responseEntity).isNotNull(); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(responseEntity.getHeaders().containsKey(HttpHeaders.CACHE_CONTROL)).isTrue(); + assertThat((int) responseEntity.getBody()).isEqualTo((int) entity); String cacheControlHeader = responseEntity.getHeaders().getCacheControl(); assertThat(cacheControlHeader).isEqualTo("no-store"); @@ -291,8 +283,8 @@ public class ResponseEntityTests { Integer entity = 42; ResponseEntity responseEntity = ResponseEntity.status(200).body(entity); - assertEquals(200, responseEntity.getStatusCode().value()); - assertEquals(entity, responseEntity.getBody()); + assertThat(responseEntity.getStatusCode().value()).isEqualTo(200); + assertThat((int) responseEntity.getBody()).isEqualTo((int) entity); } @Test @@ -300,8 +292,8 @@ public class ResponseEntityTests { Integer entity = 42; ResponseEntity responseEntity = ResponseEntity.status(299).body(entity); - assertEquals(299, responseEntity.getStatusCodeValue()); - assertEquals(entity, responseEntity.getBody()); + assertThat(responseEntity.getStatusCodeValue()).isEqualTo(299); + assertThat((int) responseEntity.getBody()).isEqualTo((int) entity); } } diff --git a/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java b/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java index bd9e2a32d3d..4039ccbda61 100644 --- a/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java +++ b/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java @@ -36,10 +36,9 @@ import org.springframework.util.StreamUtils; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; @SuppressWarnings("deprecation") public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMockWebServerTestCase { @@ -69,12 +68,12 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo public void status() throws Exception { URI uri = new URI(baseUrl + "/status/notfound"); AsyncClientHttpRequest request = this.factory.createAsyncRequest(uri, HttpMethod.GET); - assertEquals("Invalid HTTP method", HttpMethod.GET, request.getMethod()); - assertEquals("Invalid HTTP URI", uri, request.getURI()); + assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.GET); + assertThat(request.getURI()).as("Invalid HTTP URI").isEqualTo(uri); Future futureResponse = request.executeAsync(); ClientHttpResponse response = futureResponse.get(); try { - assertEquals("Invalid status code", HttpStatus.NOT_FOUND, response.getStatusCode()); + assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.NOT_FOUND); } finally { response.close(); @@ -85,14 +84,14 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo public void statusCallback() throws Exception { URI uri = new URI(baseUrl + "/status/notfound"); AsyncClientHttpRequest request = this.factory.createAsyncRequest(uri, HttpMethod.GET); - assertEquals("Invalid HTTP method", HttpMethod.GET, request.getMethod()); - assertEquals("Invalid HTTP URI", uri, request.getURI()); + assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.GET); + assertThat(request.getURI()).as("Invalid HTTP URI").isEqualTo(uri); ListenableFuture listenableFuture = request.executeAsync(); listenableFuture.addCallback(new ListenableFutureCallback() { @Override public void onSuccess(ClientHttpResponse result) { try { - assertEquals("Invalid status code", HttpStatus.NOT_FOUND, result.getStatusCode()); + assertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.NOT_FOUND); } catch (IOException ex) { throw new AssertionError(ex.getMessage(), ex); @@ -105,7 +104,7 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo }); ClientHttpResponse response = listenableFuture.get(); try { - assertEquals("Invalid status code", HttpStatus.NOT_FOUND, response.getStatusCode()); + assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.NOT_FOUND); } finally { response.close(); @@ -115,7 +114,7 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo @Test public void echo() throws Exception { AsyncClientHttpRequest request = this.factory.createAsyncRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT); - assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod()); + assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.PUT); String headerName = "MyHeader"; String headerValue1 = "value1"; request.getHeaders().add(headerName, headerValue1); @@ -135,12 +134,11 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo Future futureResponse = request.executeAsync(); ClientHttpResponse response = futureResponse.get(); try { - assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); - assertTrue("Header not found", response.getHeaders().containsKey(headerName)); - assertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2), - response.getHeaders().get(headerName)); + assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().containsKey(headerName)).as("Header not found").isTrue(); + assertThat(response.getHeaders().get(headerName)).as("Header value not found").isEqualTo(Arrays.asList(headerValue1, headerValue2)); byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); - assertTrue("Invalid body", Arrays.equals(body, result)); + assertThat(Arrays.equals(body, result)).as("Invalid body").isTrue(); } finally { response.close(); @@ -209,8 +207,8 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo } Future futureResponse = request.executeAsync(); response = futureResponse.get(); - assertEquals("Invalid response status", HttpStatus.OK, response.getStatusCode()); - assertEquals("Invalid method", path.toUpperCase(Locale.ENGLISH), request.getMethod().name()); + assertThat(response.getStatusCode()).as("Invalid response status").isEqualTo(HttpStatus.OK); + assertThat(request.getMethod().name()).as("Invalid method").isEqualTo(path.toUpperCase(Locale.ENGLISH)); } finally { if (response != null) { @@ -225,7 +223,7 @@ public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractMo AsyncClientHttpRequest request = this.factory.createAsyncRequest(uri, HttpMethod.GET); Future futureResponse = request.executeAsync(); futureResponse.cancel(true); - assertTrue(futureResponse.isCancelled()); + assertThat(futureResponse.isCancelled()).isTrue(); } diff --git a/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java b/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java index 1b13571779d..21a5931d557 100644 --- a/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java +++ b/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java @@ -33,11 +33,9 @@ import org.springframework.http.StreamingHttpOutputMessage; import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Arjen Poutsma @@ -70,18 +68,18 @@ public abstract class AbstractHttpRequestFactoryTestCase extends AbstractMockWeb public void status() throws Exception { URI uri = new URI(baseUrl + "/status/notfound"); ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET); - assertEquals("Invalid HTTP method", HttpMethod.GET, request.getMethod()); - assertEquals("Invalid HTTP URI", uri, request.getURI()); + assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.GET); + assertThat(request.getURI()).as("Invalid HTTP URI").isEqualTo(uri); try (ClientHttpResponse response = request.execute()) { - assertEquals("Invalid status code", HttpStatus.NOT_FOUND, response.getStatusCode()); + assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.NOT_FOUND); } } @Test public void echo() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT); - assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod()); + assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.PUT); String headerName = "MyHeader"; String headerValue1 = "value1"; @@ -100,12 +98,11 @@ public abstract class AbstractHttpRequestFactoryTestCase extends AbstractMockWeb } try (ClientHttpResponse response = request.execute()) { - assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); - assertTrue("Header not found", response.getHeaders().containsKey(headerName)); - assertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2), - response.getHeaders().get(headerName)); + assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().containsKey(headerName)).as("Header not found").isTrue(); + assertThat(response.getHeaders().get(headerName)).as("Header value not found").isEqualTo(Arrays.asList(headerValue1, headerValue2)); byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); - assertArrayEquals("Invalid body", body, result); + assertThat(Arrays.equals(body, result)).as("Invalid body").isTrue(); } } @@ -170,8 +167,8 @@ public abstract class AbstractHttpRequestFactoryTestCase extends AbstractMockWeb } } response = request.execute(); - assertEquals("Invalid response status", HttpStatus.OK, response.getStatusCode()); - assertEquals("Invalid method", path.toUpperCase(Locale.ENGLISH), request.getMethod().name()); + assertThat(response.getStatusCode()).as("Invalid response status").isEqualTo(HttpStatus.OK); + assertThat(request.getMethod().name()).as("Invalid method").isEqualTo(path.toUpperCase(Locale.ENGLISH)); } finally { if (response != null) { @@ -186,7 +183,7 @@ public abstract class AbstractHttpRequestFactoryTestCase extends AbstractMockWeb ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET); try (ClientHttpResponse response = request.execute()) { - assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); } } diff --git a/spring-web/src/test/java/org/springframework/http/client/BufferedSimpleHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/BufferedSimpleHttpRequestFactoryTests.java index 8c238dc0d27..97dd5f73684 100644 --- a/spring-web/src/test/java/org/springframework/http/client/BufferedSimpleHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/BufferedSimpleHttpRequestFactoryTests.java @@ -27,7 +27,7 @@ import org.junit.Test; import org.springframework.http.HttpMethod; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class BufferedSimpleHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase { @@ -70,7 +70,7 @@ public class BufferedSimpleHttpRequestFactoryTests extends AbstractHttpRequestFa private void testRequestBodyAllowed(URL uri, String httpMethod, boolean allowed) throws IOException { HttpURLConnection connection = new TestHttpURLConnection(uri); ((SimpleClientHttpRequestFactory) this.factory).prepareConnection(connection, httpMethod); - assertEquals(allowed, connection.getDoOutput()); + assertThat(connection.getDoOutput()).isEqualTo(allowed); } diff --git a/spring-web/src/test/java/org/springframework/http/client/BufferingClientHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/BufferingClientHttpRequestFactoryTests.java index 1aabe95fc15..309283a1c97 100644 --- a/spring-web/src/test/java/org/springframework/http/client/BufferingClientHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/BufferingClientHttpRequestFactoryTests.java @@ -25,8 +25,7 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.util.FileCopyUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class BufferingClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase { @@ -38,7 +37,7 @@ public class BufferingClientHttpRequestFactoryTests extends AbstractHttpRequestF @Test public void repeatableRead() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT); - assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod()); + assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.PUT); String headerName = "MyHeader"; String headerValue1 = "value1"; request.getHeaders().add(headerName, headerValue1); @@ -49,21 +48,19 @@ public class BufferingClientHttpRequestFactoryTests extends AbstractHttpRequestF FileCopyUtils.copy(body, request.getBody()); ClientHttpResponse response = request.execute(); try { - assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); - assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); + assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); - assertTrue("Header not found", response.getHeaders().containsKey(headerName)); - assertTrue("Header not found", response.getHeaders().containsKey(headerName)); + assertThat(response.getHeaders().containsKey(headerName)).as("Header not found").isTrue(); + assertThat(response.getHeaders().containsKey(headerName)).as("Header not found").isTrue(); - assertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2), - response.getHeaders().get(headerName)); - assertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2), - response.getHeaders().get(headerName)); + assertThat(response.getHeaders().get(headerName)).as("Header value not found").isEqualTo(Arrays.asList(headerValue1, headerValue2)); + assertThat(response.getHeaders().get(headerName)).as("Header value not found").isEqualTo(Arrays.asList(headerValue1, headerValue2)); byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); - assertTrue("Invalid body", Arrays.equals(body, result)); + assertThat(Arrays.equals(body, result)).as("Invalid body").isTrue(); FileCopyUtils.copyToByteArray(response.getBody()); - assertTrue("Invalid body", Arrays.equals(body, result)); + assertThat(Arrays.equals(body, result)).as("Invalid body").isTrue(); } finally { response.close(); diff --git a/spring-web/src/test/java/org/springframework/http/client/HttpComponentsAsyncClientHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/HttpComponentsAsyncClientHttpRequestFactoryTests.java index 747920bca4e..fddded68fbb 100644 --- a/spring-web/src/test/java/org/springframework/http/client/HttpComponentsAsyncClientHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/HttpComponentsAsyncClientHttpRequestFactoryTests.java @@ -26,9 +26,7 @@ import org.junit.Test; import org.springframework.http.HttpMethod; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -59,8 +57,7 @@ public class HttpComponentsAsyncClientHttpRequestFactoryTests extends AbstractAs HttpComponentsAsyncClientHttpRequest request = (HttpComponentsAsyncClientHttpRequest) factory.createAsyncRequest(uri, HttpMethod.GET); - assertNull("No custom config should be set with a custom HttpAsyncClient", - request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG)); + assertThat(request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG)).as("No custom config should be set with a custom HttpAsyncClient").isNull(); } @Test @@ -74,19 +71,18 @@ public class HttpComponentsAsyncClientHttpRequestFactoryTests extends AbstractAs HttpComponentsAsyncClientHttpRequest request = (HttpComponentsAsyncClientHttpRequest) factory.createAsyncRequest(uri, HttpMethod.GET); - assertNull("No custom config should be set with a custom HttpClient", - request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG)); + assertThat(request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG)).as("No custom config should be set with a custom HttpClient").isNull(); factory.setConnectionRequestTimeout(4567); HttpComponentsAsyncClientHttpRequest request2 = (HttpComponentsAsyncClientHttpRequest) factory.createAsyncRequest(uri, HttpMethod.GET); Object requestConfigAttribute = request2.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG); - assertNotNull(requestConfigAttribute); + assertThat(requestConfigAttribute).isNotNull(); RequestConfig requestConfig = (RequestConfig) requestConfigAttribute; - assertEquals(4567, requestConfig.getConnectionRequestTimeout()); + assertThat(requestConfig.getConnectionRequestTimeout()).isEqualTo(4567); // No way to access the request config of the HTTP client so no way to "merge" our customizations - assertEquals(-1, requestConfig.getConnectTimeout()); + assertThat(requestConfig.getConnectTimeout()).isEqualTo(-1); } } diff --git a/spring-web/src/test/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactoryTests.java index d6e72978986..458d8b30f7e 100644 --- a/spring-web/src/test/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactoryTests.java @@ -30,10 +30,7 @@ import org.junit.Test; import org.springframework.http.HttpMethod; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings; @@ -68,13 +65,12 @@ public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpReq hrf.createRequest(uri, HttpMethod.GET); Object config = request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG); - assertNotNull("Request config should be set", config); - assertTrue("Wrong request config type" + config.getClass().getName(), - RequestConfig.class.isInstance(config)); + assertThat(config).as("Request config should be set").isNotNull(); + assertThat(RequestConfig.class.isInstance(config)).as("Wrong request config type" + config.getClass().getName()).isTrue(); RequestConfig requestConfig = (RequestConfig) config; - assertEquals("Wrong custom connection timeout", 1234, requestConfig.getConnectTimeout()); - assertEquals("Wrong custom connection request timeout", 4321, requestConfig.getConnectionRequestTimeout()); - assertEquals("Wrong custom socket timeout", 4567, requestConfig.getSocketTimeout()); + assertThat(requestConfig.getConnectTimeout()).as("Wrong custom connection timeout").isEqualTo(1234); + assertThat(requestConfig.getConnectionRequestTimeout()).as("Wrong custom connection request timeout").isEqualTo(4321); + assertThat(requestConfig.getSocketTimeout()).as("Wrong custom socket timeout").isEqualTo(4567); } @Test @@ -86,14 +82,14 @@ public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpReq given(configurable.getConfig()).willReturn(defaultConfig); HttpComponentsClientHttpRequestFactory hrf = new HttpComponentsClientHttpRequestFactory(client); - assertSame("Default client configuration is expected", defaultConfig, retrieveRequestConfig(hrf)); + assertThat(retrieveRequestConfig(hrf)).as("Default client configuration is expected").isSameAs(defaultConfig); hrf.setConnectionRequestTimeout(4567); RequestConfig requestConfig = retrieveRequestConfig(hrf); - assertNotNull(requestConfig); - assertEquals(4567, requestConfig.getConnectionRequestTimeout()); + assertThat(requestConfig).isNotNull(); + assertThat(requestConfig.getConnectionRequestTimeout()).isEqualTo(4567); // Default connection timeout merged - assertEquals(1234, requestConfig.getConnectTimeout()); + assertThat(requestConfig.getConnectTimeout()).isEqualTo(1234); } @Test @@ -109,9 +105,9 @@ public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpReq hrf.setConnectTimeout(5000); RequestConfig requestConfig = retrieveRequestConfig(hrf); - assertEquals(5000, requestConfig.getConnectTimeout()); - assertEquals(6789, requestConfig.getConnectionRequestTimeout()); - assertEquals(-1, requestConfig.getSocketTimeout()); + assertThat(requestConfig.getConnectTimeout()).isEqualTo(5000); + assertThat(requestConfig.getConnectionRequestTimeout()).isEqualTo(6789); + assertThat(requestConfig.getSocketTimeout()).isEqualTo(-1); } @Test @@ -132,9 +128,9 @@ public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpReq hrf.setReadTimeout(5000); RequestConfig requestConfig = retrieveRequestConfig(hrf); - assertEquals(-1, requestConfig.getConnectTimeout()); - assertEquals(-1, requestConfig.getConnectionRequestTimeout()); - assertEquals(5000, requestConfig.getSocketTimeout()); + assertThat(requestConfig.getConnectTimeout()).isEqualTo(-1); + assertThat(requestConfig.getConnectionRequestTimeout()).isEqualTo(-1); + assertThat(requestConfig.getSocketTimeout()).isEqualTo(5000); // Update the Http client so that it returns an updated config RequestConfig updatedDefaultConfig = RequestConfig.custom() @@ -142,9 +138,9 @@ public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpReq given(configurable.getConfig()).willReturn(updatedDefaultConfig); hrf.setReadTimeout(7000); RequestConfig requestConfig2 = retrieveRequestConfig(hrf); - assertEquals(1234, requestConfig2.getConnectTimeout()); - assertEquals(-1, requestConfig2.getConnectionRequestTimeout()); - assertEquals(7000, requestConfig2.getSocketTimeout()); + assertThat(requestConfig2.getConnectTimeout()).isEqualTo(1234); + assertThat(requestConfig2.getConnectionRequestTimeout()).isEqualTo(-1); + assertThat(requestConfig2.getSocketTimeout()).isEqualTo(7000); } private RequestConfig retrieveRequestConfig(HttpComponentsClientHttpRequestFactory factory) throws Exception { @@ -170,7 +166,8 @@ public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpReq private void testRequestBodyAllowed(URI uri, HttpMethod method, boolean allowed) { HttpUriRequest request = ((HttpComponentsClientHttpRequestFactory) this.factory).createHttpUriRequest(method, uri); - assertEquals(allowed, request instanceof HttpEntityEnclosingRequest); + Object actual = request instanceof HttpEntityEnclosingRequest; + assertThat(actual).isEqualTo(allowed); } } diff --git a/spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java index f9e2cbfa82b..5fee92cb947 100644 --- a/spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java @@ -34,10 +34,7 @@ import org.springframework.http.HttpRequest; import org.springframework.http.HttpStatus; import org.springframework.http.client.support.HttpRequestWrapper; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -65,11 +62,11 @@ public class InterceptingClientHttpRequestFactoryTests { ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET); ClientHttpResponse response = request.execute(); - assertTrue(((NoOpInterceptor) interceptors.get(0)).invoked); - assertTrue(((NoOpInterceptor) interceptors.get(1)).invoked); - assertTrue(((NoOpInterceptor) interceptors.get(2)).invoked); - assertTrue(requestMock.executed); - assertSame(responseMock, response); + assertThat(((NoOpInterceptor) interceptors.get(0)).invoked).isTrue(); + assertThat(((NoOpInterceptor) interceptors.get(1)).invoked).isTrue(); + assertThat(((NoOpInterceptor) interceptors.get(2)).invoked).isTrue(); + assertThat(requestMock.executed).isTrue(); + assertThat(response).isSameAs(responseMock); } @Test @@ -89,9 +86,9 @@ public class InterceptingClientHttpRequestFactoryTests { ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET); ClientHttpResponse response = request.execute(); - assertFalse(((NoOpInterceptor) interceptors.get(1)).invoked); - assertFalse(requestMock.executed); - assertSame(responseMock, response); + assertThat(((NoOpInterceptor) interceptors.get(1)).invoked).isFalse(); + assertThat(requestMock.executed).isFalse(); + assertThat(response).isSameAs(responseMock); } @Test @@ -114,9 +111,9 @@ public class InterceptingClientHttpRequestFactoryTests { @Override public ClientHttpResponse execute() throws IOException { List headerValues = getHeaders().get(headerName); - assertEquals(2, headerValues.size()); - assertEquals(headerValue, headerValues.get(0)); - assertEquals(otherValue, headerValues.get(1)); + assertThat(headerValues.size()).isEqualTo(2); + assertThat(headerValues.get(0)).isEqualTo(headerValue); + assertThat(headerValues.get(1)).isEqualTo(otherValue); return super.execute(); } }; @@ -150,7 +147,7 @@ public class InterceptingClientHttpRequestFactoryTests { requestFactoryMock = new RequestFactoryMock() { @Override public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { - assertEquals(changedUri, uri); + assertThat(uri).isEqualTo(changedUri); return super.createRequest(uri, httpMethod); } }; @@ -183,7 +180,7 @@ public class InterceptingClientHttpRequestFactoryTests { requestFactoryMock = new RequestFactoryMock() { @Override public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { - assertEquals(changedMethod, httpMethod); + assertThat(httpMethod).isEqualTo(changedMethod); return super.createRequest(uri, httpMethod); } }; @@ -212,7 +209,7 @@ public class InterceptingClientHttpRequestFactoryTests { ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET); request.execute(); - assertTrue(Arrays.equals(changedBody, requestMock.body.toByteArray())); + assertThat(Arrays.equals(changedBody, requestMock.body.toByteArray())).isTrue(); } diff --git a/spring-web/src/test/java/org/springframework/http/client/MultipartBodyBuilderTests.java b/spring-web/src/test/java/org/springframework/http/client/MultipartBodyBuilderTests.java index 88f5c034592..25ce6f4d5a3 100644 --- a/spring-web/src/test/java/org/springframework/http/client/MultipartBodyBuilderTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/MultipartBodyBuilderTests.java @@ -30,8 +30,7 @@ import org.springframework.http.client.MultipartBodyBuilder.PublisherEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -61,36 +60,34 @@ public class MultipartBodyBuilderTests { MultiValueMap> result = builder.build(); - assertEquals(5, result.size()); + assertThat(result.size()).isEqualTo(5); HttpEntity resultEntity = result.getFirst("key"); - assertNotNull(resultEntity); - assertEquals(multipartData, resultEntity.getBody()); - assertEquals("bar", resultEntity.getHeaders().getFirst("foo")); + assertThat(resultEntity).isNotNull(); + assertThat(resultEntity.getBody()).isEqualTo(multipartData); + assertThat(resultEntity.getHeaders().getFirst("foo")).isEqualTo("bar"); resultEntity = result.getFirst("logo"); - assertNotNull(resultEntity); - assertEquals(logo, resultEntity.getBody()); - assertEquals("qux", resultEntity.getHeaders().getFirst("baz")); + assertThat(resultEntity).isNotNull(); + assertThat(resultEntity.getBody()).isEqualTo(logo); + assertThat(resultEntity.getHeaders().getFirst("baz")).isEqualTo("qux"); resultEntity = result.getFirst("entity"); - assertNotNull(resultEntity); - assertEquals("body", resultEntity.getBody()); - assertEquals("bar", resultEntity.getHeaders().getFirst("foo")); - assertEquals("qux", resultEntity.getHeaders().getFirst("baz")); + assertThat(resultEntity).isNotNull(); + assertThat(resultEntity.getBody()).isEqualTo("body"); + assertThat(resultEntity.getHeaders().getFirst("foo")).isEqualTo("bar"); + assertThat(resultEntity.getHeaders().getFirst("baz")).isEqualTo("qux"); resultEntity = result.getFirst("publisherClass"); - assertNotNull(resultEntity); - assertEquals(publisher, resultEntity.getBody()); - assertEquals(ResolvableType.forClass(String.class), - ((PublisherEntity) resultEntity).getResolvableType()); - assertEquals("qux", resultEntity.getHeaders().getFirst("baz")); + assertThat(resultEntity).isNotNull(); + assertThat(resultEntity.getBody()).isEqualTo(publisher); + assertThat(((PublisherEntity) resultEntity).getResolvableType()).isEqualTo(ResolvableType.forClass(String.class)); + assertThat(resultEntity.getHeaders().getFirst("baz")).isEqualTo("qux"); resultEntity = result.getFirst("publisherPtr"); - assertNotNull(resultEntity); - assertEquals(publisher, resultEntity.getBody()); - assertEquals(ResolvableType.forClass(String.class), - ((PublisherEntity) resultEntity).getResolvableType()); - assertEquals("qux", resultEntity.getHeaders().getFirst("baz")); + assertThat(resultEntity).isNotNull(); + assertThat(resultEntity.getBody()).isEqualTo(publisher); + assertThat(((PublisherEntity) resultEntity).getResolvableType()).isEqualTo(ResolvableType.forClass(String.class)); + assertThat(resultEntity.getHeaders().getFirst("baz")).isEqualTo("qux"); } @Test // SPR-16601 @@ -101,8 +98,8 @@ public class MultipartBodyBuilderTests { builder.asyncPart("publisherClass", publisher, String.class).header("baz", "qux"); HttpEntity entity = builder.build().getFirst("publisherClass"); - assertNotNull(entity); - assertEquals(PublisherEntity.class, entity.getClass()); + assertThat(entity).isNotNull(); + assertThat(entity.getClass()).isEqualTo(PublisherEntity.class); // Now build a new MultipartBodyBuilder, as BodyInserters.fromMultipartData would do... @@ -110,8 +107,8 @@ public class MultipartBodyBuilderTests { builder.part("publisherClass", entity); entity = builder.build().getFirst("publisherClass"); - assertNotNull(entity); - assertEquals(PublisherEntity.class, entity.getClass()); + assertThat(entity).isNotNull(); + assertThat(entity.getClass()).isEqualTo(PublisherEntity.class); } } diff --git a/spring-web/src/test/java/org/springframework/http/client/SimpleClientHttpResponseTests.java b/spring-web/src/test/java/org/springframework/http/client/SimpleClientHttpResponseTests.java index 9a3ef80f486..2b03dfe1d2a 100644 --- a/spring-web/src/test/java/org/springframework/http/client/SimpleClientHttpResponseTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/SimpleClientHttpResponseTests.java @@ -27,7 +27,6 @@ import org.junit.Test; import org.springframework.util.StreamUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willDoNothing; @@ -56,7 +55,7 @@ public class SimpleClientHttpResponseTests { assertThat(StreamUtils.copyToString(responseStream, StandardCharsets.UTF_8)).isEqualTo("Spring"); this.response.close(); - assertTrue(is.isClosed()); + assertThat(is.isClosed()).isTrue(); verify(this.connection, never()).disconnect(); } @@ -74,7 +73,7 @@ public class SimpleClientHttpResponseTests { this.response.close(); assertThat(is.available()).isEqualTo(0); - assertTrue(is.isClosed()); + assertThat(is.isClosed()).isTrue(); verify(this.connection, never()).disconnect(); } @@ -91,7 +90,7 @@ public class SimpleClientHttpResponseTests { this.response.close(); assertThat(is.available()).isEqualTo(0); - assertTrue(is.isClosed()); + assertThat(is.isClosed()).isTrue(); verify(this.connection, never()).disconnect(); } @@ -117,7 +116,7 @@ public class SimpleClientHttpResponseTests { this.response.close(); assertThat(is.available()).isEqualTo(0); - assertTrue(is.isClosed()); + assertThat(is.isClosed()).isTrue(); verify(this.connection, never()).disconnect(); } diff --git a/spring-web/src/test/java/org/springframework/http/client/StreamingSimpleClientHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/StreamingSimpleClientHttpRequestFactoryTests.java index 0005ee98104..c6bad90bb17 100644 --- a/spring-web/src/test/java/org/springframework/http/client/StreamingSimpleClientHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/StreamingSimpleClientHttpRequestFactoryTests.java @@ -28,7 +28,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -57,9 +57,9 @@ public class StreamingSimpleClientHttpRequestFactoryTests extends AbstractHttpRe try { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.GET); response = request.execute(); - assertEquals("Invalid response status", HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).as("Invalid response status").isEqualTo(HttpStatus.OK); HttpHeaders responseHeaders = response.getHeaders(); - assertEquals("Custom header invalid", headerValue, responseHeaders.getFirst(headerName)); + assertThat(responseHeaders.getFirst(headerName)).as("Custom header invalid").isEqualTo(headerValue); } finally { if (response != null) { @@ -86,7 +86,7 @@ public class StreamingSimpleClientHttpRequestFactoryTests extends AbstractHttpRe body.write(buffer); } response = request.execute(); - assertEquals("Invalid response status", HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).as("Invalid response status").isEqualTo(HttpStatus.OK); } finally { if (response != null) { diff --git a/spring-web/src/test/java/org/springframework/http/client/reactive/ReactorResourceFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/reactive/ReactorResourceFactoryTests.java index 129b54a4d64..e7c84c9674a 100644 --- a/spring-web/src/test/java/org/springframework/http/client/reactive/ReactorResourceFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/reactive/ReactorResourceFactoryTests.java @@ -22,10 +22,7 @@ import reactor.netty.http.HttpResources; import reactor.netty.resources.ConnectionProvider; import reactor.netty.resources.LoopResources; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -50,13 +47,13 @@ public class ReactorResourceFactoryTests { this.resourceFactory.afterPropertiesSet(); HttpResources globalResources = HttpResources.get(); - assertSame(globalResources, this.resourceFactory.getConnectionProvider()); - assertSame(globalResources, this.resourceFactory.getLoopResources()); - assertFalse(globalResources.isDisposed()); + assertThat(this.resourceFactory.getConnectionProvider()).isSameAs(globalResources); + assertThat(this.resourceFactory.getLoopResources()).isSameAs(globalResources); + assertThat(globalResources.isDisposed()).isFalse(); this.resourceFactory.destroy(); - assertTrue(globalResources.isDisposed()); + assertThat(globalResources.isDisposed()).isTrue(); } @Test @@ -67,7 +64,7 @@ public class ReactorResourceFactoryTests { this.resourceFactory.addGlobalResourcesConsumer(httpResources -> invoked.set(true)); this.resourceFactory.afterPropertiesSet(); - assertTrue(invoked.get()); + assertThat(invoked.get()).isTrue(); this.resourceFactory.destroy(); } @@ -80,17 +77,17 @@ public class ReactorResourceFactoryTests { ConnectionProvider connectionProvider = this.resourceFactory.getConnectionProvider(); LoopResources loopResources = this.resourceFactory.getLoopResources(); - assertNotSame(HttpResources.get(), connectionProvider); - assertNotSame(HttpResources.get(), loopResources); + assertThat(connectionProvider).isNotSameAs(HttpResources.get()); + assertThat(loopResources).isNotSameAs(HttpResources.get()); // The below does not work since ConnectionPoolProvider simply checks if pool is empty. // assertFalse(connectionProvider.isDisposed()); - assertFalse(loopResources.isDisposed()); + assertThat(loopResources.isDisposed()).isFalse(); this.resourceFactory.destroy(); - assertTrue(connectionProvider.isDisposed()); - assertTrue(loopResources.isDisposed()); + assertThat(connectionProvider.isDisposed()).isTrue(); + assertThat(loopResources.isDisposed()).isTrue(); } @Test @@ -104,8 +101,8 @@ public class ReactorResourceFactoryTests { ConnectionProvider connectionProvider = this.resourceFactory.getConnectionProvider(); LoopResources loopResources = this.resourceFactory.getLoopResources(); - assertSame(this.connectionProvider, connectionProvider); - assertSame(this.loopResources, loopResources); + assertThat(connectionProvider).isSameAs(this.connectionProvider); + assertThat(loopResources).isSameAs(this.loopResources); verifyNoMoreInteractions(this.connectionProvider, this.loopResources); @@ -128,8 +125,8 @@ public class ReactorResourceFactoryTests { ConnectionProvider connectionProvider = this.resourceFactory.getConnectionProvider(); LoopResources loopResources = this.resourceFactory.getLoopResources(); - assertSame(this.connectionProvider, connectionProvider); - assertSame(this.loopResources, loopResources); + assertThat(connectionProvider).isSameAs(this.connectionProvider); + assertThat(loopResources).isSameAs(this.loopResources); verifyNoMoreInteractions(this.connectionProvider, this.loopResources); diff --git a/spring-web/src/test/java/org/springframework/http/client/support/BasicAuthorizationInterceptorTests.java b/spring-web/src/test/java/org/springframework/http/client/support/BasicAuthorizationInterceptorTests.java index 049cb97f18b..704ee4b2479 100644 --- a/spring-web/src/test/java/org/springframework/http/client/support/BasicAuthorizationInterceptorTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/support/BasicAuthorizationInterceptorTests.java @@ -26,8 +26,8 @@ import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.SimpleClientHttpRequestFactory; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -51,14 +51,14 @@ public class BasicAuthorizationInterceptorTests { public void createWhenUsernameIsNullShouldUseEmptyUsername() throws Exception { BasicAuthorizationInterceptor interceptor = new BasicAuthorizationInterceptor( null, "password"); - assertEquals("", new DirectFieldAccessor(interceptor).getPropertyValue("username")); + assertThat(new DirectFieldAccessor(interceptor).getPropertyValue("username")).isEqualTo(""); } @Test public void createWhenPasswordIsNullShouldUseEmptyPassword() throws Exception { BasicAuthorizationInterceptor interceptor = new BasicAuthorizationInterceptor( "username", null); - assertEquals("", new DirectFieldAccessor(interceptor).getPropertyValue("password")); + assertThat(new DirectFieldAccessor(interceptor).getPropertyValue("password")).isEqualTo(""); } @Test @@ -70,7 +70,7 @@ public class BasicAuthorizationInterceptorTests { new BasicAuthorizationInterceptor("spring", "boot").intercept(request, body, execution); verify(execution).execute(request, body); - assertEquals("Basic c3ByaW5nOmJvb3Q=", request.getHeaders().getFirst("Authorization")); + assertThat(request.getHeaders().getFirst("Authorization")).isEqualTo("Basic c3ByaW5nOmJvb3Q="); } } diff --git a/spring-web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTests.java b/spring-web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTests.java index 679a9eb28ae..c9308bd94a2 100644 --- a/spring-web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTests.java @@ -22,8 +22,8 @@ import java.net.Proxy; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @author Arjen Poutsma @@ -70,10 +70,10 @@ public class ProxyFactoryBeanTests { Proxy result = factoryBean.getObject(); - assertEquals(type, result.type()); + assertThat(result.type()).isEqualTo(type); InetSocketAddress address = (InetSocketAddress) result.address(); - assertEquals(hostname, address.getHostName()); - assertEquals(port, address.getPort()); + assertThat(address.getHostName()).isEqualTo(hostname); + assertThat(address.getPort()).isEqualTo(port); } } diff --git a/spring-web/src/test/java/org/springframework/http/codec/EncoderHttpMessageWriterTests.java b/spring-web/src/test/java/org/springframework/http/codec/EncoderHttpMessageWriterTests.java index 1d3cd879cbc..7de00643aa7 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/EncoderHttpMessageWriterTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/EncoderHttpMessageWriterTests.java @@ -44,9 +44,7 @@ import org.springframework.util.ReflectionUtils; import static java.nio.charset.StandardCharsets.ISO_8859_1; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.springframework.core.ResolvableType.forClass; @@ -86,7 +84,7 @@ public class EncoderHttpMessageWriterTests { public void getWritableMediaTypes() { configureEncoder(MimeTypeUtils.TEXT_HTML, MimeTypeUtils.TEXT_XML); HttpMessageWriter writer = new EncoderHttpMessageWriter<>(this.encoder); - assertEquals(Arrays.asList(TEXT_HTML, TEXT_XML), writer.getWritableMediaTypes()); + assertThat(writer.getWritableMediaTypes()).isEqualTo(Arrays.asList(TEXT_HTML, TEXT_XML)); } @Test @@ -95,8 +93,8 @@ public class EncoderHttpMessageWriterTests { HttpMessageWriter writer = new EncoderHttpMessageWriter<>(this.encoder); given(this.encoder.canEncode(forClass(String.class), TEXT_HTML)).willReturn(true); - assertTrue(writer.canWrite(forClass(String.class), TEXT_HTML)); - assertFalse(writer.canWrite(forClass(String.class), TEXT_XML)); + assertThat(writer.canWrite(forClass(String.class), TEXT_HTML)).isTrue(); + assertThat(writer.canWrite(forClass(String.class), TEXT_XML)).isFalse(); } @Test @@ -105,8 +103,8 @@ public class EncoderHttpMessageWriterTests { HttpMessageWriter writer = new EncoderHttpMessageWriter<>(this.encoder); writer.write(Flux.empty(), forClass(String.class), TEXT_PLAIN, this.response, NO_HINTS); - assertEquals(TEXT_PLAIN, response.getHeaders().getContentType()); - assertEquals(TEXT_PLAIN, this.mediaTypeCaptor.getValue()); + assertThat(response.getHeaders().getContentType()).isEqualTo(TEXT_PLAIN); + assertThat(this.mediaTypeCaptor.getValue()).isEqualTo(TEXT_PLAIN); } @Test @@ -126,8 +124,8 @@ public class EncoderHttpMessageWriterTests { HttpMessageWriter writer = new EncoderHttpMessageWriter<>(this.encoder); writer.write(Flux.empty(), forClass(String.class), negotiatedMediaType, this.response, NO_HINTS); - assertEquals(defaultContentType, this.response.getHeaders().getContentType()); - assertEquals(defaultContentType, this.mediaTypeCaptor.getValue()); + assertThat(this.response.getHeaders().getContentType()).isEqualTo(defaultContentType); + assertThat(this.mediaTypeCaptor.getValue()).isEqualTo(defaultContentType); } @Test @@ -136,8 +134,8 @@ public class EncoderHttpMessageWriterTests { HttpMessageWriter writer = new EncoderHttpMessageWriter<>(this.encoder); writer.write(Flux.empty(), forClass(String.class), TEXT_HTML, response, NO_HINTS); - assertEquals(new MediaType("text", "html", UTF_8), this.response.getHeaders().getContentType()); - assertEquals(new MediaType("text", "html", UTF_8), this.mediaTypeCaptor.getValue()); + assertThat(this.response.getHeaders().getContentType()).isEqualTo(new MediaType("text", "html", UTF_8)); + assertThat(this.mediaTypeCaptor.getValue()).isEqualTo(new MediaType("text", "html", UTF_8)); } @Test @@ -147,8 +145,8 @@ public class EncoderHttpMessageWriterTests { HttpMessageWriter writer = new EncoderHttpMessageWriter<>(this.encoder); writer.write(Flux.empty(), forClass(String.class), negotiatedMediaType, this.response, NO_HINTS); - assertEquals(negotiatedMediaType, this.response.getHeaders().getContentType()); - assertEquals(negotiatedMediaType, this.mediaTypeCaptor.getValue()); + assertThat(this.response.getHeaders().getContentType()).isEqualTo(negotiatedMediaType); + assertThat(this.mediaTypeCaptor.getValue()).isEqualTo(negotiatedMediaType); } @Test @@ -160,8 +158,8 @@ public class EncoderHttpMessageWriterTests { HttpMessageWriter writer = new EncoderHttpMessageWriter<>(this.encoder); writer.write(Flux.empty(), forClass(String.class), TEXT_PLAIN, this.response, NO_HINTS); - assertEquals(outputMessageMediaType, this.response.getHeaders().getContentType()); - assertEquals(outputMessageMediaType, this.mediaTypeCaptor.getValue()); + assertThat(this.response.getHeaders().getContentType()).isEqualTo(outputMessageMediaType); + assertThat(this.mediaTypeCaptor.getValue()).isEqualTo(outputMessageMediaType); } @Test @@ -172,7 +170,7 @@ public class EncoderHttpMessageWriterTests { HttpMessageWriter writer = new EncoderHttpMessageWriter<>(this.encoder); writer.write(Mono.just("body"), forClass(String.class), TEXT_PLAIN, this.response, NO_HINTS).block(); - assertEquals(4, this.response.getHeaders().getContentLength()); + assertThat(this.response.getHeaders().getContentLength()).isEqualTo(4); } @Test // gh-22952 @@ -192,7 +190,7 @@ public class EncoderHttpMessageWriterTests { HttpMessageWriter writer = new EncoderHttpMessageWriter<>(this.encoder); writer.write(Mono.empty(), forClass(String.class), TEXT_PLAIN, this.response, NO_HINTS).block(); StepVerifier.create(this.response.getBody()).expectComplete(); - assertEquals(0, this.response.getHeaders().getContentLength()); + assertThat(this.response.getHeaders().getContentLength()).isEqualTo(0); } @Test // gh-22936 @@ -205,9 +203,9 @@ public class EncoderHttpMessageWriterTests { Method method = ReflectionUtils.findMethod(writer.getClass(), "isStreamingMediaType", MediaType.class); ReflectionUtils.makeAccessible(method); - assertTrue((Boolean) method.invoke(writer, streamingMediaType)); - assertFalse((Boolean) method.invoke(writer, new MediaType(TEXT_PLAIN, Collections.singletonMap("streaming", "false")))); - assertFalse((Boolean) method.invoke(writer, TEXT_HTML)); + assertThat((boolean) (Boolean) method.invoke(writer, streamingMediaType)).isTrue(); + assertThat((boolean) (Boolean) method.invoke(writer, new MediaType(TEXT_PLAIN, Collections.singletonMap("streaming", "false")))).isFalse(); + assertThat((boolean) (Boolean) method.invoke(writer, TEXT_HTML)).isFalse(); } private void configureEncoder(MimeType... mimeTypes) { diff --git a/spring-web/src/test/java/org/springframework/http/codec/FormHttpMessageReaderTests.java b/spring-web/src/test/java/org/springframework/http/codec/FormHttpMessageReaderTests.java index e306b94261d..6012fa19ada 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/FormHttpMessageReaderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/FormHttpMessageReaderTests.java @@ -36,10 +36,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze @@ -51,29 +48,29 @@ public class FormHttpMessageReaderTests extends AbstractLeakCheckingTestCase { @Test public void canRead() { - assertTrue(this.reader.canRead( + assertThat(this.reader.canRead( ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class), - MediaType.APPLICATION_FORM_URLENCODED)); + MediaType.APPLICATION_FORM_URLENCODED)).isTrue(); - assertTrue(this.reader.canRead( + assertThat(this.reader.canRead( ResolvableType.forInstance(new LinkedMultiValueMap()), - MediaType.APPLICATION_FORM_URLENCODED)); + MediaType.APPLICATION_FORM_URLENCODED)).isTrue(); - assertFalse(this.reader.canRead( + assertThat(this.reader.canRead( ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Object.class), - MediaType.APPLICATION_FORM_URLENCODED)); + MediaType.APPLICATION_FORM_URLENCODED)).isFalse(); - assertFalse(this.reader.canRead( + assertThat(this.reader.canRead( ResolvableType.forClassWithGenerics(MultiValueMap.class, Object.class, String.class), - MediaType.APPLICATION_FORM_URLENCODED)); + MediaType.APPLICATION_FORM_URLENCODED)).isFalse(); - assertFalse(this.reader.canRead( + assertThat(this.reader.canRead( ResolvableType.forClassWithGenerics(Map.class, String.class, String.class), - MediaType.APPLICATION_FORM_URLENCODED)); + MediaType.APPLICATION_FORM_URLENCODED)).isFalse(); - assertFalse(this.reader.canRead( + assertThat(this.reader.canRead( ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class), - MediaType.MULTIPART_FORM_DATA)); + MediaType.MULTIPART_FORM_DATA)).isFalse(); } @Test @@ -82,13 +79,13 @@ public class FormHttpMessageReaderTests extends AbstractLeakCheckingTestCase { MockServerHttpRequest request = request(body); MultiValueMap result = this.reader.readMono(null, request, null).block(); - assertEquals("Invalid result", 3, result.size()); - assertEquals("Invalid result", "value 1", result.getFirst("name 1")); + assertThat(result.size()).as("Invalid result").isEqualTo(3); + assertThat(result.getFirst("name 1")).as("Invalid result").isEqualTo("value 1"); List values = result.get("name 2"); - assertEquals("Invalid result", 2, values.size()); - assertEquals("Invalid result", "value 2+1", values.get(0)); - assertEquals("Invalid result", "value 2+2", values.get(1)); - assertNull("Invalid result", result.getFirst("name 3")); + assertThat(values.size()).as("Invalid result").isEqualTo(2); + assertThat(values.get(0)).as("Invalid result").isEqualTo("value 2+1"); + assertThat(values.get(1)).as("Invalid result").isEqualTo("value 2+2"); + assertThat(result.getFirst("name 3")).as("Invalid result").isNull(); } @Test @@ -97,13 +94,13 @@ public class FormHttpMessageReaderTests extends AbstractLeakCheckingTestCase { MockServerHttpRequest request = request(body); MultiValueMap result = this.reader.read(null, request, null).single().block(); - assertEquals("Invalid result", 3, result.size()); - assertEquals("Invalid result", "value 1", result.getFirst("name 1")); + assertThat(result.size()).as("Invalid result").isEqualTo(3); + assertThat(result.getFirst("name 1")).as("Invalid result").isEqualTo("value 1"); List values = result.get("name 2"); - assertEquals("Invalid result", 2, values.size()); - assertEquals("Invalid result", "value 2+1", values.get(0)); - assertEquals("Invalid result", "value 2+2", values.get(1)); - assertNull("Invalid result", result.getFirst("name 3")); + assertThat(values.size()).as("Invalid result").isEqualTo(2); + assertThat(values.get(0)).as("Invalid result").isEqualTo("value 2+1"); + assertThat(values.get(1)).as("Invalid result").isEqualTo("value 2+2"); + assertThat(result.getFirst("name 3")).as("Invalid result").isNull(); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/codec/FormHttpMessageWriterTests.java b/spring-web/src/test/java/org/springframework/http/codec/FormHttpMessageWriterTests.java index 9d73c815b7d..2357391b9fe 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/FormHttpMessageWriterTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/FormHttpMessageWriterTests.java @@ -35,9 +35,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze @@ -49,30 +47,30 @@ public class FormHttpMessageWriterTests extends AbstractLeakCheckingTestCase { @Test public void canWrite() { - assertTrue(this.writer.canWrite( + assertThat(this.writer.canWrite( ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class), - MediaType.APPLICATION_FORM_URLENCODED)); + MediaType.APPLICATION_FORM_URLENCODED)).isTrue(); // No generic information - assertTrue(this.writer.canWrite( + assertThat(this.writer.canWrite( ResolvableType.forInstance(new LinkedMultiValueMap()), - MediaType.APPLICATION_FORM_URLENCODED)); + MediaType.APPLICATION_FORM_URLENCODED)).isTrue(); - assertFalse(this.writer.canWrite( + assertThat(this.writer.canWrite( ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Object.class), - null)); + null)).isFalse(); - assertFalse(this.writer.canWrite( + assertThat(this.writer.canWrite( ResolvableType.forClassWithGenerics(MultiValueMap.class, Object.class, String.class), - null)); + null)).isFalse(); - assertFalse(this.writer.canWrite( + assertThat(this.writer.canWrite( ResolvableType.forClassWithGenerics(Map.class, String.class, String.class), - MediaType.APPLICATION_FORM_URLENCODED)); + MediaType.APPLICATION_FORM_URLENCODED)).isFalse(); - assertFalse(this.writer.canWrite( + assertThat(this.writer.canWrite( ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class), - MediaType.MULTIPART_FORM_DATA)); + MediaType.MULTIPART_FORM_DATA)).isFalse(); } @Test @@ -91,15 +89,15 @@ public class FormHttpMessageWriterTests extends AbstractLeakCheckingTestCase { .expectComplete() .verify(); HttpHeaders headers = response.getHeaders(); - assertEquals("application/x-www-form-urlencoded;charset=UTF-8", headers.getContentType().toString()); - assertEquals(expected.length(), headers.getContentLength()); + assertThat(headers.getContentType().toString()).isEqualTo("application/x-www-form-urlencoded;charset=UTF-8"); + assertThat(headers.getContentLength()).isEqualTo(expected.length()); } private Consumer stringConsumer(String expected) { return dataBuffer -> { String value = DataBufferTestUtils.dumpString(dataBuffer, StandardCharsets.UTF_8); DataBufferUtils.release(dataBuffer); - assertEquals(expected, value); + assertThat(value).isEqualTo(expected); }; } diff --git a/spring-web/src/test/java/org/springframework/http/codec/ResourceHttpMessageWriterTests.java b/spring-web/src/test/java/org/springframework/http/codec/ResourceHttpMessageWriterTests.java index df85d49cea7..aab3cb7116c 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/ResourceHttpMessageWriterTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/ResourceHttpMessageWriterTests.java @@ -36,7 +36,6 @@ import org.springframework.util.MimeTypeUtils; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertArrayEquals; import static org.springframework.http.MediaType.TEXT_PLAIN; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; @@ -124,7 +123,7 @@ public class ResourceHttpMessageWriterTests { "resource content.", "--" + boundary + "--" }; - assertArrayEquals(expected, actualRanges); + assertThat(actualRanges).isEqualTo(expected); }) .expectComplete() .verify(); diff --git a/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageReaderTests.java b/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageReaderTests.java index 49882eb5d5a..306278e87b6 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageReaderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageReaderTests.java @@ -32,10 +32,7 @@ import org.springframework.http.MediaType; import org.springframework.http.codec.json.Jackson2JsonDecoder; import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ServerSentEventHttpMessageReader}. @@ -50,14 +47,14 @@ public class ServerSentEventHttpMessageReaderTests extends AbstractLeakCheckingT @Test public void cantRead() { - assertFalse(messageReader.canRead(ResolvableType.forClass(Object.class), new MediaType("foo", "bar"))); - assertFalse(messageReader.canRead(ResolvableType.forClass(Object.class), null)); + assertThat(messageReader.canRead(ResolvableType.forClass(Object.class), new MediaType("foo", "bar"))).isFalse(); + assertThat(messageReader.canRead(ResolvableType.forClass(Object.class), null)).isFalse(); } @Test public void canRead() { - assertTrue(messageReader.canRead(ResolvableType.forClass(Object.class), new MediaType("text", "event-stream"))); - assertTrue(messageReader.canRead(ResolvableType.forClass(ServerSentEvent.class), new MediaType("foo", "bar"))); + assertThat(messageReader.canRead(ResolvableType.forClass(Object.class), new MediaType("text", "event-stream"))).isTrue(); + assertThat(messageReader.canRead(ResolvableType.forClass(ServerSentEvent.class), new MediaType("foo", "bar"))).isTrue(); } @Test @@ -74,18 +71,18 @@ public class ServerSentEventHttpMessageReaderTests extends AbstractLeakCheckingT StepVerifier.create(events) .consumeNextWith(event -> { - assertEquals("c42", event.id()); - assertEquals("foo", event.event()); - assertEquals(Duration.ofMillis(123), event.retry()); - assertEquals("bla\nbla bla\nbla bla bla", event.comment()); - assertEquals("bar", event.data()); + assertThat(event.id()).isEqualTo("c42"); + assertThat(event.event()).isEqualTo("foo"); + assertThat(event.retry()).isEqualTo(Duration.ofMillis(123)); + assertThat(event.comment()).isEqualTo("bla\nbla bla\nbla bla bla"); + assertThat(event.data()).isEqualTo("bar"); }) .consumeNextWith(event -> { - assertEquals("c43", event.id()); - assertEquals("bar", event.event()); - assertEquals(Duration.ofMillis(456), event.retry()); - assertNull(event.comment()); - assertEquals("baz", event.data()); + assertThat(event.id()).isEqualTo("c43"); + assertThat(event.event()).isEqualTo("bar"); + assertThat(event.retry()).isEqualTo(Duration.ofMillis(456)); + assertThat(event.comment()).isNull(); + assertThat(event.data()).isEqualTo("baz"); }) .expectComplete() .verify(); @@ -106,18 +103,18 @@ public class ServerSentEventHttpMessageReaderTests extends AbstractLeakCheckingT StepVerifier.create(events) .consumeNextWith(event -> { - assertEquals("c42", event.id()); - assertEquals("foo", event.event()); - assertEquals(Duration.ofMillis(123), event.retry()); - assertEquals("bla\nbla bla\nbla bla bla", event.comment()); - assertEquals("bar", event.data()); + assertThat(event.id()).isEqualTo("c42"); + assertThat(event.event()).isEqualTo("foo"); + assertThat(event.retry()).isEqualTo(Duration.ofMillis(123)); + assertThat(event.comment()).isEqualTo("bla\nbla bla\nbla bla bla"); + assertThat(event.data()).isEqualTo("bar"); }) .consumeNextWith(event -> { - assertEquals("c43", event.id()); - assertEquals("bar", event.event()); - assertEquals(Duration.ofMillis(456), event.retry()); - assertNull(event.comment()); - assertEquals("baz", event.data()); + assertThat(event.id()).isEqualTo("c43"); + assertThat(event.event()).isEqualTo("bar"); + assertThat(event.retry()).isEqualTo(Duration.ofMillis(456)); + assertThat(event.comment()).isNull(); + assertThat(event.data()).isEqualTo("baz"); }) .expectComplete() .verify(); @@ -150,12 +147,12 @@ public class ServerSentEventHttpMessageReaderTests extends AbstractLeakCheckingT StepVerifier.create(data) .consumeNextWith(pojo -> { - assertEquals("foofoo", pojo.getFoo()); - assertEquals("barbar", pojo.getBar()); + assertThat(pojo.getFoo()).isEqualTo("foofoo"); + assertThat(pojo.getBar()).isEqualTo("barbar"); }) .consumeNextWith(pojo -> { - assertEquals("foofoofoo", pojo.getFoo()); - assertEquals("barbarbar", pojo.getBar()); + assertThat(pojo.getFoo()).isEqualTo("foofoofoo"); + assertThat(pojo.getBar()).isEqualTo("barbarbar"); }) .expectComplete() .verify(); @@ -172,7 +169,7 @@ public class ServerSentEventHttpMessageReaderTests extends AbstractLeakCheckingT .cast(String.class) .block(Duration.ZERO); - assertEquals(body, actual); + assertThat(actual).isEqualTo(body); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageWriterTests.java b/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageWriterTests.java index 002c13c980a..79f088be953 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageWriterTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/ServerSentEventHttpMessageWriterTests.java @@ -39,9 +39,7 @@ import org.springframework.http.codec.json.Jackson2JsonEncoder; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.ResolvableType.forClass; /** @@ -70,15 +68,15 @@ public class ServerSentEventHttpMessageWriterTests extends AbstractDataBufferAll @Test public void canWrite() { - assertTrue(this.messageWriter.canWrite(forClass(Object.class), null)); - assertFalse(this.messageWriter.canWrite(forClass(Object.class), new MediaType("foo", "bar"))); + assertThat(this.messageWriter.canWrite(forClass(Object.class), null)).isTrue(); + assertThat(this.messageWriter.canWrite(forClass(Object.class), new MediaType("foo", "bar"))).isFalse(); - assertTrue(this.messageWriter.canWrite(null, MediaType.TEXT_EVENT_STREAM)); - assertTrue(this.messageWriter.canWrite(forClass(ServerSentEvent.class), new MediaType("foo", "bar"))); + assertThat(this.messageWriter.canWrite(null, MediaType.TEXT_EVENT_STREAM)).isTrue(); + assertThat(this.messageWriter.canWrite(forClass(ServerSentEvent.class), new MediaType("foo", "bar"))).isTrue(); // SPR-15464 - assertTrue(this.messageWriter.canWrite(ResolvableType.NONE, MediaType.TEXT_EVENT_STREAM)); - assertFalse(this.messageWriter.canWrite(ResolvableType.NONE, new MediaType("foo", "bar"))); + assertThat(this.messageWriter.canWrite(ResolvableType.NONE, MediaType.TEXT_EVENT_STREAM)).isTrue(); + assertThat(this.messageWriter.canWrite(ResolvableType.NONE, new MediaType("foo", "bar"))).isFalse(); } @Test @@ -127,12 +125,12 @@ public class ServerSentEventHttpMessageWriterTests extends AbstractDataBufferAll MediaType mediaType = new MediaType("text", "event-stream", charset); testWrite(source, mediaType, outputMessage, String.class); - assertEquals(mediaType, outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(mediaType); StepVerifier.create(outputMessage.getBody()) .consumeNextWith(dataBuffer -> { String value = DataBufferTestUtils.dumpString(dataBuffer, charset); DataBufferUtils.release(dataBuffer); - assertEquals("data:\u00A3\n\n", value); + assertThat(value).isEqualTo("data:\u00A3\n\n"); }) .expectComplete() .verify(); @@ -176,12 +174,12 @@ public class ServerSentEventHttpMessageWriterTests extends AbstractDataBufferAll MediaType mediaType = new MediaType("text", "event-stream", charset); testWrite(source, mediaType, outputMessage, Pojo.class); - assertEquals(mediaType, outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(mediaType); StepVerifier.create(outputMessage.getBody()) .consumeNextWith(dataBuffer -> { String value = DataBufferTestUtils.dumpString(dataBuffer, charset); DataBufferUtils.release(dataBuffer); - assertEquals("data:{\"foo\":\"foo\uD834\uDD1E\",\"bar\":\"bar\uD834\uDD1E\"}\n\n", value); + assertThat(value).isEqualTo("data:{\"foo\":\"foo\uD834\uDD1E\",\"bar\":\"bar\uD834\uDD1E\"}\n\n"); }) .expectComplete() .verify(); diff --git a/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborDecoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborDecoderTests.java index b66eb5550ed..5cb4fcf5887 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborDecoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/cbor/Jackson2CborDecoderTests.java @@ -31,9 +31,8 @@ import org.springframework.http.codec.Pojo; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.util.MimeType; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.springframework.core.ResolvableType.forClass; import static org.springframework.http.MediaType.APPLICATION_JSON; @@ -59,11 +58,11 @@ public class Jackson2CborDecoderTests extends AbstractDecoderTestCase step .consumeNextWith(o -> { JacksonViewBean b = (JacksonViewBean) o; - assertEquals("with", b.getWithView1()); - assertNull(b.getWithView2()); - assertNull(b.getWithoutView()); + assertThat(b.getWithView1()).isEqualTo("with"); + assertThat(b.getWithView2()).isNull(); + assertThat(b.getWithoutView()).isNull(); }), null, hints); } @@ -165,9 +162,9 @@ public class Jackson2JsonDecoderTests extends AbstractDecoderTestCase step .consumeNextWith(o -> { JacksonViewBean b = (JacksonViewBean) o; - assertEquals("without", b.getWithoutView()); - assertNull(b.getWithView1()); - assertNull(b.getWithView2()); + assertThat(b.getWithoutView()).isEqualTo("without"); + assertThat(b.getWithView1()).isNull(); + assertThat(b.getWithView2()).isNull(); }) .verifyComplete(), null, hints); } @@ -202,7 +199,7 @@ public class Jackson2JsonDecoderTests extends AbstractDecoderTestCase input = stringBuffer("{\"test\": 1}"); testDecode(input, TestObject.class, step -> step - .consumeNextWith(o -> assertEquals(1, o.getTest())) + .consumeNextWith(o -> assertThat(o.getTest()).isEqualTo(1)) .verifyComplete() ); } diff --git a/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonEncoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonEncoderTests.java index ba7e9479953..8a1e6317e62 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonEncoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonEncoderTests.java @@ -44,10 +44,8 @@ import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; import static java.util.Collections.singletonMap; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM; import static org.springframework.http.MediaType.APPLICATION_STREAM_JSON; @@ -68,15 +66,15 @@ public class Jackson2JsonEncoderTests extends AbstractEncoderTestCase { - assertTrue(part.headers().isEmpty()); + assertThat(part.headers().isEmpty()).isTrue(); part.content().subscribe(DataBufferUtils::release); }) .verifyComplete(); @@ -129,18 +128,20 @@ public class DefaultMultipartMessageReaderTests extends AbstractDataBufferAlloca } private static void testBrowserFormField(Part part, String name, String value) { - assertTrue(part instanceof FormFieldPart); - assertEquals(name, part.name()); + boolean condition = part instanceof FormFieldPart; + assertThat(condition).isTrue(); + assertThat(part.name()).isEqualTo(name); FormFieldPart formField = (FormFieldPart) part; - assertEquals(value, formField.value()); + assertThat(formField.value()).isEqualTo(value); } private static void testBrowserFile(Part part, String name, String filename, String contents) { try { - assertTrue(part instanceof FilePart); - assertEquals(name, part.name()); + boolean condition = part instanceof FilePart; + assertThat(condition).isTrue(); + assertThat(part.name()).isEqualTo(name); FilePart file = (FilePart) part; - assertEquals(filename, file.filename()); + assertThat(file.filename()).isEqualTo(filename); Path tempFile = Files.createTempFile("DefaultMultipartMessageReaderTests", null); @@ -170,7 +171,7 @@ public class DefaultMultipartMessageReaderTests extends AbstractDataBufferAlloca private static void verifyContents(Path tempFile, String contents) { try { String result = String.join("", Files.readAllLines(tempFile)); - assertEquals(contents, result); + assertThat(result).isEqualTo(contents); } catch (IOException ex) { throw new AssertionError(ex); diff --git a/spring-web/src/test/java/org/springframework/http/codec/multipart/MultipartHttpMessageWriterTests.java b/spring-web/src/test/java/org/springframework/http/codec/multipart/MultipartHttpMessageWriterTests.java index 149a50f9245..0886d2c83fb 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/multipart/MultipartHttpMessageWriterTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/multipart/MultipartHttpMessageWriterTests.java @@ -44,10 +44,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -65,19 +62,19 @@ public class MultipartHttpMessageWriterTests extends AbstractLeakCheckingTestCas @Test public void canWrite() { - assertTrue(this.writer.canWrite( + assertThat(this.writer.canWrite( ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Object.class), - MediaType.MULTIPART_FORM_DATA)); - assertTrue(this.writer.canWrite( + MediaType.MULTIPART_FORM_DATA)).isTrue(); + assertThat(this.writer.canWrite( ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class), - MediaType.MULTIPART_FORM_DATA)); + MediaType.MULTIPART_FORM_DATA)).isTrue(); - assertFalse(this.writer.canWrite( + assertThat(this.writer.canWrite( ResolvableType.forClassWithGenerics(Map.class, String.class, Object.class), - MediaType.MULTIPART_FORM_DATA)); - assertTrue(this.writer.canWrite( + MediaType.MULTIPART_FORM_DATA)).isFalse(); + assertThat(this.writer.canWrite( ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, Object.class), - MediaType.APPLICATION_FORM_URLENCODED)); + MediaType.APPLICATION_FORM_URLENCODED)).isTrue(); } @Test @@ -114,53 +111,58 @@ public class MultipartHttpMessageWriterTests extends AbstractLeakCheckingTestCas this.writer.write(result, null, MediaType.MULTIPART_FORM_DATA, this.response, hints).block(Duration.ofSeconds(5)); MultiValueMap requestParts = parse(hints); - assertEquals(7, requestParts.size()); + assertThat(requestParts.size()).isEqualTo(7); Part part = requestParts.getFirst("name 1"); - assertTrue(part instanceof FormFieldPart); - assertEquals("name 1", part.name()); - assertEquals("value 1", ((FormFieldPart) part).value()); + boolean condition4 = part instanceof FormFieldPart; + assertThat(condition4).isTrue(); + assertThat(part.name()).isEqualTo("name 1"); + assertThat(((FormFieldPart) part).value()).isEqualTo("value 1"); List parts2 = requestParts.get("name 2"); - assertEquals(2, parts2.size()); + assertThat(parts2.size()).isEqualTo(2); part = parts2.get(0); - assertTrue(part instanceof FormFieldPart); - assertEquals("name 2", part.name()); - assertEquals("value 2+1", ((FormFieldPart) part).value()); + boolean condition3 = part instanceof FormFieldPart; + assertThat(condition3).isTrue(); + assertThat(part.name()).isEqualTo("name 2"); + assertThat(((FormFieldPart) part).value()).isEqualTo("value 2+1"); part = parts2.get(1); - assertTrue(part instanceof FormFieldPart); - assertEquals("name 2", part.name()); - assertEquals("value 2+2", ((FormFieldPart) part).value()); + boolean condition2 = part instanceof FormFieldPart; + assertThat(condition2).isTrue(); + assertThat(part.name()).isEqualTo("name 2"); + assertThat(((FormFieldPart) part).value()).isEqualTo("value 2+2"); part = requestParts.getFirst("logo"); - assertTrue(part instanceof FilePart); - assertEquals("logo", part.name()); - assertEquals("logo.jpg", ((FilePart) part).filename()); - assertEquals(MediaType.IMAGE_JPEG, part.headers().getContentType()); - assertEquals(logo.getFile().length(), part.headers().getContentLength()); + boolean condition1 = part instanceof FilePart; + assertThat(condition1).isTrue(); + assertThat(part.name()).isEqualTo("logo"); + assertThat(((FilePart) part).filename()).isEqualTo("logo.jpg"); + assertThat(part.headers().getContentType()).isEqualTo(MediaType.IMAGE_JPEG); + assertThat(part.headers().getContentLength()).isEqualTo(logo.getFile().length()); part = requestParts.getFirst("utf8"); - assertTrue(part instanceof FilePart); - assertEquals("utf8", part.name()); - assertEquals("Hall\u00F6le.jpg", ((FilePart) part).filename()); - assertEquals(MediaType.IMAGE_JPEG, part.headers().getContentType()); - assertEquals(utf8.getFile().length(), part.headers().getContentLength()); + boolean condition = part instanceof FilePart; + assertThat(condition).isTrue(); + assertThat(part.name()).isEqualTo("utf8"); + assertThat(((FilePart) part).filename()).isEqualTo("Hall\u00F6le.jpg"); + assertThat(part.headers().getContentType()).isEqualTo(MediaType.IMAGE_JPEG); + assertThat(part.headers().getContentLength()).isEqualTo(utf8.getFile().length()); part = requestParts.getFirst("json"); - assertEquals("json", part.name()); - assertEquals(MediaType.APPLICATION_JSON, part.headers().getContentType()); + assertThat(part.name()).isEqualTo("json"); + assertThat(part.headers().getContentType()).isEqualTo(MediaType.APPLICATION_JSON); String value = decodeToString(part); - assertEquals("{\"bar\":\"bar\"}", value); + assertThat(value).isEqualTo("{\"bar\":\"bar\"}"); part = requestParts.getFirst("publisher"); - assertEquals("publisher", part.name()); + assertThat(part.name()).isEqualTo("publisher"); value = decodeToString(part); - assertEquals("foobarbaz", value); + assertThat(value).isEqualTo("foobarbaz"); part = requestParts.getFirst("partPublisher"); - assertEquals("partPublisher", part.name()); + assertThat(part.name()).isEqualTo("partPublisher"); value = decodeToString(part); - assertEquals("AaBbCc", value); + assertThat(value).isEqualTo("AaBbCc"); } @SuppressWarnings("ConstantConditions") @@ -185,14 +187,15 @@ public class MultipartHttpMessageWriterTests extends AbstractLeakCheckingTestCas this.writer.write(result, null, MediaType.MULTIPART_FORM_DATA, this.response, hints).block(); MultiValueMap requestParts = parse(hints); - assertEquals(1, requestParts.size()); + assertThat(requestParts.size()).isEqualTo(1); Part part = requestParts.getFirst("logo"); - assertEquals("logo", part.name()); - assertTrue(part instanceof FilePart); - assertEquals("logo.jpg", ((FilePart) part).filename()); - assertEquals(MediaType.IMAGE_JPEG, part.headers().getContentType()); - assertEquals(logo.getFile().length(), part.headers().getContentLength()); + assertThat(part.name()).isEqualTo("logo"); + boolean condition = part instanceof FilePart; + assertThat(condition).isTrue(); + assertThat(((FilePart) part).filename()).isEqualTo("logo.jpg"); + assertThat(part.headers().getContentType()).isEqualTo(MediaType.IMAGE_JPEG); + assertThat(part.headers().getContentLength()).isEqualTo(logo.getFile().length()); } @Test // SPR-16402 @@ -235,22 +238,24 @@ public class MultipartHttpMessageWriterTests extends AbstractLeakCheckingTestCas this.response, hints).block(); MultiValueMap requestParts = parse(hints); - assertEquals(2, requestParts.size()); + assertThat(requestParts.size()).isEqualTo(2); Part part = requestParts.getFirst("resource"); - assertTrue(part instanceof FilePart); - assertEquals("spring.jpg", ((FilePart) part).filename()); - assertEquals(logo.getFile().length(), part.headers().getContentLength()); + boolean condition1 = part instanceof FilePart; + assertThat(condition1).isTrue(); + assertThat(((FilePart) part).filename()).isEqualTo("spring.jpg"); + assertThat(part.headers().getContentLength()).isEqualTo(logo.getFile().length()); part = requestParts.getFirst("buffers"); - assertTrue(part instanceof FilePart); - assertEquals("buffers.jpg", ((FilePart) part).filename()); - assertEquals(logo.getFile().length(), part.headers().getContentLength()); + boolean condition = part instanceof FilePart; + assertThat(condition).isTrue(); + assertThat(((FilePart) part).filename()).isEqualTo("buffers.jpg"); + assertThat(part.headers().getContentLength()).isEqualTo(logo.getFile().length()); } private MultiValueMap parse(Map hints) { MediaType contentType = this.response.getHeaders().getContentType(); - assertNotNull("No boundary found", contentType.getParameter("boundary")); + assertThat(contentType.getParameter("boundary")).as("No boundary found").isNotNull(); // see if Synchronoss NIO Multipart can read what we wrote SynchronossPartHttpMessageReader synchronossReader = new SynchronossPartHttpMessageReader(); @@ -266,7 +271,7 @@ public class MultipartHttpMessageWriterTests extends AbstractLeakCheckingTestCas MultiValueMap result = reader.readMono(elementType, request, hints) .block(Duration.ofSeconds(5)); - assertNotNull(result); + assertThat(result).isNotNull(); return result; } diff --git a/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java b/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java index f95423ea75b..e287dcf5d28 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java @@ -39,10 +39,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.util.MultiValueMap; import static java.util.Collections.emptyMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.ResolvableType.forClassWithGenerics; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.MediaType.MULTIPART_FORM_DATA; @@ -61,25 +58,25 @@ public class SynchronossPartHttpMessageReaderTests { @Test public void canRead() { - assertTrue(this.reader.canRead( + assertThat(this.reader.canRead( forClassWithGenerics(MultiValueMap.class, String.class, Part.class), - MediaType.MULTIPART_FORM_DATA)); + MediaType.MULTIPART_FORM_DATA)).isTrue(); - assertFalse(this.reader.canRead( + assertThat(this.reader.canRead( forClassWithGenerics(MultiValueMap.class, String.class, Object.class), - MediaType.MULTIPART_FORM_DATA)); + MediaType.MULTIPART_FORM_DATA)).isFalse(); - assertFalse(this.reader.canRead( + assertThat(this.reader.canRead( forClassWithGenerics(MultiValueMap.class, String.class, String.class), - MediaType.MULTIPART_FORM_DATA)); + MediaType.MULTIPART_FORM_DATA)).isFalse(); - assertFalse(this.reader.canRead( + assertThat(this.reader.canRead( forClassWithGenerics(Map.class, String.class, String.class), - MediaType.MULTIPART_FORM_DATA)); + MediaType.MULTIPART_FORM_DATA)).isFalse(); - assertFalse(this.reader.canRead( + assertThat(this.reader.canRead( forClassWithGenerics(MultiValueMap.class, String.class, Part.class), - MediaType.APPLICATION_FORM_URLENCODED)); + MediaType.APPLICATION_FORM_URLENCODED)).isFalse(); } @Test @@ -87,24 +84,26 @@ public class SynchronossPartHttpMessageReaderTests { ServerHttpRequest request = generateMultipartRequest(); ResolvableType elementType = forClassWithGenerics(MultiValueMap.class, String.class, Part.class); MultiValueMap parts = this.reader.readMono(elementType, request, emptyMap()).block(); - assertEquals(2, parts.size()); + assertThat(parts.size()).isEqualTo(2); - assertTrue(parts.containsKey("fooPart")); + assertThat(parts.containsKey("fooPart")).isTrue(); Part part = parts.getFirst("fooPart"); - assertTrue(part instanceof FilePart); - assertEquals("fooPart", part.name()); - assertEquals("foo.txt", ((FilePart) part).filename()); + boolean condition1 = part instanceof FilePart; + assertThat(condition1).isTrue(); + assertThat(part.name()).isEqualTo("fooPart"); + assertThat(((FilePart) part).filename()).isEqualTo("foo.txt"); DataBuffer buffer = DataBufferUtils.join(part.content()).block(); - assertEquals(12, buffer.readableByteCount()); + assertThat(buffer.readableByteCount()).isEqualTo(12); byte[] byteContent = new byte[12]; buffer.read(byteContent); - assertEquals("Lorem Ipsum.", new String(byteContent)); + assertThat(new String(byteContent)).isEqualTo("Lorem Ipsum."); - assertTrue(parts.containsKey("barPart")); + assertThat(parts.containsKey("barPart")).isTrue(); part = parts.getFirst("barPart"); - assertTrue(part instanceof FormFieldPart); - assertEquals("barPart", part.name()); - assertEquals("bar", ((FormFieldPart) part).value()); + boolean condition = part instanceof FormFieldPart; + assertThat(condition).isTrue(); + assertThat(part.name()).isEqualTo("barPart"); + assertThat(((FormFieldPart) part).value()).isEqualTo("bar"); } @Test // SPR-16545 @@ -113,16 +112,16 @@ public class SynchronossPartHttpMessageReaderTests { ResolvableType elementType = forClassWithGenerics(MultiValueMap.class, String.class, Part.class); MultiValueMap parts = this.reader.readMono(elementType, request, emptyMap()).block(); - assertNotNull(parts); + assertThat(parts).isNotNull(); FilePart part = (FilePart) parts.getFirst("fooPart"); - assertNotNull(part); + assertThat(part).isNotNull(); File dest = new File(System.getProperty("java.io.tmpdir") + "/" + part.filename()); part.transferTo(dest).block(Duration.ofSeconds(5)); - assertTrue(dest.exists()); - assertEquals(12, dest.length()); - assertTrue(dest.delete()); + assertThat(dest.exists()).isTrue(); + assertThat(dest.length()).isEqualTo(12); + assertThat(dest.delete()).isTrue(); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java index 3cc50d037e7..f842a86831a 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java @@ -36,9 +36,8 @@ import org.springframework.protobuf.SecondMsg; import org.springframework.util.MimeType; import static java.util.Collections.emptyMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.springframework.core.ResolvableType.forClass; import static org.springframework.core.io.buffer.DataBufferUtils.release; @@ -73,11 +72,11 @@ public class ProtobufDecoderTests extends AbstractDecoderTestCase step .consumeNextWith(dataBuffer -> { try { - assertEquals(this.msg1, Msg.parseFrom(dataBuffer.asInputStream())); + assertThat(Msg.parseFrom(dataBuffer.asInputStream())).isEqualTo(this.msg1); } catch (IOException ex) { @@ -102,7 +100,7 @@ public class ProtobufEncoderTests extends AbstractEncoderTestCase expect(Msg msg) { return dataBuffer -> { try { - assertEquals(msg, Msg.parseDelimitedFrom(dataBuffer.asInputStream())); + assertThat(Msg.parseDelimitedFrom(dataBuffer.asInputStream())).isEqualTo(msg); } catch (IOException ex) { diff --git a/spring-web/src/test/java/org/springframework/http/codec/support/ClientCodecConfigurerTests.java b/spring-web/src/test/java/org/springframework/http/codec/support/ClientCodecConfigurerTests.java index 54e96b2a461..62b41befdaf 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/support/ClientCodecConfigurerTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/support/ClientCodecConfigurerTests.java @@ -59,10 +59,7 @@ import org.springframework.http.codec.xml.Jaxb2XmlDecoder; import org.springframework.http.codec.xml.Jaxb2XmlEncoder; import org.springframework.util.MimeTypeUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.ResolvableType.forClass; /** @@ -80,17 +77,18 @@ public class ClientCodecConfigurerTests { @Test public void defaultReaders() { List> readers = this.configurer.getReaders(); - assertEquals(12, readers.size()); - assertEquals(ByteArrayDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(ByteBufferDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(DataBufferDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(ResourceHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); + assertThat(readers.size()).isEqualTo(12); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ByteArrayDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ByteBufferDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(DataBufferDecoder.class); + assertThat(readers.get(this.index.getAndIncrement()).getClass()).isEqualTo(ResourceHttpMessageReader.class); assertStringDecoder(getNextDecoder(readers), true); - assertEquals(ProtobufDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(FormHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); // SPR-16804 - assertEquals(Jackson2JsonDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(Jackson2SmileDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(Jaxb2XmlDecoder.class, getNextDecoder(readers).getClass()); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ProtobufDecoder.class); + // SPR-16804 + assertThat(readers.get(this.index.getAndIncrement()).getClass()).isEqualTo(FormHttpMessageReader.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jackson2JsonDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jackson2SmileDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jaxb2XmlDecoder.class); assertSseReader(readers); assertStringDecoder(getNextDecoder(readers), false); } @@ -98,17 +96,17 @@ public class ClientCodecConfigurerTests { @Test public void defaultWriters() { List> writers = this.configurer.getWriters(); - assertEquals(11, writers.size()); - assertEquals(ByteArrayEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(ByteBufferEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(DataBufferEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(ResourceHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass()); + assertThat(writers.size()).isEqualTo(11); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(ByteArrayEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(ByteBufferEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(DataBufferEncoder.class); + assertThat(writers.get(index.getAndIncrement()).getClass()).isEqualTo(ResourceHttpMessageWriter.class); assertStringEncoder(getNextEncoder(writers), true); - assertEquals(MultipartHttpMessageWriter.class, writers.get(this.index.getAndIncrement()).getClass()); - assertEquals(ProtobufHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass()); - assertEquals(Jackson2JsonEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(Jackson2SmileEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(Jaxb2XmlEncoder.class, getNextEncoder(writers).getClass()); + assertThat(writers.get(this.index.getAndIncrement()).getClass()).isEqualTo(MultipartHttpMessageWriter.class); + assertThat(writers.get(index.getAndIncrement()).getClass()).isEqualTo(ProtobufHttpMessageWriter.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jackson2JsonEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jackson2SmileEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jaxb2XmlEncoder.class); assertStringEncoder(getNextEncoder(writers), false); } @@ -117,52 +115,54 @@ public class ClientCodecConfigurerTests { Jackson2JsonDecoder decoder = new Jackson2JsonDecoder(); this.configurer.defaultCodecs().jackson2JsonDecoder(decoder); - assertSame(decoder, this.configurer.getReaders().stream() + assertThat(this.configurer.getReaders().stream() .filter(reader -> ServerSentEventHttpMessageReader.class.equals(reader.getClass())) .map(reader -> (ServerSentEventHttpMessageReader) reader) .findFirst() .map(ServerSentEventHttpMessageReader::getDecoder) - .filter(e -> e == decoder).orElse(null)); + .filter(e -> e == decoder).orElse(null)).isSameAs(decoder); } private Decoder getNextDecoder(List> readers) { HttpMessageReader reader = readers.get(this.index.getAndIncrement()); - assertEquals(DecoderHttpMessageReader.class, reader.getClass()); + assertThat(reader.getClass()).isEqualTo(DecoderHttpMessageReader.class); return ((DecoderHttpMessageReader) reader).getDecoder(); } private Encoder getNextEncoder(List> writers) { HttpMessageWriter writer = writers.get(this.index.getAndIncrement()); - assertEquals(EncoderHttpMessageWriter.class, writer.getClass()); + assertThat(writer.getClass()).isEqualTo(EncoderHttpMessageWriter.class); return ((EncoderHttpMessageWriter) writer).getEncoder(); } @SuppressWarnings("unchecked") private void assertStringDecoder(Decoder decoder, boolean textOnly) { - assertEquals(StringDecoder.class, decoder.getClass()); - assertTrue(decoder.canDecode(forClass(String.class), MimeTypeUtils.TEXT_PLAIN)); - assertEquals(!textOnly, decoder.canDecode(forClass(String.class), MediaType.TEXT_EVENT_STREAM)); + assertThat(decoder.getClass()).isEqualTo(StringDecoder.class); + assertThat(decoder.canDecode(forClass(String.class), MimeTypeUtils.TEXT_PLAIN)).isTrue(); + Object expected = !textOnly; + assertThat(decoder.canDecode(forClass(String.class), MediaType.TEXT_EVENT_STREAM)).isEqualTo(expected); Flux decoded = (Flux) decoder.decode( Flux.just(new DefaultDataBufferFactory().wrap("line1\nline2".getBytes(StandardCharsets.UTF_8))), ResolvableType.forClass(String.class), MimeTypeUtils.TEXT_PLAIN, Collections.emptyMap()); - assertEquals(Arrays.asList("line1", "line2"), decoded.collectList().block(Duration.ZERO)); + assertThat(decoded.collectList().block(Duration.ZERO)).isEqualTo(Arrays.asList("line1", "line2")); } private void assertStringEncoder(Encoder encoder, boolean textOnly) { - assertEquals(CharSequenceEncoder.class, encoder.getClass()); - assertTrue(encoder.canEncode(forClass(String.class), MimeTypeUtils.TEXT_PLAIN)); - assertEquals(!textOnly, encoder.canEncode(forClass(String.class), MediaType.TEXT_EVENT_STREAM)); + assertThat(encoder.getClass()).isEqualTo(CharSequenceEncoder.class); + assertThat(encoder.canEncode(forClass(String.class), MimeTypeUtils.TEXT_PLAIN)).isTrue(); + Object expected = !textOnly; + assertThat(encoder.canEncode(forClass(String.class), MediaType.TEXT_EVENT_STREAM)).isEqualTo(expected); } private void assertSseReader(List> readers) { HttpMessageReader reader = readers.get(this.index.getAndIncrement()); - assertEquals(ServerSentEventHttpMessageReader.class, reader.getClass()); + assertThat(reader.getClass()).isEqualTo(ServerSentEventHttpMessageReader.class); Decoder decoder = ((ServerSentEventHttpMessageReader) reader).getDecoder(); - assertNotNull(decoder); - assertEquals(Jackson2JsonDecoder.class, decoder.getClass()); + assertThat(decoder).isNotNull(); + assertThat(decoder.getClass()).isEqualTo(Jackson2JsonDecoder.class); } } diff --git a/spring-web/src/test/java/org/springframework/http/codec/support/CodecConfigurerTests.java b/spring-web/src/test/java/org/springframework/http/codec/support/CodecConfigurerTests.java index beaf78e945a..a3cadd4e234 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/support/CodecConfigurerTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/support/CodecConfigurerTests.java @@ -53,9 +53,7 @@ import org.springframework.http.codec.xml.Jaxb2XmlDecoder; import org.springframework.http.codec.xml.Jaxb2XmlEncoder; import org.springframework.util.MimeTypeUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -75,33 +73,33 @@ public class CodecConfigurerTests { @Test public void defaultReaders() { List> readers = this.configurer.getReaders(); - assertEquals(11, readers.size()); - assertEquals(ByteArrayDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(ByteBufferDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(DataBufferDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(ResourceHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); + assertThat(readers.size()).isEqualTo(11); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ByteArrayDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ByteBufferDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(DataBufferDecoder.class); + assertThat(readers.get(this.index.getAndIncrement()).getClass()).isEqualTo(ResourceHttpMessageReader.class); assertStringDecoder(getNextDecoder(readers), true); - assertEquals(ProtobufDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(FormHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); - assertEquals(Jackson2JsonDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(Jackson2SmileDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(Jaxb2XmlDecoder.class, getNextDecoder(readers).getClass()); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ProtobufDecoder.class); + assertThat(readers.get(this.index.getAndIncrement()).getClass()).isEqualTo(FormHttpMessageReader.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jackson2JsonDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jackson2SmileDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jaxb2XmlDecoder.class); assertStringDecoder(getNextDecoder(readers), false); } @Test public void defaultWriters() { List> writers = this.configurer.getWriters(); - assertEquals(10, writers.size()); - assertEquals(ByteArrayEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(ByteBufferEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(DataBufferEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(ResourceHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass()); + assertThat(writers.size()).isEqualTo(10); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(ByteArrayEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(ByteBufferEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(DataBufferEncoder.class); + assertThat(writers.get(index.getAndIncrement()).getClass()).isEqualTo(ResourceHttpMessageWriter.class); assertStringEncoder(getNextEncoder(writers), true); - assertEquals(ProtobufHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass()); - assertEquals(Jackson2JsonEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(Jackson2SmileEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(Jaxb2XmlEncoder.class, getNextEncoder(writers).getClass()); + assertThat(writers.get(index.getAndIncrement()).getClass()).isEqualTo(ProtobufHttpMessageWriter.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jackson2JsonEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jackson2SmileEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jaxb2XmlEncoder.class); assertStringEncoder(getNextEncoder(writers), false); } @@ -127,22 +125,22 @@ public class CodecConfigurerTests { List> readers = this.configurer.getReaders(); - assertEquals(15, readers.size()); - assertSame(customDecoder1, getNextDecoder(readers)); - assertSame(customReader1, readers.get(this.index.getAndIncrement())); - assertEquals(ByteArrayDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(ByteBufferDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(DataBufferDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(ResourceHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); - assertEquals(StringDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(ProtobufDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(FormHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); - assertSame(customDecoder2, getNextDecoder(readers)); - assertSame(customReader2, readers.get(this.index.getAndIncrement())); - assertEquals(Jackson2JsonDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(Jackson2SmileDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(Jaxb2XmlDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(StringDecoder.class, getNextDecoder(readers).getClass()); + assertThat(readers.size()).isEqualTo(15); + assertThat(getNextDecoder(readers)).isSameAs(customDecoder1); + assertThat(readers.get(this.index.getAndIncrement())).isSameAs(customReader1); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ByteArrayDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ByteBufferDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(DataBufferDecoder.class); + assertThat(readers.get(this.index.getAndIncrement()).getClass()).isEqualTo(ResourceHttpMessageReader.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(StringDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ProtobufDecoder.class); + assertThat(readers.get(this.index.getAndIncrement()).getClass()).isEqualTo(FormHttpMessageReader.class); + assertThat(getNextDecoder(readers)).isSameAs(customDecoder2); + assertThat(readers.get(this.index.getAndIncrement())).isSameAs(customReader2); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jackson2JsonDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jackson2SmileDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jaxb2XmlDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(StringDecoder.class); } @Test @@ -167,21 +165,21 @@ public class CodecConfigurerTests { List> writers = this.configurer.getWriters(); - assertEquals(14, writers.size()); - assertSame(customEncoder1, getNextEncoder(writers)); - assertSame(customWriter1, writers.get(this.index.getAndIncrement())); - assertEquals(ByteArrayEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(ByteBufferEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(DataBufferEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(ResourceHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass()); - assertEquals(CharSequenceEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(ProtobufHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass()); - assertSame(customEncoder2, getNextEncoder(writers)); - assertSame(customWriter2, writers.get(this.index.getAndIncrement())); - assertEquals(Jackson2JsonEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(Jackson2SmileEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(Jaxb2XmlEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(CharSequenceEncoder.class, getNextEncoder(writers).getClass()); + assertThat(writers.size()).isEqualTo(14); + assertThat(getNextEncoder(writers)).isSameAs(customEncoder1); + assertThat(writers.get(this.index.getAndIncrement())).isSameAs(customWriter1); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(ByteArrayEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(ByteBufferEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(DataBufferEncoder.class); + assertThat(writers.get(index.getAndIncrement()).getClass()).isEqualTo(ResourceHttpMessageWriter.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(CharSequenceEncoder.class); + assertThat(writers.get(index.getAndIncrement()).getClass()).isEqualTo(ProtobufHttpMessageWriter.class); + assertThat(getNextEncoder(writers)).isSameAs(customEncoder2); + assertThat(writers.get(this.index.getAndIncrement())).isSameAs(customWriter2); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jackson2JsonEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jackson2SmileEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jaxb2XmlEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(CharSequenceEncoder.class); } @Test @@ -208,11 +206,11 @@ public class CodecConfigurerTests { List> readers = this.configurer.getReaders(); - assertEquals(4, readers.size()); - assertSame(customDecoder1, getNextDecoder(readers)); - assertSame(customReader1, readers.get(this.index.getAndIncrement())); - assertSame(customDecoder2, getNextDecoder(readers)); - assertSame(customReader2, readers.get(this.index.getAndIncrement())); + assertThat(readers.size()).isEqualTo(4); + assertThat(getNextDecoder(readers)).isSameAs(customDecoder1); + assertThat(readers.get(this.index.getAndIncrement())).isSameAs(customReader1); + assertThat(getNextDecoder(readers)).isSameAs(customDecoder2); + assertThat(readers.get(this.index.getAndIncrement())).isSameAs(customReader2); } @Test @@ -239,11 +237,11 @@ public class CodecConfigurerTests { List> writers = this.configurer.getWriters(); - assertEquals(4, writers.size()); - assertSame(customEncoder1, getNextEncoder(writers)); - assertSame(customWriter1, writers.get(this.index.getAndIncrement())); - assertSame(customEncoder2, getNextEncoder(writers)); - assertSame(customWriter2, writers.get(this.index.getAndIncrement())); + assertThat(writers.size()).isEqualTo(4); + assertThat(getNextEncoder(writers)).isSameAs(customEncoder1); + assertThat(writers.get(this.index.getAndIncrement())).isSameAs(customWriter1); + assertThat(getNextEncoder(writers)).isSameAs(customEncoder2); + assertThat(writers.get(this.index.getAndIncrement())).isSameAs(customWriter2); } @Test @@ -272,44 +270,46 @@ public class CodecConfigurerTests { private Decoder getNextDecoder(List> readers) { HttpMessageReader reader = readers.get(this.index.getAndIncrement()); - assertEquals(DecoderHttpMessageReader.class, reader.getClass()); + assertThat(reader.getClass()).isEqualTo(DecoderHttpMessageReader.class); return ((DecoderHttpMessageReader) reader).getDecoder(); } private Encoder getNextEncoder(List> writers) { HttpMessageWriter writer = writers.get(this.index.getAndIncrement()); - assertEquals(EncoderHttpMessageWriter.class, writer.getClass()); + assertThat(writer.getClass()).isEqualTo(EncoderHttpMessageWriter.class); return ((EncoderHttpMessageWriter) writer).getEncoder(); } private void assertStringDecoder(Decoder decoder, boolean textOnly) { - assertEquals(StringDecoder.class, decoder.getClass()); - assertTrue(decoder.canDecode(ResolvableType.forClass(String.class), MimeTypeUtils.TEXT_PLAIN)); - assertEquals(!textOnly, decoder.canDecode(ResolvableType.forClass(String.class), MediaType.TEXT_EVENT_STREAM)); + assertThat(decoder.getClass()).isEqualTo(StringDecoder.class); + assertThat(decoder.canDecode(ResolvableType.forClass(String.class), MimeTypeUtils.TEXT_PLAIN)).isTrue(); + Object expected = !textOnly; + assertThat(decoder.canDecode(ResolvableType.forClass(String.class), MediaType.TEXT_EVENT_STREAM)).isEqualTo(expected); } private void assertStringEncoder(Encoder encoder, boolean textOnly) { - assertEquals(CharSequenceEncoder.class, encoder.getClass()); - assertTrue(encoder.canEncode(ResolvableType.forClass(String.class), MimeTypeUtils.TEXT_PLAIN)); - assertEquals(!textOnly, encoder.canEncode(ResolvableType.forClass(String.class), MediaType.TEXT_EVENT_STREAM)); + assertThat(encoder.getClass()).isEqualTo(CharSequenceEncoder.class); + assertThat(encoder.canEncode(ResolvableType.forClass(String.class), MimeTypeUtils.TEXT_PLAIN)).isTrue(); + Object expected = !textOnly; + assertThat(encoder.canEncode(ResolvableType.forClass(String.class), MediaType.TEXT_EVENT_STREAM)).isEqualTo(expected); } private void assertDecoderInstance(Decoder decoder) { - assertSame(decoder, this.configurer.getReaders().stream() + assertThat(this.configurer.getReaders().stream() .filter(writer -> writer instanceof DecoderHttpMessageReader) .map(writer -> ((DecoderHttpMessageReader) writer).getDecoder()) .filter(e -> decoder.getClass().equals(e.getClass())) .findFirst() - .filter(e -> e == decoder).orElse(null)); + .filter(e -> e == decoder).orElse(null)).isSameAs(decoder); } private void assertEncoderInstance(Encoder encoder) { - assertSame(encoder, this.configurer.getWriters().stream() + assertThat(this.configurer.getWriters().stream() .filter(writer -> writer instanceof EncoderHttpMessageWriter) .map(writer -> ((EncoderHttpMessageWriter) writer).getEncoder()) .filter(e -> encoder.getClass().equals(e.getClass())) .findFirst() - .filter(e -> e == encoder).orElse(null)); + .filter(e -> e == encoder).orElse(null)).isSameAs(encoder); } diff --git a/spring-web/src/test/java/org/springframework/http/codec/support/ServerCodecConfigurerTests.java b/spring-web/src/test/java/org/springframework/http/codec/support/ServerCodecConfigurerTests.java index f6a8ee6c5de..1f8116e0771 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/support/ServerCodecConfigurerTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/support/ServerCodecConfigurerTests.java @@ -60,10 +60,7 @@ import org.springframework.http.codec.xml.Jaxb2XmlDecoder; import org.springframework.http.codec.xml.Jaxb2XmlEncoder; import org.springframework.util.MimeTypeUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.ResolvableType.forClass; /** @@ -81,35 +78,35 @@ public class ServerCodecConfigurerTests { @Test public void defaultReaders() { List> readers = this.configurer.getReaders(); - assertEquals(13, readers.size()); - assertEquals(ByteArrayDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(ByteBufferDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(DataBufferDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(ResourceHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); + assertThat(readers.size()).isEqualTo(13); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ByteArrayDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ByteBufferDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(DataBufferDecoder.class); + assertThat(readers.get(this.index.getAndIncrement()).getClass()).isEqualTo(ResourceHttpMessageReader.class); assertStringDecoder(getNextDecoder(readers), true); - assertEquals(ProtobufDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(FormHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); - assertEquals(DefaultMultipartMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); - assertEquals(MultipartHttpMessageReader.class, readers.get(this.index.getAndIncrement()).getClass()); - assertEquals(Jackson2JsonDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(Jackson2SmileDecoder.class, getNextDecoder(readers).getClass()); - assertEquals(Jaxb2XmlDecoder.class, getNextDecoder(readers).getClass()); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(ProtobufDecoder.class); + assertThat(readers.get(this.index.getAndIncrement()).getClass()).isEqualTo(FormHttpMessageReader.class); + assertThat(readers.get(this.index.getAndIncrement()).getClass()).isEqualTo(DefaultMultipartMessageReader.class); + assertThat(readers.get(this.index.getAndIncrement()).getClass()).isEqualTo(MultipartHttpMessageReader.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jackson2JsonDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jackson2SmileDecoder.class); + assertThat(getNextDecoder(readers).getClass()).isEqualTo(Jaxb2XmlDecoder.class); assertStringDecoder(getNextDecoder(readers), false); } @Test public void defaultWriters() { List> writers = this.configurer.getWriters(); - assertEquals(11, writers.size()); - assertEquals(ByteArrayEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(ByteBufferEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(DataBufferEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(ResourceHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass()); + assertThat(writers.size()).isEqualTo(11); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(ByteArrayEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(ByteBufferEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(DataBufferEncoder.class); + assertThat(writers.get(index.getAndIncrement()).getClass()).isEqualTo(ResourceHttpMessageWriter.class); assertStringEncoder(getNextEncoder(writers), true); - assertEquals(ProtobufHttpMessageWriter.class, writers.get(index.getAndIncrement()).getClass()); - assertEquals(Jackson2JsonEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(Jackson2SmileEncoder.class, getNextEncoder(writers).getClass()); - assertEquals(Jaxb2XmlEncoder.class, getNextEncoder(writers).getClass()); + assertThat(writers.get(index.getAndIncrement()).getClass()).isEqualTo(ProtobufHttpMessageWriter.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jackson2JsonEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jackson2SmileEncoder.class); + assertThat(getNextEncoder(writers).getClass()).isEqualTo(Jaxb2XmlEncoder.class); assertSseWriter(writers); assertStringEncoder(getNextEncoder(writers), false); } @@ -119,52 +116,54 @@ public class ServerCodecConfigurerTests { Jackson2JsonEncoder encoder = new Jackson2JsonEncoder(); this.configurer.defaultCodecs().jackson2JsonEncoder(encoder); - assertSame(encoder, this.configurer.getWriters().stream() + assertThat(this.configurer.getWriters().stream() .filter(writer -> ServerSentEventHttpMessageWriter.class.equals(writer.getClass())) .map(writer -> (ServerSentEventHttpMessageWriter) writer) .findFirst() .map(ServerSentEventHttpMessageWriter::getEncoder) - .filter(e -> e == encoder).orElse(null)); + .filter(e -> e == encoder).orElse(null)).isSameAs(encoder); } private Decoder getNextDecoder(List> readers) { HttpMessageReader reader = readers.get(this.index.getAndIncrement()); - assertEquals(DecoderHttpMessageReader.class, reader.getClass()); + assertThat(reader.getClass()).isEqualTo(DecoderHttpMessageReader.class); return ((DecoderHttpMessageReader) reader).getDecoder(); } private Encoder getNextEncoder(List> writers) { HttpMessageWriter writer = writers.get(this.index.getAndIncrement()); - assertEquals(EncoderHttpMessageWriter.class, writer.getClass()); + assertThat(writer.getClass()).isEqualTo(EncoderHttpMessageWriter.class); return ((EncoderHttpMessageWriter) writer).getEncoder(); } @SuppressWarnings("unchecked") private void assertStringDecoder(Decoder decoder, boolean textOnly) { - assertEquals(StringDecoder.class, decoder.getClass()); - assertTrue(decoder.canDecode(forClass(String.class), MimeTypeUtils.TEXT_PLAIN)); - assertEquals(!textOnly, decoder.canDecode(forClass(String.class), MediaType.TEXT_EVENT_STREAM)); + assertThat(decoder.getClass()).isEqualTo(StringDecoder.class); + assertThat(decoder.canDecode(forClass(String.class), MimeTypeUtils.TEXT_PLAIN)).isTrue(); + Object expected = !textOnly; + assertThat(decoder.canDecode(forClass(String.class), MediaType.TEXT_EVENT_STREAM)).isEqualTo(expected); Flux flux = (Flux) decoder.decode( Flux.just(new DefaultDataBufferFactory().wrap("line1\nline2".getBytes(StandardCharsets.UTF_8))), ResolvableType.forClass(String.class), MimeTypeUtils.TEXT_PLAIN, Collections.emptyMap()); - assertEquals(Arrays.asList("line1", "line2"), flux.collectList().block(Duration.ZERO)); + assertThat(flux.collectList().block(Duration.ZERO)).isEqualTo(Arrays.asList("line1", "line2")); } private void assertStringEncoder(Encoder encoder, boolean textOnly) { - assertEquals(CharSequenceEncoder.class, encoder.getClass()); - assertTrue(encoder.canEncode(forClass(String.class), MimeTypeUtils.TEXT_PLAIN)); - assertEquals(!textOnly, encoder.canEncode(forClass(String.class), MediaType.TEXT_EVENT_STREAM)); + assertThat(encoder.getClass()).isEqualTo(CharSequenceEncoder.class); + assertThat(encoder.canEncode(forClass(String.class), MimeTypeUtils.TEXT_PLAIN)).isTrue(); + Object expected = !textOnly; + assertThat(encoder.canEncode(forClass(String.class), MediaType.TEXT_EVENT_STREAM)).isEqualTo(expected); } private void assertSseWriter(List> writers) { HttpMessageWriter writer = writers.get(this.index.getAndIncrement()); - assertEquals(ServerSentEventHttpMessageWriter.class, writer.getClass()); + assertThat(writer.getClass()).isEqualTo(ServerSentEventHttpMessageWriter.class); Encoder encoder = ((ServerSentEventHttpMessageWriter) writer).getEncoder(); - assertNotNull(encoder); - assertEquals(Jackson2JsonEncoder.class, encoder.getClass()); + assertThat(encoder).isNotNull(); + assertThat(encoder.getClass()).isEqualTo(Jackson2JsonEncoder.class); } } diff --git a/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlDecoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlDecoderTests.java index 36c8db800e7..43e1c3e0100 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlDecoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlDecoderTests.java @@ -39,9 +39,7 @@ import org.springframework.http.codec.xml.jaxb.XmlType; import org.springframework.http.codec.xml.jaxb.XmlTypeWithName; import org.springframework.http.codec.xml.jaxb.XmlTypeWithNameAndNamespace; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze @@ -75,16 +73,16 @@ public class Jaxb2XmlDecoderTests extends AbstractLeakCheckingTestCase { @Test public void canDecode() { - assertTrue(this.decoder.canDecode(ResolvableType.forClass(Pojo.class), - MediaType.APPLICATION_XML)); - assertTrue(this.decoder.canDecode(ResolvableType.forClass(Pojo.class), - MediaType.TEXT_XML)); - assertFalse(this.decoder.canDecode(ResolvableType.forClass(Pojo.class), - MediaType.APPLICATION_JSON)); - assertTrue(this.decoder.canDecode(ResolvableType.forClass(TypePojo.class), - MediaType.APPLICATION_XML)); - assertFalse(this.decoder.canDecode(ResolvableType.forClass(getClass()), - MediaType.APPLICATION_XML)); + assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class), + MediaType.APPLICATION_XML)).isTrue(); + assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class), + MediaType.TEXT_XML)).isTrue(); + assertThat(this.decoder.canDecode(ResolvableType.forClass(Pojo.class), + MediaType.APPLICATION_JSON)).isFalse(); + assertThat(this.decoder.canDecode(ResolvableType.forClass(TypePojo.class), + MediaType.APPLICATION_XML)).isTrue(); + assertThat(this.decoder.canDecode(ResolvableType.forClass(getClass()), + MediaType.APPLICATION_XML)).isFalse(); } @Test @@ -95,7 +93,7 @@ public class Jaxb2XmlDecoderTests extends AbstractLeakCheckingTestCase { StepVerifier.create(result) .consumeNextWith(events -> { - assertEquals(8, events.size()); + assertThat(events.size()).isEqualTo(8); assertStartElement(events.get(0), "pojo"); assertStartElement(events.get(1), "foo"); assertCharacters(events.get(2), "foofoo"); @@ -118,7 +116,7 @@ public class Jaxb2XmlDecoderTests extends AbstractLeakCheckingTestCase { StepVerifier.create(result) .consumeNextWith(events -> { - assertEquals(8, events.size()); + assertThat(events.size()).isEqualTo(8); assertStartElement(events.get(0), "pojo"); assertStartElement(events.get(1), "foo"); assertCharacters(events.get(2), "foo"); @@ -129,7 +127,7 @@ public class Jaxb2XmlDecoderTests extends AbstractLeakCheckingTestCase { assertEndElement(events.get(7), "pojo"); }) .consumeNextWith(events -> { - assertEquals(8, events.size()); + assertThat(events.size()).isEqualTo(8); assertStartElement(events.get(0), "pojo"); assertStartElement(events.get(1), "foo"); assertCharacters(events.get(2), "foofoo"); @@ -144,18 +142,18 @@ public class Jaxb2XmlDecoderTests extends AbstractLeakCheckingTestCase { } private static void assertStartElement(XMLEvent event, String expectedLocalName) { - assertTrue(event.isStartElement()); - assertEquals(expectedLocalName, event.asStartElement().getName().getLocalPart()); + assertThat(event.isStartElement()).isTrue(); + assertThat(event.asStartElement().getName().getLocalPart()).isEqualTo(expectedLocalName); } private static void assertEndElement(XMLEvent event, String expectedLocalName) { - assertTrue(event.isEndElement()); - assertEquals(expectedLocalName, event.asEndElement().getName().getLocalPart()); + assertThat(event.isEndElement()).isTrue(); + assertThat(event.asEndElement().getName().getLocalPart()).isEqualTo(expectedLocalName); } private static void assertCharacters(XMLEvent event, String expectedData) { - assertTrue(event.isCharacters()); - assertEquals(expectedData, event.asCharacters().getData()); + assertThat(event.isCharacters()).isTrue(); + assertThat(event.asCharacters().getData()).isEqualTo(expectedData); } @Test @@ -224,22 +222,16 @@ public class Jaxb2XmlDecoderTests extends AbstractLeakCheckingTestCase { @Test public void toExpectedQName() { - assertEquals(new QName("pojo"), this.decoder.toQName(Pojo.class)); - assertEquals(new QName("pojo"), this.decoder.toQName(TypePojo.class)); + assertThat(this.decoder.toQName(Pojo.class)).isEqualTo(new QName("pojo")); + assertThat(this.decoder.toQName(TypePojo.class)).isEqualTo(new QName("pojo")); - assertEquals(new QName("namespace", "name"), - this.decoder.toQName(XmlRootElementWithNameAndNamespace.class)); - assertEquals(new QName("namespace", "name"), - this.decoder.toQName(XmlRootElementWithName.class)); - assertEquals(new QName("namespace", "xmlRootElement"), - this.decoder.toQName(XmlRootElement.class)); + assertThat(this.decoder.toQName(XmlRootElementWithNameAndNamespace.class)).isEqualTo(new QName("namespace", "name")); + assertThat(this.decoder.toQName(XmlRootElementWithName.class)).isEqualTo(new QName("namespace", "name")); + assertThat(this.decoder.toQName(XmlRootElement.class)).isEqualTo(new QName("namespace", "xmlRootElement")); - assertEquals(new QName("namespace", "name"), - this.decoder.toQName(XmlTypeWithNameAndNamespace.class)); - assertEquals(new QName("namespace", "name"), - this.decoder.toQName(XmlTypeWithName.class)); - assertEquals(new QName("namespace", "xmlType"), - this.decoder.toQName(XmlType.class)); + assertThat(this.decoder.toQName(XmlTypeWithNameAndNamespace.class)).isEqualTo(new QName("namespace", "name")); + assertThat(this.decoder.toQName(XmlTypeWithName.class)).isEqualTo(new QName("namespace", "name")); + assertThat(this.decoder.toQName(XmlType.class)).isEqualTo(new QName("namespace", "xmlType")); } diff --git a/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlEncoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlEncoderTests.java index 9f241c09046..5d2711b1ae5 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlEncoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlEncoderTests.java @@ -36,8 +36,6 @@ import org.springframework.tests.XmlContent; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.springframework.core.io.buffer.DataBufferUtils.release; /** @@ -53,22 +51,22 @@ public class Jaxb2XmlEncoderTests extends AbstractEncoderTestCase assertTrue(e.isStartDocument())) + .consumeNextWith(e -> assertThat(e.isStartDocument()).isTrue()) .consumeNextWith(e -> assertStartElement(e, "pojo")) .consumeNextWith(e -> assertStartElement(e, "foo")) .consumeNextWith(e -> assertCharacters(e, "foofoo")) @@ -72,7 +71,7 @@ public class XmlEventDecoderTests extends AbstractLeakCheckingTestCase { this.decoder.decode(stringBuffer(XML), null, null, Collections.emptyMap()); StepVerifier.create(events) - .consumeNextWith(e -> assertTrue(e.isStartDocument())) + .consumeNextWith(e -> assertThat(e.isStartDocument()).isTrue()) .consumeNextWith(e -> assertStartElement(e, "pojo")) .consumeNextWith(e -> assertStartElement(e, "foo")) .consumeNextWith(e -> assertCharacters(e, "foofoo")) @@ -81,7 +80,7 @@ public class XmlEventDecoderTests extends AbstractLeakCheckingTestCase { .consumeNextWith(e -> assertCharacters(e, "barbar")) .consumeNextWith(e -> assertEndElement(e, "bar")) .consumeNextWith(e -> assertEndElement(e, "pojo")) - .consumeNextWith(e -> assertTrue(e.isEndDocument())) + .consumeNextWith(e -> assertThat(e.isEndDocument()).isTrue()) .expectComplete() .verify(); } @@ -96,7 +95,7 @@ public class XmlEventDecoderTests extends AbstractLeakCheckingTestCase { this.decoder.decode(source, null, null, Collections.emptyMap()); StepVerifier.create(events) - .consumeNextWith(e -> assertTrue(e.isStartDocument())) + .consumeNextWith(e -> assertThat(e.isStartDocument()).isTrue()) .consumeNextWith(e -> assertStartElement(e, "pojo")) .expectError(RuntimeException.class) .verify(); @@ -119,18 +118,18 @@ public class XmlEventDecoderTests extends AbstractLeakCheckingTestCase { } private static void assertStartElement(XMLEvent event, String expectedLocalName) { - assertTrue(event.isStartElement()); - assertEquals(expectedLocalName, event.asStartElement().getName().getLocalPart()); + assertThat(event.isStartElement()).isTrue(); + assertThat(event.asStartElement().getName().getLocalPart()).isEqualTo(expectedLocalName); } private static void assertEndElement(XMLEvent event, String expectedLocalName) { - assertTrue(event + " is no end element", event.isEndElement()); - assertEquals(expectedLocalName, event.asEndElement().getName().getLocalPart()); + assertThat(event.isEndElement()).as(event + " is no end element").isTrue(); + assertThat(event.asEndElement().getName().getLocalPart()).isEqualTo(expectedLocalName); } private static void assertCharacters(XMLEvent event, String expectedData) { - assertTrue(event.isCharacters()); - assertEquals(expectedData, event.asCharacters().getData()); + assertThat(event.isCharacters()).isTrue(); + assertThat(event.asCharacters().getData()).isEqualTo(expectedData); } private Mono stringBuffer(String value) { diff --git a/spring-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java index f5e97f7c2eb..3bea616317d 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java @@ -31,8 +31,7 @@ import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; import org.springframework.util.FileCopyUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for BufferedImageHttpMessageConverter. @@ -50,15 +49,15 @@ public class BufferedImageHttpMessageConverterTests { @Test public void canRead() { - assertTrue("Image not supported", converter.canRead(BufferedImage.class, null)); - assertTrue("Image not supported", converter.canRead(BufferedImage.class, new MediaType("image", "png"))); + assertThat(converter.canRead(BufferedImage.class, null)).as("Image not supported").isTrue(); + assertThat(converter.canRead(BufferedImage.class, new MediaType("image", "png"))).as("Image not supported").isTrue(); } @Test public void canWrite() { - assertTrue("Image not supported", converter.canWrite(BufferedImage.class, null)); - assertTrue("Image not supported", converter.canWrite(BufferedImage.class, new MediaType("image", "png"))); - assertTrue("Image not supported", converter.canWrite(BufferedImage.class, new MediaType("*", "*"))); + assertThat(converter.canWrite(BufferedImage.class, null)).as("Image not supported").isTrue(); + assertThat(converter.canWrite(BufferedImage.class, new MediaType("image", "png"))).as("Image not supported").isTrue(); + assertThat(converter.canWrite(BufferedImage.class, new MediaType("*", "*"))).as("Image not supported").isTrue(); } @Test @@ -68,8 +67,8 @@ public class BufferedImageHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); inputMessage.getHeaders().setContentType(new MediaType("image", "jpeg")); BufferedImage result = converter.read(BufferedImage.class, inputMessage); - assertEquals("Invalid height", 500, result.getHeight()); - assertEquals("Invalid width", 750, result.getWidth()); + assertThat(result.getHeight()).as("Invalid height").isEqualTo(500); + assertThat(result.getWidth()).as("Invalid width").isEqualTo(750); } @Test @@ -79,11 +78,11 @@ public class BufferedImageHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MediaType contentType = new MediaType("image", "png"); converter.write(body, contentType, outputMessage); - assertEquals("Invalid content type", contentType, outputMessage.getWrittenHeaders().getContentType()); - assertTrue("Invalid size", outputMessage.getBodyAsBytes().length > 0); + assertThat(outputMessage.getWrittenHeaders().getContentType()).as("Invalid content type").isEqualTo(contentType); + assertThat(outputMessage.getBodyAsBytes().length > 0).as("Invalid size").isTrue(); BufferedImage result = ImageIO.read(new ByteArrayInputStream(outputMessage.getBodyAsBytes())); - assertEquals("Invalid height", 500, result.getHeight()); - assertEquals("Invalid width", 750, result.getWidth()); + assertThat(result.getHeight()).as("Invalid height").isEqualTo(500); + assertThat(result.getWidth()).as("Invalid width").isEqualTo(750); } @Test @@ -94,11 +93,11 @@ public class BufferedImageHttpMessageConverterTests { BufferedImage body = ImageIO.read(logo.getFile()); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(body, new MediaType("*", "*"), outputMessage); - assertEquals("Invalid content type", contentType, outputMessage.getWrittenHeaders().getContentType()); - assertTrue("Invalid size", outputMessage.getBodyAsBytes().length > 0); + assertThat(outputMessage.getWrittenHeaders().getContentType()).as("Invalid content type").isEqualTo(contentType); + assertThat(outputMessage.getBodyAsBytes().length > 0).as("Invalid size").isTrue(); BufferedImage result = ImageIO.read(new ByteArrayInputStream(outputMessage.getBodyAsBytes())); - assertEquals("Invalid height", 500, result.getHeight()); - assertEquals("Invalid width", 750, result.getWidth()); + assertThat(result.getHeight()).as("Invalid height").isEqualTo(500); + assertThat(result.getWidth()).as("Invalid width").isEqualTo(750); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/ByteArrayHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/ByteArrayHttpMessageConverterTests.java index e00d0d2893c..194e9c80541 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/ByteArrayHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/ByteArrayHttpMessageConverterTests.java @@ -25,9 +25,7 @@ import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** @author Arjen Poutsma */ public class ByteArrayHttpMessageConverterTests { @@ -41,13 +39,13 @@ public class ByteArrayHttpMessageConverterTests { @Test public void canRead() { - assertTrue(converter.canRead(byte[].class, new MediaType("application", "octet-stream"))); + assertThat(converter.canRead(byte[].class, new MediaType("application", "octet-stream"))).isTrue(); } @Test public void canWrite() { - assertTrue(converter.canWrite(byte[].class, new MediaType("application", "octet-stream"))); - assertTrue(converter.canWrite(byte[].class, MediaType.ALL)); + assertThat(converter.canWrite(byte[].class, new MediaType("application", "octet-stream"))).isTrue(); + assertThat(converter.canWrite(byte[].class, MediaType.ALL)).isTrue(); } @Test @@ -56,7 +54,7 @@ public class ByteArrayHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); inputMessage.getHeaders().setContentType(new MediaType("application", "octet-stream")); byte[] result = converter.read(byte[].class, inputMessage); - assertArrayEquals("Invalid result", body, result); + assertThat(result).as("Invalid result").isEqualTo(body); } @Test @@ -64,10 +62,9 @@ public class ByteArrayHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); byte[] body = new byte[]{0x1, 0x2}; converter.write(body, null, outputMessage); - assertArrayEquals("Invalid result", body, outputMessage.getBodyAsBytes()); - assertEquals("Invalid content-type", new MediaType("application", "octet-stream"), - outputMessage.getHeaders().getContentType()); - assertEquals("Invalid content-length", 2, outputMessage.getHeaders().getContentLength()); + assertThat(outputMessage.getBodyAsBytes()).as("Invalid result").isEqualTo(body); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "octet-stream")); + assertThat(outputMessage.getHeaders().getContentLength()).as("Invalid content-length").isEqualTo(2); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java index b76d2a07ce4..1a538970208 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java @@ -44,11 +44,6 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -63,21 +58,21 @@ public class FormHttpMessageConverterTests { @Test public void canRead() { - assertTrue(this.converter.canRead(MultiValueMap.class, - new MediaType("application", "x-www-form-urlencoded"))); - assertFalse(this.converter.canRead(MultiValueMap.class, - new MediaType("multipart", "form-data"))); + assertThat(this.converter.canRead(MultiValueMap.class, + new MediaType("application", "x-www-form-urlencoded"))).isTrue(); + assertThat(this.converter.canRead(MultiValueMap.class, + new MediaType("multipart", "form-data"))).isFalse(); } @Test public void canWrite() { - assertTrue(this.converter.canWrite(MultiValueMap.class, - new MediaType("application", "x-www-form-urlencoded"))); - assertTrue(this.converter.canWrite(MultiValueMap.class, - new MediaType("multipart", "form-data"))); - assertTrue(this.converter.canWrite(MultiValueMap.class, - new MediaType("multipart", "form-data", StandardCharsets.UTF_8))); - assertTrue(this.converter.canWrite(MultiValueMap.class, MediaType.ALL)); + assertThat(this.converter.canWrite(MultiValueMap.class, + new MediaType("application", "x-www-form-urlencoded"))).isTrue(); + assertThat(this.converter.canWrite(MultiValueMap.class, + new MediaType("multipart", "form-data"))).isTrue(); + assertThat(this.converter.canWrite(MultiValueMap.class, + new MediaType("multipart", "form-data", StandardCharsets.UTF_8))).isTrue(); + assertThat(this.converter.canWrite(MultiValueMap.class, MediaType.ALL)).isTrue(); } @Test @@ -88,13 +83,13 @@ public class FormHttpMessageConverterTests { new MediaType("application", "x-www-form-urlencoded", StandardCharsets.ISO_8859_1)); MultiValueMap result = this.converter.read(null, inputMessage); - assertEquals("Invalid result", 3, result.size()); - assertEquals("Invalid result", "value 1", result.getFirst("name 1")); + assertThat(result.size()).as("Invalid result").isEqualTo(3); + assertThat(result.getFirst("name 1")).as("Invalid result").isEqualTo("value 1"); List values = result.get("name 2"); - assertEquals("Invalid result", 2, values.size()); - assertEquals("Invalid result", "value 2+1", values.get(0)); - assertEquals("Invalid result", "value 2+2", values.get(1)); - assertNull("Invalid result", result.getFirst("name 3")); + assertThat(values.size()).as("Invalid result").isEqualTo(2); + assertThat(values.get(0)).as("Invalid result").isEqualTo("value 2+1"); + assertThat(values.get(1)).as("Invalid result").isEqualTo("value 2+2"); + assertThat(result.getFirst("name 3")).as("Invalid result").isNull(); } @Test @@ -107,12 +102,9 @@ public class FormHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); this.converter.write(body, MediaType.APPLICATION_FORM_URLENCODED, outputMessage); - assertEquals("Invalid result", "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3", - outputMessage.getBodyAsString(StandardCharsets.UTF_8)); - assertEquals("Invalid content-type", "application/x-www-form-urlencoded;charset=UTF-8", - outputMessage.getHeaders().getContentType().toString()); - assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length, - outputMessage.getHeaders().getContentLength()); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).as("Invalid result").isEqualTo("name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3"); + assertThat(outputMessage.getHeaders().getContentType().toString()).as("Invalid content-type").isEqualTo("application/x-www-form-urlencoded;charset=UTF-8"); + assertThat(outputMessage.getHeaders().getContentLength()).as("Invalid content-length").isEqualTo(outputMessage.getBodyAsBytes().length); } @Test @@ -153,39 +145,39 @@ public class FormHttpMessageConverterTests { FileUpload fileUpload = new FileUpload(fileItemFactory); RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage); List items = fileUpload.parseRequest(requestContext); - assertEquals(6, items.size()); + assertThat(items.size()).isEqualTo(6); FileItem item = items.get(0); - assertTrue(item.isFormField()); - assertEquals("name 1", item.getFieldName()); - assertEquals("value 1", item.getString()); + assertThat(item.isFormField()).isTrue(); + assertThat(item.getFieldName()).isEqualTo("name 1"); + assertThat(item.getString()).isEqualTo("value 1"); item = items.get(1); - assertTrue(item.isFormField()); - assertEquals("name 2", item.getFieldName()); - assertEquals("value 2+1", item.getString()); + assertThat(item.isFormField()).isTrue(); + assertThat(item.getFieldName()).isEqualTo("name 2"); + assertThat(item.getString()).isEqualTo("value 2+1"); item = items.get(2); - assertTrue(item.isFormField()); - assertEquals("name 2", item.getFieldName()); - assertEquals("value 2+2", item.getString()); + assertThat(item.isFormField()).isTrue(); + assertThat(item.getFieldName()).isEqualTo("name 2"); + assertThat(item.getString()).isEqualTo("value 2+2"); item = items.get(3); - assertFalse(item.isFormField()); - assertEquals("logo", item.getFieldName()); - assertEquals("logo.jpg", item.getName()); - assertEquals("image/jpeg", item.getContentType()); - assertEquals(logo.getFile().length(), item.getSize()); + assertThat(item.isFormField()).isFalse(); + assertThat(item.getFieldName()).isEqualTo("logo"); + assertThat(item.getName()).isEqualTo("logo.jpg"); + assertThat(item.getContentType()).isEqualTo("image/jpeg"); + assertThat(item.getSize()).isEqualTo(logo.getFile().length()); item = items.get(4); - assertFalse(item.isFormField()); - assertEquals("utf8", item.getFieldName()); - assertEquals("Hall\u00F6le.jpg", item.getName()); - assertEquals("image/jpeg", item.getContentType()); - assertEquals(logo.getFile().length(), item.getSize()); + assertThat(item.isFormField()).isFalse(); + assertThat(item.getFieldName()).isEqualTo("utf8"); + assertThat(item.getName()).isEqualTo("Hall\u00F6le.jpg"); + assertThat(item.getContentType()).isEqualTo("image/jpeg"); + assertThat(item.getSize()).isEqualTo(logo.getFile().length()); item = items.get(5); - assertEquals("xml", item.getFieldName()); - assertEquals("text/xml", item.getContentType()); + assertThat(item.getFieldName()).isEqualTo("xml"); + assertThat(item.getContentType()).isEqualTo("text/xml"); verify(outputMessage.getBody(), never()).close(); } @@ -209,23 +201,23 @@ public class FormHttpMessageConverterTests { this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage); final MediaType contentType = outputMessage.getHeaders().getContentType(); - assertNotNull("No boundary found", contentType.getParameter("boundary")); + assertThat(contentType.getParameter("boundary")).as("No boundary found").isNotNull(); // see if Commons FileUpload can read what we wrote FileItemFactory fileItemFactory = new DiskFileItemFactory(); FileUpload fileUpload = new FileUpload(fileItemFactory); RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage); List items = fileUpload.parseRequest(requestContext); - assertEquals(2, items.size()); + assertThat(items.size()).isEqualTo(2); FileItem item = items.get(0); - assertTrue(item.isFormField()); - assertEquals("part1", item.getFieldName()); - assertEquals("{\"string\":\"foo\"}", item.getString()); + assertThat(item.isFormField()).isTrue(); + assertThat(item.getFieldName()).isEqualTo("part1"); + assertThat(item.getString()).isEqualTo("{\"string\":\"foo\"}"); item = items.get(1); - assertTrue(item.isFormField()); - assertEquals("part2", item.getFieldName()); + assertThat(item.isFormField()).isTrue(); + assertThat(item.getFieldName()).isEqualTo("part2"); // With developer builds we get: foo // But on CI server we get: foo diff --git a/spring-web/src/test/java/org/springframework/http/converter/HttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/HttpMessageConverterTests.java index 8d229cd45ce..e37c5768b77 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/HttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/HttpMessageConverterTests.java @@ -24,8 +24,7 @@ import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test-case for AbstractHttpMessageConverter. @@ -41,9 +40,9 @@ public class HttpMessageConverterTests { MediaType mediaType = new MediaType("foo", "bar"); HttpMessageConverter converter = new MyHttpMessageConverter<>(mediaType); - assertTrue(converter.canRead(MyType.class, mediaType)); - assertFalse(converter.canRead(MyType.class, new MediaType("foo", "*"))); - assertFalse(converter.canRead(MyType.class, MediaType.ALL)); + assertThat(converter.canRead(MyType.class, mediaType)).isTrue(); + assertThat(converter.canRead(MyType.class, new MediaType("foo", "*"))).isFalse(); + assertThat(converter.canRead(MyType.class, MediaType.ALL)).isFalse(); } @Test @@ -51,9 +50,9 @@ public class HttpMessageConverterTests { MediaType mediaType = new MediaType("foo"); HttpMessageConverter converter = new MyHttpMessageConverter<>(mediaType); - assertTrue(converter.canRead(MyType.class, new MediaType("foo", "bar"))); - assertTrue(converter.canRead(MyType.class, new MediaType("foo", "*"))); - assertFalse(converter.canRead(MyType.class, MediaType.ALL)); + assertThat(converter.canRead(MyType.class, new MediaType("foo", "bar"))).isTrue(); + assertThat(converter.canRead(MyType.class, new MediaType("foo", "*"))).isTrue(); + assertThat(converter.canRead(MyType.class, MediaType.ALL)).isFalse(); } @Test @@ -61,9 +60,9 @@ public class HttpMessageConverterTests { MediaType mediaType = new MediaType("foo", "bar"); HttpMessageConverter converter = new MyHttpMessageConverter<>(mediaType); - assertTrue(converter.canWrite(MyType.class, mediaType)); - assertTrue(converter.canWrite(MyType.class, new MediaType("foo", "*"))); - assertTrue(converter.canWrite(MyType.class, MediaType.ALL)); + assertThat(converter.canWrite(MyType.class, mediaType)).isTrue(); + assertThat(converter.canWrite(MyType.class, new MediaType("foo", "*"))).isTrue(); + assertThat(converter.canWrite(MyType.class, MediaType.ALL)).isTrue(); } @Test @@ -71,9 +70,9 @@ public class HttpMessageConverterTests { MediaType mediaType = new MediaType("foo"); HttpMessageConverter converter = new MyHttpMessageConverter<>(mediaType); - assertTrue(converter.canWrite(MyType.class, new MediaType("foo", "bar"))); - assertTrue(converter.canWrite(MyType.class, new MediaType("foo", "*"))); - assertTrue(converter.canWrite(MyType.class, MediaType.ALL)); + assertThat(converter.canWrite(MyType.class, new MediaType("foo", "bar"))).isTrue(); + assertThat(converter.canWrite(MyType.class, new MediaType("foo", "*"))).isTrue(); + assertThat(converter.canWrite(MyType.class, MediaType.ALL)).isTrue(); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/ObjectToStringHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/ObjectToStringHttpMessageConverterTests.java index ed9d1ebd5e6..52bbbe3f5a1 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/ObjectToStringHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/ObjectToStringHttpMessageConverterTests.java @@ -34,13 +34,8 @@ import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Test cases for {@link ObjectToStringHttpMessageConverter} class. @@ -69,37 +64,37 @@ public class ObjectToStringHttpMessageConverterTests { @Test public void canRead() { - assertFalse(this.converter.canRead(Math.class, null)); - assertFalse(this.converter.canRead(Resource.class, null)); + assertThat(this.converter.canRead(Math.class, null)).isFalse(); + assertThat(this.converter.canRead(Resource.class, null)).isFalse(); - assertTrue(this.converter.canRead(Locale.class, null)); - assertTrue(this.converter.canRead(BigInteger.class, null)); + assertThat(this.converter.canRead(Locale.class, null)).isTrue(); + assertThat(this.converter.canRead(BigInteger.class, null)).isTrue(); - assertFalse(this.converter.canRead(BigInteger.class, MediaType.TEXT_HTML)); - assertFalse(this.converter.canRead(BigInteger.class, MediaType.TEXT_XML)); - assertFalse(this.converter.canRead(BigInteger.class, MediaType.APPLICATION_XML)); + assertThat(this.converter.canRead(BigInteger.class, MediaType.TEXT_HTML)).isFalse(); + assertThat(this.converter.canRead(BigInteger.class, MediaType.TEXT_XML)).isFalse(); + assertThat(this.converter.canRead(BigInteger.class, MediaType.APPLICATION_XML)).isFalse(); } @Test public void canWrite() { - assertFalse(this.converter.canWrite(Math.class, null)); - assertFalse(this.converter.canWrite(Resource.class, null)); + assertThat(this.converter.canWrite(Math.class, null)).isFalse(); + assertThat(this.converter.canWrite(Resource.class, null)).isFalse(); - assertTrue(this.converter.canWrite(Locale.class, null)); - assertTrue(this.converter.canWrite(Double.class, null)); + assertThat(this.converter.canWrite(Locale.class, null)).isTrue(); + assertThat(this.converter.canWrite(Double.class, null)).isTrue(); - assertFalse(this.converter.canWrite(BigInteger.class, MediaType.TEXT_HTML)); - assertFalse(this.converter.canWrite(BigInteger.class, MediaType.TEXT_XML)); - assertFalse(this.converter.canWrite(BigInteger.class, MediaType.APPLICATION_XML)); + assertThat(this.converter.canWrite(BigInteger.class, MediaType.TEXT_HTML)).isFalse(); + assertThat(this.converter.canWrite(BigInteger.class, MediaType.TEXT_XML)).isFalse(); + assertThat(this.converter.canWrite(BigInteger.class, MediaType.APPLICATION_XML)).isFalse(); - assertTrue(this.converter.canWrite(BigInteger.class, MediaType.valueOf("text/*"))); + assertThat(this.converter.canWrite(BigInteger.class, MediaType.valueOf("text/*"))).isTrue(); } @Test public void defaultCharset() throws IOException { this.converter.write(Integer.valueOf(5), null, response); - assertEquals("ISO-8859-1", servletResponse.getCharacterEncoding()); + assertThat(servletResponse.getCharacterEncoding()).isEqualTo("ISO-8859-1"); } @Test @@ -108,7 +103,7 @@ public class ObjectToStringHttpMessageConverterTests { ObjectToStringHttpMessageConverter converter = new ObjectToStringHttpMessageConverter(cs, StandardCharsets.UTF_16); converter.write((byte) 31, null, this.response); - assertEquals("UTF-16", this.servletResponse.getCharacterEncoding()); + assertThat(this.servletResponse.getCharacterEncoding()).isEqualTo("UTF-16"); } @Test @@ -116,7 +111,7 @@ public class ObjectToStringHttpMessageConverterTests { this.converter.setWriteAcceptCharset(true); this.converter.write(new Date(), null, this.response); - assertNotNull(this.servletResponse.getHeader("Accept-Charset")); + assertThat(this.servletResponse.getHeader("Accept-Charset")).isNotNull(); } @Test @@ -124,7 +119,7 @@ public class ObjectToStringHttpMessageConverterTests { this.converter.setWriteAcceptCharset(false); this.converter.write(new Date(), null, this.response); - assertNull(this.servletResponse.getHeader("Accept-Charset")); + assertThat(this.servletResponse.getHeader("Accept-Charset")).isNull(); } @Test @@ -133,31 +128,31 @@ public class ObjectToStringHttpMessageConverterTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.setContentType(MediaType.TEXT_PLAIN_VALUE); request.setContent(shortValue.toString().getBytes(StringHttpMessageConverter.DEFAULT_CHARSET)); - assertEquals(shortValue, this.converter.read(Short.class, new ServletServerHttpRequest(request))); + assertThat(this.converter.read(Short.class, new ServletServerHttpRequest(request))).isEqualTo(shortValue); Float floatValue = Float.valueOf(123); request = new MockHttpServletRequest(); request.setContentType(MediaType.TEXT_PLAIN_VALUE); request.setCharacterEncoding("UTF-16"); request.setContent(floatValue.toString().getBytes("UTF-16")); - assertEquals(floatValue, this.converter.read(Float.class, new ServletServerHttpRequest(request))); + assertThat(this.converter.read(Float.class, new ServletServerHttpRequest(request))).isEqualTo(floatValue); Long longValue = Long.valueOf(55819182821331L); request = new MockHttpServletRequest(); request.setContentType(MediaType.TEXT_PLAIN_VALUE); request.setCharacterEncoding("UTF-8"); request.setContent(longValue.toString().getBytes("UTF-8")); - assertEquals(longValue, this.converter.read(Long.class, new ServletServerHttpRequest(request))); + assertThat(this.converter.read(Long.class, new ServletServerHttpRequest(request))).isEqualTo(longValue); } @Test public void write() throws IOException { this.converter.write((byte) -8, null, this.response); - assertEquals("ISO-8859-1", this.servletResponse.getCharacterEncoding()); - assertTrue(this.servletResponse.getContentType().startsWith(MediaType.TEXT_PLAIN_VALUE)); - assertEquals(2, this.servletResponse.getContentLength()); - assertArrayEquals(new byte[] { '-', '8' }, this.servletResponse.getContentAsByteArray()); + assertThat(this.servletResponse.getCharacterEncoding()).isEqualTo("ISO-8859-1"); + assertThat(this.servletResponse.getContentType().startsWith(MediaType.TEXT_PLAIN_VALUE)).isTrue(); + assertThat(this.servletResponse.getContentLength()).isEqualTo(2); + assertThat(this.servletResponse.getContentAsByteArray()).isEqualTo(new byte[] { '-', '8' }); } @Test @@ -165,11 +160,11 @@ public class ObjectToStringHttpMessageConverterTests { MediaType contentType = new MediaType("text", "plain", StandardCharsets.UTF_16); this.converter.write(Integer.valueOf(958), contentType, this.response); - assertEquals("UTF-16", this.servletResponse.getCharacterEncoding()); - assertTrue(this.servletResponse.getContentType().startsWith(MediaType.TEXT_PLAIN_VALUE)); - assertEquals(8, this.servletResponse.getContentLength()); + assertThat(this.servletResponse.getCharacterEncoding()).isEqualTo("UTF-16"); + assertThat(this.servletResponse.getContentType().startsWith(MediaType.TEXT_PLAIN_VALUE)).isTrue(); + assertThat(this.servletResponse.getContentLength()).isEqualTo(8); // First two bytes: byte order mark - assertArrayEquals(new byte[] { -2, -1, 0, '9', 0, '5', 0, '8' }, this.servletResponse.getContentAsByteArray()); + assertThat(this.servletResponse.getContentAsByteArray()).isEqualTo(new byte[] { -2, -1, 0, '9', 0, '5', 0, '8' }); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/converter/ResourceHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/ResourceHttpMessageConverterTests.java index c9a439f2748..20b5b6d35a0 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/ResourceHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/ResourceHttpMessageConverterTests.java @@ -35,8 +35,6 @@ import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; @@ -54,13 +52,13 @@ public class ResourceHttpMessageConverterTests { @Test public void canReadResource() { - assertTrue(converter.canRead(Resource.class, new MediaType("application", "octet-stream"))); + assertThat(converter.canRead(Resource.class, new MediaType("application", "octet-stream"))).isTrue(); } @Test public void canWriteResource() { - assertTrue(converter.canWrite(Resource.class, new MediaType("application", "octet-stream"))); - assertTrue(converter.canWrite(Resource.class, MediaType.ALL)); + assertThat(converter.canWrite(Resource.class, new MediaType("application", "octet-stream"))).isTrue(); + assertThat(converter.canWrite(Resource.class, MediaType.ALL)).isTrue(); } @Test @@ -72,7 +70,7 @@ public class ResourceHttpMessageConverterTests { ContentDisposition.builder("attachment").filename("yourlogo.jpg").build()); Resource actualResource = converter.read(Resource.class, inputMessage); assertThat(FileCopyUtils.copyToByteArray(actualResource.getInputStream())).isEqualTo(body); - assertEquals("yourlogo.jpg", actualResource.getFilename()); + assertThat(actualResource.getFilename()).isEqualTo("yourlogo.jpg"); } @Test // SPR-13443 @@ -85,7 +83,7 @@ public class ResourceHttpMessageConverterTests { Resource actualResource = converter.read(InputStreamResource.class, inputMessage); assertThat(actualResource).isInstanceOf(InputStreamResource.class); assertThat(actualResource.getInputStream()).isEqualTo(body); - assertEquals("yourlogo.jpg", actualResource.getFilename()); + assertThat(actualResource.getFilename()).isEqualTo("yourlogo.jpg"); } } @@ -106,9 +104,8 @@ public class ResourceHttpMessageConverterTests { Resource body = new ClassPathResource("logo.jpg", getClass()); converter.write(body, null, outputMessage); - assertEquals("Invalid content-type", MediaType.IMAGE_JPEG, - outputMessage.getHeaders().getContentType()); - assertEquals("Invalid content-length", body.getFile().length(), outputMessage.getHeaders().getContentLength()); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(MediaType.IMAGE_JPEG); + assertThat(outputMessage.getHeaders().getContentLength()).as("Invalid content-length").isEqualTo(body.getFile().length()); } @Test // SPR-10848 @@ -118,18 +115,17 @@ public class ResourceHttpMessageConverterTests { Resource body = new ByteArrayResource(byteArray); converter.write(body, null, outputMessage); - assertTrue(Arrays.equals(byteArray, outputMessage.getBodyAsBytes())); + assertThat(Arrays.equals(byteArray, outputMessage.getBodyAsBytes())).isTrue(); } @Test // SPR-12999 - @SuppressWarnings("unchecked") public void writeContentNotGettingInputStream() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); Resource resource = mock(Resource.class); given(resource.getInputStream()).willThrow(FileNotFoundException.class); converter.write(resource, MediaType.APPLICATION_OCTET_STREAM, outputMessage); - assertEquals(0, outputMessage.getHeaders().getContentLength()); + assertThat(outputMessage.getHeaders().getContentLength()).isEqualTo(0); } @Test // SPR-12999 @@ -142,11 +138,10 @@ public class ResourceHttpMessageConverterTests { willThrow(new NullPointerException()).given(inputStream).close(); converter.write(resource, MediaType.APPLICATION_OCTET_STREAM, outputMessage); - assertEquals(0, outputMessage.getHeaders().getContentLength()); + assertThat(outputMessage.getHeaders().getContentLength()).isEqualTo(0); } @Test // SPR-13620 - @SuppressWarnings("unchecked") public void writeContentInputStreamThrowingNullPointerException() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); Resource resource = mock(Resource.class); @@ -155,7 +150,7 @@ public class ResourceHttpMessageConverterTests { given(in.read(any())).willThrow(NullPointerException.class); converter.write(resource, MediaType.APPLICATION_OCTET_STREAM, outputMessage); - assertEquals(0, outputMessage.getHeaders().getContentLength()); + assertThat(outputMessage.getHeaders().getContentLength()).isEqualTo(0); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/ResourceRegionHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/ResourceRegionHttpMessageConverterTests.java index 7a0604c13d2..7f9e0b1dfb0 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/ResourceRegionHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/ResourceRegionHttpMessageConverterTests.java @@ -38,8 +38,6 @@ import org.springframework.http.MockHttpOutputMessage; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Test cases for {@link ResourceRegionHttpMessageConverter} class. @@ -52,29 +50,29 @@ public class ResourceRegionHttpMessageConverterTests { @Test public void canReadResource() { - assertFalse(converter.canRead(Resource.class, MediaType.APPLICATION_OCTET_STREAM)); - assertFalse(converter.canRead(Resource.class, MediaType.ALL)); - assertFalse(converter.canRead(List.class, MediaType.APPLICATION_OCTET_STREAM)); - assertFalse(converter.canRead(List.class, MediaType.ALL)); + assertThat(converter.canRead(Resource.class, MediaType.APPLICATION_OCTET_STREAM)).isFalse(); + assertThat(converter.canRead(Resource.class, MediaType.ALL)).isFalse(); + assertThat(converter.canRead(List.class, MediaType.APPLICATION_OCTET_STREAM)).isFalse(); + assertThat(converter.canRead(List.class, MediaType.ALL)).isFalse(); } @Test public void canWriteResource() { - assertTrue(converter.canWrite(ResourceRegion.class, null, MediaType.APPLICATION_OCTET_STREAM)); - assertTrue(converter.canWrite(ResourceRegion.class, null, MediaType.ALL)); - assertFalse(converter.canWrite(Object.class, null, MediaType.ALL)); + assertThat(converter.canWrite(ResourceRegion.class, null, MediaType.APPLICATION_OCTET_STREAM)).isTrue(); + assertThat(converter.canWrite(ResourceRegion.class, null, MediaType.ALL)).isTrue(); + assertThat(converter.canWrite(Object.class, null, MediaType.ALL)).isFalse(); } @Test public void canWriteResourceCollection() { Type resourceRegionList = new ParameterizedTypeReference>() {}.getType(); - assertTrue(converter.canWrite(resourceRegionList, null, MediaType.APPLICATION_OCTET_STREAM)); - assertTrue(converter.canWrite(resourceRegionList, null, MediaType.ALL)); + assertThat(converter.canWrite(resourceRegionList, null, MediaType.APPLICATION_OCTET_STREAM)).isTrue(); + assertThat(converter.canWrite(resourceRegionList, null, MediaType.ALL)).isTrue(); - assertFalse(converter.canWrite(List.class, MediaType.APPLICATION_OCTET_STREAM)); - assertFalse(converter.canWrite(List.class, MediaType.ALL)); + assertThat(converter.canWrite(List.class, MediaType.APPLICATION_OCTET_STREAM)).isFalse(); + assertThat(converter.canWrite(List.class, MediaType.ALL)).isFalse(); Type resourceObjectList = new ParameterizedTypeReference>() {}.getType(); - assertFalse(converter.canWrite(resourceObjectList, null, MediaType.ALL)); + assertThat(converter.canWrite(resourceObjectList, null, MediaType.ALL)).isFalse(); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/converter/StringHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/StringHttpMessageConverterTests.java index d814ef0f527..e51a8ebce1f 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/StringHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/StringHttpMessageConverterTests.java @@ -27,8 +27,7 @@ import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -52,13 +51,13 @@ public class StringHttpMessageConverterTests { @Test public void canRead() { - assertTrue(this.converter.canRead(String.class, MediaType.TEXT_PLAIN)); + assertThat(this.converter.canRead(String.class, MediaType.TEXT_PLAIN)).isTrue(); } @Test public void canWrite() { - assertTrue(this.converter.canWrite(String.class, MediaType.TEXT_PLAIN)); - assertTrue(this.converter.canWrite(String.class, MediaType.ALL)); + assertThat(this.converter.canWrite(String.class, MediaType.TEXT_PLAIN)).isTrue(); + assertThat(this.converter.canWrite(String.class, MediaType.ALL)).isTrue(); } @Test @@ -68,7 +67,7 @@ public class StringHttpMessageConverterTests { inputMessage.getHeaders().setContentType(TEXT_PLAIN_UTF_8); String result = this.converter.read(String.class, inputMessage); - assertEquals("Invalid result", body, result); + assertThat(result).as("Invalid result").isEqualTo(body); } @Test @@ -77,10 +76,10 @@ public class StringHttpMessageConverterTests { this.converter.write(body, null, this.outputMessage); HttpHeaders headers = this.outputMessage.getHeaders(); - assertEquals(body, this.outputMessage.getBodyAsString(StandardCharsets.ISO_8859_1)); - assertEquals(new MediaType("text", "plain", StandardCharsets.ISO_8859_1), headers.getContentType()); - assertEquals(body.getBytes(StandardCharsets.ISO_8859_1).length, headers.getContentLength()); - assertTrue(headers.getAcceptCharset().isEmpty()); + assertThat(this.outputMessage.getBodyAsString(StandardCharsets.ISO_8859_1)).isEqualTo(body); + assertThat(headers.getContentType()).isEqualTo(new MediaType("text", "plain", StandardCharsets.ISO_8859_1)); + assertThat(headers.getContentLength()).isEqualTo(body.getBytes(StandardCharsets.ISO_8859_1).length); + assertThat(headers.getAcceptCharset().isEmpty()).isTrue(); } @Test @@ -89,10 +88,10 @@ public class StringHttpMessageConverterTests { this.converter.write(body, TEXT_PLAIN_UTF_8, this.outputMessage); HttpHeaders headers = this.outputMessage.getHeaders(); - assertEquals(body, this.outputMessage.getBodyAsString(StandardCharsets.UTF_8)); - assertEquals(TEXT_PLAIN_UTF_8, headers.getContentType()); - assertEquals(body.getBytes(StandardCharsets.UTF_8).length, headers.getContentLength()); - assertTrue(headers.getAcceptCharset().isEmpty()); + assertThat(this.outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo(body); + assertThat(headers.getContentType()).isEqualTo(TEXT_PLAIN_UTF_8); + assertThat(headers.getContentLength()).isEqualTo(body.getBytes(StandardCharsets.UTF_8).length); + assertThat(headers.getAcceptCharset().isEmpty()).isTrue(); } @Test // SPR-8867 @@ -104,10 +103,10 @@ public class StringHttpMessageConverterTests { headers.setContentType(TEXT_PLAIN_UTF_8); this.converter.write(body, requestedContentType, this.outputMessage); - assertEquals(body, this.outputMessage.getBodyAsString(StandardCharsets.UTF_8)); - assertEquals(TEXT_PLAIN_UTF_8, headers.getContentType()); - assertEquals(body.getBytes(StandardCharsets.UTF_8).length, headers.getContentLength()); - assertTrue(headers.getAcceptCharset().isEmpty()); + assertThat(this.outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo(body); + assertThat(headers.getContentType()).isEqualTo(TEXT_PLAIN_UTF_8); + assertThat(headers.getContentLength()).isEqualTo(body.getBytes(StandardCharsets.UTF_8).length); + assertThat(headers.getAcceptCharset().isEmpty()).isTrue(); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/feed/AtomFeedHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/feed/AtomFeedHttpMessageConverterTests.java index 5fe703ec99b..67e95276c43 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/feed/AtomFeedHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/feed/AtomFeedHttpMessageConverterTests.java @@ -38,8 +38,6 @@ import org.springframework.http.MockHttpOutputMessage; import org.springframework.tests.XmlContent; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Arjen Poutsma @@ -57,14 +55,14 @@ public class AtomFeedHttpMessageConverterTests { @Test public void canRead() { - assertTrue(converter.canRead(Feed.class, new MediaType("application", "atom+xml"))); - assertTrue(converter.canRead(Feed.class, new MediaType("application", "atom+xml", StandardCharsets.UTF_8))); + assertThat(converter.canRead(Feed.class, new MediaType("application", "atom+xml"))).isTrue(); + assertThat(converter.canRead(Feed.class, new MediaType("application", "atom+xml", StandardCharsets.UTF_8))).isTrue(); } @Test public void canWrite() { - assertTrue(converter.canWrite(Feed.class, new MediaType("application", "atom+xml"))); - assertTrue(converter.canWrite(Feed.class, new MediaType("application", "atom+xml", StandardCharsets.UTF_8))); + assertThat(converter.canWrite(Feed.class, new MediaType("application", "atom+xml"))).isTrue(); + assertThat(converter.canWrite(Feed.class, new MediaType("application", "atom+xml", StandardCharsets.UTF_8))).isTrue(); } @Test @@ -73,18 +71,18 @@ public class AtomFeedHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(is); inputMessage.getHeaders().setContentType(new MediaType("application", "atom+xml", StandardCharsets.UTF_8)); Feed result = converter.read(Feed.class, inputMessage); - assertEquals("title", result.getTitle()); - assertEquals("subtitle", result.getSubtitle().getValue()); + assertThat(result.getTitle()).isEqualTo("title"); + assertThat(result.getSubtitle().getValue()).isEqualTo("subtitle"); List entries = result.getEntries(); - assertEquals(2, entries.size()); + assertThat(entries.size()).isEqualTo(2); Entry entry1 = (Entry) entries.get(0); - assertEquals("id1", entry1.getId()); - assertEquals("title1", entry1.getTitle()); + assertThat(entry1.getId()).isEqualTo("id1"); + assertThat(entry1.getTitle()).isEqualTo("title1"); Entry entry2 = (Entry) entries.get(1); - assertEquals("id2", entry2.getId()); - assertEquals("title2", entry2.getTitle()); + assertThat(entry2.getId()).isEqualTo("id2"); + assertThat(entry2.getTitle()).isEqualTo("title2"); } @Test @@ -108,8 +106,7 @@ public class AtomFeedHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(feed, null, outputMessage); - assertEquals("Invalid content-type", new MediaType("application", "atom+xml", StandardCharsets.UTF_8), - outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "atom+xml", StandardCharsets.UTF_8)); String expected = "" + "title" + "id1title1" + "id2title2"; @@ -128,8 +125,7 @@ public class AtomFeedHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(feed, null, outputMessage); - assertEquals("Invalid content-type", new MediaType("application", "atom+xml", Charset.forName(encoding)), - outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "atom+xml", Charset.forName(encoding))); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverterTests.java index 689103c70f0..5e3fbb01c4a 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverterTests.java @@ -35,8 +35,6 @@ import org.springframework.http.MockHttpOutputMessage; import org.springframework.tests.XmlContent; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Arjen Poutsma @@ -54,14 +52,14 @@ public class RssChannelHttpMessageConverterTests { @Test public void canRead() { - assertTrue(converter.canRead(Channel.class, new MediaType("application", "rss+xml"))); - assertTrue(converter.canRead(Channel.class, new MediaType("application", "rss+xml", StandardCharsets.UTF_8))); + assertThat(converter.canRead(Channel.class, new MediaType("application", "rss+xml"))).isTrue(); + assertThat(converter.canRead(Channel.class, new MediaType("application", "rss+xml", StandardCharsets.UTF_8))).isTrue(); } @Test public void canWrite() { - assertTrue(converter.canWrite(Channel.class, new MediaType("application", "rss+xml"))); - assertTrue(converter.canWrite(Channel.class, new MediaType("application", "rss+xml", StandardCharsets.UTF_8))); + assertThat(converter.canWrite(Channel.class, new MediaType("application", "rss+xml"))).isTrue(); + assertThat(converter.canWrite(Channel.class, new MediaType("application", "rss+xml", StandardCharsets.UTF_8))).isTrue(); } @Test @@ -70,18 +68,18 @@ public class RssChannelHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(is); inputMessage.getHeaders().setContentType(new MediaType("application", "rss+xml", StandardCharsets.UTF_8)); Channel result = converter.read(Channel.class, inputMessage); - assertEquals("title", result.getTitle()); - assertEquals("https://example.com", result.getLink()); - assertEquals("description", result.getDescription()); + assertThat(result.getTitle()).isEqualTo("title"); + assertThat(result.getLink()).isEqualTo("https://example.com"); + assertThat(result.getDescription()).isEqualTo("description"); List items = result.getItems(); - assertEquals(2, items.size()); + assertThat(items.size()).isEqualTo(2); Item item1 = (Item) items.get(0); - assertEquals("title1", item1.getTitle()); + assertThat(item1.getTitle()).isEqualTo("title1"); Item item2 = (Item) items.get(1); - assertEquals("title2", item2.getTitle()); + assertThat(item2.getTitle()).isEqualTo("title2"); } @Test @@ -105,8 +103,7 @@ public class RssChannelHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(channel, null, outputMessage); - assertEquals("Invalid content-type", new MediaType("application", "rss+xml", StandardCharsets.UTF_8), - outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "rss+xml", StandardCharsets.UTF_8)); String expected = "" + "titlehttps://example.comdescription" + "title1" + @@ -132,8 +129,7 @@ public class RssChannelHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(channel, null, outputMessage); - assertEquals("Invalid content-type", new MediaType("application", "rss+xml", Charset.forName(encoding)), - outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "rss+xml", Charset.forName(encoding))); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/GsonFactoryBeanTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/GsonFactoryBeanTests.java index 3135b122512..2fa1aa51cfc 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/GsonFactoryBeanTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/GsonFactoryBeanTests.java @@ -22,8 +22,7 @@ import java.util.Date; import com.google.gson.Gson; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * {@link GsonFactoryBean} tests. @@ -44,7 +43,7 @@ public class GsonFactoryBeanTests { Gson gson = this.factory.getObject(); StringBean bean = new StringBean(); String result = gson.toJson(bean); - assertEquals("{\"name\":null}", result); + assertThat(result).isEqualTo("{\"name\":null}"); } @Test @@ -54,7 +53,7 @@ public class GsonFactoryBeanTests { Gson gson = this.factory.getObject(); StringBean bean = new StringBean(); String result = gson.toJson(bean); - assertEquals("{}", result); + assertThat(result).isEqualTo("{}"); } @Test @@ -65,7 +64,7 @@ public class GsonFactoryBeanTests { StringBean bean = new StringBean(); bean.setName("Jason"); String result = gson.toJson(bean); - assertTrue(result.contains(" \"name\": \"Jason\"")); + assertThat(result.contains(" \"name\": \"Jason\"")).isTrue(); } @Test @@ -76,7 +75,7 @@ public class GsonFactoryBeanTests { StringBean bean = new StringBean(); bean.setName("Jason"); String result = gson.toJson(bean); - assertEquals("{\"name\":\"Jason\"}", result); + assertThat(result).isEqualTo("{\"name\":\"Jason\"}"); } @Test @@ -87,7 +86,7 @@ public class GsonFactoryBeanTests { StringBean bean = new StringBean(); bean.setName("Bob=Bob"); String result = gson.toJson(bean); - assertEquals("{\"name\":\"Bob=Bob\"}", result); + assertThat(result).isEqualTo("{\"name\":\"Bob=Bob\"}"); } @Test @@ -98,7 +97,7 @@ public class GsonFactoryBeanTests { StringBean bean = new StringBean(); bean.setName("Bob=Bob"); String result = gson.toJson(bean); - assertEquals("{\"name\":\"Bob\\u003dBob\"}", result); + assertThat(result).isEqualTo("{\"name\":\"Bob\\u003dBob\"}"); } @Test @@ -115,7 +114,7 @@ public class GsonFactoryBeanTests { Date date = cal.getTime(); bean.setDate(date); String result = gson.toJson(bean); - assertEquals("{\"date\":\"2014-01-01\"}", result); + assertThat(result).isEqualTo("{\"date\":\"2014-01-01\"}"); } @Test @@ -131,8 +130,8 @@ public class GsonFactoryBeanTests { Date date = cal.getTime(); bean.setDate(date); String result = gson.toJson(bean); - assertTrue(result.startsWith("{\"date\":\"Jan 1, 2014")); - assertTrue(result.endsWith("12:00:00 AM\"}")); + assertThat(result.startsWith("{\"date\":\"Jan 1, 2014")).isTrue(); + assertThat(result.endsWith("12:00:00 AM\"}")).isTrue(); } @Test @@ -143,7 +142,7 @@ public class GsonFactoryBeanTests { ByteArrayBean bean = new ByteArrayBean(); bean.setBytes(new byte[] {0x1, 0x2}); String result = gson.toJson(bean); - assertEquals("{\"bytes\":\"AQI\\u003d\"}", result); + assertThat(result).isEqualTo("{\"bytes\":\"AQI\\u003d\"}"); } @Test @@ -155,7 +154,7 @@ public class GsonFactoryBeanTests { ByteArrayBean bean = new ByteArrayBean(); bean.setBytes(new byte[] {0x1, 0x2}); String result = gson.toJson(bean); - assertEquals("{\"bytes\":\"AQI=\"}", result); + assertThat(result).isEqualTo("{\"bytes\":\"AQI=\"}"); } @Test @@ -166,7 +165,7 @@ public class GsonFactoryBeanTests { ByteArrayBean bean = new ByteArrayBean(); bean.setBytes(new byte[] {0x1, 0x2}); String result = gson.toJson(bean); - assertEquals("{\"bytes\":[1,2]}", result); + assertThat(result).isEqualTo("{\"bytes\":[1,2]}"); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/GsonHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/GsonHttpMessageConverterTests.java index 926bff47305..aa72ece2117 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/GsonHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/GsonHttpMessageConverterTests.java @@ -35,10 +35,9 @@ import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; import org.springframework.http.converter.HttpMessageNotReadableException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.within; /** * Gson 2.x converter tests. @@ -53,20 +52,20 @@ public class GsonHttpMessageConverterTests { @Test public void canRead() { - assertTrue(this.converter.canRead(MyBean.class, new MediaType("application", "json"))); - assertTrue(this.converter.canRead(Map.class, new MediaType("application", "json"))); + assertThat(this.converter.canRead(MyBean.class, new MediaType("application", "json"))).isTrue(); + assertThat(this.converter.canRead(Map.class, new MediaType("application", "json"))).isTrue(); } @Test public void canWrite() { - assertTrue(this.converter.canWrite(MyBean.class, new MediaType("application", "json"))); - assertTrue(this.converter.canWrite(Map.class, new MediaType("application", "json"))); + assertThat(this.converter.canWrite(MyBean.class, new MediaType("application", "json"))).isTrue(); + assertThat(this.converter.canWrite(Map.class, new MediaType("application", "json"))).isTrue(); } @Test public void canReadAndWriteMicroformats() { - assertTrue(this.converter.canRead(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))); - assertTrue(this.converter.canWrite(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))); + assertThat(this.converter.canRead(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))).isTrue(); + assertThat(this.converter.canWrite(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))).isTrue(); } @Test @@ -77,12 +76,13 @@ public class GsonHttpMessageConverterTests { inputMessage.getHeaders().setContentType(new MediaType("application", "json")); MyBean result = (MyBean) this.converter.read(MyBean.class, inputMessage); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); } @Test @@ -93,22 +93,23 @@ public class GsonHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); HashMap result = (HashMap) this.converter.read(HashMap.class, inputMessage); - assertEquals("Foo", result.get("string")); + assertThat(result.get("string")).isEqualTo("Foo"); Number n = (Number) result.get("number"); - assertEquals(42, n.longValue()); + assertThat(n.longValue()).isEqualTo(42); n = (Number) result.get("fraction"); - assertEquals(42D, n.doubleValue(), 0D); + assertThat(n.doubleValue()).isCloseTo(42D, within(0D)); + List array = new ArrayList<>(); array.add("Foo"); array.add("Bar"); - assertEquals(array, result.get("array")); - assertEquals(Boolean.TRUE, result.get("bool")); + assertThat(result.get("array")).isEqualTo(array); + assertThat(result.get("bool")).isEqualTo(Boolean.TRUE); byte[] bytes = new byte[2]; List resultBytes = (ArrayList)result.get("bytes"); for (int i = 0; i < 2; i++) { bytes[i] = resultBytes.get(i).byteValue(); } - assertArrayEquals(new byte[] {0x1, 0x2}, bytes); + assertThat(bytes).isEqualTo(new byte[] {0x1, 0x2}); } @Test @@ -124,14 +125,13 @@ public class GsonHttpMessageConverterTests { this.converter.write(body, null, outputMessage); Charset utf8 = StandardCharsets.UTF_8; String result = outputMessage.getBodyAsString(utf8); - assertTrue(result.contains("\"string\":\"Foo\"")); - assertTrue(result.contains("\"number\":42")); - assertTrue(result.contains("fraction\":42.0")); - assertTrue(result.contains("\"array\":[\"Foo\",\"Bar\"]")); - assertTrue(result.contains("\"bool\":true")); - assertTrue(result.contains("\"bytes\":[1,2]")); - assertEquals("Invalid content-type", new MediaType("application", "json", utf8), - outputMessage.getHeaders().getContentType()); + assertThat(result.contains("\"string\":\"Foo\"")).isTrue(); + assertThat(result.contains("\"number\":42")).isTrue(); + assertThat(result.contains("fraction\":42.0")).isTrue(); + assertThat(result.contains("\"array\":[\"Foo\",\"Bar\"]")).isTrue(); + assertThat(result.contains("\"bool\":true")).isTrue(); + assertThat(result.contains("\"bytes\":[1,2]")).isTrue(); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "json", utf8)); } @Test @@ -147,14 +147,13 @@ public class GsonHttpMessageConverterTests { this.converter.write(body, MyBase.class, null, outputMessage); Charset utf8 = StandardCharsets.UTF_8; String result = outputMessage.getBodyAsString(utf8); - assertTrue(result.contains("\"string\":\"Foo\"")); - assertTrue(result.contains("\"number\":42")); - assertTrue(result.contains("fraction\":42.0")); - assertTrue(result.contains("\"array\":[\"Foo\",\"Bar\"]")); - assertTrue(result.contains("\"bool\":true")); - assertTrue(result.contains("\"bytes\":[1,2]")); - assertEquals("Invalid content-type", new MediaType("application", "json", utf8), - outputMessage.getHeaders().getContentType()); + assertThat(result.contains("\"string\":\"Foo\"")).isTrue(); + assertThat(result.contains("\"number\":42")).isTrue(); + assertThat(result.contains("fraction\":42.0")).isTrue(); + assertThat(result.contains("\"array\":[\"Foo\",\"Bar\"]")).isTrue(); + assertThat(result.contains("\"bool\":true")).isTrue(); + assertThat(result.contains("\"bytes\":[1,2]")).isTrue(); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "json", utf8)); } @Test @@ -163,8 +162,8 @@ public class GsonHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); String body = "H\u00e9llo W\u00f6rld"; this.converter.write(body, contentType, outputMessage); - assertEquals("Invalid result", "\"" + body + "\"", outputMessage.getBodyAsString(StandardCharsets.UTF_16BE)); - assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_16BE)).as("Invalid result").isEqualTo(("\"" + body + "\"")); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(contentType); } @Test @@ -188,14 +187,15 @@ public class GsonHttpMessageConverterTests { Type genericType = beansList.getGenericType(); List results = (List) converter.read(genericType, MyBeanListHolder.class, inputMessage); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); MyBean result = results.get(0); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(results, genericType, new MediaType("application", "json"), outputMessage); @@ -214,14 +214,15 @@ public class GsonHttpMessageConverterTests { inputMessage.getHeaders().setContentType(new MediaType("application", "json")); List results = (List) converter.read(beansList.getType(), null, inputMessage); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); MyBean result = results.get(0); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(results, beansList.getType(), new MediaType("application", "json"), outputMessage); @@ -240,14 +241,15 @@ public class GsonHttpMessageConverterTests { inputMessage.getHeaders().setContentType(new MediaType("application", "json")); List results = (List) converter.read(beansList.getType(), null, inputMessage); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); MyBean result = results.get(0); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(results, baseList.getType(), new MediaType("application", "json"), outputMessage); @@ -259,7 +261,7 @@ public class GsonHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); this.converter.setPrefixJson(true); this.converter.writeInternal("foo", null, outputMessage); - assertEquals(")]}', \"foo\"", outputMessage.getBodyAsString(StandardCharsets.UTF_8)); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo(")]}', \"foo\""); } @Test @@ -267,7 +269,7 @@ public class GsonHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); this.converter.setJsonPrefix(")))"); this.converter.writeInternal("foo", null, outputMessage); - assertEquals(")))\"foo\"", outputMessage.getBodyAsString(StandardCharsets.UTF_8)); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo(")))\"foo\""); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilderTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilderTests.java index ef0f0cf4f73..c9fd2b95bf6 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilderTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilderTests.java @@ -86,12 +86,6 @@ 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.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; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Test class for {@link Jackson2ObjectMapperBuilder}. @@ -116,15 +110,15 @@ public class Jackson2ObjectMapperBuilderTests { @Test public void defaultProperties() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build(); - assertNotNull(objectMapper); - assertFalse(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); - assertFalse(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); - assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); - assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); - assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS)); - assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS)); - assertFalse(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)); - assertTrue(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); + assertThat(objectMapper).isNotNull(); + assertThat(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); + assertThat(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS)).isTrue(); + assertThat(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS)).isTrue(); + assertThat(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS)).isTrue(); + assertThat(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS)).isTrue(); + assertThat(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)).isFalse(); + assertThat(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)).isTrue(); } @Test @@ -132,15 +126,15 @@ public class Jackson2ObjectMapperBuilderTests { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().autoDetectFields(false) .defaultViewInclusion(true).failOnUnknownProperties(true).failOnEmptyBeans(false) .autoDetectGettersSetters(false).indentOutput(true).build(); - assertNotNull(objectMapper); - assertTrue(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); - assertTrue(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); - assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); - assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); - assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS)); - assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS)); - assertTrue(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)); - assertFalse(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); + assertThat(objectMapper).isNotNull(); + assertThat(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isTrue(); + assertThat(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isTrue(); + assertThat(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS)).isFalse(); + assertThat(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS)).isFalse(); + assertThat(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS)).isFalse(); + assertThat(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS)).isFalse(); + assertThat(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)).isTrue(); + assertThat(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)).isFalse(); } @Test @@ -153,69 +147,69 @@ public class Jackson2ObjectMapperBuilderTests { MapperFeature.AUTO_DETECT_GETTERS, MapperFeature.AUTO_DETECT_SETTERS, SerializationFeature.FAIL_ON_EMPTY_BEANS).build(); - assertNotNull(objectMapper); - assertTrue(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); - assertTrue(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); - assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); - assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); - assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS)); - assertTrue(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)); - assertFalse(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); + assertThat(objectMapper).isNotNull(); + assertThat(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isTrue(); + assertThat(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isTrue(); + assertThat(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS)).isFalse(); + assertThat(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS)).isFalse(); + assertThat(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS)).isFalse(); + assertThat(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)).isTrue(); + assertThat(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)).isFalse(); } @Test public void setNotNullSerializationInclusion() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build(); - assertSame(JsonInclude.Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion()); + assertThat(objectMapper.getSerializationConfig().getSerializationInclusion()).isSameAs(JsonInclude.Include.ALWAYS); objectMapper = Jackson2ObjectMapperBuilder.json().serializationInclusion(JsonInclude.Include.NON_NULL).build(); - assertSame(JsonInclude.Include.NON_NULL, objectMapper.getSerializationConfig().getSerializationInclusion()); + assertThat(objectMapper.getSerializationConfig().getSerializationInclusion()).isSameAs(JsonInclude.Include.NON_NULL); } @Test public void setNotDefaultSerializationInclusion() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build(); - assertSame(JsonInclude.Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion()); + assertThat(objectMapper.getSerializationConfig().getSerializationInclusion()).isSameAs(JsonInclude.Include.ALWAYS); objectMapper = Jackson2ObjectMapperBuilder.json().serializationInclusion(JsonInclude.Include.NON_DEFAULT).build(); - assertSame(JsonInclude.Include.NON_DEFAULT, objectMapper.getSerializationConfig().getSerializationInclusion()); + assertThat(objectMapper.getSerializationConfig().getSerializationInclusion()).isSameAs(JsonInclude.Include.NON_DEFAULT); } @Test public void setNotEmptySerializationInclusion() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build(); - assertSame(JsonInclude.Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion()); + assertThat(objectMapper.getSerializationConfig().getSerializationInclusion()).isSameAs(JsonInclude.Include.ALWAYS); objectMapper = Jackson2ObjectMapperBuilder.json().serializationInclusion(JsonInclude.Include.NON_EMPTY).build(); - assertSame(JsonInclude.Include.NON_EMPTY, objectMapper.getSerializationConfig().getSerializationInclusion()); + assertThat(objectMapper.getSerializationConfig().getSerializationInclusion()).isSameAs(JsonInclude.Include.NON_EMPTY); } @Test public void dateTimeFormatSetter() { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().dateFormat(dateFormat).build(); - assertEquals(dateFormat, objectMapper.getSerializationConfig().getDateFormat()); - assertEquals(dateFormat, objectMapper.getDeserializationConfig().getDateFormat()); + assertThat(objectMapper.getSerializationConfig().getDateFormat()).isEqualTo(dateFormat); + assertThat(objectMapper.getDeserializationConfig().getDateFormat()).isEqualTo(dateFormat); } @Test public void simpleDateFormatStringSetter() { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().simpleDateFormat(DATE_FORMAT).build(); - assertEquals(dateFormat, objectMapper.getSerializationConfig().getDateFormat()); - assertEquals(dateFormat, objectMapper.getDeserializationConfig().getDateFormat()); + assertThat(objectMapper.getSerializationConfig().getDateFormat()).isEqualTo(dateFormat); + assertThat(objectMapper.getDeserializationConfig().getDateFormat()).isEqualTo(dateFormat); } @Test public void localeSetter() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().locale(Locale.FRENCH).build(); - assertEquals(Locale.FRENCH, objectMapper.getSerializationConfig().getLocale()); - assertEquals(Locale.FRENCH, objectMapper.getDeserializationConfig().getLocale()); + assertThat(objectMapper.getSerializationConfig().getLocale()).isEqualTo(Locale.FRENCH); + assertThat(objectMapper.getDeserializationConfig().getLocale()).isEqualTo(Locale.FRENCH); } @Test public void timeZoneSetter() { TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().timeZone(timeZone).build(); - assertEquals(timeZone, objectMapper.getSerializationConfig().getTimeZone()); - assertEquals(timeZone, objectMapper.getDeserializationConfig().getTimeZone()); + assertThat(objectMapper.getSerializationConfig().getTimeZone()).isEqualTo(timeZone); + assertThat(objectMapper.getDeserializationConfig().getTimeZone()).isEqualTo(timeZone); } @Test @@ -223,8 +217,8 @@ public class Jackson2ObjectMapperBuilderTests { String zoneId = "Europe/Paris"; ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().timeZone(zoneId).build(); TimeZone timeZone = TimeZone.getTimeZone(zoneId); - assertEquals(timeZone, objectMapper.getSerializationConfig().getTimeZone()); - assertEquals(timeZone, objectMapper.getDeserializationConfig().getTimeZone()); + assertThat(objectMapper.getSerializationConfig().getTimeZone()).isEqualTo(timeZone); + assertThat(objectMapper.getDeserializationConfig().getTimeZone()).isEqualTo(timeZone); } @Test @@ -241,7 +235,7 @@ public class Jackson2ObjectMapperBuilderTests { module.addSerializer(Integer.class, serializer1); ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modules(module).build(); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); - assertSame(serializer1, serializers.findSerializer(null, SimpleType.construct(Integer.class), null)); + assertThat(serializers.findSerializer(null, SimpleType.construct(Integer.class), null)).isSameAs(serializer1); } @Test @@ -251,8 +245,7 @@ public class Jackson2ObjectMapperBuilderTests { .modulesToInstall(CustomIntegerModule.class) .build(); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); - assertSame(CustomIntegerSerializer.class, - serializers.findSerializer(null, SimpleType.construct(Integer.class), null).getClass()); + assertThat(serializers.findSerializer(null, SimpleType.construct(Integer.class), null).getClass()).isSameAs(CustomIntegerSerializer.class); } @Test @@ -261,8 +254,7 @@ public class Jackson2ObjectMapperBuilderTests { .modulesToInstall(new CustomIntegerModule()) .build(); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); - assertSame(CustomIntegerSerializer.class, - serializers.findSerializer(null, SimpleType.construct(Integer.class), null).getClass()); + assertThat(serializers.findSerializer(null, SimpleType.construct(Integer.class), null).getClass()).isSameAs(CustomIntegerSerializer.class); } @Test @@ -271,17 +263,17 @@ public class Jackson2ObjectMapperBuilderTests { Long timestamp = 1322903730000L; DateTime dateTime = new DateTime(timestamp, DateTimeZone.UTC); - assertEquals(timestamp.toString(), new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); + assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo(timestamp.toString()); Path file = Paths.get("foo"); - assertTrue(new String(objectMapper.writeValueAsBytes(file), "UTF-8").endsWith("foo\"")); + assertThat(new String(objectMapper.writeValueAsBytes(file), "UTF-8").endsWith("foo\"")).isTrue(); Optional optional = Optional.of("test"); - assertEquals("\"test\"", new String(objectMapper.writeValueAsBytes(optional), "UTF-8")); + assertThat(new String(objectMapper.writeValueAsBytes(optional), "UTF-8")).isEqualTo("\"test\""); // Kotlin module IntRange range = new IntRange(1, 3); - assertEquals("{\"start\":1,\"end\":3}", new String(objectMapper.writeValueAsBytes(range), "UTF-8")); + assertThat(new String(objectMapper.writeValueAsBytes(range), "UTF-8")).isEqualTo("{\"start\":1,\"end\":3}"); } @Test // SPR-12634 @@ -292,7 +284,7 @@ public class Jackson2ObjectMapperBuilderTests { .modulesToInstall(new CustomIntegerModule()) .build(); DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC); - assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); + assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo("1322903730000"); assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8")).contains("customid"); } @@ -305,7 +297,7 @@ public class Jackson2ObjectMapperBuilderTests { .modulesToInstall(CustomIntegerModule.class) .build(); DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC); - assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); + assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo("1322903730000"); assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8")).contains("customid"); } @@ -316,7 +308,7 @@ public class Jackson2ObjectMapperBuilderTests { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() .serializerByType(Integer.class, new CustomIntegerSerializer()).build(); DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC); - assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); + assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo("1322903730000"); assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8")).contains("customid"); } @@ -329,7 +321,7 @@ public class Jackson2ObjectMapperBuilderTests { builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); ObjectMapper objectMapper = builder.build(); DemoPojo demoPojo = objectMapper.readValue(DATA, DemoPojo.class); - assertNotNull(demoPojo.getOffsetDateTime()); + assertThat(demoPojo.getOffsetDateTime()).isNotNull(); } @Test // gh-22740 @@ -341,14 +333,14 @@ public class Jackson2ObjectMapperBuilderTests { barModule.addSerializer(new BarSerializer()); builder.modulesToInstall(fooModule, barModule); ObjectMapper objectMapper = builder.build(); - assertEquals(1, StreamSupport - .stream(getSerializerFactoryConfig(objectMapper).serializers().spliterator(), false) - .filter(s -> s.findSerializer(null, SimpleType.construct(Foo.class), null) != null) - .count()); - assertEquals(1, StreamSupport - .stream(getSerializerFactoryConfig(objectMapper).serializers().spliterator(), false) - .filter(s -> s.findSerializer(null, SimpleType.construct(Bar.class), null) != null) - .count()); + assertThat(StreamSupport + .stream(getSerializerFactoryConfig(objectMapper).serializers().spliterator(), false) + .filter(s -> s.findSerializer(null, SimpleType.construct(Foo.class), null) != null) + .count()).isEqualTo(1); + assertThat(StreamSupport + .stream(getSerializerFactoryConfig(objectMapper).serializers().spliterator(), false) + .filter(s -> s.findSerializer(null, SimpleType.construct(Bar.class), null) != null) + .count()).isEqualTo(1); } private static SerializerFactoryConfig getSerializerFactoryConfig(ObjectMapper objectMapper) { @@ -363,8 +355,8 @@ public class Jackson2ObjectMapperBuilderTests { public void propertyNamingStrategy() { PropertyNamingStrategy strategy = new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy(); ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().propertyNamingStrategy(strategy).build(); - assertSame(strategy, objectMapper.getSerializationConfig().getPropertyNamingStrategy()); - assertSame(strategy, objectMapper.getDeserializationConfig().getPropertyNamingStrategy()); + assertThat(objectMapper.getSerializationConfig().getPropertyNamingStrategy()).isSameAs(strategy); + assertThat(objectMapper.getDeserializationConfig().getPropertyNamingStrategy()).isSameAs(strategy); } @Test @@ -374,9 +366,9 @@ public class Jackson2ObjectMapperBuilderTests { .modules(new ArrayList<>()) // Disable well-known modules detection .serializerByType(Boolean.class, serializer) .build(); - assertTrue(getSerializerFactoryConfig(objectMapper).hasSerializers()); + assertThat(getSerializerFactoryConfig(objectMapper).hasSerializers()).isTrue(); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); - assertSame(serializer, serializers.findSerializer(null, SimpleType.construct(Boolean.class), null)); + assertThat(serializers.findSerializer(null, SimpleType.construct(Boolean.class), null)).isSameAs(serializer); } @Test @@ -386,9 +378,9 @@ public class Jackson2ObjectMapperBuilderTests { .modules(new ArrayList<>()) // Disable well-known modules detection .deserializerByType(Date.class, deserializer) .build(); - assertTrue(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); + assertThat(getDeserializerFactoryConfig(objectMapper).hasDeserializers()).isTrue(); Deserializers deserializers = getDeserializerFactoryConfig(objectMapper).deserializers().iterator().next(); - assertSame(deserializer, deserializers.findBeanDeserializer(SimpleType.construct(Date.class), null, null)); + assertThat(deserializers.findBeanDeserializer(SimpleType.construct(Date.class), null, null)).isSameAs(deserializer); } @Test @@ -400,8 +392,8 @@ public class Jackson2ObjectMapperBuilderTests { .modules().mixIn(target, mixInSource) .build(); - assertEquals(1, objectMapper.mixInCount()); - assertSame(mixInSource, objectMapper.findMixInClassFor(target)); + assertThat(objectMapper.mixInCount()).isEqualTo(1); + assertThat(objectMapper.findMixInClassFor(target)).isSameAs(mixInSource); } @Test @@ -415,8 +407,8 @@ public class Jackson2ObjectMapperBuilderTests { .modules().mixIns(mixIns) .build(); - assertEquals(1, objectMapper.mixInCount()); - assertSame(mixInSource, objectMapper.findMixInClassFor(target)); + assertThat(objectMapper.mixInCount()).isEqualTo(1); + assertThat(objectMapper.findMixInClassFor(target)).isSameAs(mixInSource); } @Test @@ -467,47 +459,47 @@ public class Jackson2ObjectMapperBuilderTests { ObjectMapper mapper = new ObjectMapper(); builder.configure(mapper); - assertTrue(getSerializerFactoryConfig(mapper).hasSerializers()); - assertTrue(getDeserializerFactoryConfig(mapper).hasDeserializers()); + assertThat(getSerializerFactoryConfig(mapper).hasSerializers()).isTrue(); + assertThat(getDeserializerFactoryConfig(mapper).hasDeserializers()).isTrue(); Serializers serializers = getSerializerFactoryConfig(mapper).serializers().iterator().next(); - assertSame(serializer1, serializers.findSerializer(null, SimpleType.construct(Class.class), null)); - assertSame(serializer2, serializers.findSerializer(null, SimpleType.construct(Boolean.class), null)); - assertNull(serializers.findSerializer(null, SimpleType.construct(Number.class), null)); + assertThat(serializers.findSerializer(null, SimpleType.construct(Class.class), null)).isSameAs(serializer1); + assertThat(serializers.findSerializer(null, SimpleType.construct(Boolean.class), null)).isSameAs(serializer2); + assertThat(serializers.findSerializer(null, SimpleType.construct(Number.class), null)).isNull(); Deserializers deserializers = getDeserializerFactoryConfig(mapper).deserializers().iterator().next(); - assertSame(deserializer, deserializers.findBeanDeserializer(SimpleType.construct(Date.class), null, null)); + assertThat(deserializers.findBeanDeserializer(SimpleType.construct(Date.class), null, null)).isSameAs(deserializer); - assertSame(annotationIntrospector, mapper.getSerializationConfig().getAnnotationIntrospector()); - assertSame(annotationIntrospector, mapper.getDeserializationConfig().getAnnotationIntrospector()); + assertThat(mapper.getSerializationConfig().getAnnotationIntrospector()).isSameAs(annotationIntrospector); + assertThat(mapper.getDeserializationConfig().getAnnotationIntrospector()).isSameAs(annotationIntrospector); - assertTrue(mapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); - assertTrue(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); - assertTrue(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)); - assertTrue(mapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)); + assertThat(mapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)).isTrue(); + assertThat(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)).isTrue(); + assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)).isTrue(); + assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)).isTrue(); - assertFalse(mapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); - assertFalse(mapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); - assertFalse(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); - assertFalse(mapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); - assertFalse(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); - assertFalse(mapper.getFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)); - assertSame(JsonInclude.Include.NON_NULL, mapper.getSerializationConfig().getSerializationInclusion()); + assertThat(mapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)).isFalse(); + assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); + assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)).isFalse(); + assertThat(mapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)).isFalse(); + assertThat(mapper.getFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)).isFalse(); + assertThat(mapper.getSerializationConfig().getSerializationInclusion()).isSameAs(JsonInclude.Include.NON_NULL); } @Test public void xmlMapper() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.xml().build(); - assertNotNull(objectMapper); - assertEquals(XmlMapper.class, objectMapper.getClass()); + assertThat(objectMapper).isNotNull(); + assertThat(objectMapper.getClass()).isEqualTo(XmlMapper.class); } @Test // gh-22428 public void xmlMapperAndCustomFactory() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.xml().factory(new MyXmlFactory()).build(); - assertNotNull(objectMapper); - assertEquals(XmlMapper.class, objectMapper.getClass()); - assertEquals(MyXmlFactory.class, objectMapper.getFactory().getClass()); + assertThat(objectMapper).isNotNull(); + assertThat(objectMapper.getClass()).isEqualTo(XmlMapper.class); + assertThat(objectMapper.getFactory().getClass()).isEqualTo(MyXmlFactory.class); } @Test @@ -515,16 +507,16 @@ public class Jackson2ObjectMapperBuilderTests { Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json().indentOutput(true); ObjectMapper jsonObjectMapper = builder.build(); ObjectMapper xmlObjectMapper = builder.createXmlMapper(true).build(); - assertTrue(jsonObjectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)); - assertTrue(xmlObjectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)); - assertTrue(xmlObjectMapper.getClass().isAssignableFrom(XmlMapper.class)); + assertThat(jsonObjectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)).isTrue(); + assertThat(xmlObjectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)).isTrue(); + assertThat(xmlObjectMapper.getClass().isAssignableFrom(XmlMapper.class)).isTrue(); } @Test // SPR-13975 public void defaultUseWrapper() throws JsonProcessingException { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.xml().defaultUseWrapper(false).build(); - assertNotNull(objectMapper); - assertEquals(XmlMapper.class, objectMapper.getClass()); + assertThat(objectMapper).isNotNull(); + assertThat(objectMapper.getClass()).isEqualTo(XmlMapper.class); ListContainer container = new ListContainer<>(Arrays.asList("foo", "bar")); String output = objectMapper.writeValueAsString(container); assertThat(output).contains("foobar"); @@ -533,22 +525,22 @@ public class Jackson2ObjectMapperBuilderTests { @Test // SPR-14435 public void smile() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.smile().build(); - assertNotNull(objectMapper); - assertEquals(SmileFactory.class, objectMapper.getFactory().getClass()); + assertThat(objectMapper).isNotNull(); + assertThat(objectMapper.getFactory().getClass()).isEqualTo(SmileFactory.class); } @Test // SPR-14435 public void cbor() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.cbor().build(); - assertNotNull(objectMapper); - assertEquals(CBORFactory.class, objectMapper.getFactory().getClass()); + assertThat(objectMapper).isNotNull(); + assertThat(objectMapper.getFactory().getClass()).isEqualTo(CBORFactory.class); } @Test // SPR-14435 public void factory() { ObjectMapper objectMapper = new Jackson2ObjectMapperBuilder().factory(new SmileFactory()).build(); - assertNotNull(objectMapper); - assertEquals(SmileFactory.class, objectMapper.getFactory().getClass()); + assertThat(objectMapper).isNotNull(); + assertThat(objectMapper.getFactory().getClass()).isEqualTo(SmileFactory.class); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBeanTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBeanTests.java index a4b2d557668..d207e7c8a75 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBeanTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBeanTests.java @@ -66,12 +66,6 @@ import org.springframework.beans.FatalBeanException; import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Test cases for {@link Jackson2ObjectMapperFactoryBean}. @@ -109,41 +103,41 @@ public class Jackson2ObjectMapperFactoryBeanTests { ObjectMapper objectMapper = this.factory.getObject(); - assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); - assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); - assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); - assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS)); - assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); - assertFalse(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); - assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT)); - assertSame(Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion()); + assertThat(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)).isFalse(); + assertThat(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)).isFalse(); + assertThat(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)).isFalse(); + assertThat(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS)).isFalse(); + assertThat(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)).isFalse(); + assertThat(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT)).isTrue(); + assertThat(objectMapper.getSerializationConfig().getSerializationInclusion()).isSameAs(Include.ALWAYS); } @Test public void defaultSerializationInclusion() { this.factory.afterPropertiesSet(); - assertSame(Include.ALWAYS, this.factory.getObject().getSerializationConfig().getSerializationInclusion()); + assertThat(this.factory.getObject().getSerializationConfig().getSerializationInclusion()).isSameAs(Include.ALWAYS); } @Test public void nonNullSerializationInclusion() { this.factory.setSerializationInclusion(Include.NON_NULL); this.factory.afterPropertiesSet(); - assertSame(Include.NON_NULL, this.factory.getObject().getSerializationConfig().getSerializationInclusion()); + assertThat(this.factory.getObject().getSerializationConfig().getSerializationInclusion()).isSameAs(Include.NON_NULL); } @Test public void nonDefaultSerializationInclusion() { this.factory.setSerializationInclusion(Include.NON_DEFAULT); this.factory.afterPropertiesSet(); - assertSame(Include.NON_DEFAULT, this.factory.getObject().getSerializationConfig().getSerializationInclusion()); + assertThat(this.factory.getObject().getSerializationConfig().getSerializationInclusion()).isSameAs(Include.NON_DEFAULT); } @Test public void nonEmptySerializationInclusion() { this.factory.setSerializationInclusion(Include.NON_EMPTY); this.factory.afterPropertiesSet(); - assertSame(Include.NON_EMPTY, this.factory.getObject().getSerializationConfig().getSerializationInclusion()); + assertThat(this.factory.getObject().getSerializationConfig().getSerializationInclusion()).isSameAs(Include.NON_EMPTY); } @Test @@ -151,8 +145,8 @@ public class Jackson2ObjectMapperFactoryBeanTests { this.factory.setDateFormat(this.dateFormat); this.factory.afterPropertiesSet(); - assertEquals(this.dateFormat, this.factory.getObject().getSerializationConfig().getDateFormat()); - assertEquals(this.dateFormat, this.factory.getObject().getDeserializationConfig().getDateFormat()); + assertThat(this.factory.getObject().getSerializationConfig().getDateFormat()).isEqualTo(this.dateFormat); + assertThat(this.factory.getObject().getDeserializationConfig().getDateFormat()).isEqualTo(this.dateFormat); } @Test @@ -160,8 +154,8 @@ public class Jackson2ObjectMapperFactoryBeanTests { this.factory.setSimpleDateFormat(DATE_FORMAT); this.factory.afterPropertiesSet(); - assertEquals(this.dateFormat, this.factory.getObject().getSerializationConfig().getDateFormat()); - assertEquals(this.dateFormat, this.factory.getObject().getDeserializationConfig().getDateFormat()); + assertThat(this.factory.getObject().getSerializationConfig().getDateFormat()).isEqualTo(this.dateFormat); + assertThat(this.factory.getObject().getDeserializationConfig().getDateFormat()).isEqualTo(this.dateFormat); } @Test @@ -169,8 +163,8 @@ public class Jackson2ObjectMapperFactoryBeanTests { this.factory.setLocale(Locale.FRENCH); this.factory.afterPropertiesSet(); - assertEquals(Locale.FRENCH, this.factory.getObject().getSerializationConfig().getLocale()); - assertEquals(Locale.FRENCH, this.factory.getObject().getDeserializationConfig().getLocale()); + assertThat(this.factory.getObject().getSerializationConfig().getLocale()).isEqualTo(Locale.FRENCH); + assertThat(this.factory.getObject().getDeserializationConfig().getLocale()).isEqualTo(Locale.FRENCH); } @Test @@ -180,8 +174,8 @@ public class Jackson2ObjectMapperFactoryBeanTests { this.factory.setTimeZone(timeZone); this.factory.afterPropertiesSet(); - assertEquals(timeZone, this.factory.getObject().getSerializationConfig().getTimeZone()); - assertEquals(timeZone, this.factory.getObject().getDeserializationConfig().getTimeZone()); + assertThat(this.factory.getObject().getSerializationConfig().getTimeZone()).isEqualTo(timeZone); + assertThat(this.factory.getObject().getDeserializationConfig().getTimeZone()).isEqualTo(timeZone); } @Test @@ -190,8 +184,8 @@ public class Jackson2ObjectMapperFactoryBeanTests { this.factory.afterPropertiesSet(); TimeZone timeZone = TimeZone.getTimeZone("GMT"); - assertEquals(timeZone, this.factory.getObject().getSerializationConfig().getTimeZone()); - assertEquals(timeZone, this.factory.getObject().getDeserializationConfig().getTimeZone()); + assertThat(this.factory.getObject().getSerializationConfig().getTimeZone()).isEqualTo(timeZone); + assertThat(this.factory.getObject().getDeserializationConfig().getTimeZone()).isEqualTo(timeZone); } @Test @@ -205,7 +199,7 @@ public class Jackson2ObjectMapperFactoryBeanTests { ObjectMapper objectMapper = this.factory.getObject(); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); - assertSame(serializer, serializers.findSerializer(null, SimpleType.construct(Integer.class), null)); + assertThat(serializers.findSerializer(null, SimpleType.construct(Integer.class), null)).isSameAs(serializer); } @Test @@ -215,7 +209,7 @@ public class Jackson2ObjectMapperFactoryBeanTests { Long timestamp = 1322903730000L; DateTime dateTime = new DateTime(timestamp, DateTimeZone.UTC); - assertEquals(timestamp.toString(), new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); + assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo(timestamp.toString()); } @Test // SPR-12634 @@ -226,7 +220,7 @@ public class Jackson2ObjectMapperFactoryBeanTests { ObjectMapper objectMapper = this.factory.getObject(); DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC); - assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); + assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo("1322903730000"); assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8")).contains("customid"); } @@ -240,7 +234,7 @@ public class Jackson2ObjectMapperFactoryBeanTests { ObjectMapper objectMapper = this.factory.getObject(); DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC); - assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); + assertThat(new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")).isEqualTo("1322903730000"); assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8")).contains("customid"); } @@ -248,14 +242,14 @@ public class Jackson2ObjectMapperFactoryBeanTests { public void simpleSetup() { this.factory.afterPropertiesSet(); - assertNotNull(this.factory.getObject()); - assertTrue(this.factory.isSingleton()); - assertEquals(ObjectMapper.class, this.factory.getObjectType()); + assertThat(this.factory.getObject()).isNotNull(); + assertThat(this.factory.isSingleton()).isTrue(); + assertThat(this.factory.getObjectType()).isEqualTo(ObjectMapper.class); } @Test public void undefinedObjectType() { - assertNull(this.factory.getObjectType()); + assertThat((Object) this.factory.getObjectType()).isNull(); } private static SerializerFactoryConfig getSerializerFactoryConfig(ObjectMapper objectMapper) { @@ -272,8 +266,8 @@ public class Jackson2ObjectMapperFactoryBeanTests { this.factory.setPropertyNamingStrategy(strategy); this.factory.afterPropertiesSet(); - assertSame(strategy, this.factory.getObject().getSerializationConfig().getPropertyNamingStrategy()); - assertSame(strategy, this.factory.getObject().getDeserializationConfig().getPropertyNamingStrategy()); + assertThat(this.factory.getObject().getSerializationConfig().getPropertyNamingStrategy()).isSameAs(strategy); + assertThat(this.factory.getObject().getDeserializationConfig().getPropertyNamingStrategy()).isSameAs(strategy); } @Test @@ -288,8 +282,8 @@ public class Jackson2ObjectMapperFactoryBeanTests { this.factory.afterPropertiesSet(); ObjectMapper objectMapper = this.factory.getObject(); - assertEquals(1, objectMapper.mixInCount()); - assertSame(mixinSource, objectMapper.findMixInClassFor(target)); + assertThat(objectMapper.mixInCount()).isEqualTo(1); + assertThat(objectMapper.findMixInClassFor(target)).isSameAs(mixinSource); } @Test @@ -310,8 +304,8 @@ public class Jackson2ObjectMapperFactoryBeanTests { ObjectMapper objectMapper = new ObjectMapper(); this.factory.setObjectMapper(objectMapper); - assertTrue(this.factory.isSingleton()); - assertEquals(ObjectMapper.class, this.factory.getObjectType()); + assertThat(this.factory.isSingleton()).isTrue(); + assertThat(this.factory.getObjectType()).isEqualTo(ObjectMapper.class); Map, JsonDeserializer> deserializers = new HashMap<>(); deserializers.put(Date.class, new DateDeserializer()); @@ -336,36 +330,36 @@ public class Jackson2ObjectMapperFactoryBeanTests { JsonParser.Feature.AUTO_CLOSE_SOURCE, JsonGenerator.Feature.QUOTE_FIELD_NAMES); - assertFalse(getSerializerFactoryConfig(objectMapper).hasSerializers()); - assertFalse(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); + assertThat(getSerializerFactoryConfig(objectMapper).hasSerializers()).isFalse(); + assertThat(getDeserializerFactoryConfig(objectMapper).hasDeserializers()).isFalse(); this.factory.setSerializationInclusion(Include.NON_NULL); this.factory.afterPropertiesSet(); - assertSame(objectMapper, this.factory.getObject()); - assertTrue(getSerializerFactoryConfig(objectMapper).hasSerializers()); - assertTrue(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); + assertThat(this.factory.getObject()).isSameAs(objectMapper); + assertThat(getSerializerFactoryConfig(objectMapper).hasSerializers()).isTrue(); + assertThat(getDeserializerFactoryConfig(objectMapper).hasDeserializers()).isTrue(); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); - assertSame(serializer1, serializers.findSerializer(null, SimpleType.construct(Class.class), null)); - assertSame(serializer2, serializers.findSerializer(null, SimpleType.construct(Boolean.class), null)); - assertNull(serializers.findSerializer(null, SimpleType.construct(Number.class), null)); + assertThat(serializers.findSerializer(null, SimpleType.construct(Class.class), null)).isSameAs(serializer1); + assertThat(serializers.findSerializer(null, SimpleType.construct(Boolean.class), null)).isSameAs(serializer2); + assertThat(serializers.findSerializer(null, SimpleType.construct(Number.class), null)).isNull(); - assertSame(annotationIntrospector, objectMapper.getSerializationConfig().getAnnotationIntrospector()); - assertSame(annotationIntrospector, objectMapper.getDeserializationConfig().getAnnotationIntrospector()); + assertThat(objectMapper.getSerializationConfig().getAnnotationIntrospector()).isSameAs(annotationIntrospector); + assertThat(objectMapper.getDeserializationConfig().getAnnotationIntrospector()).isSameAs(annotationIntrospector); - assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); - assertTrue(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); - assertTrue(objectMapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)); - assertTrue(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)); + assertThat(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)).isTrue(); + assertThat(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)).isTrue(); + assertThat(objectMapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)).isTrue(); + assertThat(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)).isTrue(); - assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); - assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); - assertFalse(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); - assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); - assertFalse(objectMapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); - assertFalse(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)); - assertSame(Include.NON_NULL, objectMapper.getSerializationConfig().getSerializationInclusion()); + assertThat(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)).isFalse(); + assertThat(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); + assertThat(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)).isFalse(); + assertThat(objectMapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)).isFalse(); + assertThat(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)).isFalse(); + assertThat(objectMapper.getSerializationConfig().getSerializationInclusion()).isSameAs(Include.NON_NULL); } @Test @@ -373,9 +367,9 @@ public class Jackson2ObjectMapperFactoryBeanTests { this.factory.setObjectMapper(new XmlMapper()); this.factory.afterPropertiesSet(); - assertNotNull(this.factory.getObject()); - assertTrue(this.factory.isSingleton()); - assertEquals(XmlMapper.class, this.factory.getObjectType()); + assertThat(this.factory.getObject()).isNotNull(); + assertThat(this.factory.isSingleton()).isTrue(); + assertThat(this.factory.getObjectType()).isEqualTo(XmlMapper.class); } @Test @@ -383,9 +377,9 @@ public class Jackson2ObjectMapperFactoryBeanTests { this.factory.setCreateXmlMapper(true); this.factory.afterPropertiesSet(); - assertNotNull(this.factory.getObject()); - assertTrue(this.factory.isSingleton()); - assertEquals(XmlMapper.class, this.factory.getObjectType()); + assertThat(this.factory.getObject()).isNotNull(); + assertThat(this.factory.isSingleton()).isTrue(); + assertThat(this.factory.getObjectType()).isEqualTo(XmlMapper.class); } @Test // SPR-14435 @@ -393,9 +387,9 @@ public class Jackson2ObjectMapperFactoryBeanTests { this.factory.setFactory(new SmileFactory()); this.factory.afterPropertiesSet(); - assertNotNull(this.factory.getObject()); - assertTrue(this.factory.isSingleton()); - assertEquals(SmileFactory.class, this.factory.getObject().getFactory().getClass()); + assertThat(this.factory.getObject()).isNotNull(); + assertThat(this.factory.isSingleton()).isTrue(); + assertThat(this.factory.getObject().getFactory().getClass()).isEqualTo(SmileFactory.class); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/JsonbHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/JsonbHttpMessageConverterTests.java index 380f756f951..a862f52ddb9 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/JsonbHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/JsonbHttpMessageConverterTests.java @@ -35,10 +35,9 @@ import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; import org.springframework.http.converter.HttpMessageNotReadableException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.within; /** * Integration tests for the JSON Binding API, running against Apache Johnzon. @@ -53,20 +52,20 @@ public class JsonbHttpMessageConverterTests { @Test public void canRead() { - assertTrue(this.converter.canRead(MyBean.class, new MediaType("application", "json"))); - assertTrue(this.converter.canRead(Map.class, new MediaType("application", "json"))); + assertThat(this.converter.canRead(MyBean.class, new MediaType("application", "json"))).isTrue(); + assertThat(this.converter.canRead(Map.class, new MediaType("application", "json"))).isTrue(); } @Test public void canWrite() { - assertTrue(this.converter.canWrite(MyBean.class, new MediaType("application", "json"))); - assertTrue(this.converter.canWrite(Map.class, new MediaType("application", "json"))); + assertThat(this.converter.canWrite(MyBean.class, new MediaType("application", "json"))).isTrue(); + assertThat(this.converter.canWrite(Map.class, new MediaType("application", "json"))).isTrue(); } @Test public void canReadAndWriteMicroformats() { - assertTrue(this.converter.canRead(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))); - assertTrue(this.converter.canWrite(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))); + assertThat(this.converter.canRead(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))).isTrue(); + assertThat(this.converter.canWrite(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))).isTrue(); } @Test @@ -77,12 +76,13 @@ public class JsonbHttpMessageConverterTests { inputMessage.getHeaders().setContentType(new MediaType("application", "json")); MyBean result = (MyBean) this.converter.read(MyBean.class, inputMessage); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); } @Test @@ -93,22 +93,23 @@ public class JsonbHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); HashMap result = (HashMap) this.converter.read(HashMap.class, inputMessage); - assertEquals("Foo", result.get("string")); + assertThat(result.get("string")).isEqualTo("Foo"); Number n = (Number) result.get("number"); - assertEquals(42, n.longValue()); + assertThat(n.longValue()).isEqualTo(42); n = (Number) result.get("fraction"); - assertEquals(42D, n.doubleValue(), 0D); + assertThat(n.doubleValue()).isCloseTo(42D, within(0D)); + List array = new ArrayList<>(); array.add("Foo"); array.add("Bar"); - assertEquals(array, result.get("array")); - assertEquals(Boolean.TRUE, result.get("bool")); + assertThat(result.get("array")).isEqualTo(array); + assertThat(result.get("bool")).isEqualTo(Boolean.TRUE); byte[] bytes = new byte[2]; List resultBytes = (ArrayList)result.get("bytes"); for (int i = 0; i < 2; i++) { bytes[i] = resultBytes.get(i).byteValue(); } - assertArrayEquals(new byte[] {0x1, 0x2}, bytes); + assertThat(bytes).isEqualTo(new byte[] {0x1, 0x2}); } @Test @@ -124,14 +125,13 @@ public class JsonbHttpMessageConverterTests { this.converter.write(body, null, outputMessage); Charset utf8 = StandardCharsets.UTF_8; String result = outputMessage.getBodyAsString(utf8); - assertTrue(result.contains("\"string\":\"Foo\"")); - assertTrue(result.contains("\"number\":42")); - assertTrue(result.contains("fraction\":42.0")); - assertTrue(result.contains("\"array\":[\"Foo\",\"Bar\"]")); - assertTrue(result.contains("\"bool\":true")); - assertTrue(result.contains("\"bytes\":[1,2]")); - assertEquals("Invalid content-type", new MediaType("application", "json", utf8), - outputMessage.getHeaders().getContentType()); + assertThat(result.contains("\"string\":\"Foo\"")).isTrue(); + assertThat(result.contains("\"number\":42")).isTrue(); + assertThat(result.contains("fraction\":42.0")).isTrue(); + assertThat(result.contains("\"array\":[\"Foo\",\"Bar\"]")).isTrue(); + assertThat(result.contains("\"bool\":true")).isTrue(); + assertThat(result.contains("\"bytes\":[1,2]")).isTrue(); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "json", utf8)); } @Test @@ -147,14 +147,13 @@ public class JsonbHttpMessageConverterTests { this.converter.write(body, MyBase.class, null, outputMessage); Charset utf8 = StandardCharsets.UTF_8; String result = outputMessage.getBodyAsString(utf8); - assertTrue(result.contains("\"string\":\"Foo\"")); - assertTrue(result.contains("\"number\":42")); - assertTrue(result.contains("fraction\":42.0")); - assertTrue(result.contains("\"array\":[\"Foo\",\"Bar\"]")); - assertTrue(result.contains("\"bool\":true")); - assertTrue(result.contains("\"bytes\":[1,2]")); - assertEquals("Invalid content-type", new MediaType("application", "json", utf8), - outputMessage.getHeaders().getContentType()); + assertThat(result.contains("\"string\":\"Foo\"")).isTrue(); + assertThat(result.contains("\"number\":42")).isTrue(); + assertThat(result.contains("fraction\":42.0")).isTrue(); + assertThat(result.contains("\"array\":[\"Foo\",\"Bar\"]")).isTrue(); + assertThat(result.contains("\"bool\":true")).isTrue(); + assertThat(result.contains("\"bytes\":[1,2]")).isTrue(); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "json", utf8)); } @Test @@ -163,8 +162,8 @@ public class JsonbHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); String body = "H\u00e9llo W\u00f6rld"; this.converter.write(body, contentType, outputMessage); - assertEquals("Invalid result", body, outputMessage.getBodyAsString(StandardCharsets.UTF_16BE)); - assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_16BE)).as("Invalid result").isEqualTo(body); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(contentType); } @Test @@ -188,14 +187,15 @@ public class JsonbHttpMessageConverterTests { Type genericType = beansList.getGenericType(); List results = (List) converter.read(genericType, MyBeanListHolder.class, inputMessage); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); MyBean result = results.get(0); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(results, genericType, new MediaType("application", "json"), outputMessage); @@ -213,14 +213,15 @@ public class JsonbHttpMessageConverterTests { inputMessage.getHeaders().setContentType(new MediaType("application", "json")); List results = (List) converter.read(beansList.getType(), null, inputMessage); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); MyBean result = results.get(0); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(results, beansList.getType(), new MediaType("application", "json"), outputMessage); @@ -239,14 +240,15 @@ public class JsonbHttpMessageConverterTests { inputMessage.getHeaders().setContentType(new MediaType("application", "json")); List results = (List) converter.read(beansList.getType(), null, inputMessage); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); MyBean result = results.get(0); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(results, baseList.getType(), new MediaType("application", "json"), outputMessage); @@ -258,7 +260,7 @@ public class JsonbHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); this.converter.setPrefixJson(true); this.converter.writeInternal("foo", null, outputMessage); - assertEquals(")]}', foo", outputMessage.getBodyAsString(StandardCharsets.UTF_8)); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo(")]}', foo"); } @Test @@ -266,7 +268,7 @@ public class JsonbHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); this.converter.setJsonPrefix(")))"); this.converter.writeInternal("foo", null, outputMessage); - assertEquals(")))foo", outputMessage.getBodyAsString(StandardCharsets.UTF_8)); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo(")))foo"); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java index 9aca2bef94d..2a1b9bf9aea 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java @@ -44,9 +44,7 @@ import org.springframework.lang.Nullable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.within; /** * Jackson 2.x converter tests. @@ -64,20 +62,20 @@ public class MappingJackson2HttpMessageConverterTests { @Test public void canRead() { - assertTrue(converter.canRead(MyBean.class, new MediaType("application", "json"))); - assertTrue(converter.canRead(Map.class, new MediaType("application", "json"))); + assertThat(converter.canRead(MyBean.class, new MediaType("application", "json"))).isTrue(); + assertThat(converter.canRead(Map.class, new MediaType("application", "json"))).isTrue(); } @Test public void canWrite() { - assertTrue(converter.canWrite(MyBean.class, new MediaType("application", "json"))); - assertTrue(converter.canWrite(Map.class, new MediaType("application", "json"))); + assertThat(converter.canWrite(MyBean.class, new MediaType("application", "json"))).isTrue(); + assertThat(converter.canWrite(Map.class, new MediaType("application", "json"))).isTrue(); } @Test // SPR-7905 public void canReadAndWriteMicroformats() { - assertTrue(converter.canRead(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))); - assertTrue(converter.canWrite(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))); + assertThat(converter.canRead(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))).isTrue(); + assertThat(converter.canWrite(MyBean.class, new MediaType("application", "vnd.test-micro-type+json"))).isTrue(); } @Test @@ -92,12 +90,12 @@ public class MappingJackson2HttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); MyBean result = (MyBean) converter.read(MyBean.class, inputMessage); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); } @Test @@ -113,15 +111,15 @@ public class MappingJackson2HttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); HashMap result = (HashMap) converter.read(HashMap.class, inputMessage); - assertEquals("Foo", result.get("string")); - assertEquals(42, result.get("number")); - assertEquals(42D, (Double) result.get("fraction"), 0D); + assertThat(result.get("string")).isEqualTo("Foo"); + assertThat(result.get("number")).isEqualTo(42); + assertThat((Double) result.get("fraction")).isCloseTo(42D, within(0D)); List array = new ArrayList<>(); array.add("Foo"); array.add("Bar"); - assertEquals(array, result.get("array")); - assertEquals(Boolean.TRUE, result.get("bool")); - assertEquals("AQI=", result.get("bytes")); + assertThat(result.get("array")).isEqualTo(array); + assertThat(result.get("bool")).isEqualTo(Boolean.TRUE); + assertThat(result.get("bytes")).isEqualTo("AQI="); } @Test @@ -136,14 +134,13 @@ public class MappingJackson2HttpMessageConverterTests { body.setBytes(new byte[] {0x1, 0x2}); converter.write(body, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertTrue(result.contains("\"string\":\"Foo\"")); - assertTrue(result.contains("\"number\":42")); - assertTrue(result.contains("fraction\":42.0")); - assertTrue(result.contains("\"array\":[\"Foo\",\"Bar\"]")); - assertTrue(result.contains("\"bool\":true")); - assertTrue(result.contains("\"bytes\":\"AQI=\"")); - assertEquals("Invalid content-type", MediaType.APPLICATION_JSON, - outputMessage.getHeaders().getContentType()); + assertThat(result.contains("\"string\":\"Foo\"")).isTrue(); + assertThat(result.contains("\"number\":42")).isTrue(); + assertThat(result.contains("fraction\":42.0")).isTrue(); + assertThat(result.contains("\"array\":[\"Foo\",\"Bar\"]")).isTrue(); + assertThat(result.contains("\"bool\":true")).isTrue(); + assertThat(result.contains("\"bytes\":\"AQI=\"")).isTrue(); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(MediaType.APPLICATION_JSON); } @Test @@ -158,14 +155,13 @@ public class MappingJackson2HttpMessageConverterTests { body.setBytes(new byte[] {0x1, 0x2}); converter.write(body, MyBase.class, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertTrue(result.contains("\"string\":\"Foo\"")); - assertTrue(result.contains("\"number\":42")); - assertTrue(result.contains("fraction\":42.0")); - assertTrue(result.contains("\"array\":[\"Foo\",\"Bar\"]")); - assertTrue(result.contains("\"bool\":true")); - assertTrue(result.contains("\"bytes\":\"AQI=\"")); - assertEquals("Invalid content-type", MediaType.APPLICATION_JSON, - outputMessage.getHeaders().getContentType()); + assertThat(result.contains("\"string\":\"Foo\"")).isTrue(); + assertThat(result.contains("\"number\":42")).isTrue(); + assertThat(result.contains("fraction\":42.0")).isTrue(); + assertThat(result.contains("\"array\":[\"Foo\",\"Bar\"]")).isTrue(); + assertThat(result.contains("\"bool\":true")).isTrue(); + assertThat(result.contains("\"bytes\":\"AQI=\"")).isTrue(); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(MediaType.APPLICATION_JSON); } @Test @@ -174,8 +170,8 @@ public class MappingJackson2HttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); String body = "H\u00e9llo W\u00f6rld"; converter.write(body, contentType, outputMessage); - assertEquals("Invalid result", "\"" + body + "\"", outputMessage.getBodyAsString(StandardCharsets.UTF_16BE)); - assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_16BE)).as("Invalid result").isEqualTo(("\"" + body + "\"")); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(contentType); } @Test @@ -221,14 +217,14 @@ public class MappingJackson2HttpMessageConverterTests { inputMessage.getHeaders().setContentType(new MediaType("application", "json")); List results = (List) converter.read(List.class, inputMessage); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); MyBean result = results.get(0); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(results, new MediaType("application", "json"), outputMessage); @@ -252,14 +248,14 @@ public class MappingJackson2HttpMessageConverterTests { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); List results = (List) converter.read(beansList.getType(), null, inputMessage); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); MyBean result = results.get(0); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(results, beansList.getType(), new MediaType("application", "json"), outputMessage); @@ -284,14 +280,14 @@ public class MappingJackson2HttpMessageConverterTests { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); List results = (List) converter.read(beansList.getType(), null, inputMessage); - assertEquals(1, results.size()); + assertThat(results.size()).isEqualTo(1); MyBean result = results.get(0); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + assertThat(result.getArray()).isEqualTo(new String[] {"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[] {0x1, 0x2}); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(results, baseList.getType(), new MediaType("application", "json"), outputMessage); @@ -308,8 +304,8 @@ public class MappingJackson2HttpMessageConverterTests { this.converter.writeInternal(bean, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertEquals("{" + NEWLINE_SYSTEM_PROPERTY + - " \"name\" : \"Jason\"" + NEWLINE_SYSTEM_PROPERTY + "}", result); + assertThat(result).isEqualTo(("{" + NEWLINE_SYSTEM_PROPERTY + + " \"name\" : \"Jason\"" + NEWLINE_SYSTEM_PROPERTY + "}")); } @Test @@ -323,7 +319,7 @@ public class MappingJackson2HttpMessageConverterTests { this.converter.writeInternal(bean, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertEquals("{\ndata: \"name\" : \"Jason\"\ndata:}", result); + assertThat(result).isEqualTo("{\ndata: \"name\" : \"Jason\"\ndata:}"); } @Test @@ -332,7 +328,7 @@ public class MappingJackson2HttpMessageConverterTests { this.converter.setPrefixJson(true); this.converter.writeInternal("foo", null, outputMessage); - assertEquals(")]}', \"foo\"", outputMessage.getBodyAsString(StandardCharsets.UTF_8)); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo(")]}', \"foo\""); } @Test @@ -341,7 +337,7 @@ public class MappingJackson2HttpMessageConverterTests { this.converter.setJsonPrefix(")))"); this.converter.writeInternal("foo", null, outputMessage); - assertEquals(")))\"foo\"", outputMessage.getBodyAsString(StandardCharsets.UTF_8)); + assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8)).isEqualTo(")))\"foo\""); } @Test @@ -408,8 +404,8 @@ public class MappingJackson2HttpMessageConverterTests { this.converter.writeInternal(bean, MyInterface.class, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertTrue(result.contains("\"string\":\"Foo\"")); - assertTrue(result.contains("\"number\":42")); + assertThat(result.contains("\"string\":\"Foo\"")).isTrue(); + assertThat(result.contains("\"number\":42")).isTrue(); } @Test // SPR-13318 @@ -430,10 +426,10 @@ public class MappingJackson2HttpMessageConverterTests { this.converter.writeInternal(beans, typeReference.getType(), outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertTrue(result.contains("\"string\":\"Foo\"")); - assertTrue(result.contains("\"number\":42")); - assertTrue(result.contains("\"string\":\"Bar\"")); - assertTrue(result.contains("\"number\":123")); + assertThat(result.contains("\"string\":\"Foo\"")).isTrue(); + assertThat(result.contains("\"number\":42")).isTrue(); + assertThat(result.contains("\"string\":\"Bar\"")).isTrue(); + assertThat(result.contains("\"number\":123")).isTrue(); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/converter/json/SpringHandlerInstantiatorTests.java b/spring-web/src/test/java/org/springframework/http/converter/json/SpringHandlerInstantiatorTests.java index 3b41cd2d003..a5e27def477 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/json/SpringHandlerInstantiatorTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/json/SpringHandlerInstantiatorTests.java @@ -55,9 +55,7 @@ import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostP import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test class for {@link SpringHandlerInstantiatorTests}. @@ -87,34 +85,34 @@ public class SpringHandlerInstantiatorTests { public void autowiredSerializer() throws JsonProcessingException { User user = new User("bob"); String json = this.objectMapper.writeValueAsString(user); - assertEquals("{\"username\":\"BOB\"}", json); + assertThat(json).isEqualTo("{\"username\":\"BOB\"}"); } @Test public void autowiredDeserializer() throws IOException { String json = "{\"username\":\"bob\"}"; User user = this.objectMapper.readValue(json, User.class); - assertEquals("BOB", user.getUsername()); + assertThat(user.getUsername()).isEqualTo("BOB"); } @Test public void autowiredKeyDeserializer() throws IOException { String json = "{\"credentials\":{\"bob\":\"admin\"}}"; SecurityRegistry registry = this.objectMapper.readValue(json, SecurityRegistry.class); - assertTrue(registry.getCredentials().keySet().contains("BOB")); - assertFalse(registry.getCredentials().keySet().contains("bob")); + assertThat(registry.getCredentials().keySet().contains("BOB")).isTrue(); + assertThat(registry.getCredentials().keySet().contains("bob")).isFalse(); } @Test public void applicationContextAwaretypeResolverBuilder() throws JsonProcessingException { this.objectMapper.writeValueAsString(new Group()); - assertTrue(CustomTypeResolverBuilder.isAutowiredFiledInitialized); + assertThat(CustomTypeResolverBuilder.isAutowiredFiledInitialized).isTrue(); } @Test public void applicationContextAwareTypeIdResolver() throws JsonProcessingException { this.objectMapper.writeValueAsString(new Group()); - assertTrue(CustomTypeIdResolver.isAutowiredFiledInitialized); + assertThat(CustomTypeIdResolver.isAutowiredFiledInitialized).isTrue(); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/protobuf/ProtobufHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/protobuf/ProtobufHttpMessageConverterTests.java index e4572356975..47855a18ef0 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/protobuf/ProtobufHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/protobuf/ProtobufHttpMessageConverterTests.java @@ -31,11 +31,7 @@ import org.springframework.http.MockHttpOutputMessage; import org.springframework.protobuf.Msg; import org.springframework.protobuf.SecondMsg; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -78,35 +74,35 @@ public class ProtobufHttpMessageConverterTests { @Test public void extensionRegistryInitializerNull() { ProtobufHttpMessageConverter converter = new ProtobufHttpMessageConverter((ExtensionRegistryInitializer)null); - assertNotNull(converter.extensionRegistry); + assertThat(converter.extensionRegistry).isNotNull(); } @Test public void extensionRegistryNull() { ProtobufHttpMessageConverter converter = new ProtobufHttpMessageConverter((ExtensionRegistry)null); - assertNotNull(converter.extensionRegistry); + assertThat(converter.extensionRegistry).isNotNull(); } @Test public void canRead() { - assertTrue(this.converter.canRead(Msg.class, null)); - assertTrue(this.converter.canRead(Msg.class, ProtobufHttpMessageConverter.PROTOBUF)); - assertTrue(this.converter.canRead(Msg.class, MediaType.APPLICATION_JSON)); - assertTrue(this.converter.canRead(Msg.class, MediaType.APPLICATION_XML)); - assertTrue(this.converter.canRead(Msg.class, MediaType.TEXT_PLAIN)); + assertThat(this.converter.canRead(Msg.class, null)).isTrue(); + assertThat(this.converter.canRead(Msg.class, ProtobufHttpMessageConverter.PROTOBUF)).isTrue(); + assertThat(this.converter.canRead(Msg.class, MediaType.APPLICATION_JSON)).isTrue(); + assertThat(this.converter.canRead(Msg.class, MediaType.APPLICATION_XML)).isTrue(); + assertThat(this.converter.canRead(Msg.class, MediaType.TEXT_PLAIN)).isTrue(); // only supported as an output format - assertFalse(this.converter.canRead(Msg.class, MediaType.TEXT_HTML)); + assertThat(this.converter.canRead(Msg.class, MediaType.TEXT_HTML)).isFalse(); } @Test public void canWrite() { - assertTrue(this.converter.canWrite(Msg.class, null)); - assertTrue(this.converter.canWrite(Msg.class, ProtobufHttpMessageConverter.PROTOBUF)); - assertTrue(this.converter.canWrite(Msg.class, MediaType.APPLICATION_JSON)); - assertTrue(this.converter.canWrite(Msg.class, MediaType.APPLICATION_XML)); - assertTrue(this.converter.canWrite(Msg.class, MediaType.TEXT_PLAIN)); - assertTrue(this.converter.canWrite(Msg.class, MediaType.TEXT_HTML)); + assertThat(this.converter.canWrite(Msg.class, null)).isTrue(); + assertThat(this.converter.canWrite(Msg.class, ProtobufHttpMessageConverter.PROTOBUF)).isTrue(); + assertThat(this.converter.canWrite(Msg.class, MediaType.APPLICATION_JSON)).isTrue(); + assertThat(this.converter.canWrite(Msg.class, MediaType.APPLICATION_XML)).isTrue(); + assertThat(this.converter.canWrite(Msg.class, MediaType.TEXT_PLAIN)).isTrue(); + assertThat(this.converter.canWrite(Msg.class, MediaType.TEXT_HTML)).isTrue(); } @Test @@ -115,7 +111,7 @@ public class ProtobufHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); inputMessage.getHeaders().setContentType(ProtobufHttpMessageConverter.PROTOBUF); Message result = this.converter.read(Msg.class, inputMessage); - assertEquals(this.testMsg, result); + assertThat(result).isEqualTo(this.testMsg); } @Test @@ -123,7 +119,7 @@ public class ProtobufHttpMessageConverterTests { byte[] body = this.testMsg.toByteArray(); MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); Message result = this.converter.read(Msg.class, inputMessage); - assertEquals(this.testMsg, result); + assertThat(result).isEqualTo(this.testMsg); } @Test @@ -131,17 +127,17 @@ public class ProtobufHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MediaType contentType = ProtobufHttpMessageConverter.PROTOBUF; this.converter.write(this.testMsg, contentType, outputMessage); - assertEquals(contentType, outputMessage.getHeaders().getContentType()); - assertTrue(outputMessage.getBodyAsBytes().length > 0); + assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(contentType); + assertThat(outputMessage.getBodyAsBytes().length > 0).isTrue(); Message result = Msg.parseFrom(outputMessage.getBodyAsBytes()); - assertEquals(this.testMsg, result); + assertThat(result).isEqualTo(this.testMsg); String messageHeader = outputMessage.getHeaders().getFirst(ProtobufHttpMessageConverter.X_PROTOBUF_MESSAGE_HEADER); - assertEquals("Msg", messageHeader); + assertThat(messageHeader).isEqualTo("Msg"); String schemaHeader = outputMessage.getHeaders().getFirst(ProtobufHttpMessageConverter.X_PROTOBUF_SCHEMA_HEADER); - assertEquals("sample.proto", schemaHeader); + assertThat(schemaHeader).isEqualTo("sample.proto"); } @Test @@ -153,19 +149,19 @@ public class ProtobufHttpMessageConverterTests { MediaType contentType = MediaType.APPLICATION_JSON; this.converter.write(this.testMsg, contentType, outputMessage); - assertEquals(contentType, outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(contentType); final String body = outputMessage.getBodyAsString(Charset.forName("UTF-8")); - assertFalse("body is empty", body.isEmpty()); + assertThat(body.isEmpty()).as("body is empty").isFalse(); Msg.Builder builder = Msg.newBuilder(); JsonFormat.parser().merge(body, builder); - assertEquals(this.testMsg, builder.build()); + assertThat(builder.build()).isEqualTo(this.testMsg); - assertNull(outputMessage.getHeaders().getFirst( - ProtobufHttpMessageConverter.X_PROTOBUF_MESSAGE_HEADER)); - assertNull(outputMessage.getHeaders().getFirst( - ProtobufHttpMessageConverter.X_PROTOBUF_SCHEMA_HEADER)); + assertThat(outputMessage.getHeaders().getFirst( + ProtobufHttpMessageConverter.X_PROTOBUF_MESSAGE_HEADER)).isNull(); + assertThat(outputMessage.getHeaders().getFirst( + ProtobufHttpMessageConverter.X_PROTOBUF_SCHEMA_HEADER)).isNull(); } @Test @@ -177,24 +173,24 @@ public class ProtobufHttpMessageConverterTests { MediaType contentType = MediaType.APPLICATION_JSON_UTF8; this.converter.write(this.testMsg, contentType, outputMessage); - assertEquals(contentType, outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(contentType); final String body = outputMessage.getBodyAsString(Charset.forName("UTF-8")); - assertFalse("body is empty", body.isEmpty()); + assertThat(body.isEmpty()).as("body is empty").isFalse(); Msg.Builder builder = Msg.newBuilder(); JsonFormat.parser().merge(body, builder); - assertEquals(this.testMsg, builder.build()); + assertThat(builder.build()).isEqualTo(this.testMsg); - assertNull(outputMessage.getHeaders().getFirst( - ProtobufHttpMessageConverter.X_PROTOBUF_MESSAGE_HEADER)); - assertNull(outputMessage.getHeaders().getFirst( - ProtobufHttpMessageConverter.X_PROTOBUF_SCHEMA_HEADER)); + assertThat(outputMessage.getHeaders().getFirst( + ProtobufHttpMessageConverter.X_PROTOBUF_MESSAGE_HEADER)).isNull(); + assertThat(outputMessage.getHeaders().getFirst( + ProtobufHttpMessageConverter.X_PROTOBUF_SCHEMA_HEADER)).isNull(); } @Test public void defaultContentType() throws Exception { - assertEquals(ProtobufHttpMessageConverter.PROTOBUF, this.converter.getDefaultContentType(this.testMsg)); + assertThat(this.converter.getDefaultContentType(this.testMsg)).isEqualTo(ProtobufHttpMessageConverter.PROTOBUF); } @Test @@ -202,7 +198,7 @@ public class ProtobufHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MediaType contentType = ProtobufHttpMessageConverter.PROTOBUF; this.converter.write(this.testMsg, contentType, outputMessage); - assertEquals(-1, outputMessage.getHeaders().getContentLength()); + assertThat(outputMessage.getHeaders().getContentLength()).isEqualTo(-1); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/protobuf/ProtobufJsonFormatHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/protobuf/ProtobufJsonFormatHttpMessageConverterTests.java index 1b3b2be574d..af4825418f4 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/protobuf/ProtobufJsonFormatHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/protobuf/ProtobufJsonFormatHttpMessageConverterTests.java @@ -29,9 +29,7 @@ import org.springframework.http.MockHttpOutputMessage; import org.springframework.protobuf.Msg; import org.springframework.protobuf.SecondMsg; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -62,29 +60,29 @@ public class ProtobufJsonFormatHttpMessageConverterTests { @Test public void extensionRegistryInitializerNull() { ProtobufHttpMessageConverter converter = new ProtobufHttpMessageConverter((ExtensionRegistryInitializer)null); - assertNotNull(converter); + assertThat(converter).isNotNull(); } @Test public void extensionRegistryInitializer() { ProtobufHttpMessageConverter converter = new ProtobufHttpMessageConverter((ExtensionRegistry)null); - assertNotNull(converter); + assertThat(converter).isNotNull(); } @Test public void canRead() { - assertTrue(this.converter.canRead(Msg.class, null)); - assertTrue(this.converter.canRead(Msg.class, ProtobufHttpMessageConverter.PROTOBUF)); - assertTrue(this.converter.canRead(Msg.class, MediaType.APPLICATION_JSON)); - assertTrue(this.converter.canRead(Msg.class, MediaType.TEXT_PLAIN)); + assertThat(this.converter.canRead(Msg.class, null)).isTrue(); + assertThat(this.converter.canRead(Msg.class, ProtobufHttpMessageConverter.PROTOBUF)).isTrue(); + assertThat(this.converter.canRead(Msg.class, MediaType.APPLICATION_JSON)).isTrue(); + assertThat(this.converter.canRead(Msg.class, MediaType.TEXT_PLAIN)).isTrue(); } @Test public void canWrite() { - assertTrue(this.converter.canWrite(Msg.class, null)); - assertTrue(this.converter.canWrite(Msg.class, ProtobufHttpMessageConverter.PROTOBUF)); - assertTrue(this.converter.canWrite(Msg.class, MediaType.APPLICATION_JSON)); - assertTrue(this.converter.canWrite(Msg.class, MediaType.TEXT_PLAIN)); + assertThat(this.converter.canWrite(Msg.class, null)).isTrue(); + assertThat(this.converter.canWrite(Msg.class, ProtobufHttpMessageConverter.PROTOBUF)).isTrue(); + assertThat(this.converter.canWrite(Msg.class, MediaType.APPLICATION_JSON)).isTrue(); + assertThat(this.converter.canWrite(Msg.class, MediaType.TEXT_PLAIN)).isTrue(); } @Test @@ -93,7 +91,7 @@ public class ProtobufJsonFormatHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); inputMessage.getHeaders().setContentType(ProtobufHttpMessageConverter.PROTOBUF); Message result = this.converter.read(Msg.class, inputMessage); - assertEquals(this.testMsg, result); + assertThat(result).isEqualTo(this.testMsg); } @Test @@ -101,7 +99,7 @@ public class ProtobufJsonFormatHttpMessageConverterTests { byte[] body = this.testMsg.toByteArray(); MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); Message result = this.converter.read(Msg.class, inputMessage); - assertEquals(this.testMsg, result); + assertThat(result).isEqualTo(this.testMsg); } @Test @@ -109,22 +107,22 @@ public class ProtobufJsonFormatHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MediaType contentType = ProtobufHttpMessageConverter.PROTOBUF; this.converter.write(this.testMsg, contentType, outputMessage); - assertEquals(contentType, outputMessage.getHeaders().getContentType()); - assertTrue(outputMessage.getBodyAsBytes().length > 0); + assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(contentType); + assertThat(outputMessage.getBodyAsBytes().length > 0).isTrue(); Message result = Msg.parseFrom(outputMessage.getBodyAsBytes()); - assertEquals(this.testMsg, result); + assertThat(result).isEqualTo(this.testMsg); String messageHeader = outputMessage.getHeaders().getFirst(ProtobufHttpMessageConverter.X_PROTOBUF_MESSAGE_HEADER); - assertEquals("Msg", messageHeader); + assertThat(messageHeader).isEqualTo("Msg"); String schemaHeader = outputMessage.getHeaders().getFirst(ProtobufHttpMessageConverter.X_PROTOBUF_SCHEMA_HEADER); - assertEquals("sample.proto", schemaHeader); + assertThat(schemaHeader).isEqualTo("sample.proto"); } @Test public void defaultContentType() throws Exception { - assertEquals(ProtobufHttpMessageConverter.PROTOBUF, this.converter.getDefaultContentType(this.testMsg)); + assertThat(this.converter.getDefaultContentType(this.testMsg)).isEqualTo(ProtobufHttpMessageConverter.PROTOBUF); } @Test @@ -132,7 +130,7 @@ public class ProtobufJsonFormatHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MediaType contentType = ProtobufHttpMessageConverter.PROTOBUF; this.converter.write(this.testMsg, contentType, outputMessage); - assertEquals(-1, outputMessage.getHeaders().getContentLength()); + assertThat(outputMessage.getHeaders().getContentLength()).isEqualTo(-1); } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/smile/MappingJackson2SmileHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/smile/MappingJackson2SmileHttpMessageConverterTests.java index 61a7dd6dec4..c493456546c 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/smile/MappingJackson2SmileHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/smile/MappingJackson2SmileHttpMessageConverterTests.java @@ -26,10 +26,8 @@ import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; /** * Jackson 2.x Smile converter tests. @@ -44,16 +42,16 @@ public class MappingJackson2SmileHttpMessageConverterTests { @Test public void canRead() { - assertTrue(converter.canRead(MyBean.class, new MediaType("application", "x-jackson-smile"))); - assertFalse(converter.canRead(MyBean.class, new MediaType("application", "json"))); - assertFalse(converter.canRead(MyBean.class, new MediaType("application", "xml"))); + assertThat(converter.canRead(MyBean.class, new MediaType("application", "x-jackson-smile"))).isTrue(); + assertThat(converter.canRead(MyBean.class, new MediaType("application", "json"))).isFalse(); + assertThat(converter.canRead(MyBean.class, new MediaType("application", "xml"))).isFalse(); } @Test public void canWrite() { - assertTrue(converter.canWrite(MyBean.class, new MediaType("application", "x-jackson-smile"))); - assertFalse(converter.canWrite(MyBean.class, new MediaType("application", "json"))); - assertFalse(converter.canWrite(MyBean.class, new MediaType("application", "xml"))); + assertThat(converter.canWrite(MyBean.class, new MediaType("application", "x-jackson-smile"))).isTrue(); + assertThat(converter.canWrite(MyBean.class, new MediaType("application", "json"))).isFalse(); + assertThat(converter.canWrite(MyBean.class, new MediaType("application", "xml"))).isFalse(); } @Test @@ -68,12 +66,13 @@ public class MappingJackson2SmileHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(mapper.writeValueAsBytes(body)); inputMessage.getHeaders().setContentType(new MediaType("application", "x-jackson-smile")); MyBean result = (MyBean) converter.read(MyBean.class, inputMessage); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[]{"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[]{0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + + assertThat(result.getArray()).isEqualTo(new String[]{"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[]{0x1, 0x2}); } @Test @@ -87,9 +86,8 @@ public class MappingJackson2SmileHttpMessageConverterTests { body.setBool(true); body.setBytes(new byte[]{0x1, 0x2}); converter.write(body, null, outputMessage); - assertArrayEquals(mapper.writeValueAsBytes(body), outputMessage.getBodyAsBytes()); - assertEquals("Invalid content-type", new MediaType("application", "x-jackson-smile"), - outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getBodyAsBytes()).isEqualTo(mapper.writeValueAsBytes(body)); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "x-jackson-smile")); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverterTests.java index d6615723447..61e7a43727f 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverterTests.java @@ -35,9 +35,8 @@ import org.springframework.core.io.Resource; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.converter.HttpMessageNotReadableException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Test fixture for {@link Jaxb2CollectionHttpMessageConverter}. @@ -70,9 +69,9 @@ public class Jaxb2CollectionHttpMessageConverterTests { @Test public void canRead() { - assertTrue(converter.canRead(rootElementListType, null, null)); - assertTrue(converter.canRead(rootElementSetType, null, null)); - assertTrue(converter.canRead(typeSetType, null, null)); + assertThat(converter.canRead(rootElementListType, null, null)).isTrue(); + assertThat(converter.canRead(rootElementSetType, null, null)).isTrue(); + assertThat(converter.canRead(typeSetType, null, null)).isTrue(); } @Test @@ -82,9 +81,9 @@ public class Jaxb2CollectionHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8")); List result = (List) converter.read(rootElementListType, null, inputMessage); - assertEquals("Invalid result", 2, result.size()); - assertEquals("Invalid result", "1", result.get(0).type.s); - assertEquals("Invalid result", "2", result.get(1).type.s); + assertThat(result.size()).as("Invalid result").isEqualTo(2); + assertThat(result.get(0).type.s).as("Invalid result").isEqualTo("1"); + assertThat(result.get(1).type.s).as("Invalid result").isEqualTo("2"); } @Test @@ -94,9 +93,9 @@ public class Jaxb2CollectionHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8")); Set result = (Set) converter.read(rootElementSetType, null, inputMessage); - assertEquals("Invalid result", 2, result.size()); - assertTrue("Invalid result", result.contains(new RootElement("1"))); - assertTrue("Invalid result", result.contains(new RootElement("2"))); + assertThat(result.size()).as("Invalid result").isEqualTo(2); + assertThat(result.contains(new RootElement("1"))).as("Invalid result").isTrue(); + assertThat(result.contains(new RootElement("2"))).as("Invalid result").isTrue(); } @Test @@ -106,9 +105,9 @@ public class Jaxb2CollectionHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8")); List result = (List) converter.read(typeListType, null, inputMessage); - assertEquals("Invalid result", 2, result.size()); - assertEquals("Invalid result", "1", result.get(0).s); - assertEquals("Invalid result", "2", result.get(1).s); + assertThat(result.size()).as("Invalid result").isEqualTo(2); + assertThat(result.get(0).s).as("Invalid result").isEqualTo("1"); + assertThat(result.get(1).s).as("Invalid result").isEqualTo("2"); } @Test @@ -118,9 +117,9 @@ public class Jaxb2CollectionHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8")); Set result = (Set) converter.read(typeSetType, null, inputMessage); - assertEquals("Invalid result", 2, result.size()); - assertTrue("Invalid result", result.contains(new TestType("1"))); - assertTrue("Invalid result", result.contains(new TestType("2"))); + assertThat(result.size()).as("Invalid result").isEqualTo(2); + assertThat(result.contains(new TestType("1"))).as("Invalid result").isTrue(); + assertThat(result.contains(new TestType("2"))).as("Invalid result").isTrue(); } @Test @@ -144,8 +143,8 @@ public class Jaxb2CollectionHttpMessageConverterTests { try { Collection result = converter.read(rootElementListType, null, inputMessage); - assertEquals(1, result.size()); - assertEquals("", result.iterator().next().external); + assertThat(result.size()).isEqualTo(1); + assertThat(result.iterator().next().external).isEqualTo(""); } catch (HttpMessageNotReadableException ex) { // Some parsers raise an exception @@ -172,8 +171,8 @@ public class Jaxb2CollectionHttpMessageConverterTests { }; Collection result = c.read(rootElementListType, null, inputMessage); - assertEquals(1, result.size()); - assertEquals("Foo Bar", result.iterator().next().external); + assertThat(result.size()).isEqualTo(1); + assertThat(result.iterator().next().external).isEqualTo("Foo Bar"); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverterTests.java index 6a7e3049772..c849b95a037 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverterTests.java @@ -43,9 +43,6 @@ import org.springframework.tests.XmlContent; import static org.assertj.core.api.Assertions.assertThat; 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; import static org.xmlunit.diff.ComparisonType.XML_STANDALONE; import static org.xmlunit.diff.DifferenceEvaluators.Default; import static org.xmlunit.diff.DifferenceEvaluators.chain; @@ -82,21 +79,16 @@ public class Jaxb2RootElementHttpMessageConverterTests { @Test public void canRead() { - assertTrue("Converter does not support reading @XmlRootElement", - converter.canRead(RootElement.class, null)); - assertTrue("Converter does not support reading @XmlType", - converter.canRead(Type.class, null)); + assertThat(converter.canRead(RootElement.class, null)).as("Converter does not support reading @XmlRootElement").isTrue(); + assertThat(converter.canRead(Type.class, null)).as("Converter does not support reading @XmlType").isTrue(); } @Test public void canWrite() { - assertTrue("Converter does not support writing @XmlRootElement", - converter.canWrite(RootElement.class, null)); - assertTrue("Converter does not support writing @XmlRootElement subclass", - converter.canWrite(RootElementSubclass.class, null)); - assertTrue("Converter does not support writing @XmlRootElement subclass", - converter.canWrite(rootElementCglib.getClass(), null)); - assertFalse("Converter supports writing @XmlType", converter.canWrite(Type.class, null)); + assertThat(converter.canWrite(RootElement.class, null)).as("Converter does not support writing @XmlRootElement").isTrue(); + assertThat(converter.canWrite(RootElementSubclass.class, null)).as("Converter does not support writing @XmlRootElement subclass").isTrue(); + assertThat(converter.canWrite(rootElementCglib.getClass(), null)).as("Converter does not support writing @XmlRootElement subclass").isTrue(); + assertThat(converter.canWrite(Type.class, null)).as("Converter supports writing @XmlType").isFalse(); } @Test @@ -104,7 +96,7 @@ public class Jaxb2RootElementHttpMessageConverterTests { byte[] body = "".getBytes("UTF-8"); MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); RootElement result = (RootElement) converter.read(RootElement.class, inputMessage); - assertEquals("Invalid result", "Hello World", result.type.s); + assertThat(result.type.s).as("Invalid result").isEqualTo("Hello World"); } @Test @@ -112,7 +104,7 @@ public class Jaxb2RootElementHttpMessageConverterTests { byte[] body = "".getBytes("UTF-8"); MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); RootElementSubclass result = (RootElementSubclass) converter.read(RootElementSubclass.class, inputMessage); - assertEquals("Invalid result", "Hello World", result.getType().s); + assertThat(result.getType().s).as("Invalid result").isEqualTo("Hello World"); } @Test @@ -120,7 +112,7 @@ public class Jaxb2RootElementHttpMessageConverterTests { byte[] body = "".getBytes("UTF-8"); MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); Type result = (Type) converter.read(Type.class, inputMessage); - assertEquals("Invalid result", "Hello World", result.s); + assertThat(result.s).as("Invalid result").isEqualTo("Hello World"); } @Test @@ -134,7 +126,7 @@ public class Jaxb2RootElementHttpMessageConverterTests { converter.setSupportDtd(true); RootElement rootElement = (RootElement) converter.read(RootElement.class, inputMessage); - assertEquals("", rootElement.external); + assertThat(rootElement.external).isEqualTo(""); } @Test @@ -148,7 +140,7 @@ public class Jaxb2RootElementHttpMessageConverterTests { this.converter.setProcessExternalEntities(true); RootElement rootElement = (RootElement) converter.read(RootElement.class, inputMessage); - assertEquals("Foo Bar", rootElement.external); + assertThat(rootElement.external).isEqualTo("Foo Bar"); } @Test @@ -180,8 +172,7 @@ public class Jaxb2RootElementHttpMessageConverterTests { public void writeXmlRootElement() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(rootElement, null, outputMessage); - assertEquals("Invalid content-type", new MediaType("application", "xml"), - outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "xml")); DifferenceEvaluator ev = chain(Default, downgradeDifferencesToEqual(XML_STANDALONE)); assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) .isSimilarTo("", ev); @@ -191,8 +182,7 @@ public class Jaxb2RootElementHttpMessageConverterTests { public void writeXmlRootElementSubclass() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(rootElementCglib, null, outputMessage); - assertEquals("Invalid content-type", new MediaType("application", "xml"), - outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "xml")); DifferenceEvaluator ev = chain(Default, downgradeDifferencesToEqual(XML_STANDALONE)); assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) .isSimilarTo("", ev); @@ -216,8 +206,8 @@ public class Jaxb2RootElementHttpMessageConverterTests { MyJaxb2RootElementHttpMessageConverter myConverter = new MyJaxb2RootElementHttpMessageConverter(); MockHttpInputMessage inputMessage = new MockHttpInputMessage(body); MyRootElement result = (MyRootElement) myConverter.read(MyRootElement.class, inputMessage); - assertEquals("a", result.getElement().getField1()); - assertEquals("b", result.getElement().getField2()); + assertThat(result.getElement().getField1()).isEqualTo("a"); + assertThat(result.getElement().getField2()).isEqualTo("b"); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverterTests.java index 88d9000618c..b267a21c40d 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverterTests.java @@ -32,9 +32,7 @@ import org.springframework.http.converter.json.MappingJacksonValue; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.within; /** * Jackson 2.x XML converter tests. @@ -49,16 +47,16 @@ public class MappingJackson2XmlHttpMessageConverterTests { @Test public void canRead() { - assertTrue(converter.canRead(MyBean.class, new MediaType("application", "xml"))); - assertTrue(converter.canRead(MyBean.class, new MediaType("text", "xml"))); - assertTrue(converter.canRead(MyBean.class, new MediaType("application", "soap+xml"))); + assertThat(converter.canRead(MyBean.class, new MediaType("application", "xml"))).isTrue(); + assertThat(converter.canRead(MyBean.class, new MediaType("text", "xml"))).isTrue(); + assertThat(converter.canRead(MyBean.class, new MediaType("application", "soap+xml"))).isTrue(); } @Test public void canWrite() { - assertTrue(converter.canWrite(MyBean.class, new MediaType("application", "xml"))); - assertTrue(converter.canWrite(MyBean.class, new MediaType("text", "xml"))); - assertTrue(converter.canWrite(MyBean.class, new MediaType("application", "soap+xml"))); + assertThat(converter.canWrite(MyBean.class, new MediaType("application", "xml"))).isTrue(); + assertThat(converter.canWrite(MyBean.class, new MediaType("text", "xml"))).isTrue(); + assertThat(converter.canWrite(MyBean.class, new MediaType("application", "soap+xml"))).isTrue(); } @Test @@ -74,12 +72,12 @@ public class MappingJackson2XmlHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); inputMessage.getHeaders().setContentType(new MediaType("application", "xml")); MyBean result = (MyBean) converter.read(MyBean.class, inputMessage); - assertEquals("Foo", result.getString()); - assertEquals(42, result.getNumber()); - assertEquals(42F, result.getFraction(), 0F); - assertArrayEquals(new String[]{"Foo", "Bar"}, result.getArray()); - assertTrue(result.isBool()); - assertArrayEquals(new byte[]{0x1, 0x2}, result.getBytes()); + assertThat(result.getString()).isEqualTo("Foo"); + assertThat(result.getNumber()).isEqualTo(42); + assertThat(result.getFraction()).isCloseTo(42F, within(0F)); + assertThat(result.getArray()).isEqualTo(new String[]{"Foo", "Bar"}); + assertThat(result.isBool()).isTrue(); + assertThat(result.getBytes()).isEqualTo(new byte[]{0x1, 0x2}); } @Test @@ -94,14 +92,13 @@ public class MappingJackson2XmlHttpMessageConverterTests { body.setBytes(new byte[]{0x1, 0x2}); converter.write(body, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertTrue(result.contains("Foo")); - assertTrue(result.contains("42")); - assertTrue(result.contains("42.0")); - assertTrue(result.contains("FooBar")); - assertTrue(result.contains("true")); - assertTrue(result.contains("AQI=")); - assertEquals("Invalid content-type", new MediaType("application", "xml", StandardCharsets.UTF_8), - outputMessage.getHeaders().getContentType()); + assertThat(result.contains("Foo")).isTrue(); + assertThat(result.contains("42")).isTrue(); + assertThat(result.contains("42.0")).isTrue(); + assertThat(result.contains("FooBar")).isTrue(); + assertThat(result.contains("true")).isTrue(); + assertThat(result.contains("AQI=")).isTrue(); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "xml", StandardCharsets.UTF_8)); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java index f1709542784..f24d4655615 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java @@ -32,10 +32,8 @@ import org.springframework.oxm.MarshallingFailureException; import org.springframework.oxm.Unmarshaller; import org.springframework.oxm.UnmarshallingFailureException; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; @@ -60,9 +58,9 @@ public class MarshallingHttpMessageConverterTests { MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(); converter.setUnmarshaller(unmarshaller); - assertFalse(converter.canRead(Boolean.class, MediaType.TEXT_PLAIN)); - assertFalse(converter.canRead(Integer.class, MediaType.TEXT_XML)); - assertTrue(converter.canRead(String.class, MediaType.TEXT_XML)); + assertThat(converter.canRead(Boolean.class, MediaType.TEXT_PLAIN)).isFalse(); + assertThat(converter.canRead(Integer.class, MediaType.TEXT_XML)).isFalse(); + assertThat(converter.canRead(String.class, MediaType.TEXT_XML)).isTrue(); } @Test @@ -75,9 +73,9 @@ public class MarshallingHttpMessageConverterTests { MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(); converter.setMarshaller(marshaller); - assertFalse(converter.canWrite(Boolean.class, MediaType.TEXT_PLAIN)); - assertFalse(converter.canWrite(Integer.class, MediaType.TEXT_XML)); - assertTrue(converter.canWrite(String.class, MediaType.TEXT_XML)); + assertThat(converter.canWrite(Boolean.class, MediaType.TEXT_PLAIN)).isFalse(); + assertThat(converter.canWrite(Integer.class, MediaType.TEXT_XML)).isFalse(); + assertThat(converter.canWrite(String.class, MediaType.TEXT_XML)).isTrue(); } @Test @@ -92,7 +90,7 @@ public class MarshallingHttpMessageConverterTests { converter.setUnmarshaller(unmarshaller); String result = (String) converter.read(Object.class, inputMessage); - assertEquals("Invalid result", body, result); + assertThat(result).as("Invalid result").isEqualTo(body); } @Test @@ -136,8 +134,7 @@ public class MarshallingHttpMessageConverterTests { MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller); converter.write(body, null, outputMessage); - assertEquals("Invalid content-type", new MediaType("application", "xml"), - outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "xml")); } @Test diff --git a/spring-web/src/test/java/org/springframework/http/converter/xml/SourceHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/xml/SourceHttpMessageConverterTests.java index 3bfce9c5fb5..77269ff17f3 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/xml/SourceHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/xml/SourceHttpMessageConverterTests.java @@ -49,9 +49,6 @@ import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; /** * @author Arjen Poutsma @@ -79,15 +76,15 @@ public class SourceHttpMessageConverterTests { @Test public void canRead() { - assertTrue(converter.canRead(Source.class, new MediaType("application", "xml"))); - assertTrue(converter.canRead(Source.class, new MediaType("application", "soap+xml"))); + assertThat(converter.canRead(Source.class, new MediaType("application", "xml"))).isTrue(); + assertThat(converter.canRead(Source.class, new MediaType("application", "soap+xml"))).isTrue(); } @Test public void canWrite() { - assertTrue(converter.canWrite(Source.class, new MediaType("application", "xml"))); - assertTrue(converter.canWrite(Source.class, new MediaType("application", "soap+xml"))); - assertTrue(converter.canWrite(Source.class, MediaType.ALL)); + assertThat(converter.canWrite(Source.class, new MediaType("application", "xml"))).isTrue(); + assertThat(converter.canWrite(Source.class, new MediaType("application", "soap+xml"))).isTrue(); + assertThat(converter.canWrite(Source.class, MediaType.ALL)).isTrue(); } @Test @@ -96,7 +93,7 @@ public class SourceHttpMessageConverterTests { inputMessage.getHeaders().setContentType(new MediaType("application", "xml")); DOMSource result = (DOMSource) converter.read(DOMSource.class, inputMessage); Document document = (Document) result.getNode(); - assertEquals("Invalid result", "root", document.getDocumentElement().getLocalName()); + assertThat(document.getDocumentElement().getLocalName()).as("Invalid result").isEqualTo("root"); } @Test @@ -106,8 +103,8 @@ public class SourceHttpMessageConverterTests { converter.setSupportDtd(true); DOMSource result = (DOMSource) converter.read(DOMSource.class, inputMessage); Document document = (Document) result.getNode(); - assertEquals("Invalid result", "root", document.getDocumentElement().getLocalName()); - assertNotEquals("Invalid result", "Foo Bar", document.getDocumentElement().getTextContent()); + assertThat(document.getDocumentElement().getLocalName()).as("Invalid result").isEqualTo("root"); + assertThat(document.getDocumentElement().getTextContent()).as("Invalid result").isNotEqualTo("Foo Bar"); } @Test @@ -158,7 +155,7 @@ public class SourceHttpMessageConverterTests { @Override public void characters(char[] ch, int start, int length) { String s = new String(ch, start, length); - assertNotEquals("Invalid result", "Foo Bar", s); + assertThat(s).as("Invalid result").isNotEqualTo("Foo Bar"); } }); reader.parse(inputSource); @@ -200,12 +197,12 @@ public class SourceHttpMessageConverterTests { inputMessage.getHeaders().setContentType(new MediaType("application", "xml")); StAXSource result = (StAXSource) converter.read(StAXSource.class, inputMessage); XMLStreamReader streamReader = result.getXMLStreamReader(); - assertTrue(streamReader.hasNext()); + assertThat(streamReader.hasNext()).isTrue(); streamReader.nextTag(); String s = streamReader.getLocalName(); - assertEquals("root", s); + assertThat(s).isEqualTo("root"); s = streamReader.getElementText(); - assertEquals("Hello World", s); + assertThat(s).isEqualTo("Hello World"); streamReader.close(); } @@ -216,14 +213,14 @@ public class SourceHttpMessageConverterTests { converter.setSupportDtd(true); StAXSource result = (StAXSource) converter.read(StAXSource.class, inputMessage); XMLStreamReader streamReader = result.getXMLStreamReader(); - assertTrue(streamReader.hasNext()); + assertThat(streamReader.hasNext()).isTrue(); streamReader.next(); streamReader.next(); String s = streamReader.getLocalName(); - assertEquals("root", s); + assertThat(s).isEqualTo("root"); try { s = streamReader.getElementText(); - assertNotEquals("Foo Bar", s); + assertThat(s).isNotEqualTo("Foo Bar"); } catch (XMLStreamException ex) { // Some parsers raise a parse exception @@ -254,11 +251,11 @@ public class SourceHttpMessageConverterTests { StAXSource result = (StAXSource) this.converter.read(StAXSource.class, inputMessage); XMLStreamReader streamReader = result.getXMLStreamReader(); - assertTrue(streamReader.hasNext()); + assertThat(streamReader.hasNext()).isTrue(); streamReader.next(); streamReader.next(); String s = streamReader.getLocalName(); - assertEquals("root", s); + assertThat(s).isEqualTo("root"); assertThatExceptionOfType(XMLStreamException.class).isThrownBy(() -> streamReader.getElementText()) .withMessageContaining("\"lol9\""); @@ -294,10 +291,8 @@ public class SourceHttpMessageConverterTests { converter.write(domSource, null, outputMessage); assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) .isSimilarTo("Hello World"); - assertEquals("Invalid content-type", new MediaType("application", "xml"), - outputMessage.getHeaders().getContentType()); - assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length, - outputMessage.getHeaders().getContentLength()); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "xml")); + assertThat(outputMessage.getHeaders().getContentLength()).as("Invalid content-length").isEqualTo(outputMessage.getBodyAsBytes().length); } @Test @@ -309,8 +304,7 @@ public class SourceHttpMessageConverterTests { converter.write(saxSource, null, outputMessage); assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) .isSimilarTo("Hello World"); - assertEquals("Invalid content-type", new MediaType("application", "xml"), - outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "xml")); } @Test @@ -322,8 +316,7 @@ public class SourceHttpMessageConverterTests { converter.write(streamSource, null, outputMessage); assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) .isSimilarTo("Hello World"); - assertEquals("Invalid content-type", new MediaType("application", "xml"), - outputMessage.getHeaders().getContentType()); + assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(new MediaType("application", "xml")); } } diff --git a/spring-web/src/test/java/org/springframework/http/server/DefaultPathContainerTests.java b/spring-web/src/test/java/org/springframework/http/server/DefaultPathContainerTests.java index fb4a03a740b..623bf820226 100644 --- a/spring-web/src/test/java/org/springframework/http/server/DefaultPathContainerTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/DefaultPathContainerTests.java @@ -26,8 +26,7 @@ import org.springframework.http.server.PathContainer.PathSegment; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link DefaultPathContainer}. @@ -79,16 +78,16 @@ public class DefaultPathContainerTests { PathContainer container = PathContainer.parsePath(rawValue); if ("".equals(rawValue)) { - assertEquals(0, container.elements().size()); + assertThat(container.elements().size()).isEqualTo(0); return; } - assertEquals(1, container.elements().size()); + assertThat(container.elements().size()).isEqualTo(1); PathSegment segment = (PathSegment) container.elements().get(0); - assertEquals("value: '" + rawValue + "'", rawValue, segment.value()); - assertEquals("valueToMatch: '" + rawValue + "'", valueToMatch, segment.valueToMatch()); - assertEquals("params: '" + rawValue + "'", params, segment.parameters()); + assertThat(segment.value()).as("value: '" + rawValue + "'").isEqualTo(rawValue); + assertThat(segment.valueToMatch()).as("valueToMatch: '" + rawValue + "'").isEqualTo(valueToMatch); + assertThat(segment.parameters()).as("params: '" + rawValue + "'").isEqualTo(params); } @Test @@ -116,26 +115,26 @@ public class DefaultPathContainerTests { PathContainer path = PathContainer.parsePath(input); - assertEquals("value: '" + input + "'", value, path.value()); - assertEquals("elements: " + input, expectedElements, path.elements().stream() - .map(PathContainer.Element::value).collect(Collectors.toList())); + assertThat(path.value()).as("value: '" + input + "'").isEqualTo(value); + assertThat(path.elements().stream() + .map(PathContainer.Element::value).collect(Collectors.toList())).as("elements: " + input).isEqualTo(expectedElements); } @Test public void subPath() throws Exception { // basic PathContainer path = PathContainer.parsePath("/a/b/c"); - assertSame(path, path.subPath(0)); - assertEquals("/b/c", path.subPath(2).value()); - assertEquals("/c", path.subPath(4).value()); + assertThat(path.subPath(0)).isSameAs(path); + assertThat(path.subPath(2).value()).isEqualTo("/b/c"); + assertThat(path.subPath(4).value()).isEqualTo("/c"); // root path path = PathContainer.parsePath("/"); - assertEquals("/", path.subPath(0).value()); + assertThat(path.subPath(0).value()).isEqualTo("/"); // trailing slash path = PathContainer.parsePath("/a/b/"); - assertEquals("/b/", path.subPath(2).value()); + assertThat(path.subPath(2).value()).isEqualTo("/b/"); } } diff --git a/spring-web/src/test/java/org/springframework/http/server/DefaultRequestPathTests.java b/spring-web/src/test/java/org/springframework/http/server/DefaultRequestPathTests.java index eec4c4b591b..fbfa40fc340 100644 --- a/spring-web/src/test/java/org/springframework/http/server/DefaultRequestPathTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/DefaultRequestPathTests.java @@ -19,7 +19,7 @@ import java.net.URI; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link DefaultRequestPath}. @@ -55,8 +55,9 @@ public class DefaultRequestPathTests { URI uri = URI.create("http://localhost:8080" + fullPath); RequestPath requestPath = RequestPath.parse(uri, contextPath); - assertEquals(contextPath.equals("/") ? "" : contextPath, requestPath.contextPath().value()); - assertEquals(pathWithinApplication, requestPath.pathWithinApplication().value()); + Object expected = contextPath.equals("/") ? "" : contextPath; + assertThat(requestPath.contextPath().value()).isEqualTo(expected); + assertThat(requestPath.pathWithinApplication().value()).isEqualTo(pathWithinApplication); } @Test @@ -65,13 +66,13 @@ public class DefaultRequestPathTests { URI uri = URI.create("http://localhost:8080/aA/bB/cC"); RequestPath requestPath = RequestPath.parse(uri, null); - assertEquals("", requestPath.contextPath().value()); - assertEquals("/aA/bB/cC", requestPath.pathWithinApplication().value()); + assertThat(requestPath.contextPath().value()).isEqualTo(""); + assertThat(requestPath.pathWithinApplication().value()).isEqualTo("/aA/bB/cC"); requestPath = requestPath.modifyContextPath("/aA"); - assertEquals("/aA", requestPath.contextPath().value()); - assertEquals("/bB/cC", requestPath.pathWithinApplication().value()); + assertThat(requestPath.contextPath().value()).isEqualTo("/aA"); + assertThat(requestPath.pathWithinApplication().value()).isEqualTo("/bB/cC"); } } diff --git a/spring-web/src/test/java/org/springframework/http/server/ServletServerHttpRequestTests.java b/spring-web/src/test/java/org/springframework/http/server/ServletServerHttpRequestTests.java index f4c507f30c2..7f5b9f25078 100644 --- a/spring-web/src/test/java/org/springframework/http/server/ServletServerHttpRequestTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/ServletServerHttpRequestTests.java @@ -31,11 +31,7 @@ import org.springframework.http.MediaType; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.util.FileCopyUtils; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -58,7 +54,7 @@ public class ServletServerHttpRequestTests { @Test public void getMethod() { mockRequest.setMethod("POST"); - assertEquals("Invalid method", HttpMethod.POST, request.getMethod()); + assertThat(request.getMethod()).as("Invalid method").isEqualTo(HttpMethod.POST); } @Test @@ -69,7 +65,7 @@ public class ServletServerHttpRequestTests { mockRequest.setServerPort(uri.getPort()); mockRequest.setRequestURI(uri.getPath()); mockRequest.setQueryString(uri.getQuery()); - assertEquals(uri, request.getURI()); + assertThat(request.getURI()).isEqualTo(uri); } @Test @@ -80,7 +76,7 @@ public class ServletServerHttpRequestTests { mockRequest.setServerPort(uri.getPort()); mockRequest.setRequestURI(uri.getPath()); mockRequest.setQueryString(uri.getQuery()); - assertEquals(uri, request.getURI()); + assertThat(request.getURI()).isEqualTo(uri); } @Test // SPR-16414 @@ -88,7 +84,7 @@ public class ServletServerHttpRequestTests { mockRequest.setServerName("example.com"); mockRequest.setRequestURI("/path"); mockRequest.setQueryString("query=foo"); - assertEquals(new URI("http://example.com/path?query=foo"), request.getURI()); + assertThat(request.getURI()).isEqualTo(new URI("http://example.com/path?query=foo")); } @Test // SPR-16414 @@ -96,7 +92,7 @@ public class ServletServerHttpRequestTests { mockRequest.setServerName("example.com"); mockRequest.setRequestURI("/path"); mockRequest.setQueryString("query=foo%%x"); - assertEquals(new URI("http://example.com/path"), request.getURI()); + assertThat(request.getURI()).isEqualTo(new URI("http://example.com/path")); } @Test // SPR-13876 @@ -108,7 +104,7 @@ public class ServletServerHttpRequestTests { mockRequest.setServerPort(uri.getPort()); mockRequest.setRequestURI(uri.getRawPath()); mockRequest.setQueryString(uri.getRawQuery()); - assertEquals(uri, request.getURI()); + assertThat(request.getURI()).isEqualTo(uri); } @Test @@ -122,14 +118,13 @@ public class ServletServerHttpRequestTests { mockRequest.setCharacterEncoding("UTF-8"); HttpHeaders headers = request.getHeaders(); - assertNotNull("No HttpHeaders returned", headers); - assertTrue("Invalid headers returned", headers.containsKey(headerName)); + assertThat(headers).as("No HttpHeaders returned").isNotNull(); + assertThat(headers.containsKey(headerName)).as("Invalid headers returned").isTrue(); List headerValues = headers.get(headerName); - assertEquals("Invalid header values returned", 2, headerValues.size()); - assertTrue("Invalid header values returned", headerValues.contains(headerValue1)); - assertTrue("Invalid header values returned", headerValues.contains(headerValue2)); - assertEquals("Invalid Content-Type", new MediaType("text", "plain", StandardCharsets.UTF_8), - headers.getContentType()); + assertThat(headerValues.size()).as("Invalid header values returned").isEqualTo(2); + assertThat(headerValues.contains(headerValue1)).as("Invalid header values returned").isTrue(); + assertThat(headerValues.contains(headerValue2)).as("Invalid header values returned").isTrue(); + assertThat(headers.getContentType()).as("Invalid Content-Type").isEqualTo(new MediaType("text", "plain", StandardCharsets.UTF_8)); } @Test @@ -143,13 +138,13 @@ public class ServletServerHttpRequestTests { mockRequest.setCharacterEncoding(""); HttpHeaders headers = request.getHeaders(); - assertNotNull("No HttpHeaders returned", headers); - assertTrue("Invalid headers returned", headers.containsKey(headerName)); + assertThat(headers).as("No HttpHeaders returned").isNotNull(); + assertThat(headers.containsKey(headerName)).as("Invalid headers returned").isTrue(); List headerValues = headers.get(headerName); - assertEquals("Invalid header values returned", 2, headerValues.size()); - assertTrue("Invalid header values returned", headerValues.contains(headerValue1)); - assertTrue("Invalid header values returned", headerValues.contains(headerValue2)); - assertNull(headers.getContentType()); + assertThat(headerValues.size()).as("Invalid header values returned").isEqualTo(2); + assertThat(headerValues.contains(headerValue1)).as("Invalid header values returned").isTrue(); + assertThat(headerValues.contains(headerValue2)).as("Invalid header values returned").isTrue(); + assertThat(headers.getContentType()).isNull(); } @Test @@ -158,7 +153,7 @@ public class ServletServerHttpRequestTests { mockRequest.setContent(content); byte[] result = FileCopyUtils.copyToByteArray(request.getBody()); - assertArrayEquals("Invalid content returned", content, result); + assertThat(result).as("Invalid content returned").isEqualTo(content); } @Test @@ -172,7 +167,7 @@ public class ServletServerHttpRequestTests { byte[] result = FileCopyUtils.copyToByteArray(request.getBody()); byte[] content = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3".getBytes("UTF-8"); - assertArrayEquals("Invalid content returned", content, result); + assertThat(result).as("Invalid content returned").isEqualTo(content); } } diff --git a/spring-web/src/test/java/org/springframework/http/server/ServletServerHttpResponseTests.java b/spring-web/src/test/java/org/springframework/http/server/ServletServerHttpResponseTests.java index fce82e1ad1b..eb1fab9ac48 100644 --- a/spring-web/src/test/java/org/springframework/http/server/ServletServerHttpResponseTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/ServletServerHttpResponseTests.java @@ -29,9 +29,7 @@ import org.springframework.http.MediaType; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.util.FileCopyUtils; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -55,7 +53,7 @@ public class ServletServerHttpResponseTests { @Test public void setStatusCode() throws Exception { response.setStatusCode(HttpStatus.NOT_FOUND); - assertEquals("Invalid status code", 404, mockResponse.getStatus()); + assertThat(mockResponse.getStatus()).as("Invalid status code").isEqualTo(404); } @Test @@ -69,13 +67,13 @@ public class ServletServerHttpResponseTests { headers.setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8)); response.close(); - assertTrue("Header not set", mockResponse.getHeaderNames().contains(headerName)); + assertThat(mockResponse.getHeaderNames().contains(headerName)).as("Header not set").isTrue(); List headerValues = mockResponse.getHeaders(headerName); - assertTrue("Header not set", headerValues.contains(headerValue1)); - assertTrue("Header not set", headerValues.contains(headerValue2)); - assertEquals("Invalid Content-Type", "text/plain;charset=UTF-8", mockResponse.getHeader("Content-Type")); - assertEquals("Invalid Content-Type", "text/plain;charset=UTF-8", mockResponse.getContentType()); - assertEquals("Invalid Content-Type", "UTF-8", mockResponse.getCharacterEncoding()); + assertThat(headerValues.contains(headerValue1)).as("Header not set").isTrue(); + assertThat(headerValues.contains(headerValue2)).as("Header not set").isTrue(); + assertThat(mockResponse.getHeader("Content-Type")).as("Invalid Content-Type").isEqualTo("text/plain;charset=UTF-8"); + assertThat(mockResponse.getContentType()).as("Invalid Content-Type").isEqualTo("text/plain;charset=UTF-8"); + assertThat(mockResponse.getCharacterEncoding()).as("Invalid Content-Type").isEqualTo("UTF-8"); } @Test @@ -86,11 +84,11 @@ public class ServletServerHttpResponseTests { this.mockResponse.addHeader(headerName, headerValue); this.response = new ServletServerHttpResponse(this.mockResponse); - assertEquals(headerValue, this.response.getHeaders().getFirst(headerName)); - assertEquals(Collections.singletonList(headerValue), this.response.getHeaders().get(headerName)); - assertTrue(this.response.getHeaders().containsKey(headerName)); - assertEquals(headerValue, this.response.getHeaders().getFirst(headerName)); - assertEquals(headerValue, this.response.getHeaders().getAccessControlAllowOrigin()); + assertThat(this.response.getHeaders().getFirst(headerName)).isEqualTo(headerValue); + assertThat(this.response.getHeaders().get(headerName)).isEqualTo(Collections.singletonList(headerValue)); + assertThat(this.response.getHeaders().containsKey(headerName)).isTrue(); + assertThat(this.response.getHeaders().getFirst(headerName)).isEqualTo(headerValue); + assertThat(this.response.getHeaders().getAccessControlAllowOrigin()).isEqualTo(headerValue); } @Test @@ -98,7 +96,7 @@ public class ServletServerHttpResponseTests { byte[] content = "Hello World".getBytes("UTF-8"); FileCopyUtils.copy(content, response.getBody()); - assertArrayEquals("Invalid content written", content, mockResponse.getContentAsByteArray()); + assertThat(mockResponse.getContentAsByteArray()).as("Invalid content written").isEqualTo(content); } } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ChannelSendOperatorTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ChannelSendOperatorTests.java index cee30172b0c..266a7f14f1f 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ChannelSendOperatorTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ChannelSendOperatorTests.java @@ -38,10 +38,7 @@ import reactor.test.StepVerifier; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.LeakAwareDataBufferFactory; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rossen Stoyanchev @@ -64,8 +61,8 @@ public class ChannelSendOperatorTests { Mono completion = Mono.error(error).as(this::sendOperator); Signal signal = completion.materialize().block(); - assertNotNull(signal); - assertSame("Unexpected signal: " + signal, error, signal.getThrowable()); + assertThat(signal).isNotNull(); + assertThat(signal.getThrowable()).as("Unexpected signal: " + signal).isSameAs(error); } @Test @@ -73,11 +70,11 @@ public class ChannelSendOperatorTests { Mono completion = Flux.empty().as(this::sendOperator); Signal signal = completion.materialize().block(); - assertNotNull(signal); - assertTrue("Unexpected signal: " + signal, signal.isOnComplete()); + assertThat(signal).isNotNull(); + assertThat(signal.isOnComplete()).as("Unexpected signal: " + signal).isTrue(); - assertEquals(0, this.writer.items.size()); - assertTrue(this.writer.completed); + assertThat(this.writer.items.size()).isEqualTo(0); + assertThat(this.writer.completed).isTrue(); } @Test @@ -85,12 +82,12 @@ public class ChannelSendOperatorTests { Mono completion = Flux.just("one").as(this::sendOperator); Signal signal = completion.materialize().block(); - assertNotNull(signal); - assertTrue("Unexpected signal: " + signal, signal.isOnComplete()); + assertThat(signal).isNotNull(); + assertThat(signal.isOnComplete()).as("Unexpected signal: " + signal).isTrue(); - assertEquals(1, this.writer.items.size()); - assertEquals("one", this.writer.items.get(0)); - assertTrue(this.writer.completed); + assertThat(this.writer.items.size()).isEqualTo(1); + assertThat(this.writer.items.get(0)).isEqualTo("one"); + assertThat(this.writer.completed).isTrue(); } @@ -100,14 +97,14 @@ public class ChannelSendOperatorTests { Mono completion = Flux.fromIterable(items).as(this::sendOperator); Signal signal = completion.materialize().block(); - assertNotNull(signal); - assertTrue("Unexpected signal: " + signal, signal.isOnComplete()); + assertThat(signal).isNotNull(); + assertThat(signal.isOnComplete()).as("Unexpected signal: " + signal).isTrue(); - assertEquals(3, this.writer.items.size()); - assertEquals("one", this.writer.items.get(0)); - assertEquals("two", this.writer.items.get(1)); - assertEquals("three", this.writer.items.get(2)); - assertTrue(this.writer.completed); + assertThat(this.writer.items.size()).isEqualTo(3); + assertThat(this.writer.items.get(0)).isEqualTo("one"); + assertThat(this.writer.items.get(1)).isEqualTo("two"); + assertThat(this.writer.items.get(2)).isEqualTo("three"); + assertThat(this.writer.completed).isTrue(); } @Test @@ -124,14 +121,14 @@ public class ChannelSendOperatorTests { Mono completion = publisher.as(this::sendOperator); Signal signal = completion.materialize().block(); - assertNotNull(signal); - assertSame("Unexpected signal: " + signal, error, signal.getThrowable()); + assertThat(signal).isNotNull(); + assertThat(signal.getThrowable()).as("Unexpected signal: " + signal).isSameAs(error); - assertEquals(3, this.writer.items.size()); - assertEquals("1", this.writer.items.get(0)); - assertEquals("2", this.writer.items.get(1)); - assertEquals("3", this.writer.items.get(2)); - assertSame(error, this.writer.error); + assertThat(this.writer.items.size()).isEqualTo(3); + assertThat(this.writer.items.get(0)).isEqualTo("1"); + assertThat(this.writer.items.get(1)).isEqualTo("2"); + assertThat(this.writer.items.get(2)).isEqualTo("3"); + assertThat(this.writer.error).isSameAs(error); } @Test // gh-22720 @@ -185,8 +182,8 @@ public class ChannelSendOperatorTests { writeSubscriber.signalDemand(1); // Let cached signals ("foo" and error) be published.. } catch (Throwable ex) { - assertNotNull(ex.getCause()); - assertEquals("err", ex.getCause().getMessage()); + assertThat(ex.getCause()).isNotNull(); + assertThat(ex.getCause().getMessage()).isEqualTo("err"); } bufferFactory.checkForLeaks(); diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ContextPathCompositeHandlerTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ContextPathCompositeHandlerTests.java index 71b26babaef..8670068e70a 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ContextPathCompositeHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ContextPathCompositeHandlerTests.java @@ -30,10 +30,8 @@ import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for {@link ContextPathCompositeHandler}. @@ -101,8 +99,8 @@ public class ContextPathCompositeHandlerTests { new ContextPathCompositeHandler(map).handle(request, new MockServerHttpResponse()); - assertTrue(handler.wasInvoked()); - assertEquals("/yet/another/path", handler.getRequest().getPath().contextPath().value()); + assertThat(handler.wasInvoked()).isTrue(); + assertThat(handler.getRequest().getPath().contextPath().value()).isEqualTo("/yet/another/path"); } @Test @@ -117,7 +115,7 @@ public class ContextPathCompositeHandlerTests { ServerHttpResponse response = testHandle("/yet/another/path", map); assertNotInvoked(handler1, handler2); - assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test // SPR-17144 @@ -138,8 +136,8 @@ public class ContextPathCompositeHandlerTests { new ContextPathCompositeHandler(map).handle(request, response).block(Duration.ofSeconds(5)); assertNotInvoked(handler); - assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); - assertTrue(commitInvoked.get()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(commitInvoked.get()).isTrue(); } @@ -151,12 +149,12 @@ public class ContextPathCompositeHandlerTests { } private void assertInvoked(TestHttpHandler handler, String contextPath) { - assertTrue(handler.wasInvoked()); - assertEquals(contextPath, handler.getRequest().getPath().contextPath().value()); + assertThat(handler.wasInvoked()).isTrue(); + assertThat(handler.getRequest().getPath().contextPath().value()).isEqualTo(contextPath); } private void assertNotInvoked(TestHttpHandler... handlers) { - Arrays.stream(handlers).forEach(handler -> assertFalse(handler.wasInvoked())); + Arrays.stream(handlers).forEach(handler -> assertThat(handler.wasInvoked()).isFalse()); } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/CookieIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/CookieIntegrationTests.java index 2583df3f448..6c24fea1b7a 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/CookieIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/CookieIntegrationTests.java @@ -33,7 +33,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * @author Rossen Stoyanchev @@ -50,7 +49,6 @@ public class CookieIntegrationTests extends AbstractHttpHandlerIntegrationTests } - @SuppressWarnings("unchecked") @Test public void basicTest() throws Exception { URI url = new URI("http://localhost:" + port); @@ -59,18 +57,18 @@ public class CookieIntegrationTests extends AbstractHttpHandlerIntegrationTests RequestEntity.get(url).header("Cookie", header).build(), Void.class); Map> requestCookies = this.cookieHandler.requestCookies; - assertEquals(2, requestCookies.size()); + assertThat(requestCookies.size()).isEqualTo(2); List list = requestCookies.get("SID"); - assertEquals(1, list.size()); - assertEquals("31d4d96e407aad42", list.iterator().next().getValue()); + assertThat(list.size()).isEqualTo(1); + assertThat(list.iterator().next().getValue()).isEqualTo("31d4d96e407aad42"); list = requestCookies.get("lang"); - assertEquals(1, list.size()); - assertEquals("en-US", list.iterator().next().getValue()); + assertThat(list.size()).isEqualTo(1); + assertThat(list.iterator().next().getValue()).isEqualTo("en-US"); List headerValues = response.getHeaders().get("Set-Cookie"); - assertEquals(2, headerValues.size()); + assertThat(headerValues.size()).isEqualTo(2); List cookie0 = splitCookie(headerValues.get(0)); assertThat(cookie0.remove("SID=31d4d96e407aad42")).as("SID").isTrue(); diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/EchoHandlerIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/EchoHandlerIntegrationTests.java index 4bd12222743..66ae60ad9e2 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/EchoHandlerIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/EchoHandlerIntegrationTests.java @@ -26,7 +26,7 @@ import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertArrayEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -52,7 +52,7 @@ public class EchoHandlerIntegrationTests extends AbstractHttpHandlerIntegrationT RequestEntity request = RequestEntity.post(new URI("http://localhost:" + port)).body(body); ResponseEntity response = restTemplate.exchange(request, byte[].class); - assertArrayEquals(body, response.getBody()); + assertThat(response.getBody()).isEqualTo(body); } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ErrorHandlerIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ErrorHandlerIntegrationTests.java index 6d18e46f6f3..ac4b8ce4a28 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ErrorHandlerIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ErrorHandlerIntegrationTests.java @@ -27,7 +27,7 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -51,7 +51,7 @@ public class ErrorHandlerIntegrationTests extends AbstractHttpHandlerIntegration URI url = new URI("http://localhost:" + port + "/response-body-error"); ResponseEntity response = restTemplate.getForEntity(url, String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @Test @@ -62,7 +62,7 @@ public class ErrorHandlerIntegrationTests extends AbstractHttpHandlerIntegration URI url = new URI("http://localhost:" + port + "/handling-error"); ResponseEntity response = restTemplate.getForEntity(url, String.class); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @Test // SPR-15560 @@ -74,7 +74,7 @@ public class ErrorHandlerIntegrationTests extends AbstractHttpHandlerIntegration URI url = new URI("http://localhost:" + port + "//"); ResponseEntity response = restTemplate.getForEntity(url, String.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/HeadersAdaptersTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/HeadersAdaptersTests.java index 2b529c2cae8..60bdb168be3 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/HeadersAdaptersTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/HeadersAdaptersTests.java @@ -32,9 +32,7 @@ import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedCaseInsensitiveMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@code HeadersAdapters} {@code MultiValueMap} implementations. @@ -66,19 +64,19 @@ public class HeadersAdaptersTests { @Test public void getWithUnknownHeaderShouldReturnNull() { - assertNull(this.headers.get("Unknown")); + assertThat(this.headers.get("Unknown")).isNull(); } @Test public void getFirstWithUnknownHeaderShouldReturnNull() { - assertNull(this.headers.getFirst("Unknown")); + assertThat(this.headers.getFirst("Unknown")).isNull(); } @Test public void sizeWithMultipleValuesForHeaderShouldCountHeaders() { this.headers.add("TestHeader", "first"); this.headers.add("TestHeader", "second"); - assertEquals(1, this.headers.size()); + assertThat(this.headers.size()).isEqualTo(1); } @Test @@ -86,29 +84,29 @@ public class HeadersAdaptersTests { this.headers.add("TestHeader", "first"); this.headers.add("OtherHeader", "test"); this.headers.add("TestHeader", "second"); - assertEquals(2, this.headers.keySet().size()); + assertThat(this.headers.keySet().size()).isEqualTo(2); } @Test public void containsKeyShouldBeCaseInsensitive() { this.headers.add("TestHeader", "first"); - assertTrue(this.headers.containsKey("testheader")); + assertThat(this.headers.containsKey("testheader")).isTrue(); } @Test public void addShouldKeepOrdering() { this.headers.add("TestHeader", "first"); this.headers.add("TestHeader", "second"); - assertEquals("first", this.headers.getFirst("TestHeader")); - assertEquals("first", this.headers.get("TestHeader").get(0)); + assertThat(this.headers.getFirst("TestHeader")).isEqualTo("first"); + assertThat(this.headers.get("TestHeader").get(0)).isEqualTo("first"); } @Test public void putShouldOverrideExisting() { this.headers.add("TestHeader", "first"); this.headers.put("TestHeader", Arrays.asList("override")); - assertEquals("override", this.headers.getFirst("TestHeader")); - assertEquals(1, this.headers.get("TestHeader").size()); + assertThat(this.headers.getFirst("TestHeader")).isEqualTo("override"); + assertThat(this.headers.get("TestHeader").size()).isEqualTo(1); } } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ListenerReadPublisherTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ListenerReadPublisherTests.java index bd956ce596c..fc4bb1e6952 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ListenerReadPublisherTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ListenerReadPublisherTests.java @@ -23,7 +23,7 @@ import org.reactivestreams.Subscription; import org.springframework.core.io.buffer.DataBuffer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -51,7 +51,7 @@ public class ListenerReadPublisherTests { this.subscriber.getSubscription().request(2); this.publisher.onDataAvailable(); - assertEquals(2, this.publisher.getReadCalls()); + assertThat(this.publisher.getReadCalls()).isEqualTo(2); } @Test // SPR-17410 @@ -61,8 +61,8 @@ public class ListenerReadPublisherTests { this.publisher.onDataAvailable(); this.publisher.onError(new IllegalStateException()); - assertEquals(2, this.publisher.getReadCalls()); - assertEquals(1, this.publisher.getDiscardCalls()); + assertThat(this.publisher.getReadCalls()).isEqualTo(2); + assertThat(this.publisher.getDiscardCalls()).isEqualTo(1); } @Test // SPR-17410 @@ -72,8 +72,8 @@ public class ListenerReadPublisherTests { this.subscriber.setCancelOnNext(true); this.publisher.onDataAvailable(); - assertEquals(1, this.publisher.getReadCalls()); - assertEquals(1, this.publisher.getDiscardCalls()); + assertThat(this.publisher.getReadCalls()).isEqualTo(1); + assertThat(this.publisher.getDiscardCalls()).isEqualTo(1); } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ListenerWriteProcessorTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ListenerWriteProcessorTests.java index ac32c1566da..7786ab4adab 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ListenerWriteProcessorTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ListenerWriteProcessorTests.java @@ -27,9 +27,7 @@ import org.reactivestreams.Subscription; import org.springframework.core.io.buffer.DataBuffer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -50,7 +48,7 @@ public class ListenerWriteProcessorTests { public void setup() { this.processor.subscribe(this.resultSubscriber); this.processor.onSubscribe(this.subscription); - assertEquals(1, subscription.getDemand()); + assertThat(subscription.getDemand()).isEqualTo(1); } @@ -65,9 +63,9 @@ public class ListenerWriteProcessorTests { // Send error while item cached this.processor.onError(new IllegalStateException()); - assertNotNull("Error should flow to result publisher", this.resultSubscriber.getError()); - assertEquals(1, this.processor.getDiscardedBuffers().size()); - assertSame(buffer, this.processor.getDiscardedBuffers().get(0)); + assertThat(this.resultSubscriber.getError()).as("Error should flow to result publisher").isNotNull(); + assertThat(this.processor.getDiscardedBuffers().size()).isEqualTo(1); + assertThat(this.processor.getDiscardedBuffers().get(0)).isSameAs(buffer); } @Test // SPR-17410 @@ -81,9 +79,9 @@ public class ListenerWriteProcessorTests { DataBuffer buffer = mock(DataBuffer.class); this.processor.onNext(buffer); - assertNotNull("Error should flow to result publisher", this.resultSubscriber.getError()); - assertEquals(1, this.processor.getDiscardedBuffers().size()); - assertSame(buffer, this.processor.getDiscardedBuffers().get(0)); + assertThat(this.resultSubscriber.getError()).as("Error should flow to result publisher").isNotNull(); + assertThat(this.processor.getDiscardedBuffers().size()).isEqualTo(1); + assertThat(this.processor.getDiscardedBuffers().get(0)).isSameAs(buffer); } @Test // SPR-17410 @@ -98,10 +96,10 @@ public class ListenerWriteProcessorTests { DataBuffer buffer2 = mock(DataBuffer.class); this.processor.onNext(buffer2); - assertNotNull("Error should flow to result publisher", this.resultSubscriber.getError()); - assertEquals(2, this.processor.getDiscardedBuffers().size()); - assertSame(buffer2, this.processor.getDiscardedBuffers().get(0)); - assertSame(buffer1, this.processor.getDiscardedBuffers().get(1)); + assertThat(this.resultSubscriber.getError()).as("Error should flow to result publisher").isNotNull(); + assertThat(this.processor.getDiscardedBuffers().size()).isEqualTo(2); + assertThat(this.processor.getDiscardedBuffers().get(0)).isSameAs(buffer2); + assertThat(this.processor.getDiscardedBuffers().get(1)).isSameAs(buffer1); } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/MultipartIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/MultipartIntegrationTests.java index b34fccd5d8c..af6b71c04b5 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/MultipartIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/MultipartIntegrationTests.java @@ -40,8 +40,7 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.HttpWebHandlerAdapter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze @@ -61,7 +60,7 @@ public class MultipartIntegrationTests extends AbstractHttpHandlerIntegrationTes .contentType(MediaType.MULTIPART_FORM_DATA) .body(generateBody()); ResponseEntity response = restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); } private MultiValueMap generateBody() { @@ -91,34 +90,36 @@ public class MultipartIntegrationTests extends AbstractHttpHandlerIntegrationTes return exchange .getMultipartData() .doOnNext(parts -> { - assertEquals(2, parts.size()); - assertTrue(parts.containsKey("fooPart")); + assertThat(parts.size()).isEqualTo(2); + assertThat(parts.containsKey("fooPart")).isTrue(); assertFooPart(parts.getFirst("fooPart")); - assertTrue(parts.containsKey("barPart")); + assertThat(parts.containsKey("barPart")).isTrue(); assertBarPart(parts.getFirst("barPart")); }) .then(); } private void assertFooPart(Part part) { - assertEquals("fooPart", part.name()); - assertTrue(part instanceof FilePart); - assertEquals("foo.txt", ((FilePart) part).filename()); + assertThat(part.name()).isEqualTo("fooPart"); + boolean condition = part instanceof FilePart; + assertThat(condition).isTrue(); + assertThat(((FilePart) part).filename()).isEqualTo("foo.txt"); StepVerifier.create(DataBufferUtils.join(part.content())) .consumeNextWith(buffer -> { - assertEquals(12, buffer.readableByteCount()); + assertThat(buffer.readableByteCount()).isEqualTo(12); byte[] byteContent = new byte[12]; buffer.read(byteContent); - assertEquals("Lorem Ipsum.", new String(byteContent)); + assertThat(new String(byteContent)).isEqualTo("Lorem Ipsum."); }) .verifyComplete(); } private void assertBarPart(Part part) { - assertEquals("barPart", part.name()); - assertTrue(part instanceof FormFieldPart); - assertEquals("bar", ((FormFieldPart) part).value()); + assertThat(part.name()).isEqualTo("barPart"); + boolean condition = part instanceof FormFieldPart; + assertThat(condition).isTrue(); + assertThat(((FormFieldPart) part).value()).isEqualTo("bar"); } } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/RandomHandlerIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/RandomHandlerIntegrationTests.java index 4f264c68ff6..7a53879209d 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/RandomHandlerIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/RandomHandlerIntegrationTests.java @@ -31,9 +31,7 @@ import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -67,10 +65,9 @@ public class RandomHandlerIntegrationTests extends AbstractHttpHandlerIntegratio RequestEntity request = RequestEntity.post(new URI("http://localhost:" + port)).body(body); ResponseEntity response = restTemplate.exchange(request, byte[].class); - assertNotNull(response.getBody()); - assertEquals(RESPONSE_SIZE, - response.getHeaders().getContentLength()); - assertEquals(RESPONSE_SIZE, response.getBody().length); + assertThat(response.getBody()).isNotNull(); + assertThat(response.getHeaders().getContentLength()).isEqualTo(RESPONSE_SIZE); + assertThat(response.getBody().length).isEqualTo(RESPONSE_SIZE); } @@ -90,8 +87,8 @@ public class RandomHandlerIntegrationTests extends AbstractHttpHandlerIntegratio reduce(0, (integer, dataBuffer) -> integer + dataBuffer.readableByteCount()). doOnSuccessOrError((size, throwable) -> { - assertNull(throwable); - assertEquals(REQUEST_SIZE, (long) size); + assertThat(throwable).isNull(); + assertThat(size).isEqualTo(REQUEST_SIZE); }); response.getHeaders().setContentLength(RESPONSE_SIZE); diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestIntegrationTests.java index 7c61f601ba6..799600479ee 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestIntegrationTests.java @@ -26,9 +26,7 @@ import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze @@ -45,7 +43,7 @@ public class ServerHttpRequestIntegrationTests extends AbstractHttpHandlerIntegr URI url = new URI("http://localhost:" + port + "/foo?param=bar"); RequestEntity request = RequestEntity.post(url).build(); ResponseEntity response = new RestTemplate().exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -54,12 +52,12 @@ public class ServerHttpRequestIntegrationTests extends AbstractHttpHandlerIntegr @Override public Mono handle(ServerHttpRequest request, ServerHttpResponse response) { URI uri = request.getURI(); - assertEquals("http", uri.getScheme()); - assertNotNull(uri.getHost()); - assertNotEquals(-1, uri.getPort()); - assertNotNull(request.getRemoteAddress()); - assertEquals("/foo", uri.getPath()); - assertEquals("param=bar", uri.getQuery()); + assertThat(uri.getScheme()).isEqualTo("http"); + assertThat(uri.getHost()).isNotNull(); + assertThat(uri.getPort()).isNotEqualTo((long) -1); + assertThat(request.getRemoteAddress()).isNotNull(); + assertThat(uri.getPath()).isEqualTo("/foo"); + assertThat(uri.getQuery()).isEqualTo("param=bar"); return Mono.empty(); } } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestTests.java index ffbbd7aabe0..08f062079af 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestTests.java @@ -34,9 +34,8 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; /** @@ -49,43 +48,43 @@ public class ServerHttpRequestTests { @Test public void queryParamsNone() throws Exception { MultiValueMap params = createHttpRequest("/path").getQueryParams(); - assertEquals(0, params.size()); + assertThat(params.size()).isEqualTo(0); } @Test public void queryParams() throws Exception { MultiValueMap params = createHttpRequest("/path?a=A&b=B").getQueryParams(); - assertEquals(2, params.size()); - assertEquals(Collections.singletonList("A"), params.get("a")); - assertEquals(Collections.singletonList("B"), params.get("b")); + assertThat(params.size()).isEqualTo(2); + assertThat(params.get("a")).isEqualTo(Collections.singletonList("A")); + assertThat(params.get("b")).isEqualTo(Collections.singletonList("B")); } @Test public void queryParamsWithMultipleValues() throws Exception { MultiValueMap params = createHttpRequest("/path?a=1&a=2").getQueryParams(); - assertEquals(1, params.size()); - assertEquals(Arrays.asList("1", "2"), params.get("a")); + assertThat(params.size()).isEqualTo(1); + assertThat(params.get("a")).isEqualTo(Arrays.asList("1", "2")); } @Test // SPR-15140 public void queryParamsWithEncodedValue() throws Exception { MultiValueMap params = createHttpRequest("/path?a=%20%2B+%C3%A0").getQueryParams(); - assertEquals(1, params.size()); - assertEquals(Collections.singletonList(" + \u00e0"), params.get("a")); + assertThat(params.size()).isEqualTo(1); + assertThat(params.get("a")).isEqualTo(Collections.singletonList(" + \u00e0")); } @Test public void queryParamsWithEmptyValue() throws Exception { MultiValueMap params = createHttpRequest("/path?a=").getQueryParams(); - assertEquals(1, params.size()); - assertEquals(Collections.singletonList(""), params.get("a")); + assertThat(params.size()).isEqualTo(1); + assertThat(params.get("a")).isEqualTo(Collections.singletonList("")); } @Test public void queryParamsWithNoValue() throws Exception { MultiValueMap params = createHttpRequest("/path?a").getQueryParams(); - assertEquals(1, params.size()); - assertEquals(Collections.singletonList(null), params.get("a")); + assertThat(params.size()).isEqualTo(1); + assertThat(params.get("a")).isEqualTo(Collections.singletonList(null)); } @Test @@ -93,22 +92,22 @@ public class ServerHttpRequestTests { SslInfo sslInfo = mock(SslInfo.class); ServerHttpRequest request = createHttpRequest("/").mutate().sslInfo(sslInfo).build(); - assertSame(sslInfo, request.getSslInfo()); + assertThat(request.getSslInfo()).isSameAs(sslInfo); request = createHttpRequest("/").mutate().method(HttpMethod.DELETE).build(); - assertEquals(HttpMethod.DELETE, request.getMethod()); + assertThat(request.getMethod()).isEqualTo(HttpMethod.DELETE); String baseUri = "https://aaa.org:8080/a"; request = createHttpRequest(baseUri).mutate().uri(URI.create("https://bbb.org:9090/b")).build(); - assertEquals("https://bbb.org:9090/b", request.getURI().toString()); + assertThat(request.getURI().toString()).isEqualTo("https://bbb.org:9090/b"); request = createHttpRequest(baseUri).mutate().path("/b/c/d").build(); - assertEquals("https://aaa.org:8080/b/c/d", request.getURI().toString()); + assertThat(request.getURI().toString()).isEqualTo("https://aaa.org:8080/b/c/d"); request = createHttpRequest(baseUri).mutate().path("/app/b/c/d").contextPath("/app").build(); - assertEquals("https://aaa.org:8080/app/b/c/d", request.getURI().toString()); - assertEquals("/app", request.getPath().contextPath().value()); + assertThat(request.getURI().toString()).isEqualTo("https://aaa.org:8080/app/b/c/d"); + assertThat(request.getPath().contextPath().value()).isEqualTo("/app"); } @Test @@ -122,8 +121,8 @@ public class ServerHttpRequestTests { ServerHttpRequest request = createHttpRequest("/path?name=%E6%89%8E%E6%A0%B9"); request = request.mutate().path("/mutatedPath").build(); - assertEquals("/mutatedPath", request.getURI().getRawPath()); - assertEquals("name=%E6%89%8E%E6%A0%B9", request.getURI().getRawQuery()); + assertThat(request.getURI().getRawPath()).isEqualTo("/mutatedPath"); + assertThat(request.getURI().getRawQuery()).isEqualTo("name=%E6%89%8E%E6%A0%B9"); } private ServerHttpRequest createHttpRequest(String uriString) throws Exception { diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpResponseTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpResponseTests.java index 8fbadfb9ad5..b384efc74db 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpResponseTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpResponseTests.java @@ -32,10 +32,7 @@ import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseCookie; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rossen Stoyanchev @@ -48,14 +45,14 @@ public class ServerHttpResponseTests { TestServerHttpResponse response = new TestServerHttpResponse(); response.writeWith(Flux.just(wrap("a"), wrap("b"), wrap("c"))).block(); - assertTrue(response.statusCodeWritten); - assertTrue(response.headersWritten); - assertTrue(response.cookiesWritten); + assertThat(response.statusCodeWritten).isTrue(); + assertThat(response.headersWritten).isTrue(); + assertThat(response.cookiesWritten).isTrue(); - assertEquals(3, response.body.size()); - assertEquals("a", new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)); - assertEquals("b", new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8)); - assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8)); + assertThat(response.body.size()).isEqualTo(3); + assertThat(new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("a"); + assertThat(new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("b"); + assertThat(new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("c"); } @Test // SPR-14952 @@ -64,12 +61,12 @@ public class ServerHttpResponseTests { Flux> flux = Flux.just(Flux.just(wrap("foo"))); response.writeAndFlushWith(flux).block(); - assertTrue(response.statusCodeWritten); - assertTrue(response.headersWritten); - assertTrue(response.cookiesWritten); + assertThat(response.statusCodeWritten).isTrue(); + assertThat(response.headersWritten).isTrue(); + assertThat(response.cookiesWritten).isTrue(); - assertEquals(1, response.body.size()); - assertEquals("foo", new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)); + assertThat(response.body.size()).isEqualTo(1); + assertThat(new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("foo"); } @Test @@ -79,11 +76,11 @@ public class ServerHttpResponseTests { IllegalStateException error = new IllegalStateException("boo"); response.writeWith(Flux.error(error)).onErrorResume(ex -> Mono.empty()).block(); - assertFalse(response.statusCodeWritten); - assertFalse(response.headersWritten); - assertFalse(response.cookiesWritten); - assertFalse(response.getHeaders().containsKey(HttpHeaders.CONTENT_LENGTH)); - assertTrue(response.body.isEmpty()); + assertThat(response.statusCodeWritten).isFalse(); + assertThat(response.headersWritten).isFalse(); + assertThat(response.cookiesWritten).isFalse(); + assertThat(response.getHeaders().containsKey(HttpHeaders.CONTENT_LENGTH)).isFalse(); + assertThat(response.body.isEmpty()).isTrue(); } @Test @@ -91,10 +88,10 @@ public class ServerHttpResponseTests { TestServerHttpResponse response = new TestServerHttpResponse(); response.setComplete().block(); - assertTrue(response.statusCodeWritten); - assertTrue(response.headersWritten); - assertTrue(response.cookiesWritten); - assertTrue(response.body.isEmpty()); + assertThat(response.statusCodeWritten).isTrue(); + assertThat(response.headersWritten).isTrue(); + assertThat(response.cookiesWritten).isTrue(); + assertThat(response.body.isEmpty()).isTrue(); } @Test @@ -104,15 +101,15 @@ public class ServerHttpResponseTests { response.beforeCommit(() -> Mono.fromRunnable(() -> response.getCookies().add(cookie.getName(), cookie))); response.writeWith(Flux.just(wrap("a"), wrap("b"), wrap("c"))).block(); - assertTrue(response.statusCodeWritten); - assertTrue(response.headersWritten); - assertTrue(response.cookiesWritten); - assertSame(cookie, response.getCookies().getFirst("ID")); + assertThat(response.statusCodeWritten).isTrue(); + assertThat(response.headersWritten).isTrue(); + assertThat(response.cookiesWritten).isTrue(); + assertThat(response.getCookies().getFirst("ID")).isSameAs(cookie); - assertEquals(3, response.body.size()); - assertEquals("a", new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)); - assertEquals("b", new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8)); - assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8)); + assertThat(response.body.size()).isEqualTo(3); + assertThat(new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("a"); + assertThat(new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("b"); + assertThat(new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("c"); } @Test @@ -125,11 +122,11 @@ public class ServerHttpResponseTests { }); response.setComplete().block(); - assertTrue(response.statusCodeWritten); - assertTrue(response.headersWritten); - assertTrue(response.cookiesWritten); - assertTrue(response.body.isEmpty()); - assertSame(cookie, response.getCookies().getFirst("ID")); + assertThat(response.statusCodeWritten).isTrue(); + assertThat(response.headersWritten).isTrue(); + assertThat(response.cookiesWritten).isTrue(); + assertThat(response.body.isEmpty()).isTrue(); + assertThat(response.getCookies().getFirst("ID")).isSameAs(cookie); } @@ -160,19 +157,19 @@ public class ServerHttpResponseTests { @Override public void applyStatusCode() { - assertFalse(this.statusCodeWritten); + assertThat(this.statusCodeWritten).isFalse(); this.statusCodeWritten = true; } @Override protected void applyHeaders() { - assertFalse(this.headersWritten); + assertThat(this.headersWritten).isFalse(); this.headersWritten = true; } @Override protected void applyCookies() { - assertFalse(this.cookiesWritten); + assertThat(this.cookiesWritten).isFalse(); this.cookiesWritten = true; } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpsRequestIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpsRequestIntegrationTests.java index 0501e08e48c..3c28fd29347 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpsRequestIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpsRequestIntegrationTests.java @@ -39,9 +39,7 @@ import org.springframework.http.server.reactive.bootstrap.HttpServer; import org.springframework.http.server.reactive.bootstrap.ReactorHttpsServer; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * HTTPS-specific integration test for {@link ServerHttpRequest}. @@ -95,7 +93,7 @@ public class ServerHttpsRequestIntegrationTests { URI url = new URI("https://localhost:" + port + "/foo?param=bar"); RequestEntity request = RequestEntity.post(url).build(); ResponseEntity response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); } public static class CheckRequestHandler implements HttpHandler { @@ -103,12 +101,12 @@ public class ServerHttpsRequestIntegrationTests { @Override public Mono handle(ServerHttpRequest request, ServerHttpResponse response) { URI uri = request.getURI(); - assertEquals("https", uri.getScheme()); - assertNotNull(uri.getHost()); - assertNotEquals(-1, uri.getPort()); - assertNotNull(request.getRemoteAddress()); - assertEquals("/foo", uri.getPath()); - assertEquals("param=bar", uri.getQuery()); + assertThat(uri.getScheme()).isEqualTo("https"); + assertThat(uri.getHost()).isNotNull(); + assertThat(uri.getPort()).isNotEqualTo((long) -1); + assertThat(request.getRemoteAddress()).isNotNull(); + assertThat(uri.getPath()).isEqualTo("/foo"); + assertThat(uri.getQuery()).isEqualTo("param=bar"); return Mono.empty(); } } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/WriteOnlyHandlerIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/WriteOnlyHandlerIntegrationTests.java index 08045fcbc3f..aefceae1895 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/WriteOnlyHandlerIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/WriteOnlyHandlerIntegrationTests.java @@ -29,7 +29,7 @@ import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertArrayEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Violeta Georgieva @@ -59,7 +59,7 @@ public class WriteOnlyHandlerIntegrationTests extends AbstractHttpHandlerIntegra "".getBytes(StandardCharsets.UTF_8)); ResponseEntity response = restTemplate.exchange(request, byte[].class); - assertArrayEquals(body, response.getBody()); + assertThat(response.getBody()).isEqualTo(body); } private byte[] randomBytes() { diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ZeroCopyIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ZeroCopyIntegrationTests.java index d57c0efd4f4..05687e99663 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ZeroCopyIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ZeroCopyIntegrationTests.java @@ -32,8 +32,7 @@ import org.springframework.http.server.reactive.bootstrap.ReactorHttpServer; import org.springframework.http.server.reactive.bootstrap.UndertowHttpServer; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; /** @@ -61,10 +60,10 @@ public class ZeroCopyIntegrationTests extends AbstractHttpHandlerIntegrationTest Resource logo = new ClassPathResource("spring.png", ZeroCopyIntegrationTests.class); - assertTrue(response.hasBody()); - assertEquals(logo.contentLength(), response.getHeaders().getContentLength()); - assertEquals(logo.contentLength(), response.getBody().length); - assertEquals(MediaType.IMAGE_PNG, response.getHeaders().getContentType()); + assertThat(response.hasBody()).isTrue(); + assertThat(response.getHeaders().getContentLength()).isEqualTo(logo.contentLength()); + assertThat(response.getBody().length).isEqualTo(logo.contentLength()); + assertThat(response.getHeaders().getContentType()).isEqualTo(MediaType.IMAGE_PNG); } diff --git a/spring-web/src/test/java/org/springframework/remoting/caucho/CauchoRemotingTests.java b/spring-web/src/test/java/org/springframework/remoting/caucho/CauchoRemotingTests.java index 379eed6f644..d2d52a12d84 100644 --- a/spring-web/src/test/java/org/springframework/remoting/caucho/CauchoRemotingTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/caucho/CauchoRemotingTests.java @@ -29,10 +29,9 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SocketUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -55,8 +54,9 @@ public class CauchoRemotingTests { factory.setServiceUrl("http://localhosta/testbean"); factory.afterPropertiesSet(); - assertTrue("Correct singleton value", factory.isSingleton()); - assertTrue(factory.getObject() instanceof ITestBean); + assertThat(factory.isSingleton()).as("Correct singleton value").isTrue(); + boolean condition = factory.getObject() instanceof ITestBean; + assertThat(condition).isTrue(); ITestBean bean = (ITestBean) factory.getObject(); assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(() -> @@ -73,8 +73,9 @@ public class CauchoRemotingTests { factory.setOverloadEnabled(true); factory.afterPropertiesSet(); - assertTrue("Correct singleton value", factory.isSingleton()); - assertTrue(factory.getObject() instanceof ITestBean); + assertThat(factory.isSingleton()).as("Correct singleton value").isTrue(); + boolean condition = factory.getObject() instanceof ITestBean; + assertThat(condition).isTrue(); ITestBean bean = (ITestBean) factory.getObject(); assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(() -> @@ -92,13 +93,14 @@ public class CauchoRemotingTests { factory.setPassword("bean"); factory.setOverloadEnabled(true); factory.afterPropertiesSet(); - assertTrue("Correct singleton value", factory.isSingleton()); - assertTrue(factory.getObject() instanceof ITestBean); + assertThat(factory.isSingleton()).as("Correct singleton value").isTrue(); + boolean condition = factory.getObject() instanceof ITestBean; + assertThat(condition).isTrue(); ITestBean bean = (ITestBean) factory.getObject(); - assertEquals("test", proxyFactory.user); - assertEquals("bean", proxyFactory.password); - assertTrue(proxyFactory.overloadEnabled); + assertThat(proxyFactory.user).isEqualTo("test"); + assertThat(proxyFactory.password).isEqualTo("bean"); + assertThat(proxyFactory.overloadEnabled).isTrue(); assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(() -> bean.setName("test")); @@ -126,9 +128,9 @@ public class CauchoRemotingTests { //client.setHessian2(true); client.prepare(); ITestBean proxy = ProxyFactory.getProxy(ITestBean.class, client); - assertEquals("tb", proxy.getName()); + assertThat(proxy.getName()).isEqualTo("tb"); proxy.setName("test"); - assertEquals("test", proxy.getName()); + assertThat(proxy.getName()).isEqualTo("test"); } finally { server.stop(Integer.MAX_VALUE); diff --git a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpComponentsHttpInvokerRequestExecutorTests.java b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpComponentsHttpInvokerRequestExecutorTests.java index c8013d14538..f017f8a925a 100644 --- a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpComponentsHttpInvokerRequestExecutorTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpComponentsHttpInvokerRequestExecutorTests.java @@ -26,10 +26,7 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.Test; -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.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings; @@ -46,7 +43,7 @@ public class HttpComponentsHttpInvokerRequestExecutorTests { HttpInvokerClientConfiguration config = mockHttpInvokerClientConfiguration("https://fake-service"); HttpPost httpPost = executor.createHttpPost(config); - assertEquals(5000, httpPost.getConfig().getConnectTimeout()); + assertThat(httpPost.getConfig().getConnectTimeout()).isEqualTo(5000); } @Test @@ -56,7 +53,7 @@ public class HttpComponentsHttpInvokerRequestExecutorTests { HttpInvokerClientConfiguration config = mockHttpInvokerClientConfiguration("https://fake-service"); HttpPost httpPost = executor.createHttpPost(config); - assertEquals(7000, httpPost.getConfig().getConnectionRequestTimeout()); + assertThat(httpPost.getConfig().getConnectionRequestTimeout()).isEqualTo(7000); } @Test @@ -66,7 +63,7 @@ public class HttpComponentsHttpInvokerRequestExecutorTests { HttpInvokerClientConfiguration config = mockHttpInvokerClientConfiguration("https://fake-service"); HttpPost httpPost = executor.createHttpPost(config); - assertEquals(10000, httpPost.getConfig().getSocketTimeout()); + assertThat(httpPost.getConfig().getSocketTimeout()).isEqualTo(10000); } @Test @@ -81,14 +78,14 @@ public class HttpComponentsHttpInvokerRequestExecutorTests { new HttpComponentsHttpInvokerRequestExecutor(client); HttpInvokerClientConfiguration config = mockHttpInvokerClientConfiguration("https://fake-service"); HttpPost httpPost = executor.createHttpPost(config); - assertSame("Default client configuration is expected", defaultConfig, httpPost.getConfig()); + assertThat(httpPost.getConfig()).as("Default client configuration is expected").isSameAs(defaultConfig); executor.setConnectionRequestTimeout(4567); HttpPost httpPost2 = executor.createHttpPost(config); - assertNotNull(httpPost2.getConfig()); - assertEquals(4567, httpPost2.getConfig().getConnectionRequestTimeout()); + assertThat(httpPost2.getConfig()).isNotNull(); + assertThat(httpPost2.getConfig().getConnectionRequestTimeout()).isEqualTo(4567); // Default connection timeout merged - assertEquals(1234, httpPost2.getConfig().getConnectTimeout()); + assertThat(httpPost2.getConfig().getConnectTimeout()).isEqualTo(1234); } @Test @@ -107,9 +104,9 @@ public class HttpComponentsHttpInvokerRequestExecutorTests { HttpInvokerClientConfiguration config = mockHttpInvokerClientConfiguration("https://fake-service"); HttpPost httpPost = executor.createHttpPost(config); RequestConfig requestConfig = httpPost.getConfig(); - assertEquals(5000, requestConfig.getConnectTimeout()); - assertEquals(6789, requestConfig.getConnectionRequestTimeout()); - assertEquals(-1, requestConfig.getSocketTimeout()); + assertThat(requestConfig.getConnectTimeout()).isEqualTo(5000); + assertThat(requestConfig.getConnectionRequestTimeout()).isEqualTo(6789); + assertThat(requestConfig.getSocketTimeout()).isEqualTo(-1); } @Test @@ -132,9 +129,9 @@ public class HttpComponentsHttpInvokerRequestExecutorTests { HttpInvokerClientConfiguration config = mockHttpInvokerClientConfiguration("https://fake-service"); HttpPost httpPost = executor.createHttpPost(config); RequestConfig requestConfig = httpPost.getConfig(); - assertEquals(-1, requestConfig.getConnectTimeout()); - assertEquals(-1, requestConfig.getConnectionRequestTimeout()); - assertEquals(5000, requestConfig.getSocketTimeout()); + assertThat(requestConfig.getConnectTimeout()).isEqualTo(-1); + assertThat(requestConfig.getConnectionRequestTimeout()).isEqualTo(-1); + assertThat(requestConfig.getSocketTimeout()).isEqualTo(5000); // Update the Http client so that it returns an updated config RequestConfig updatedDefaultConfig = RequestConfig.custom() @@ -143,9 +140,9 @@ public class HttpComponentsHttpInvokerRequestExecutorTests { executor.setReadTimeout(7000); HttpPost httpPost2 = executor.createHttpPost(config); RequestConfig requestConfig2 = httpPost2.getConfig(); - assertEquals(1234, requestConfig2.getConnectTimeout()); - assertEquals(-1, requestConfig2.getConnectionRequestTimeout()); - assertEquals(7000, requestConfig2.getSocketTimeout()); + assertThat(requestConfig2.getConnectTimeout()).isEqualTo(1234); + assertThat(requestConfig2.getConnectionRequestTimeout()).isEqualTo(-1); + assertThat(requestConfig2.getSocketTimeout()).isEqualTo(7000); } @Test @@ -160,7 +157,7 @@ public class HttpComponentsHttpInvokerRequestExecutorTests { HttpInvokerClientConfiguration config = mockHttpInvokerClientConfiguration("https://fake-service"); HttpPost httpPost = executor.createHttpPost(config); - assertNull("custom request config should not be set", httpPost.getConfig()); + assertThat(httpPost.getConfig()).as("custom request config should not be set").isNull(); } private HttpInvokerClientConfiguration mockHttpInvokerClientConfiguration(String serviceUrl) { diff --git a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerFactoryBeanIntegrationTests.java b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerFactoryBeanIntegrationTests.java index 89778597801..a60a886aaab 100644 --- a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerFactoryBeanIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerFactoryBeanIntegrationTests.java @@ -33,7 +33,7 @@ import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor; import org.springframework.stereotype.Component; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll @@ -45,7 +45,7 @@ public class HttpInvokerFactoryBeanIntegrationTests { public void testLoadedConfigClass() { ApplicationContext context = new AnnotationConfigApplicationContext(InvokerAutowiringConfig.class); MyBean myBean = context.getBean("myBean", MyBean.class); - assertSame(context.getBean("myService"), myBean.myService); + assertThat(myBean.myService).isSameAs(context.getBean("myService")); myBean.myService.handle(); myBean.myService.handleAsync(); } @@ -57,7 +57,7 @@ public class HttpInvokerFactoryBeanIntegrationTests { context.registerBeanDefinition("config", new RootBeanDefinition(InvokerAutowiringConfig.class.getName())); context.refresh(); MyBean myBean = context.getBean("myBean", MyBean.class); - assertSame(context.getBean("myService"), myBean.myService); + assertThat(myBean.myService).isSameAs(context.getBean("myService")); myBean.myService.handle(); myBean.myService.handleAsync(); } @@ -69,7 +69,7 @@ public class HttpInvokerFactoryBeanIntegrationTests { context.register(ConfigWithPlainFactoryBean.class); context.refresh(); MyBean myBean = context.getBean("myBean", MyBean.class); - assertSame(context.getBean("myService"), myBean.myService); + assertThat(myBean.myService).isSameAs(context.getBean("myService")); myBean.myService.handle(); myBean.myService.handleAsync(); } diff --git a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java index 2d99c5e6ba9..881b150fd8a 100644 --- a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java @@ -46,12 +46,9 @@ import org.springframework.remoting.support.RemoteInvocationResult; import org.springframework.tests.sample.beans.ITestBean; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -85,7 +82,7 @@ public class HttpInvokerTests { @Override protected RemoteInvocationResult doExecuteRequest( HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception { - assertEquals("https://myurl", config.getServiceUrl()); + assertThat(config.getServiceUrl()).isEqualTo("https://myurl"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setContent(baos.toByteArray()); @@ -100,24 +97,24 @@ public class HttpInvokerTests { pfb.afterPropertiesSet(); ITestBean proxy = (ITestBean) pfb.getObject(); - assertEquals("myname", proxy.getName()); - assertEquals(99, proxy.getAge()); + assertThat(proxy.getName()).isEqualTo("myname"); + assertThat(proxy.getAge()).isEqualTo(99); proxy.setAge(50); - assertEquals(50, proxy.getAge()); + assertThat(proxy.getAge()).isEqualTo(50); proxy.setStringArray(new String[] {"str1", "str2"}); - assertTrue(Arrays.equals(new String[] {"str1", "str2"}, proxy.getStringArray())); + assertThat(Arrays.equals(new String[] {"str1", "str2"}, proxy.getStringArray())).isTrue(); proxy.setSomeIntegerArray(new Integer[] {1, 2, 3}); - assertTrue(Arrays.equals(new Integer[] {1, 2, 3}, proxy.getSomeIntegerArray())); + assertThat(Arrays.equals(new Integer[] {1, 2, 3}, proxy.getSomeIntegerArray())).isTrue(); proxy.setNestedIntegerArray(new Integer[][] {{1, 2, 3}, {4, 5, 6}}); Integer[][] integerArray = proxy.getNestedIntegerArray(); - assertTrue(Arrays.equals(new Integer[] {1, 2, 3}, integerArray[0])); - assertTrue(Arrays.equals(new Integer[] {4, 5, 6}, integerArray[1])); + assertThat(Arrays.equals(new Integer[] {1, 2, 3}, integerArray[0])).isTrue(); + assertThat(Arrays.equals(new Integer[] {4, 5, 6}, integerArray[1])).isTrue(); proxy.setSomeIntArray(new int[] {1, 2, 3}); - assertTrue(Arrays.equals(new int[] {1, 2, 3}, proxy.getSomeIntArray())); + assertThat(Arrays.equals(new int[] {1, 2, 3}, proxy.getSomeIntArray())).isTrue(); proxy.setNestedIntArray(new int[][] {{1, 2, 3}, {4, 5, 6}}); int[][] intArray = proxy.getNestedIntArray(); - assertTrue(Arrays.equals(new int[] {1, 2, 3}, intArray[0])); - assertTrue(Arrays.equals(new int[] {4, 5, 6}, intArray[1])); + assertThat(Arrays.equals(new int[] {1, 2, 3}, intArray[0])).isTrue(); + assertThat(Arrays.equals(new int[] {4, 5, 6}, intArray[1])).isTrue(); assertThatIllegalStateException().isThrownBy(() -> proxy.exceptional(new IllegalStateException())); @@ -191,7 +188,7 @@ public class HttpInvokerTests { protected RemoteInvocationResult doExecuteRequest( HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws IOException, ClassNotFoundException { - assertEquals("https://myurl", config.getServiceUrl()); + assertThat(config.getServiceUrl()).isEqualTo("https://myurl"); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Compression", "gzip"); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -217,10 +214,10 @@ public class HttpInvokerTests { pfb.afterPropertiesSet(); ITestBean proxy = (ITestBean) pfb.getObject(); - assertEquals("myname", proxy.getName()); - assertEquals(99, proxy.getAge()); + assertThat(proxy.getName()).isEqualTo("myname"); + assertThat(proxy.getAge()).isEqualTo(99); proxy.setAge(50); - assertEquals(50, proxy.getAge()); + assertThat(proxy.getAge()).isEqualTo(50); assertThatIllegalStateException().isThrownBy(() -> proxy.exceptional(new IllegalStateException())); @@ -261,7 +258,7 @@ public class HttpInvokerTests { @Override protected RemoteInvocationResult doExecuteRequest( HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception { - assertEquals("https://myurl", config.getServiceUrl()); + assertThat(config.getServiceUrl()).isEqualTo("https://myurl"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setContent(baos.toByteArray()); @@ -287,10 +284,10 @@ public class HttpInvokerTests { pfb.afterPropertiesSet(); ITestBean proxy = (ITestBean) pfb.getObject(); - assertEquals("myname", proxy.getName()); - assertEquals(99, proxy.getAge()); + assertThat(proxy.getName()).isEqualTo("myname"); + assertThat(proxy.getAge()).isEqualTo(99); proxy.setAge(50); - assertEquals(50, proxy.getAge()); + assertThat(proxy.getAge()).isEqualTo(50); assertThatIllegalStateException().isThrownBy(() -> proxy.exceptional(new IllegalStateException())); @@ -309,10 +306,10 @@ public class HttpInvokerTests { @Override public Object invoke(RemoteInvocation invocation, Object targetObject) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { - assertNotNull(invocation.getAttributes()); - assertEquals(1, invocation.getAttributes().size()); - assertEquals("myValue", invocation.getAttributes().get("myKey")); - assertEquals("myValue", invocation.getAttribute("myKey")); + assertThat(invocation.getAttributes()).isNotNull(); + assertThat(invocation.getAttributes().size()).isEqualTo(1); + assertThat(invocation.getAttributes().get("myKey")).isEqualTo("myValue"); + assertThat(invocation.getAttribute("myKey")).isEqualTo("myValue"); return super.invoke(invocation, targetObject); } }); @@ -328,10 +325,10 @@ public class HttpInvokerTests { invocation.addAttribute("myKey", "myValue"); assertThatIllegalStateException().isThrownBy(() -> invocation.addAttribute("myKey", "myValue")); - assertNotNull(invocation.getAttributes()); - assertEquals(1, invocation.getAttributes().size()); - assertEquals("myValue", invocation.getAttributes().get("myKey")); - assertEquals("myValue", invocation.getAttribute("myKey")); + assertThat(invocation.getAttributes()).isNotNull(); + assertThat(invocation.getAttributes().size()).isEqualTo(1); + assertThat(invocation.getAttributes().get("myKey")).isEqualTo("myValue"); + assertThat(invocation.getAttribute("myKey")).isEqualTo("myValue"); return invocation; } }); @@ -340,7 +337,7 @@ public class HttpInvokerTests { @Override protected RemoteInvocationResult doExecuteRequest( HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception { - assertEquals("https://myurl", config.getServiceUrl()); + assertThat(config.getServiceUrl()).isEqualTo("https://myurl"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setContent(baos.toByteArray()); @@ -352,8 +349,8 @@ public class HttpInvokerTests { pfb.afterPropertiesSet(); ITestBean proxy = (ITestBean) pfb.getObject(); - assertEquals("myname", proxy.getName()); - assertEquals(99, proxy.getAge()); + assertThat(proxy.getName()).isEqualTo("myname"); + assertThat(proxy.getAge()).isEqualTo(99); } @Test @@ -367,9 +364,10 @@ public class HttpInvokerTests { @Override public Object invoke(RemoteInvocation invocation, Object targetObject) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { - assertTrue(invocation instanceof TestRemoteInvocation); - assertNull(invocation.getAttributes()); - assertNull(invocation.getAttribute("myKey")); + boolean condition = invocation instanceof TestRemoteInvocation; + assertThat(condition).isTrue(); + assertThat(invocation.getAttributes()).isNull(); + assertThat(invocation.getAttribute("myKey")).isNull(); return super.invoke(invocation, targetObject); } }); @@ -382,8 +380,8 @@ public class HttpInvokerTests { @Override public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) { RemoteInvocation invocation = new TestRemoteInvocation(methodInvocation); - assertNull(invocation.getAttributes()); - assertNull(invocation.getAttribute("myKey")); + assertThat(invocation.getAttributes()).isNull(); + assertThat(invocation.getAttribute("myKey")).isNull(); return invocation; } }); @@ -392,7 +390,7 @@ public class HttpInvokerTests { @Override protected RemoteInvocationResult doExecuteRequest( HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception { - assertEquals("https://myurl", config.getServiceUrl()); + assertThat(config.getServiceUrl()).isEqualTo("https://myurl"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setContent(baos.toByteArray()); @@ -404,8 +402,8 @@ public class HttpInvokerTests { pfb.afterPropertiesSet(); ITestBean proxy = (ITestBean) pfb.getObject(); - assertEquals("myname", proxy.getName()); - assertEquals(99, proxy.getAge()); + assertThat(proxy.getName()).isEqualTo("myname"); + assertThat(proxy.getAge()).isEqualTo(99); } @Test @@ -427,10 +425,10 @@ public class HttpInvokerTests { ITestBean proxy = (ITestBean) pfb.getObject(); // shouldn't go through to remote service - assertTrue(proxy.toString().contains("HTTP invoker")); - assertTrue(proxy.toString().contains(serviceUrl)); - assertEquals(proxy.hashCode(), proxy.hashCode()); - assertTrue(proxy.equals(proxy)); + assertThat(proxy.toString().contains("HTTP invoker")).isTrue(); + assertThat(proxy.toString().contains(serviceUrl)).isTrue(); + assertThat(proxy.hashCode()).isEqualTo(proxy.hashCode()); + assertThat(proxy.equals(proxy)).isTrue(); // should go through diff --git a/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java b/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java index d3a61cd8ade..6dd47eaeb79 100644 --- a/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java @@ -36,9 +36,8 @@ import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.support.GenericApplicationContext; import org.springframework.remoting.RemoteAccessException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -96,11 +95,12 @@ public class JaxWsSupportTests { ac.refresh(); OrderService orderService = ac.getBean("client", OrderService.class); - assertTrue(orderService instanceof BindingProvider); + boolean condition = orderService instanceof BindingProvider; + assertThat(condition).isTrue(); ((BindingProvider) orderService).getRequestContext(); String order = orderService.getOrder(1000); - assertEquals("order 1000", order); + assertThat(order).isEqualTo("order 1000"); assertThatExceptionOfType(Exception.class).isThrownBy(() -> orderService.getOrder(0)) .matches(ex -> ex instanceof OrderNotFoundException || @@ -109,7 +109,7 @@ public class JaxWsSupportTests { ServiceAccessor serviceAccessor = ac.getBean("accessor", ServiceAccessor.class); order = serviceAccessor.orderService.getOrder(1000); - assertEquals("order 1000", order); + assertThat(order).isEqualTo("order 1000"); assertThatExceptionOfType(Exception.class).isThrownBy(() -> serviceAccessor.orderService.getOrder(0)) .matches(ex -> ex instanceof OrderNotFoundException || diff --git a/spring-web/src/test/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBeanTests.java b/spring-web/src/test/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBeanTests.java index d59bfdc3ccd..062505e2f73 100644 --- a/spring-web/src/test/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBeanTests.java +++ b/spring-web/src/test/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBeanTests.java @@ -33,8 +33,8 @@ import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * Test fixture for {@link ContentNegotiationManagerFactoryBean} tests. @@ -70,25 +70,21 @@ public class ContentNegotiationManagerFactoryBeanTests { this.servletRequest.setRequestURI("/flower.gif"); - assertEquals("Should be able to resolve file extensions by default", - Collections.singletonList(MediaType.IMAGE_GIF), manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).as("Should be able to resolve file extensions by default").isEqualTo(Collections.singletonList(MediaType.IMAGE_GIF)); this.servletRequest.setRequestURI("/flower.foobarbaz"); - assertEquals("Should ignore unknown extensions by default", - ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).as("Should ignore unknown extensions by default").isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST); this.servletRequest.setRequestURI("/flower"); this.servletRequest.setParameter("format", "gif"); - assertEquals("Should not resolve request parameters by default", - ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).as("Should not resolve request parameters by default").isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST); this.servletRequest.setRequestURI("/flower"); this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE); - assertEquals("Should resolve Accept header by default", - Collections.singletonList(MediaType.IMAGE_GIF), manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).as("Should resolve Accept header by default").isEqualTo(Collections.singletonList(MediaType.IMAGE_GIF)); } @Test @@ -101,12 +97,11 @@ public class ContentNegotiationManagerFactoryBeanTests { this.factoryBean.afterPropertiesSet(); ContentNegotiationManager manager = this.factoryBean.getObject(); - assertEquals(strategies, manager.getStrategies()); + assertThat(manager.getStrategies()).isEqualTo(strategies); this.servletRequest.setRequestURI("/flower"); this.servletRequest.addParameter("format", "bar"); - assertEquals(Collections.singletonList(new MediaType("application", "bar")), - manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(Collections.singletonList(new MediaType("application", "bar"))); } @@ -118,15 +113,13 @@ public class ContentNegotiationManagerFactoryBeanTests { ContentNegotiationManager manager = this.factoryBean.getObject(); this.servletRequest.setRequestURI("/flower.foo"); - assertEquals(Collections.singletonList(new MediaType("application", "foo")), - manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(Collections.singletonList(new MediaType("application", "foo"))); this.servletRequest.setRequestURI("/flower.bar"); - assertEquals(Collections.singletonList(new MediaType("application", "bar")), - manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(Collections.singletonList(new MediaType("application", "bar"))); this.servletRequest.setRequestURI("/flower.gif"); - assertEquals(Collections.singletonList(MediaType.IMAGE_GIF), manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(Collections.singletonList(MediaType.IMAGE_GIF)); } @Test // SPR-10170 @@ -157,8 +150,7 @@ public class ContentNegotiationManagerFactoryBeanTests { this.servletRequest.setRequestURI("/flower"); this.servletRequest.addParameter("format", "json"); - assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), - manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); } @Test // SPR-10170 @@ -183,7 +175,7 @@ public class ContentNegotiationManagerFactoryBeanTests { this.servletRequest.setRequestURI("/flower"); this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE); - assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST); } @Test @@ -192,11 +184,11 @@ public class ContentNegotiationManagerFactoryBeanTests { this.factoryBean.afterPropertiesSet(); ContentNegotiationManager manager = this.factoryBean.getObject(); - assertEquals(MediaType.APPLICATION_JSON, manager.resolveMediaTypes(this.webRequest).get(0)); + assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).isEqualTo(MediaType.APPLICATION_JSON); // SPR-10513 this.servletRequest.addHeader("Accept", MediaType.ALL_VALUE); - assertEquals(MediaType.APPLICATION_JSON, manager.resolveMediaTypes(this.webRequest).get(0)); + assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).isEqualTo(MediaType.APPLICATION_JSON); } @Test // SPR-15367 @@ -206,10 +198,10 @@ public class ContentNegotiationManagerFactoryBeanTests { this.factoryBean.afterPropertiesSet(); ContentNegotiationManager manager = this.factoryBean.getObject(); - assertEquals(mediaTypes, manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(mediaTypes); this.servletRequest.addHeader("Accept", MediaType.ALL_VALUE); - assertEquals(mediaTypes, manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(mediaTypes); } @Test // SPR-12286 @@ -218,12 +210,10 @@ public class ContentNegotiationManagerFactoryBeanTests { this.factoryBean.afterPropertiesSet(); ContentNegotiationManager manager = this.factoryBean.getObject(); - assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), - manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); this.servletRequest.addHeader("Accept", MediaType.ALL_VALUE); - assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), - manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); } diff --git a/spring-web/src/test/java/org/springframework/web/accept/HeaderContentNegotiationStrategyTests.java b/spring-web/src/test/java/org/springframework/web/accept/HeaderContentNegotiationStrategyTests.java index 3c70a9279a5..d32024dea0b 100644 --- a/spring-web/src/test/java/org/springframework/web/accept/HeaderContentNegotiationStrategyTests.java +++ b/spring-web/src/test/java/org/springframework/web/accept/HeaderContentNegotiationStrategyTests.java @@ -26,8 +26,8 @@ import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * Test fixture for HeaderContentNegotiationStrategy tests. @@ -49,11 +49,11 @@ public class HeaderContentNegotiationStrategyTests { this.servletRequest.addHeader("Accept", "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"); List mediaTypes = this.strategy.resolveMediaTypes(this.webRequest); - assertEquals(4, mediaTypes.size()); - assertEquals("text/html", mediaTypes.get(0).toString()); - assertEquals("text/x-c", mediaTypes.get(1).toString()); - assertEquals("text/x-dvi;q=0.8", mediaTypes.get(2).toString()); - assertEquals("text/plain;q=0.5", mediaTypes.get(3).toString()); + assertThat(mediaTypes.size()).isEqualTo(4); + assertThat(mediaTypes.get(0).toString()).isEqualTo("text/html"); + assertThat(mediaTypes.get(1).toString()).isEqualTo("text/x-c"); + assertThat(mediaTypes.get(2).toString()).isEqualTo("text/x-dvi;q=0.8"); + assertThat(mediaTypes.get(3).toString()).isEqualTo("text/plain;q=0.5"); } @Test // SPR-14506 @@ -62,11 +62,11 @@ public class HeaderContentNegotiationStrategyTests { this.servletRequest.addHeader("Accept", "text/x-dvi; q=0.8, text/x-c"); List mediaTypes = this.strategy.resolveMediaTypes(this.webRequest); - assertEquals(4, mediaTypes.size()); - assertEquals("text/html", mediaTypes.get(0).toString()); - assertEquals("text/x-c", mediaTypes.get(1).toString()); - assertEquals("text/x-dvi;q=0.8", mediaTypes.get(2).toString()); - assertEquals("text/plain;q=0.5", mediaTypes.get(3).toString()); + assertThat(mediaTypes.size()).isEqualTo(4); + assertThat(mediaTypes.get(0).toString()).isEqualTo("text/html"); + assertThat(mediaTypes.get(1).toString()).isEqualTo("text/x-c"); + assertThat(mediaTypes.get(2).toString()).isEqualTo("text/x-dvi;q=0.8"); + assertThat(mediaTypes.get(3).toString()).isEqualTo("text/plain;q=0.5"); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/accept/MappingContentNegotiationStrategyTests.java b/spring-web/src/test/java/org/springframework/web/accept/MappingContentNegotiationStrategyTests.java index b9d70095e08..a4e6f630f2e 100644 --- a/spring-web/src/test/java/org/springframework/web/accept/MappingContentNegotiationStrategyTests.java +++ b/spring-web/src/test/java/org/springframework/web/accept/MappingContentNegotiationStrategyTests.java @@ -25,7 +25,7 @@ import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.web.context.request.NativeWebRequest; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * A test fixture with a test sub-class of AbstractMappingContentNegotiationStrategy. @@ -42,8 +42,8 @@ public class MappingContentNegotiationStrategyTests { List mediaTypes = strategy.resolveMediaTypes(null); - assertEquals(1, mediaTypes.size()); - assertEquals("application/json", mediaTypes.get(0).toString()); + assertThat(mediaTypes.size()).isEqualTo(1); + assertThat(mediaTypes.get(0).toString()).isEqualTo("application/json"); } @Test @@ -53,7 +53,7 @@ public class MappingContentNegotiationStrategyTests { List mediaTypes = strategy.resolveMediaTypes(null); - assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, mediaTypes); + assertThat(mediaTypes).isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST); } @Test @@ -63,7 +63,7 @@ public class MappingContentNegotiationStrategyTests { List mediaTypes = strategy.resolveMediaTypes(null); - assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, mediaTypes); + assertThat(mediaTypes).isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST); } @Test @@ -73,8 +73,8 @@ public class MappingContentNegotiationStrategyTests { List mediaTypes = strategy.resolveMediaTypes(null); - assertEquals(1, mediaTypes.size()); - assertEquals("application/xml", mediaTypes.get(0).toString()); + assertThat(mediaTypes.size()).isEqualTo(1); + assertThat(mediaTypes.get(0).toString()).isEqualTo("application/xml"); } diff --git a/spring-web/src/test/java/org/springframework/web/accept/MappingMediaTypeFileExtensionResolverTests.java b/spring-web/src/test/java/org/springframework/web/accept/MappingMediaTypeFileExtensionResolverTests.java index 668f686bdaa..ce83f6a6040 100644 --- a/spring-web/src/test/java/org/springframework/web/accept/MappingMediaTypeFileExtensionResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/accept/MappingMediaTypeFileExtensionResolverTests.java @@ -23,8 +23,7 @@ import org.junit.Test; import org.springframework.http.MediaType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link MappingMediaTypeFileExtensionResolver}. @@ -40,8 +39,8 @@ public class MappingMediaTypeFileExtensionResolverTests { MappingMediaTypeFileExtensionResolver resolver = new MappingMediaTypeFileExtensionResolver(mapping); List extensions = resolver.resolveFileExtensions(MediaType.APPLICATION_JSON); - assertEquals(1, extensions.size()); - assertEquals("json", extensions.get(0)); + assertThat(extensions.size()).isEqualTo(1); + assertThat(extensions.get(0)).isEqualTo("json"); } @Test @@ -50,7 +49,7 @@ public class MappingMediaTypeFileExtensionResolverTests { MappingMediaTypeFileExtensionResolver resolver = new MappingMediaTypeFileExtensionResolver(mapping); List extensions = resolver.resolveFileExtensions(MediaType.TEXT_HTML); - assertTrue(extensions.isEmpty()); + assertThat(extensions.isEmpty()).isTrue(); } /** @@ -63,7 +62,7 @@ public class MappingMediaTypeFileExtensionResolverTests { MappingMediaTypeFileExtensionResolver resolver = new MappingMediaTypeFileExtensionResolver(mapping); MediaType mediaType = resolver.lookupMediaType("JSON"); - assertEquals(MediaType.APPLICATION_JSON, mediaType); + assertThat(mediaType).isEqualTo(MediaType.APPLICATION_JSON); } } diff --git a/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java b/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java index ce1623d23a6..c3f63306aeb 100644 --- a/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java +++ b/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java @@ -29,8 +29,8 @@ import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * A test fixture for PathExtensionContentNegotiationStrategy. @@ -60,13 +60,13 @@ public class PathExtensionContentNegotiationStrategyTests { PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(); List mediaTypes = strategy.resolveMediaTypes(this.webRequest); - assertEquals(Arrays.asList(new MediaType("text", "html")), mediaTypes); + assertThat(mediaTypes).isEqualTo(Arrays.asList(new MediaType("text", "html"))); Map mapping = Collections.singletonMap("HTML", MediaType.APPLICATION_XHTML_XML); strategy = new PathExtensionContentNegotiationStrategy(mapping); mediaTypes = strategy.resolveMediaTypes(this.webRequest); - assertEquals(Arrays.asList(new MediaType("application", "xhtml+xml")), mediaTypes); + assertThat(mediaTypes).isEqualTo(Arrays.asList(new MediaType("application", "xhtml+xml"))); } @Test @@ -77,7 +77,7 @@ public class PathExtensionContentNegotiationStrategyTests { PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(); List mediaTypes = strategy.resolveMediaTypes(this.webRequest); - assertEquals(Arrays.asList(new MediaType("application", "vnd.ms-excel")), mediaTypes); + assertThat(mediaTypes).isEqualTo(Arrays.asList(new MediaType("application", "vnd.ms-excel"))); } // SPR-8678 @@ -89,12 +89,10 @@ public class PathExtensionContentNegotiationStrategyTests { this.servletRequest.setContextPath("/project-1.0.0.M3"); this.servletRequest.setRequestURI("/project-1.0.0.M3/"); - assertEquals("Context path should be excluded", ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, - strategy.resolveMediaTypes(webRequest)); + assertThat(strategy.resolveMediaTypes(webRequest)).as("Context path should be excluded").isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST); this.servletRequest.setRequestURI("/project-1.0.0.M3"); - assertEquals("Context path should be excluded", ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, - strategy.resolveMediaTypes(webRequest)); + assertThat(strategy.resolveMediaTypes(webRequest)).as("Context path should be excluded").isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST); } // SPR-9390 @@ -107,7 +105,7 @@ public class PathExtensionContentNegotiationStrategyTests { PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(); List result = strategy.resolveMediaTypes(webRequest); - assertEquals("Invalid content type", Collections.singletonList(new MediaType("text", "html")), result); + assertThat(result).as("Invalid content type").isEqualTo(Collections.singletonList(new MediaType("text", "html"))); } // SPR-10170 @@ -120,7 +118,7 @@ public class PathExtensionContentNegotiationStrategyTests { PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(); List mediaTypes = strategy.resolveMediaTypes(this.webRequest); - assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, mediaTypes); + assertThat(mediaTypes).isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java b/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java index 1cbb5d3fcd1..30691e89c8c 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java @@ -24,7 +24,7 @@ import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -43,52 +43,52 @@ public class EscapedErrorsTests { errors.rejectValue("age", "AGE_NOT_32 ", null, "message: "); errors.reject("GENERAL_ERROR \" '", null, "message: \" '"); - assertTrue("Correct errors flag", errors.hasErrors()); - assertTrue("Correct number of errors", errors.getErrorCount() == 4); - assertTrue("Correct object name", "tb".equals(errors.getObjectName())); + assertThat(errors.hasErrors()).as("Correct errors flag").isTrue(); + assertThat(errors.getErrorCount() == 4).as("Correct number of errors").isTrue(); + assertThat("tb".equals(errors.getObjectName())).as("Correct object name").isTrue(); - assertTrue("Correct global errors flag", errors.hasGlobalErrors()); - assertTrue("Correct number of global errors", errors.getGlobalErrorCount() == 1); + assertThat(errors.hasGlobalErrors()).as("Correct global errors flag").isTrue(); + assertThat(errors.getGlobalErrorCount() == 1).as("Correct number of global errors").isTrue(); ObjectError globalError = errors.getGlobalError(); String defaultMessage = globalError.getDefaultMessage(); - assertTrue("Global error message escaped", "message: " '".equals(defaultMessage)); - assertTrue("Global error code not escaped", "GENERAL_ERROR \" '".equals(globalError.getCode())); + assertThat("message: " '".equals(defaultMessage)).as("Global error message escaped").isTrue(); + assertThat("GENERAL_ERROR \" '".equals(globalError.getCode())).as("Global error code not escaped").isTrue(); ObjectError globalErrorInList = errors.getGlobalErrors().get(0); - assertTrue("Same global error in list", defaultMessage.equals(globalErrorInList.getDefaultMessage())); + assertThat(defaultMessage.equals(globalErrorInList.getDefaultMessage())).as("Same global error in list").isTrue(); ObjectError globalErrorInAllList = errors.getAllErrors().get(3); - assertTrue("Same global error in list", defaultMessage.equals(globalErrorInAllList.getDefaultMessage())); + assertThat(defaultMessage.equals(globalErrorInAllList.getDefaultMessage())).as("Same global error in list").isTrue(); - assertTrue("Correct field errors flag", errors.hasFieldErrors()); - assertTrue("Correct number of field errors", errors.getFieldErrorCount() == 3); - assertTrue("Correct number of field errors in list", errors.getFieldErrors().size() == 3); + assertThat(errors.hasFieldErrors()).as("Correct field errors flag").isTrue(); + assertThat(errors.getFieldErrorCount() == 3).as("Correct number of field errors").isTrue(); + assertThat(errors.getFieldErrors().size() == 3).as("Correct number of field errors in list").isTrue(); FieldError fieldError = errors.getFieldError(); - assertTrue("Field error code not escaped", "NAME_EMPTY &".equals(fieldError.getCode())); - assertTrue("Field value escaped", "empty &".equals(errors.getFieldValue("name"))); + assertThat("NAME_EMPTY &".equals(fieldError.getCode())).as("Field error code not escaped").isTrue(); + assertThat("empty &".equals(errors.getFieldValue("name"))).as("Field value escaped").isTrue(); FieldError fieldErrorInList = errors.getFieldErrors().get(0); - assertTrue("Same field error in list", fieldError.getDefaultMessage().equals(fieldErrorInList.getDefaultMessage())); + assertThat(fieldError.getDefaultMessage().equals(fieldErrorInList.getDefaultMessage())).as("Same field error in list").isTrue(); - assertTrue("Correct name errors flag", errors.hasFieldErrors("name")); - assertTrue("Correct number of name errors", errors.getFieldErrorCount("name") == 1); - assertTrue("Correct number of name errors in list", errors.getFieldErrors("name").size() == 1); + assertThat(errors.hasFieldErrors("name")).as("Correct name errors flag").isTrue(); + assertThat(errors.getFieldErrorCount("name") == 1).as("Correct number of name errors").isTrue(); + assertThat(errors.getFieldErrors("name").size() == 1).as("Correct number of name errors in list").isTrue(); FieldError nameError = errors.getFieldError("name"); - assertTrue("Name error message escaped", "message: &".equals(nameError.getDefaultMessage())); - assertTrue("Name error code not escaped", "NAME_EMPTY &".equals(nameError.getCode())); - assertTrue("Name value escaped", "empty &".equals(errors.getFieldValue("name"))); + assertThat("message: &".equals(nameError.getDefaultMessage())).as("Name error message escaped").isTrue(); + assertThat("NAME_EMPTY &".equals(nameError.getCode())).as("Name error code not escaped").isTrue(); + assertThat("empty &".equals(errors.getFieldValue("name"))).as("Name value escaped").isTrue(); FieldError nameErrorInList = errors.getFieldErrors("name").get(0); - assertTrue("Same name error in list", nameError.getDefaultMessage().equals(nameErrorInList.getDefaultMessage())); + assertThat(nameError.getDefaultMessage().equals(nameErrorInList.getDefaultMessage())).as("Same name error in list").isTrue(); - assertTrue("Correct age errors flag", errors.hasFieldErrors("age")); - assertTrue("Correct number of age errors", errors.getFieldErrorCount("age") == 2); - assertTrue("Correct number of age errors in list", errors.getFieldErrors("age").size() == 2); + assertThat(errors.hasFieldErrors("age")).as("Correct age errors flag").isTrue(); + assertThat(errors.getFieldErrorCount("age") == 2).as("Correct number of age errors").isTrue(); + assertThat(errors.getFieldErrors("age").size() == 2).as("Correct number of age errors in list").isTrue(); FieldError ageError = errors.getFieldError("age"); - assertTrue("Age error message escaped", "message: <tag>".equals(ageError.getDefaultMessage())); - assertTrue("Age error code not escaped", "AGE_NOT_SET ".equals(ageError.getCode())); - assertTrue("Age value not escaped", (new Integer(0)).equals(errors.getFieldValue("age"))); + assertThat("message: <tag>".equals(ageError.getDefaultMessage())).as("Age error message escaped").isTrue(); + assertThat("AGE_NOT_SET ".equals(ageError.getCode())).as("Age error code not escaped").isTrue(); + assertThat((new Integer(0)).equals(errors.getFieldValue("age"))).as("Age value not escaped").isTrue(); FieldError ageErrorInList = errors.getFieldErrors("age").get(0); - assertTrue("Same name error in list", ageError.getDefaultMessage().equals(ageErrorInList.getDefaultMessage())); + assertThat(ageError.getDefaultMessage().equals(ageErrorInList.getDefaultMessage())).as("Same name error in list").isTrue(); FieldError ageError2 = errors.getFieldErrors("age").get(1); - assertTrue("Age error 2 message escaped", "message: <tag>".equals(ageError2.getDefaultMessage())); - assertTrue("Age error 2 code not escaped", "AGE_NOT_32 ".equals(ageError2.getCode())); + assertThat("message: <tag>".equals(ageError2.getDefaultMessage())).as("Age error 2 message escaped").isTrue(); + assertThat("AGE_NOT_32 ".equals(ageError2.getCode())).as("Age error 2 code not escaped").isTrue(); } } diff --git a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestDataBinderTests.java b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestDataBinderTests.java index d10b226b359..3b5a4bc46b6 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestDataBinderTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestDataBinderTests.java @@ -29,10 +29,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson @@ -59,8 +56,8 @@ public class ServletRequestDataBinderTests { request.addParameter("spouse.name", "test"); binder.bind(request); - assertNotNull(tb.getSpouse()); - assertEquals("test", tb.getSpouse().getName()); + assertThat(tb.getSpouse()).isNotNull(); + assertThat(tb.getSpouse().getName()).isEqualTo("test"); } @Test @@ -72,11 +69,11 @@ public class ServletRequestDataBinderTests { request.addParameter("_postProcessed", "visible"); request.addParameter("postProcessed", "on"); binder.bind(request); - assertTrue(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isTrue(); request.removeParameter("postProcessed"); binder.bind(request); - assertFalse(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isFalse(); } @Test @@ -89,11 +86,11 @@ public class ServletRequestDataBinderTests { request.addParameter("_postProcessed", "visible"); request.addParameter("postProcessed", "on"); binder.bind(request); - assertTrue(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isTrue(); request.removeParameter("postProcessed"); binder.bind(request); - assertFalse(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isFalse(); } @Test @@ -105,11 +102,11 @@ public class ServletRequestDataBinderTests { request.addParameter("!postProcessed", "off"); request.addParameter("postProcessed", "on"); binder.bind(request); - assertTrue(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isTrue(); request.removeParameter("postProcessed"); binder.bind(request); - assertFalse(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isFalse(); } @Test @@ -122,15 +119,15 @@ public class ServletRequestDataBinderTests { request.addParameter("_postProcessed", "visible"); request.addParameter("postProcessed", "on"); binder.bind(request); - assertTrue(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isTrue(); request.removeParameter("postProcessed"); binder.bind(request); - assertTrue(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isTrue(); request.removeParameter("!postProcessed"); binder.bind(request); - assertFalse(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isFalse(); } @Test @@ -142,11 +139,11 @@ public class ServletRequestDataBinderTests { request.addParameter("!name", "anonymous"); request.addParameter("name", "Scott"); binder.bind(request); - assertEquals("Scott", target.getName()); + assertThat(target.getName()).isEqualTo("Scott"); request.removeParameter("name"); binder.bind(request); - assertEquals("anonymous", target.getName()); + assertThat(target.getName()).isEqualTo("anonymous"); } @Test @@ -159,12 +156,12 @@ public class ServletRequestDataBinderTests { request.addParameter("stringArray", "abc"); request.addParameter("stringArray", "123,def"); binder.bind(request); - assertEquals("Expected all three items to be bound", 3, target.getStringArray().length); + assertThat(target.getStringArray().length).as("Expected all three items to be bound").isEqualTo(3); request.removeParameter("stringArray"); request.addParameter("stringArray", "123,def"); binder.bind(request); - assertEquals("Expected only 1 item to be bound", 1, target.getStringArray().length); + assertThat(target.getStringArray().length).as("Expected only 1 item to be bound").isEqualTo(1); } @Test @@ -184,8 +181,8 @@ public class ServletRequestDataBinderTests { request.addParameter("spouse", "someValue"); binder.bind(request); - assertNotNull(tb.getSpouse()); - assertEquals("test", tb.getSpouse().getName()); + assertThat(tb.getSpouse()).isNotNull(); + assertThat(tb.getSpouse().getName()).isEqualTo("test"); } @Test @@ -207,8 +204,9 @@ public class ServletRequestDataBinderTests { request.addParameter("test_age", "" + 50); ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request); - assertTrue("Didn't find normal when given prefix", !pvs.contains("forname")); - assertTrue("Did treat prefix as normal when not given prefix", pvs.contains("test_forname")); + boolean condition = !pvs.contains("forname"); + assertThat(condition).as("Didn't find normal when given prefix").isTrue(); + assertThat(pvs.contains("test_forname")).as("Did treat prefix as normal when not given prefix").isTrue(); pvs = new ServletRequestParameterPropertyValues(request, "test"); doTestTony(pvs); @@ -218,7 +216,7 @@ public class ServletRequestDataBinderTests { public void testNoParameters() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request); - assertTrue("Found no parameters", pvs.getPropertyValues().length == 0); + assertThat(pvs.getPropertyValues().length == 0).as("Found no parameters").isTrue(); } @Test @@ -228,21 +226,23 @@ public class ServletRequestDataBinderTests { request.addParameter("forname", original); ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request); - assertTrue("Found 1 parameter", pvs.getPropertyValues().length == 1); - assertTrue("Found array value", pvs.getPropertyValue("forname").getValue() instanceof String[]); + assertThat(pvs.getPropertyValues().length == 1).as("Found 1 parameter").isTrue(); + boolean condition = pvs.getPropertyValue("forname").getValue() instanceof String[]; + assertThat(condition).as("Found array value").isTrue(); String[] values = (String[]) pvs.getPropertyValue("forname").getValue(); - assertEquals("Correct values", Arrays.asList(values), Arrays.asList(original)); + assertThat(Arrays.asList(original)).as("Correct values").isEqualTo(Arrays.asList(values)); } /** * Must contain: forname=Tony surname=Blair age=50 */ protected void doTestTony(PropertyValues pvs) throws Exception { - assertTrue("Contains 3", pvs.getPropertyValues().length == 3); - assertTrue("Contains forname", pvs.contains("forname")); - assertTrue("Contains surname", pvs.contains("surname")); - assertTrue("Contains age", pvs.contains("age")); - assertTrue("Doesn't contain tory", !pvs.contains("tory")); + assertThat(pvs.getPropertyValues().length == 3).as("Contains 3").isTrue(); + assertThat(pvs.contains("forname")).as("Contains forname").isTrue(); + assertThat(pvs.contains("surname")).as("Contains surname").isTrue(); + assertThat(pvs.contains("age")).as("Contains age").isTrue(); + boolean condition1 = !pvs.contains("tory"); + assertThat(condition1).as("Doesn't contain tory").isTrue(); PropertyValue[] ps = pvs.getPropertyValues(); Map m = new HashMap<>(); @@ -251,12 +251,13 @@ public class ServletRequestDataBinderTests { m.put("age", "50"); for (int i = 0; i < ps.length; i++) { Object val = m.get(ps[i].getName()); - assertTrue("Can't have unexpected value", val != null); - assertTrue("Val i string", val instanceof String); - assertTrue("val matches expected", val.equals(ps[i].getValue())); + assertThat(val != null).as("Can't have unexpected value").isTrue(); + boolean condition = val instanceof String; + assertThat(condition).as("Val i string").isTrue(); + assertThat(val.equals(ps[i].getValue())).as("val matches expected").isTrue(); m.remove(ps[i].getName()); } - assertTrue("Map size is 0", m.size() == 0); + assertThat(m.size() == 0).as("Map size is 0").isTrue(); } } diff --git a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java index 89a7059a9ac..7cbbdb82eb5 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java @@ -23,11 +23,8 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import org.springframework.util.StopWatch; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * @author Juergen Hoeller @@ -43,16 +40,16 @@ public class ServletRequestUtilsTests { request.addParameter("param2", "e"); request.addParameter("paramEmpty", ""); - assertEquals(ServletRequestUtils.getIntParameter(request, "param1"), new Integer(5)); - assertEquals(ServletRequestUtils.getIntParameter(request, "param1", 6), 5); - assertEquals(ServletRequestUtils.getRequiredIntParameter(request, "param1"), 5); + assertThat(ServletRequestUtils.getIntParameter(request, "param1")).isEqualTo(new Integer(5)); + assertThat(ServletRequestUtils.getIntParameter(request, "param1", 6)).isEqualTo(5); + assertThat(ServletRequestUtils.getRequiredIntParameter(request, "param1")).isEqualTo(5); - assertEquals(ServletRequestUtils.getIntParameter(request, "param2", 6), 6); + assertThat(ServletRequestUtils.getIntParameter(request, "param2", 6)).isEqualTo(6); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredIntParameter(request, "param2")); - assertEquals(ServletRequestUtils.getIntParameter(request, "param3"), null); - assertEquals(ServletRequestUtils.getIntParameter(request, "param3", 6), 6); + assertThat(ServletRequestUtils.getIntParameter(request, "param3")).isEqualTo(null); + assertThat(ServletRequestUtils.getIntParameter(request, "param3", 6)).isEqualTo(6); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredIntParameter(request, "param3")); @@ -71,9 +68,9 @@ public class ServletRequestUtilsTests { int[] array = new int[] {1, 2, 3}; int[] values = ServletRequestUtils.getRequiredIntParameters(request, "param"); - assertEquals(3, values.length); + assertThat(3).isEqualTo(values.length); for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i]); + assertThat(array[i]).isEqualTo(values[i]); } assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> @@ -87,16 +84,16 @@ public class ServletRequestUtilsTests { request.addParameter("param2", "e"); request.addParameter("paramEmpty", ""); - assertEquals(ServletRequestUtils.getLongParameter(request, "param1"), new Long(5L)); - assertEquals(ServletRequestUtils.getLongParameter(request, "param1", 6L), 5L); - assertEquals(ServletRequestUtils.getRequiredIntParameter(request, "param1"), 5L); + assertThat(ServletRequestUtils.getLongParameter(request, "param1")).isEqualTo(new Long(5L)); + assertThat(ServletRequestUtils.getLongParameter(request, "param1", 6L)).isEqualTo(5L); + assertThat(ServletRequestUtils.getRequiredIntParameter(request, "param1")).isEqualTo(5L); - assertEquals(ServletRequestUtils.getLongParameter(request, "param2", 6L), 6L); + assertThat(ServletRequestUtils.getLongParameter(request, "param2", 6L)).isEqualTo(6L); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredLongParameter(request, "param2")); - assertEquals(ServletRequestUtils.getLongParameter(request, "param3"), null); - assertEquals(ServletRequestUtils.getLongParameter(request, "param3", 6L), 6L); + assertThat(ServletRequestUtils.getLongParameter(request, "param3")).isEqualTo(null); + assertThat(ServletRequestUtils.getLongParameter(request, "param3", 6L)).isEqualTo(6L); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredLongParameter(request, "param3")); @@ -114,21 +111,15 @@ public class ServletRequestUtilsTests { request.addParameter("param2", "2"); request.addParameter("param2", "bogus"); - long[] array = new long[] {1L, 2L, 3L}; long[] values = ServletRequestUtils.getRequiredLongParameters(request, "param"); - assertEquals(3, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i]); - } + assertThat(values).containsExactly(1, 2, 3); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredLongParameters(request, "param2")); request.setParameter("param2", new String[] {"1", "2"}); values = ServletRequestUtils.getRequiredLongParameters(request, "param2"); - assertEquals(2, values.length); - assertEquals(1, values[0]); - assertEquals(2, values[1]); + assertThat(values).containsExactly(1, 2); request.removeParameter("param2"); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> @@ -142,16 +133,16 @@ public class ServletRequestUtilsTests { request.addParameter("param2", "e"); request.addParameter("paramEmpty", ""); - assertTrue(ServletRequestUtils.getFloatParameter(request, "param1").equals(new Float(5.5f))); - assertTrue(ServletRequestUtils.getFloatParameter(request, "param1", 6.5f) == 5.5f); - assertTrue(ServletRequestUtils.getRequiredFloatParameter(request, "param1") == 5.5f); + assertThat(ServletRequestUtils.getFloatParameter(request, "param1").equals(new Float(5.5f))).isTrue(); + assertThat(ServletRequestUtils.getFloatParameter(request, "param1", 6.5f) == 5.5f).isTrue(); + assertThat(ServletRequestUtils.getRequiredFloatParameter(request, "param1") == 5.5f).isTrue(); - assertTrue(ServletRequestUtils.getFloatParameter(request, "param2", 6.5f) == 6.5f); + assertThat(ServletRequestUtils.getFloatParameter(request, "param2", 6.5f) == 6.5f).isTrue(); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredFloatParameter(request, "param2")); - assertTrue(ServletRequestUtils.getFloatParameter(request, "param3") == null); - assertTrue(ServletRequestUtils.getFloatParameter(request, "param3", 6.5f) == 6.5f); + assertThat(ServletRequestUtils.getFloatParameter(request, "param3") == null).isTrue(); + assertThat(ServletRequestUtils.getFloatParameter(request, "param3", 6.5f) == 6.5f).isTrue(); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredFloatParameter(request, "param3")); @@ -168,12 +159,8 @@ public class ServletRequestUtilsTests { request.addParameter("param2", "2"); request.addParameter("param2", "bogus"); - float[] array = new float[] {1.5F, 2.5F, 3}; float[] values = ServletRequestUtils.getRequiredFloatParameters(request, "param"); - assertEquals(3, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i], 0); - } + assertThat(values).containsExactly(1.5F, 2.5F, 3F); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredFloatParameters(request, "param2")); @@ -186,16 +173,16 @@ public class ServletRequestUtilsTests { request.addParameter("param2", "e"); request.addParameter("paramEmpty", ""); - assertTrue(ServletRequestUtils.getDoubleParameter(request, "param1").equals(new Double(5.5))); - assertTrue(ServletRequestUtils.getDoubleParameter(request, "param1", 6.5) == 5.5); - assertTrue(ServletRequestUtils.getRequiredDoubleParameter(request, "param1") == 5.5); + assertThat(ServletRequestUtils.getDoubleParameter(request, "param1").equals(new Double(5.5))).isTrue(); + assertThat(ServletRequestUtils.getDoubleParameter(request, "param1", 6.5) == 5.5).isTrue(); + assertThat(ServletRequestUtils.getRequiredDoubleParameter(request, "param1") == 5.5).isTrue(); - assertTrue(ServletRequestUtils.getDoubleParameter(request, "param2", 6.5) == 6.5); + assertThat(ServletRequestUtils.getDoubleParameter(request, "param2", 6.5) == 6.5).isTrue(); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredDoubleParameter(request, "param2")); - assertTrue(ServletRequestUtils.getDoubleParameter(request, "param3") == null); - assertTrue(ServletRequestUtils.getDoubleParameter(request, "param3", 6.5) == 6.5); + assertThat(ServletRequestUtils.getDoubleParameter(request, "param3") == null).isTrue(); + assertThat(ServletRequestUtils.getDoubleParameter(request, "param3", 6.5) == 6.5).isTrue(); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredDoubleParameter(request, "param3")); @@ -212,13 +199,8 @@ public class ServletRequestUtilsTests { request.addParameter("param2", "2"); request.addParameter("param2", "bogus"); - double[] array = new double[] {1.5, 2.5, 3}; double[] values = ServletRequestUtils.getRequiredDoubleParameters(request, "param"); - assertEquals(3, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i], 0); - } - + assertThat(values).containsExactly(1.5, 2.5, 3); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredDoubleParameters(request, "param2")); } @@ -232,24 +214,24 @@ public class ServletRequestUtilsTests { request.addParameter("param5", "1"); request.addParameter("paramEmpty", ""); - assertTrue(ServletRequestUtils.getBooleanParameter(request, "param1").equals(Boolean.TRUE)); - assertTrue(ServletRequestUtils.getBooleanParameter(request, "param1", false)); - assertTrue(ServletRequestUtils.getRequiredBooleanParameter(request, "param1")); + assertThat(ServletRequestUtils.getBooleanParameter(request, "param1").equals(Boolean.TRUE)).isTrue(); + assertThat(ServletRequestUtils.getBooleanParameter(request, "param1", false)).isTrue(); + assertThat(ServletRequestUtils.getRequiredBooleanParameter(request, "param1")).isTrue(); - assertFalse(ServletRequestUtils.getBooleanParameter(request, "param2", true)); - assertFalse(ServletRequestUtils.getRequiredBooleanParameter(request, "param2")); + assertThat(ServletRequestUtils.getBooleanParameter(request, "param2", true)).isFalse(); + assertThat(ServletRequestUtils.getRequiredBooleanParameter(request, "param2")).isFalse(); - assertTrue(ServletRequestUtils.getBooleanParameter(request, "param3") == null); - assertTrue(ServletRequestUtils.getBooleanParameter(request, "param3", true)); + assertThat(ServletRequestUtils.getBooleanParameter(request, "param3") == null).isTrue(); + assertThat(ServletRequestUtils.getBooleanParameter(request, "param3", true)).isTrue(); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredBooleanParameter(request, "param3")); - assertTrue(ServletRequestUtils.getBooleanParameter(request, "param4", false)); - assertTrue(ServletRequestUtils.getRequiredBooleanParameter(request, "param4")); + assertThat(ServletRequestUtils.getBooleanParameter(request, "param4", false)).isTrue(); + assertThat(ServletRequestUtils.getRequiredBooleanParameter(request, "param4")).isTrue(); - assertTrue(ServletRequestUtils.getBooleanParameter(request, "param5", false)); - assertTrue(ServletRequestUtils.getRequiredBooleanParameter(request, "param5")); - assertFalse(ServletRequestUtils.getRequiredBooleanParameter(request, "paramEmpty")); + assertThat(ServletRequestUtils.getBooleanParameter(request, "param5", false)).isTrue(); + assertThat(ServletRequestUtils.getRequiredBooleanParameter(request, "param5")).isTrue(); + assertThat(ServletRequestUtils.getRequiredBooleanParameter(request, "paramEmpty")).isFalse(); } @Test @@ -263,16 +245,16 @@ public class ServletRequestUtilsTests { boolean[] array = new boolean[] {true, true, false, true, false}; boolean[] values = ServletRequestUtils.getRequiredBooleanParameters(request, "param"); - assertEquals(array.length, values.length); + assertThat(array.length).isEqualTo(values.length); for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i]); + assertThat(array[i]).isEqualTo(values[i]); } array = new boolean[] {false, true, false}; values = ServletRequestUtils.getRequiredBooleanParameters(request, "param2"); - assertEquals(array.length, values.length); + assertThat(array.length).isEqualTo(values.length); for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i]); + assertThat(array[i]).isEqualTo(values[i]); } } @@ -282,18 +264,18 @@ public class ServletRequestUtilsTests { request.addParameter("param1", "str"); request.addParameter("paramEmpty", ""); - assertEquals("str", ServletRequestUtils.getStringParameter(request, "param1")); - assertEquals("str", ServletRequestUtils.getStringParameter(request, "param1", "string")); - assertEquals("str", ServletRequestUtils.getRequiredStringParameter(request, "param1")); + assertThat(ServletRequestUtils.getStringParameter(request, "param1")).isEqualTo("str"); + assertThat(ServletRequestUtils.getStringParameter(request, "param1", "string")).isEqualTo("str"); + assertThat(ServletRequestUtils.getRequiredStringParameter(request, "param1")).isEqualTo("str"); - assertEquals(null, ServletRequestUtils.getStringParameter(request, "param3")); - assertEquals("string", ServletRequestUtils.getStringParameter(request, "param3", "string")); - assertNull(ServletRequestUtils.getStringParameter(request, "param3", null)); + assertThat(ServletRequestUtils.getStringParameter(request, "param3")).isNull(); + assertThat(ServletRequestUtils.getStringParameter(request, "param3", "string")).isEqualTo("string"); + assertThat(ServletRequestUtils.getStringParameter(request, "param3", null)).isNull(); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredStringParameter(request, "param3")); - assertEquals("", ServletRequestUtils.getStringParameter(request, "paramEmpty")); - assertEquals("", ServletRequestUtils.getRequiredStringParameter(request, "paramEmpty")); + assertThat(ServletRequestUtils.getStringParameter(request, "paramEmpty")).isEmpty(); + assertThat(ServletRequestUtils.getRequiredStringParameter(request, "paramEmpty")).isEmpty(); } @Test @@ -307,7 +289,7 @@ public class ServletRequestUtilsTests { } sw.stop(); System.out.println(sw.getTotalTimeMillis()); - assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250); + assertThat(sw.getTotalTimeMillis() < 250).as("getStringParameter took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -321,7 +303,7 @@ public class ServletRequestUtilsTests { } sw.stop(); System.out.println(sw.getTotalTimeMillis()); - assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250); + assertThat(sw.getTotalTimeMillis() < 250).as("getStringParameter took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -335,7 +317,7 @@ public class ServletRequestUtilsTests { } sw.stop(); System.out.println(sw.getTotalTimeMillis()); - assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250); + assertThat(sw.getTotalTimeMillis() < 250).as("getStringParameter took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -349,7 +331,7 @@ public class ServletRequestUtilsTests { } sw.stop(); System.out.println(sw.getTotalTimeMillis()); - assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250); + assertThat(sw.getTotalTimeMillis() < 250).as("getStringParameter took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -363,7 +345,7 @@ public class ServletRequestUtilsTests { } sw.stop(); System.out.println(sw.getTotalTimeMillis()); - assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250); + assertThat(sw.getTotalTimeMillis() < 250).as("getStringParameter took too long: " + sw.getTotalTimeMillis()).isTrue(); } @Test @@ -377,7 +359,7 @@ public class ServletRequestUtilsTests { } sw.stop(); System.out.println(sw.getTotalTimeMillis()); - assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250); + assertThat(sw.getTotalTimeMillis() < 250).as("getStringParameter took too long: " + sw.getTotalTimeMillis()).isTrue(); } } diff --git a/spring-web/src/test/java/org/springframework/web/bind/support/WebExchangeDataBinderTests.java b/spring-web/src/test/java/org/springframework/web/bind/support/WebExchangeDataBinderTests.java index 7b7bb4ec036..f5896e9d88f 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/support/WebExchangeDataBinderTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/support/WebExchangeDataBinderTests.java @@ -41,11 +41,7 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.ResolvableType.forClass; import static org.springframework.core.ResolvableType.forClassWithGenerics; @@ -76,8 +72,8 @@ public class WebExchangeDataBinderTests { formData.add("spouse.name", "test"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertNotNull(this.testBean.getSpouse()); - assertEquals("test", testBean.getSpouse().getName()); + assertThat(this.testBean.getSpouse()).isNotNull(); + assertThat(testBean.getSpouse().getName()).isEqualTo("test"); } @Test @@ -86,11 +82,11 @@ public class WebExchangeDataBinderTests { formData.add("_postProcessed", "visible"); formData.add("postProcessed", "on"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertTrue(this.testBean.isPostProcessed()); + assertThat(this.testBean.isPostProcessed()).isTrue(); formData.remove("postProcessed"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertFalse(this.testBean.isPostProcessed()); + assertThat(this.testBean.isPostProcessed()).isFalse(); } @Test @@ -101,11 +97,11 @@ public class WebExchangeDataBinderTests { formData.add("_postProcessed", "visible"); formData.add("postProcessed", "on"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertTrue(this.testBean.isPostProcessed()); + assertThat(this.testBean.isPostProcessed()).isTrue(); formData.remove("postProcessed"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertFalse(this.testBean.isPostProcessed()); + assertThat(this.testBean.isPostProcessed()).isFalse(); } @Test @@ -114,11 +110,11 @@ public class WebExchangeDataBinderTests { formData.add("!postProcessed", "off"); formData.add("postProcessed", "on"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertTrue(this.testBean.isPostProcessed()); + assertThat(this.testBean.isPostProcessed()).isTrue(); formData.remove("postProcessed"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertFalse(this.testBean.isPostProcessed()); + assertThat(this.testBean.isPostProcessed()).isFalse(); } @Test @@ -128,15 +124,15 @@ public class WebExchangeDataBinderTests { formData.add("_postProcessed", "visible"); formData.add("postProcessed", "on"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertTrue(this.testBean.isPostProcessed()); + assertThat(this.testBean.isPostProcessed()).isTrue(); formData.remove("postProcessed"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertTrue(this.testBean.isPostProcessed()); + assertThat(this.testBean.isPostProcessed()).isTrue(); formData.remove("!postProcessed"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertFalse(this.testBean.isPostProcessed()); + assertThat(this.testBean.isPostProcessed()).isFalse(); } @Test @@ -145,11 +141,11 @@ public class WebExchangeDataBinderTests { formData.add("!name", "anonymous"); formData.add("name", "Scott"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertEquals("Scott", this.testBean.getName()); + assertThat(this.testBean.getName()).isEqualTo("Scott"); formData.remove("name"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertEquals("anonymous", this.testBean.getName()); + assertThat(this.testBean.getName()).isEqualTo("anonymous"); } @Test @@ -159,12 +155,12 @@ public class WebExchangeDataBinderTests { formData.add("stringArray", "abc"); formData.add("stringArray", "123,def"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertEquals("Expected all three items to be bound", 3, this.testBean.getStringArray().length); + assertThat(this.testBean.getStringArray().length).as("Expected all three items to be bound").isEqualTo(3); formData.remove("stringArray"); formData.add("stringArray", "123,def"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertEquals("Expected only 1 item to be bound", 1, this.testBean.getStringArray().length); + assertThat(this.testBean.getStringArray().length).as("Expected only 1 item to be bound").isEqualTo(1); } @Test @@ -174,8 +170,8 @@ public class WebExchangeDataBinderTests { formData.add("spouse", "someValue"); this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000)); - assertNotNull(this.testBean.getSpouse()); - assertEquals("test", this.testBean.getSpouse().getName()); + assertThat(this.testBean.getSpouse()).isNotNull(); + assertThat(this.testBean.getSpouse().getName()).isEqualTo("test"); } @Test @@ -184,8 +180,8 @@ public class WebExchangeDataBinderTests { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post(url)); this.binder.bind(exchange).block(Duration.ofSeconds(5)); - assertNotNull(this.testBean.getSpouse()); - assertEquals("test", this.testBean.getSpouse().getName()); + assertThat(this.testBean.getSpouse()).isNotNull(); + assertThat(this.testBean.getSpouse().getName()).isEqualTo("test"); } @Test @@ -205,13 +201,13 @@ public class WebExchangeDataBinderTests { data.add("somePartList", new ClassPathResource("org/springframework/http/server/reactive/spring.png")); binder.bind(exchangeMultipart(data)).block(Duration.ofMillis(5000)); - assertEquals("bar", bean.getName()); - assertEquals(Arrays.asList("123", "abc"), bean.getSomeList()); - assertArrayEquals(new String[] {"dec", "456"}, bean.getSomeArray()); - assertEquals("foo.txt", bean.getPart().filename()); - assertEquals(2, bean.getSomePartList().size()); - assertEquals("foo.txt", bean.getSomePartList().get(0).filename()); - assertEquals("spring.png", bean.getSomePartList().get(1).filename()); + assertThat(bean.getName()).isEqualTo("bar"); + assertThat(bean.getSomeList()).isEqualTo(Arrays.asList("123", "abc")); + assertThat(bean.getSomeArray()).isEqualTo(new String[] {"dec", "456"}); + assertThat(bean.getPart().filename()).isEqualTo("foo.txt"); + assertThat(bean.getSomePartList().size()).isEqualTo(2); + assertThat(bean.getSomePartList().get(0).filename()).isEqualTo("foo.txt"); + assertThat(bean.getSomePartList().get(1).filename()).isEqualTo("spring.png"); } diff --git a/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderIntegrationTests.java b/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderIntegrationTests.java index 4563c335be6..b4978d830fa 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderIntegrationTests.java @@ -41,8 +41,7 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import org.springframework.web.context.request.ServletWebRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Brian Clozel @@ -108,8 +107,8 @@ public class WebRequestDataBinderIntegrationTests { template.postForLocation(baseUrl + "/parts", parts); - assertNotNull(bean.getFirstPart()); - assertNotNull(bean.getSecondPart()); + assertThat(bean.getFirstPart()).isNotNull(); + assertThat(bean.getSecondPart()).isNotNull(); } @Test @@ -125,8 +124,8 @@ public class WebRequestDataBinderIntegrationTests { template.postForLocation(baseUrl + "/partlist", parts); - assertNotNull(bean.getPartList()); - assertEquals(parts.get("partList").size(), bean.getPartList().size()); + assertThat(bean.getPartList()).isNotNull(); + assertThat(bean.getPartList().size()).isEqualTo(parts.get("partList").size()); } diff --git a/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderTests.java b/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderTests.java index cc20b1f0b65..6810255e5ae 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderTests.java @@ -37,10 +37,6 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.multipart.support.StringMultipartFileEditor; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * @author Juergen Hoeller @@ -64,8 +60,8 @@ public class WebRequestDataBinderTests { request.addParameter("spouse.name", "test"); binder.bind(new ServletWebRequest(request)); - assertNotNull(tb.getSpouse()); - assertEquals("test", tb.getSpouse().getName()); + assertThat(tb.getSpouse()).isNotNull(); + assertThat(tb.getSpouse().getName()).isEqualTo("test"); } @Test @@ -79,8 +75,8 @@ public class WebRequestDataBinderTests { request.addParameter("concreteSpouse.name", "test"); binder.bind(new ServletWebRequest(request)); - assertNotNull(tb.getSpouse()); - assertEquals("test", tb.getSpouse().getName()); + assertThat(tb.getSpouse()).isNotNull(); + assertThat(tb.getSpouse().getName()).isEqualTo("test"); } @Test @@ -92,11 +88,11 @@ public class WebRequestDataBinderTests { request.addParameter("_postProcessed", "visible"); request.addParameter("postProcessed", "on"); binder.bind(new ServletWebRequest(request)); - assertTrue(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isTrue(); request.removeParameter("postProcessed"); binder.bind(new ServletWebRequest(request)); - assertFalse(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isFalse(); } @Test @@ -109,11 +105,11 @@ public class WebRequestDataBinderTests { request.addParameter("_postProcessed", "visible"); request.addParameter("postProcessed", "on"); binder.bind(new ServletWebRequest(request)); - assertTrue(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isTrue(); request.removeParameter("postProcessed"); binder.bind(new ServletWebRequest(request)); - assertFalse(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isFalse(); } @Test @@ -125,11 +121,11 @@ public class WebRequestDataBinderTests { request.addParameter("!postProcessed", "off"); request.addParameter("postProcessed", "on"); binder.bind(new ServletWebRequest(request)); - assertTrue(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isTrue(); request.removeParameter("postProcessed"); binder.bind(new ServletWebRequest(request)); - assertFalse(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isFalse(); } // SPR-13502 @@ -162,15 +158,15 @@ public class WebRequestDataBinderTests { request.addParameter("_postProcessed", "visible"); request.addParameter("postProcessed", "on"); binder.bind(new ServletWebRequest(request)); - assertTrue(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isTrue(); request.removeParameter("postProcessed"); binder.bind(new ServletWebRequest(request)); - assertTrue(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isTrue(); request.removeParameter("!postProcessed"); binder.bind(new ServletWebRequest(request)); - assertFalse(target.isPostProcessed()); + assertThat(target.isPostProcessed()).isFalse(); } @Test @@ -184,15 +180,15 @@ public class WebRequestDataBinderTests { request.addParameter("_spouse.postProcessed", "visible"); request.addParameter("spouse.postProcessed", "on"); binder.bind(new ServletWebRequest(request)); - assertTrue(((TestBean) target.getSpouse()).isPostProcessed()); + assertThat(((TestBean) target.getSpouse()).isPostProcessed()).isTrue(); request.removeParameter("spouse.postProcessed"); binder.bind(new ServletWebRequest(request)); - assertTrue(((TestBean) target.getSpouse()).isPostProcessed()); + assertThat(((TestBean) target.getSpouse()).isPostProcessed()).isTrue(); request.removeParameter("!spouse.postProcessed"); binder.bind(new ServletWebRequest(request)); - assertFalse(((TestBean) target.getSpouse()).isPostProcessed()); + assertThat(((TestBean) target.getSpouse()).isPostProcessed()).isFalse(); } @Test @@ -204,11 +200,11 @@ public class WebRequestDataBinderTests { request.addParameter("!name", "anonymous"); request.addParameter("name", "Scott"); binder.bind(new ServletWebRequest(request)); - assertEquals("Scott", target.getName()); + assertThat(target.getName()).isEqualTo("Scott"); request.removeParameter("name"); binder.bind(new ServletWebRequest(request)); - assertEquals("anonymous", target.getName()); + assertThat(target.getName()).isEqualTo("anonymous"); } @Test @@ -221,12 +217,12 @@ public class WebRequestDataBinderTests { request.addParameter("stringArray", "abc"); request.addParameter("stringArray", "123,def"); binder.bind(new ServletWebRequest(request)); - assertEquals("Expected all three items to be bound", 3, target.getStringArray().length); + assertThat(target.getStringArray().length).as("Expected all three items to be bound").isEqualTo(3); request.removeParameter("stringArray"); request.addParameter("stringArray", "123,def"); binder.bind(new ServletWebRequest(request)); - assertEquals("Expected only 1 item to be bound", 1, target.getStringArray().length); + assertThat(target.getStringArray().length).as("Expected only 1 item to be bound").isEqualTo(1); } @Test @@ -237,7 +233,7 @@ public class WebRequestDataBinderTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("myEnum", "FOO"); binder.bind(new ServletWebRequest(request)); - assertEquals(MyEnum.FOO, target.getMyEnum()); + assertThat(target.getMyEnum()).isEqualTo(MyEnum.FOO); } @Test @@ -249,7 +245,7 @@ public class WebRequestDataBinderTests { MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); request.addFile(new MockMultipartFile("name", "Juergen".getBytes())); binder.bind(new ServletWebRequest(request)); - assertEquals("Juergen", target.getName()); + assertThat(target.getName()).isEqualTo("Juergen"); } @Test @@ -261,8 +257,8 @@ public class WebRequestDataBinderTests { MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); request.addFile(new MockMultipartFile("stringArray", "Juergen".getBytes())); binder.bind(new ServletWebRequest(request)); - assertEquals(1, target.getStringArray().length); - assertEquals("Juergen", target.getStringArray()[0]); + assertThat(target.getStringArray().length).isEqualTo(1); + assertThat(target.getStringArray()[0]).isEqualTo("Juergen"); } @Test @@ -275,9 +271,9 @@ public class WebRequestDataBinderTests { request.addFile(new MockMultipartFile("stringArray", "Juergen".getBytes())); request.addFile(new MockMultipartFile("stringArray", "Eva".getBytes())); binder.bind(new ServletWebRequest(request)); - assertEquals(2, target.getStringArray().length); - assertEquals("Juergen", target.getStringArray()[0]); - assertEquals("Eva", target.getStringArray()[1]); + assertThat(target.getStringArray().length).isEqualTo(2); + assertThat(target.getStringArray()[0]).isEqualTo("Juergen"); + assertThat(target.getStringArray()[1]).isEqualTo("Eva"); } @Test @@ -299,8 +295,9 @@ public class WebRequestDataBinderTests { request.addParameter("test_age", "" + 50); ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request); - assertTrue("Didn't find normal when given prefix", !pvs.contains("forname")); - assertTrue("Did treat prefix as normal when not given prefix", pvs.contains("test_forname")); + boolean condition = !pvs.contains("forname"); + assertThat(condition).as("Didn't find normal when given prefix").isTrue(); + assertThat(pvs.contains("test_forname")).as("Did treat prefix as normal when not given prefix").isTrue(); pvs = new ServletRequestParameterPropertyValues(request, "test"); doTestTony(pvs); @@ -310,11 +307,12 @@ public class WebRequestDataBinderTests { * Must contain: forname=Tony surname=Blair age=50 */ protected void doTestTony(PropertyValues pvs) throws Exception { - assertTrue("Contains 3", pvs.getPropertyValues().length == 3); - assertTrue("Contains forname", pvs.contains("forname")); - assertTrue("Contains surname", pvs.contains("surname")); - assertTrue("Contains age", pvs.contains("age")); - assertTrue("Doesn't contain tory", !pvs.contains("tory")); + assertThat(pvs.getPropertyValues().length == 3).as("Contains 3").isTrue(); + assertThat(pvs.contains("forname")).as("Contains forname").isTrue(); + assertThat(pvs.contains("surname")).as("Contains surname").isTrue(); + assertThat(pvs.contains("age")).as("Contains age").isTrue(); + boolean condition1 = !pvs.contains("tory"); + assertThat(condition1).as("Doesn't contain tory").isTrue(); PropertyValue[] pvArray = pvs.getPropertyValues(); Map m = new HashMap<>(); @@ -323,19 +321,20 @@ public class WebRequestDataBinderTests { m.put("age", "50"); for (PropertyValue pv : pvArray) { Object val = m.get(pv.getName()); - assertTrue("Can't have unexpected value", val != null); - assertTrue("Val i string", val instanceof String); - assertTrue("val matches expected", val.equals(pv.getValue())); + assertThat(val != null).as("Can't have unexpected value").isTrue(); + boolean condition = val instanceof String; + assertThat(condition).as("Val i string").isTrue(); + assertThat(val.equals(pv.getValue())).as("val matches expected").isTrue(); m.remove(pv.getName()); } - assertTrue("Map size is 0", m.size() == 0); + assertThat(m.size() == 0).as("Map size is 0").isTrue(); } @Test public void testNoParameters() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request); - assertTrue("Found no parameters", pvs.getPropertyValues().length == 0); + assertThat(pvs.getPropertyValues().length == 0).as("Found no parameters").isTrue(); } @Test @@ -345,10 +344,11 @@ public class WebRequestDataBinderTests { request.addParameter("forname", original); ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request); - assertTrue("Found 1 parameter", pvs.getPropertyValues().length == 1); - assertTrue("Found array value", pvs.getPropertyValue("forname").getValue() instanceof String[]); + assertThat(pvs.getPropertyValues().length == 1).as("Found 1 parameter").isTrue(); + boolean condition = pvs.getPropertyValue("forname").getValue() instanceof String[]; + assertThat(condition).as("Found array value").isTrue(); String[] values = (String[]) pvs.getPropertyValue("forname").getValue(); - assertEquals("Correct values", Arrays.asList(values), Arrays.asList(original)); + assertThat(Arrays.asList(original)).as("Correct values").isEqualTo(Arrays.asList(values)); } diff --git a/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTestCase.java b/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTestCase.java index b22129ed37f..7b3f6e89877 100644 --- a/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTestCase.java +++ b/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTestCase.java @@ -32,9 +32,6 @@ import org.junit.Before; import org.springframework.http.MediaType; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; /** * @author Brian Clozel @@ -87,17 +84,16 @@ public class AbstractMockWebServerTestCase { private MockResponse postRequest(RecordedRequest request, String expectedRequestContent, String location, String contentType, byte[] responseBody) { - assertEquals(1, request.getHeaders().values("Content-Length").size()); - assertTrue("Invalid request content-length", - Integer.parseInt(request.getHeader("Content-Length")) > 0); + assertThat(request.getHeaders().values("Content-Length").size()).isEqualTo(1); + assertThat(Integer.parseInt(request.getHeader("Content-Length")) > 0).as("Invalid request content-length").isTrue(); String requestContentType = request.getHeader("Content-Type"); - assertNotNull("No content-type", requestContentType); + assertThat(requestContentType).as("No content-type").isNotNull(); Charset charset = StandardCharsets.ISO_8859_1; if (requestContentType.contains("charset=")) { String charsetName = requestContentType.split("charset=")[1]; charset = Charset.forName(charsetName); } - assertEquals("Invalid request body", expectedRequestContent, request.getBody().readString(charset)); + assertThat(request.getBody().readString(charset)).as("Invalid request body").isEqualTo(expectedRequestContent); Buffer buf = new Buffer(); buf.write(responseBody); return new MockResponse() @@ -110,9 +106,8 @@ public class AbstractMockWebServerTestCase { private MockResponse jsonPostRequest(RecordedRequest request, String location, String contentType) { if (request.getBodySize() > 0) { - assertTrue("Invalid request content-length", - Integer.parseInt(request.getHeader("Content-Length")) > 0); - assertNotNull("No content-type", request.getHeader("Content-Type")); + assertThat(Integer.parseInt(request.getHeader("Content-Length")) > 0).as("Invalid request content-length").isTrue(); + assertThat(request.getHeader("Content-Type")).as("No content-type").isNotNull(); } return new MockResponse() .setHeader("Location", baseUrl + location) @@ -124,7 +119,7 @@ public class AbstractMockWebServerTestCase { private MockResponse multipartRequest(RecordedRequest request) { MediaType mediaType = MediaType.parseMediaType(request.getHeader("Content-Type")); - assertTrue(mediaType.isCompatibleWith(MediaType.MULTIPART_FORM_DATA)); + assertThat(mediaType.isCompatibleWith(MediaType.MULTIPART_FORM_DATA)).isTrue(); String boundary = mediaType.getParameter("boundary"); Buffer body = request.getBody(); try { @@ -142,32 +137,32 @@ public class AbstractMockWebServerTestCase { private void assertPart(Buffer buffer, String disposition, String boundary, String name, String contentType, String value) throws EOFException { - assertTrue(buffer.readUtf8Line().contains("--" + boundary)); + assertThat(buffer.readUtf8Line().contains("--" + boundary)).isTrue(); String line = buffer.readUtf8Line(); - assertTrue(line.contains("Content-Disposition: "+ disposition)); - assertTrue(line.contains("name=\""+ name + "\"")); - assertTrue(buffer.readUtf8Line().startsWith("Content-Type: "+contentType)); - assertTrue(buffer.readUtf8Line().equals("Content-Length: " + value.length())); - assertTrue(buffer.readUtf8Line().equals("")); - assertTrue(buffer.readUtf8Line().equals(value)); + assertThat(line.contains("Content-Disposition: "+ disposition)).isTrue(); + assertThat(line.contains("name=\""+ name + "\"")).isTrue(); + assertThat(buffer.readUtf8Line().startsWith("Content-Type: "+contentType)).isTrue(); + assertThat(buffer.readUtf8Line().equals("Content-Length: " + value.length())).isTrue(); + assertThat(buffer.readUtf8Line().equals("")).isTrue(); + assertThat(buffer.readUtf8Line().equals(value)).isTrue(); } private void assertFilePart(Buffer buffer, String disposition, String boundary, String name, String filename, String contentType) throws EOFException { - assertTrue(buffer.readUtf8Line().contains("--" + boundary)); + assertThat(buffer.readUtf8Line().contains("--" + boundary)).isTrue(); String line = buffer.readUtf8Line(); - assertTrue(line.contains("Content-Disposition: "+ disposition)); - assertTrue(line.contains("name=\""+ name + "\"")); - assertTrue(line.contains("filename=\""+ filename + "\"")); - assertTrue(buffer.readUtf8Line().startsWith("Content-Type: "+contentType)); - assertTrue(buffer.readUtf8Line().startsWith("Content-Length: ")); - assertTrue(buffer.readUtf8Line().equals("")); - assertNotNull(buffer.readUtf8Line()); + assertThat(line.contains("Content-Disposition: "+ disposition)).isTrue(); + assertThat(line.contains("name=\""+ name + "\"")).isTrue(); + assertThat(line.contains("filename=\""+ filename + "\"")).isTrue(); + assertThat(buffer.readUtf8Line().startsWith("Content-Type: "+contentType)).isTrue(); + assertThat(buffer.readUtf8Line().startsWith("Content-Length: ")).isTrue(); + assertThat(buffer.readUtf8Line().equals("")).isTrue(); + assertThat(buffer.readUtf8Line()).isNotNull(); } private MockResponse formRequest(RecordedRequest request) { - assertEquals("application/x-www-form-urlencoded;charset=UTF-8", request.getHeader("Content-Type")); + assertThat(request.getHeader("Content-Type")).isEqualTo("application/x-www-form-urlencoded;charset=UTF-8"); String body = request.getBody().readUtf8(); assertThat(body).contains("name+1=value+1"); assertThat(body).contains("name+2=value+2%2B1"); @@ -178,17 +173,16 @@ public class AbstractMockWebServerTestCase { private MockResponse patchRequest(RecordedRequest request, String expectedRequestContent, String contentType, byte[] responseBody) { - assertEquals("PATCH", request.getMethod()); - assertTrue("Invalid request content-length", - Integer.parseInt(request.getHeader("Content-Length")) > 0); + assertThat(request.getMethod()).isEqualTo("PATCH"); + assertThat(Integer.parseInt(request.getHeader("Content-Length")) > 0).as("Invalid request content-length").isTrue(); String requestContentType = request.getHeader("Content-Type"); - assertNotNull("No content-type", requestContentType); + assertThat(requestContentType).as("No content-type").isNotNull(); Charset charset = StandardCharsets.ISO_8859_1; if (requestContentType.contains("charset=")) { String charsetName = requestContentType.split("charset=")[1]; charset = Charset.forName(charsetName); } - assertEquals("Invalid request body", expectedRequestContent, request.getBody().readString(charset)); + assertThat(request.getBody().readString(charset)).as("Invalid request body").isEqualTo(expectedRequestContent); Buffer buf = new Buffer(); buf.write(responseBody); return new MockResponse().setResponseCode(201) @@ -198,16 +192,15 @@ public class AbstractMockWebServerTestCase { } private MockResponse putRequest(RecordedRequest request, String expectedRequestContent) { - assertTrue("Invalid request content-length", - Integer.parseInt(request.getHeader("Content-Length")) > 0); + assertThat(Integer.parseInt(request.getHeader("Content-Length")) > 0).as("Invalid request content-length").isTrue(); String requestContentType = request.getHeader("Content-Type"); - assertNotNull("No content-type", requestContentType); + assertThat(requestContentType).as("No content-type").isNotNull(); Charset charset = StandardCharsets.ISO_8859_1; if (requestContentType.contains("charset=")) { String charsetName = requestContentType.split("charset=")[1]; charset = Charset.forName(charsetName); } - assertEquals("Invalid request body", expectedRequestContent, request.getBody().readString(charset)); + assertThat(request.getBody().readString(charset)).as("Invalid request body").isEqualTo(expectedRequestContent); return new MockResponse().setResponseCode(202); } diff --git a/spring-web/src/test/java/org/springframework/web/client/AsyncRestTemplateIntegrationTests.java b/spring-web/src/test/java/org/springframework/web/client/AsyncRestTemplateIntegrationTests.java index fa548af6d2a..b13e7be0153 100644 --- a/spring-web/src/test/java/org/springframework/web/client/AsyncRestTemplateIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/AsyncRestTemplateIntegrationTests.java @@ -44,15 +44,9 @@ import org.springframework.util.MultiValueMap; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; /** * @author Arjen Poutsma @@ -69,20 +63,20 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest public void getEntity() throws Exception { Future> future = template.getForEntity(baseUrl + "/{method}", String.class, "get"); ResponseEntity entity = future.get(); - assertEquals("Invalid content", helloWorld, entity.getBody()); - assertFalse("No headers", entity.getHeaders().isEmpty()); - assertEquals("Invalid content-type", textContentType, entity.getHeaders().getContentType()); - assertEquals("Invalid status code", HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getBody()).as("Invalid content").isEqualTo(helloWorld); + assertThat(entity.getHeaders().isEmpty()).as("No headers").isFalse(); + assertThat(entity.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(textContentType); + assertThat(entity.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); } @Test public void getEntityFromCompletable() throws Exception { ListenableFuture> future = template.getForEntity(baseUrl + "/{method}", String.class, "get"); ResponseEntity entity = future.completable().get(); - assertEquals("Invalid content", helloWorld, entity.getBody()); - assertFalse("No headers", entity.getHeaders().isEmpty()); - assertEquals("Invalid content-type", textContentType, entity.getHeaders().getContentType()); - assertEquals("Invalid status code", HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getBody()).as("Invalid content").isEqualTo(helloWorld); + assertThat(entity.getHeaders().isEmpty()).as("No headers").isFalse(); + assertThat(entity.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(textContentType); + assertThat(entity.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); } @Test @@ -99,10 +93,10 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest futureEntity.addCallback(new ListenableFutureCallback>() { @Override public void onSuccess(ResponseEntity entity) { - assertEquals("Invalid content", helloWorld, entity.getBody()); - assertFalse("No headers", entity.getHeaders().isEmpty()); - assertEquals("Invalid content-type", textContentType, entity.getHeaders().getContentType()); - assertEquals("Invalid status code", HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getBody()).as("Invalid content").isEqualTo(helloWorld); + assertThat(entity.getHeaders().isEmpty()).as("No headers").isFalse(); + assertThat(entity.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(textContentType); + assertThat(entity.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); } @Override public void onFailure(Throwable ex) { @@ -117,10 +111,10 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest ListenableFuture> futureEntity = template.getForEntity(baseUrl + "/{method}", String.class, "get"); futureEntity.addCallback(entity -> { - assertEquals("Invalid content", helloWorld, entity.getBody()); - assertFalse("No headers", entity.getHeaders().isEmpty()); - assertEquals("Invalid content-type", textContentType, entity.getHeaders().getContentType()); - assertEquals("Invalid status code", HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getBody()).as("Invalid content").isEqualTo(helloWorld); + assertThat(entity.getHeaders().isEmpty()).as("No headers").isFalse(); + assertThat(entity.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(textContentType); + assertThat(entity.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); }, ex -> fail(ex.getMessage())); waitTillDone(futureEntity); } @@ -129,37 +123,37 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest public void getNoResponse() throws Exception { Future> futureEntity = template.getForEntity(baseUrl + "/get/nothing", String.class); ResponseEntity entity = futureEntity.get(); - assertNull("Invalid content", entity.getBody()); + assertThat(entity.getBody()).as("Invalid content").isNull(); } @Test public void getNoContentTypeHeader() throws Exception { Future> futureEntity = template.getForEntity(baseUrl + "/get/nocontenttype", byte[].class); ResponseEntity responseEntity = futureEntity.get(); - assertArrayEquals("Invalid content", helloWorld.getBytes("UTF-8"), responseEntity.getBody()); + assertThat(responseEntity.getBody()).as("Invalid content").isEqualTo(helloWorld.getBytes("UTF-8")); } @Test public void getNoContent() throws Exception { Future> responseFuture = template.getForEntity(baseUrl + "/status/nocontent", String.class); ResponseEntity entity = responseFuture.get(); - assertEquals("Invalid response code", HttpStatus.NO_CONTENT, entity.getStatusCode()); - assertNull("Invalid content", entity.getBody()); + assertThat(entity.getStatusCode()).as("Invalid response code").isEqualTo(HttpStatus.NO_CONTENT); + assertThat(entity.getBody()).as("Invalid content").isNull(); } @Test public void getNotModified() throws Exception { Future> responseFuture = template.getForEntity(baseUrl + "/status/notmodified", String.class); ResponseEntity entity = responseFuture.get(); - assertEquals("Invalid response code", HttpStatus.NOT_MODIFIED, entity.getStatusCode()); - assertNull("Invalid content", entity.getBody()); + assertThat(entity.getStatusCode()).as("Invalid response code").isEqualTo(HttpStatus.NOT_MODIFIED); + assertThat(entity.getBody()).as("Invalid content").isNull(); } @Test public void headForHeaders() throws Exception { Future headersFuture = template.headForHeaders(baseUrl + "/get"); HttpHeaders headers = headersFuture.get(); - assertTrue("No Content-Type header", headers.containsKey("Content-Type")); + assertThat(headers.containsKey("Content-Type")).as("No Content-Type header").isTrue(); } @Test @@ -168,7 +162,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest headersFuture.addCallback(new ListenableFutureCallback() { @Override public void onSuccess(HttpHeaders result) { - assertTrue("No Content-Type header", result.containsKey("Content-Type")); + assertThat(result.containsKey("Content-Type")).as("No Content-Type header").isTrue(); } @Override public void onFailure(Throwable ex) { @@ -181,8 +175,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest @Test public void headForHeadersCallbackWithLambdas() throws Exception { ListenableFuture headersFuture = template.headForHeaders(baseUrl + "/get"); - headersFuture.addCallback(result -> assertTrue("No Content-Type header", - result.containsKey("Content-Type")), ex -> fail(ex.getMessage())); + headersFuture.addCallback(result -> assertThat(result.containsKey("Content-Type")).as("No Content-Type header").isTrue(), ex -> fail(ex.getMessage())); waitTillDone(headersFuture); } @@ -193,7 +186,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest HttpEntity entity = new HttpEntity<>(helloWorld, entityHeaders); Future locationFuture = template.postForLocation(baseUrl + "/{method}", entity, "post"); URI location = locationFuture.get(); - assertEquals("Invalid location", new URI(baseUrl + "/post/1"), location); + assertThat(location).as("Invalid location").isEqualTo(new URI(baseUrl + "/post/1")); } @Test @@ -206,7 +199,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest locationFuture.addCallback(new ListenableFutureCallback() { @Override public void onSuccess(URI result) { - assertEquals("Invalid location", expected, result); + assertThat(result).as("Invalid location").isEqualTo(expected); } @Override public void onFailure(Throwable ex) { @@ -223,7 +216,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest HttpEntity entity = new HttpEntity<>(helloWorld, entityHeaders); final URI expected = new URI(baseUrl + "/post/1"); ListenableFuture locationFuture = template.postForLocation(baseUrl + "/{method}", entity, "post"); - locationFuture.addCallback(result -> assertEquals("Invalid location", expected, result), + locationFuture.addCallback(result -> assertThat(result).as("Invalid location").isEqualTo(expected), ex -> fail(ex.getMessage())); waitTillDone(locationFuture); } @@ -234,7 +227,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest Future> responseEntityFuture = template.postForEntity(baseUrl + "/{method}", requestEntity, String.class, "post"); ResponseEntity responseEntity = responseEntityFuture.get(); - assertEquals("Invalid content", helloWorld, responseEntity.getBody()); + assertThat(responseEntity.getBody()).as("Invalid content").isEqualTo(helloWorld); } @Test @@ -245,7 +238,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest responseEntityFuture.addCallback(new ListenableFutureCallback>() { @Override public void onSuccess(ResponseEntity result) { - assertEquals("Invalid content", helloWorld, result.getBody()); + assertThat(result.getBody()).as("Invalid content").isEqualTo(helloWorld); } @Override public void onFailure(Throwable ex) { @@ -261,7 +254,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest ListenableFuture> responseEntityFuture = template.postForEntity(baseUrl + "/{method}", requestEntity, String.class, "post"); responseEntityFuture.addCallback( - result -> assertEquals("Invalid content", helloWorld, result.getBody()), + result -> assertThat(result.getBody()).as("Invalid content").isEqualTo(helloWorld), ex -> fail(ex.getMessage())); waitTillDone(responseEntityFuture); } @@ -280,7 +273,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest responseEntityFuture.addCallback(new ListenableFutureCallback() { @Override public void onSuccess(Object result) { - assertNull(result); + assertThat(result).isNull(); } @Override public void onFailure(Throwable ex) { @@ -302,7 +295,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest deletedFuture.addCallback(new ListenableFutureCallback() { @Override public void onSuccess(Object result) { - assertNull(result); + assertThat(result).isNull(); } @Override public void onFailure(Throwable ex) { @@ -315,7 +308,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest @Test public void deleteCallbackWithLambdas() throws Exception { ListenableFuture deletedFuture = template.delete(new URI(baseUrl + "/delete")); - deletedFuture.addCallback(result -> assertNull(result), ex -> fail(ex.getMessage())); + deletedFuture.addCallback(result -> assertThat(result).isNull(), ex -> fail(ex.getMessage())); waitTillDone(deletedFuture); } @@ -332,7 +325,8 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest } @Override public void onFailure(Throwable ex) { - assertTrue(ex instanceof HttpClientErrorException); + boolean condition = ex instanceof HttpClientErrorException; + assertThat(condition).isTrue(); callbackException[0] = (HttpClientErrorException) ex; latch.countDown(); } @@ -344,9 +338,10 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest } catch (ExecutionException ex) { Throwable cause = ex.getCause(); - assertTrue(cause instanceof HttpClientErrorException); + boolean condition = cause instanceof HttpClientErrorException; + assertThat(condition).isTrue(); latch.await(5, TimeUnit.SECONDS); - assertSame(callbackException[0], cause); + assertThat(cause).isSameAs(callbackException[0]); } } @@ -359,9 +354,9 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest .withCauseInstanceOf(HttpClientErrorException.class) .satisfies(ex -> { HttpClientErrorException cause = (HttpClientErrorException) ex.getCause(); - assertEquals(HttpStatus.NOT_FOUND, cause.getStatusCode()); - assertNotNull(cause.getStatusText()); - assertNotNull(cause.getResponseBodyAsString()); + assertThat(cause.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(cause.getStatusText()).isNotNull(); + assertThat(cause.getResponseBodyAsString()).isNotNull(); }); } @@ -375,11 +370,12 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest } @Override public void onFailure(Throwable t) { - assertTrue(t instanceof HttpClientErrorException); + boolean condition = t instanceof HttpClientErrorException; + assertThat(condition).isTrue(); HttpClientErrorException ex = (HttpClientErrorException) t; - assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode()); - assertNotNull(ex.getStatusText()); - assertNotNull(ex.getResponseBodyAsString()); + assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(ex.getStatusText()).isNotNull(); + assertThat(ex.getResponseBodyAsString()).isNotNull(); } }); waitTillDone(future); @@ -389,11 +385,12 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest public void notFoundCallbackWithLambdas() throws Exception { ListenableFuture future = template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null); future.addCallback(result -> fail("onSuccess not expected"), ex -> { - assertTrue(ex instanceof HttpClientErrorException); - HttpClientErrorException hcex = (HttpClientErrorException) ex; - assertEquals(HttpStatus.NOT_FOUND, hcex.getStatusCode()); - assertNotNull(hcex.getStatusText()); - assertNotNull(hcex.getResponseBodyAsString()); + boolean condition = ex instanceof HttpClientErrorException; + assertThat(condition).isTrue(); + HttpClientErrorException hcex = (HttpClientErrorException) ex; + assertThat(hcex.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(hcex.getStatusText()).isNotNull(); + assertThat(hcex.getResponseBodyAsString()).isNotNull(); }); waitTillDone(future); } @@ -406,12 +403,13 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest fail("HttpServerErrorException expected"); } catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof HttpServerErrorException); + boolean condition = ex.getCause() instanceof HttpServerErrorException; + assertThat(condition).isTrue(); HttpServerErrorException cause = (HttpServerErrorException)ex.getCause(); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, cause.getStatusCode()); - assertNotNull(cause.getStatusText()); - assertNotNull(cause.getResponseBodyAsString()); + assertThat(cause.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + assertThat(cause.getStatusText()).isNotNull(); + assertThat(cause.getResponseBodyAsString()).isNotNull(); } } @@ -425,11 +423,12 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest } @Override public void onFailure(Throwable ex) { - assertTrue(ex instanceof HttpServerErrorException); + boolean condition = ex instanceof HttpServerErrorException; + assertThat(condition).isTrue(); HttpServerErrorException hsex = (HttpServerErrorException) ex; - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, hsex.getStatusCode()); - assertNotNull(hsex.getStatusText()); - assertNotNull(hsex.getResponseBodyAsString()); + assertThat(hsex.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + assertThat(hsex.getStatusText()).isNotNull(); + assertThat(hsex.getResponseBodyAsString()).isNotNull(); } }); waitTillDone(future); @@ -439,11 +438,12 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest public void serverErrorCallbackWithLambdas() throws Exception { ListenableFuture future = template.execute(baseUrl + "/status/server", HttpMethod.GET, null, null); future.addCallback(result -> fail("onSuccess not expected"), ex -> { - assertTrue(ex instanceof HttpServerErrorException); - HttpServerErrorException hsex = (HttpServerErrorException) ex; - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, hsex.getStatusCode()); - assertNotNull(hsex.getStatusText()); - assertNotNull(hsex.getResponseBodyAsString()); + boolean condition = ex instanceof HttpServerErrorException; + assertThat(condition).isTrue(); + HttpServerErrorException hsex = (HttpServerErrorException) ex; + assertThat(hsex.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + assertThat(hsex.getStatusText()).isNotNull(); + assertThat(hsex.getResponseBodyAsString()).isNotNull(); }); waitTillDone(future); } @@ -452,8 +452,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest public void optionsForAllow() throws Exception { Future> allowedFuture = template.optionsForAllow(new URI(baseUrl + "/get")); Set allowed = allowedFuture.get(); - assertEquals("Invalid response", - EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.HEAD, HttpMethod.TRACE), allowed); + assertThat(allowed).as("Invalid response").isEqualTo(EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.HEAD, HttpMethod.TRACE)); } @Test @@ -462,8 +461,8 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest allowedFuture.addCallback(new ListenableFutureCallback>() { @Override public void onSuccess(Set result) { - assertEquals("Invalid response", EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS, - HttpMethod.HEAD, HttpMethod.TRACE), result); + assertThat(result).as("Invalid response").isEqualTo(EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS, + HttpMethod.HEAD, HttpMethod.TRACE)); } @Override public void onFailure(Throwable ex) { @@ -476,8 +475,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest @Test public void optionsForAllowCallbackWithLambdas() throws Exception{ ListenableFuture> allowedFuture = template.optionsForAllow(new URI(baseUrl + "/get")); - allowedFuture.addCallback(result -> assertEquals("Invalid response", - EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.HEAD,HttpMethod.TRACE), result), + allowedFuture.addCallback(result -> assertThat(result).as("Invalid response").isEqualTo(EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.HEAD,HttpMethod.TRACE)), ex -> fail(ex.getMessage())); waitTillDone(allowedFuture); } @@ -491,7 +489,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest Future> responseFuture = template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get"); ResponseEntity response = responseFuture.get(); - assertEquals("Invalid content", helloWorld, response.getBody()); + assertThat(response.getBody()).as("Invalid content").isEqualTo(helloWorld); } @Test @@ -505,7 +503,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest responseFuture.addCallback(new ListenableFutureCallback>() { @Override public void onSuccess(ResponseEntity result) { - assertEquals("Invalid content", helloWorld, result.getBody()); + assertThat(result.getBody()).as("Invalid content").isEqualTo(helloWorld); } @Override public void onFailure(Throwable ex) { @@ -523,8 +521,7 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest HttpEntity requestEntity = new HttpEntity(requestHeaders); ListenableFuture> responseFuture = template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get"); - responseFuture.addCallback(result -> assertEquals("Invalid content", helloWorld, - result.getBody()), ex -> fail(ex.getMessage())); + responseFuture.addCallback(result -> assertThat(result.getBody()).as("Invalid content").isEqualTo(helloWorld), ex -> fail(ex.getMessage())); waitTillDone(responseFuture); } @@ -537,9 +534,8 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest Future> resultFuture = template.exchange(baseUrl + "/{method}", HttpMethod.POST, requestEntity, Void.class, "post"); ResponseEntity result = resultFuture.get(); - assertEquals("Invalid location", new URI(baseUrl + "/post/1"), - result.getHeaders().getLocation()); - assertFalse(result.hasBody()); + assertThat(result.getHeaders().getLocation()).as("Invalid location").isEqualTo(new URI(baseUrl + "/post/1")); + assertThat(result.hasBody()).isFalse(); } @Test @@ -554,8 +550,8 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest resultFuture.addCallback(new ListenableFutureCallback>() { @Override public void onSuccess(ResponseEntity result) { - assertEquals("Invalid location", expected, result.getHeaders().getLocation()); - assertFalse(result.hasBody()); + assertThat(result.getHeaders().getLocation()).as("Invalid location").isEqualTo(expected); + assertThat(result.hasBody()).isFalse(); } @Override public void onFailure(Throwable ex) { @@ -575,9 +571,9 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest template.exchange(baseUrl + "/{method}", HttpMethod.POST, requestEntity, Void.class, "post"); final URI expected =new URI(baseUrl + "/post/1"); resultFuture.addCallback(result -> { - assertEquals("Invalid location", expected, result.getHeaders().getLocation()); - assertFalse(result.hasBody()); - }, ex -> fail(ex.getMessage())); + assertThat(result.getHeaders().getLocation()).as("Invalid location").isEqualTo(expected); + assertThat(result.hasBody()).isFalse(); + }, ex -> fail(ex.getMessage())); waitTillDone(resultFuture); } @@ -602,10 +598,10 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest ListenableFuture> future = template.getForEntity(baseUrl + "/get", String.class); interceptor.latch.await(5, TimeUnit.SECONDS); - assertNotNull(interceptor.response); - assertEquals(HttpStatus.OK, interceptor.response.getStatusCode()); - assertNull(interceptor.exception); - assertEquals(helloWorld, future.get().getBody()); + assertThat(interceptor.response).isNotNull(); + assertThat(interceptor.response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(interceptor.exception).isNull(); + assertThat(future.get().getBody()).isEqualTo(helloWorld); } @Test @@ -615,9 +611,9 @@ public class AsyncRestTemplateIntegrationTests extends AbstractMockWebServerTest template.getForEntity(baseUrl + "/status/notfound", String.class); interceptor.latch.await(5, TimeUnit.SECONDS); - assertNotNull(interceptor.response); - assertEquals(HttpStatus.NOT_FOUND, interceptor.response.getStatusCode()); - assertNull(interceptor.exception); + assertThat(interceptor.response).isNotNull(); + assertThat(interceptor.response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(interceptor.exception).isNull(); } private void waitTillDone(ListenableFuture future) { diff --git a/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerHttpStatusTests.java b/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerHttpStatusTests.java index ace47e6bea2..076c54ea4a1 100644 --- a/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerHttpStatusTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerHttpStatusTests.java @@ -26,8 +26,8 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpResponse; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.http.HttpStatus.BAD_GATEWAY; @@ -92,7 +92,7 @@ public class DefaultResponseErrorHandlerHttpStatusTests { @Test public void hasErrorTrue() throws Exception { given(this.response.getRawStatusCode()).willReturn(this.httpStatus.value()); - assertTrue(this.handler.hasError(this.response)); + assertThat(this.handler.hasError(this.response)).isTrue(); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java b/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java index d4952e53fc4..8a2abeb95b2 100644 --- a/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java @@ -30,9 +30,6 @@ import org.springframework.util.StreamUtils; import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -53,13 +50,13 @@ public class DefaultResponseErrorHandlerTests { @Test public void hasErrorTrue() throws Exception { given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value()); - assertTrue(handler.hasError(response)); + assertThat(handler.hasError(response)).isTrue(); } @Test public void hasErrorFalse() throws Exception { given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value()); - assertFalse(handler.hasError(response)); + assertThat(handler.hasError(response)).isFalse(); } @Test @@ -113,7 +110,7 @@ public class DefaultResponseErrorHandlerTests { given(response.getStatusText()).willReturn("Custom status code"); given(response.getHeaders()).willReturn(headers); - assertFalse(handler.hasError(response)); + assertThat(handler.hasError(response)).isFalse(); } @Test // SPR-9406 @@ -138,7 +135,7 @@ public class DefaultResponseErrorHandlerTests { given(response.getStatusText()).willReturn("Custom status code"); given(response.getHeaders()).willReturn(headers); - assertTrue(handler.hasError(response)); + assertThat(handler.hasError(response)).isTrue(); } @Test @@ -163,7 +160,7 @@ public class DefaultResponseErrorHandlerTests { given(response.getStatusText()).willReturn("Custom status code"); given(response.getHeaders()).willReturn(headers); - assertTrue(handler.hasError(response)); + assertThat(handler.hasError(response)).isTrue(); } @Test @@ -190,9 +187,9 @@ public class DefaultResponseErrorHandlerTests { given(response.getHeaders()).willReturn(headers); given(response.getBody()).willReturn(body); - assertFalse(handler.hasError(response)); - assertFalse(body.isClosed()); - assertEquals("Hello World", StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8)); + assertThat(handler.hasError(response)).isFalse(); + assertThat(body.isClosed()).isFalse(); + assertThat(StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8)).isEqualTo("Hello World"); } diff --git a/spring-web/src/test/java/org/springframework/web/client/ExtractingResponseErrorHandlerTests.java b/spring-web/src/test/java/org/springframework/web/client/ExtractingResponseErrorHandlerTests.java index 8ebcbe0a2f5..4f7b613c4f2 100644 --- a/spring-web/src/test/java/org/springframework/web/client/ExtractingResponseErrorHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/ExtractingResponseErrorHandlerTests.java @@ -32,10 +32,6 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -65,13 +61,13 @@ public class ExtractingResponseErrorHandlerTests { @Test public void hasError() throws Exception { given(this.response.getRawStatusCode()).willReturn(HttpStatus.I_AM_A_TEAPOT.value()); - assertTrue(this.errorHandler.hasError(this.response)); + assertThat(this.errorHandler.hasError(this.response)).isTrue(); given(this.response.getRawStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR.value()); - assertTrue(this.errorHandler.hasError(this.response)); + assertThat(this.errorHandler.hasError(this.response)).isTrue(); given(this.response.getRawStatusCode()).willReturn(HttpStatus.OK.value()); - assertFalse(this.errorHandler.hasError(this.response)); + assertThat(this.errorHandler.hasError(this.response)).isFalse(); } @Test @@ -80,13 +76,13 @@ public class ExtractingResponseErrorHandlerTests { .singletonMap(HttpStatus.Series.CLIENT_ERROR, null)); given(this.response.getRawStatusCode()).willReturn(HttpStatus.I_AM_A_TEAPOT.value()); - assertTrue(this.errorHandler.hasError(this.response)); + assertThat(this.errorHandler.hasError(this.response)).isTrue(); given(this.response.getRawStatusCode()).willReturn(HttpStatus.NOT_FOUND.value()); - assertFalse(this.errorHandler.hasError(this.response)); + assertThat(this.errorHandler.hasError(this.response)).isFalse(); given(this.response.getRawStatusCode()).willReturn(HttpStatus.OK.value()); - assertFalse(this.errorHandler.hasError(this.response)); + assertThat(this.errorHandler.hasError(this.response)).isFalse(); } @Test @@ -135,8 +131,8 @@ public class ExtractingResponseErrorHandlerTests { assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> this.errorHandler.handleError(this.response)) .satisfies(ex -> { - assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode()); - assertArrayEquals(body, ex.getResponseBodyAsByteArray()); + assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(ex.getResponseBodyAsByteArray()).isEqualTo(body); }); } diff --git a/spring-web/src/test/java/org/springframework/web/client/HttpMessageConverterExtractorTests.java b/spring-web/src/test/java/org/springframework/web/client/HttpMessageConverterExtractorTests.java index 4bec9204e4b..3a941797729 100644 --- a/spring-web/src/test/java/org/springframework/web/client/HttpMessageConverterExtractorTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/HttpMessageConverterExtractorTests.java @@ -34,9 +34,8 @@ import org.springframework.http.converter.GenericHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -62,7 +61,7 @@ public class HttpMessageConverterExtractorTests { given(response.getRawStatusCode()).willReturn(HttpStatus.NO_CONTENT.value()); Object result = extractor.extractData(response); - assertNull(result); + assertThat(result).isNull(); } @Test @@ -72,7 +71,7 @@ public class HttpMessageConverterExtractorTests { given(response.getRawStatusCode()).willReturn(HttpStatus.NOT_MODIFIED.value()); Object result = extractor.extractData(response); - assertNull(result); + assertThat(result).isNull(); } @Test @@ -82,7 +81,7 @@ public class HttpMessageConverterExtractorTests { given(response.getRawStatusCode()).willReturn(HttpStatus.CONTINUE.value()); Object result = extractor.extractData(response); - assertNull(result); + assertThat(result).isNull(); } @Test @@ -95,7 +94,7 @@ public class HttpMessageConverterExtractorTests { given(response.getHeaders()).willReturn(responseHeaders); Object result = extractor.extractData(response); - assertNull(result); + assertThat(result).isNull(); } @Test @@ -109,7 +108,7 @@ public class HttpMessageConverterExtractorTests { given(response.getBody()).willReturn(new ByteArrayInputStream("".getBytes())); Object result = extractor.extractData(response); - assertNull(result); + assertThat(result).isNull(); } @Test // gh-22265 @@ -123,7 +122,7 @@ public class HttpMessageConverterExtractorTests { given(response.getBody()).willReturn(null); Object result = extractor.extractData(response); - assertNull(result); + assertThat(result).isNull(); } @Test @@ -142,7 +141,7 @@ public class HttpMessageConverterExtractorTests { given(converter.read(eq(String.class), any(HttpInputMessage.class))).willReturn(expected); Object result = extractor.extractData(response); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); } @Test @@ -179,7 +178,7 @@ public class HttpMessageConverterExtractorTests { given(converter.read(eq(type), eq(null), any(HttpInputMessage.class))).willReturn(expected); Object result = extractor.extractData(response); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); } @Test // SPR-13592 diff --git a/spring-web/src/test/java/org/springframework/web/client/HttpStatusCodeExceptionTests.java b/spring-web/src/test/java/org/springframework/web/client/HttpStatusCodeExceptionTests.java index 466a8a37674..5080566e24d 100644 --- a/spring-web/src/test/java/org/springframework/web/client/HttpStatusCodeExceptionTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/HttpStatusCodeExceptionTests.java @@ -28,7 +28,6 @@ import org.junit.Test; import org.springframework.http.HttpStatus; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link HttpStatusCodeException} and subclasses. @@ -58,7 +57,7 @@ public class HttpStatusCodeExceptionTests { public void emptyStatusText() { HttpStatusCodeException ex = new HttpClientErrorException(HttpStatus.NOT_FOUND, ""); - assertEquals("404 Not Found", ex.getMessage()); + assertThat(ex.getMessage()).isEqualTo("404 Not Found"); } } diff --git a/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java b/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java index af5e3dbc02a..b101610c79a 100644 --- a/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java @@ -54,13 +54,8 @@ import org.springframework.http.converter.json.MappingJacksonValue; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; import static org.springframework.http.HttpMethod.POST; @@ -97,54 +92,54 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase @Test public void getString() { String s = template.getForObject(baseUrl + "/{method}", String.class, "get"); - assertEquals("Invalid content", helloWorld, s); + assertThat(s).as("Invalid content").isEqualTo(helloWorld); } @Test public void getEntity() { ResponseEntity entity = template.getForEntity(baseUrl + "/{method}", String.class, "get"); - assertEquals("Invalid content", helloWorld, entity.getBody()); - assertFalse("No headers", entity.getHeaders().isEmpty()); - assertEquals("Invalid content-type", textContentType, entity.getHeaders().getContentType()); - assertEquals("Invalid status code", HttpStatus.OK, entity.getStatusCode()); + assertThat(entity.getBody()).as("Invalid content").isEqualTo(helloWorld); + assertThat(entity.getHeaders().isEmpty()).as("No headers").isFalse(); + assertThat(entity.getHeaders().getContentType()).as("Invalid content-type").isEqualTo(textContentType); + assertThat(entity.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); } @Test public void getNoResponse() { String s = template.getForObject(baseUrl + "/get/nothing", String.class); - assertNull("Invalid content", s); + assertThat(s).as("Invalid content").isNull(); } @Test public void getNoContentTypeHeader() throws UnsupportedEncodingException { byte[] bytes = template.getForObject(baseUrl + "/get/nocontenttype", byte[].class); - assertArrayEquals("Invalid content", helloWorld.getBytes("UTF-8"), bytes); + assertThat(bytes).as("Invalid content").isEqualTo(helloWorld.getBytes("UTF-8")); } @Test public void getNoContent() { String s = template.getForObject(baseUrl + "/status/nocontent", String.class); - assertNull("Invalid content", s); + assertThat(s).as("Invalid content").isNull(); ResponseEntity entity = template.getForEntity(baseUrl + "/status/nocontent", String.class); - assertEquals("Invalid response code", HttpStatus.NO_CONTENT, entity.getStatusCode()); - assertNull("Invalid content", entity.getBody()); + assertThat(entity.getStatusCode()).as("Invalid response code").isEqualTo(HttpStatus.NO_CONTENT); + assertThat(entity.getBody()).as("Invalid content").isNull(); } @Test public void getNotModified() { String s = template.getForObject(baseUrl + "/status/notmodified", String.class); - assertNull("Invalid content", s); + assertThat(s).as("Invalid content").isNull(); ResponseEntity entity = template.getForEntity(baseUrl + "/status/notmodified", String.class); - assertEquals("Invalid response code", HttpStatus.NOT_MODIFIED, entity.getStatusCode()); - assertNull("Invalid content", entity.getBody()); + assertThat(entity.getStatusCode()).as("Invalid response code").isEqualTo(HttpStatus.NOT_MODIFIED); + assertThat(entity.getBody()).as("Invalid content").isNull(); } @Test public void postForLocation() throws URISyntaxException { URI location = template.postForLocation(baseUrl + "/{method}", helloWorld, "post"); - assertEquals("Invalid location", new URI(baseUrl + "/post/1"), location); + assertThat(location).as("Invalid location").isEqualTo(new URI(baseUrl + "/post/1")); } @Test @@ -153,13 +148,13 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase entityHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.ISO_8859_1)); HttpEntity entity = new HttpEntity<>(helloWorld, entityHeaders); URI location = template.postForLocation(baseUrl + "/{method}", entity, "post"); - assertEquals("Invalid location", new URI(baseUrl + "/post/1"), location); + assertThat(location).as("Invalid location").isEqualTo(new URI(baseUrl + "/post/1")); } @Test public void postForObject() throws URISyntaxException { String s = template.postForObject(baseUrl + "/{method}", helloWorld, String.class, "post"); - assertEquals("Invalid content", helloWorld, s); + assertThat(s).as("Invalid content").isEqualTo(helloWorld); } @Test @@ -168,7 +163,7 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase assumeFalse(this.clientHttpRequestFactory instanceof SimpleClientHttpRequestFactory); String s = template.patchForObject(baseUrl + "/{method}", helloWorld, String.class, "patch"); - assertEquals("Invalid content", helloWorld, s); + assertThat(s).as("Invalid content").isEqualTo(helloWorld); } @Test @@ -176,9 +171,9 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null)) .satisfies(ex -> { - assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode()); - assertNotNull(ex.getStatusText()); - assertNotNull(ex.getResponseBodyAsString()); + assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(ex.getStatusText()).isNotNull(); + assertThat(ex.getResponseBodyAsString()).isNotNull(); }); } @@ -187,8 +182,8 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> template.execute(baseUrl + "/status/badrequest", HttpMethod.GET, null, null)) .satisfies(ex -> { - assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode()); - assertEquals("400 Client Error", ex.getMessage()); + assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(ex.getMessage()).isEqualTo("400 Client Error"); }); } @@ -197,29 +192,28 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() -> template.execute(baseUrl + "/status/server", HttpMethod.GET, null, null)) .satisfies(ex -> { - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, ex.getStatusCode()); - assertNotNull(ex.getStatusText()); - assertNotNull(ex.getResponseBodyAsString()); + assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + assertThat(ex.getStatusText()).isNotNull(); + assertThat(ex.getResponseBodyAsString()).isNotNull(); }); } @Test public void optionsForAllow() throws URISyntaxException { Set allowed = template.optionsForAllow(new URI(baseUrl + "/get")); - assertEquals("Invalid response", - EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.HEAD, HttpMethod.TRACE), allowed); + assertThat(allowed).as("Invalid response").isEqualTo(EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.HEAD, HttpMethod.TRACE)); } @Test public void uri() throws InterruptedException, URISyntaxException { String result = template.getForObject(baseUrl + "/uri/{query}", String.class, "Z\u00fcrich"); - assertEquals("Invalid request URI", "/uri/Z%C3%BCrich", result); + assertThat(result).as("Invalid request URI").isEqualTo("/uri/Z%C3%BCrich"); result = template.getForObject(baseUrl + "/uri/query={query}", String.class, "foo@bar"); - assertEquals("Invalid request URI", "/uri/query=foo@bar", result); + assertThat(result).as("Invalid request URI").isEqualTo("/uri/query=foo@bar"); result = template.getForObject(baseUrl + "/uri/query={query}", String.class, "T\u014dky\u014d"); - assertEquals("Invalid request URI", "/uri/query=T%C5%8Dky%C5%8D", result); + assertThat(result).as("Invalid request URI").isEqualTo("/uri/query=T%C5%8Dky%C5%8D"); } @Test @@ -251,7 +245,7 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase HttpEntity requestEntity = new HttpEntity<>(requestHeaders); ResponseEntity response = template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get"); - assertEquals("Invalid content", helloWorld, response.getBody()); + assertThat(response.getBody()).as("Invalid content").isEqualTo(helloWorld); } @Test @@ -261,8 +255,8 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase requestHeaders.setContentType(MediaType.TEXT_PLAIN); HttpEntity entity = new HttpEntity<>(helloWorld, requestHeaders); HttpEntity result = template.exchange(baseUrl + "/{method}", POST, entity, Void.class, "post"); - assertEquals("Invalid location", new URI(baseUrl + "/post/1"), result.getHeaders().getLocation()); - assertFalse(result.hasBody()); + assertThat(result.getHeaders().getLocation()).as("Invalid location").isEqualTo(new URI(baseUrl + "/post/1")); + assertThat(result.hasBody()).isFalse(); } @Test @@ -275,9 +269,9 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase bean.setWithout("without"); HttpEntity entity = new HttpEntity<>(bean, entityHeaders); String s = template.postForObject(baseUrl + "/jsonpost", entity, String.class); - assertTrue(s.contains("\"with1\":\"with\"")); - assertTrue(s.contains("\"with2\":\"with\"")); - assertTrue(s.contains("\"without\":\"without\"")); + assertThat(s.contains("\"with1\":\"with\"")).isTrue(); + assertThat(s.contains("\"with2\":\"with\"")).isTrue(); + assertThat(s.contains("\"without\":\"without\"")).isTrue(); } @Test @@ -289,15 +283,15 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase jacksonValue.setSerializationView(MyJacksonView1.class); HttpEntity entity = new HttpEntity<>(jacksonValue, entityHeaders); String s = template.postForObject(baseUrl + "/jsonpost", entity, String.class); - assertTrue(s.contains("\"with1\":\"with\"")); - assertFalse(s.contains("\"with2\":\"with\"")); - assertFalse(s.contains("\"without\":\"without\"")); + assertThat(s.contains("\"with1\":\"with\"")).isTrue(); + assertThat(s.contains("\"with2\":\"with\"")).isFalse(); + assertThat(s.contains("\"without\":\"without\"")).isFalse(); } @Test // SPR-12123 public void serverPort() { String s = template.getForObject("http://localhost:{port}/get", String.class, port); - assertEquals("Invalid content", helloWorld, s); + assertThat(s).as("Invalid content").isEqualTo(helloWorld); } @Test // SPR-13154 @@ -311,13 +305,13 @@ public class RestTemplateIntegrationTests extends AbstractMockWebServerTestCase .contentType(new MediaType("application", "json", StandardCharsets.UTF_8)) .body(list, typeReference.getType()); String content = template.exchange(entity, String.class).getBody(); - assertTrue(content.contains("\"type\":\"foo\"")); - assertTrue(content.contains("\"type\":\"bar\"")); + assertThat(content.contains("\"type\":\"foo\"")).isTrue(); + assertThat(content.contains("\"type\":\"bar\"")).isTrue(); } @Test // SPR-15015 public void postWithoutBody() throws Exception { - assertNull(template.postForObject(baseUrl + "/jsonpost", null, String.class)); + assertThat(template.postForObject(baseUrl + "/jsonpost", null, String.class)).isNull(); } diff --git a/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java b/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java index e44334a7d0b..bc8a3a0b41a 100644 --- a/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java @@ -49,10 +49,6 @@ import org.springframework.web.util.DefaultUriBuilderFactory; import static org.assertj.core.api.Assertions.assertThat; 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.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -183,9 +179,8 @@ public class RestTemplateTests { mockTextResponseBody("Hello World"); String result = template.getForObject("https://example.com", String.class); - assertEquals("Invalid GET result", expected, result); - assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, - requestHeaders.getFirst("Accept")); + assertThat(result).as("Invalid GET result").isEqualTo(expected); + assertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE); verify(response).close(); } @@ -228,8 +223,7 @@ public class RestTemplateTests { template.setMessageConverters(Arrays.asList(firstConverter, secondConverter)); template.getForObject("https://example.com/", String.class); - assertEquals("Sent duplicate Accept header values", 1, - requestHeaders.getAccept().size()); + assertThat(requestHeaders.getAccept().size()).as("Sent duplicate Accept header values").isEqualTo(1); } @Test @@ -242,10 +236,10 @@ public class RestTemplateTests { mockTextResponseBody(expected); ResponseEntity result = template.getForEntity("https://example.com", String.class); - assertEquals("Invalid GET result", expected, result.getBody()); - assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); - assertEquals("Invalid Content-Type header", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); - assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); + assertThat(result.getBody()).as("Invalid GET result").isEqualTo(expected); + assertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE); + assertThat(result.getHeaders().getContentType()).as("Invalid Content-Type header").isEqualTo(MediaType.TEXT_PLAIN); + assertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); verify(response).close(); } @@ -279,7 +273,7 @@ public class RestTemplateTests { HttpHeaders result = template.headForHeaders("https://example.com"); - assertSame("Invalid headers returned", responseHeaders, result); + assertThat(result).as("Invalid headers returned").isSameAs(responseHeaders); verify(response).close(); } @@ -296,7 +290,7 @@ public class RestTemplateTests { given(response.getHeaders()).willReturn(responseHeaders); URI result = template.postForLocation("https://example.com", helloWorld); - assertEquals("Invalid POST result", expected, result); + assertThat(result).as("Invalid POST result").isEqualTo(expected); verify(response).close(); } @@ -318,7 +312,7 @@ public class RestTemplateTests { HttpEntity entity = new HttpEntity<>(helloWorld, entityHeaders); URI result = template.postForLocation("https://example.com", entity); - assertEquals("Invalid POST result", expected, result); + assertThat(result).as("Invalid POST result").isEqualTo(expected); verify(response).close(); } @@ -339,8 +333,8 @@ public class RestTemplateTests { HttpEntity entity = new HttpEntity<>("Hello World", entityHeaders); URI result = template.postForLocation("https://example.com", entity); - assertEquals("Invalid POST result", expected, result); - assertEquals("No custom header set", "MyValue", requestHeaders.getFirst("MyHeader")); + assertThat(result).as("Invalid POST result").isEqualTo(expected); + assertThat(requestHeaders.getFirst("MyHeader")).as("No custom header set").isEqualTo("MyValue"); verify(response).close(); } @@ -352,7 +346,7 @@ public class RestTemplateTests { mockResponseStatus(HttpStatus.OK); URI result = template.postForLocation("https://example.com", "Hello World"); - assertNull("Invalid POST result", result); + assertThat(result).as("Invalid POST result").isNull(); verify(response).close(); } @@ -364,7 +358,7 @@ public class RestTemplateTests { mockResponseStatus(HttpStatus.OK); template.postForLocation("https://example.com", null); - assertEquals("Invalid content length", 0, requestHeaders.getContentLength()); + assertThat(requestHeaders.getContentLength()).as("Invalid content length").isEqualTo(0); verify(response).close(); } @@ -379,8 +373,8 @@ public class RestTemplateTests { mockResponseBody(expected, MediaType.TEXT_PLAIN); String result = template.postForObject("https://example.com", "Hello World", String.class); - assertEquals("Invalid POST result", expected, result); - assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); + assertThat(result).as("Invalid POST result").isEqualTo(expected); + assertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE); verify(response).close(); } @@ -395,10 +389,10 @@ public class RestTemplateTests { mockResponseBody(expected, MediaType.TEXT_PLAIN); ResponseEntity result = template.postForEntity("https://example.com", "Hello World", String.class); - assertEquals("Invalid POST result", expected, result.getBody()); - assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); - assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); - assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); + assertThat(result.getBody()).as("Invalid POST result").isEqualTo(expected); + assertThat(result.getHeaders().getContentType()).as("Invalid Content-Type").isEqualTo(MediaType.TEXT_PLAIN); + assertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE); + assertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); verify(response).close(); } @@ -417,8 +411,8 @@ public class RestTemplateTests { given(converter.read(String.class, response)).willReturn(null); String result = template.postForObject("https://example.com", null, String.class); - assertNull("Invalid POST result", result); - assertEquals("Invalid content length", 0, requestHeaders.getContentLength()); + assertThat(result).as("Invalid POST result").isNull(); + assertThat(requestHeaders.getContentLength()).as("Invalid content length").isEqualTo(0); verify(response).close(); } @@ -437,10 +431,10 @@ public class RestTemplateTests { given(converter.read(String.class, response)).willReturn(null); ResponseEntity result = template.postForEntity("https://example.com", null, String.class); - assertFalse("Invalid POST result", result.hasBody()); - assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); - assertEquals("Invalid content length", 0, requestHeaders.getContentLength()); - assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); + assertThat(result.hasBody()).as("Invalid POST result").isFalse(); + assertThat(result.getHeaders().getContentType()).as("Invalid Content-Type").isEqualTo(MediaType.TEXT_PLAIN); + assertThat(requestHeaders.getContentLength()).as("Invalid content length").isEqualTo(0); + assertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); verify(response).close(); } @@ -463,7 +457,7 @@ public class RestTemplateTests { mockResponseStatus(HttpStatus.OK); template.put("https://example.com", null); - assertEquals("Invalid content length", 0, requestHeaders.getContentLength()); + assertThat(requestHeaders.getContentLength()).as("Invalid content length").isEqualTo(0); verify(response).close(); } @@ -478,8 +472,8 @@ public class RestTemplateTests { mockResponseBody("42", MediaType.TEXT_PLAIN); String result = template.patchForObject("https://example.com", "Hello World", String.class); - assertEquals("Invalid POST result", expected, result); - assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); + assertThat(result).as("Invalid POST result").isEqualTo(expected); + assertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE); verify(response).close(); } @@ -497,8 +491,8 @@ public class RestTemplateTests { given(response.getBody()).willReturn(StreamUtils.emptyInput()); String result = template.patchForObject("https://example.com", null, String.class); - assertNull("Invalid POST result", result); - assertEquals("Invalid content length", 0, requestHeaders.getContentLength()); + assertThat(result).as("Invalid POST result").isNull(); + assertThat(requestHeaders.getContentLength()).as("Invalid content length").isEqualTo(0); verify(response).close(); } @@ -524,7 +518,7 @@ public class RestTemplateTests { given(response.getHeaders()).willReturn(responseHeaders); Set result = template.optionsForAllow("https://example.com"); - assertEquals("Invalid OPTIONS result", expected, result); + assertThat(result).as("Invalid OPTIONS result").isEqualTo(expected); verify(response).close(); } @@ -573,11 +567,11 @@ public class RestTemplateTests { entityHeaders.set("MyHeader", "MyValue"); HttpEntity entity = new HttpEntity<>("Hello World", entityHeaders); ResponseEntity result = template.exchange("https://example.com", POST, entity, String.class); - assertEquals("Invalid POST result", expected, result.getBody()); - assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); - assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); - assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader")); - assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); + assertThat(result.getBody()).as("Invalid POST result").isEqualTo(expected); + assertThat(result.getHeaders().getContentType()).as("Invalid Content-Type").isEqualTo(MediaType.TEXT_PLAIN); + assertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE); + assertThat(requestHeaders.getFirst("MyHeader")).as("Invalid custom header").isEqualTo("MyValue"); + assertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); verify(response).close(); } @@ -608,11 +602,11 @@ public class RestTemplateTests { entityHeaders.set("MyHeader", "MyValue"); HttpEntity requestEntity = new HttpEntity<>("Hello World", entityHeaders); ResponseEntity> result = template.exchange("https://example.com", POST, requestEntity, intList); - assertEquals("Invalid POST result", expected, result.getBody()); - assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); - assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept")); - assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader")); - assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); + assertThat(result.getBody()).as("Invalid POST result").isEqualTo(expected); + assertThat(result.getHeaders().getContentType()).as("Invalid Content-Type").isEqualTo(MediaType.TEXT_PLAIN); + assertThat(requestHeaders.getFirst("Accept")).as("Invalid Accept header").isEqualTo(MediaType.TEXT_PLAIN_VALUE); + assertThat(requestHeaders.getFirst("MyHeader")).as("Invalid custom header").isEqualTo("MyValue"); + assertThat(result.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); verify(response).close(); } diff --git a/spring-web/src/test/java/org/springframework/web/context/ContextLoaderInitializerTests.java b/spring-web/src/test/java/org/springframework/web/context/ContextLoaderInitializerTests.java index 8714e6d3b52..3cd28430f16 100644 --- a/spring-web/src/test/java/org/springframework/web/context/ContextLoaderInitializerTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/ContextLoaderInitializerTests.java @@ -27,7 +27,7 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test case for {@link AbstractContextLoaderInitializer}. @@ -55,15 +55,17 @@ public class ContextLoaderInitializerTests { public void register() throws ServletException { initializer.onStartup(servletContext); - assertTrue(eventListener instanceof ContextLoaderListener); + boolean condition1 = eventListener instanceof ContextLoaderListener; + assertThat(condition1).isTrue(); ContextLoaderListener cll = (ContextLoaderListener) eventListener; cll.contextInitialized(new ServletContextEvent(servletContext)); WebApplicationContext applicationContext = WebApplicationContextUtils .getRequiredWebApplicationContext(servletContext); - assertTrue(applicationContext.containsBean(BEAN_NAME)); - assertTrue(applicationContext.getBean(BEAN_NAME) instanceof MyBean); + assertThat(applicationContext.containsBean(BEAN_NAME)).isTrue(); + boolean condition = applicationContext.getBean(BEAN_NAME) instanceof MyBean; + assertThat(condition).isTrue(); } private class MyMockServletContext extends MockServletContext { diff --git a/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java b/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java index 6f1436af81d..6c9597b3e68 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java @@ -27,10 +27,8 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StaticWebApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; /** * @author Rod Johnson @@ -53,20 +51,20 @@ public class RequestAndSessionScopedBeanTests { HttpServletRequest request = new MockHttpServletRequest(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); TestBean target = (TestBean) wac.getBean(targetBeanName); - assertEquals("abc", target.getName()); - assertSame(target, request.getAttribute(targetBeanName)); + assertThat(target.getName()).isEqualTo("abc"); + assertThat(request.getAttribute(targetBeanName)).isSameAs(target); TestBean target2 = (TestBean) wac.getBean(targetBeanName); - assertEquals("abc", target2.getName()); - assertSame(target2, target); - assertSame(target2, request.getAttribute(targetBeanName)); + assertThat(target2.getName()).isEqualTo("abc"); + assertThat(target).isSameAs(target2); + assertThat(request.getAttribute(targetBeanName)).isSameAs(target2); request = new MockHttpServletRequest(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); TestBean target3 = (TestBean) wac.getBean(targetBeanName); - assertEquals("abc", target3.getName()); - assertSame(target3, request.getAttribute(targetBeanName)); - assertNotSame(target3, target); + assertThat(target3.getName()).isEqualTo("abc"); + assertThat(request.getAttribute(targetBeanName)).isSameAs(target3); + assertThat(target).isNotSameAs(target3); RequestContextHolder.setRequestAttributes(null); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> @@ -88,8 +86,8 @@ public class RequestAndSessionScopedBeanTests { wac.refresh(); TestBean target = (TestBean) wac.getBean(targetBeanName); - assertEquals("abc", target.getName()); - assertSame(target, request.getSession().getAttribute(targetBeanName)); + assertThat(target.getName()).isEqualTo("abc"); + assertThat(request.getSession().getAttribute(targetBeanName)).isSameAs(target); RequestContextHolder.setRequestAttributes(null); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> diff --git a/spring-web/src/test/java/org/springframework/web/context/request/RequestContextListenerTests.java b/spring-web/src/test/java/org/springframework/web/context/request/RequestContextListenerTests.java index 326e06bfce8..72b95e4d803 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/RequestContextListenerTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/RequestContextListenerTests.java @@ -24,10 +24,7 @@ import org.springframework.core.task.MockRunnable; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockServletContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -41,18 +38,17 @@ public class RequestContextListenerTests { MockHttpServletRequest request = new MockHttpServletRequest(context); request.setAttribute("test", "value"); - assertNull(RequestContextHolder.getRequestAttributes()); + assertThat(RequestContextHolder.getRequestAttributes()).isNull(); listener.requestInitialized(new ServletRequestEvent(context, request)); - assertNotNull(RequestContextHolder.getRequestAttributes()); - assertEquals("value", - RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)); + assertThat(RequestContextHolder.getRequestAttributes()).isNotNull(); + assertThat(RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)).isEqualTo("value"); MockRunnable runnable = new MockRunnable(); RequestContextHolder.getRequestAttributes().registerDestructionCallback( "test", runnable, RequestAttributes.SCOPE_REQUEST); listener.requestDestroyed(new ServletRequestEvent(context, request)); - assertNull(RequestContextHolder.getRequestAttributes()); - assertTrue(runnable.wasExecuted()); + assertThat(RequestContextHolder.getRequestAttributes()).isNull(); + assertThat(runnable.wasExecuted()).isTrue(); } @Test @@ -62,19 +58,18 @@ public class RequestContextListenerTests { MockHttpServletRequest request = new MockHttpServletRequest(context); request.setAttribute("test", "value"); - assertNull(RequestContextHolder.getRequestAttributes()); + assertThat(RequestContextHolder.getRequestAttributes()).isNull(); listener.requestInitialized(new ServletRequestEvent(context, request)); - assertNotNull(RequestContextHolder.getRequestAttributes()); - assertEquals("value", - RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)); + assertThat(RequestContextHolder.getRequestAttributes()).isNotNull(); + assertThat(RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)).isEqualTo("value"); MockRunnable runnable = new MockRunnable(); RequestContextHolder.getRequestAttributes().registerDestructionCallback( "test", runnable, RequestAttributes.SCOPE_REQUEST); request.clearAttributes(); listener.requestDestroyed(new ServletRequestEvent(context, request)); - assertNull(RequestContextHolder.getRequestAttributes()); - assertTrue(runnable.wasExecuted()); + assertThat(RequestContextHolder.getRequestAttributes()).isNull(); + assertThat(runnable.wasExecuted()).isTrue(); } @Test @@ -84,11 +79,10 @@ public class RequestContextListenerTests { final MockHttpServletRequest request = new MockHttpServletRequest(context); request.setAttribute("test", "value"); - assertNull(RequestContextHolder.getRequestAttributes()); + assertThat(RequestContextHolder.getRequestAttributes()).isNull(); listener.requestInitialized(new ServletRequestEvent(context, request)); - assertNotNull(RequestContextHolder.getRequestAttributes()); - assertEquals("value", - RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)); + assertThat(RequestContextHolder.getRequestAttributes()).isNotNull(); + assertThat(RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)).isEqualTo("value"); MockRunnable runnable = new MockRunnable(); RequestContextHolder.getRequestAttributes().registerDestructionCallback( "test", runnable, RequestAttributes.SCOPE_REQUEST); @@ -107,13 +101,13 @@ public class RequestContextListenerTests { catch (InterruptedException ex) { } // Still bound to original thread, but at least completed. - assertNotNull(RequestContextHolder.getRequestAttributes()); - assertTrue(runnable.wasExecuted()); + assertThat(RequestContextHolder.getRequestAttributes()).isNotNull(); + assertThat(runnable.wasExecuted()).isTrue(); // Check that a repeated execution in the same thread works and performs cleanup. listener.requestInitialized(new ServletRequestEvent(context, request)); listener.requestDestroyed(new ServletRequestEvent(context, request)); - assertNull(RequestContextHolder.getRequestAttributes()); + assertThat(RequestContextHolder.getRequestAttributes()).isNull(); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java index 923d823e3c3..d65a6a5697a 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java @@ -31,14 +31,8 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.tests.sample.beans.DerivedTestBean; 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.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; /** * @author Rob Harrop @@ -75,11 +69,11 @@ public class RequestScopeTests { RequestContextHolder.setRequestAttributes(requestAttributes); String name = "requestScopedObject"; - assertNull(request.getAttribute(name)); + assertThat(request.getAttribute(name)).isNull(); TestBean bean = (TestBean) this.beanFactory.getBean(name); - assertEquals("/path", bean.getName()); - assertSame(bean, request.getAttribute(name)); - assertSame(bean, this.beanFactory.getBean(name)); + assertThat(bean.getName()).isEqualTo("/path"); + assertThat(request.getAttribute(name)).isSameAs(bean); + assertThat(this.beanFactory.getBean(name)).isSameAs(bean); } @Test @@ -89,13 +83,13 @@ public class RequestScopeTests { RequestContextHolder.setRequestAttributes(requestAttributes); String name = "requestScopedDisposableObject"; - assertNull(request.getAttribute(name)); + assertThat(request.getAttribute(name)).isNull(); DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name); - assertSame(bean, request.getAttribute(name)); - assertSame(bean, this.beanFactory.getBean(name)); + assertThat(request.getAttribute(name)).isSameAs(bean); + assertThat(this.beanFactory.getBean(name)).isSameAs(bean); requestAttributes.requestCompleted(); - assertTrue(bean.wasDestroyed()); + assertThat(bean.wasDestroyed()).isTrue(); } @Test @@ -105,10 +99,11 @@ public class RequestScopeTests { RequestContextHolder.setRequestAttributes(requestAttributes); String name = "requestScopedFactoryBean"; - assertNull(request.getAttribute(name)); + assertThat(request.getAttribute(name)).isNull(); TestBean bean = (TestBean) this.beanFactory.getBean(name); - assertTrue(request.getAttribute(name) instanceof FactoryBean); - assertSame(bean, this.beanFactory.getBean(name)); + boolean condition = request.getAttribute(name) instanceof FactoryBean; + assertThat(condition).isTrue(); + assertThat(this.beanFactory.getBean(name)).isSameAs(bean); } @Test @@ -118,7 +113,7 @@ public class RequestScopeTests { RequestContextHolder.setRequestAttributes(requestAttributes); String name = "requestScopedObjectCircle1"; - assertNull(request.getAttribute(name)); + assertThat(request.getAttribute(name)).isNull(); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> this.beanFactory.getBean(name)) .matches(ex -> ex.contains(BeanCurrentlyInCreationException.class)); @@ -131,20 +126,20 @@ public class RequestScopeTests { RequestContextHolder.setRequestAttributes(requestAttributes); String outerBeanName = "requestScopedOuterBean"; - assertNull(request.getAttribute(outerBeanName)); + assertThat(request.getAttribute(outerBeanName)).isNull(); TestBean outer1 = (TestBean) this.beanFactory.getBean(outerBeanName); - assertNotNull(request.getAttribute(outerBeanName)); + assertThat(request.getAttribute(outerBeanName)).isNotNull(); TestBean inner1 = (TestBean) outer1.getSpouse(); - assertSame(outer1, this.beanFactory.getBean(outerBeanName)); + assertThat(this.beanFactory.getBean(outerBeanName)).isSameAs(outer1); requestAttributes.requestCompleted(); - assertTrue(outer1.wasDestroyed()); - assertTrue(inner1.wasDestroyed()); + assertThat(outer1.wasDestroyed()).isTrue(); + assertThat(inner1.wasDestroyed()).isTrue(); request = new MockHttpServletRequest(); requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); TestBean outer2 = (TestBean) this.beanFactory.getBean(outerBeanName); - assertNotSame(outer1, outer2); - assertNotSame(inner1, outer2.getSpouse()); + assertThat(outer2).isNotSameAs(outer1); + assertThat(outer2.getSpouse()).isNotSameAs(inner1); } @Test @@ -155,14 +150,14 @@ public class RequestScopeTests { String outerBeanName = "singletonOuterBean"; TestBean outer1 = (TestBean) this.beanFactory.getBean(outerBeanName); - assertNull(request.getAttribute(outerBeanName)); + assertThat(request.getAttribute(outerBeanName)).isNull(); TestBean inner1 = (TestBean) outer1.getSpouse(); TestBean outer2 = (TestBean) this.beanFactory.getBean(outerBeanName); - assertSame(outer1, outer2); - assertSame(inner1, outer2.getSpouse()); + assertThat(outer2).isSameAs(outer1); + assertThat(outer2.getSpouse()).isSameAs(inner1); requestAttributes.requestCompleted(); - assertTrue(inner1.wasDestroyed()); - assertFalse(outer1.wasDestroyed()); + assertThat(inner1.wasDestroyed()).isTrue(); + assertThat(outer1.wasDestroyed()).isFalse(); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopedProxyTests.java b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopedProxyTests.java index d2cb0f29269..2d67993ca68 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopedProxyTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopedProxyTests.java @@ -31,12 +31,7 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.factory.DummyFactory; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -59,21 +54,21 @@ public class RequestScopedProxyTests { public void testGetFromScope() throws Exception { String name = "requestScopedObject"; TestBean bean = (TestBean) this.beanFactory.getBean(name); - assertTrue(AopUtils.isCglibProxy(bean)); + assertThat(AopUtils.isCglibProxy(bean)).isTrue(); MockHttpServletRequest request = new MockHttpServletRequest(); RequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); try { - assertNull(request.getAttribute("scopedTarget." + name)); - assertEquals("scoped", bean.getName()); - assertNotNull(request.getAttribute("scopedTarget." + name)); + assertThat(request.getAttribute("scopedTarget." + name)).isNull(); + assertThat(bean.getName()).isEqualTo("scoped"); + assertThat(request.getAttribute("scopedTarget." + name)).isNotNull(); TestBean target = (TestBean) request.getAttribute("scopedTarget." + name); - assertEquals(TestBean.class, target.getClass()); - assertEquals("scoped", target.getName()); - assertSame(bean, this.beanFactory.getBean(name)); - assertEquals(bean.toString(), target.toString()); + assertThat(target.getClass()).isEqualTo(TestBean.class); + assertThat(target.getName()).isEqualTo("scoped"); + assertThat(this.beanFactory.getBean(name)).isSameAs(bean); + assertThat(target.toString()).isEqualTo(bean.toString()); } finally { RequestContextHolder.setRequestAttributes(null); @@ -91,14 +86,14 @@ public class RequestScopedProxyTests { RequestContextHolder.setRequestAttributes(requestAttributes); try { - assertNull(request.getAttribute("scopedTarget." + name)); - assertEquals("scoped", bean.getName()); - assertNotNull(request.getAttribute("scopedTarget." + name)); + assertThat(request.getAttribute("scopedTarget." + name)).isNull(); + assertThat(bean.getName()).isEqualTo("scoped"); + assertThat(request.getAttribute("scopedTarget." + name)).isNotNull(); TestBean target = (TestBean) request.getAttribute("scopedTarget." + name); - assertEquals(TestBean.class, target.getClass()); - assertEquals("scoped", target.getName()); - assertSame(bean, this.beanFactory.getBean(name)); - assertEquals(bean.toString(), target.toString()); + assertThat(target.getClass()).isEqualTo(TestBean.class); + assertThat(target.getName()).isEqualTo("scoped"); + assertThat(this.beanFactory.getBean(name)).isSameAs(bean); + assertThat(target.toString()).isEqualTo(bean.toString()); } finally { RequestContextHolder.setRequestAttributes(null); @@ -109,22 +104,22 @@ public class RequestScopedProxyTests { public void testDestructionAtRequestCompletion() throws Exception { String name = "requestScopedDisposableObject"; DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name); - assertTrue(AopUtils.isCglibProxy(bean)); + assertThat(AopUtils.isCglibProxy(bean)).isTrue(); MockHttpServletRequest request = new MockHttpServletRequest(); ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); try { - assertNull(request.getAttribute("scopedTarget." + name)); - assertEquals("scoped", bean.getName()); - assertNotNull(request.getAttribute("scopedTarget." + name)); - assertEquals(DerivedTestBean.class, request.getAttribute("scopedTarget." + name).getClass()); - assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName()); - assertSame(bean, this.beanFactory.getBean(name)); + assertThat(request.getAttribute("scopedTarget." + name)).isNull(); + assertThat(bean.getName()).isEqualTo("scoped"); + assertThat(request.getAttribute("scopedTarget." + name)).isNotNull(); + assertThat(request.getAttribute("scopedTarget." + name).getClass()).isEqualTo(DerivedTestBean.class); + assertThat(((TestBean) request.getAttribute("scopedTarget." + name)).getName()).isEqualTo("scoped"); + assertThat(this.beanFactory.getBean(name)).isSameAs(bean); requestAttributes.requestCompleted(); - assertTrue(((TestBean) request.getAttribute("scopedTarget." + name)).wasDestroyed()); + assertThat(((TestBean) request.getAttribute("scopedTarget." + name)).wasDestroyed()).isTrue(); } finally { RequestContextHolder.setRequestAttributes(null); @@ -135,18 +130,18 @@ public class RequestScopedProxyTests { public void testGetFromFactoryBeanInScope() throws Exception { String name = "requestScopedFactoryBean"; TestBean bean = (TestBean) this.beanFactory.getBean(name); - assertTrue(AopUtils.isCglibProxy(bean)); + assertThat(AopUtils.isCglibProxy(bean)).isTrue(); MockHttpServletRequest request = new MockHttpServletRequest(); RequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); try { - assertNull(request.getAttribute("scopedTarget." + name)); - assertEquals(DummyFactory.SINGLETON_NAME, bean.getName()); - assertNotNull(request.getAttribute("scopedTarget." + name)); - assertEquals(DummyFactory.class, request.getAttribute("scopedTarget." + name).getClass()); - assertSame(bean, this.beanFactory.getBean(name)); + assertThat(request.getAttribute("scopedTarget." + name)).isNull(); + assertThat(bean.getName()).isEqualTo(DummyFactory.SINGLETON_NAME); + assertThat(request.getAttribute("scopedTarget." + name)).isNotNull(); + assertThat(request.getAttribute("scopedTarget." + name).getClass()).isEqualTo(DummyFactory.class); + assertThat(this.beanFactory.getBean(name)).isSameAs(bean); } finally { RequestContextHolder.setRequestAttributes(null); @@ -156,8 +151,8 @@ public class RequestScopedProxyTests { @Test public void testGetInnerBeanFromScope() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("outerBean"); - assertFalse(AopUtils.isAopProxy(bean)); - assertTrue(AopUtils.isCglibProxy(bean.getSpouse())); + assertThat(AopUtils.isAopProxy(bean)).isFalse(); + assertThat(AopUtils.isCglibProxy(bean.getSpouse())).isTrue(); String name = "scopedInnerBean"; @@ -166,11 +161,11 @@ public class RequestScopedProxyTests { RequestContextHolder.setRequestAttributes(requestAttributes); try { - assertNull(request.getAttribute("scopedTarget." + name)); - assertEquals("scoped", bean.getSpouse().getName()); - assertNotNull(request.getAttribute("scopedTarget." + name)); - assertEquals(TestBean.class, request.getAttribute("scopedTarget." + name).getClass()); - assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName()); + assertThat(request.getAttribute("scopedTarget." + name)).isNull(); + assertThat(bean.getSpouse().getName()).isEqualTo("scoped"); + assertThat(request.getAttribute("scopedTarget." + name)).isNotNull(); + assertThat(request.getAttribute("scopedTarget." + name).getClass()).isEqualTo(TestBean.class); + assertThat(((TestBean) request.getAttribute("scopedTarget." + name)).getName()).isEqualTo("scoped"); } finally { RequestContextHolder.setRequestAttributes(null); @@ -180,8 +175,8 @@ public class RequestScopedProxyTests { @Test public void testGetAnonymousInnerBeanFromScope() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("outerBean"); - assertFalse(AopUtils.isAopProxy(bean)); - assertTrue(AopUtils.isCglibProxy(bean.getSpouse())); + assertThat(AopUtils.isAopProxy(bean)).isFalse(); + assertThat(AopUtils.isCglibProxy(bean.getSpouse())).isTrue(); BeanDefinition beanDef = this.beanFactory.getBeanDefinition("outerBean"); BeanDefinitionHolder innerBeanDef = @@ -193,11 +188,11 @@ public class RequestScopedProxyTests { RequestContextHolder.setRequestAttributes(requestAttributes); try { - assertNull(request.getAttribute("scopedTarget." + name)); - assertEquals("scoped", bean.getSpouse().getName()); - assertNotNull(request.getAttribute("scopedTarget." + name)); - assertEquals(TestBean.class, request.getAttribute("scopedTarget." + name).getClass()); - assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName()); + assertThat(request.getAttribute("scopedTarget." + name)).isNull(); + assertThat(bean.getSpouse().getName()).isEqualTo("scoped"); + assertThat(request.getAttribute("scopedTarget." + name)).isNotNull(); + assertThat(request.getAttribute("scopedTarget." + name).getClass()).isEqualTo(TestBean.class); + assertThat(((TestBean) request.getAttribute("scopedTarget." + name)).getName()).isEqualTo("scoped"); } finally { RequestContextHolder.setRequestAttributes(null); diff --git a/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java b/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java index dbd4a1417a3..2d3fa4d2a97 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java @@ -26,10 +26,9 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpSession; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -62,7 +61,7 @@ public class ServletRequestAttributesTests { ServletRequestAttributes attrs = new ServletRequestAttributes(request); attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST); Object value = request.getAttribute(KEY); - assertSame(VALUE, value); + assertThat(value).isSameAs(VALUE); } @Test @@ -82,7 +81,7 @@ public class ServletRequestAttributesTests { request.setSession(session); ServletRequestAttributes attrs = new ServletRequestAttributes(request); attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_SESSION); - assertSame(VALUE, session.getAttribute(KEY)); + assertThat(session.getAttribute(KEY)).isSameAs(VALUE); } @Test @@ -92,11 +91,11 @@ public class ServletRequestAttributesTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); ServletRequestAttributes attrs = new ServletRequestAttributes(request); - assertSame(VALUE, attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION)); + assertThat(attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION)).isSameAs(VALUE); attrs.requestCompleted(); request.close(); attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_SESSION); - assertSame(VALUE, session.getAttribute(KEY)); + assertThat(session.getAttribute(KEY)).isSameAs(VALUE); } @Test @@ -105,7 +104,7 @@ public class ServletRequestAttributesTests { ServletRequestAttributes attrs = new ServletRequestAttributes(request); Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION); - assertNull(value); + assertThat(value).isNull(); verify(request).getSession(false); } @@ -118,7 +117,7 @@ public class ServletRequestAttributesTests { ServletRequestAttributes attrs = new ServletRequestAttributes(request); attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION); Object value = session.getAttribute(KEY); - assertNull(value); + assertThat(value).isNull(); } @Test @@ -138,7 +137,7 @@ public class ServletRequestAttributesTests { given(session.getAttribute(KEY)).willReturn(VALUE); ServletRequestAttributes attrs = new ServletRequestAttributes(request); - assertSame(VALUE, attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION)); + assertThat(attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION)).isSameAs(VALUE); attrs.requestCompleted(); verify(session, times(2)).getAttribute(KEY); diff --git a/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestHttpMethodsTests.java b/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestHttpMethodsTests.java index bea6c1142c9..d07c4069f4a 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestHttpMethodsTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestHttpMethodsTests.java @@ -31,10 +31,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Parameterized tests for {@link ServletWebRequest}. @@ -82,9 +79,9 @@ public class ServletWebRequestHttpMethodsTests { servletRequest.addHeader("If-Modified-Since", epochTime); servletResponse.setStatus(304); - assertFalse(request.checkNotModified(epochTime)); - assertEquals(304, servletResponse.getStatus()); - assertNull(servletResponse.getHeader("Last-Modified")); + assertThat(request.checkNotModified(epochTime)).isFalse(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getHeader("Last-Modified")).isNull(); } @Test // SPR-13516 @@ -93,16 +90,16 @@ public class ServletWebRequestHttpMethodsTests { servletRequest.addHeader("If-Modified-Since", epochTime); servletResponse.setStatus(0); - assertFalse(request.checkNotModified(epochTime)); + assertThat(request.checkNotModified(epochTime)).isFalse(); } @Test // SPR-14559 public void checkNotModifiedInvalidIfNoneMatchHeader() { String etag = "\"etagvalue\""; servletRequest.addHeader("If-None-Match", "missingquotes"); - assertFalse(request.checkNotModified(etag)); - assertEquals(200, servletResponse.getStatus()); - assertEquals(etag, servletResponse.getHeader("ETag")); + assertThat(request.checkNotModified(etag)).isFalse(); + assertThat(servletResponse.getStatus()).isEqualTo(200); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(etag); } @Test @@ -111,10 +108,10 @@ public class ServletWebRequestHttpMethodsTests { servletRequest.addHeader("If-Modified-Since", epochTime); servletResponse.addHeader("Last-Modified", CURRENT_TIME); - assertTrue(request.checkNotModified(epochTime)); - assertEquals(304, servletResponse.getStatus()); - assertEquals(1, servletResponse.getHeaders("Last-Modified").size()); - assertEquals(CURRENT_TIME, servletResponse.getHeader("Last-Modified")); + assertThat(request.checkNotModified(epochTime)).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getHeaders("Last-Modified").size()).isEqualTo(1); + assertThat(servletResponse.getHeader("Last-Modified")).isEqualTo(CURRENT_TIME); } @Test @@ -122,9 +119,9 @@ public class ServletWebRequestHttpMethodsTests { long epochTime = currentDate.getTime(); servletRequest.addHeader("If-Modified-Since", epochTime); - assertTrue(request.checkNotModified(epochTime)); - assertEquals(304, servletResponse.getStatus()); - assertEquals(currentDate.getTime() / 1000, servletResponse.getDateHeader("Last-Modified") / 1000); + assertThat(request.checkNotModified(epochTime)).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getDateHeader("Last-Modified") / 1000).isEqualTo(currentDate.getTime() / 1000); } @Test @@ -132,9 +129,9 @@ public class ServletWebRequestHttpMethodsTests { long oneMinuteAgo = currentDate.getTime() - (1000 * 60); servletRequest.addHeader("If-Modified-Since", oneMinuteAgo); - assertFalse(request.checkNotModified(currentDate.getTime())); - assertEquals(200, servletResponse.getStatus()); - assertEquals(currentDate.getTime() / 1000, servletResponse.getDateHeader("Last-Modified") / 1000); + assertThat(request.checkNotModified(currentDate.getTime())).isFalse(); + assertThat(servletResponse.getStatus()).isEqualTo(200); + assertThat(servletResponse.getDateHeader("Last-Modified") / 1000).isEqualTo(currentDate.getTime() / 1000); } @Test @@ -142,9 +139,9 @@ public class ServletWebRequestHttpMethodsTests { String etag = "\"Foo\""; servletRequest.addHeader("If-None-Match", etag); - assertTrue(request.checkNotModified(etag)); - assertEquals(304, servletResponse.getStatus()); - assertEquals(etag, servletResponse.getHeader("ETag")); + assertThat(request.checkNotModified(etag)).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(etag); } @Test @@ -152,9 +149,9 @@ public class ServletWebRequestHttpMethodsTests { String etag = "\"Foo, Bar\""; servletRequest.addHeader("If-None-Match", etag); - assertTrue(request.checkNotModified(etag)); - assertEquals(304, servletResponse.getStatus()); - assertEquals(etag, servletResponse.getHeader("ETag")); + assertThat(request.checkNotModified(etag)).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(etag); } @@ -164,9 +161,9 @@ public class ServletWebRequestHttpMethodsTests { String oldETag = "Bar"; servletRequest.addHeader("If-None-Match", oldETag); - assertFalse(request.checkNotModified(currentETag)); - assertEquals(200, servletResponse.getStatus()); - assertEquals(currentETag, servletResponse.getHeader("ETag")); + assertThat(request.checkNotModified(currentETag)).isFalse(); + assertThat(servletResponse.getStatus()).isEqualTo(200); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(currentETag); } @Test @@ -175,9 +172,9 @@ public class ServletWebRequestHttpMethodsTests { String paddedETag = String.format("\"%s\"", etag); servletRequest.addHeader("If-None-Match", paddedETag); - assertTrue(request.checkNotModified(etag)); - assertEquals(304, servletResponse.getStatus()); - assertEquals(paddedETag, servletResponse.getHeader("ETag")); + assertThat(request.checkNotModified(etag)).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(paddedETag); } @Test @@ -186,9 +183,9 @@ public class ServletWebRequestHttpMethodsTests { String oldETag = "Bar"; servletRequest.addHeader("If-None-Match", oldETag); - assertFalse(request.checkNotModified(currentETag)); - assertEquals(200, servletResponse.getStatus()); - assertEquals(String.format("\"%s\"", currentETag), servletResponse.getHeader("ETag")); + assertThat(request.checkNotModified(currentETag)).isFalse(); + assertThat(servletResponse.getStatus()).isEqualTo(200); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(String.format("\"%s\"", currentETag)); } @Test @@ -196,9 +193,9 @@ public class ServletWebRequestHttpMethodsTests { String etag = "\"Foo\""; servletRequest.addHeader("If-None-Match", "*"); - assertFalse(request.checkNotModified(etag)); - assertEquals(200, servletResponse.getStatus()); - assertEquals(etag, servletResponse.getHeader("ETag")); + assertThat(request.checkNotModified(etag)).isFalse(); + assertThat(servletResponse.getStatus()).isEqualTo(200); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(etag); } @Test @@ -207,10 +204,10 @@ public class ServletWebRequestHttpMethodsTests { servletRequest.addHeader("If-None-Match", etag); servletRequest.addHeader("If-Modified-Since", currentDate.getTime()); - assertTrue(request.checkNotModified(etag, currentDate.getTime())); - assertEquals(304, servletResponse.getStatus()); - assertEquals(etag, servletResponse.getHeader("ETag")); - assertEquals(currentDate.getTime() / 1000, servletResponse.getDateHeader("Last-Modified") / 1000); + assertThat(request.checkNotModified(etag, currentDate.getTime())).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(etag); + assertThat(servletResponse.getDateHeader("Last-Modified") / 1000).isEqualTo(currentDate.getTime() / 1000); } @Test // SPR-14224 @@ -221,10 +218,10 @@ public class ServletWebRequestHttpMethodsTests { long oneMinuteAgo = currentEpoch - (1000 * 60); servletRequest.addHeader("If-Modified-Since", oneMinuteAgo); - assertTrue(request.checkNotModified(etag, currentEpoch)); - assertEquals(304, servletResponse.getStatus()); - assertEquals(etag, servletResponse.getHeader("ETag")); - assertEquals(currentDate.getTime() / 1000, servletResponse.getDateHeader("Last-Modified") / 1000); + assertThat(request.checkNotModified(etag, currentEpoch)).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(etag); + assertThat(servletResponse.getDateHeader("Last-Modified") / 1000).isEqualTo(currentDate.getTime() / 1000); } @Test @@ -235,10 +232,10 @@ public class ServletWebRequestHttpMethodsTests { long epochTime = currentDate.getTime(); servletRequest.addHeader("If-Modified-Since", epochTime); - assertFalse(request.checkNotModified(currentETag, epochTime)); - assertEquals(200, servletResponse.getStatus()); - assertEquals(currentETag, servletResponse.getHeader("ETag")); - assertEquals(currentDate.getTime() / 1000, servletResponse.getDateHeader("Last-Modified") / 1000); + assertThat(request.checkNotModified(currentETag, epochTime)).isFalse(); + assertThat(servletResponse.getStatus()).isEqualTo(200); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(currentETag); + assertThat(servletResponse.getDateHeader("Last-Modified") / 1000).isEqualTo(currentDate.getTime() / 1000); } @Test @@ -247,9 +244,9 @@ public class ServletWebRequestHttpMethodsTests { String weakETag = String.format("W/%s", etag); servletRequest.addHeader("If-None-Match", etag); - assertTrue(request.checkNotModified(weakETag)); - assertEquals(304, servletResponse.getStatus()); - assertEquals(weakETag, servletResponse.getHeader("ETag")); + assertThat(request.checkNotModified(weakETag)).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(weakETag); } @Test @@ -257,9 +254,9 @@ public class ServletWebRequestHttpMethodsTests { String etag = "\"Foo\""; servletRequest.addHeader("If-None-Match", String.format("W/%s", etag)); - assertTrue(request.checkNotModified(etag)); - assertEquals(304, servletResponse.getStatus()); - assertEquals(etag, servletResponse.getHeader("ETag")); + assertThat(request.checkNotModified(etag)).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(etag); } @Test @@ -268,9 +265,9 @@ public class ServletWebRequestHttpMethodsTests { String multipleETags = String.format("\"Foo\", %s", etag); servletRequest.addHeader("If-None-Match", multipleETags); - assertTrue(request.checkNotModified(etag)); - assertEquals(304, servletResponse.getStatus()); - assertEquals(etag, servletResponse.getHeader("ETag")); + assertThat(request.checkNotModified(etag)).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getHeader("ETag")).isEqualTo(etag); } @Test @@ -279,9 +276,9 @@ public class ServletWebRequestHttpMethodsTests { servletRequest.setMethod("GET"); servletRequest.addHeader("If-Modified-Since", "Wed, 09 Apr 2014 09:57:42 GMT; length=13774"); - assertTrue(request.checkNotModified(epochTime)); - assertEquals(304, servletResponse.getStatus()); - assertEquals(epochTime / 1000, servletResponse.getDateHeader("Last-Modified") / 1000); + assertThat(request.checkNotModified(epochTime)).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(304); + assertThat(servletResponse.getDateHeader("Last-Modified") / 1000).isEqualTo(epochTime / 1000); } @Test @@ -290,9 +287,9 @@ public class ServletWebRequestHttpMethodsTests { servletRequest.setMethod("GET"); servletRequest.addHeader("If-Modified-Since", "Wed, 08 Apr 2014 09:57:42 GMT; length=13774"); - assertFalse(request.checkNotModified(epochTime)); - assertEquals(200, servletResponse.getStatus()); - assertEquals(epochTime / 1000, servletResponse.getDateHeader("Last-Modified") / 1000); + assertThat(request.checkNotModified(epochTime)).isFalse(); + assertThat(servletResponse.getStatus()).isEqualTo(200); + assertThat(servletResponse.getDateHeader("Last-Modified") / 1000).isEqualTo(epochTime / 1000); } @Test @@ -302,9 +299,9 @@ public class ServletWebRequestHttpMethodsTests { servletRequest.setMethod("PUT"); servletRequest.addHeader("If-UnModified-Since", currentEpoch); - assertFalse(request.checkNotModified(oneMinuteAgo)); - assertEquals(200, servletResponse.getStatus()); - assertEquals(null, servletResponse.getHeader("Last-Modified")); + assertThat(request.checkNotModified(oneMinuteAgo)).isFalse(); + assertThat(servletResponse.getStatus()).isEqualTo(200); + assertThat(servletResponse.getHeader("Last-Modified")).isEqualTo(null); } @Test @@ -314,9 +311,9 @@ public class ServletWebRequestHttpMethodsTests { servletRequest.setMethod("PUT"); servletRequest.addHeader("If-UnModified-Since", oneMinuteAgo); - assertTrue(request.checkNotModified(currentEpoch)); - assertEquals(412, servletResponse.getStatus()); - assertEquals(null, servletResponse.getHeader("Last-Modified")); + assertThat(request.checkNotModified(currentEpoch)).isTrue(); + assertThat(servletResponse.getStatus()).isEqualTo(412); + assertThat(servletResponse.getHeader("Last-Modified")).isEqualTo(null); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestTests.java b/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestTests.java index 6c1080254a7..cbf47b625c6 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestTests.java @@ -32,9 +32,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.multipart.MultipartRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -62,42 +60,42 @@ public class ServletWebRequestTests { servletRequest.addParameter("param2", "value2"); servletRequest.addParameter("param2", "value2a"); - assertEquals("value1", request.getParameter("param1")); - assertEquals(1, request.getParameterValues("param1").length); - assertEquals("value1", request.getParameterValues("param1")[0]); - assertEquals("value2", request.getParameter("param2")); - assertEquals(2, request.getParameterValues("param2").length); - assertEquals("value2", request.getParameterValues("param2")[0]); - assertEquals("value2a", request.getParameterValues("param2")[1]); + assertThat(request.getParameter("param1")).isEqualTo("value1"); + assertThat(request.getParameterValues("param1").length).isEqualTo(1); + assertThat(request.getParameterValues("param1")[0]).isEqualTo("value1"); + assertThat(request.getParameter("param2")).isEqualTo("value2"); + assertThat(request.getParameterValues("param2").length).isEqualTo(2); + assertThat(request.getParameterValues("param2")[0]).isEqualTo("value2"); + assertThat(request.getParameterValues("param2")[1]).isEqualTo("value2a"); Map paramMap = request.getParameterMap(); - assertEquals(2, paramMap.size()); - assertEquals(1, paramMap.get("param1").length); - assertEquals("value1", paramMap.get("param1")[0]); - assertEquals(2, paramMap.get("param2").length); - assertEquals("value2", paramMap.get("param2")[0]); - assertEquals("value2a", paramMap.get("param2")[1]); + assertThat(paramMap.size()).isEqualTo(2); + assertThat(paramMap.get("param1").length).isEqualTo(1); + assertThat(paramMap.get("param1")[0]).isEqualTo("value1"); + assertThat(paramMap.get("param2").length).isEqualTo(2); + assertThat(paramMap.get("param2")[0]).isEqualTo("value2"); + assertThat(paramMap.get("param2")[1]).isEqualTo("value2a"); } @Test public void locale() { servletRequest.addPreferredLocale(Locale.UK); - assertEquals(Locale.UK, request.getLocale()); + assertThat(request.getLocale()).isEqualTo(Locale.UK); } @Test public void nativeRequest() { - assertSame(servletRequest, request.getNativeRequest()); - assertSame(servletRequest, request.getNativeRequest(ServletRequest.class)); - assertSame(servletRequest, request.getNativeRequest(HttpServletRequest.class)); - assertSame(servletRequest, request.getNativeRequest(MockHttpServletRequest.class)); - assertNull(request.getNativeRequest(MultipartRequest.class)); - assertSame(servletResponse, request.getNativeResponse()); - assertSame(servletResponse, request.getNativeResponse(ServletResponse.class)); - assertSame(servletResponse, request.getNativeResponse(HttpServletResponse.class)); - assertSame(servletResponse, request.getNativeResponse(MockHttpServletResponse.class)); - assertNull(request.getNativeResponse(MultipartRequest.class)); + assertThat(request.getNativeRequest()).isSameAs(servletRequest); + assertThat(request.getNativeRequest(ServletRequest.class)).isSameAs(servletRequest); + assertThat(request.getNativeRequest(HttpServletRequest.class)).isSameAs(servletRequest); + assertThat(request.getNativeRequest(MockHttpServletRequest.class)).isSameAs(servletRequest); + assertThat(request.getNativeRequest(MultipartRequest.class)).isNull(); + assertThat(request.getNativeResponse()).isSameAs(servletResponse); + assertThat(request.getNativeResponse(ServletResponse.class)).isSameAs(servletResponse); + assertThat(request.getNativeResponse(HttpServletResponse.class)).isSameAs(servletResponse); + assertThat(request.getNativeResponse(MockHttpServletResponse.class)).isSameAs(servletResponse); + assertThat(request.getNativeResponse(MultipartRequest.class)).isNull(); } @Test @@ -105,16 +103,16 @@ public class ServletWebRequestTests { HttpServletRequest decoratedRequest = new HttpServletRequestWrapper(servletRequest); HttpServletResponse decoratedResponse = new HttpServletResponseWrapper(servletResponse); ServletWebRequest request = new ServletWebRequest(decoratedRequest, decoratedResponse); - assertSame(decoratedRequest, request.getNativeRequest()); - assertSame(decoratedRequest, request.getNativeRequest(ServletRequest.class)); - assertSame(decoratedRequest, request.getNativeRequest(HttpServletRequest.class)); - assertSame(servletRequest, request.getNativeRequest(MockHttpServletRequest.class)); - assertNull(request.getNativeRequest(MultipartRequest.class)); - assertSame(decoratedResponse, request.getNativeResponse()); - assertSame(decoratedResponse, request.getNativeResponse(ServletResponse.class)); - assertSame(decoratedResponse, request.getNativeResponse(HttpServletResponse.class)); - assertSame(servletResponse, request.getNativeResponse(MockHttpServletResponse.class)); - assertNull(request.getNativeResponse(MultipartRequest.class)); + assertThat(request.getNativeRequest()).isSameAs(decoratedRequest); + assertThat(request.getNativeRequest(ServletRequest.class)).isSameAs(decoratedRequest); + assertThat(request.getNativeRequest(HttpServletRequest.class)).isSameAs(decoratedRequest); + assertThat(request.getNativeRequest(MockHttpServletRequest.class)).isSameAs(servletRequest); + assertThat(request.getNativeRequest(MultipartRequest.class)).isNull(); + assertThat(request.getNativeResponse()).isSameAs(decoratedResponse); + assertThat(request.getNativeResponse(ServletResponse.class)).isSameAs(decoratedResponse); + assertThat(request.getNativeResponse(HttpServletResponse.class)).isSameAs(decoratedResponse); + assertThat(request.getNativeResponse(MockHttpServletResponse.class)).isSameAs(servletResponse); + assertThat(request.getNativeResponse(MultipartRequest.class)).isNull(); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java b/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java index ff886d8138d..3991dd09f29 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java @@ -35,12 +35,7 @@ import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop @@ -82,17 +77,17 @@ public class SessionScopeTests { RequestContextHolder.setRequestAttributes(requestAttributes); String name = "sessionScopedObject"; - assertNull(session.getAttribute(name)); + assertThat(session.getAttribute(name)).isNull(); TestBean bean = (TestBean) this.beanFactory.getBean(name); - assertEquals(1, count.intValue()); - assertEquals(session.getAttribute(name), bean); - assertSame(bean, this.beanFactory.getBean(name)); - assertEquals(1, count.intValue()); + assertThat(count.intValue()).isEqualTo(1); + assertThat(bean).isEqualTo(session.getAttribute(name)); + assertThat(this.beanFactory.getBean(name)).isSameAs(bean); + assertThat(count.intValue()).isEqualTo(1); // should re-propagate updated attribute requestAttributes.requestCompleted(); - assertEquals(session.getAttribute(name), bean); - assertEquals(2, count.intValue()); + assertThat(bean).isEqualTo(session.getAttribute(name)); + assertThat(count.intValue()).isEqualTo(2); } @Test @@ -111,14 +106,14 @@ public class SessionScopeTests { RequestContextHolder.setRequestAttributes(requestAttributes); String name = "sessionScopedObject"; - assertNull(session.getAttribute(name)); + assertThat(session.getAttribute(name)).isNull(); TestBean bean = (TestBean) this.beanFactory.getBean(name); - assertEquals(1, count.intValue()); + assertThat(count.intValue()).isEqualTo(1); // should re-propagate updated attribute requestAttributes.requestCompleted(); - assertEquals(session.getAttribute(name), bean); - assertEquals(2, count.intValue()); + assertThat(bean).isEqualTo(session.getAttribute(name)); + assertThat(count.intValue()).isEqualTo(2); } @Test @@ -130,14 +125,14 @@ public class SessionScopeTests { RequestContextHolder.setRequestAttributes(requestAttributes); String name = "sessionScopedDisposableObject"; - assertNull(session.getAttribute(name)); + assertThat(session.getAttribute(name)).isNull(); DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name); - assertEquals(session.getAttribute(name), bean); - assertSame(bean, this.beanFactory.getBean(name)); + assertThat(bean).isEqualTo(session.getAttribute(name)); + assertThat(this.beanFactory.getBean(name)).isSameAs(bean); requestAttributes.requestCompleted(); session.invalidate(); - assertTrue(bean.wasDestroyed()); + assertThat(bean.wasDestroyed()).isTrue(); } @Test @@ -167,14 +162,14 @@ public class SessionScopeTests { RequestContextHolder.setRequestAttributes(requestAttributes); String name = "sessionScopedDisposableObject"; - assertNull(session.getAttribute(name)); + assertThat(session.getAttribute(name)).isNull(); DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name); - assertEquals(session.getAttribute(name), bean); - assertSame(bean, this.beanFactory.getBean(name)); + assertThat(bean).isEqualTo(session.getAttribute(name)); + assertThat(this.beanFactory.getBean(name)).isSameAs(bean); requestAttributes.requestCompleted(); serializedState = session.serializeState(); - assertFalse(bean.wasDestroyed()); + assertThat(bean.wasDestroyed()).isFalse(); serializedState = (Serializable) SerializationTestUtils.serializeAndDeserialize(serializedState); @@ -186,20 +181,20 @@ public class SessionScopeTests { RequestContextHolder.setRequestAttributes(requestAttributes); name = "sessionScopedDisposableObject"; - assertNotNull(session.getAttribute(name)); + assertThat(session.getAttribute(name)).isNotNull(); bean = (DerivedTestBean) this.beanFactory.getBean(name); - assertEquals(session.getAttribute(name), bean); - assertSame(bean, this.beanFactory.getBean(name)); + assertThat(bean).isEqualTo(session.getAttribute(name)); + assertThat(this.beanFactory.getBean(name)).isSameAs(bean); requestAttributes.requestCompleted(); session.invalidate(); - assertTrue(bean.wasDestroyed()); + assertThat(bean.wasDestroyed()).isTrue(); if (beanNameReset) { - assertNull(bean.getBeanName()); + assertThat(bean.getBeanName()).isNull(); } else { - assertNotNull(bean.getBeanName()); + assertThat(bean.getBeanName()).isNotNull(); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/WebApplicationContextScopeTests.java b/spring-web/src/test/java/org/springframework/web/context/request/WebApplicationContextScopeTests.java index 84f32251f27..a762d14a8e2 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/WebApplicationContextScopeTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/WebApplicationContextScopeTests.java @@ -28,9 +28,7 @@ import org.springframework.web.context.ContextCleanupListener; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -58,12 +56,12 @@ public class WebApplicationContextScopeTests { ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); try { - assertNull(request.getAttribute(NAME)); + assertThat(request.getAttribute(NAME)).isNull(); DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class); - assertSame(bean, request.getAttribute(NAME)); - assertSame(bean, ac.getBean(NAME)); + assertThat(request.getAttribute(NAME)).isSameAs(bean); + assertThat(ac.getBean(NAME)).isSameAs(bean); requestAttributes.requestCompleted(); - assertTrue(bean.wasDestroyed()); + assertThat(bean.wasDestroyed()).isTrue(); } finally { RequestContextHolder.setRequestAttributes(null); @@ -77,12 +75,12 @@ public class WebApplicationContextScopeTests { ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); try { - assertNull(request.getSession().getAttribute(NAME)); + assertThat(request.getSession().getAttribute(NAME)).isNull(); DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class); - assertSame(bean, request.getSession().getAttribute(NAME)); - assertSame(bean, ac.getBean(NAME)); + assertThat(request.getSession().getAttribute(NAME)).isSameAs(bean); + assertThat(ac.getBean(NAME)).isSameAs(bean); request.getSession().invalidate(); - assertTrue(bean.wasDestroyed()); + assertThat(bean.wasDestroyed()).isTrue(); } finally { RequestContextHolder.setRequestAttributes(null); @@ -92,12 +90,12 @@ public class WebApplicationContextScopeTests { @Test public void testApplicationScope() { WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_APPLICATION); - assertNull(ac.getServletContext().getAttribute(NAME)); + assertThat(ac.getServletContext().getAttribute(NAME)).isNull(); DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class); - assertSame(bean, ac.getServletContext().getAttribute(NAME)); - assertSame(bean, ac.getBean(NAME)); + assertThat(ac.getServletContext().getAttribute(NAME)).isSameAs(bean); + assertThat(ac.getBean(NAME)).isSameAs(bean); new ContextCleanupListener().contextDestroyed(new ServletContextEvent(ac.getServletContext())); - assertTrue(bean.wasDestroyed()); + assertThat(bean.wasDestroyed()).isTrue(); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/DeferredResultTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/DeferredResultTests.java index bd14bd24c45..1b7fea4aabe 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/DeferredResultTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/DeferredResultTests.java @@ -22,10 +22,7 @@ import org.junit.Test; import org.springframework.web.context.request.async.DeferredResult.DeferredResultHandler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -43,7 +40,7 @@ public class DeferredResultTests { DeferredResult result = new DeferredResult<>(); result.setResultHandler(handler); - assertTrue(result.setResult("hello")); + assertThat(result.setResult("hello")).isTrue(); verify(handler).handleResult("hello"); } @@ -54,8 +51,8 @@ public class DeferredResultTests { DeferredResult result = new DeferredResult<>(); result.setResultHandler(handler); - assertTrue(result.setResult("hello")); - assertFalse(result.setResult("hi")); + assertThat(result.setResult("hello")).isTrue(); + assertThat(result.setResult("hi")).isFalse(); verify(handler).handleResult("hello"); } @@ -67,11 +64,11 @@ public class DeferredResultTests { DeferredResult result = new DeferredResult<>(); result.setResultHandler(handler); - assertFalse(result.isSetOrExpired()); + assertThat(result.isSetOrExpired()).isFalse(); result.setResult("hello"); - assertTrue(result.isSetOrExpired()); + assertThat(result.isSetOrExpired()).isTrue(); verify(handler).handleResult("hello"); } @@ -83,12 +80,12 @@ public class DeferredResultTests { DeferredResult result = new DeferredResult<>(); result.setResultHandler(handler); - assertFalse(result.hasResult()); - assertNull(result.getResult()); + assertThat(result.hasResult()).isFalse(); + assertThat(result.getResult()).isNull(); result.setResult("hello"); - assertEquals("hello", result.getResult()); + assertThat(result.getResult()).isEqualTo("hello"); } @Test @@ -105,8 +102,8 @@ public class DeferredResultTests { result.getInterceptor().afterCompletion(null, null); - assertTrue(result.isSetOrExpired()); - assertEquals("completion event", sb.toString()); + assertThat(result.isSetOrExpired()).isTrue(); + assertThat(sb.toString()).isEqualTo("completion event"); } @Test @@ -126,8 +123,8 @@ public class DeferredResultTests { result.getInterceptor().handleTimeout(null, null); - assertEquals("timeout event", sb.toString()); - assertFalse("Should not be able to set result a second time", result.setResult("hello")); + assertThat(sb.toString()).isEqualTo("timeout event"); + assertThat(result.setResult("hello")).as("Should not be able to set result a second time").isFalse(); verify(handler).handleResult("timeout result"); } @@ -149,8 +146,8 @@ public class DeferredResultTests { result.getInterceptor().handleError(null, null, e); - assertEquals("error event", sb.toString()); - assertFalse("Should not be able to set result a second time", result.setResult("hello")); + assertThat(sb.toString()).isEqualTo("error event"); + assertThat(result.setResult("hello")).as("Should not be able to set result a second time").isFalse(); verify(handler).handleResult(e); } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java index 9defe742bf2..4c34d6e3efc 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java @@ -26,12 +26,8 @@ import org.springframework.mock.web.test.MockAsyncContext; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -60,9 +56,9 @@ public class StandardServletAsyncWebRequestTests { @Test public void isAsyncStarted() throws Exception { - assertFalse(this.asyncRequest.isAsyncStarted()); + assertThat(this.asyncRequest.isAsyncStarted()).isFalse(); this.asyncRequest.startAsync(); - assertTrue(this.asyncRequest.isAsyncStarted()); + assertThat(this.asyncRequest.isAsyncStarted()).isTrue(); } @Test @@ -70,10 +66,10 @@ public class StandardServletAsyncWebRequestTests { this.asyncRequest.startAsync(); MockAsyncContext context = (MockAsyncContext) this.request.getAsyncContext(); - assertNotNull(context); - assertEquals("Timeout value not set", 44 * 1000, context.getTimeout()); - assertEquals(1, context.getListeners().size()); - assertSame(this.asyncRequest, context.getListeners().get(0)); + assertThat(context).isNotNull(); + assertThat(context.getTimeout()).as("Timeout value not set").isEqualTo((44 * 1000)); + assertThat(context.getListeners().size()).isEqualTo(1); + assertThat(context.getListeners().get(0)).isSameAs(this.asyncRequest); } @Test @@ -84,8 +80,8 @@ public class StandardServletAsyncWebRequestTests { this.asyncRequest.startAsync(); // idempotent MockAsyncContext context = (MockAsyncContext) this.request.getAsyncContext(); - assertNotNull(context); - assertEquals(1, context.getListeners().size()); + assertThat(context).isNotNull(); + assertThat(context.getListeners().size()).isEqualTo(1); } @Test @@ -107,7 +103,7 @@ public class StandardServletAsyncWebRequestTests { @Test public void onTimeoutDefaultBehavior() throws Exception { this.asyncRequest.onTimeout(new AsyncEvent(new MockAsyncContext(this.request, this.response))); - assertEquals(200, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(200); } @Test @@ -144,7 +140,7 @@ public class StandardServletAsyncWebRequestTests { this.asyncRequest.onComplete(new AsyncEvent(this.request.getAsyncContext())); verify(handler).run(); - assertTrue(this.asyncRequest.isAsyncComplete()); + assertThat(this.asyncRequest.isAsyncComplete()).isTrue(); } // SPR-13292 @@ -171,6 +167,6 @@ public class StandardServletAsyncWebRequestTests { this.asyncRequest.onComplete(new AsyncEvent(this.request.getAsyncContext())); verify(handler).run(); - assertTrue(this.asyncRequest.isAsyncComplete()); + assertThat(this.asyncRequest.isAsyncComplete()).isTrue(); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerErrorTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerErrorTests.java index 8e5605dc970..edb534676d4 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerErrorTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerErrorTests.java @@ -29,8 +29,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.context.request.NativeWebRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -84,8 +83,8 @@ public class WebAsyncManagerErrorTests { this.asyncWebRequest.onError(event); this.asyncWebRequest.onComplete(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(e, this.asyncManager.getConcurrentResult()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(e); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, callable); verify(interceptor).afterCompletion(this.asyncWebRequest, callable); @@ -109,9 +108,9 @@ public class WebAsyncManagerErrorTests { AsyncEvent event = new AsyncEvent(new MockAsyncContext(this.servletRequest, this.servletResponse), e); this.asyncWebRequest.onError(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(7, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(7); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); } @Test @@ -129,9 +128,9 @@ public class WebAsyncManagerErrorTests { AsyncEvent event = new AsyncEvent(new MockAsyncContext(this.servletRequest, this.servletResponse), e); this.asyncWebRequest.onError(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(22, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(22); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, callable); } @@ -152,9 +151,9 @@ public class WebAsyncManagerErrorTests { AsyncEvent event = new AsyncEvent(new MockAsyncContext(this.servletRequest, this.servletResponse), e); this.asyncWebRequest.onError(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(exception, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(exception); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, callable); } @@ -175,8 +174,8 @@ public class WebAsyncManagerErrorTests { this.asyncWebRequest.onError(event); this.asyncWebRequest.onComplete(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(e, this.asyncManager.getConcurrentResult()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(e); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, deferredResult); verify(interceptor).preProcess(this.asyncWebRequest, deferredResult); @@ -193,9 +192,9 @@ public class WebAsyncManagerErrorTests { AsyncEvent event = new AsyncEvent(new MockAsyncContext(this.servletRequest, this.servletResponse), e); this.asyncWebRequest.onError(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(e, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(e); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); } @Test @@ -215,9 +214,9 @@ public class WebAsyncManagerErrorTests { AsyncEvent event = new AsyncEvent(new MockAsyncContext(this.servletRequest, this.servletResponse), e); this.asyncWebRequest.onError(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(e, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(e); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); } @Test @@ -241,9 +240,9 @@ public class WebAsyncManagerErrorTests { AsyncEvent event = new AsyncEvent(new MockAsyncContext(this.servletRequest, this.servletResponse), e); this.asyncWebRequest.onError(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(e, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(e); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); } @Test @@ -267,9 +266,9 @@ public class WebAsyncManagerErrorTests { AsyncEvent event = new AsyncEvent(new MockAsyncContext(this.servletRequest, this.servletResponse), e); this.asyncWebRequest.onError(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(e, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(e); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java index ef8a14b5169..51bc66d29a7 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java @@ -27,12 +27,10 @@ import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.mock.web.test.MockHttpServletRequest; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.notNull; import static org.mockito.BDDMockito.given; @@ -84,12 +82,12 @@ public class WebAsyncManagerTests { public void isConcurrentHandlingStarted() { given(this.asyncWebRequest.isAsyncStarted()).willReturn(false); - assertFalse(this.asyncManager.isConcurrentHandlingStarted()); + assertThat(this.asyncManager.isConcurrentHandlingStarted()).isFalse(); reset(this.asyncWebRequest); given(this.asyncWebRequest.isAsyncStarted()).willReturn(true); - assertTrue(this.asyncManager.isConcurrentHandlingStarted()); + assertThat(this.asyncManager.isConcurrentHandlingStarted()).isTrue(); } @Test @@ -112,8 +110,8 @@ public class WebAsyncManagerTests { this.asyncManager.registerCallableInterceptor("interceptor", interceptor); this.asyncManager.startCallableProcessing(task); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(concurrentResult, this.asyncManager.getConcurrentResult()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(concurrentResult); verifyDefaultAsyncScenario(); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, task); @@ -134,8 +132,8 @@ public class WebAsyncManagerTests { this.asyncManager.registerCallableInterceptor("interceptor", interceptor); this.asyncManager.startCallableProcessing(task); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(concurrentResult, this.asyncManager.getConcurrentResult()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(concurrentResult); verifyDefaultAsyncScenario(); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, task); @@ -157,7 +155,7 @@ public class WebAsyncManagerTests { this.asyncManager.startCallableProcessing(task)) .isEqualTo(exception); - assertFalse(this.asyncManager.hasConcurrentResult()); + assertThat(this.asyncManager.hasConcurrentResult()).isFalse(); verify(this.asyncWebRequest).addTimeoutHandler(notNull()); verify(this.asyncWebRequest).addErrorHandler(notNull()); @@ -177,8 +175,8 @@ public class WebAsyncManagerTests { this.asyncManager.registerCallableInterceptor("interceptor", interceptor); this.asyncManager.startCallableProcessing(task); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(exception, this.asyncManager.getConcurrentResult()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(exception); verifyDefaultAsyncScenario(); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, task); @@ -197,8 +195,8 @@ public class WebAsyncManagerTests { this.asyncManager.registerCallableInterceptor("interceptor", interceptor); this.asyncManager.startCallableProcessing(task); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(exception, this.asyncManager.getConcurrentResult()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(exception); verifyDefaultAsyncScenario(); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, task); @@ -219,8 +217,8 @@ public class WebAsyncManagerTests { this.asyncManager.registerCallableInterceptors(interceptor1, interceptor2); this.asyncManager.startCallableProcessing(task); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(exception, this.asyncManager.getConcurrentResult()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(exception); verifyDefaultAsyncScenario(); verify(interceptor1).beforeConcurrentHandling(this.asyncWebRequest, task); @@ -268,7 +266,7 @@ public class WebAsyncManagerTests { deferredResult.setResult(concurrentResult); - assertEquals(concurrentResult, this.asyncManager.getConcurrentResult()); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(concurrentResult); verifyDefaultAsyncScenario(); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, deferredResult); verify(interceptor).preProcess(this.asyncWebRequest, deferredResult); @@ -290,7 +288,7 @@ public class WebAsyncManagerTests { this.asyncManager.startDeferredResultProcessing(deferredResult)) .isEqualTo(exception); - assertFalse(this.asyncManager.hasConcurrentResult()); + assertThat(this.asyncManager.hasConcurrentResult()).isFalse(); verify(this.asyncWebRequest).addTimeoutHandler(notNull()); verify(this.asyncWebRequest).addErrorHandler(notNull()); @@ -313,7 +311,7 @@ public class WebAsyncManagerTests { deferredResult.setResult(25); - assertEquals(exception, this.asyncManager.getConcurrentResult()); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(exception); verifyDefaultAsyncScenario(); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, deferredResult); } @@ -333,7 +331,7 @@ public class WebAsyncManagerTests { deferredResult.setResult(25); - assertEquals(exception, this.asyncManager.getConcurrentResult()); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(exception); verifyDefaultAsyncScenario(); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, deferredResult); verify(interceptor).preProcess(this.asyncWebRequest, deferredResult); diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTimeoutTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTimeoutTests.java index c87d0e32694..5bd37ecee32 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTimeoutTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTimeoutTests.java @@ -29,8 +29,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.context.request.NativeWebRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -85,8 +84,8 @@ public class WebAsyncManagerTimeoutTests { this.asyncWebRequest.onTimeout(ASYNC_EVENT); this.asyncWebRequest.onComplete(ASYNC_EVENT); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(AsyncRequestTimeoutException.class, this.asyncManager.getConcurrentResult().getClass()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult().getClass()).isEqualTo(AsyncRequestTimeoutException.class); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, callable); verify(interceptor).afterCompletion(this.asyncWebRequest, callable); @@ -108,9 +107,9 @@ public class WebAsyncManagerTimeoutTests { this.asyncWebRequest.onTimeout(ASYNC_EVENT); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(7, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(7); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); } @Test @@ -126,9 +125,9 @@ public class WebAsyncManagerTimeoutTests { this.asyncWebRequest.onTimeout(ASYNC_EVENT); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(22, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(22); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, callable); } @@ -147,9 +146,9 @@ public class WebAsyncManagerTimeoutTests { this.asyncWebRequest.onTimeout(ASYNC_EVENT); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(exception, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(exception); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, callable); } @@ -169,7 +168,7 @@ public class WebAsyncManagerTimeoutTests { this.asyncWebRequest.onTimeout(ASYNC_EVENT); - assertTrue(this.asyncManager.hasConcurrentResult()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); verify(future).cancel(true); verifyNoMoreInteractions(future); @@ -189,8 +188,8 @@ public class WebAsyncManagerTimeoutTests { this.asyncWebRequest.onTimeout(ASYNC_EVENT); this.asyncWebRequest.onComplete(ASYNC_EVENT); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(AsyncRequestTimeoutException.class, this.asyncManager.getConcurrentResult().getClass()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult().getClass()).isEqualTo(AsyncRequestTimeoutException.class); verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, deferredResult); verify(interceptor).preProcess(this.asyncWebRequest, deferredResult); @@ -206,9 +205,9 @@ public class WebAsyncManagerTimeoutTests { AsyncEvent event = null; this.asyncWebRequest.onTimeout(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(23, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(23); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); } @Test @@ -227,9 +226,9 @@ public class WebAsyncManagerTimeoutTests { AsyncEvent event = null; this.asyncWebRequest.onTimeout(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(23, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(23); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); } @Test @@ -251,9 +250,9 @@ public class WebAsyncManagerTimeoutTests { AsyncEvent event = null; this.asyncWebRequest.onTimeout(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(23, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(23); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); } @Test @@ -275,9 +274,9 @@ public class WebAsyncManagerTimeoutTests { AsyncEvent event = null; this.asyncWebRequest.onTimeout(event); - assertTrue(this.asyncManager.hasConcurrentResult()); - assertEquals(exception, this.asyncManager.getConcurrentResult()); - assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); + assertThat(this.asyncManager.hasConcurrentResult()).isTrue(); + assertThat(this.asyncManager.getConcurrentResult()).isEqualTo(exception); + assertThat(((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()).isEqualTo("/test"); } diff --git a/spring-web/src/test/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContextTests.java b/spring-web/src/test/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContextTests.java index 58b7e86c5e5..05040d586e8 100644 --- a/spring-web/src/test/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContextTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContextTests.java @@ -25,7 +25,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; /** * @author Chris Beams @@ -41,7 +40,7 @@ public class AnnotationConfigWebApplicationContextTests { ctx.refresh(); TestBean bean = ctx.getBean(TestBean.class); - assertNotNull(bean); + assertThat(bean).isNotNull(); } @Test @@ -52,7 +51,7 @@ public class AnnotationConfigWebApplicationContextTests { ctx.refresh(); TestBean bean = ctx.getBean(TestBean.class); - assertNotNull(bean); + assertThat(bean).isNotNull(); } @Test @@ -63,7 +62,7 @@ public class AnnotationConfigWebApplicationContextTests { ctx.refresh(); TestBean bean = ctx.getBean(TestBean.class); - assertNotNull(bean); + assertThat(bean).isNotNull(); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/context/support/ResourceTests.java b/spring-web/src/test/java/org/springframework/web/context/support/ResourceTests.java index 7bd10b28110..885a70f658a 100644 --- a/spring-web/src/test/java/org/springframework/web/context/support/ResourceTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/support/ResourceTests.java @@ -23,8 +23,7 @@ import org.junit.Test; import org.springframework.core.io.Resource; import org.springframework.mock.web.test.MockServletContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Chris Beams @@ -37,7 +36,7 @@ public class ResourceTests { MockServletContext sc = new MockServletContext(); Resource resource = new ServletContextResource(sc, "org/springframework/core/io/Resource.class"); doTestResource(resource); - assertEquals(resource, new ServletContextResource(sc, "org/springframework/core/../core/io/./Resource.class")); + assertThat(new ServletContextResource(sc, "org/springframework/core/../core/io/./Resource.class")).isEqualTo(resource); } @Test @@ -45,21 +44,21 @@ public class ResourceTests { MockServletContext sc = new MockServletContext(); Resource resource = new ServletContextResource(sc, "dir/"); Resource relative = resource.createRelative("subdir"); - assertEquals(new ServletContextResource(sc, "dir/subdir"), relative); + assertThat(relative).isEqualTo(new ServletContextResource(sc, "dir/subdir")); } private void doTestResource(Resource resource) throws IOException { - assertEquals("Resource.class", resource.getFilename()); - assertTrue(resource.getURL().getFile().endsWith("Resource.class")); + assertThat(resource.getFilename()).isEqualTo("Resource.class"); + assertThat(resource.getURL().getFile().endsWith("Resource.class")).isTrue(); Resource relative1 = resource.createRelative("ClassPathResource.class"); - assertEquals("ClassPathResource.class", relative1.getFilename()); - assertTrue(relative1.getURL().getFile().endsWith("ClassPathResource.class")); - assertTrue(relative1.exists()); + assertThat(relative1.getFilename()).isEqualTo("ClassPathResource.class"); + assertThat(relative1.getURL().getFile().endsWith("ClassPathResource.class")).isTrue(); + assertThat(relative1.exists()).isTrue(); Resource relative2 = resource.createRelative("support/ResourcePatternResolver.class"); - assertEquals("ResourcePatternResolver.class", relative2.getFilename()); - assertTrue(relative2.getURL().getFile().endsWith("ResourcePatternResolver.class")); - assertTrue(relative2.exists()); + assertThat(relative2.getFilename()).isEqualTo("ResourcePatternResolver.class"); + assertThat(relative2.getURL().getFile().endsWith("ResourcePatternResolver.class")).isTrue(); + assertThat(relative2.exists()).isTrue(); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/support/SpringBeanAutowiringSupportTests.java b/spring-web/src/test/java/org/springframework/web/context/support/SpringBeanAutowiringSupportTests.java index a447eaee383..52b408f9102 100644 --- a/spring-web/src/test/java/org/springframework/web/context/support/SpringBeanAutowiringSupportTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/support/SpringBeanAutowiringSupportTests.java @@ -27,8 +27,7 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -51,8 +50,9 @@ public class SpringBeanAutowiringSupportTests { InjectionTarget target = new InjectionTarget(); SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(target, sc); - assertTrue(target.testBean instanceof TestBean); - assertEquals("tb", target.name); + boolean condition = target.testBean instanceof TestBean; + assertThat(condition).isTrue(); + assertThat(target.name).isEqualTo("tb"); } diff --git a/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java b/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java index f028da1e816..0770732fcef 100644 --- a/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java +++ b/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java @@ -24,11 +24,8 @@ import org.junit.Test; import org.springframework.http.HttpMethod; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link CorsConfiguration}. @@ -42,35 +39,35 @@ public class CorsConfigurationTests { public void setNullValues() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(null); - assertNull(config.getAllowedOrigins()); + assertThat(config.getAllowedOrigins()).isNull(); config.setAllowedHeaders(null); - assertNull(config.getAllowedHeaders()); + assertThat(config.getAllowedHeaders()).isNull(); config.setAllowedMethods(null); - assertNull(config.getAllowedMethods()); + assertThat(config.getAllowedMethods()).isNull(); config.setExposedHeaders(null); - assertNull(config.getExposedHeaders()); + assertThat(config.getExposedHeaders()).isNull(); config.setAllowCredentials(null); - assertNull(config.getAllowCredentials()); + assertThat(config.getAllowCredentials()).isNull(); config.setMaxAge((Long) null); - assertNull(config.getMaxAge()); + assertThat(config.getMaxAge()).isNull(); } @Test public void setValues() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); - assertEquals(Arrays.asList("*"), config.getAllowedOrigins()); + assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("*")); config.addAllowedHeader("*"); - assertEquals(Arrays.asList("*"), config.getAllowedHeaders()); + assertThat(config.getAllowedHeaders()).isEqualTo(Arrays.asList("*")); config.addAllowedMethod("*"); - assertEquals(Arrays.asList("*"), config.getAllowedMethods()); + assertThat(config.getAllowedMethods()).isEqualTo(Arrays.asList("*")); config.addExposedHeader("header1"); config.addExposedHeader("header2"); - assertEquals(Arrays.asList("header1", "header2"), config.getExposedHeaders()); + assertThat(config.getExposedHeaders()).isEqualTo(Arrays.asList("header1", "header2")); config.setAllowCredentials(true); - assertTrue(config.getAllowCredentials()); + assertThat((boolean) config.getAllowCredentials()).isTrue(); config.setMaxAge(123L); - assertEquals(new Long(123), config.getMaxAge()); + assertThat(config.getMaxAge()).isEqualTo(new Long(123)); } @Test @@ -92,7 +89,7 @@ public class CorsConfigurationTests { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Arrays.asList("*")); config.combine(null); - assertEquals(Arrays.asList("*"), config.getAllowedOrigins()); + assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("*")); } @Test @@ -106,12 +103,12 @@ public class CorsConfigurationTests { config.setAllowCredentials(true); CorsConfiguration other = new CorsConfiguration(); config = config.combine(other); - assertEquals(Arrays.asList("*"), config.getAllowedOrigins()); - assertEquals(Arrays.asList("header1"), config.getAllowedHeaders()); - assertEquals(Arrays.asList("header3"), config.getExposedHeaders()); - assertEquals(Arrays.asList(HttpMethod.GET.name()), config.getAllowedMethods()); - assertEquals(new Long(123), config.getMaxAge()); - assertTrue(config.getAllowCredentials()); + assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("*")); + assertThat(config.getAllowedHeaders()).isEqualTo(Arrays.asList("header1")); + assertThat(config.getExposedHeaders()).isEqualTo(Arrays.asList("header3")); + assertThat(config.getAllowedMethods()).isEqualTo(Arrays.asList(HttpMethod.GET.name())); + assertThat(config.getMaxAge()).isEqualTo(new Long(123)); + assertThat((boolean) config.getAllowCredentials()).isTrue(); } @Test // SPR-15772 @@ -123,26 +120,26 @@ public class CorsConfigurationTests { other.addAllowedMethod(HttpMethod.PUT.name()); CorsConfiguration combinedConfig = config.combine(other); - assertEquals(Arrays.asList("https://domain.com"), combinedConfig.getAllowedOrigins()); - assertEquals(Arrays.asList("header1"), combinedConfig.getAllowedHeaders()); - assertEquals(Arrays.asList(HttpMethod.PUT.name()), combinedConfig.getAllowedMethods()); + assertThat(combinedConfig.getAllowedOrigins()).isEqualTo(Arrays.asList("https://domain.com")); + assertThat(combinedConfig.getAllowedHeaders()).isEqualTo(Arrays.asList("header1")); + assertThat(combinedConfig.getAllowedMethods()).isEqualTo(Arrays.asList(HttpMethod.PUT.name())); combinedConfig = other.combine(config); - assertEquals(Arrays.asList("https://domain.com"), combinedConfig.getAllowedOrigins()); - assertEquals(Arrays.asList("header1"), combinedConfig.getAllowedHeaders()); - assertEquals(Arrays.asList(HttpMethod.PUT.name()), combinedConfig.getAllowedMethods()); + assertThat(combinedConfig.getAllowedOrigins()).isEqualTo(Arrays.asList("https://domain.com")); + assertThat(combinedConfig.getAllowedHeaders()).isEqualTo(Arrays.asList("header1")); + assertThat(combinedConfig.getAllowedMethods()).isEqualTo(Arrays.asList(HttpMethod.PUT.name())); combinedConfig = config.combine(new CorsConfiguration()); - assertEquals(Arrays.asList("*"), config.getAllowedOrigins()); - assertEquals(Arrays.asList("*"), config.getAllowedHeaders()); - assertEquals(Arrays.asList(HttpMethod.GET.name(), HttpMethod.HEAD.name(), - HttpMethod.POST.name()), combinedConfig.getAllowedMethods()); + assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("*")); + assertThat(config.getAllowedHeaders()).isEqualTo(Arrays.asList("*")); + assertThat(combinedConfig.getAllowedMethods()).isEqualTo(Arrays.asList(HttpMethod.GET.name(), HttpMethod.HEAD.name(), + HttpMethod.POST.name())); combinedConfig = new CorsConfiguration().combine(config); - assertEquals(Arrays.asList("*"), config.getAllowedOrigins()); - assertEquals(Arrays.asList("*"), config.getAllowedHeaders()); - assertEquals(Arrays.asList(HttpMethod.GET.name(), HttpMethod.HEAD.name(), - HttpMethod.POST.name()), combinedConfig.getAllowedMethods()); + assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("*")); + assertThat(config.getAllowedHeaders()).isEqualTo(Arrays.asList("*")); + assertThat(combinedConfig.getAllowedMethods()).isEqualTo(Arrays.asList(HttpMethod.GET.name(), HttpMethod.HEAD.name(), + HttpMethod.POST.name())); } @Test @@ -157,13 +154,13 @@ public class CorsConfigurationTests { other.addExposedHeader("header2"); other.addAllowedMethod(HttpMethod.PUT.name()); CorsConfiguration combinedConfig = config.combine(other); - assertEquals(Arrays.asList("*"), combinedConfig.getAllowedOrigins()); - assertEquals(Arrays.asList("*"), combinedConfig.getAllowedHeaders()); - assertEquals(Arrays.asList("*"), combinedConfig.getAllowedMethods()); + assertThat(combinedConfig.getAllowedOrigins()).isEqualTo(Arrays.asList("*")); + assertThat(combinedConfig.getAllowedHeaders()).isEqualTo(Arrays.asList("*")); + assertThat(combinedConfig.getAllowedMethods()).isEqualTo(Arrays.asList("*")); combinedConfig = other.combine(config); - assertEquals(Arrays.asList("*"), combinedConfig.getAllowedOrigins()); - assertEquals(Arrays.asList("*"), combinedConfig.getAllowedHeaders()); - assertEquals(Arrays.asList("*"), combinedConfig.getAllowedMethods()); + assertThat(combinedConfig.getAllowedOrigins()).isEqualTo(Arrays.asList("*")); + assertThat(combinedConfig.getAllowedHeaders()).isEqualTo(Arrays.asList("*")); + assertThat(combinedConfig.getAllowedMethods()).isEqualTo(Arrays.asList("*")); } @Test // SPR-14792 @@ -183,10 +180,10 @@ public class CorsConfigurationTests { other.addExposedHeader("header3"); other.addAllowedMethod(HttpMethod.GET.name()); CorsConfiguration combinedConfig = config.combine(other); - assertEquals(Arrays.asList("https://domain1.com", "https://domain2.com"), combinedConfig.getAllowedOrigins()); - assertEquals(Arrays.asList("header1", "header2"), combinedConfig.getAllowedHeaders()); - assertEquals(Arrays.asList("header3", "header4"), combinedConfig.getExposedHeaders()); - assertEquals(Arrays.asList(HttpMethod.GET.name(), HttpMethod.PUT.name()), combinedConfig.getAllowedMethods()); + assertThat(combinedConfig.getAllowedOrigins()).isEqualTo(Arrays.asList("https://domain1.com", "https://domain2.com")); + assertThat(combinedConfig.getAllowedHeaders()).isEqualTo(Arrays.asList("header1", "header2")); + assertThat(combinedConfig.getExposedHeaders()).isEqualTo(Arrays.asList("header3", "header4")); + assertThat(combinedConfig.getAllowedMethods()).isEqualTo(Arrays.asList(HttpMethod.GET.name(), HttpMethod.PUT.name())); } @Test @@ -206,83 +203,81 @@ public class CorsConfigurationTests { other.setMaxAge(456L); other.setAllowCredentials(false); config = config.combine(other); - assertEquals(Arrays.asList("https://domain1.com", "https://domain2.com"), config.getAllowedOrigins()); - assertEquals(Arrays.asList("header1", "header2"), config.getAllowedHeaders()); - assertEquals(Arrays.asList("header3", "header4"), config.getExposedHeaders()); - assertEquals(Arrays.asList(HttpMethod.GET.name(), HttpMethod.PUT.name()), config.getAllowedMethods()); - assertEquals(new Long(456), config.getMaxAge()); - assertFalse(config.getAllowCredentials()); + assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("https://domain1.com", "https://domain2.com")); + assertThat(config.getAllowedHeaders()).isEqualTo(Arrays.asList("header1", "header2")); + assertThat(config.getExposedHeaders()).isEqualTo(Arrays.asList("header3", "header4")); + assertThat(config.getAllowedMethods()).isEqualTo(Arrays.asList(HttpMethod.GET.name(), HttpMethod.PUT.name())); + assertThat(config.getMaxAge()).isEqualTo(new Long(456)); + assertThat((boolean) config.getAllowCredentials()).isFalse(); } @Test public void checkOriginAllowed() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Arrays.asList("*")); - assertEquals("*", config.checkOrigin("https://domain.com")); + assertThat(config.checkOrigin("https://domain.com")).isEqualTo("*"); config.setAllowCredentials(true); - assertEquals("https://domain.com", config.checkOrigin("https://domain.com")); + assertThat(config.checkOrigin("https://domain.com")).isEqualTo("https://domain.com"); config.setAllowedOrigins(Arrays.asList("https://domain.com")); - assertEquals("https://domain.com", config.checkOrigin("https://domain.com")); + assertThat(config.checkOrigin("https://domain.com")).isEqualTo("https://domain.com"); config.setAllowCredentials(false); - assertEquals("https://domain.com", config.checkOrigin("https://domain.com")); + assertThat(config.checkOrigin("https://domain.com")).isEqualTo("https://domain.com"); } @Test public void checkOriginNotAllowed() { CorsConfiguration config = new CorsConfiguration(); - assertNull(config.checkOrigin(null)); - assertNull(config.checkOrigin("https://domain.com")); + assertThat(config.checkOrigin(null)).isNull(); + assertThat(config.checkOrigin("https://domain.com")).isNull(); config.addAllowedOrigin("*"); - assertNull(config.checkOrigin(null)); + assertThat(config.checkOrigin(null)).isNull(); config.setAllowedOrigins(Arrays.asList("https://domain1.com")); - assertNull(config.checkOrigin("https://domain2.com")); + assertThat(config.checkOrigin("https://domain2.com")).isNull(); config.setAllowedOrigins(new ArrayList<>()); - assertNull(config.checkOrigin("https://domain.com")); + assertThat(config.checkOrigin("https://domain.com")).isNull(); } @Test public void checkMethodAllowed() { CorsConfiguration config = new CorsConfiguration(); - assertEquals(Arrays.asList(HttpMethod.GET, HttpMethod.HEAD), config.checkHttpMethod(HttpMethod.GET)); + assertThat(config.checkHttpMethod(HttpMethod.GET)).isEqualTo(Arrays.asList(HttpMethod.GET, HttpMethod.HEAD)); config.addAllowedMethod("GET"); - assertEquals(Arrays.asList(HttpMethod.GET), config.checkHttpMethod(HttpMethod.GET)); + assertThat(config.checkHttpMethod(HttpMethod.GET)).isEqualTo(Arrays.asList(HttpMethod.GET)); config.addAllowedMethod("POST"); - assertEquals(Arrays.asList(HttpMethod.GET, HttpMethod.POST), config.checkHttpMethod(HttpMethod.GET)); - assertEquals(Arrays.asList(HttpMethod.GET, HttpMethod.POST), config.checkHttpMethod(HttpMethod.POST)); + assertThat(config.checkHttpMethod(HttpMethod.GET)).isEqualTo(Arrays.asList(HttpMethod.GET, HttpMethod.POST)); + assertThat(config.checkHttpMethod(HttpMethod.POST)).isEqualTo(Arrays.asList(HttpMethod.GET, HttpMethod.POST)); } @Test public void checkMethodNotAllowed() { CorsConfiguration config = new CorsConfiguration(); - assertNull(config.checkHttpMethod(null)); - assertNull(config.checkHttpMethod(HttpMethod.DELETE)); + assertThat(config.checkHttpMethod(null)).isNull(); + assertThat(config.checkHttpMethod(HttpMethod.DELETE)).isNull(); config.setAllowedMethods(new ArrayList<>()); - assertNull(config.checkHttpMethod(HttpMethod.POST)); + assertThat(config.checkHttpMethod(HttpMethod.POST)).isNull(); } @Test public void checkHeadersAllowed() { CorsConfiguration config = new CorsConfiguration(); - assertEquals(Collections.emptyList(), config.checkHeaders(Collections.emptyList())); + assertThat(config.checkHeaders(Collections.emptyList())).isEqualTo(Collections.emptyList()); config.addAllowedHeader("header1"); config.addAllowedHeader("header2"); - assertEquals(Arrays.asList("header1"), config.checkHeaders(Arrays.asList("header1"))); - assertEquals(Arrays.asList("header1", "header2"), - config.checkHeaders(Arrays.asList("header1", "header2"))); - assertEquals(Arrays.asList("header1", "header2"), - config.checkHeaders(Arrays.asList("header1", "header2", "header3"))); + assertThat(config.checkHeaders(Arrays.asList("header1"))).isEqualTo(Arrays.asList("header1")); + assertThat(config.checkHeaders(Arrays.asList("header1", "header2"))).isEqualTo(Arrays.asList("header1", "header2")); + assertThat(config.checkHeaders(Arrays.asList("header1", "header2", "header3"))).isEqualTo(Arrays.asList("header1", "header2")); } @Test public void checkHeadersNotAllowed() { CorsConfiguration config = new CorsConfiguration(); - assertNull(config.checkHeaders(null)); - assertNull(config.checkHeaders(Arrays.asList("header1"))); + assertThat(config.checkHeaders(null)).isNull(); + assertThat(config.checkHeaders(Arrays.asList("header1"))).isNull(); config.setAllowedHeaders(Collections.emptyList()); - assertNull(config.checkHeaders(Arrays.asList("header1"))); + assertThat(config.checkHeaders(Arrays.asList("header1"))).isNull(); config.addAllowedHeader("header2"); config.addAllowedHeader("header3"); - assertNull(config.checkHeaders(Arrays.asList("header1"))); + assertThat(config.checkHeaders(Arrays.asList("header1"))).isNull(); } @Test // SPR-15772 @@ -291,9 +286,9 @@ public class CorsConfigurationTests { config.addAllowedOrigin("https://domain.com"); config.addAllowedHeader("header1"); config.addAllowedMethod("PATCH"); - assertEquals(Arrays.asList("*", "https://domain.com"), config.getAllowedOrigins()); - assertEquals(Arrays.asList("*", "header1"), config.getAllowedHeaders()); - assertEquals(Arrays.asList("GET", "HEAD", "POST", "PATCH"), config.getAllowedMethods()); + assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("*", "https://domain.com")); + assertThat(config.getAllowedHeaders()).isEqualTo(Arrays.asList("*", "header1")); + assertThat(config.getAllowedMethods()).isEqualTo(Arrays.asList("GET", "HEAD", "POST", "PATCH")); } } diff --git a/spring-web/src/test/java/org/springframework/web/cors/CorsUtilsTests.java b/spring-web/src/test/java/org/springframework/web/cors/CorsUtilsTests.java index 1f8d6a46b46..57faad68e43 100644 --- a/spring-web/src/test/java/org/springframework/web/cors/CorsUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/cors/CorsUtilsTests.java @@ -22,8 +22,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.mock.web.test.MockHttpServletRequest; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test case for {@link CorsUtils}. @@ -36,13 +35,13 @@ public class CorsUtilsTests { public void isCorsRequest() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.ORIGIN, "https://domain.com"); - assertTrue(CorsUtils.isCorsRequest(request)); + assertThat(CorsUtils.isCorsRequest(request)).isTrue(); } @Test public void isNotCorsRequest() { MockHttpServletRequest request = new MockHttpServletRequest(); - assertFalse(CorsUtils.isCorsRequest(request)); + assertThat(CorsUtils.isCorsRequest(request)).isFalse(); } @Test @@ -51,18 +50,18 @@ public class CorsUtilsTests { request.setMethod(HttpMethod.OPTIONS.name()); request.addHeader(HttpHeaders.ORIGIN, "https://domain.com"); request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); - assertTrue(CorsUtils.isPreFlightRequest(request)); + assertThat(CorsUtils.isPreFlightRequest(request)).isTrue(); } @Test public void isNotPreFlightRequest() { MockHttpServletRequest request = new MockHttpServletRequest(); - assertFalse(CorsUtils.isPreFlightRequest(request)); + assertThat(CorsUtils.isPreFlightRequest(request)).isFalse(); request = new MockHttpServletRequest(); request.setMethod(HttpMethod.OPTIONS.name()); request.addHeader(HttpHeaders.ORIGIN, "https://domain.com"); - assertFalse(CorsUtils.isPreFlightRequest(request)); + assertThat(CorsUtils.isPreFlightRequest(request)).isFalse(); } } diff --git a/spring-web/src/test/java/org/springframework/web/cors/DefaultCorsProcessorTests.java b/spring-web/src/test/java/org/springframework/web/cors/DefaultCorsProcessorTests.java index 19d6a57cebd..a9c9c21c3c0 100644 --- a/spring-web/src/test/java/org/springframework/web/cors/DefaultCorsProcessorTests.java +++ b/spring-web/src/test/java/org/springframework/web/cors/DefaultCorsProcessorTests.java @@ -27,9 +27,6 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Test {@link DefaultCorsProcessor} with simple or preflight CORS request. @@ -65,10 +62,10 @@ public class DefaultCorsProcessorTests { this.request.setMethod(HttpMethod.GET.name()); this.processor.processRequest(this.conf, this.request, this.response); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -77,10 +74,10 @@ public class DefaultCorsProcessorTests { this.request.addHeader(HttpHeaders.ORIGIN, "http://domain1.com"); this.processor.processRequest(this.conf, this.request, this.response); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -89,10 +86,10 @@ public class DefaultCorsProcessorTests { this.request.addHeader(HttpHeaders.ORIGIN, "https://domain2.com"); this.processor.processRequest(this.conf, this.request, this.response); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN); } @Test @@ -101,8 +98,8 @@ public class DefaultCorsProcessorTests { this.request.addHeader(HttpHeaders.ORIGIN, "https://domain2.com"); this.processor.processRequest(null, this.request, this.response); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -112,13 +109,13 @@ public class DefaultCorsProcessorTests { this.conf.addAllowedOrigin("*"); this.processor.processRequest(this.conf, this.request, this.response); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("*", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE)); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*"); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE)).isFalse(); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).isFalse(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -131,13 +128,13 @@ public class DefaultCorsProcessorTests { this.conf.setAllowCredentials(true); this.processor.processRequest(this.conf, this.request, this.response); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("https://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertEquals("true", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isEqualTo("true"); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -148,13 +145,13 @@ public class DefaultCorsProcessorTests { this.conf.setAllowCredentials(true); this.processor.processRequest(this.conf, this.request, this.response); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("https://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertEquals("true", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isEqualTo("true"); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -164,10 +161,10 @@ public class DefaultCorsProcessorTests { this.conf.addAllowedOrigin("https://DOMAIN2.com"); this.processor.processRequest(this.conf, this.request, this.response); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -179,14 +176,14 @@ public class DefaultCorsProcessorTests { this.conf.addAllowedOrigin("https://domain2.com"); this.processor.processRequest(this.conf, this.request, this.response); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("https://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); - assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header1")); - assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header2")); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header1")).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header2")).isTrue(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -199,7 +196,7 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -212,7 +209,7 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN); } @Test @@ -223,8 +220,8 @@ public class DefaultCorsProcessorTests { this.conf.addAllowedOrigin("*"); this.processor.processRequest(this.conf, this.request, this.response); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); - assertEquals("GET,HEAD", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)).isEqualTo("GET,HEAD"); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); } @@ -235,10 +232,10 @@ public class DefaultCorsProcessorTests { this.request.addHeader(HttpHeaders.ORIGIN, "https://domain2.com"); this.processor.processRequest(this.conf, this.request, this.response); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN); } @Test @@ -248,10 +245,10 @@ public class DefaultCorsProcessorTests { this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Header1"); this.processor.processRequest(this.conf, this.request, this.response); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN); } @Test @@ -262,10 +259,10 @@ public class DefaultCorsProcessorTests { this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Header1"); this.processor.processRequest(this.conf, this.request, this.response); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN); } @Test @@ -281,14 +278,14 @@ public class DefaultCorsProcessorTests { this.conf.addAllowedHeader("header2"); this.processor.processRequest(this.conf, this.request, this.response); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("*", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); - assertEquals("GET,PUT", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*"); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)).isEqualTo("GET,PUT"); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE)).isFalse(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -304,13 +301,13 @@ public class DefaultCorsProcessorTests { this.conf.setAllowCredentials(true); this.processor.processRequest(this.conf, this.request, this.response); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("https://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertEquals("true", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isEqualTo("true"); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -326,11 +323,11 @@ public class DefaultCorsProcessorTests { this.conf.setAllowCredentials(true); this.processor.processRequest(this.conf, this.request, this.response); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("https://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -345,14 +342,14 @@ public class DefaultCorsProcessorTests { this.conf.addAllowedOrigin("https://domain2.com"); this.processor.processRequest(this.conf, this.request, this.response); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)); - assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")); - assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")); - assertFalse(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header3")); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header3")).isFalse(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -365,14 +362,14 @@ public class DefaultCorsProcessorTests { this.conf.addAllowedOrigin("https://domain2.com"); this.processor.processRequest(this.conf, this.request, this.response); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)); - assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")); - assertTrue(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")); - assertFalse(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("*")); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")).isTrue(); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS).contains("*")).isFalse(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -385,11 +382,11 @@ public class DefaultCorsProcessorTests { this.conf.addAllowedOrigin("https://domain2.com"); this.processor.processRequest(this.conf, this.request, this.response); - assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).isFalse(); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -400,8 +397,8 @@ public class DefaultCorsProcessorTests { this.conf.addAllowedOrigin("*"); this.processor.processRequest(null, this.request, this.response); - assertFalse(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals(HttpServletResponse.SC_FORBIDDEN, this.response.getStatus()); + assertThat(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN); } } diff --git a/spring-web/src/test/java/org/springframework/web/cors/UrlBasedCorsConfigurationSourceTests.java b/spring-web/src/test/java/org/springframework/web/cors/UrlBasedCorsConfigurationSourceTests.java index f4fda927063..71d25291f63 100644 --- a/spring-web/src/test/java/org/springframework/web/cors/UrlBasedCorsConfigurationSourceTests.java +++ b/spring-web/src/test/java/org/springframework/web/cors/UrlBasedCorsConfigurationSourceTests.java @@ -21,9 +21,8 @@ import org.junit.Test; import org.springframework.http.HttpMethod; import org.springframework.mock.web.test.MockHttpServletRequest; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * Unit tests for {@link UrlBasedCorsConfigurationSource}. @@ -36,7 +35,7 @@ public class UrlBasedCorsConfigurationSourceTests { @Test public void empty() { MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "/bar/test.html"); - assertNull(this.configSource.getCorsConfiguration(request)); + assertThat(this.configSource.getCorsConfiguration(request)).isNull(); } @Test @@ -45,10 +44,10 @@ public class UrlBasedCorsConfigurationSourceTests { this.configSource.registerCorsConfiguration("/bar/**", config); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo/test.html"); - assertNull(this.configSource.getCorsConfiguration(request)); + assertThat(this.configSource.getCorsConfiguration(request)).isNull(); request.setRequestURI("/bar/test.html"); - assertEquals(config, this.configSource.getCorsConfiguration(request)); + assertThat(this.configSource.getCorsConfiguration(request)).isEqualTo(config); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/cors/reactive/CorsUtilsTests.java b/spring-web/src/test/java/org/springframework/web/cors/reactive/CorsUtilsTests.java index 6cc31fe0ccd..90eb655e0d9 100644 --- a/spring-web/src/test/java/org/springframework/web/cors/reactive/CorsUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/cors/reactive/CorsUtilsTests.java @@ -26,8 +26,7 @@ import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.options; @@ -41,13 +40,13 @@ public class CorsUtilsTests { @Test public void isCorsRequest() { ServerHttpRequest request = get("http://domain.com/").header(HttpHeaders.ORIGIN, "https://domain.com").build(); - assertTrue(CorsUtils.isCorsRequest(request)); + assertThat(CorsUtils.isCorsRequest(request)).isTrue(); } @Test public void isNotCorsRequest() { ServerHttpRequest request = get("/").build(); - assertFalse(CorsUtils.isCorsRequest(request)); + assertThat(CorsUtils.isCorsRequest(request)).isFalse(); } @Test @@ -56,16 +55,16 @@ public class CorsUtilsTests { .header(HttpHeaders.ORIGIN, "https://domain.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .build(); - assertTrue(CorsUtils.isPreFlightRequest(request)); + assertThat(CorsUtils.isPreFlightRequest(request)).isTrue(); } @Test public void isNotPreFlightRequest() { ServerHttpRequest request = get("/").build(); - assertFalse(CorsUtils.isPreFlightRequest(request)); + assertThat(CorsUtils.isPreFlightRequest(request)).isFalse(); request = options("/").header(HttpHeaders.ORIGIN, "https://domain.com").build(); - assertFalse(CorsUtils.isPreFlightRequest(request)); + assertThat(CorsUtils.isPreFlightRequest(request)).isFalse(); } @Test // SPR-16262 @@ -97,7 +96,7 @@ public class CorsUtilsTests { .get("http://mydomain1.com") .header(HttpHeaders.ORIGIN, "https://mydomain1.com") .build(); - assertFalse(CorsUtils.isSameOrigin(request)); + assertThat(CorsUtils.isSameOrigin(request)).isFalse(); } @SuppressWarnings("deprecation") @@ -121,7 +120,7 @@ public class CorsUtilsTests { } ServerHttpRequest request = adaptFromForwardedHeaders(builder); - assertTrue(CorsUtils.isSameOrigin(request)); + assertThat(CorsUtils.isSameOrigin(request)).isTrue(); } @SuppressWarnings("deprecation") @@ -138,7 +137,7 @@ public class CorsUtilsTests { .header(HttpHeaders.ORIGIN, originHeader); ServerHttpRequest request = adaptFromForwardedHeaders(builder); - assertTrue(CorsUtils.isSameOrigin(request)); + assertThat(CorsUtils.isSameOrigin(request)).isTrue(); } // SPR-16668 diff --git a/spring-web/src/test/java/org/springframework/web/cors/reactive/CorsWebFilterTests.java b/spring-web/src/test/java/org/springframework/web/cors/reactive/CorsWebFilterTests.java index c2290ff080c..0254a016a32 100644 --- a/spring-web/src/test/java/org/springframework/web/cors/reactive/CorsWebFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/cors/reactive/CorsWebFilterTests.java @@ -31,8 +31,7 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.server.WebFilterChain; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS; import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN; import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS; @@ -68,8 +67,8 @@ public class CorsWebFilterTests { WebFilterChain filterChain = filterExchange -> { try { HttpHeaders headers = filterExchange.getResponse().getHeaders(); - assertNull(headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertNull(headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS)); + assertThat(headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isNull(); + assertThat(headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS)).isNull(); } catch (AssertionError ex) { return Mono.error(ex); @@ -89,8 +88,8 @@ public class CorsWebFilterTests { WebFilterChain filterChain = filterExchange -> { try { HttpHeaders headers = filterExchange.getResponse().getHeaders(); - assertNull(headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertNull(headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS)); + assertThat(headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isNull(); + assertThat(headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS)).isNull(); } catch (AssertionError ex) { return Mono.error(ex); @@ -110,8 +109,8 @@ public class CorsWebFilterTests { WebFilterChain filterChain = filterExchange -> { try { HttpHeaders headers = filterExchange.getResponse().getHeaders(); - assertEquals("https://domain2.com", headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("header3, header4", headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS)); + assertThat(headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS)).isEqualTo("header3, header4"); } catch (AssertionError ex) { return Mono.error(ex); @@ -140,7 +139,7 @@ public class CorsWebFilterTests { WebFilterChain filterChain = filterExchange -> Mono.error( new AssertionError("Invalid requests must not be forwarded to the filter chain")); filter.filter(exchange, filterChain).block(); - assertNull(exchange.getResponse().getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(exchange.getResponse().getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isNull(); } @Test @@ -160,10 +159,10 @@ public class CorsWebFilterTests { filter.filter(exchange, filterChain).block(); HttpHeaders headers = exchange.getResponse().getHeaders(); - assertEquals("https://domain2.com", headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("header1, header2", headers.getFirst(ACCESS_CONTROL_ALLOW_HEADERS)); - assertEquals("header3, header4", headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS)); - assertEquals(123L, Long.parseLong(headers.getFirst(ACCESS_CONTROL_MAX_AGE))); + assertThat(headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(headers.getFirst(ACCESS_CONTROL_ALLOW_HEADERS)).isEqualTo("header1, header2"); + assertThat(headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS)).isEqualTo("header3, header4"); + assertThat(Long.parseLong(headers.getFirst(ACCESS_CONTROL_MAX_AGE))).isEqualTo(123L); } @Test @@ -182,7 +181,7 @@ public class CorsWebFilterTests { filter.filter(exchange, filterChain).block(); - assertNull(exchange.getResponse().getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(exchange.getResponse().getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isNull(); } } diff --git a/spring-web/src/test/java/org/springframework/web/cors/reactive/DefaultCorsProcessorTests.java b/spring-web/src/test/java/org/springframework/web/cors/reactive/DefaultCorsProcessorTests.java index 64949a433e0..71f214ca599 100644 --- a/spring-web/src/test/java/org/springframework/web/cors/reactive/DefaultCorsProcessorTests.java +++ b/spring-web/src/test/java/org/springframework/web/cors/reactive/DefaultCorsProcessorTests.java @@ -29,10 +29,6 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS; import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN; import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS; @@ -68,10 +64,10 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -84,10 +80,10 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -96,10 +92,10 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test @@ -108,8 +104,8 @@ public class DefaultCorsProcessorTests { this.processor.process(null, exchange); ServerHttpResponse response = exchange.getResponse(); - assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertNull(response.getStatusCode()); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -119,13 +115,13 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("*", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertFalse(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_MAX_AGE)); - assertFalse(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*"); + assertThat(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_MAX_AGE)).isFalse(); + assertThat(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).isFalse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -138,13 +134,13 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isTrue(); + assertThat(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isEqualTo("true"); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -155,13 +151,13 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isTrue(); + assertThat(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isEqualTo("true"); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -171,10 +167,10 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -186,14 +182,14 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); - assertTrue(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header1")); - assertTrue(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header2")); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).isTrue(); + assertThat(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header1")).isTrue(); + assertThat(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header2")).isTrue(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -206,7 +202,7 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @@ -220,7 +216,7 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test @@ -231,10 +227,10 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals("GET,HEAD", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); + assertThat(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)).isEqualTo("GET,HEAD"); } @Test @@ -243,10 +239,10 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test @@ -256,10 +252,10 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test @@ -271,10 +267,10 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test @@ -292,14 +288,14 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("*", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); - assertEquals("GET,PUT", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)); - assertFalse(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_MAX_AGE)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*"); + assertThat(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)).isTrue(); + assertThat(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)).isEqualTo("GET,PUT"); + assertThat(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_MAX_AGE)).isFalse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -317,13 +313,13 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); - assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isTrue(); + assertThat(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isEqualTo("true"); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -341,11 +337,11 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -362,14 +358,14 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS)); - assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")); - assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")); - assertFalse(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header3")); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS)).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header3")).isFalse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -384,14 +380,14 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS)); - assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")); - assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")); - assertFalse(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("*")); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS)).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1")).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2")).isTrue(); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("*")).isFalse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -406,11 +402,11 @@ public class DefaultCorsProcessorTests { this.processor.process(this.conf, exchange); ServerHttpResponse response = exchange.getResponse(); - assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS)); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isTrue(); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS)).isFalse(); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); - assertNull(response.getStatusCode()); + assertThat((Object) response.getStatusCode()).isNull(); } @Test @@ -421,8 +417,8 @@ public class DefaultCorsProcessorTests { this.processor.process(null, exchange); ServerHttpResponse response = exchange.getResponse(); - assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + assertThat(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN)).isFalse(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } diff --git a/spring-web/src/test/java/org/springframework/web/cors/reactive/UrlBasedCorsConfigurationSourceTests.java b/spring-web/src/test/java/org/springframework/web/cors/reactive/UrlBasedCorsConfigurationSourceTests.java index 9b8e81d02c4..34f1de0a3a0 100644 --- a/spring-web/src/test/java/org/springframework/web/cors/reactive/UrlBasedCorsConfigurationSourceTests.java +++ b/spring-web/src/test/java/org/springframework/web/cors/reactive/UrlBasedCorsConfigurationSourceTests.java @@ -22,8 +22,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.cors.CorsConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link UrlBasedCorsConfigurationSource}. @@ -40,7 +39,7 @@ public class UrlBasedCorsConfigurationSourceTests { @Test public void empty() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/bar/test.html")); - assertNull(this.configSource.getCorsConfiguration(exchange)); + assertThat(this.configSource.getCorsConfiguration(exchange)).isNull(); } @Test @@ -49,10 +48,10 @@ public class UrlBasedCorsConfigurationSourceTests { this.configSource.registerCorsConfiguration("/bar/**", config); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/foo/test.html")); - assertNull(this.configSource.getCorsConfiguration(exchange)); + assertThat(this.configSource.getCorsConfiguration(exchange)).isNull(); exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/bar/test.html")); - assertEquals(config, this.configSource.getCorsConfiguration(exchange)); + assertThat(this.configSource.getCorsConfiguration(exchange)).isEqualTo(config); } } diff --git a/spring-web/src/test/java/org/springframework/web/filter/CompositeFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/CompositeFilterTests.java index 4d933ae0ebc..c2a02176d37 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/CompositeFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/CompositeFilterTests.java @@ -33,9 +33,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.mock.web.test.MockServletContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -56,11 +54,11 @@ public class CompositeFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertNotNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNotNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } diff --git a/spring-web/src/test/java/org/springframework/web/filter/CorsFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/CorsFilterTests.java index 4d35e915b40..3b73b370a18 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/CorsFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/CorsFilterTests.java @@ -30,9 +30,8 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.cors.CorsConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * Unit tests for {@link CorsFilter}. @@ -62,8 +61,8 @@ public class CorsFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertNull(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertNull(response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); + assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isNull(); + assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).isNull(); }; filter.doFilter(request, response, filterChain); } @@ -79,8 +78,8 @@ public class CorsFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertNull(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertNull(response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); + assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isNull(); + assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).isNull(); }; filter.doFilter(request, response, filterChain); } @@ -94,8 +93,8 @@ public class CorsFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertEquals("https://domain2.com", response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("header3, header4", response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); + assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).isEqualTo("header3, header4"); }; filter.doFilter(request, response, filterChain); } @@ -111,7 +110,7 @@ public class CorsFilterTests { FilterChain filterChain = (filterRequest, filterResponse) -> fail("Invalid requests must not be forwarded to the filter chain"); filter.doFilter(request, response, filterChain); - assertNull(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isNull(); } @Test @@ -127,10 +126,10 @@ public class CorsFilterTests { fail("Preflight requests must not be forwarded to the filter chain"); filter.doFilter(request, response, filterChain); - assertEquals("https://domain2.com", response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("header1, header2", response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)); - assertEquals("header3, header4", response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); - assertEquals(123L, Long.parseLong(response.getHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE))); + assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).isEqualTo("header1, header2"); + assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).isEqualTo("header3, header4"); + assertThat(Long.parseLong(response.getHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE))).isEqualTo(123L); } @Test @@ -146,7 +145,7 @@ public class CorsFilterTests { fail("Preflight requests must not be forwarded to the filter chain"); filter.doFilter(request, response, filterChain); - assertNull(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isNull(); } } diff --git a/spring-web/src/test/java/org/springframework/web/filter/DelegatingFilterProxyTests.java b/spring-web/src/test/java/org/springframework/web/filter/DelegatingFilterProxyTests.java index 7b45e97747c..a55a78396fe 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/DelegatingFilterProxyTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/DelegatingFilterProxyTests.java @@ -34,9 +34,8 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StaticWebApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * @author Juergen Hoeller @@ -67,11 +66,11 @@ public class DelegatingFilterProxyTests { MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } @Test @@ -96,11 +95,11 @@ public class DelegatingFilterProxyTests { MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } @Test @@ -114,11 +113,11 @@ public class DelegatingFilterProxyTests { MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } @Test @@ -140,11 +139,11 @@ public class DelegatingFilterProxyTests { MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } @Test @@ -168,11 +167,11 @@ public class DelegatingFilterProxyTests { MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter"); - assertNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } @Test @@ -210,11 +209,11 @@ public class DelegatingFilterProxyTests { MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } @Test @@ -238,11 +237,11 @@ public class DelegatingFilterProxyTests { MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } @Test @@ -262,17 +261,17 @@ public class DelegatingFilterProxyTests { proxyConfig.addInitParameter("targetFilterLifecycle", "true"); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(); filterProxy.init(proxyConfig); - assertEquals(proxyConfig, targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isEqualTo(proxyConfig); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertEquals(proxyConfig, targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isEqualTo(proxyConfig); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } @Test @@ -295,11 +294,11 @@ public class DelegatingFilterProxyTests { MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } @Test @@ -324,11 +323,11 @@ public class DelegatingFilterProxyTests { MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } @Test @@ -360,11 +359,11 @@ public class DelegatingFilterProxyTests { MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } @Test @@ -392,11 +391,11 @@ public class DelegatingFilterProxyTests { MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); - assertNull(targetFilter.filterConfig); - assertEquals(Boolean.TRUE, request.getAttribute("called")); + assertThat(targetFilter.filterConfig).isNull(); + assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); - assertNull(targetFilter.filterConfig); + assertThat(targetFilter.filterConfig).isNull(); } diff --git a/spring-web/src/test/java/org/springframework/web/filter/FormContentFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/FormContentFilterTests.java index cb69ee72eb5..d82590472b5 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/FormContentFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/FormContentFilterTests.java @@ -29,11 +29,7 @@ import org.springframework.mock.web.test.MockFilterChain; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link FormContentFilter}. @@ -69,10 +65,10 @@ public class FormContentFilterTests { this.filterChain = new MockFilterChain(); this.filter.doFilter(request, this.response, this.filterChain); if (method == HttpMethod.PUT || method == HttpMethod.PATCH || method == HttpMethod.DELETE) { - assertNotSame(request, this.filterChain.getRequest()); + assertThat(this.filterChain.getRequest()).isNotSameAs(request); } else { - assertSame(request, this.filterChain.getRequest()); + assertThat(this.filterChain.getRequest()).isSameAs(request); } } } @@ -86,7 +82,7 @@ public class FormContentFilterTests { request.setContentType(contentType); this.filterChain = new MockFilterChain(); this.filter.doFilter(request, this.response, this.filterChain); - assertSame(request, this.filterChain.getRequest()); + assertThat(this.filterChain.getRequest()).isSameAs(request); } } @@ -96,7 +92,7 @@ public class FormContentFilterTests { this.request.setContentType("foo"); this.filterChain = new MockFilterChain(); this.filter.doFilter(this.request, this.response, this.filterChain); - assertSame(this.request, this.filterChain.getRequest()); + assertThat(this.filterChain.getRequest()).isSameAs(this.request); } @Test @@ -104,7 +100,7 @@ public class FormContentFilterTests { this.request.setContent("name=value".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); - assertEquals("value", this.filterChain.getRequest().getParameter("name")); + assertThat(this.filterChain.getRequest().getParameter("name")).isEqualTo("value"); } @Test @@ -113,9 +109,8 @@ public class FormContentFilterTests { this.request.setContent("name=value2".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); - assertNotSame("Request not wrapped", this.request, this.filterChain.getRequest()); - assertEquals("Query string parameters should be listed ahead of form parameters", - "value1", this.filterChain.getRequest().getParameter("name")); + assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); + assertThat(this.filterChain.getRequest().getParameter("name")).as("Query string parameters should be listed ahead of form parameters").isEqualTo("value1"); } @Test @@ -123,8 +118,8 @@ public class FormContentFilterTests { this.request.setContent("name=value".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); - assertNotSame("Request not wrapped", this.request, this.filterChain.getRequest()); - assertNull(this.filterChain.getRequest().getParameter("noSuchParam")); + assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); + assertThat(this.filterChain.getRequest().getParameter("noSuchParam")).isNull(); } @Test @@ -136,8 +131,8 @@ public class FormContentFilterTests { this.filter.doFilter(this.request, this.response, this.filterChain); List names = Collections.list(this.filterChain.getRequest().getParameterNames()); - assertNotSame("Request not wrapped", this.request, this.filterChain.getRequest()); - assertEquals(Arrays.asList("name1", "name2", "name3", "name4"), names); + assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); + assertThat(names).isEqualTo(Arrays.asList("name1", "name2", "name3", "name4")); } @Test @@ -150,8 +145,8 @@ public class FormContentFilterTests { this.filter.doFilter(this.request, this.response, this.filterChain); String[] values = this.filterChain.getRequest().getParameterValues("name"); - assertNotSame("Request not wrapped", this.request, filterChain.getRequest()); - assertArrayEquals(new String[] {"value1", "value2", "value3", "value4"}, values); + assertThat(filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); + assertThat(values).isEqualTo(new String[] {"value1", "value2", "value3", "value4"}); } @Test @@ -164,8 +159,8 @@ public class FormContentFilterTests { this.filter.doFilter(this.request, this.response, this.filterChain); String[] values = this.filterChain.getRequest().getParameterValues("name"); - assertNotSame("Request not wrapped", this.request, this.filterChain.getRequest()); - assertArrayEquals(new String[] {"value1", "value2"}, values); + assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); + assertThat(values).isEqualTo(new String[] {"value1", "value2"}); } @Test @@ -177,8 +172,8 @@ public class FormContentFilterTests { this.filter.doFilter(this.request, this.response, this.filterChain); String[] values = this.filterChain.getRequest().getParameterValues("anotherName"); - assertNotSame("Request not wrapped", this.request, this.filterChain.getRequest()); - assertArrayEquals(new String[] {"anotherValue"}, values); + assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); + assertThat(values).isEqualTo(new String[] {"anotherValue"}); } @Test @@ -190,8 +185,8 @@ public class FormContentFilterTests { this.filter.doFilter(this.request, this.response, this.filterChain); String[] values = this.filterChain.getRequest().getParameterValues("noSuchParameter"); - assertNotSame("Request not wrapped", this.request, this.filterChain.getRequest()); - assertNull(values); + assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); + assertThat(values).isNull(); } @Test @@ -204,10 +199,10 @@ public class FormContentFilterTests { this.filter.doFilter(this.request, this.response, this.filterChain); Map parameters = this.filterChain.getRequest().getParameterMap(); - assertNotSame("Request not wrapped", this.request, this.filterChain.getRequest()); - assertEquals(2, parameters.size()); - assertArrayEquals(new String[] {"value1", "value2", "value3"}, parameters.get("name")); - assertArrayEquals(new String[] {"value4"}, parameters.get("name4")); + assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); + assertThat(parameters.size()).isEqualTo(2); + assertThat(parameters.get("name")).isEqualTo(new String[] {"value1", "value2", "value3"}); + assertThat(parameters.get("name4")).isEqualTo(new String[] {"value4"}); } @Test // SPR-15835 @@ -216,8 +211,7 @@ public class FormContentFilterTests { this.request.addParameter("hiddenField", "testHidden"); this.filter.doFilter(this.request, this.response, this.filterChain); - assertArrayEquals(new String[] {"testHidden"}, - this.filterChain.getRequest().getParameterValues("hiddenField")); + assertThat(this.filterChain.getRequest().getParameterValues("hiddenField")).isEqualTo(new String[] {"testHidden"}); } } diff --git a/spring-web/src/test/java/org/springframework/web/filter/ForwardedHeaderFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/ForwardedHeaderFilterTests.java index d0295bd596f..8b3084da4bc 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/ForwardedHeaderFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/ForwardedHeaderFilterTests.java @@ -33,11 +33,7 @@ import org.springframework.mock.web.test.MockFilterChain; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -77,19 +73,19 @@ public class ForwardedHeaderFilterTests { @Test public void contextPathEmpty() throws Exception { this.request.addHeader(X_FORWARDED_PREFIX, ""); - assertEquals("", filterAndGetContextPath()); + assertThat(filterAndGetContextPath()).isEqualTo(""); } @Test public void contextPathWithTrailingSlash() throws Exception { this.request.addHeader(X_FORWARDED_PREFIX, "/foo/bar/"); - assertEquals("/foo/bar", filterAndGetContextPath()); + assertThat(filterAndGetContextPath()).isEqualTo("/foo/bar"); } @Test public void contextPathWithTrailingSlashes() throws Exception { this.request.addHeader(X_FORWARDED_PREFIX, "/foo/bar/baz///"); - assertEquals("/foo/bar/baz", filterAndGetContextPath()); + assertThat(filterAndGetContextPath()).isEqualTo("/foo/bar/baz"); } @Test @@ -98,7 +94,7 @@ public class ForwardedHeaderFilterTests { this.request.setContextPath("/mvc-showcase"); String actual = filterAndGetContextPath(); - assertEquals("/prefix", actual); + assertThat(actual).isEqualTo("/prefix"); } @Test @@ -107,7 +103,7 @@ public class ForwardedHeaderFilterTests { this.request.setContextPath("/mvc-showcase"); String actual = filterAndGetContextPath(); - assertEquals("/prefix", actual); + assertThat(actual).isEqualTo("/prefix"); } private String filterAndGetContextPath() throws ServletException, IOException { @@ -127,9 +123,9 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/app%20/path/"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertEquals("/app%20", actual.getContextPath()); - assertEquals("/app%20/path/", actual.getRequestURI()); - assertEquals("http://localhost/app%20/path/", actual.getRequestURL().toString()); + assertThat(actual.getContextPath()).isEqualTo("/app%20"); + assertThat(actual.getRequestURI()).isEqualTo("/app%20/path/"); + assertThat(actual.getRequestURL().toString()).isEqualTo("http://localhost/app%20/path/"); } @Test @@ -139,8 +135,8 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/app/path"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertEquals("", actual.getContextPath()); - assertEquals("/path", actual.getRequestURI()); + assertThat(actual.getContextPath()).isEqualTo(""); + assertThat(actual.getRequestURI()).isEqualTo("/path"); } @Test @@ -150,8 +146,8 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/app/path/"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertEquals("", actual.getContextPath()); - assertEquals("/path/", actual.getRequestURI()); + assertThat(actual.getContextPath()).isEqualTo(""); + assertThat(actual.getRequestURI()).isEqualTo("/path/"); } @Test @@ -160,9 +156,9 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/app/path%20with%20spaces/"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertEquals("/app", actual.getContextPath()); - assertEquals("/app/path%20with%20spaces/", actual.getRequestURI()); - assertEquals("http://localhost/app/path%20with%20spaces/", actual.getRequestURL().toString()); + assertThat(actual.getContextPath()).isEqualTo("/app"); + assertThat(actual.getRequestURI()).isEqualTo("/app/path%20with%20spaces/"); + assertThat(actual.getRequestURL().toString()).isEqualTo("http://localhost/app/path%20with%20spaces/"); } @Test @@ -172,8 +168,8 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/app"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertEquals("", actual.getContextPath()); - assertEquals("/", actual.getRequestURI()); + assertThat(actual.getContextPath()).isEqualTo(""); + assertThat(actual.getRequestURI()).isEqualTo("/"); } @Test @@ -183,8 +179,8 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/app/"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertEquals("", actual.getContextPath()); - assertEquals("/", actual.getRequestURI()); + assertThat(actual.getContextPath()).isEqualTo(""); + assertThat(actual.getRequestURI()).isEqualTo("/"); } @Test @@ -193,9 +189,9 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/path;a=b/with/semicolon"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertEquals("", actual.getContextPath()); - assertEquals("/path;a=b/with/semicolon", actual.getRequestURI()); - assertEquals("http://localhost/path;a=b/with/semicolon", actual.getRequestURL().toString()); + assertThat(actual.getContextPath()).isEqualTo(""); + assertThat(actual.getRequestURI()).isEqualTo("/path;a=b/with/semicolon"); + assertThat(actual.getRequestURL().toString()).isEqualTo("http://localhost/path;a=b/with/semicolon"); } @Test @@ -218,7 +214,7 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/path"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertEquals("/prefix/path", actual.getRequestURI()); + assertThat(actual.getRequestURI()).isEqualTo("/prefix/path"); } @Test @@ -233,12 +229,12 @@ public class ForwardedHeaderFilterTests { private void testShouldFilter(String headerName) { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(headerName, "1"); - assertFalse(this.filter.shouldNotFilter(request)); + assertThat(this.filter.shouldNotFilter(request)).isFalse(); } @Test public void shouldNotFilter() { - assertTrue(this.filter.shouldNotFilter(new MockHttpServletRequest())); + assertThat(this.filter.shouldNotFilter(new MockHttpServletRequest())).isTrue(); } @Test @@ -252,16 +248,16 @@ public class ForwardedHeaderFilterTests { this.filter.doFilter(this.request, new MockHttpServletResponse(), this.filterChain); HttpServletRequest actual = (HttpServletRequest) this.filterChain.getRequest(); - assertEquals("https://84.198.58.199/mvc-showcase", actual.getRequestURL().toString()); - assertEquals("https", actual.getScheme()); - assertEquals("84.198.58.199", actual.getServerName()); - assertEquals(443, actual.getServerPort()); - assertTrue(actual.isSecure()); + assertThat(actual.getRequestURL().toString()).isEqualTo("https://84.198.58.199/mvc-showcase"); + assertThat(actual.getScheme()).isEqualTo("https"); + assertThat(actual.getServerName()).isEqualTo("84.198.58.199"); + assertThat(actual.getServerPort()).isEqualTo(443); + assertThat(actual.isSecure()).isTrue(); - assertNull(actual.getHeader(X_FORWARDED_PROTO)); - assertNull(actual.getHeader(X_FORWARDED_HOST)); - assertNull(actual.getHeader(X_FORWARDED_PORT)); - assertEquals("bar", actual.getHeader("foo")); + assertThat(actual.getHeader(X_FORWARDED_PROTO)).isNull(); + assertThat(actual.getHeader(X_FORWARDED_HOST)).isNull(); + assertThat(actual.getHeader(X_FORWARDED_PORT)).isNull(); + assertThat(actual.getHeader("foo")).isEqualTo("bar"); } @Test @@ -277,17 +273,17 @@ public class ForwardedHeaderFilterTests { this.filter.doFilter(this.request, new MockHttpServletResponse(), this.filterChain); HttpServletRequest actual = (HttpServletRequest) this.filterChain.getRequest(); - assertEquals("http://localhost/mvc-showcase", actual.getRequestURL().toString()); - assertEquals("http", actual.getScheme()); - assertEquals("localhost", actual.getServerName()); - assertEquals(80, actual.getServerPort()); - assertFalse(actual.isSecure()); + assertThat(actual.getRequestURL().toString()).isEqualTo("http://localhost/mvc-showcase"); + assertThat(actual.getScheme()).isEqualTo("http"); + assertThat(actual.getServerName()).isEqualTo("localhost"); + assertThat(actual.getServerPort()).isEqualTo(80); + assertThat(actual.isSecure()).isFalse(); - assertNull(actual.getHeader(X_FORWARDED_PROTO)); - assertNull(actual.getHeader(X_FORWARDED_HOST)); - assertNull(actual.getHeader(X_FORWARDED_PORT)); - assertNull(actual.getHeader(X_FORWARDED_SSL)); - assertEquals("bar", actual.getHeader("foo")); + assertThat(actual.getHeader(X_FORWARDED_PROTO)).isNull(); + assertThat(actual.getHeader(X_FORWARDED_HOST)).isNull(); + assertThat(actual.getHeader(X_FORWARDED_PORT)).isNull(); + assertThat(actual.getHeader(X_FORWARDED_SSL)).isNull(); + assertThat(actual.getHeader("foo")).isEqualTo("bar"); } @Test @@ -301,16 +297,16 @@ public class ForwardedHeaderFilterTests { this.filter.doFilter(this.request, new MockHttpServletResponse(), this.filterChain); HttpServletRequest actual = (HttpServletRequest) this.filterChain.getRequest(); - assertEquals("https://84.198.58.199/mvc-showcase", actual.getRequestURL().toString()); - assertEquals("https", actual.getScheme()); - assertEquals("84.198.58.199", actual.getServerName()); - assertEquals(443, actual.getServerPort()); - assertTrue(actual.isSecure()); + assertThat(actual.getRequestURL().toString()).isEqualTo("https://84.198.58.199/mvc-showcase"); + assertThat(actual.getScheme()).isEqualTo("https"); + assertThat(actual.getServerName()).isEqualTo("84.198.58.199"); + assertThat(actual.getServerPort()).isEqualTo(443); + assertThat(actual.isSecure()).isTrue(); - assertNull(actual.getHeader(X_FORWARDED_SSL)); - assertNull(actual.getHeader(X_FORWARDED_HOST)); - assertNull(actual.getHeader(X_FORWARDED_PORT)); - assertEquals("bar", actual.getHeader("foo")); + assertThat(actual.getHeader(X_FORWARDED_SSL)).isNull(); + assertThat(actual.getHeader(X_FORWARDED_HOST)).isNull(); + assertThat(actual.getHeader(X_FORWARDED_PORT)).isNull(); + assertThat(actual.getHeader("foo")).isEqualTo("bar"); } @Test // SPR-16983 @@ -330,9 +326,9 @@ public class ForwardedHeaderFilterTests { this.filter.doFilter(wrappedRequest, new MockHttpServletResponse(), this.filterChain); HttpServletRequest actual = (HttpServletRequest) this.filterChain.getRequest(); - assertNotNull(actual); - assertEquals("/bar", actual.getRequestURI()); - assertEquals("https://www.mycompany.com/bar", actual.getRequestURL().toString()); + assertThat(actual).isNotNull(); + assertThat(actual.getRequestURI()).isEqualTo("/bar"); + assertThat(actual.getRequestURL().toString()).isEqualTo("https://www.mycompany.com/bar"); } @Test @@ -341,7 +337,7 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/mvc-showcase"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertEquals("http://localhost/prefix/mvc-showcase", actual.getRequestURL().toString()); + assertThat(actual.getRequestURL().toString()).isEqualTo("http://localhost/prefix/mvc-showcase"); } @Test @@ -350,7 +346,7 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/mvc-showcase"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertEquals("http://localhost/prefix/mvc-showcase", actual.getRequestURL().toString()); + assertThat(actual.getRequestURL().toString()).isEqualTo("http://localhost/prefix/mvc-showcase"); } @Test @@ -360,7 +356,7 @@ public class ForwardedHeaderFilterTests { HttpServletRequest actual = filterAndGetWrappedRequest(); actual.getRequestURL().append("?key=value"); - assertEquals("http://localhost/prefix/mvc-showcase", actual.getRequestURL().toString()); + assertThat(actual.getRequestURL().toString()).isEqualTo("http://localhost/prefix/mvc-showcase"); } @Test @@ -370,7 +366,7 @@ public class ForwardedHeaderFilterTests { this.request.addHeader(X_FORWARDED_PORT, "443"); String redirectedUrl = sendRedirect("/foo/bar"); - assertEquals("https://example.com/foo/bar", redirectedUrl); + assertThat(redirectedUrl).isEqualTo("https://example.com/foo/bar"); } @Test // SPR-16506 @@ -381,7 +377,7 @@ public class ForwardedHeaderFilterTests { this.request.setQueryString("oldqp=1"); String redirectedUrl = sendRedirect("/foo/bar?newqp=2#fragment"); - assertEquals("https://example.com/foo/bar?newqp=2#fragment", redirectedUrl); + assertThat(redirectedUrl).isEqualTo("https://example.com/foo/bar?newqp=2#fragment"); } @Test @@ -392,7 +388,7 @@ public class ForwardedHeaderFilterTests { this.request.setContextPath("/context"); String redirectedUrl = sendRedirect("/context/foo/bar"); - assertEquals("https://example.com/context/foo/bar", redirectedUrl); + assertThat(redirectedUrl).isEqualTo("https://example.com/context/foo/bar"); } @Test @@ -403,7 +399,7 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/parent/"); String redirectedUrl = sendRedirect("foo/bar"); - assertEquals("https://example.com/parent/foo/bar", redirectedUrl); + assertThat(redirectedUrl).isEqualTo("https://example.com/parent/foo/bar"); } @Test @@ -414,7 +410,7 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/context/a"); String redirectedUrl = sendRedirect("foo/bar"); - assertEquals("https://example.com/context/foo/bar", redirectedUrl); + assertThat(redirectedUrl).isEqualTo("https://example.com/context/foo/bar"); } @Test @@ -425,7 +421,7 @@ public class ForwardedHeaderFilterTests { this.request.setRequestURI("/parent"); String redirectedUrl = sendRedirect("foo/bar"); - assertEquals("https://example.com/foo/bar", redirectedUrl); + assertThat(redirectedUrl).isEqualTo("https://example.com/foo/bar"); } @Test @@ -435,7 +431,7 @@ public class ForwardedHeaderFilterTests { this.request.addHeader(X_FORWARDED_PORT, "443"); String redirectedUrl = sendRedirect("parent/../foo/bar"); - assertEquals("https://example.com/foo/bar", redirectedUrl); + assertThat(redirectedUrl).isEqualTo("https://example.com/foo/bar"); } @Test @@ -446,7 +442,7 @@ public class ForwardedHeaderFilterTests { String location = "http://example.org/foo/bar"; String redirectedUrl = sendRedirect(location); - assertEquals(location, redirectedUrl); + assertThat(redirectedUrl).isEqualTo(location); } @Test @@ -457,7 +453,7 @@ public class ForwardedHeaderFilterTests { String location = "//other.info/foo/bar"; String redirectedUrl = sendRedirect(location); - assertEquals("https:" + location, redirectedUrl); + assertThat(redirectedUrl).isEqualTo(("https:" + location)); } @Test @@ -468,19 +464,19 @@ public class ForwardedHeaderFilterTests { String location = "//other.info/parent/../foo/bar"; String redirectedUrl = sendRedirect(location); - assertEquals("https:" + location, redirectedUrl); + assertThat(redirectedUrl).isEqualTo(("https:" + location)); } @Test public void sendRedirectWithNoXForwardedAndAbsolutePath() throws Exception { String redirectedUrl = sendRedirect("/foo/bar"); - assertEquals("/foo/bar", redirectedUrl); + assertThat(redirectedUrl).isEqualTo("/foo/bar"); } @Test public void sendRedirectWithNoXForwardedAndDotDotPath() throws Exception { String redirectedUrl = sendRedirect("../foo/bar"); - assertEquals("../foo/bar", redirectedUrl); + assertThat(redirectedUrl).isEqualTo("../foo/bar"); } @Test @@ -491,7 +487,7 @@ public class ForwardedHeaderFilterTests { this.filter.setRelativeRedirects(true); String location = sendRedirect("/a"); - assertEquals("/a", location); + assertThat(location).isEqualTo("/a"); } @Test @@ -499,7 +495,7 @@ public class ForwardedHeaderFilterTests { this.filter.setRelativeRedirects(true); String location = sendRedirect("/a"); - assertEquals("/a", location); + assertThat(location).isEqualTo("/a"); } private String sendRedirect(final String location) throws ServletException, IOException { diff --git a/spring-web/src/test/java/org/springframework/web/filter/HiddenHttpMethodFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/HiddenHttpMethodFilterTests.java index 8f083a4d9e0..1da78f21526 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/HiddenHttpMethodFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/HiddenHttpMethodFilterTests.java @@ -28,7 +28,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link HiddenHttpMethodFilter}. @@ -72,8 +72,7 @@ public class HiddenHttpMethodFilterTests { @Override public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse) throws IOException, ServletException { - assertEquals("Invalid method", expectedMethod, - ((HttpServletRequest) filterRequest).getMethod()); + assertThat(((HttpServletRequest) filterRequest).getMethod()).as("Invalid method").isEqualTo(expectedMethod); } }; this.filter.doFilter(request, response, filterChain); diff --git a/spring-web/src/test/java/org/springframework/web/filter/RelativeRedirectFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/RelativeRedirectFilterTests.java index 8c9afed854b..a2c8590a0fa 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/RelativeRedirectFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/RelativeRedirectFilterTests.java @@ -29,9 +29,8 @@ import org.springframework.mock.web.test.MockFilterChain; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; /** * Unit tests for {@link RelativeRedirectFilter}. @@ -88,18 +87,18 @@ public class RelativeRedirectFilterTests { this.filter.doFilterInternal(new MockHttpServletRequest(), original, chain); HttpServletResponse wrapped1 = (HttpServletResponse) chain.getResponse(); - assertNotSame(original, wrapped1); + assertThat(wrapped1).isNotSameAs(original); chain.reset(); this.filter.doFilterInternal(new MockHttpServletRequest(), wrapped1, chain); HttpServletResponse current = (HttpServletResponse) chain.getResponse(); - assertSame(wrapped1, current); + assertThat(current).isSameAs(wrapped1); chain.reset(); HttpServletResponse wrapped2 = new HttpServletResponseWrapper(wrapped1); this.filter.doFilterInternal(new MockHttpServletRequest(), wrapped2, chain); current = (HttpServletResponse) chain.getResponse(); - assertSame(wrapped2, current); + assertThat(current).isSameAs(wrapped2); } diff --git a/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java index 57d91abed1c..fd353de16c9 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java @@ -33,9 +33,6 @@ import org.springframework.web.context.request.RequestContextHolder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; /** * @author Rod Johnson @@ -65,8 +62,7 @@ public class RequestContextFilterTests { public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException { ++invocations; if (invocations == 1) { - assertSame("myValue", - RequestContextHolder.currentRequestAttributes().getAttribute("myAttr", RequestAttributes.SCOPE_REQUEST)); + assertThat(RequestContextHolder.currentRequestAttributes().getAttribute("myAttr", RequestAttributes.SCOPE_REQUEST)).isSameAs("myValue"); if (sex != null) { throw sex; } @@ -88,13 +84,13 @@ public class RequestContextFilterTests { assertThat(sex).isNull(); } catch (ServletException ex) { - assertNotNull(sex); + assertThat(sex).isNotNull(); } assertThatIllegalStateException().isThrownBy( RequestContextHolder::currentRequestAttributes); - assertEquals(1, fc.invocations); + assertThat(fc.invocations).isEqualTo(1); } } diff --git a/spring-web/src/test/java/org/springframework/web/filter/RequestLoggingFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/RequestLoggingFilterTests.java index db57c1c2842..7b8d4f1d979 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/RequestLoggingFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/RequestLoggingFilterTests.java @@ -33,11 +33,7 @@ import org.springframework.util.FileCopyUtils; import org.springframework.web.util.ContentCachingRequestWrapper; import org.springframework.web.util.WebUtils; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test for {@link AbstractRequestLoggingFilter} and subclasses. @@ -60,13 +56,13 @@ public class RequestLoggingFilterTests { FilterChain filterChain = new NoOpFilterChain(); filter.doFilter(request, response, filterChain); - assertNotNull(filter.beforeRequestMessage); - assertTrue(filter.beforeRequestMessage.contains("uri=/hotel")); - assertFalse(filter.beforeRequestMessage.contains("booking=42")); + assertThat(filter.beforeRequestMessage).isNotNull(); + assertThat(filter.beforeRequestMessage.contains("uri=/hotel")).isTrue(); + assertThat(filter.beforeRequestMessage.contains("booking=42")).isFalse(); - assertNotNull(filter.afterRequestMessage); - assertTrue(filter.afterRequestMessage.contains("uri=/hotel")); - assertFalse(filter.afterRequestMessage.contains("booking=42")); + assertThat(filter.afterRequestMessage).isNotNull(); + assertThat(filter.afterRequestMessage.contains("uri=/hotel")).isTrue(); + assertThat(filter.afterRequestMessage.contains("booking=42")).isFalse(); } @Test @@ -81,11 +77,11 @@ public class RequestLoggingFilterTests { FilterChain filterChain = new NoOpFilterChain(); filter.doFilter(request, response, filterChain); - assertNotNull(filter.beforeRequestMessage); - assertTrue(filter.beforeRequestMessage.contains("[uri=/hotels?booking=42]")); + assertThat(filter.beforeRequestMessage).isNotNull(); + assertThat(filter.beforeRequestMessage.contains("[uri=/hotels?booking=42]")).isTrue(); - assertNotNull(filter.afterRequestMessage); - assertTrue(filter.afterRequestMessage.contains("[uri=/hotels?booking=42]")); + assertThat(filter.afterRequestMessage).isNotNull(); + assertThat(filter.afterRequestMessage.contains("[uri=/hotels?booking=42]")).isTrue(); } @Test @@ -98,11 +94,11 @@ public class RequestLoggingFilterTests { FilterChain filterChain = new NoOpFilterChain(); filter.doFilter(request, response, filterChain); - assertNotNull(filter.beforeRequestMessage); - assertTrue(filter.beforeRequestMessage.contains("[uri=/hotels]")); + assertThat(filter.beforeRequestMessage).isNotNull(); + assertThat(filter.beforeRequestMessage.contains("[uri=/hotels]")).isTrue(); - assertNotNull(filter.afterRequestMessage); - assertTrue(filter.afterRequestMessage.contains("[uri=/hotels]")); + assertThat(filter.afterRequestMessage).isNotNull(); + assertThat(filter.afterRequestMessage.contains("[uri=/hotels]")).isTrue(); } @Test @@ -117,13 +113,11 @@ public class RequestLoggingFilterTests { filter.setHeaderPredicate(name -> !name.equalsIgnoreCase("token")); filter.doFilter(request, response, filterChain); - assertNotNull(filter.beforeRequestMessage); - assertEquals("Before request [uri=/hotels;headers=[Content-Type:\"application/json\", token:\"masked\"]]", - filter.beforeRequestMessage); + assertThat(filter.beforeRequestMessage).isNotNull(); + assertThat(filter.beforeRequestMessage).isEqualTo("Before request [uri=/hotels;headers=[Content-Type:\"application/json\", token:\"masked\"]]"); - assertNotNull(filter.afterRequestMessage); - assertEquals("After request [uri=/hotels;headers=[Content-Type:\"application/json\", token:\"masked\"]]", - filter.afterRequestMessage); + assertThat(filter.afterRequestMessage).isNotNull(); + assertThat(filter.afterRequestMessage).isEqualTo("After request [uri=/hotels;headers=[Content-Type:\"application/json\", token:\"masked\"]]"); } @Test @@ -139,13 +133,13 @@ public class RequestLoggingFilterTests { FilterChain filterChain = (filterRequest, filterResponse) -> { ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); byte[] buf = FileCopyUtils.copyToByteArray(filterRequest.getInputStream()); - assertArrayEquals(requestBody, buf); + assertThat(buf).isEqualTo(requestBody); }; filter.doFilter(request, response, filterChain); - assertNotNull(filter.afterRequestMessage); - assertTrue(filter.afterRequestMessage.contains("Hello World")); + assertThat(filter.afterRequestMessage).isNotNull(); + assertThat(filter.afterRequestMessage.contains("Hello World")).isTrue(); } @Test @@ -161,13 +155,13 @@ public class RequestLoggingFilterTests { FilterChain filterChain = (filterRequest, filterResponse) -> { ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); String buf = FileCopyUtils.copyToString(filterRequest.getReader()); - assertEquals(requestBody, buf); + assertThat(buf).isEqualTo(requestBody); }; filter.doFilter(request, response, filterChain); - assertNotNull(filter.afterRequestMessage); - assertTrue(filter.afterRequestMessage.contains(requestBody)); + assertThat(filter.afterRequestMessage).isNotNull(); + assertThat(filter.afterRequestMessage.contains(requestBody)).isTrue(); } @Test @@ -184,17 +178,17 @@ public class RequestLoggingFilterTests { FilterChain filterChain = (filterRequest, filterResponse) -> { ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); byte[] buf = FileCopyUtils.copyToByteArray(filterRequest.getInputStream()); - assertArrayEquals(requestBody, buf); + assertThat(buf).isEqualTo(requestBody); ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(filterRequest, ContentCachingRequestWrapper.class); - assertArrayEquals("Hel".getBytes(StandardCharsets.UTF_8), wrapper.getContentAsByteArray()); + assertThat(wrapper.getContentAsByteArray()).isEqualTo("Hel".getBytes(StandardCharsets.UTF_8)); }; filter.doFilter(request, response, filterChain); - assertNotNull(filter.afterRequestMessage); - assertTrue(filter.afterRequestMessage.contains("Hel")); - assertFalse(filter.afterRequestMessage.contains("Hello World")); + assertThat(filter.afterRequestMessage).isNotNull(); + assertThat(filter.afterRequestMessage.contains("Hel")).isTrue(); + assertThat(filter.afterRequestMessage.contains("Hello World")).isFalse(); } diff --git a/spring-web/src/test/java/org/springframework/web/filter/ShallowEtagHeaderFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/ShallowEtagHeaderFilterTests.java index 718d310b0ef..69380413a98 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/ShallowEtagHeaderFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/ShallowEtagHeaderFilterTests.java @@ -26,11 +26,7 @@ import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -47,18 +43,18 @@ public class ShallowEtagHeaderFilterTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels"); MockHttpServletResponse response = new MockHttpServletResponse(); - assertTrue(filter.isEligibleForEtag(request, response, 200, StreamUtils.emptyInput())); - assertFalse(filter.isEligibleForEtag(request, response, 300, StreamUtils.emptyInput())); + assertThat(filter.isEligibleForEtag(request, response, 200, StreamUtils.emptyInput())).isTrue(); + assertThat(filter.isEligibleForEtag(request, response, 300, StreamUtils.emptyInput())).isFalse(); request = new MockHttpServletRequest("HEAD", "/hotels"); - assertFalse(filter.isEligibleForEtag(request, response, 200, StreamUtils.emptyInput())); + assertThat(filter.isEligibleForEtag(request, response, 200, StreamUtils.emptyInput())).isFalse(); request = new MockHttpServletRequest("POST", "/hotels"); - assertFalse(filter.isEligibleForEtag(request, response, 200, StreamUtils.emptyInput())); + assertThat(filter.isEligibleForEtag(request, response, 200, StreamUtils.emptyInput())).isFalse(); request = new MockHttpServletRequest("POST", "/hotels"); request.addHeader("Cache-Control","must-revalidate, no-store"); - assertFalse(filter.isEligibleForEtag(request, response, 200, StreamUtils.emptyInput())); + assertThat(filter.isEligibleForEtag(request, response, 200, StreamUtils.emptyInput())).isFalse(); } @Test @@ -68,16 +64,16 @@ public class ShallowEtagHeaderFilterTests { final byte[] responseBody = "Hello World".getBytes("UTF-8"); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertEquals("Invalid request passed", request, filterRequest); + assertThat(filterRequest).as("Invalid request passed").isEqualTo(request); ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); }; filter.doFilter(request, response, filterChain); - assertEquals("Invalid status", 200, response.getStatus()); - assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag")); - assertTrue("Invalid Content-Length header", response.getContentLength() > 0); - assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray()); + assertThat(response.getStatus()).as("Invalid status").isEqualTo(200); + assertThat(response.getHeader("ETag")).as("Invalid ETag header").isEqualTo("\"0b10a8db164e0754105b7a99be72e3fe5\""); + assertThat(response.getContentLength() > 0).as("Invalid Content-Length header").isTrue(); + assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(responseBody); } @Test @@ -88,16 +84,16 @@ public class ShallowEtagHeaderFilterTests { final byte[] responseBody = "Hello World".getBytes("UTF-8"); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertEquals("Invalid request passed", request, filterRequest); + assertThat(filterRequest).as("Invalid request passed").isEqualTo(request); ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); }; filter.doFilter(request, response, filterChain); - assertEquals("Invalid status", 200, response.getStatus()); - assertEquals("Invalid ETag header", "W/\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag")); - assertTrue("Invalid Content-Length header", response.getContentLength() > 0); - assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray()); + assertThat(response.getStatus()).as("Invalid status").isEqualTo(200); + assertThat(response.getHeader("ETag")).as("Invalid ETag header").isEqualTo("W/\"0b10a8db164e0754105b7a99be72e3fe5\""); + assertThat(response.getContentLength() > 0).as("Invalid Content-Length header").isTrue(); + assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(responseBody); } @Test @@ -108,17 +104,18 @@ public class ShallowEtagHeaderFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertEquals("Invalid request passed", request, filterRequest); + assertThat(filterRequest).as("Invalid request passed").isEqualTo(request); byte[] responseBody = "Hello World".getBytes("UTF-8"); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); filterResponse.setContentLength(responseBody.length); }; filter.doFilter(request, response, filterChain); - assertEquals("Invalid status", 304, response.getStatus()); - assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag")); - assertFalse("Response has Content-Length header", response.containsHeader("Content-Length")); - assertArrayEquals("Invalid content", new byte[0], response.getContentAsByteArray()); + assertThat(response.getStatus()).as("Invalid status").isEqualTo(304); + assertThat(response.getHeader("ETag")).as("Invalid ETag header").isEqualTo("\"0b10a8db164e0754105b7a99be72e3fe5\""); + assertThat(response.containsHeader("Content-Length")).as("Response has Content-Length header").isFalse(); + byte[] expecteds = new byte[0]; + assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(expecteds); } @Test @@ -129,17 +126,18 @@ public class ShallowEtagHeaderFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertEquals("Invalid request passed", request, filterRequest); + assertThat(filterRequest).as("Invalid request passed").isEqualTo(request); byte[] responseBody = "Hello World".getBytes("UTF-8"); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); filterResponse.setContentLength(responseBody.length); }; filter.doFilter(request, response, filterChain); - assertEquals("Invalid status", 304, response.getStatus()); - assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag")); - assertFalse("Response has Content-Length header", response.containsHeader("Content-Length")); - assertArrayEquals("Invalid content", new byte[0], response.getContentAsByteArray()); + assertThat(response.getStatus()).as("Invalid status").isEqualTo(304); + assertThat(response.getHeader("ETag")).as("Invalid ETag header").isEqualTo("\"0b10a8db164e0754105b7a99be72e3fe5\""); + assertThat(response.containsHeader("Content-Length")).as("Response has Content-Length header").isFalse(); + byte[] expecteds = new byte[0]; + assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(expecteds); } @Test @@ -150,17 +148,18 @@ public class ShallowEtagHeaderFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertEquals("Invalid request passed", request, filterRequest); + assertThat(filterRequest).as("Invalid request passed").isEqualTo(request); ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); String responseBody = "Hello World"; FileCopyUtils.copy(responseBody, filterResponse.getWriter()); }; filter.doFilter(request, response, filterChain); - assertEquals("Invalid status", 304, response.getStatus()); - assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag")); - assertFalse("Response has Content-Length header", response.containsHeader("Content-Length")); - assertArrayEquals("Invalid content", new byte[0], response.getContentAsByteArray()); + assertThat(response.getStatus()).as("Invalid status").isEqualTo(304); + assertThat(response.getHeader("ETag")).as("Invalid ETag header").isEqualTo("\"0b10a8db164e0754105b7a99be72e3fe5\""); + assertThat(response.containsHeader("Content-Length")).as("Response has Content-Length header").isFalse(); + byte[] expecteds = new byte[0]; + assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(expecteds); } @Test // SPR-12960 @@ -170,7 +169,7 @@ public class ShallowEtagHeaderFilterTests { final byte[] responseBody = "Hello World".getBytes("UTF-8"); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertEquals("Invalid request passed", request, filterRequest); + assertThat(filterRequest).as("Invalid request passed").isEqualTo(request); ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); }; @@ -178,9 +177,9 @@ public class ShallowEtagHeaderFilterTests { ShallowEtagHeaderFilter.disableContentCaching(request); this.filter.doFilter(request, response, filterChain); - assertEquals(200, response.getStatus()); - assertNull(response.getHeader("ETag")); - assertArrayEquals(responseBody, response.getContentAsByteArray()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getHeader("ETag")).isNull(); + assertThat(response.getContentAsByteArray()).isEqualTo(responseBody); } @Test @@ -190,17 +189,17 @@ public class ShallowEtagHeaderFilterTests { final byte[] responseBody = "Hello World".getBytes("UTF-8"); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertEquals("Invalid request passed", request, filterRequest); + assertThat(filterRequest).as("Invalid request passed").isEqualTo(request); response.setContentLength(100); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); ((HttpServletResponse) filterResponse).sendError(HttpServletResponse.SC_FORBIDDEN); }; filter.doFilter(request, response, filterChain); - assertEquals("Invalid status", 403, response.getStatus()); - assertNull("Invalid ETag header", response.getHeader("ETag")); - assertEquals("Invalid Content-Length header", 100, response.getContentLength()); - assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray()); + assertThat(response.getStatus()).as("Invalid status").isEqualTo(403); + assertThat(response.getHeader("ETag")).as("Invalid ETag header").isNull(); + assertThat(response.getContentLength()).as("Invalid Content-Length header").isEqualTo(100); + assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(responseBody); } @Test @@ -210,18 +209,18 @@ public class ShallowEtagHeaderFilterTests { final byte[] responseBody = "Hello World".getBytes("UTF-8"); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertEquals("Invalid request passed", request, filterRequest); + assertThat(filterRequest).as("Invalid request passed").isEqualTo(request); response.setContentLength(100); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); ((HttpServletResponse) filterResponse).sendError(HttpServletResponse.SC_FORBIDDEN, "ERROR"); }; filter.doFilter(request, response, filterChain); - assertEquals("Invalid status", 403, response.getStatus()); - assertNull("Invalid ETag header", response.getHeader("ETag")); - assertEquals("Invalid Content-Length header", 100, response.getContentLength()); - assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray()); - assertEquals("Invalid error message", "ERROR", response.getErrorMessage()); + assertThat(response.getStatus()).as("Invalid status").isEqualTo(403); + assertThat(response.getHeader("ETag")).as("Invalid ETag header").isNull(); + assertThat(response.getContentLength()).as("Invalid Content-Length header").isEqualTo(100); + assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(responseBody); + assertThat(response.getErrorMessage()).as("Invalid error message").isEqualTo("ERROR"); } @Test @@ -231,18 +230,18 @@ public class ShallowEtagHeaderFilterTests { final byte[] responseBody = "Hello World".getBytes("UTF-8"); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertEquals("Invalid request passed", request, filterRequest); + assertThat(filterRequest).as("Invalid request passed").isEqualTo(request); response.setContentLength(100); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); ((HttpServletResponse) filterResponse).sendRedirect("https://www.google.com"); }; filter.doFilter(request, response, filterChain); - assertEquals("Invalid status", 302, response.getStatus()); - assertNull("Invalid ETag header", response.getHeader("ETag")); - assertEquals("Invalid Content-Length header", 100, response.getContentLength()); - assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray()); - assertEquals("Invalid redirect URL", "https://www.google.com", response.getRedirectedUrl()); + assertThat(response.getStatus()).as("Invalid status").isEqualTo(302); + assertThat(response.getHeader("ETag")).as("Invalid ETag header").isNull(); + assertThat(response.getContentLength()).as("Invalid Content-Length header").isEqualTo(100); + assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(responseBody); + assertThat(response.getRedirectedUrl()).as("Invalid redirect URL").isEqualTo("https://www.google.com"); } // SPR-13717 @@ -253,17 +252,17 @@ public class ShallowEtagHeaderFilterTests { final byte[] responseBody = "Hello World".getBytes("UTF-8"); FilterChain filterChain = (filterRequest, filterResponse) -> { - assertEquals("Invalid request passed", request, filterRequest); + assertThat(filterRequest).as("Invalid request passed").isEqualTo(request); ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); filterResponse.flushBuffer(); }; filter.doFilter(request, response, filterChain); - assertEquals("Invalid status", 200, response.getStatus()); - assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag")); - assertTrue("Invalid Content-Length header", response.getContentLength() > 0); - assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray()); + assertThat(response.getStatus()).as("Invalid status").isEqualTo(200); + assertThat(response.getHeader("ETag")).as("Invalid ETag header").isEqualTo("\"0b10a8db164e0754105b7a99be72e3fe5\""); + assertThat(response.getContentLength() > 0).as("Invalid Content-Length header").isTrue(); + assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(responseBody); } } diff --git a/spring-web/src/test/java/org/springframework/web/filter/reactive/HiddenHttpMethodFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/reactive/HiddenHttpMethodFilterTests.java index 075548dd21a..4518c23c623 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/reactive/HiddenHttpMethodFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/reactive/HiddenHttpMethodFilterTests.java @@ -31,7 +31,6 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Tests for {@link HiddenHttpMethodFilter}. @@ -48,32 +47,32 @@ public class HiddenHttpMethodFilterTests { @Test public void filterWithParameter() { postForm("_method=DELETE").block(Duration.ZERO); - assertEquals(HttpMethod.DELETE, this.filterChain.getHttpMethod()); + assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.DELETE); } @Test public void filterWithParameterMethodNotAllowed() { postForm("_method=TRACE").block(Duration.ZERO); - assertEquals(HttpMethod.POST, this.filterChain.getHttpMethod()); + assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.POST); } @Test public void filterWithNoParameter() { postForm("").block(Duration.ZERO); - assertEquals(HttpMethod.POST, this.filterChain.getHttpMethod()); + assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.POST); } @Test public void filterWithEmptyStringParameter() { postForm("_method=").block(Duration.ZERO); - assertEquals(HttpMethod.POST, this.filterChain.getHttpMethod()); + assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.POST); } @Test public void filterWithDifferentMethodParam() { this.filter.setMethodParamName("_foo"); postForm("_foo=DELETE").block(Duration.ZERO); - assertEquals(HttpMethod.DELETE, this.filterChain.getHttpMethod()); + assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.DELETE); } @Test @@ -81,7 +80,7 @@ public class HiddenHttpMethodFilterTests { StepVerifier.create(postForm("_method=INVALID")) .consumeErrorWith(error -> { assertThat(error).isInstanceOf(IllegalArgumentException.class); - assertEquals("HttpMethod 'INVALID' not supported", error.getMessage()); + assertThat(error.getMessage()).isEqualTo("HttpMethod 'INVALID' not supported"); }) .verify(); } @@ -95,7 +94,7 @@ public class HiddenHttpMethodFilterTests { .body("_method=DELETE")); this.filter.filter(exchange, this.filterChain).block(Duration.ZERO); - assertEquals(HttpMethod.PUT, this.filterChain.getHttpMethod()); + assertThat(this.filterChain.getHttpMethod()).isEqualTo(HttpMethod.PUT); } diff --git a/spring-web/src/test/java/org/springframework/web/filter/reactive/ServerWebExchangeContextFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/reactive/ServerWebExchangeContextFilterTests.java index f228dffd28f..e58905eb409 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/reactive/ServerWebExchangeContextFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/reactive/ServerWebExchangeContextFilterTests.java @@ -27,7 +27,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ServerWebExchangeContextFilter}. @@ -47,7 +47,7 @@ public class ServerWebExchangeContextFilterTests { httpHandler.handle(MockServerHttpRequest.get("/path").build(), new MockServerHttpResponse()) .block(Duration.ofSeconds(5)); - assertNotNull(service.getExchange()); + assertThat(service.getExchange()).isNotNull(); } diff --git a/spring-web/src/test/java/org/springframework/web/jsf/DelegatingNavigationHandlerTests.java b/spring-web/src/test/java/org/springframework/web/jsf/DelegatingNavigationHandlerTests.java index 0a875c505a7..8714a74be2c 100644 --- a/spring-web/src/test/java/org/springframework/web/jsf/DelegatingNavigationHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/jsf/DelegatingNavigationHandlerTests.java @@ -25,7 +25,7 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.StaticListableBeanFactory; import org.springframework.lang.Nullable; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Colin Sampaleanu @@ -53,8 +53,8 @@ public class DelegatingNavigationHandlerTests { beanFactory.addBean("jsfNavigationHandler", targetHandler); delNavHandler.handleNavigation(facesContext, "fromAction", "myViewId"); - assertEquals("fromAction", targetHandler.lastFromAction); - assertEquals("myViewId", targetHandler.lastOutcome); + assertThat(targetHandler.lastFromAction).isEqualTo("fromAction"); + assertThat(targetHandler.lastOutcome).isEqualTo("myViewId"); } @Test @@ -63,12 +63,12 @@ public class DelegatingNavigationHandlerTests { beanFactory.addBean("jsfNavigationHandler", targetHandler); delNavHandler.handleNavigation(facesContext, "fromAction", "myViewId"); - assertEquals("fromAction", targetHandler.lastFromAction); - assertEquals("myViewId", targetHandler.lastOutcome); + assertThat(targetHandler.lastFromAction).isEqualTo("fromAction"); + assertThat(targetHandler.lastOutcome).isEqualTo("myViewId"); // Original handler must have been invoked as well... - assertEquals("fromAction", origNavHandler.lastFromAction); - assertEquals("myViewId", origNavHandler.lastOutcome); + assertThat(origNavHandler.lastFromAction).isEqualTo("fromAction"); + assertThat(origNavHandler.lastOutcome).isEqualTo("myViewId"); } diff --git a/spring-web/src/test/java/org/springframework/web/jsf/DelegatingPhaseListenerTests.java b/spring-web/src/test/java/org/springframework/web/jsf/DelegatingPhaseListenerTests.java index 054e845d642..68809d55b76 100644 --- a/spring-web/src/test/java/org/springframework/web/jsf/DelegatingPhaseListenerTests.java +++ b/spring-web/src/test/java/org/springframework/web/jsf/DelegatingPhaseListenerTests.java @@ -26,8 +26,7 @@ import org.junit.Test; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.support.StaticListableBeanFactory; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Colin Sampaleanu @@ -52,14 +51,14 @@ public class DelegatingPhaseListenerTests { TestListener target = new TestListener(); beanFactory.addBean("testListener", target); - assertEquals(PhaseId.ANY_PHASE, delPhaseListener.getPhaseId()); + assertThat((Object) delPhaseListener.getPhaseId()).isEqualTo(PhaseId.ANY_PHASE); PhaseEvent event = new PhaseEvent(facesContext, PhaseId.INVOKE_APPLICATION, new MockLifecycle()); delPhaseListener.beforePhase(event); - assertTrue(target.beforeCalled); + assertThat(target.beforeCalled).isTrue(); delPhaseListener.afterPhase(event); - assertTrue(target.afterCalled); + assertThat(target.afterCalled).isTrue(); } @Test @@ -69,16 +68,16 @@ public class DelegatingPhaseListenerTests { beanFactory.addBean("testListener1", target1); beanFactory.addBean("testListener2", target2); - assertEquals(PhaseId.ANY_PHASE, delPhaseListener.getPhaseId()); + assertThat((Object) delPhaseListener.getPhaseId()).isEqualTo(PhaseId.ANY_PHASE); PhaseEvent event = new PhaseEvent(facesContext, PhaseId.INVOKE_APPLICATION, new MockLifecycle()); delPhaseListener.beforePhase(event); - assertTrue(target1.beforeCalled); - assertTrue(target2.beforeCalled); + assertThat(target1.beforeCalled).isTrue(); + assertThat(target2.beforeCalled).isTrue(); delPhaseListener.afterPhase(event); - assertTrue(target1.afterCalled); - assertTrue(target2.afterCalled); + assertThat(target1.afterCalled).isTrue(); + assertThat(target2.afterCalled).isTrue(); } diff --git a/spring-web/src/test/java/org/springframework/web/method/ControllerAdviceBeanTests.java b/spring-web/src/test/java/org/springframework/web/method/ControllerAdviceBeanTests.java index fee3774dc51..c2f47513104 100644 --- a/spring-web/src/test/java/org/springframework/web/method/ControllerAdviceBeanTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/ControllerAdviceBeanTests.java @@ -24,9 +24,7 @@ import org.junit.Test; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.RestController; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Brian Clozel @@ -103,13 +101,13 @@ public class ControllerAdviceBeanTests { } private void assertApplicable(String message, ControllerAdviceBean controllerAdvice, Class controllerBeanType) { - assertNotNull(controllerAdvice); - assertTrue(message, controllerAdvice.isApplicableToBeanType(controllerBeanType)); + assertThat(controllerAdvice).isNotNull(); + assertThat(controllerAdvice.isApplicableToBeanType(controllerBeanType)).as(message).isTrue(); } private void assertNotApplicable(String message, ControllerAdviceBean controllerAdvice, Class controllerBeanType) { - assertNotNull(controllerAdvice); - assertFalse(message, controllerAdvice.isApplicableToBeanType(controllerBeanType)); + assertThat(controllerAdvice).isNotNull(); + assertThat(controllerAdvice.isApplicableToBeanType(controllerBeanType)).as(message).isFalse(); } diff --git a/spring-web/src/test/java/org/springframework/web/method/HandlerTypePredicateTests.java b/spring-web/src/test/java/org/springframework/web/method/HandlerTypePredicateTests.java index c622ea6a3b8..311b2f18eaf 100644 --- a/spring-web/src/test/java/org/springframework/web/method/HandlerTypePredicateTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/HandlerTypePredicateTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RestController; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link HandlerTypePredicate}. @@ -36,9 +35,9 @@ public class HandlerTypePredicateTests { Predicate> predicate = HandlerTypePredicate.forAnnotation(Controller.class); - assertTrue(predicate.test(HtmlController.class)); - assertTrue(predicate.test(ApiController.class)); - assertTrue(predicate.test(AnotherApiController.class)); + assertThat(predicate.test(HtmlController.class)).isTrue(); + assertThat(predicate.test(ApiController.class)).isTrue(); + assertThat(predicate.test(AnotherApiController.class)).isTrue(); } @Test @@ -47,9 +46,9 @@ public class HandlerTypePredicateTests { Predicate> predicate = HandlerTypePredicate.forAnnotation(Controller.class) .and(HandlerTypePredicate.forAssignableType(Special.class)); - assertFalse(predicate.test(HtmlController.class)); - assertFalse(predicate.test(ApiController.class)); - assertTrue(predicate.test(AnotherApiController.class)); + assertThat(predicate.test(HtmlController.class)).isFalse(); + assertThat(predicate.test(ApiController.class)).isFalse(); + assertThat(predicate.test(AnotherApiController.class)).isTrue(); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/CookieValueMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/CookieValueMethodArgumentResolverTests.java index 2886ba56114..125f3353e0f 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/CookieValueMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/CookieValueMethodArgumentResolverTests.java @@ -31,10 +31,8 @@ import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Test fixture with {@link org.springframework.web.method.annotation.AbstractCookieValueMethodArgumentResolver}. @@ -73,17 +71,18 @@ public class CookieValueMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue("Cookie parameter not supported", resolver.supportsParameter(paramNamedCookie)); - assertTrue("Cookie string parameter not supported", resolver.supportsParameter(paramNamedDefaultValueString)); - assertFalse("non-@CookieValue parameter supported", resolver.supportsParameter(paramString)); + assertThat(resolver.supportsParameter(paramNamedCookie)).as("Cookie parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramNamedDefaultValueString)).as("Cookie string parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramString)).as("non-@CookieValue parameter supported").isFalse(); } @Test public void resolveCookieDefaultValue() throws Exception { Object result = resolver.resolveArgument(paramNamedDefaultValueString, null, webRequest, null); - assertTrue(result instanceof String); - assertEquals("Invalid result", "bar", result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo("bar"); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ErrorsMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ErrorsMethodArgumentResolverTests.java index e88c5e44def..6edf54e02ec 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ErrorsMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ErrorsMethodArgumentResolverTests.java @@ -28,8 +28,8 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertSame; /** * Test fixture with {@link ErrorsMethodArgumentResolver}. @@ -71,7 +71,7 @@ public class ErrorsMethodArgumentResolverTests { mavContainer.addAllAttributes(bindingResult.getModel()); Object actual = resolver.resolveArgument(paramErrors, mavContainer, webRequest, null); - assertSame(actual, bindingResult); + assertThat(bindingResult).isSameAs(actual); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java index 246d6998eb9..ede0b189e49 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java @@ -29,9 +29,8 @@ import org.springframework.stereotype.Controller; import org.springframework.util.ClassUtils; import org.springframework.web.bind.annotation.ExceptionHandler; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * Test fixture for {@link ExceptionHandlerMethodResolver} tests. @@ -44,45 +43,45 @@ public class ExceptionHandlerMethodResolverTests { public void resolveMethodFromAnnotation() { ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(ExceptionController.class); IOException exception = new IOException(); - assertEquals("handleIOException", resolver.resolveMethod(exception).getName()); + assertThat(resolver.resolveMethod(exception).getName()).isEqualTo("handleIOException"); } @Test public void resolveMethodFromArgument() { ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(ExceptionController.class); IllegalArgumentException exception = new IllegalArgumentException(); - assertEquals("handleIllegalArgumentException", resolver.resolveMethod(exception).getName()); + assertThat(resolver.resolveMethod(exception).getName()).isEqualTo("handleIllegalArgumentException"); } @Test public void resolveMethodExceptionSubType() { ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(ExceptionController.class); IOException ioException = new FileNotFoundException(); - assertEquals("handleIOException", resolver.resolveMethod(ioException).getName()); + assertThat(resolver.resolveMethod(ioException).getName()).isEqualTo("handleIOException"); SocketException bindException = new BindException(); - assertEquals("handleSocketException", resolver.resolveMethod(bindException).getName()); + assertThat(resolver.resolveMethod(bindException).getName()).isEqualTo("handleSocketException"); } @Test public void resolveMethodBestMatch() { ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(ExceptionController.class); SocketException exception = new SocketException(); - assertEquals("handleSocketException", resolver.resolveMethod(exception).getName()); + assertThat(resolver.resolveMethod(exception).getName()).isEqualTo("handleSocketException"); } @Test public void resolveMethodNoMatch() { ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(ExceptionController.class); Exception exception = new Exception(); - assertNull("1st lookup", resolver.resolveMethod(exception)); - assertNull("2nd lookup from cache", resolver.resolveMethod(exception)); + assertThat(resolver.resolveMethod(exception)).as("1st lookup").isNull(); + assertThat(resolver.resolveMethod(exception)).as("2nd lookup from cache").isNull(); } @Test public void resolveMethodInherited() { ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(InheritedController.class); IOException exception = new IOException(); - assertEquals("handleIOException", resolver.resolveMethod(exception).getName()); + assertThat(resolver.resolveMethod(exception).getName()).isEqualTo("handleIOException"); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ExpressionValueMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ExpressionValueMethodArgumentResolverTests.java index 40ddb5d187a..b5fb9d93857 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ExpressionValueMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ExpressionValueMethodArgumentResolverTests.java @@ -31,9 +31,7 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.support.GenericWebApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link ExpressionValueMethodArgumentResolver}. @@ -77,9 +75,9 @@ public class ExpressionValueMethodArgumentResolverTests { @Test public void supportsParameter() throws Exception { - assertTrue(resolver.supportsParameter(paramSystemProperty)); - assertTrue(resolver.supportsParameter(paramContextPath)); - assertFalse(resolver.supportsParameter(paramNotSupported)); + assertThat(resolver.supportsParameter(paramSystemProperty)).isTrue(); + assertThat(resolver.supportsParameter(paramContextPath)).isTrue(); + assertThat(resolver.supportsParameter(paramNotSupported)).isFalse(); } @Test @@ -88,7 +86,7 @@ public class ExpressionValueMethodArgumentResolverTests { Object value = resolver.resolveArgument(paramSystemProperty, null, webRequest, null); System.clearProperty("systemProperty"); - assertEquals("22", value); + assertThat(value).isEqualTo("22"); } @Test @@ -96,7 +94,7 @@ public class ExpressionValueMethodArgumentResolverTests { webRequest.getNativeRequest(MockHttpServletRequest.class).setContextPath("/contextPath"); Object value = resolver.resolveArgument(paramContextPath, null, webRequest, null); - assertEquals("/contextPath", value); + assertThat(value).isEqualTo("/contextPath"); } public void params(@Value("#{systemProperties.systemProperty}") int param1, diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java index 04a6aeecf76..a4f94e41091 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java @@ -36,11 +36,8 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite; import org.springframework.web.method.support.InvocableHandlerMethod; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; /** * Test fixture with {@link InitBinderDataBinderFactory}. @@ -63,8 +60,8 @@ public class InitBinderDataBinderFactoryTests { WebDataBinderFactory factory = createFactory("initBinder", WebDataBinder.class); WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, null); - assertNotNull(dataBinder.getDisallowedFields()); - assertEquals("id", dataBinder.getDisallowedFields()[0]); + assertThat(dataBinder.getDisallowedFields()).isNotNull(); + assertThat(dataBinder.getDisallowedFields()[0]).isEqualTo("id"); } @Test @@ -75,7 +72,7 @@ public class InitBinderDataBinderFactoryTests { WebDataBinderFactory factory = createFactory("initBinder", WebDataBinder.class); WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, null); - assertSame(conversionService, dataBinder.getConversionService()); + assertThat(dataBinder.getConversionService()).isSameAs(conversionService); } @Test @@ -83,8 +80,8 @@ public class InitBinderDataBinderFactoryTests { WebDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class); WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, "foo"); - assertNotNull(dataBinder.getDisallowedFields()); - assertEquals("id", dataBinder.getDisallowedFields()[0]); + assertThat(dataBinder.getDisallowedFields()).isNotNull(); + assertThat(dataBinder.getDisallowedFields()[0]).isEqualTo("id"); } @Test @@ -92,7 +89,7 @@ public class InitBinderDataBinderFactoryTests { WebDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class); WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, "invalidName"); - assertNull(dataBinder.getDisallowedFields()); + assertThat(dataBinder.getDisallowedFields()).isNull(); } @Test @@ -100,7 +97,7 @@ public class InitBinderDataBinderFactoryTests { WebDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class); WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, null); - assertNull(dataBinder.getDisallowedFields()); + assertThat(dataBinder.getDisallowedFields()).isNull(); } @Test @@ -118,8 +115,8 @@ public class InitBinderDataBinderFactoryTests { WebDataBinderFactory factory = createFactory("initBinderTypeConversion", WebDataBinder.class, int.class); WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, "foo"); - assertNotNull(dataBinder.getDisallowedFields()); - assertEquals("requestParam-22", dataBinder.getDisallowedFields()[0]); + assertThat(dataBinder.getDisallowedFields()).isNotNull(); + assertThat(dataBinder.getDisallowedFields()[0]).isEqualTo("requestParam-22"); } private WebDataBinderFactory createFactory(String methodName, Class... parameterTypes) diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/MapMethodProcessorTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/MapMethodProcessorTests.java index 6bbaeeb58cf..53805d9647d 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/MapMethodProcessorTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/MapMethodProcessorTests.java @@ -31,10 +31,7 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.ResolvableMethod; import org.springframework.web.method.support.ModelAndViewContainer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with @@ -64,22 +61,21 @@ public class MapMethodProcessorTests { @Test public void supportsParameter() { - assertTrue(this.processor.supportsParameter( - this.resolvable.annotNotPresent().arg(Map.class, String.class, Object.class))); - assertFalse(this.processor.supportsParameter( - this.resolvable.annotPresent(RequestBody.class).arg(Map.class, String.class, Object.class))); + assertThat(this.processor.supportsParameter( + this.resolvable.annotNotPresent().arg(Map.class, String.class, Object.class))).isTrue(); + assertThat(this.processor.supportsParameter( + this.resolvable.annotPresent(RequestBody.class).arg(Map.class, String.class, Object.class))).isFalse(); } @Test public void supportsReturnType() { - assertTrue(this.processor.supportsReturnType(this.resolvable.returnType())); + assertThat(this.processor.supportsReturnType(this.resolvable.returnType())).isTrue(); } @Test public void resolveArgumentValue() throws Exception { MethodParameter param = this.resolvable.annotNotPresent().arg(Map.class, String.class, Object.class); - assertSame(this.mavContainer.getModel(), - this.processor.resolveArgument(param, this.mavContainer, this.webRequest, null)); + assertThat(this.processor.resolveArgument(param, this.mavContainer, this.webRequest, null)).isSameAs(this.mavContainer.getModel()); } @Test @@ -90,8 +86,8 @@ public class MapMethodProcessorTests { this.processor.handleReturnValue( returnValue , this.resolvable.returnType(), this.mavContainer, this.webRequest); - assertEquals("value1", mavContainer.getModel().get("attr1")); - assertEquals("value2", mavContainer.getModel().get("attr2")); + assertThat(mavContainer.getModel().get("attr1")).isEqualTo("value1"); + assertThat(mavContainer.getModel().get("attr2")).isEqualTo("value2"); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java index 31dc4da81b4..5a80f5a4c60 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java @@ -45,11 +45,8 @@ import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; +import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.notNull; @@ -108,12 +105,12 @@ public class ModelAttributeMethodProcessorTests { @Test public void supportedParameters() throws Exception { - assertTrue(this.processor.supportsParameter(this.paramNamedValidModelAttr)); - assertTrue(this.processor.supportsParameter(this.paramModelAttr)); + assertThat(this.processor.supportsParameter(this.paramNamedValidModelAttr)).isTrue(); + assertThat(this.processor.supportsParameter(this.paramModelAttr)).isTrue(); - assertFalse(this.processor.supportsParameter(this.paramErrors)); - assertFalse(this.processor.supportsParameter(this.paramInt)); - assertFalse(this.processor.supportsParameter(this.paramNonSimpleType)); + assertThat(this.processor.supportsParameter(this.paramErrors)).isFalse(); + assertThat(this.processor.supportsParameter(this.paramInt)).isFalse(); + assertThat(this.processor.supportsParameter(this.paramNonSimpleType)).isFalse(); } @Test @@ -121,32 +118,32 @@ public class ModelAttributeMethodProcessorTests { processor = new ModelAttributeMethodProcessor(true); // Only non-simple types, even if not annotated - assertTrue(this.processor.supportsParameter(this.paramNamedValidModelAttr)); - assertTrue(this.processor.supportsParameter(this.paramErrors)); - assertTrue(this.processor.supportsParameter(this.paramModelAttr)); - assertTrue(this.processor.supportsParameter(this.paramNonSimpleType)); + assertThat(this.processor.supportsParameter(this.paramNamedValidModelAttr)).isTrue(); + assertThat(this.processor.supportsParameter(this.paramErrors)).isTrue(); + assertThat(this.processor.supportsParameter(this.paramModelAttr)).isTrue(); + assertThat(this.processor.supportsParameter(this.paramNonSimpleType)).isTrue(); - assertFalse(this.processor.supportsParameter(this.paramInt)); + assertThat(this.processor.supportsParameter(this.paramInt)).isFalse(); } @Test public void supportedReturnTypes() throws Exception { processor = new ModelAttributeMethodProcessor(false); - assertTrue(this.processor.supportsReturnType(returnParamNamedModelAttr)); - assertFalse(this.processor.supportsReturnType(returnParamNonSimpleType)); + assertThat(this.processor.supportsReturnType(returnParamNamedModelAttr)).isTrue(); + assertThat(this.processor.supportsReturnType(returnParamNonSimpleType)).isFalse(); } @Test public void supportedReturnTypesInDefaultResolutionMode() throws Exception { processor = new ModelAttributeMethodProcessor(true); - assertTrue(this.processor.supportsReturnType(returnParamNamedModelAttr)); - assertTrue(this.processor.supportsReturnType(returnParamNonSimpleType)); + assertThat(this.processor.supportsReturnType(returnParamNamedModelAttr)).isTrue(); + assertThat(this.processor.supportsReturnType(returnParamNonSimpleType)).isTrue(); } @Test public void bindExceptionRequired() throws Exception { - assertTrue(this.processor.isBindExceptionRequired(null, this.paramNonSimpleType)); - assertFalse(this.processor.isBindExceptionRequired(null, this.paramNamedValidModelAttr)); + assertThat(this.processor.isBindExceptionRequired(null, this.paramNonSimpleType)).isTrue(); + assertThat(this.processor.isBindExceptionRequired(null, this.paramNamedValidModelAttr)).isFalse(); } @Test @@ -178,8 +175,8 @@ public class ModelAttributeMethodProcessorTests { this.processor.resolveArgument(this.paramNamedValidModelAttr, this.container, this.request, factory); - assertTrue(dataBinder.isBindInvoked()); - assertTrue(dataBinder.isValidateInvoked()); + assertThat(dataBinder.isBindInvoked()).isTrue(); + assertThat(dataBinder.isValidateInvoked()).isTrue(); } @Test @@ -197,8 +194,8 @@ public class ModelAttributeMethodProcessorTests { this.processor.resolveArgument(this.paramNamedValidModelAttr, this.container, this.request, factory); - assertFalse(dataBinder.isBindInvoked()); - assertTrue(dataBinder.isValidateInvoked()); + assertThat(dataBinder.isBindInvoked()).isFalse(); + assertThat(dataBinder.isValidateInvoked()).isTrue(); } @Test @@ -213,8 +210,8 @@ public class ModelAttributeMethodProcessorTests { this.processor.resolveArgument(this.paramBindingDisabledAttr, this.container, this.request, factory); - assertFalse(dataBinder.isBindInvoked()); - assertTrue(dataBinder.isValidateInvoked()); + assertThat(dataBinder.isBindInvoked()).isFalse(); + assertThat(dataBinder.isValidateInvoked()).isTrue(); } @Test @@ -250,21 +247,21 @@ public class ModelAttributeMethodProcessorTests { this.processor.resolveArgument(this.paramModelAttr, this.container, this.request, binderFactory); Object[] values = this.container.getModel().values().toArray(); - assertSame("Resolved attribute should be updated to be last", testBean, values[1]); - assertSame("BindingResult of resolved attr should be last", dataBinder.getBindingResult(), values[2]); + assertThat(values[1]).as("Resolved attribute should be updated to be last").isSameAs(testBean); + assertThat(values[2]).as("BindingResult of resolved attr should be last").isSameAs(dataBinder.getBindingResult()); } @Test public void handleAnnotatedReturnValue() throws Exception { this.processor.handleReturnValue("expected", this.returnParamNamedModelAttr, this.container, this.request); - assertEquals("expected", this.container.getModel().get("modelAttrName")); + assertThat(this.container.getModel().get("modelAttrName")).isEqualTo("expected"); } @Test public void handleNotAnnotatedReturnValue() throws Exception { TestBean testBean = new TestBean("expected"); this.processor.handleReturnValue(testBean, this.returnParamNonSimpleType, this.container, this.request); - assertSame(testBean, this.container.getModel().get("testBean")); + assertThat(this.container.getModel().get("testBean")).isSameAs(testBean); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryOrderingTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryOrderingTests.java index 10050ad0fdc..0cd5240cc6c 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryOrderingTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryOrderingTests.java @@ -47,7 +47,7 @@ import org.springframework.web.method.support.HandlerMethodArgumentResolverCompo import org.springframework.web.method.support.InvocableHandlerMethod; import org.springframework.web.method.support.ModelAndViewContainer; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests verifying {@code @ModelAttribute} method inter-dependencies. @@ -144,8 +144,8 @@ public class ModelFactoryOrderingTests { private void assertInvokedBefore(String beforeMethod, String... afterMethods) { List actual = getInvokedMethods(); for (String afterMethod : afterMethods) { - assertTrue(beforeMethod + " should be before " + afterMethod + ". Actual order: " + - actual.toString(), actual.indexOf(beforeMethod) < actual.indexOf(afterMethod)); + assertThat(actual.indexOf(beforeMethod) < actual.indexOf(afterMethod)).as(beforeMethod + " should be before " + afterMethod + ". Actual order: " + + actual.toString()).isTrue(); } } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java index a28e724f5af..801b0dff3d1 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java @@ -41,11 +41,8 @@ import org.springframework.web.method.support.HandlerMethodArgumentResolverCompo import org.springframework.web.method.support.InvocableHandlerMethod; import org.springframework.web.method.support.ModelAndViewContainer; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -83,7 +80,7 @@ public class ModelFactoryTests { HandlerMethod handlerMethod = createHandlerMethod("handle"); modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod); - assertEquals(Boolean.TRUE, this.mavContainer.getModel().get("modelAttr")); + assertThat(this.mavContainer.getModel().get("modelAttr")).isEqualTo(Boolean.TRUE); } @Test @@ -92,7 +89,7 @@ public class ModelFactoryTests { HandlerMethod handlerMethod = createHandlerMethod("handle"); modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod); - assertEquals(Boolean.TRUE, this.mavContainer.getModel().get("name")); + assertThat(this.mavContainer.getModel().get("name")).isEqualTo(Boolean.TRUE); } @Test @@ -101,7 +98,7 @@ public class ModelFactoryTests { HandlerMethod handlerMethod = createHandlerMethod("handle"); modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod); - assertEquals(Boolean.TRUE, this.mavContainer.getModel().get("boolean")); + assertThat(this.mavContainer.getModel().get("boolean")).isEqualTo(Boolean.TRUE); } @Test @@ -110,8 +107,8 @@ public class ModelFactoryTests { HandlerMethod handlerMethod = createHandlerMethod("handle"); modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod); - assertTrue(this.mavContainer.containsAttribute("name")); - assertNull(this.mavContainer.getModel().get("name")); + assertThat(this.mavContainer.containsAttribute("name")).isTrue(); + assertThat(this.mavContainer.getModel().get("name")).isNull(); } @Test @@ -120,8 +117,8 @@ public class ModelFactoryTests { HandlerMethod handlerMethod = createHandlerMethod("handle"); modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod); - assertTrue(this.mavContainer.containsAttribute("foo")); - assertTrue(this.mavContainer.isBindingDisabled("foo")); + assertThat(this.mavContainer.containsAttribute("foo")).isTrue(); + assertThat(this.mavContainer.isBindingDisabled("foo")).isTrue(); } @Test @@ -133,9 +130,9 @@ public class ModelFactoryTests { HandlerMethod handlerMethod = createHandlerMethod("handle"); modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod); - assertTrue(this.mavContainer.containsAttribute("foo")); - assertSame(foo, this.mavContainer.getModel().get("foo")); - assertTrue(this.mavContainer.isBindingDisabled("foo")); + assertThat(this.mavContainer.containsAttribute("foo")).isTrue(); + assertThat(this.mavContainer.getModel().get("foo")).isSameAs(foo); + assertThat(this.mavContainer.isBindingDisabled("foo")).isTrue(); } @Test @@ -146,7 +143,7 @@ public class ModelFactoryTests { HandlerMethod handlerMethod = createHandlerMethod("handle"); modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod); - assertEquals("sessionAttrValue", this.mavContainer.getModel().get("sessionAttr")); + assertThat(this.mavContainer.getModel().get("sessionAttr")).isEqualTo("sessionAttrValue"); } @Test @@ -160,7 +157,7 @@ public class ModelFactoryTests { this.attributeStore.storeAttribute(this.webRequest, "sessionAttr", "sessionAttrValue"); modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod); - assertEquals("sessionAttrValue", this.mavContainer.getModel().get("sessionAttr")); + assertThat(this.mavContainer.getModel().get("sessionAttr")).isEqualTo("sessionAttrValue"); } @Test @@ -177,10 +174,10 @@ public class ModelFactoryTests { ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler); modelFactory.updateModel(this.webRequest, container); - assertEquals(command, container.getModel().get(commandName)); + assertThat(container.getModel().get(commandName)).isEqualTo(command); String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + commandName; - assertSame(dataBinder.getBindingResult(), container.getModel().get(bindingResultKey)); - assertEquals(2, container.getModel().size()); + assertThat(container.getModel().get(bindingResultKey)).isSameAs(dataBinder.getBindingResult()); + assertThat(container.getModel().size()).isEqualTo(2); } @Test @@ -197,8 +194,8 @@ public class ModelFactoryTests { ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler); modelFactory.updateModel(this.webRequest, container); - assertEquals(attribute, container.getModel().get(attributeName)); - assertEquals(attribute, this.attributeStore.retrieveAttribute(this.webRequest, attributeName)); + assertThat(container.getModel().get(attributeName)).isEqualTo(attribute); + assertThat(this.attributeStore.retrieveAttribute(this.webRequest, attributeName)).isEqualTo(attribute); } @Test @@ -219,8 +216,8 @@ public class ModelFactoryTests { ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler); modelFactory.updateModel(this.webRequest, container); - assertEquals(attribute, container.getModel().get(attributeName)); - assertNull(this.attributeStore.retrieveAttribute(this.webRequest, attributeName)); + assertThat(container.getModel().get(attributeName)).isEqualTo(attribute); + assertThat(this.attributeStore.retrieveAttribute(this.webRequest, attributeName)).isNull(); } @Test // SPR-12542 @@ -242,9 +239,9 @@ public class ModelFactoryTests { ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler); modelFactory.updateModel(this.webRequest, container); - assertEquals(queryParam, container.getModel().get(queryParamName)); - assertEquals(1, container.getModel().size()); - assertEquals(attribute, this.attributeStore.retrieveAttribute(this.webRequest, attributeName)); + assertThat(container.getModel().get(queryParamName)).isEqualTo(queryParam); + assertThat(container.getModel().size()).isEqualTo(1); + assertThat(this.attributeStore.retrieveAttribute(this.webRequest, attributeName)).isEqualTo(attribute); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelMethodProcessorTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelMethodProcessorTests.java index 416e04ac453..d44402809e0 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelMethodProcessorTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelMethodProcessorTests.java @@ -29,9 +29,7 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link org.springframework.web.method.annotation.ModelMethodProcessor}. @@ -64,17 +62,17 @@ public class ModelMethodProcessorTests { @Test public void supportsParameter() { - assertTrue(processor.supportsParameter(paramModel)); + assertThat(processor.supportsParameter(paramModel)).isTrue(); } @Test public void supportsReturnType() { - assertTrue(processor.supportsReturnType(returnParamModel)); + assertThat(processor.supportsReturnType(returnParamModel)).isTrue(); } @Test public void resolveArgumentValue() throws Exception { - assertSame(mavContainer.getModel(), processor.resolveArgument(paramModel, mavContainer, webRequest, null)); + assertThat(processor.resolveArgument(paramModel, mavContainer, webRequest, null)).isSameAs(mavContainer.getModel()); } @Test @@ -85,8 +83,8 @@ public class ModelMethodProcessorTests { processor.handleReturnValue(returnValue , returnParamModel, mavContainer, webRequest); - assertEquals("value1", mavContainer.getModel().get("attr1")); - assertEquals("value2", mavContainer.getModel().get("attr2")); + assertThat(mavContainer.getModel().get("attr1")).isEqualTo("value1"); + assertThat(mavContainer.getModel().get("attr2")).isEqualTo("value2"); } @SuppressWarnings("unused") diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java index fe00d06ef98..90477601242 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java @@ -34,9 +34,7 @@ import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Text fixture with {@link RequestHeaderMapMethodArgumentResolver}. @@ -78,10 +76,10 @@ public class RequestHeaderMapMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue("Map parameter not supported", resolver.supportsParameter(paramMap)); - assertTrue("MultiValueMap parameter not supported", resolver.supportsParameter(paramMultiValueMap)); - assertTrue("HttpHeaders parameter not supported", resolver.supportsParameter(paramHttpHeaders)); - assertFalse("non-@RequestParam map supported", resolver.supportsParameter(paramUnsupported)); + assertThat(resolver.supportsParameter(paramMap)).as("Map parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramMultiValueMap)).as("MultiValueMap parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramHttpHeaders)).as("HttpHeaders parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramUnsupported)).as("non-@RequestParam map supported").isFalse(); } @Test @@ -93,8 +91,9 @@ public class RequestHeaderMapMethodArgumentResolverTests { Object result = resolver.resolveArgument(paramMap, null, webRequest, null); - assertTrue(result instanceof Map); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof Map; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test @@ -112,8 +111,9 @@ public class RequestHeaderMapMethodArgumentResolverTests { Object result = resolver.resolveArgument(paramMultiValueMap, null, webRequest, null); - assertTrue(result instanceof MultiValueMap); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof MultiValueMap; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test @@ -131,8 +131,9 @@ public class RequestHeaderMapMethodArgumentResolverTests { Object result = resolver.resolveArgument(paramHttpHeaders, null, webRequest, null); - assertTrue(result instanceof HttpHeaders); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof HttpHeaders; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolverTests.java index 51b4f878e38..bbe771b404b 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolverTests.java @@ -41,11 +41,8 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.support.GenericWebApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Test fixture with {@link RequestHeaderMethodArgumentResolver}. @@ -105,9 +102,9 @@ public class RequestHeaderMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue("String parameter not supported", resolver.supportsParameter(paramNamedDefaultValueStringHeader)); - assertTrue("String array parameter not supported", resolver.supportsParameter(paramNamedValueStringArray)); - assertFalse("non-@RequestParam parameter supported", resolver.supportsParameter(paramNamedValueMap)); + assertThat(resolver.supportsParameter(paramNamedDefaultValueStringHeader)).as("String parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramNamedValueStringArray)).as("String array parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramNamedValueMap)).as("non-@RequestParam parameter supported").isFalse(); } @Test @@ -116,8 +113,9 @@ public class RequestHeaderMethodArgumentResolverTests { servletRequest.addHeader("name", expected); Object result = resolver.resolveArgument(paramNamedDefaultValueStringHeader, null, webRequest, null); - assertTrue(result instanceof String); - assertEquals(expected, result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(expected); } @Test @@ -126,15 +124,17 @@ public class RequestHeaderMethodArgumentResolverTests { servletRequest.addHeader("name", expected); Object result = resolver.resolveArgument(paramNamedValueStringArray, null, webRequest, null); - assertTrue(result instanceof String[]); - assertArrayEquals(expected, (String[]) result); + boolean condition = result instanceof String[]; + assertThat(condition).isTrue(); + assertThat((String[]) result).isEqualTo(expected); } @Test public void resolveDefaultValue() throws Exception { Object result = resolver.resolveArgument(paramNamedDefaultValueStringHeader, null, webRequest, null); - assertTrue(result instanceof String); - assertEquals("bar", result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo("bar"); } @Test @@ -142,8 +142,9 @@ public class RequestHeaderMethodArgumentResolverTests { System.setProperty("systemProperty", "bar"); try { Object result = resolver.resolveArgument(paramSystemProperty, null, webRequest, null); - assertTrue(result instanceof String); - assertEquals("bar", result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo("bar"); } finally { System.clearProperty("systemProperty"); @@ -158,8 +159,9 @@ public class RequestHeaderMethodArgumentResolverTests { System.setProperty("systemProperty", "bar"); try { Object result = resolver.resolveArgument(paramResolvedNameWithExpression, null, webRequest, null); - assertTrue(result instanceof String); - assertEquals(expected, result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(expected); } finally { System.clearProperty("systemProperty"); @@ -174,8 +176,9 @@ public class RequestHeaderMethodArgumentResolverTests { System.setProperty("systemProperty", "bar"); try { Object result = resolver.resolveArgument(paramResolvedNameWithPlaceholder, null, webRequest, null); - assertTrue(result instanceof String); - assertEquals(expected, result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(expected); } finally { System.clearProperty("systemProperty"); @@ -187,8 +190,9 @@ public class RequestHeaderMethodArgumentResolverTests { servletRequest.setContextPath("/bar"); Object result = resolver.resolveArgument(paramContextPath, null, webRequest, null); - assertTrue(result instanceof String); - assertEquals("/bar", result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo("/bar"); } @Test @@ -208,8 +212,9 @@ public class RequestHeaderMethodArgumentResolverTests { Object result = resolver.resolveArgument(paramDate, null, webRequest, new DefaultDataBinderFactory(bindingInitializer)); - assertTrue(result instanceof Date); - assertEquals(new Date(rfc1123val), result); + boolean condition = result instanceof Date; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(new Date(rfc1123val)); } @Test @@ -222,8 +227,9 @@ public class RequestHeaderMethodArgumentResolverTests { Object result = resolver.resolveArgument(paramInstant, null, webRequest, new DefaultDataBinderFactory(bindingInitializer)); - assertTrue(result instanceof Instant); - assertEquals(Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(rfc1123val)), result); + boolean condition = result instanceof Instant; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(rfc1123val))); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMapMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMapMethodArgumentResolverTests.java index 2b334e7c309..6a9dfe81ae9 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMapMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMapMethodArgumentResolverTests.java @@ -36,9 +36,7 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.ResolvableMethod; import org.springframework.web.multipart.MultipartFile; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.method.MvcAnnotationPredicates.requestParam; /** @@ -62,16 +60,16 @@ public class RequestParamMapMethodArgumentResolverTests { @Test public void supportsParameter() { MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(Map.class, String.class, String.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(MultiValueMap.class, String.class, String.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestParam().name("name")).arg(Map.class, String.class, String.class); - assertFalse(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isFalse(); param = this.testMethod.annotNotPresent(RequestParam.class).arg(Map.class, String.class, String.class); - assertFalse(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isFalse(); } @Test @@ -84,8 +82,9 @@ public class RequestParamMapMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(Map.class, String.class, String.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof Map); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof Map; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test @@ -102,8 +101,9 @@ public class RequestParamMapMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultiValueMap.class, String.class, String.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof MultiValueMap); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof MultiValueMap; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test @@ -119,11 +119,12 @@ public class RequestParamMapMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(Map.class, String.class, MultipartFile.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof Map); + boolean condition = result instanceof Map; + assertThat(condition).isTrue(); Map resultMap = (Map) result; - assertEquals(2, resultMap.size()); - assertEquals(expected1, resultMap.get("mfile")); - assertEquals(expected2, resultMap.get("other")); + assertThat(resultMap.size()).isEqualTo(2); + assertThat(resultMap.get("mfile")).isEqualTo(expected1); + assertThat(resultMap.get("other")).isEqualTo(expected2); } @Test @@ -141,14 +142,15 @@ public class RequestParamMapMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(MultiValueMap.class, String.class, MultipartFile.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof MultiValueMap); + boolean condition = result instanceof MultiValueMap; + assertThat(condition).isTrue(); MultiValueMap resultMap = (MultiValueMap) result; - assertEquals(2, resultMap.size()); - assertEquals(2, resultMap.get("mfilelist").size()); - assertEquals(expected1, resultMap.get("mfilelist").get(0)); - assertEquals(expected2, resultMap.get("mfilelist").get(1)); - assertEquals(1, resultMap.get("other").size()); - assertEquals(expected3, resultMap.get("other").get(0)); + assertThat(resultMap.size()).isEqualTo(2); + assertThat(resultMap.get("mfilelist").size()).isEqualTo(2); + assertThat(resultMap.get("mfilelist").get(0)).isEqualTo(expected1); + assertThat(resultMap.get("mfilelist").get(1)).isEqualTo(expected2); + assertThat(resultMap.get("other").size()).isEqualTo(1); + assertThat(resultMap.get("other").get(0)).isEqualTo(expected3); } @Test @@ -165,11 +167,12 @@ public class RequestParamMapMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(Map.class, String.class, Part.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof Map); + boolean condition = result instanceof Map; + assertThat(condition).isTrue(); Map resultMap = (Map) result; - assertEquals(2, resultMap.size()); - assertEquals(expected1, resultMap.get("mfile")); - assertEquals(expected2, resultMap.get("other")); + assertThat(resultMap.size()).isEqualTo(2); + assertThat(resultMap.get("mfile")).isEqualTo(expected1); + assertThat(resultMap.get("other")).isEqualTo(expected2); } @Test @@ -188,14 +191,15 @@ public class RequestParamMapMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(MultiValueMap.class, String.class, Part.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof MultiValueMap); + boolean condition = result instanceof MultiValueMap; + assertThat(condition).isTrue(); MultiValueMap resultMap = (MultiValueMap) result; - assertEquals(2, resultMap.size()); - assertEquals(2, resultMap.get("mfilelist").size()); - assertEquals(expected1, resultMap.get("mfilelist").get(0)); - assertEquals(expected2, resultMap.get("mfilelist").get(1)); - assertEquals(1, resultMap.get("other").size()); - assertEquals(expected3, resultMap.get("other").get(0)); + assertThat(resultMap.size()).isEqualTo(2); + assertThat(resultMap.get("mfilelist").size()).isEqualTo(2); + assertThat(resultMap.get("mfilelist").get(0)).isEqualTo(expected1); + assertThat(resultMap.get("mfilelist").get(1)).isEqualTo(expected2); + assertThat(resultMap.get("other").size()).isEqualTo(1); + assertThat(resultMap.get("other").get(0)).isEqualTo(expected3); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java index b42d89fb923..81b738459fe 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java @@ -47,12 +47,8 @@ import org.springframework.web.multipart.MultipartException; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.support.MissingServletRequestPartException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.web.method.MvcAnnotationPredicates.requestParam; @@ -81,69 +77,69 @@ public class RequestParamMethodArgumentResolverTests { resolver = new RequestParamMethodArgumentResolver(null, true); MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(String[].class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestParam().name("name")).arg(Map.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(List.class, MultipartFile.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile[].class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(Part.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(List.class, Part.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(Part[].class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestParam().noName()).arg(Map.class); - assertFalse(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isFalse(); param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotNotPresent().arg(MultipartFile.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotNotPresent(RequestParam.class).arg(List.class, MultipartFile.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotNotPresent(RequestParam.class).arg(Part.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestPart()).arg(MultipartFile.class); - assertFalse(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isFalse(); param = this.testMethod.annot(requestParam()).arg(String.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestParam().notRequired()).arg(String.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, Integer.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, MultipartFile.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); resolver = new RequestParamMethodArgumentResolver(null, false); param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class); - assertFalse(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isFalse(); param = this.testMethod.annotPresent(RequestPart.class).arg(MultipartFile.class); - assertFalse(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isFalse(); } @Test @@ -153,8 +149,9 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof String); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test @@ -164,8 +161,9 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(String[].class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof String[]); - assertArrayEquals("Invalid result", expected, (String[]) result); + boolean condition = result instanceof String[]; + assertThat(condition).isTrue(); + assertThat((String[]) result).as("Invalid result").isEqualTo(expected); } @Test @@ -177,8 +175,9 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof MultipartFile); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof MultipartFile; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test @@ -194,8 +193,9 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(List.class, MultipartFile.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof List); - assertEquals(Arrays.asList(expected1, expected2), result); + boolean condition = result instanceof List; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(Arrays.asList(expected1, expected2)); } @Test @@ -211,11 +211,12 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile[].class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof MultipartFile[]); + boolean condition = result instanceof MultipartFile[]; + assertThat(condition).isTrue(); MultipartFile[] parts = (MultipartFile[]) result; - assertEquals(2, parts.length); - assertEquals(parts[0], expected1); - assertEquals(parts[1], expected2); + assertThat(parts.length).isEqualTo(2); + assertThat(expected1).isEqualTo(parts[0]); + assertThat(expected2).isEqualTo(parts[1]); } @Test @@ -230,8 +231,9 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Part.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof Part); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof Part; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test @@ -249,8 +251,9 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(List.class, Part.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof List); - assertEquals(Arrays.asList(expected1, expected2), result); + boolean condition = result instanceof List; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(Arrays.asList(expected1, expected2)); } @Test @@ -268,11 +271,12 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Part[].class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof Part[]); + boolean condition = result instanceof Part[]; + assertThat(condition).isTrue(); Part[] parts = (Part[]) result; - assertEquals(2, parts.length); - assertEquals(parts[0], expected1); - assertEquals(parts[1], expected2); + assertThat(parts.length).isEqualTo(2); + assertThat(expected1).isEqualTo(parts[0]); + assertThat(expected2).isEqualTo(parts[1]); } @Test @@ -284,8 +288,9 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotNotPresent().arg(MultipartFile.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof MultipartFile); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof MultipartFile; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test @@ -301,8 +306,9 @@ public class RequestParamMethodArgumentResolverTests { .annotNotPresent(RequestParam.class).arg(List.class, MultipartFile.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof List); - assertEquals(Arrays.asList(expected1, expected2), result); + boolean condition = result instanceof List; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(Arrays.asList(expected1, expected2)); } @Test @@ -324,8 +330,9 @@ public class RequestParamMethodArgumentResolverTests { .annotNotPresent(RequestParam.class).arg(List.class, MultipartFile.class); Object actual = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(actual instanceof List); - assertEquals(expected, ((List) actual).get(0)); + boolean condition = actual instanceof List; + assertThat(condition).isTrue(); + assertThat(((List) actual).get(0)).isEqualTo(expected); } @Test @@ -356,16 +363,18 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(Part.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof Part); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof Part; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test public void resolveDefaultValue() throws Exception { MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof String); - assertEquals("Invalid result", "bar", result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo("bar"); } @Test @@ -387,7 +396,7 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class); Object arg = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertNull(arg); + assertThat(arg).isNull(); } @Test @@ -402,7 +411,7 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestParam().notRequired()).arg(String.class); Object arg = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertNull(arg); + assertThat(arg).isNull(); } @Test @@ -411,15 +420,16 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertTrue(result instanceof String); - assertEquals("plainValue", result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo("plainValue"); } @Test // SPR-8561 public void resolveSimpleTypeParamToNull() throws Exception { MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertNull(result); + assertThat(result).isNull(); } @Test // SPR-10180 @@ -427,7 +437,7 @@ public class RequestParamMethodArgumentResolverTests { request.addParameter("name", ""); MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertEquals("bar", result); + assertThat(result).isEqualTo("bar"); } @Test @@ -435,7 +445,7 @@ public class RequestParamMethodArgumentResolverTests { request.addParameter("stringNotAnnot", ""); MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertEquals("", result); + assertThat(result).isEqualTo(""); } @Test @@ -443,7 +453,7 @@ public class RequestParamMethodArgumentResolverTests { request.addParameter("name", ""); MethodParameter param = this.testMethod.annot(requestParam().notRequired()).arg(String.class); Object result = resolver.resolveArgument(param, null, webRequest, null); - assertEquals("", result); + assertThat(result).isEqualTo(""); } @Test @@ -455,12 +465,12 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, Integer.class); Object result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.empty(), result); + assertThat(result).isEqualTo(Optional.empty()); request.addParameter("name", "123"); result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.class, result.getClass()); - assertEquals(123, ((Optional) result).get()); + assertThat(result.getClass()).isEqualTo(Optional.class); + assertThat(((Optional) result).get()).isEqualTo(123); } @Test @@ -472,11 +482,11 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, Integer.class); Object result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.empty(), result); + assertThat(result).isEqualTo(Optional.empty()); result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.class, result.getClass()); - assertFalse(((Optional) result).isPresent()); + assertThat(result.getClass()).isEqualTo(Optional.class); + assertThat(((Optional) result).isPresent()).isFalse(); } @Test @@ -488,12 +498,12 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, Integer[].class); Object result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.empty(), result); + assertThat(result).isEqualTo(Optional.empty()); request.addParameter("name", "123", "456"); result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.class, result.getClass()); - assertArrayEquals(new Integer[] {123, 456}, (Integer[]) ((Optional) result).get()); + assertThat(result.getClass()).isEqualTo(Optional.class); + assertThat((Integer[]) ((Optional) result).get()).isEqualTo(new Integer[] {123, 456}); } @Test @@ -505,11 +515,11 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, Integer[].class); Object result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.empty(), result); + assertThat(result).isEqualTo(Optional.empty()); result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.class, result.getClass()); - assertFalse(((Optional) result).isPresent()); + assertThat(result.getClass()).isEqualTo(Optional.class); + assertThat(((Optional) result).isPresent()).isFalse(); } @Test @@ -521,12 +531,12 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, List.class); Object result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.empty(), result); + assertThat(result).isEqualTo(Optional.empty()); request.addParameter("name", "123", "456"); result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.class, result.getClass()); - assertEquals(Arrays.asList("123", "456"), ((Optional) result).get()); + assertThat(result.getClass()).isEqualTo(Optional.class); + assertThat(((Optional) result).get()).isEqualTo(Arrays.asList("123", "456")); } @Test @@ -538,11 +548,11 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, List.class); Object result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.empty(), result); + assertThat(result).isEqualTo(Optional.empty()); result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.class, result.getClass()); - assertFalse(((Optional) result).isPresent()); + assertThat(result.getClass()).isEqualTo(Optional.class); + assertThat(((Optional) result).isPresent()).isFalse(); } @Test @@ -559,8 +569,9 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, MultipartFile.class); Object result = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertTrue(result instanceof Optional); - assertEquals("Invalid result", expected, ((Optional) result).get()); + boolean condition = result instanceof Optional; + assertThat(condition).isTrue(); + assertThat(((Optional) result).get()).as("Invalid result").isEqualTo(expected); } @Test @@ -575,7 +586,7 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, MultipartFile.class); Object actual = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.empty(), actual); + assertThat(actual).isEqualTo(Optional.empty()); } @Test @@ -587,7 +598,7 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, MultipartFile.class); Object actual = resolver.resolveArgument(param, null, webRequest, binderFactory); - assertEquals(Optional.empty(), actual); + assertThat(actual).isEqualTo(Optional.empty()); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/SessionAttributesHandlerTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/SessionAttributesHandlerTests.java index 9734654a028..bb6506e533e 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/SessionAttributesHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/SessionAttributesHandlerTests.java @@ -31,11 +31,7 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link SessionAttributesHandler}. @@ -53,10 +49,10 @@ public class SessionAttributesHandlerTests { @Test public void isSessionAttribute() throws Exception { - assertTrue(sessionAttributesHandler.isHandlerSessionAttribute("attr1", String.class)); - assertTrue(sessionAttributesHandler.isHandlerSessionAttribute("attr2", String.class)); - assertTrue(sessionAttributesHandler.isHandlerSessionAttribute("simple", TestBean.class)); - assertFalse(sessionAttributesHandler.isHandlerSessionAttribute("simple", String.class)); + assertThat(sessionAttributesHandler.isHandlerSessionAttribute("attr1", String.class)).isTrue(); + assertThat(sessionAttributesHandler.isHandlerSessionAttribute("attr2", String.class)).isTrue(); + assertThat(sessionAttributesHandler.isHandlerSessionAttribute("simple", TestBean.class)).isTrue(); + assertThat(sessionAttributesHandler.isHandlerSessionAttribute("simple", String.class)).isFalse(); } @Test @@ -66,16 +62,12 @@ public class SessionAttributesHandlerTests { sessionAttributeStore.storeAttribute(request, "attr3", new TestBean()); sessionAttributeStore.storeAttribute(request, "attr4", new TestBean()); - assertEquals("Named attributes (attr1, attr2) should be 'known' right away", - new HashSet<>(asList("attr1", "attr2")), - sessionAttributesHandler.retrieveAttributes(request).keySet()); + assertThat(sessionAttributesHandler.retrieveAttributes(request).keySet()).as("Named attributes (attr1, attr2) should be 'known' right away").isEqualTo(new HashSet<>(asList("attr1", "attr2"))); // Resolve 'attr3' by type sessionAttributesHandler.isHandlerSessionAttribute("attr3", TestBean.class); - assertEquals("Named attributes (attr1, attr2) and resolved attribute (att3) should be 'known'", - new HashSet<>(asList("attr1", "attr2", "attr3")), - sessionAttributesHandler.retrieveAttributes(request).keySet()); + assertThat(sessionAttributesHandler.retrieveAttributes(request).keySet()).as("Named attributes (attr1, attr2) and resolved attribute (att3) should be 'known'").isEqualTo(new HashSet<>(asList("attr1", "attr2", "attr3"))); } @Test @@ -86,15 +78,15 @@ public class SessionAttributesHandlerTests { sessionAttributesHandler.cleanupAttributes(request); - assertNull(sessionAttributeStore.retrieveAttribute(request, "attr1")); - assertNull(sessionAttributeStore.retrieveAttribute(request, "attr2")); - assertNotNull(sessionAttributeStore.retrieveAttribute(request, "attr3")); + assertThat(sessionAttributeStore.retrieveAttribute(request, "attr1")).isNull(); + assertThat(sessionAttributeStore.retrieveAttribute(request, "attr2")).isNull(); + assertThat(sessionAttributeStore.retrieveAttribute(request, "attr3")).isNotNull(); // Resolve 'attr3' by type sessionAttributesHandler.isHandlerSessionAttribute("attr3", TestBean.class); sessionAttributesHandler.cleanupAttributes(request); - assertNull(sessionAttributeStore.retrieveAttribute(request, "attr3")); + assertThat(sessionAttributeStore.retrieveAttribute(request, "attr3")).isNull(); } @Test @@ -106,9 +98,10 @@ public class SessionAttributesHandlerTests { sessionAttributesHandler.storeAttributes(request, model); - assertEquals("value1", sessionAttributeStore.retrieveAttribute(request, "attr1")); - assertEquals("value2", sessionAttributeStore.retrieveAttribute(request, "attr2")); - assertTrue(sessionAttributeStore.retrieveAttribute(request, "attr3") instanceof TestBean); + assertThat(sessionAttributeStore.retrieveAttribute(request, "attr1")).isEqualTo("value1"); + assertThat(sessionAttributeStore.retrieveAttribute(request, "attr2")).isEqualTo("value2"); + boolean condition = sessionAttributeStore.retrieveAttribute(request, "attr3") instanceof TestBean; + assertThat(condition).isTrue(); } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java index eed9572900f..7d1b27a0bdc 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java @@ -27,11 +27,9 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletWebRequest; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -72,7 +70,7 @@ public class WebArgumentResolverAdapterTests { public void supportsParameter() throws Exception { given(adaptee.resolveArgument(parameter, webRequest)).willReturn(42); - assertTrue("Parameter not supported", adapter.supportsParameter(parameter)); + assertThat(adapter.supportsParameter(parameter)).as("Parameter not supported").isTrue(); verify(adaptee).resolveArgument(parameter, webRequest); } @@ -81,7 +79,7 @@ public class WebArgumentResolverAdapterTests { public void supportsParameterUnresolved() throws Exception { given(adaptee.resolveArgument(parameter, webRequest)).willReturn(WebArgumentResolver.UNRESOLVED); - assertFalse("Parameter supported", adapter.supportsParameter(parameter)); + assertThat(adapter.supportsParameter(parameter)).as("Parameter supported").isFalse(); verify(adaptee).resolveArgument(parameter, webRequest); } @@ -90,7 +88,7 @@ public class WebArgumentResolverAdapterTests { public void supportsParameterWrongType() throws Exception { given(adaptee.resolveArgument(parameter, webRequest)).willReturn("Foo"); - assertFalse("Parameter supported", adapter.supportsParameter(parameter)); + assertThat(adapter.supportsParameter(parameter)).as("Parameter supported").isFalse(); verify(adaptee).resolveArgument(parameter, webRequest); } @@ -99,7 +97,7 @@ public class WebArgumentResolverAdapterTests { public void supportsParameterThrowsException() throws Exception { given(adaptee.resolveArgument(parameter, webRequest)).willThrow(new Exception()); - assertFalse("Parameter supported", adapter.supportsParameter(parameter)); + assertThat(adapter.supportsParameter(parameter)).as("Parameter supported").isFalse(); verify(adaptee).resolveArgument(parameter, webRequest); } @@ -110,7 +108,7 @@ public class WebArgumentResolverAdapterTests { given(adaptee.resolveArgument(parameter, webRequest)).willReturn(expected); Object result = adapter.resolveArgument(parameter, null, webRequest, null); - assertEquals("Invalid result", expected, result); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/method/support/CompositeUriComponentsContributorTests.java b/spring-web/src/test/java/org/springframework/web/method/support/CompositeUriComponentsContributorTests.java index eaace301104..3e8fbc9da94 100644 --- a/spring-web/src/test/java/org/springframework/web/method/support/CompositeUriComponentsContributorTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/support/CompositeUriComponentsContributorTests.java @@ -29,8 +29,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.method.annotation.RequestHeaderMethodArgumentResolver; import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for @@ -52,9 +51,9 @@ public class CompositeUriComponentsContributorTests { Method method = ClassUtils.getMethod(this.getClass(), "handleRequest", String.class, String.class, String.class); CompositeUriComponentsContributor contributor = new CompositeUriComponentsContributor(resolvers); - assertTrue(contributor.supportsParameter(new MethodParameter(method, 0))); - assertTrue(contributor.supportsParameter(new MethodParameter(method, 1))); - assertFalse(contributor.supportsParameter(new MethodParameter(method, 2))); + assertThat(contributor.supportsParameter(new MethodParameter(method, 0))).isTrue(); + assertThat(contributor.supportsParameter(new MethodParameter(method, 1))).isTrue(); + assertThat(contributor.supportsParameter(new MethodParameter(method, 2))).isFalse(); } diff --git a/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodArgumentResolverCompositeTests.java b/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodArgumentResolverCompositeTests.java index 49b2dcc67a3..17043120c15 100644 --- a/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodArgumentResolverCompositeTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodArgumentResolverCompositeTests.java @@ -23,10 +23,8 @@ import org.junit.Test; import org.springframework.core.MethodParameter; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Test fixture with {@link HandlerMethodArgumentResolverComposite}. @@ -56,8 +54,8 @@ public class HandlerMethodArgumentResolverCompositeTests { public void supportsParameter() { this.resolverComposite.addResolver(new StubArgumentResolver(Integer.class)); - assertTrue(this.resolverComposite.supportsParameter(paramInt)); - assertFalse(this.resolverComposite.supportsParameter(paramStr)); + assertThat(this.resolverComposite.supportsParameter(paramInt)).isTrue(); + assertThat(this.resolverComposite.supportsParameter(paramStr)).isFalse(); } @Test @@ -65,7 +63,7 @@ public class HandlerMethodArgumentResolverCompositeTests { this.resolverComposite.addResolver(new StubArgumentResolver(55)); Object resolvedValue = this.resolverComposite.resolveArgument(paramInt, null, null, null); - assertEquals(55, resolvedValue); + assertThat(resolvedValue).isEqualTo(55); } @Test @@ -74,7 +72,7 @@ public class HandlerMethodArgumentResolverCompositeTests { this.resolverComposite.addResolver(new StubArgumentResolver(2)); Object resolvedValue = this.resolverComposite.resolveArgument(paramInt, null, null, null); - assertEquals("Didn't use the first registered resolver", 1, resolvedValue); + assertThat(resolvedValue).as("Didn't use the first registered resolver").isEqualTo(1); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerCompositeTests.java b/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerCompositeTests.java index 388c251f1dd..d23581c5b39 100644 --- a/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerCompositeTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerCompositeTests.java @@ -21,9 +21,8 @@ import org.junit.Test; import org.springframework.core.MethodParameter; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -64,8 +63,8 @@ public class HandlerMethodReturnValueHandlerCompositeTests { @Test public void supportsReturnType() throws Exception { - assertTrue(this.handlers.supportsReturnType(this.integerType)); - assertFalse(this.handlers.supportsReturnType(this.stringType)); + assertThat(this.handlers.supportsReturnType(this.integerType)).isTrue(); + assertThat(this.handlers.supportsReturnType(this.stringType)).isFalse(); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/method/support/InvocableHandlerMethodTests.java b/spring-web/src/test/java/org/springframework/web/method/support/InvocableHandlerMethodTests.java index cca464308c5..e589fa7fabf 100644 --- a/spring-web/src/test/java/org/springframework/web/method/support/InvocableHandlerMethodTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/support/InvocableHandlerMethodTests.java @@ -29,11 +29,10 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.ResolvableMethod; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Unit tests for {@link InvocableHandlerMethod}. @@ -60,11 +59,11 @@ public class InvocableHandlerMethodTests { Object value = getInvocable(Integer.class, String.class).invokeForRequest(request, null); - assertEquals(1, getStubResolver(0).getResolvedParameters().size()); - assertEquals(1, getStubResolver(1).getResolvedParameters().size()); - assertEquals("99-value", value); - assertEquals("intArg", getStubResolver(0).getResolvedParameters().get(0).getParameterName()); - assertEquals("stringArg", getStubResolver(1).getResolvedParameters().get(0).getParameterName()); + assertThat(getStubResolver(0).getResolvedParameters().size()).isEqualTo(1); + assertThat(getStubResolver(1).getResolvedParameters().size()).isEqualTo(1); + assertThat(value).isEqualTo("99-value"); + assertThat(getStubResolver(0).getResolvedParameters().get(0).getParameterName()).isEqualTo("intArg"); + assertThat(getStubResolver(1).getResolvedParameters().get(0).getParameterName()).isEqualTo("stringArg"); } @Test @@ -74,9 +73,9 @@ public class InvocableHandlerMethodTests { Object returnValue = getInvocable(Integer.class, String.class).invokeForRequest(request, null); - assertEquals(1, getStubResolver(0).getResolvedParameters().size()); - assertEquals(1, getStubResolver(1).getResolvedParameters().size()); - assertEquals("null-null", returnValue); + assertThat(getStubResolver(0).getResolvedParameters().size()).isEqualTo(1); + assertThat(getStubResolver(1).getResolvedParameters().size()).isEqualTo(1); + assertThat(returnValue).isEqualTo("null-null"); } @Test @@ -90,9 +89,9 @@ public class InvocableHandlerMethodTests { public void resolveProvidedArg() throws Exception { Object value = getInvocable(Integer.class, String.class).invokeForRequest(request, null, 99, "value"); - assertNotNull(value); - assertEquals(String.class, value.getClass()); - assertEquals("99-value", value); + assertThat(value).isNotNull(); + assertThat(value.getClass()).isEqualTo(String.class); + assertThat(value).isEqualTo("99-value"); } @Test @@ -101,7 +100,7 @@ public class InvocableHandlerMethodTests { this.composite.addResolver(new StubArgumentResolver("value1")); Object value = getInvocable(Integer.class, String.class).invokeForRequest(request, null, 2, "value2"); - assertEquals("2-value2", value); + assertThat(value).isEqualTo("2-value2"); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/method/support/ModelAndViewContainerTests.java b/spring-web/src/test/java/org/springframework/web/method/support/ModelAndViewContainerTests.java index 00963c2ef12..ad9fe35fce5 100644 --- a/spring-web/src/test/java/org/springframework/web/method/support/ModelAndViewContainerTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/support/ModelAndViewContainerTests.java @@ -21,8 +21,7 @@ import org.junit.Test; import org.springframework.ui.ModelMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link ModelAndViewContainer}. @@ -44,8 +43,8 @@ public class ModelAndViewContainerTests { @Test public void getModel() { this.mavContainer.addAttribute("name", "value"); - assertEquals(1, this.mavContainer.getModel().size()); - assertEquals("value", this.mavContainer.getModel().get("name")); + assertThat(this.mavContainer.getModel().size()).isEqualTo(1); + assertThat(this.mavContainer.getModel().get("name")).isEqualTo("value"); } @Test @@ -54,8 +53,8 @@ public class ModelAndViewContainerTests { this.mavContainer.setRedirectModel(new ModelMap("name2", "value2")); this.mavContainer.setRedirectModelScenario(true); - assertEquals(1, this.mavContainer.getModel().size()); - assertEquals("value2", this.mavContainer.getModel().get("name2")); + assertThat(this.mavContainer.getModel().size()).isEqualTo(1); + assertThat(this.mavContainer.getModel().get("name2")).isEqualTo("value2"); } @Test @@ -63,8 +62,8 @@ public class ModelAndViewContainerTests { this.mavContainer.addAttribute("name", "value"); this.mavContainer.setRedirectModelScenario(true); - assertEquals(1, this.mavContainer.getModel().size()); - assertEquals("value", this.mavContainer.getModel().get("name")); + assertThat(this.mavContainer.getModel().size()).isEqualTo(1); + assertThat(this.mavContainer.getModel().get("name")).isEqualTo("value"); } @Test @@ -73,7 +72,7 @@ public class ModelAndViewContainerTests { this.mavContainer.addAttribute("name", "value"); this.mavContainer.setRedirectModelScenario(true); - assertTrue(this.mavContainer.getModel().isEmpty()); + assertThat(this.mavContainer.getModel().isEmpty()).isTrue(); } @Test // SPR-14045 @@ -82,8 +81,8 @@ public class ModelAndViewContainerTests { this.mavContainer.setRedirectModelScenario(true); this.mavContainer.addAttribute("name", "value"); - assertEquals(1, this.mavContainer.getModel().size()); - assertEquals("value", this.mavContainer.getModel().get("name")); + assertThat(this.mavContainer.getModel().size()).isEqualTo(1); + assertThat(this.mavContainer.getModel().get("name")).isEqualTo("value"); } diff --git a/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java b/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java index 0cd32271c05..68eab8ebbaf 100644 --- a/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java @@ -61,10 +61,7 @@ import org.springframework.web.multipart.support.MultipartFilter; import org.springframework.web.multipart.support.StringMultipartFileEditor; import org.springframework.web.util.WebUtils; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -96,17 +93,17 @@ public class CommonsMultipartResolverTests { resolver.setResolveLazily(false); } resolver.setServletContext(wac.getServletContext()); - assertEquals(1000, resolver.getFileUpload().getSizeMax()); - assertEquals(100, resolver.getFileItemFactory().getSizeThreshold()); - assertEquals("enc", resolver.getFileUpload().getHeaderEncoding()); - assertTrue(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp")); + assertThat(resolver.getFileUpload().getSizeMax()).isEqualTo(1000); + assertThat(resolver.getFileItemFactory().getSizeThreshold()).isEqualTo(100); + assertThat(resolver.getFileUpload().getHeaderEncoding()).isEqualTo("enc"); + assertThat(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp")).isTrue(); MockHttpServletRequest originalRequest = new MockHttpServletRequest(); originalRequest.setMethod("POST"); originalRequest.setContentType("multipart/form-data"); originalRequest.addHeader("Content-type", "multipart/form-data"); originalRequest.addParameter("getField", "getValue"); - assertTrue(resolver.isMultipart(originalRequest)); + assertThat(resolver.isMultipart(originalRequest)).isTrue(); MultipartHttpServletRequest request = resolver.resolveMultipart(originalRequest); doTestParameters(request); @@ -124,21 +121,21 @@ public class CommonsMultipartResolverTests { while (parameterEnum.hasMoreElements()) { parameterNames.add(parameterEnum.nextElement()); } - assertEquals(3, parameterNames.size()); - assertTrue(parameterNames.contains("field3")); - assertTrue(parameterNames.contains("field4")); - assertTrue(parameterNames.contains("getField")); - assertEquals("value3", request.getParameter("field3")); + assertThat(parameterNames.size()).isEqualTo(3); + assertThat(parameterNames.contains("field3")).isTrue(); + assertThat(parameterNames.contains("field4")).isTrue(); + assertThat(parameterNames.contains("getField")).isTrue(); + assertThat(request.getParameter("field3")).isEqualTo("value3"); List parameterValues = Arrays.asList(request.getParameterValues("field3")); - assertEquals(1, parameterValues.size()); - assertTrue(parameterValues.contains("value3")); - assertEquals("value4", request.getParameter("field4")); + assertThat(parameterValues.size()).isEqualTo(1); + assertThat(parameterValues.contains("value3")).isTrue(); + assertThat(request.getParameter("field4")).isEqualTo("value4"); parameterValues = Arrays.asList(request.getParameterValues("field4")); - assertEquals(2, parameterValues.size()); - assertTrue(parameterValues.contains("value4")); - assertTrue(parameterValues.contains("value5")); - assertEquals("value4", request.getParameter("field4")); - assertEquals("getValue", request.getParameter("getField")); + assertThat(parameterValues.size()).isEqualTo(2); + assertThat(parameterValues.contains("value4")).isTrue(); + assertThat(parameterValues.contains("value5")).isTrue(); + assertThat(request.getParameter("field4")).isEqualTo("value4"); + assertThat(request.getParameter("getField")).isEqualTo("getValue"); List parameterMapKeys = new ArrayList<>(); List parameterMapValues = new ArrayList<>(); @@ -147,24 +144,24 @@ public class CommonsMultipartResolverTests { parameterMapKeys.add(key); parameterMapValues.add(request.getParameterMap().get(key)); } - assertEquals(3, parameterMapKeys.size()); - assertEquals(3, parameterMapValues.size()); + assertThat(parameterMapKeys.size()).isEqualTo(3); + assertThat(parameterMapValues.size()).isEqualTo(3); int field3Index = parameterMapKeys.indexOf("field3"); int field4Index = parameterMapKeys.indexOf("field4"); int getFieldIndex = parameterMapKeys.indexOf("getField"); - assertTrue(field3Index != -1); - assertTrue(field4Index != -1); - assertTrue(getFieldIndex != -1); + assertThat(field3Index != -1).isTrue(); + assertThat(field4Index != -1).isTrue(); + assertThat(getFieldIndex != -1).isTrue(); parameterValues = Arrays.asList((String[]) parameterMapValues.get(field3Index)); - assertEquals(1, parameterValues.size()); - assertTrue(parameterValues.contains("value3")); + assertThat(parameterValues.size()).isEqualTo(1); + assertThat(parameterValues.contains("value3")).isTrue(); parameterValues = Arrays.asList((String[]) parameterMapValues.get(field4Index)); - assertEquals(2, parameterValues.size()); - assertTrue(parameterValues.contains("value4")); - assertTrue(parameterValues.contains("value5")); + assertThat(parameterValues.size()).isEqualTo(2); + assertThat(parameterValues.contains("value4")).isTrue(); + assertThat(parameterValues.contains("value5")).isTrue(); parameterValues = Arrays.asList((String[]) parameterMapValues.get(getFieldIndex)); - assertEquals(1, parameterValues.size()); - assertTrue(parameterValues.contains("getValue")); + assertThat(parameterValues.size()).isEqualTo(1); + assertThat(parameterValues.contains("getValue")).isTrue(); } private void doTestFiles(MultipartHttpServletRequest request) throws IOException { @@ -173,53 +170,55 @@ public class CommonsMultipartResolverTests { while (fileIter.hasNext()) { fileNames.add(fileIter.next()); } - assertEquals(3, fileNames.size()); - assertTrue(fileNames.contains("field1")); - assertTrue(fileNames.contains("field2")); - assertTrue(fileNames.contains("field2x")); + assertThat(fileNames.size()).isEqualTo(3); + assertThat(fileNames.contains("field1")).isTrue(); + assertThat(fileNames.contains("field2")).isTrue(); + assertThat(fileNames.contains("field2x")).isTrue(); CommonsMultipartFile file1 = (CommonsMultipartFile) request.getFile("field1"); CommonsMultipartFile file2 = (CommonsMultipartFile) request.getFile("field2"); CommonsMultipartFile file2x = (CommonsMultipartFile) request.getFile("field2x"); Map fileMap = request.getFileMap(); - assertEquals(3, fileMap.size()); - assertTrue(fileMap.containsKey("field1")); - assertTrue(fileMap.containsKey("field2")); - assertTrue(fileMap.containsKey("field2x")); - assertEquals(file1, fileMap.get("field1")); - assertEquals(file2, fileMap.get("field2")); - assertEquals(file2x, fileMap.get("field2x")); + assertThat(fileMap.size()).isEqualTo(3); + assertThat(fileMap.containsKey("field1")).isTrue(); + assertThat(fileMap.containsKey("field2")).isTrue(); + assertThat(fileMap.containsKey("field2x")).isTrue(); + assertThat(fileMap.get("field1")).isEqualTo(file1); + assertThat(fileMap.get("field2")).isEqualTo(file2); + assertThat(fileMap.get("field2x")).isEqualTo(file2x); MultiValueMap multiFileMap = request.getMultiFileMap(); - assertEquals(3, multiFileMap.size()); - assertTrue(multiFileMap.containsKey("field1")); - assertTrue(multiFileMap.containsKey("field2")); - assertTrue(multiFileMap.containsKey("field2x")); + assertThat(multiFileMap.size()).isEqualTo(3); + assertThat(multiFileMap.containsKey("field1")).isTrue(); + assertThat(multiFileMap.containsKey("field2")).isTrue(); + assertThat(multiFileMap.containsKey("field2x")).isTrue(); List field1Files = multiFileMap.get("field1"); - assertEquals(2, field1Files.size()); - assertTrue(field1Files.contains(file1)); - assertEquals(file1, multiFileMap.getFirst("field1")); - assertEquals(file2, multiFileMap.getFirst("field2")); - assertEquals(file2x, multiFileMap.getFirst("field2x")); + assertThat(field1Files.size()).isEqualTo(2); + assertThat(field1Files.contains(file1)).isTrue(); + assertThat(multiFileMap.getFirst("field1")).isEqualTo(file1); + assertThat(multiFileMap.getFirst("field2")).isEqualTo(file2); + assertThat(multiFileMap.getFirst("field2x")).isEqualTo(file2x); - assertEquals("type1", file1.getContentType()); - assertEquals("type2", file2.getContentType()); - assertEquals("type2", file2x.getContentType()); - assertEquals("field1.txt", file1.getOriginalFilename()); - assertEquals("field2.txt", file2.getOriginalFilename()); - assertEquals("field2x.txt", file2x.getOriginalFilename()); - assertEquals("text1", new String(file1.getBytes())); - assertEquals("text2", new String(file2.getBytes())); - assertEquals(5, file1.getSize()); - assertEquals(5, file2.getSize()); - assertTrue(file1.getInputStream() instanceof ByteArrayInputStream); - assertTrue(file2.getInputStream() instanceof ByteArrayInputStream); + assertThat(file1.getContentType()).isEqualTo("type1"); + assertThat(file2.getContentType()).isEqualTo("type2"); + assertThat(file2x.getContentType()).isEqualTo("type2"); + assertThat(file1.getOriginalFilename()).isEqualTo("field1.txt"); + assertThat(file2.getOriginalFilename()).isEqualTo("field2.txt"); + assertThat(file2x.getOriginalFilename()).isEqualTo("field2x.txt"); + assertThat(new String(file1.getBytes())).isEqualTo("text1"); + assertThat(new String(file2.getBytes())).isEqualTo("text2"); + assertThat(file1.getSize()).isEqualTo(5); + assertThat(file2.getSize()).isEqualTo(5); + boolean condition1 = file1.getInputStream() instanceof ByteArrayInputStream; + assertThat(condition1).isTrue(); + boolean condition = file2.getInputStream() instanceof ByteArrayInputStream; + assertThat(condition).isTrue(); File transfer1 = new File("C:/transfer1"); file1.transferTo(transfer1); File transfer2 = new File("C:/transfer2"); file2.transferTo(transfer2); - assertEquals(transfer1, ((MockFileItem) file1.getFileItem()).writtenFile); - assertEquals(transfer2, ((MockFileItem) file2.getFileItem()).writtenFile); + assertThat(((MockFileItem) file1.getFileItem()).writtenFile).isEqualTo(transfer1); + assertThat(((MockFileItem) file2.getFileItem()).writtenFile).isEqualTo(transfer2); } @@ -227,8 +226,8 @@ public class CommonsMultipartResolverTests { MultipartHttpServletRequest request) throws UnsupportedEncodingException { MultipartTestBean1 mtb1 = new MultipartTestBean1(); - assertArrayEquals(null, mtb1.getField1()); - assertEquals(null, mtb1.getField2()); + assertThat(mtb1.getField1()).isEqualTo(null); + assertThat(mtb1.getField2()).isEqualTo(null); ServletRequestDataBinder binder = new ServletRequestDataBinder(mtb1, "mybean"); binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor()); binder.bind(request); @@ -236,38 +235,38 @@ public class CommonsMultipartResolverTests { CommonsMultipartFile file1a = (CommonsMultipartFile) file1List.get(0); CommonsMultipartFile file1b = (CommonsMultipartFile) file1List.get(1); CommonsMultipartFile file2 = (CommonsMultipartFile) request.getFile("field2"); - assertEquals(file1a, mtb1.getField1()[0]); - assertEquals(file1b, mtb1.getField1()[1]); - assertEquals(new String(file2.getBytes()), new String(mtb1.getField2())); + assertThat(mtb1.getField1()[0]).isEqualTo(file1a); + assertThat(mtb1.getField1()[1]).isEqualTo(file1b); + assertThat(new String(mtb1.getField2())).isEqualTo(new String(file2.getBytes())); MultipartTestBean2 mtb2 = new MultipartTestBean2(); - assertArrayEquals(null, mtb2.getField1()); - assertEquals(null, mtb2.getField2()); + assertThat(mtb2.getField1()).isEqualTo(null); + assertThat(mtb2.getField2()).isEqualTo(null); binder = new ServletRequestDataBinder(mtb2, "mybean"); binder.registerCustomEditor(String.class, "field1", new StringMultipartFileEditor()); binder.registerCustomEditor(String.class, "field2", new StringMultipartFileEditor("UTF-16")); binder.bind(request); - assertEquals(new String(file1a.getBytes()), mtb2.getField1()[0]); - assertEquals(new String(file1b.getBytes()), mtb2.getField1()[1]); - assertEquals(new String(file2.getBytes(), "UTF-16"), mtb2.getField2()); + assertThat(mtb2.getField1()[0]).isEqualTo(new String(file1a.getBytes())); + assertThat(mtb2.getField1()[1]).isEqualTo(new String(file1b.getBytes())); + assertThat(mtb2.getField2()).isEqualTo(new String(file2.getBytes(), "UTF-16")); resolver.cleanupMultipart(request); - assertTrue(((MockFileItem) file1a.getFileItem()).deleted); - assertTrue(((MockFileItem) file1b.getFileItem()).deleted); - assertTrue(((MockFileItem) file2.getFileItem()).deleted); + assertThat(((MockFileItem) file1a.getFileItem()).deleted).isTrue(); + assertThat(((MockFileItem) file1b.getFileItem()).deleted).isTrue(); + assertThat(((MockFileItem) file2.getFileItem()).deleted).isTrue(); resolver.setEmpty(true); request = resolver.resolveMultipart(originalRequest); binder.setBindEmptyMultipartFiles(false); String firstBound = mtb2.getField2(); binder.bind(request); - assertFalse(mtb2.getField2().isEmpty()); - assertEquals(firstBound, mtb2.getField2()); + assertThat(mtb2.getField2().isEmpty()).isFalse(); + assertThat(mtb2.getField2()).isEqualTo(firstBound); request = resolver.resolveMultipart(originalRequest); binder.setBindEmptyMultipartFiles(true); binder.bind(request); - assertTrue(mtb2.getField2().isEmpty()); + assertThat(mtb2.getField2().isEmpty()).isTrue(); } @Test @@ -279,7 +278,7 @@ public class CommonsMultipartResolverTests { wac.refresh(); wac.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); CommonsMultipartResolver resolver = new CommonsMultipartResolver(wac.getServletContext()); - assertTrue(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp")); + assertThat(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp")).isTrue(); MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter"); filterConfig.addInitParameter("class", "notWritable"); @@ -307,8 +306,8 @@ public class CommonsMultipartResolverTests { CommonsMultipartFile file1 = (CommonsMultipartFile) files.get(0); CommonsMultipartFile file2 = (CommonsMultipartFile) files.get(1); - assertTrue(((MockFileItem) file1.getFileItem()).deleted); - assertTrue(((MockFileItem) file2.getFileItem()).deleted); + assertThat(((MockFileItem) file1.getFileItem()).deleted).isTrue(); + assertThat(((MockFileItem) file2.getFileItem()).deleted).isTrue(); } @Test @@ -320,7 +319,7 @@ public class CommonsMultipartResolverTests { wac.getServletContext().setAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File("mytemp")); wac.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); CommonsMultipartResolver resolver = new CommonsMultipartResolver(wac.getServletContext()); - assertTrue(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp")); + assertThat(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp")).isTrue(); MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter"); filterConfig.addInitParameter("multipartResolverBeanName", "myMultipartResolver"); @@ -359,8 +358,8 @@ public class CommonsMultipartResolverTests { filter.doFilter(originalRequest, response, filterChain); CommonsMultipartFile file1 = (CommonsMultipartFile) files.get(0); CommonsMultipartFile file2 = (CommonsMultipartFile) files.get(1); - assertTrue(((MockFileItem) file1.getFileItem()).deleted); - assertTrue(((MockFileItem) file2.getFileItem()).deleted); + assertThat(((MockFileItem) file1.getFileItem()).deleted).isTrue(); + assertThat(((MockFileItem) file2.getFileItem()).deleted).isTrue(); } diff --git a/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java b/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java index d66297c51b0..5c1b33f932e 100644 --- a/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java +++ b/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java @@ -22,8 +22,8 @@ import org.junit.Test; import org.springframework.web.multipart.MultipartFile; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -39,14 +39,14 @@ public class ByteArrayMultipartFileEditorTests { public void setValueAsByteArray() throws Exception { String expectedValue = "Shumwere, shumhow, a shuck ish washing you. - Drunken Far Side"; editor.setValue(expectedValue.getBytes()); - assertEquals(expectedValue, editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(expectedValue); } @Test public void setValueAsString() throws Exception { String expectedValue = "'Green Wing' - classic British comedy"; editor.setValue(expectedValue); - assertEquals(expectedValue, editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(expectedValue); } @Test @@ -60,13 +60,13 @@ public class ByteArrayMultipartFileEditorTests { }; editor.setValue(object); - assertEquals(expectedValue, editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(expectedValue); } @Test public void setValueAsNullGetsBackEmptyString() throws Exception { editor.setValue(null); - assertEquals("", editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(""); } @Test @@ -75,7 +75,7 @@ public class ByteArrayMultipartFileEditorTests { MultipartFile file = mock(MultipartFile.class); given(file.getBytes()).willReturn(expectedValue.getBytes()); editor.setValue(file); - assertEquals(expectedValue, editor.getAsText()); + assertThat(editor.getAsText()).isEqualTo(expectedValue); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/multipart/support/DefaultMultipartHttpServletRequestTests.java b/spring-web/src/test/java/org/springframework/web/multipart/support/DefaultMultipartHttpServletRequestTests.java index fc3ee0ca8a0..602447bfb22 100644 --- a/spring-web/src/test/java/org/springframework/web/multipart/support/DefaultMultipartHttpServletRequestTests.java +++ b/spring-web/src/test/java/org/springframework/web/multipart/support/DefaultMultipartHttpServletRequestTests.java @@ -25,8 +25,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link DefaultMultipartHttpServletRequest}. @@ -50,7 +49,7 @@ public class DefaultMultipartHttpServletRequestTests { String[] values = createMultipartRequest().getParameterValues("key"); - assertArrayEquals(new String[] {"p", "q"}, values); + assertThat(values).isEqualTo(new String[] {"p", "q"}); } @Test // SPR-16590 @@ -64,10 +63,10 @@ public class DefaultMultipartHttpServletRequestTests { Map map = createMultipartRequest().getParameterMap(); - assertEquals(3, map.size()); - assertArrayEquals(new String[] {"p1", "q1"}, map.get("key1")); - assertArrayEquals(new String[] {"p2"}, map.get("key2")); - assertArrayEquals(new String[] {"q3"}, map.get("key3")); + assertThat(map.size()).isEqualTo(3); + assertThat(map.get("key1")).isEqualTo(new String[] {"p1", "q1"}); + assertThat(map.get("key2")).isEqualTo(new String[] {"p2"}); + assertThat(map.get("key3")).isEqualTo(new String[] {"q3"}); } private DefaultMultipartHttpServletRequest createMultipartRequest() { diff --git a/spring-web/src/test/java/org/springframework/web/multipart/support/RequestPartServletServerHttpRequestTests.java b/spring-web/src/test/java/org/springframework/web/multipart/support/RequestPartServletServerHttpRequestTests.java index 7776c0dde07..5d1ff721280 100644 --- a/spring-web/src/test/java/org/springframework/web/multipart/support/RequestPartServletServerHttpRequestTests.java +++ b/spring-web/src/test/java/org/springframework/web/multipart/support/RequestPartServletServerHttpRequestTests.java @@ -32,9 +32,7 @@ import org.springframework.mock.web.test.MockMultipartHttpServletRequest; import org.springframework.util.FileCopyUtils; import org.springframework.web.multipart.MultipartFile; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rossen Stoyanchev @@ -50,7 +48,7 @@ public class RequestPartServletServerHttpRequestTests { ServerHttpRequest request = new RequestPartServletServerHttpRequest(this.mockRequest, "part"); this.mockRequest.setMethod("POST"); - assertEquals(HttpMethod.POST, request.getMethod()); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); } @Test @@ -64,7 +62,7 @@ public class RequestPartServletServerHttpRequestTests { this.mockRequest.setServerPort(uri.getPort()); this.mockRequest.setRequestURI(uri.getPath()); this.mockRequest.setQueryString(uri.getQuery()); - assertEquals(uri, request.getURI()); + assertThat(request.getURI()).isEqualTo(uri); } @Test @@ -74,8 +72,8 @@ public class RequestPartServletServerHttpRequestTests { ServerHttpRequest request = new RequestPartServletServerHttpRequest(this.mockRequest, "part"); HttpHeaders headers = request.getHeaders(); - assertNotNull(headers); - assertEquals(MediaType.APPLICATION_JSON, headers.getContentType()); + assertThat(headers).isNotNull(); + assertThat(headers.getContentType()).isEqualTo(MediaType.APPLICATION_JSON); } @Test @@ -86,7 +84,7 @@ public class RequestPartServletServerHttpRequestTests { ServerHttpRequest request = new RequestPartServletServerHttpRequest(this.mockRequest, "part"); byte[] result = FileCopyUtils.copyToByteArray(request.getBody()); - assertArrayEquals(bytes, result); + assertThat(result).isEqualTo(bytes); } @Test // SPR-13317 @@ -98,7 +96,7 @@ public class RequestPartServletServerHttpRequestTests { ServerHttpRequest request = new RequestPartServletServerHttpRequest(wrapped, "part"); byte[] result = FileCopyUtils.copyToByteArray(request.getBody()); - assertArrayEquals(bytes, result); + assertThat(result).isEqualTo(bytes); } @Test // SPR-13096 @@ -116,7 +114,7 @@ public class RequestPartServletServerHttpRequestTests { mockRequest.setParameter("part", new String(bytes, StandardCharsets.ISO_8859_1)); ServerHttpRequest request = new RequestPartServletServerHttpRequest(mockRequest, "part"); byte[] result = FileCopyUtils.copyToByteArray(request.getBody()); - assertArrayEquals(bytes, result); + assertThat(result).isEqualTo(bytes); } @Test @@ -135,7 +133,7 @@ public class RequestPartServletServerHttpRequestTests { mockRequest.setCharacterEncoding("iso-8859-1"); ServerHttpRequest request = new RequestPartServletServerHttpRequest(mockRequest, "part"); byte[] result = FileCopyUtils.copyToByteArray(request.getBody()); - assertArrayEquals(bytes, result); + assertThat(result).isEqualTo(bytes); } } diff --git a/spring-web/src/test/java/org/springframework/web/multipart/support/StandardMultipartHttpServletRequestTests.java b/spring-web/src/test/java/org/springframework/web/multipart/support/StandardMultipartHttpServletRequestTests.java index f67df3be5a7..e78a49c3c6b 100644 --- a/spring-web/src/test/java/org/springframework/web/multipart/support/StandardMultipartHttpServletRequestTests.java +++ b/spring-web/src/test/java/org/springframework/web/multipart/support/StandardMultipartHttpServletRequestTests.java @@ -30,8 +30,6 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.multipart.MultipartFile; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Unit tests for {@link StandardMultipartHttpServletRequest}. @@ -46,8 +44,8 @@ public class StandardMultipartHttpServletRequestTests { StandardMultipartHttpServletRequest request = requestWithPart("file", disposition, ""); MultipartFile multipartFile = request.getFile("file"); - assertNotNull(multipartFile); - assertEquals("myFile.txt", multipartFile.getOriginalFilename()); + assertThat(multipartFile).isNotNull(); + assertThat(multipartFile.getOriginalFilename()).isEqualTo("myFile.txt"); } @Test // SPR-13319 @@ -56,8 +54,8 @@ public class StandardMultipartHttpServletRequestTests { StandardMultipartHttpServletRequest request = requestWithPart("file", disposition, ""); MultipartFile multipartFile = request.getFile("file"); - assertNotNull(multipartFile); - assertEquals("foo-ä-€.html", multipartFile.getOriginalFilename()); + assertThat(multipartFile).isNotNull(); + assertThat(multipartFile.getOriginalFilename()).isEqualTo("foo-ä-€.html"); } @Test // SPR-15205 @@ -66,8 +64,8 @@ public class StandardMultipartHttpServletRequestTests { StandardMultipartHttpServletRequest request = requestWithPart("file", disposition, ""); MultipartFile multipartFile = request.getFile("file"); - assertNotNull(multipartFile); - assertEquals("Declaração.pdf", multipartFile.getOriginalFilename()); + assertThat(multipartFile).isNotNull(); + assertThat(multipartFile.getOriginalFilename()).isEqualTo("Declaração.pdf"); } @Test @@ -77,7 +75,7 @@ public class StandardMultipartHttpServletRequestTests { StandardMultipartHttpServletRequest request = requestWithPart(name, disposition, "myBody"); MultipartFile multipartFile = request.getFile(name); - assertNotNull(multipartFile); + assertThat(multipartFile).isNotNull(); MultiValueMap map = new LinkedMultiValueMap<>(); map.add(name, multipartFile.getResource()); diff --git a/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeCheckNotModifiedTests.java b/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeCheckNotModifiedTests.java index a2bf96cb6ab..920aaf7f5fe 100644 --- a/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeCheckNotModifiedTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeCheckNotModifiedTests.java @@ -36,10 +36,7 @@ import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; /** @@ -83,18 +80,18 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { MockServerWebExchange exchange = MockServerWebExchange.from(request); exchange.getResponse().setStatusCode(HttpStatus.NOT_MODIFIED); - assertFalse(exchange.checkNotModified(this.currentDate)); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(-1, exchange.getResponse().getHeaders().getLastModified()); + assertThat(exchange.checkNotModified(this.currentDate)).isFalse(); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().getLastModified()).isEqualTo(-1); } @Test // SPR-14559 public void checkNotModifiedInvalidIfNoneMatchHeader() { String eTag = "\"etagvalue\""; MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch("missingquotes")); - assertFalse(exchange.checkNotModified(eTag)); - assertNull(exchange.getResponse().getStatusCode()); - assertEquals(eTag, exchange.getResponse().getHeaders().getETag()); + assertThat(exchange.checkNotModified(eTag)).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(eTag); } @Test @@ -103,10 +100,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { MockServerWebExchange exchange = MockServerWebExchange.from(request); exchange.getResponse().getHeaders().add("Last-Modified", CURRENT_TIME); - assertTrue(exchange.checkNotModified(currentDate)); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(1, exchange.getResponse().getHeaders().get("Last-Modified").size()); - assertEquals(CURRENT_TIME, exchange.getResponse().getHeaders().getFirst("Last-Modified")); + assertThat(exchange.checkNotModified(currentDate)).isTrue(); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().get("Last-Modified").size()).isEqualTo(1); + assertThat(exchange.getResponse().getHeaders().getFirst("Last-Modified")).isEqualTo(CURRENT_TIME); } @Test @@ -114,10 +111,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { MockServerHttpRequest request = get("/").ifModifiedSince(currentDate.toEpochMilli()).build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertTrue(exchange.checkNotModified(currentDate)); + assertThat(exchange.checkNotModified(currentDate)).isTrue(); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(currentDate.toEpochMilli(), exchange.getResponse().getHeaders().getLastModified()); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().getLastModified()).isEqualTo(currentDate.toEpochMilli()); } @Test @@ -126,10 +123,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { MockServerHttpRequest request = get("/").ifModifiedSince(oneMinuteAgo.toEpochMilli()).build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertFalse(exchange.checkNotModified(currentDate)); + assertThat(exchange.checkNotModified(currentDate)).isFalse(); - assertNull(exchange.getResponse().getStatusCode()); - assertEquals(currentDate.toEpochMilli(), exchange.getResponse().getHeaders().getLastModified()); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + assertThat(exchange.getResponse().getHeaders().getLastModified()).isEqualTo(currentDate.toEpochMilli()); } @Test @@ -137,10 +134,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { String eTag = "\"Foo\""; MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch(eTag)); - assertTrue(exchange.checkNotModified(eTag)); + assertThat(exchange.checkNotModified(eTag)).isTrue(); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(eTag, exchange.getResponse().getHeaders().getETag()); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(eTag); } @Test @@ -148,10 +145,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { String eTag = "\"Foo, Bar\""; MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch(eTag)); - assertTrue(exchange.checkNotModified(eTag)); + assertThat(exchange.checkNotModified(eTag)).isTrue(); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(eTag, exchange.getResponse().getHeaders().getETag()); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(eTag); } @@ -161,10 +158,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { String oldEtag = "Bar"; MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch(oldEtag)); - assertFalse(exchange.checkNotModified(currentETag)); + assertThat(exchange.checkNotModified(currentETag)).isFalse(); - assertNull(exchange.getResponse().getStatusCode()); - assertEquals(currentETag, exchange.getResponse().getHeaders().getETag()); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(currentETag); } @Test @@ -173,10 +170,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { String paddedEtag = String.format("\"%s\"", eTag); MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch(paddedEtag)); - assertTrue(exchange.checkNotModified(eTag)); + assertThat(exchange.checkNotModified(eTag)).isTrue(); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(paddedEtag, exchange.getResponse().getHeaders().getETag()); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(paddedEtag); } @Test @@ -185,20 +182,20 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { String oldEtag = "Bar"; MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch(oldEtag)); - assertFalse(exchange.checkNotModified(currentETag)); + assertThat(exchange.checkNotModified(currentETag)).isFalse(); - assertNull(exchange.getResponse().getStatusCode()); - assertEquals(String.format("\"%s\"", currentETag), exchange.getResponse().getHeaders().getETag()); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(String.format("\"%s\"", currentETag)); } @Test public void checkNotModifiedWildcardIsIgnored() { String eTag = "\"Foo\""; MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch("*")); - assertFalse(exchange.checkNotModified(eTag)); + assertThat(exchange.checkNotModified(eTag)).isFalse(); - assertNull(exchange.getResponse().getStatusCode()); - assertEquals(eTag, exchange.getResponse().getHeaders().getETag()); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(eTag); } @Test @@ -208,11 +205,11 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { MockServerHttpRequest request = get("/").ifNoneMatch(eTag).ifModifiedSince(time).build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertTrue(exchange.checkNotModified(eTag, currentDate)); + assertThat(exchange.checkNotModified(eTag, currentDate)).isTrue(); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(eTag, exchange.getResponse().getHeaders().getETag()); - assertEquals(time, exchange.getResponse().getHeaders().getLastModified()); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(eTag); + assertThat(exchange.getResponse().getHeaders().getLastModified()).isEqualTo(time); } // SPR-14224 @@ -225,11 +222,11 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { .ifModifiedSince(oneMinuteAgo.toEpochMilli()) ); - assertTrue(exchange.checkNotModified(eTag, currentDate)); + assertThat(exchange.checkNotModified(eTag, currentDate)).isTrue(); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(eTag, exchange.getResponse().getHeaders().getETag()); - assertEquals(currentDate.toEpochMilli(), exchange.getResponse().getHeaders().getLastModified()); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(eTag); + assertThat(exchange.getResponse().getHeaders().getLastModified()).isEqualTo(currentDate.toEpochMilli()); } @Test @@ -240,11 +237,11 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { MockServerHttpRequest request = get("/").ifNoneMatch(oldEtag).ifModifiedSince(time).build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertFalse(exchange.checkNotModified(currentETag, currentDate)); + assertThat(exchange.checkNotModified(currentETag, currentDate)).isFalse(); - assertNull(exchange.getResponse().getStatusCode()); - assertEquals(currentETag, exchange.getResponse().getHeaders().getETag()); - assertEquals(time, exchange.getResponse().getHeaders().getLastModified()); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(currentETag); + assertThat(exchange.getResponse().getHeaders().getLastModified()).isEqualTo(time); } @Test @@ -253,10 +250,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { String weakEtag = String.format("W/%s", eTag); MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch(eTag)); - assertTrue(exchange.checkNotModified(weakEtag)); + assertThat(exchange.checkNotModified(weakEtag)).isTrue(); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(weakEtag, exchange.getResponse().getHeaders().getETag()); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(weakEtag); } @Test @@ -265,10 +262,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { MockServerHttpRequest request = get("/").ifNoneMatch(String.format("W/%s", eTag)).build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertTrue(exchange.checkNotModified(eTag)); + assertThat(exchange.checkNotModified(eTag)).isTrue(); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(eTag, exchange.getResponse().getHeaders().getETag()); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(eTag); } @Test @@ -277,10 +274,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { String multipleETags = String.format("\"Foo\", %s", eTag); MockServerWebExchange exchange = MockServerWebExchange.from(get("/").ifNoneMatch(multipleETags)); - assertTrue(exchange.checkNotModified(eTag)); + assertThat(exchange.checkNotModified(eTag)).isTrue(); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(eTag, exchange.getResponse().getHeaders().getETag()); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(eTag); } @Test @@ -290,10 +287,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { MockServerHttpRequest request = get("/").header("If-Modified-Since", header).build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertTrue(exchange.checkNotModified(Instant.ofEpochMilli(epochTime))); + assertThat(exchange.checkNotModified(Instant.ofEpochMilli(epochTime))).isTrue(); - assertEquals(304, exchange.getResponse().getStatusCode().value()); - assertEquals(epochTime, exchange.getResponse().getHeaders().getLastModified()); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(304); + assertThat(exchange.getResponse().getHeaders().getLastModified()).isEqualTo(epochTime); } @Test @@ -303,10 +300,10 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { MockServerHttpRequest request = get("/").header("If-Modified-Since", header).build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertFalse(exchange.checkNotModified(Instant.ofEpochMilli(epochTime))); + assertThat(exchange.checkNotModified(Instant.ofEpochMilli(epochTime))).isFalse(); - assertNull(exchange.getResponse().getStatusCode()); - assertEquals(epochTime, exchange.getResponse().getHeaders().getLastModified()); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + assertThat(exchange.getResponse().getHeaders().getLastModified()).isEqualTo(epochTime); } @Test @@ -316,9 +313,9 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { MockServerHttpRequest request = MockServerHttpRequest.put("/").ifUnmodifiedSince(millis).build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertFalse(exchange.checkNotModified(oneMinuteAgo)); - assertNull(exchange.getResponse().getStatusCode()); - assertEquals(-1, exchange.getResponse().getHeaders().getLastModified()); + assertThat(exchange.checkNotModified(oneMinuteAgo)).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + assertThat(exchange.getResponse().getHeaders().getLastModified()).isEqualTo(-1); } @Test @@ -328,9 +325,9 @@ public class DefaultServerWebExchangeCheckNotModifiedTests { MockServerHttpRequest request = MockServerHttpRequest.put("/").ifUnmodifiedSince(millis).build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertTrue(exchange.checkNotModified(currentDate)); - assertEquals(412, exchange.getResponse().getStatusCode().value()); - assertEquals(-1, exchange.getResponse().getHeaders().getLastModified()); + assertThat(exchange.checkNotModified(currentDate)).isTrue(); + assertThat(exchange.getResponse().getStatusCode().value()).isEqualTo(412); + assertThat(exchange.getResponse().getHeaders().getLastModified()).isEqualTo(-1); } } diff --git a/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeTests.java b/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeTests.java index 15602a0bd87..68ae32158e8 100644 --- a/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/adapter/DefaultServerWebExchangeTests.java @@ -25,7 +25,7 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; import org.springframework.web.server.session.DefaultWebSessionManager; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link DefaultServerWebExchange}. @@ -38,14 +38,14 @@ public class DefaultServerWebExchangeTests { @Test public void transformUrlDefault() { ServerWebExchange exchange = createExchange(); - assertEquals("/foo", exchange.transformUrl("/foo")); + assertThat(exchange.transformUrl("/foo")).isEqualTo("/foo"); } @Test public void transformUrlWithEncoder() { ServerWebExchange exchange = createExchange(); exchange.addUrlTransformer(s -> s + "?nonce=123"); - assertEquals("/foo?nonce=123", exchange.transformUrl("/foo")); + assertThat(exchange.transformUrl("/foo")).isEqualTo("/foo?nonce=123"); } @Test @@ -53,7 +53,7 @@ public class DefaultServerWebExchangeTests { ServerWebExchange exchange = createExchange(); exchange.addUrlTransformer(s -> s + ";p=abc"); exchange.addUrlTransformer(s -> s + "?q=123"); - assertEquals("/foo;p=abc?q=123", exchange.transformUrl("/foo")); + assertThat(exchange.transformUrl("/foo")).isEqualTo("/foo;p=abc?q=123"); } diff --git a/spring-web/src/test/java/org/springframework/web/server/adapter/ForwardedHeaderTransformerTests.java b/spring-web/src/test/java/org/springframework/web/server/adapter/ForwardedHeaderTransformerTests.java index a47b143d480..3d212dd9e83 100644 --- a/spring-web/src/test/java/org/springframework/web/server/adapter/ForwardedHeaderTransformerTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/adapter/ForwardedHeaderTransformerTests.java @@ -25,8 +25,7 @@ import org.springframework.http.HttpMethod; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ForwardedHeaderTransformer}. @@ -66,7 +65,7 @@ public class ForwardedHeaderTransformerTests { headers.add("foo", "bar"); ServerHttpRequest request = this.requestMutator.apply(getRequest(headers)); - assertEquals(new URI("https://84.198.58.199/path"), request.getURI()); + assertThat(request.getURI()).isEqualTo(new URI("https://84.198.58.199/path")); assertForwardedHeadersRemoved(request); } @@ -76,7 +75,7 @@ public class ForwardedHeaderTransformerTests { headers.add("Forwarded", "host=84.198.58.199;proto=https"); ServerHttpRequest request = this.requestMutator.apply(getRequest(headers)); - assertEquals(new URI("https://84.198.58.199/path"), request.getURI()); + assertThat(request.getURI()).isEqualTo(new URI("https://84.198.58.199/path")); assertForwardedHeadersRemoved(request); } @@ -86,8 +85,8 @@ public class ForwardedHeaderTransformerTests { headers.add("X-Forwarded-Prefix", "/prefix"); ServerHttpRequest request = this.requestMutator.apply(getRequest(headers)); - assertEquals(new URI("https://example.com/prefix/path"), request.getURI()); - assertEquals("/prefix/path", request.getPath().value()); + assertThat(request.getURI()).isEqualTo(new URI("https://example.com/prefix/path")); + assertThat(request.getPath().value()).isEqualTo("/prefix/path"); assertForwardedHeadersRemoved(request); } @@ -97,8 +96,8 @@ public class ForwardedHeaderTransformerTests { headers.add("X-Forwarded-Prefix", "/prefix////"); ServerHttpRequest request = this.requestMutator.apply(getRequest(headers)); - assertEquals(new URI("https://example.com/prefix/path"), request.getURI()); - assertEquals("/prefix/path", request.getPath().value()); + assertThat(request.getURI()).isEqualTo(new URI("https://example.com/prefix/path")); + assertThat(request.getPath().value()).isEqualTo("/prefix/path"); assertForwardedHeadersRemoved(request); } @@ -114,7 +113,7 @@ public class ForwardedHeaderTransformerTests { request = this.requestMutator.apply(request); - assertEquals(new URI("https://84.198.58.199/a%20b?q=a%2Bb"), request.getURI()); + assertThat(request.getURI()).isEqualTo(new URI("https://84.198.58.199/a%20b?q=a%2Bb")); assertForwardedHeadersRemoved(request); } @@ -125,7 +124,7 @@ public class ForwardedHeaderTransformerTests { private void assertForwardedHeadersRemoved(ServerHttpRequest request) { ForwardedHeaderTransformer.FORWARDED_HEADER_NAMES - .forEach(name -> assertFalse(request.getHeaders().containsKey(name))); + .forEach(name -> assertThat(request.getHeaders().containsKey(name)).isFalse()); } } diff --git a/spring-web/src/test/java/org/springframework/web/server/adapter/WebHttpHandlerBuilderTests.java b/spring-web/src/test/java/org/springframework/web/server/adapter/WebHttpHandlerBuilderTests.java index 61e64959a0c..44af80e2dde 100644 --- a/spring-web/src/test/java/org/springframework/web/server/adapter/WebHttpHandlerBuilderTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/adapter/WebHttpHandlerBuilderTests.java @@ -38,9 +38,7 @@ import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebHandler; import static java.time.Duration.ofMillis; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link WebHttpHandlerBuilder}. @@ -55,14 +53,15 @@ public class WebHttpHandlerBuilderTests { context.refresh(); HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(context).build(); - assertTrue(httpHandler instanceof HttpWebHandlerAdapter); - assertSame(context, ((HttpWebHandlerAdapter) httpHandler).getApplicationContext()); + boolean condition = httpHandler instanceof HttpWebHandlerAdapter; + assertThat(condition).isTrue(); + assertThat(((HttpWebHandlerAdapter) httpHandler).getApplicationContext()).isSameAs(context); MockServerHttpRequest request = MockServerHttpRequest.get("/").build(); MockServerHttpResponse response = new MockServerHttpResponse(); httpHandler.handle(request, response).block(ofMillis(5000)); - assertEquals("FilterB::FilterA", response.getBodyAsString().block(ofMillis(5000))); + assertThat(response.getBodyAsString().block(ofMillis(5000))).isEqualTo("FilterB::FilterA"); } @Test @@ -72,8 +71,8 @@ public class WebHttpHandlerBuilderTests { context.refresh(); WebHttpHandlerBuilder builder = WebHttpHandlerBuilder.applicationContext(context); - builder.filters(filters -> assertEquals(Collections.emptyList(), filters)); - assertTrue(builder.hasForwardedHeaderTransformer()); + builder.filters(filters -> assertThat(filters).isEqualTo(Collections.emptyList())); + assertThat(builder.hasForwardedHeaderTransformer()).isTrue(); } @Test // SPR-15074 @@ -87,7 +86,7 @@ public class WebHttpHandlerBuilderTests { MockServerHttpResponse response = new MockServerHttpResponse(); httpHandler.handle(request, response).block(ofMillis(5000)); - assertEquals("ExceptionHandlerB", response.getBodyAsString().block(ofMillis(5000))); + assertThat(response.getBodyAsString().block(ofMillis(5000))).isEqualTo("ExceptionHandlerB"); } @Test @@ -101,7 +100,7 @@ public class WebHttpHandlerBuilderTests { MockServerHttpResponse response = new MockServerHttpResponse(); httpHandler.handle(request, response).block(ofMillis(5000)); - assertEquals("handled", response.getBodyAsString().block(ofMillis(5000))); + assertThat(response.getBodyAsString().block(ofMillis(5000))).isEqualTo("handled"); } @Test // SPR-16972 @@ -111,8 +110,8 @@ public class WebHttpHandlerBuilderTests { context.refresh(); WebHttpHandlerBuilder builder = WebHttpHandlerBuilder.applicationContext(context); - assertSame(context, ((HttpWebHandlerAdapter) builder.build()).getApplicationContext()); - assertSame(context, ((HttpWebHandlerAdapter) builder.clone().build()).getApplicationContext()); + assertThat(((HttpWebHandlerAdapter) builder.build()).getApplicationContext()).isSameAs(context); + assertThat(((HttpWebHandlerAdapter) builder.clone().build()).getApplicationContext()).isSameAs(context); } diff --git a/spring-web/src/test/java/org/springframework/web/server/handler/ExceptionHandlingWebHandlerTests.java b/spring-web/src/test/java/org/springframework/web/server/handler/ExceptionHandlingWebHandlerTests.java index 0fba7a504ae..683905dc492 100644 --- a/spring-web/src/test/java/org/springframework/web/server/handler/ExceptionHandlingWebHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/handler/ExceptionHandlingWebHandlerTests.java @@ -30,8 +30,7 @@ import org.springframework.web.server.WebExceptionHandler; import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.HttpWebHandlerAdapter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ExceptionHandlingWebHandler}. @@ -48,7 +47,7 @@ public class ExceptionHandlingWebHandlerTests { @Test public void handleErrorSignal() throws Exception { createWebHandler(new BadRequestExceptionHandler()).handle(this.exchange).block(); - assertEquals(HttpStatus.BAD_REQUEST, this.exchange.getResponse().getStatusCode()); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test @@ -59,14 +58,14 @@ public class ExceptionHandlingWebHandlerTests { new BadRequestExceptionHandler(), new UnresolvedExceptionHandler()).handle(this.exchange).block(); - assertEquals(HttpStatus.BAD_REQUEST, this.exchange.getResponse().getStatusCode()); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test public void unresolvedException() throws Exception { Mono mono = createWebHandler(new UnresolvedExceptionHandler()).handle(this.exchange); StepVerifier.create(mono).expectErrorMessage("boo").verify(); - assertNull(this.exchange.getResponse().getStatusCode()); + assertThat(this.exchange.getResponse().getStatusCode()).isNull(); } @Test @@ -77,13 +76,13 @@ public class ExceptionHandlingWebHandlerTests { new HttpWebHandlerAdapter(createWebHandler(new UnresolvedExceptionHandler())) .handle(this.exchange.getRequest(), this.exchange.getResponse()).block(); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, this.exchange.getResponse().getStatusCode()); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @Test public void thrownExceptionBecomesErrorSignal() throws Exception { createWebHandler(new BadRequestExceptionHandler()).handle(this.exchange).block(); - assertEquals(HttpStatus.BAD_REQUEST, this.exchange.getResponse().getStatusCode()); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } private WebHandler createWebHandler(WebExceptionHandler... handlers) { diff --git a/spring-web/src/test/java/org/springframework/web/server/handler/FilteringWebHandlerTests.java b/spring-web/src/test/java/org/springframework/web/server/handler/FilteringWebHandlerTests.java index dfd2a96ef76..9d8830b212a 100644 --- a/spring-web/src/test/java/org/springframework/web/server/handler/FilteringWebHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/handler/FilteringWebHandlerTests.java @@ -36,10 +36,7 @@ import org.springframework.web.server.WebFilterChain; import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link FilteringWebHandler}. @@ -62,10 +59,10 @@ public class FilteringWebHandlerTests { .handle(MockServerWebExchange.from(MockServerHttpRequest.get("/"))) .block(Duration.ZERO); - assertTrue(filter1.invoked()); - assertTrue(filter2.invoked()); - assertTrue(filter3.invoked()); - assertTrue(targetHandler.invoked()); + assertThat(filter1.invoked()).isTrue(); + assertThat(filter2.invoked()).isTrue(); + assertThat(filter3.invoked()).isTrue(); + assertThat(targetHandler.invoked()).isTrue(); } @Test @@ -77,7 +74,7 @@ public class FilteringWebHandlerTests { .handle(MockServerWebExchange.from(MockServerHttpRequest.get("/"))) .block(Duration.ZERO); - assertTrue(targetHandler.invoked()); + assertThat(targetHandler.invoked()).isTrue(); } @Test @@ -92,10 +89,10 @@ public class FilteringWebHandlerTests { .handle(MockServerWebExchange.from(MockServerHttpRequest.get("/"))) .block(Duration.ZERO); - assertTrue(filter1.invoked()); - assertTrue(filter2.invoked()); - assertFalse(filter3.invoked()); - assertFalse(targetHandler.invoked()); + assertThat(filter1.invoked()).isTrue(); + assertThat(filter2.invoked()).isTrue(); + assertThat(filter3.invoked()).isFalse(); + assertThat(targetHandler.invoked()).isFalse(); } @Test @@ -108,8 +105,8 @@ public class FilteringWebHandlerTests { .handle(MockServerWebExchange.from(MockServerHttpRequest.get("/"))) .block(Duration.ofSeconds(5)); - assertTrue(filter.invoked()); - assertTrue(targetHandler.invoked()); + assertThat(filter.invoked()).isTrue(); + assertThat(targetHandler.invoked()).isTrue(); } @Test @@ -126,9 +123,9 @@ public class FilteringWebHandlerTests { .handle(request, response) .block(); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertNotNull(exceptionHandler.ex); - assertEquals("boo", exceptionHandler.ex.getMessage()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + assertThat(exceptionHandler.ex).isNotNull(); + assertThat(exceptionHandler.ex.getMessage()).isEqualTo("boo"); } diff --git a/spring-web/src/test/java/org/springframework/web/server/handler/ResponseStatusExceptionHandlerTests.java b/spring-web/src/test/java/org/springframework/web/server/handler/ResponseStatusExceptionHandlerTests.java index b147867c70e..9a3c77af681 100644 --- a/spring-web/src/test/java/org/springframework/web/server/handler/ResponseStatusExceptionHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/handler/ResponseStatusExceptionHandlerTests.java @@ -28,8 +28,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.ResponseStatusException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ResponseStatusExceptionHandler}. @@ -58,21 +57,21 @@ public class ResponseStatusExceptionHandlerTests { public void handleResponseStatusException() { Throwable ex = new ResponseStatusException(HttpStatus.BAD_REQUEST, ""); this.handler.handle(this.exchange, ex).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.BAD_REQUEST, this.exchange.getResponse().getStatusCode()); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test public void handleNestedResponseStatusException() { Throwable ex = new Exception(new ResponseStatusException(HttpStatus.BAD_REQUEST, "")); this.handler.handle(this.exchange, ex).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.BAD_REQUEST, this.exchange.getResponse().getStatusCode()); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test public void unresolvedException() { Throwable expected = new IllegalStateException(); Mono mono = this.handler.handle(this.exchange, expected); - StepVerifier.create(mono).consumeErrorWith(actual -> assertSame(expected, actual)).verify(); + StepVerifier.create(mono).consumeErrorWith(actual -> assertThat(actual).isSameAs(expected)).verify(); } @Test // SPR-16231 @@ -81,7 +80,7 @@ public class ResponseStatusExceptionHandlerTests { this.exchange.getResponse().setStatusCode(HttpStatus.CREATED); Mono mono = this.exchange.getResponse().setComplete() .then(Mono.defer(() -> this.handler.handle(this.exchange, ex))); - StepVerifier.create(mono).consumeErrorWith(actual -> assertSame(ex, actual)).verify(); + StepVerifier.create(mono).consumeErrorWith(actual -> assertThat(actual).isSameAs(ex)).verify(); } } diff --git a/spring-web/src/test/java/org/springframework/web/server/i18n/AcceptHeaderLocaleContextResolverTests.java b/spring-web/src/test/java/org/springframework/web/server/i18n/AcceptHeaderLocaleContextResolverTests.java index 15efa193d82..6cb675377dc 100644 --- a/spring-web/src/test/java/org/springframework/web/server/i18n/AcceptHeaderLocaleContextResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/i18n/AcceptHeaderLocaleContextResolverTests.java @@ -36,8 +36,7 @@ import static java.util.Locale.JAPANESE; import static java.util.Locale.KOREA; import static java.util.Locale.UK; import static java.util.Locale.US; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link AcceptHeaderLocaleContextResolver}. @@ -52,52 +51,52 @@ public class AcceptHeaderLocaleContextResolverTests { @Test public void resolve() { - assertEquals(CANADA, this.resolver.resolveLocaleContext(exchange(CANADA)).getLocale()); - assertEquals(US, this.resolver.resolveLocaleContext(exchange(US, CANADA)).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange(CANADA)).getLocale()).isEqualTo(CANADA); + assertThat(this.resolver.resolveLocaleContext(exchange(US, CANADA)).getLocale()).isEqualTo(US); } @Test public void resolvePreferredSupported() { this.resolver.setSupportedLocales(Collections.singletonList(CANADA)); - assertEquals(CANADA, this.resolver.resolveLocaleContext(exchange(US, CANADA)).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange(US, CANADA)).getLocale()).isEqualTo(CANADA); } @Test public void resolvePreferredNotSupported() { this.resolver.setSupportedLocales(Collections.singletonList(CANADA)); - assertEquals(US, this.resolver.resolveLocaleContext(exchange(US, UK)).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange(US, UK)).getLocale()).isEqualTo(US); } @Test public void resolvePreferredNotSupportedWithDefault() { this.resolver.setSupportedLocales(Arrays.asList(US, JAPAN)); this.resolver.setDefaultLocale(JAPAN); - assertEquals(JAPAN, this.resolver.resolveLocaleContext(exchange(KOREA)).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange(KOREA)).getLocale()).isEqualTo(JAPAN); } @Test public void resolvePreferredAgainstLanguageOnly() { this.resolver.setSupportedLocales(Collections.singletonList(ENGLISH)); - assertEquals(ENGLISH, this.resolver.resolveLocaleContext(exchange(GERMANY, US, UK)).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange(GERMANY, US, UK)).getLocale()).isEqualTo(ENGLISH); } @Test public void resolvePreferredAgainstCountryIfPossible() { this.resolver.setSupportedLocales(Arrays.asList(ENGLISH, UK)); - assertEquals(UK, this.resolver.resolveLocaleContext(exchange(GERMANY, US, UK)).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange(GERMANY, US, UK)).getLocale()).isEqualTo(UK); } @Test public void resolvePreferredAgainstLanguageWithMultipleSupportedLocales() { this.resolver.setSupportedLocales(Arrays.asList(GERMAN, US)); - assertEquals(GERMAN, this.resolver.resolveLocaleContext(exchange(GERMANY, US, UK)).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange(GERMANY, US, UK)).getLocale()).isEqualTo(GERMAN); } @Test public void resolveMissingAcceptLanguageHeader() { MockServerHttpRequest request = MockServerHttpRequest.get("/").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertNull(this.resolver.resolveLocaleContext(exchange).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange).getLocale()).isNull(); } @Test @@ -106,14 +105,14 @@ public class AcceptHeaderLocaleContextResolverTests { MockServerHttpRequest request = MockServerHttpRequest.get("/").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertEquals(US, this.resolver.resolveLocaleContext(exchange).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange).getLocale()).isEqualTo(US); } @Test public void resolveEmptyAcceptLanguageHeader() { MockServerHttpRequest request = MockServerHttpRequest.get("/").header(HttpHeaders.ACCEPT_LANGUAGE, "").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertNull(this.resolver.resolveLocaleContext(exchange).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange).getLocale()).isNull(); } @Test @@ -122,14 +121,14 @@ public class AcceptHeaderLocaleContextResolverTests { MockServerHttpRequest request = MockServerHttpRequest.get("/").header(HttpHeaders.ACCEPT_LANGUAGE, "").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertEquals(US, this.resolver.resolveLocaleContext(exchange).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange).getLocale()).isEqualTo(US); } @Test public void resolveInvalidAcceptLanguageHeader() { MockServerHttpRequest request = MockServerHttpRequest.get("/").header(HttpHeaders.ACCEPT_LANGUAGE, "en_US").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertNull(this.resolver.resolveLocaleContext(exchange).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange).getLocale()).isNull(); } @Test @@ -138,7 +137,7 @@ public class AcceptHeaderLocaleContextResolverTests { MockServerHttpRequest request = MockServerHttpRequest.get("/").header(HttpHeaders.ACCEPT_LANGUAGE, "en_US").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertEquals(US, this.resolver.resolveLocaleContext(exchange).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange).getLocale()).isEqualTo(US); } @Test @@ -146,11 +145,11 @@ public class AcceptHeaderLocaleContextResolverTests { this.resolver.setDefaultLocale(JAPANESE); MockServerHttpRequest request = MockServerHttpRequest.get("/").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); - assertEquals(JAPANESE, this.resolver.resolveLocaleContext(exchange).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange).getLocale()).isEqualTo(JAPANESE); request = MockServerHttpRequest.get("/").acceptLanguageAsLocales(US).build(); exchange = MockServerWebExchange.from(request); - assertEquals(US, this.resolver.resolveLocaleContext(exchange).getLocale()); + assertThat(this.resolver.resolveLocaleContext(exchange).getLocale()).isEqualTo(US); } diff --git a/spring-web/src/test/java/org/springframework/web/server/i18n/FixedLocaleContextResolverTests.java b/spring-web/src/test/java/org/springframework/web/server/i18n/FixedLocaleContextResolverTests.java index ec41697cb52..f79b10cf6fa 100644 --- a/spring-web/src/test/java/org/springframework/web/server/i18n/FixedLocaleContextResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/i18n/FixedLocaleContextResolverTests.java @@ -31,7 +31,7 @@ import org.springframework.web.server.ServerWebExchange; import static java.util.Locale.CANADA; import static java.util.Locale.FRANCE; import static java.util.Locale.US; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link FixedLocaleContextResolver}. @@ -48,15 +48,15 @@ public class FixedLocaleContextResolverTests { @Test public void resolveDefaultLocale() { FixedLocaleContextResolver resolver = new FixedLocaleContextResolver(); - assertEquals(US, resolver.resolveLocaleContext(exchange()).getLocale()); - assertEquals(US, resolver.resolveLocaleContext(exchange(CANADA)).getLocale()); + assertThat(resolver.resolveLocaleContext(exchange()).getLocale()).isEqualTo(US); + assertThat(resolver.resolveLocaleContext(exchange(CANADA)).getLocale()).isEqualTo(US); } @Test public void resolveCustomizedLocale() { FixedLocaleContextResolver resolver = new FixedLocaleContextResolver(FRANCE); - assertEquals(FRANCE, resolver.resolveLocaleContext(exchange()).getLocale()); - assertEquals(FRANCE, resolver.resolveLocaleContext(exchange(CANADA)).getLocale()); + assertThat(resolver.resolveLocaleContext(exchange()).getLocale()).isEqualTo(FRANCE); + assertThat(resolver.resolveLocaleContext(exchange(CANADA)).getLocale()).isEqualTo(FRANCE); } @Test @@ -64,8 +64,8 @@ public class FixedLocaleContextResolverTests { TimeZone timeZone = TimeZone.getTimeZone(ZoneId.of("UTC")); FixedLocaleContextResolver resolver = new FixedLocaleContextResolver(FRANCE, timeZone); TimeZoneAwareLocaleContext context = (TimeZoneAwareLocaleContext) resolver.resolveLocaleContext(exchange()); - assertEquals(FRANCE, context.getLocale()); - assertEquals(timeZone, context.getTimeZone()); + assertThat(context.getLocale()).isEqualTo(FRANCE); + assertThat(context.getTimeZone()).isEqualTo(timeZone); } private ServerWebExchange exchange(Locale... locales) { diff --git a/spring-web/src/test/java/org/springframework/web/server/session/CookieWebSessionIdResolverTests.java b/spring-web/src/test/java/org/springframework/web/server/session/CookieWebSessionIdResolverTests.java index 64f43eded53..c5aff2459b4 100644 --- a/spring-web/src/test/java/org/springframework/web/server/session/CookieWebSessionIdResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/session/CookieWebSessionIdResolverTests.java @@ -22,8 +22,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link CookieWebSessionIdResolver}. @@ -41,10 +40,10 @@ public class CookieWebSessionIdResolverTests { this.resolver.setSessionId(exchange, "123"); MultiValueMap cookies = exchange.getResponse().getCookies(); - assertEquals(1, cookies.size()); + assertThat(cookies.size()).isEqualTo(1); ResponseCookie cookie = cookies.getFirst(this.resolver.getCookieName()); - assertNotNull(cookie); - assertEquals("SESSION=123; Path=/; Secure; HttpOnly; SameSite=Lax", cookie.toString()); + assertThat(cookie).isNotNull(); + assertThat(cookie.toString()).isEqualTo("SESSION=123; Path=/; Secure; HttpOnly; SameSite=Lax"); } @Test @@ -58,10 +57,10 @@ public class CookieWebSessionIdResolverTests { this.resolver.setSessionId(exchange, "123"); MultiValueMap cookies = exchange.getResponse().getCookies(); - assertEquals(1, cookies.size()); + assertThat(cookies.size()).isEqualTo(1); ResponseCookie cookie = cookies.getFirst(this.resolver.getCookieName()); - assertNotNull(cookie); - assertEquals("SESSION=123; Path=/; Domain=example.org; HttpOnly; SameSite=Strict", cookie.toString()); + assertThat(cookie).isNotNull(); + assertThat(cookie.toString()).isEqualTo("SESSION=123; Path=/; Domain=example.org; HttpOnly; SameSite=Strict"); } } diff --git a/spring-web/src/test/java/org/springframework/web/server/session/DefaultWebSessionManagerTests.java b/spring-web/src/test/java/org/springframework/web/server/session/DefaultWebSessionManagerTests.java index 823d23fb62a..955f12e605e 100644 --- a/spring-web/src/test/java/org/springframework/web/server/session/DefaultWebSessionManagerTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/session/DefaultWebSessionManagerTests.java @@ -34,10 +34,7 @@ import org.springframework.web.server.WebSession; import org.springframework.web.server.adapter.DefaultServerWebExchange; import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -96,9 +93,9 @@ public class DefaultWebSessionManagerTests { WebSession session = this.sessionManager.getSession(this.exchange).block(); this.exchange.getResponse().setComplete().block(); - assertSame(this.createSession, session); - assertFalse(session.isStarted()); - assertFalse(session.isExpired()); + assertThat(session).isSameAs(this.createSession); + assertThat(session.isStarted()).isFalse(); + assertThat(session.isExpired()).isFalse(); verify(this.createSession, never()).save(); verify(this.sessionIdResolver, never()).setSessionId(any(), any()); } @@ -108,7 +105,7 @@ public class DefaultWebSessionManagerTests { given(this.sessionIdResolver.resolveSessionIds(this.exchange)).willReturn(Collections.emptyList()); WebSession session = this.sessionManager.getSession(this.exchange).block(); - assertSame(this.createSession, session); + assertThat(session).isSameAs(this.createSession); String sessionId = this.createSession.getId(); given(this.createSession.isStarted()).willReturn(true); @@ -126,8 +123,8 @@ public class DefaultWebSessionManagerTests { given(this.sessionIdResolver.resolveSessionIds(this.exchange)).willReturn(Collections.singletonList(sessionId)); WebSession actual = this.sessionManager.getSession(this.exchange).block(); - assertNotNull(actual); - assertEquals(sessionId, actual.getId()); + assertThat(actual).isNotNull(); + assertThat(actual.getId()).isEqualTo(sessionId); } @Test @@ -139,7 +136,7 @@ public class DefaultWebSessionManagerTests { given(this.sessionIdResolver.resolveSessionIds(this.exchange)).willReturn(ids); WebSession actual = this.sessionManager.getSession(this.exchange).block(); - assertNotNull(actual); - assertEquals(this.updateSession.getId(), actual.getId()); + assertThat(actual).isNotNull(); + assertThat(actual.getId()).isEqualTo(this.updateSession.getId()); } } diff --git a/spring-web/src/test/java/org/springframework/web/server/session/HeaderWebSessionIdResolverTests.java b/spring-web/src/test/java/org/springframework/web/server/session/HeaderWebSessionIdResolverTests.java index 26fe7f2b725..dc508a014d2 100644 --- a/spring-web/src/test/java/org/springframework/web/server/session/HeaderWebSessionIdResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/session/HeaderWebSessionIdResolverTests.java @@ -25,9 +25,8 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * Tests using {@link HeaderWebSessionIdResolver}. @@ -50,8 +49,7 @@ public class HeaderWebSessionIdResolverTests { public void expireWhenValidThenSetsEmptyHeader() { this.idResolver.expireSession(this.exchange); - assertEquals(Arrays.asList(""), - this.exchange.getResponse().getHeaders().get(HeaderWebSessionIdResolver.DEFAULT_HEADER_NAME)); + assertThat(this.exchange.getResponse().getHeaders().get(HeaderWebSessionIdResolver.DEFAULT_HEADER_NAME)).isEqualTo(Arrays.asList("")); } @Test @@ -60,8 +58,7 @@ public class HeaderWebSessionIdResolverTests { this.idResolver.expireSession(this.exchange); - assertEquals(Arrays.asList(""), - this.exchange.getResponse().getHeaders().get(HeaderWebSessionIdResolver.DEFAULT_HEADER_NAME)); + assertThat(this.exchange.getResponse().getHeaders().get(HeaderWebSessionIdResolver.DEFAULT_HEADER_NAME)).isEqualTo(Arrays.asList("")); } @Test @@ -70,8 +67,7 @@ public class HeaderWebSessionIdResolverTests { this.idResolver.expireSession(this.exchange); - assertEquals(Arrays.asList(""), - this.exchange.getResponse().getHeaders().get(HeaderWebSessionIdResolver.DEFAULT_HEADER_NAME)); + assertThat(this.exchange.getResponse().getHeaders().get(HeaderWebSessionIdResolver.DEFAULT_HEADER_NAME)).isEqualTo(Arrays.asList("")); } @Test @@ -80,8 +76,7 @@ public class HeaderWebSessionIdResolverTests { this.idResolver.setSessionId(this.exchange, id); - assertEquals(Arrays.asList(id), - this.exchange.getResponse().getHeaders().get(HeaderWebSessionIdResolver.DEFAULT_HEADER_NAME)); + assertThat(this.exchange.getResponse().getHeaders().get(HeaderWebSessionIdResolver.DEFAULT_HEADER_NAME)).isEqualTo(Arrays.asList(id)); } @Test @@ -91,8 +86,7 @@ public class HeaderWebSessionIdResolverTests { this.idResolver.setSessionId(this.exchange, id); - assertEquals(Arrays.asList(id), - this.exchange.getResponse().getHeaders().get(HeaderWebSessionIdResolver.DEFAULT_HEADER_NAME)); + assertThat(this.exchange.getResponse().getHeaders().get(HeaderWebSessionIdResolver.DEFAULT_HEADER_NAME)).isEqualTo(Arrays.asList(id)); } @Test @@ -103,8 +97,7 @@ public class HeaderWebSessionIdResolverTests { this.idResolver.setSessionId(this.exchange, id); - assertEquals(Arrays.asList(id), - this.exchange.getResponse().getHeaders().get(headerName)); + assertThat(this.exchange.getResponse().getHeaders().get(headerName)).isEqualTo(Arrays.asList(id)); } @Test @@ -117,7 +110,7 @@ public class HeaderWebSessionIdResolverTests { public void resolveSessionIdsWhenNoIdsThenEmpty() { List ids = this.idResolver.resolveSessionIds(this.exchange); - assertTrue(ids.isEmpty()); + assertThat(ids.isEmpty()).isTrue(); } @Test @@ -128,7 +121,7 @@ public class HeaderWebSessionIdResolverTests { List ids = this.idResolver.resolveSessionIds(this.exchange); - assertEquals(Arrays.asList(id), ids); + assertThat(ids).isEqualTo(Arrays.asList(id)); } @Test @@ -141,6 +134,6 @@ public class HeaderWebSessionIdResolverTests { List ids = this.idResolver.resolveSessionIds(this.exchange); - assertEquals(Arrays.asList(id1, id2), ids); + assertThat(ids).isEqualTo(Arrays.asList(id1, id2)); } } diff --git a/spring-web/src/test/java/org/springframework/web/server/session/InMemoryWebSessionStoreTests.java b/spring-web/src/test/java/org/springframework/web/server/session/InMemoryWebSessionStoreTests.java index 63762547435..540bcd899eb 100644 --- a/spring-web/src/test/java/org/springframework/web/server/session/InMemoryWebSessionStoreTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/session/InMemoryWebSessionStoreTests.java @@ -27,12 +27,8 @@ import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; import org.springframework.web.server.WebSession; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -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; /** * Unit tests for {@link InMemoryWebSessionStore}. @@ -46,42 +42,42 @@ public class InMemoryWebSessionStoreTests { @Test public void startsSessionExplicitly() { WebSession session = this.store.createWebSession().block(); - assertNotNull(session); + assertThat(session).isNotNull(); session.start(); - assertTrue(session.isStarted()); + assertThat(session.isStarted()).isTrue(); } @Test public void startsSessionImplicitly() { WebSession session = this.store.createWebSession().block(); - assertNotNull(session); + assertThat(session).isNotNull(); session.start(); session.getAttributes().put("foo", "bar"); - assertTrue(session.isStarted()); + assertThat(session.isStarted()).isTrue(); } @Test public void retrieveExpiredSession() { WebSession session = this.store.createWebSession().block(); - assertNotNull(session); + assertThat(session).isNotNull(); session.getAttributes().put("foo", "bar"); session.save().block(); String id = session.getId(); WebSession retrieved = this.store.retrieveSession(id).block(); - assertNotNull(retrieved); - assertSame(session, retrieved); + assertThat(retrieved).isNotNull(); + assertThat(retrieved).isSameAs(session); // Fast-forward 31 minutes this.store.setClock(Clock.offset(this.store.getClock(), Duration.ofMinutes(31))); WebSession retrievedAgain = this.store.retrieveSession(id).block(); - assertNull(retrievedAgain); + assertThat(retrievedAgain).isNull(); } @Test public void lastAccessTimeIsUpdatedOnRetrieve() { WebSession session1 = this.store.createWebSession().block(); - assertNotNull(session1); + assertThat(session1).isNotNull(); String id = session1.getId(); Instant time1 = session1.getLastAccessTime(); session1.start(); @@ -91,30 +87,30 @@ public class InMemoryWebSessionStoreTests { this.store.setClock(Clock.offset(this.store.getClock(), Duration.ofSeconds(5))); WebSession session2 = this.store.retrieveSession(id).block(); - assertNotNull(session2); - assertSame(session1, session2); + assertThat(session2).isNotNull(); + assertThat(session2).isSameAs(session1); Instant time2 = session2.getLastAccessTime(); - assertTrue(time1.isBefore(time2)); + assertThat(time1.isBefore(time2)).isTrue(); } @Test // SPR-17051 public void sessionInvalidatedBeforeSave() { // Request 1 creates session WebSession session1 = this.store.createWebSession().block(); - assertNotNull(session1); + assertThat(session1).isNotNull(); String id = session1.getId(); session1.start(); session1.save().block(); // Request 2 retrieves session WebSession session2 = this.store.retrieveSession(id).block(); - assertNotNull(session2); - assertSame(session1, session2); + assertThat(session2).isNotNull(); + assertThat(session2).isSameAs(session1); // Request 3 retrieves and invalidates WebSession session3 = this.store.retrieveSession(id).block(); - assertNotNull(session3); - assertSame(session1, session3); + assertThat(session3).isNotNull(); + assertThat(session3).isSameAs(session1); session3.invalidate().block(); // Request 2 saves session after invalidated @@ -122,7 +118,7 @@ public class InMemoryWebSessionStoreTests { // Session should not be present WebSession session4 = this.store.retrieveSession(id).block(); - assertNull(session4); + assertThat(session4).isNull(); } @Test @@ -130,19 +126,19 @@ public class InMemoryWebSessionStoreTests { DirectFieldAccessor accessor = new DirectFieldAccessor(this.store); Map sessions = (Map) accessor.getPropertyValue("sessions"); - assertNotNull(sessions); + assertThat(sessions).isNotNull(); // Create 100 sessions IntStream.range(0, 100).forEach(i -> insertSession()); - assertEquals(100, sessions.size()); + assertThat(sessions.size()).isEqualTo(100); // Force a new clock (31 min later), don't use setter which would clean expired sessions accessor.setPropertyValue("clock", Clock.offset(this.store.getClock(), Duration.ofMinutes(31))); - assertEquals(100, sessions.size()); + assertThat(sessions.size()).isEqualTo(100); // Create 1 more which forces a time-based check (clock moved forward) insertSession(); - assertEquals(1, sessions.size()); + assertThat(sessions.size()).isEqualTo(1); } @Test @@ -156,7 +152,7 @@ public class InMemoryWebSessionStoreTests { private WebSession insertSession() { WebSession session = this.store.createWebSession().block(); - assertNotNull(session); + assertThat(session).isNotNull(); session.start(); session.save().block(); return session; diff --git a/spring-web/src/test/java/org/springframework/web/server/session/WebSessionIntegrationTests.java b/spring-web/src/test/java/org/springframework/web/server/session/WebSessionIntegrationTests.java index d7a6300c3c9..30dcf38b725 100644 --- a/spring-web/src/test/java/org/springframework/web/server/session/WebSessionIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/web/server/session/WebSessionIntegrationTests.java @@ -38,11 +38,7 @@ import org.springframework.web.server.WebHandler; import org.springframework.web.server.WebSession; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for with a server-side session. @@ -71,17 +67,17 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe RequestEntity request = RequestEntity.get(createUri()).build(); ResponseEntity response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); String id = extractSessionId(response.getHeaders()); - assertNotNull(id); - assertEquals(1, this.handler.getSessionRequestCount()); + assertThat(id).isNotNull(); + assertThat(this.handler.getSessionRequestCount()).isEqualTo(1); request = RequestEntity.get(createUri()).header("Cookie", "SESSION=" + id).build(); response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertNull(response.getHeaders().get("Set-Cookie")); - assertEquals(2, this.handler.getSessionRequestCount()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().get("Set-Cookie")).isNull(); + assertThat(this.handler.getSessionRequestCount()).isEqualTo(2); } @Test @@ -91,33 +87,33 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe RequestEntity request = RequestEntity.get(createUri()).build(); ResponseEntity response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); String id = extractSessionId(response.getHeaders()); - assertNotNull(id); - assertEquals(1, this.handler.getSessionRequestCount()); + assertThat(id).isNotNull(); + assertThat(this.handler.getSessionRequestCount()).isEqualTo(1); // Second request: same session request = RequestEntity.get(createUri()).header("Cookie", "SESSION=" + id).build(); response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertNull(response.getHeaders().get("Set-Cookie")); - assertEquals(2, this.handler.getSessionRequestCount()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().get("Set-Cookie")).isNull(); + assertThat(this.handler.getSessionRequestCount()).isEqualTo(2); // Now fast-forward by 31 minutes InMemoryWebSessionStore store = (InMemoryWebSessionStore) this.sessionManager.getSessionStore(); WebSession session = store.retrieveSession(id).block(); - assertNotNull(session); + assertThat(session).isNotNull(); store.setClock(Clock.offset(store.getClock(), Duration.ofMinutes(31))); // Third request: expired session, new session created request = RequestEntity.get(createUri()).header("Cookie", "SESSION=" + id).build(); response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); id = extractSessionId(response.getHeaders()); - assertNotNull("Expected new session id", id); - assertEquals(1, this.handler.getSessionRequestCount()); + assertThat(id).as("Expected new session id").isNotNull(); + assertThat(this.handler.getSessionRequestCount()).isEqualTo(1); } @Test @@ -127,9 +123,9 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe RequestEntity request = RequestEntity.get(createUri()).build(); ResponseEntity response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); String id = extractSessionId(response.getHeaders()); - assertNotNull(id); + assertThat(id).isNotNull(); // Now fast-forward by 31 minutes InMemoryWebSessionStore store = (InMemoryWebSessionStore) this.sessionManager.getSessionStore(); @@ -140,10 +136,10 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe request = RequestEntity.get(uri).header("Cookie", "SESSION=" + id).build(); response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); String value = response.getHeaders().getFirst("Set-Cookie"); - assertNotNull(value); - assertTrue("Actual value: " + value, value.contains("Max-Age=0")); + assertThat(value).isNotNull(); + assertThat(value.contains("Max-Age=0")).as("Actual value: " + value).isTrue(); } @Test @@ -153,21 +149,21 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe RequestEntity request = RequestEntity.get(createUri()).build(); ResponseEntity response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); String oldId = extractSessionId(response.getHeaders()); - assertNotNull(oldId); - assertEquals(1, this.handler.getSessionRequestCount()); + assertThat(oldId).isNotNull(); + assertThat(this.handler.getSessionRequestCount()).isEqualTo(1); // Second request: session id changes URI uri = new URI("http://localhost:" + this.port + "/?changeId"); request = RequestEntity.get(uri).header("Cookie", "SESSION=" + oldId).build(); response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); String newId = extractSessionId(response.getHeaders()); - assertNotNull("Expected new session id", newId); - assertNotEquals(oldId, newId); - assertEquals(2, this.handler.getSessionRequestCount()); + assertThat(newId).as("Expected new session id").isNotNull(); + assertThat(newId).isNotEqualTo(oldId); + assertThat(this.handler.getSessionRequestCount()).isEqualTo(2); } @Test @@ -177,25 +173,25 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe RequestEntity request = RequestEntity.get(createUri()).build(); ResponseEntity response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); String id = extractSessionId(response.getHeaders()); - assertNotNull(id); + assertThat(id).isNotNull(); // Second request: invalidates session URI uri = new URI("http://localhost:" + this.port + "/?invalidate"); request = RequestEntity.get(uri).header("Cookie", "SESSION=" + id).build(); response = this.restTemplate.exchange(request, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); String value = response.getHeaders().getFirst("Set-Cookie"); - assertNotNull(value); - assertTrue("Actual value: " + value, value.contains("Max-Age=0")); + assertThat(value).isNotNull(); + assertThat(value.contains("Max-Age=0")).as("Actual value: " + value).isTrue(); } private String extractSessionId(HttpHeaders headers) { List headerValues = headers.get("Set-Cookie"); - assertNotNull(headerValues); - assertEquals(1, headerValues.size()); + assertThat(headerValues).isNotNull(); + assertThat(headerValues.size()).isEqualTo(1); for (String s : headerValues.get(0).split(";")){ if (s.startsWith("SESSION=")) { diff --git a/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java b/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java index 4a7337aa02e..feaea348821 100644 --- a/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java @@ -21,10 +21,8 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.util.FileCopyUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; /** * @author Brian Clozel @@ -46,7 +44,7 @@ public class ContentCachingRequestWrapperTests { ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(this.request); byte[] response = FileCopyUtils.copyToByteArray(wrapper.getInputStream()); - assertArrayEquals(response, wrapper.getContentAsByteArray()); + assertThat(wrapper.getContentAsByteArray()).isEqualTo(response); } @Test @@ -57,8 +55,8 @@ public class ContentCachingRequestWrapperTests { ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(this.request, 3); byte[] response = FileCopyUtils.copyToByteArray(wrapper.getInputStream()); - assertArrayEquals("Hello World".getBytes(CHARSET), response); - assertArrayEquals("Hel".getBytes(CHARSET), wrapper.getContentAsByteArray()); + assertThat(response).isEqualTo("Hello World".getBytes(CHARSET)); + assertThat(wrapper.getContentAsByteArray()).isEqualTo("Hel".getBytes(CHARSET)); } @Test @@ -89,10 +87,10 @@ public class ContentCachingRequestWrapperTests { ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(this.request); // getting request parameters will consume the request body - assertFalse(wrapper.getParameterMap().isEmpty()); - assertEquals("first=value&second=foo&second=bar", new String(wrapper.getContentAsByteArray())); + assertThat(wrapper.getParameterMap().isEmpty()).isFalse(); + assertThat(new String(wrapper.getContentAsByteArray())).isEqualTo("first=value&second=foo&second=bar"); // SPR-12810 : inputstream body should be consumed - assertEquals("", new String(FileCopyUtils.copyToByteArray(wrapper.getInputStream()))); + assertThat(new String(FileCopyUtils.copyToByteArray(wrapper.getInputStream()))).isEqualTo(""); } @Test // SPR-12810 @@ -106,7 +104,7 @@ public class ContentCachingRequestWrapperTests { ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(this.request); byte[] response = FileCopyUtils.copyToByteArray(wrapper.getInputStream()); - assertArrayEquals(response, wrapper.getContentAsByteArray()); + assertThat(wrapper.getContentAsByteArray()).isEqualTo(response); } } diff --git a/spring-web/src/test/java/org/springframework/web/util/DefaultUriBuilderFactoryTests.java b/spring-web/src/test/java/org/springframework/web/util/DefaultUriBuilderFactoryTests.java index 5e23a6207e6..bd964b44b85 100644 --- a/spring-web/src/test/java/org/springframework/web/util/DefaultUriBuilderFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/DefaultUriBuilderFactoryTests.java @@ -25,7 +25,7 @@ import org.junit.Test; import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode; import static java.util.Collections.singletonMap; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link DefaultUriBuilderFactory}. @@ -37,36 +37,35 @@ public class DefaultUriBuilderFactoryTests { public void defaultSettings() { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(); URI uri = factory.uriString("/foo/{id}").build("a/b"); - assertEquals("/foo/a%2Fb", uri.toString()); + assertThat(uri.toString()).isEqualTo("/foo/a%2Fb"); } @Test // SPR-17465 public void defaultSettingsWithBuilder() { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(); URI uri = factory.builder().path("/foo/{id}").build("a/b"); - assertEquals("/foo/a%2Fb", uri.toString()); + assertThat(uri.toString()).isEqualTo("/foo/a%2Fb"); } @Test public void baseUri() { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory("https://foo.com/v1?id=123"); URI uri = factory.uriString("/bar").port(8080).build(); - assertEquals("https://foo.com:8080/v1/bar?id=123", uri.toString()); + assertThat(uri.toString()).isEqualTo("https://foo.com:8080/v1/bar?id=123"); } @Test public void baseUriWithFullOverride() { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory("https://foo.com/v1?id=123"); URI uri = factory.uriString("https://example.com/1/2").build(); - assertEquals("Use of host should case baseUri to be completely ignored", - "https://example.com/1/2", uri.toString()); + assertThat(uri.toString()).as("Use of host should case baseUri to be completely ignored").isEqualTo("https://example.com/1/2"); } @Test public void baseUriWithPathOverride() { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory("https://foo.com/v1"); URI uri = factory.builder().replacePath("/baz").build(); - assertEquals("https://foo.com/baz", uri.toString()); + assertThat(uri.toString()).isEqualTo("https://foo.com/baz"); } @Test @@ -74,7 +73,7 @@ public class DefaultUriBuilderFactoryTests { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory("https://{host}/v1"); factory.setDefaultUriVariables(singletonMap("host", "foo.com")); URI uri = factory.uriString("/{id}").build(singletonMap("id", "123")); - assertEquals("https://foo.com/v1/123", uri.toString()); + assertThat(uri.toString()).isEqualTo("https://foo.com/v1/123"); } @Test @@ -82,7 +81,7 @@ public class DefaultUriBuilderFactoryTests { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory("https://{host}/v1"); factory.setDefaultUriVariables(singletonMap("host", "spring.io")); URI uri = factory.uriString("/bar").build(singletonMap("host", "docs.spring.io")); - assertEquals("https://docs.spring.io/v1/bar", uri.toString()); + assertThat(uri.toString()).isEqualTo("https://docs.spring.io/v1/bar"); } @Test @@ -90,7 +89,7 @@ public class DefaultUriBuilderFactoryTests { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory("https://{host}/v1"); factory.setDefaultUriVariables(singletonMap("host", "foo.com")); URI uri = factory.uriString("/bar").build(); - assertEquals("Expected delegation to build(Map) method", "https://foo.com/v1/bar", uri.toString()); + assertThat(uri.toString()).as("Expected delegation to build(Map) method").isEqualTo("https://foo.com/v1/bar"); } @Test @@ -102,7 +101,7 @@ public class DefaultUriBuilderFactoryTests { factory.setDefaultUriVariables(defaultUriVars); URI uri = factory.expand("https://{host}:{port}/v42/customers/{id}", singletonMap("id", 123L)); - assertEquals("https://api.example.com:443/v42/customers/123", uri.toString()); + assertThat(uri.toString()).isEqualTo("https://api.example.com:443/v42/customers/123"); } @Test @@ -117,8 +116,8 @@ public class DefaultUriBuilderFactoryTests { vars.put("city", "Z\u00fcrich"); vars.put("value", "a+b"); - assertEquals(expected, uriBuilder.build("Z\u00fcrich", "a+b").toString()); - assertEquals(expected, uriBuilder.build(vars).toString()); + assertThat(uriBuilder.build("Z\u00fcrich", "a+b").toString()).isEqualTo(expected); + assertThat(uriBuilder.build(vars).toString()).isEqualTo(expected); } @Test @@ -130,8 +129,8 @@ public class DefaultUriBuilderFactoryTests { String id = "c/d"; String expected = "/foo/a%2Fb/c%2Fd"; - assertEquals(expected, uriBuilder.build(id).toString()); - assertEquals(expected, uriBuilder.build(singletonMap("id", id)).toString()); + assertThat(uriBuilder.build(id).toString()).isEqualTo(expected); + assertThat(uriBuilder.build(singletonMap("id", id)).toString()).isEqualTo(expected); } @Test @@ -141,8 +140,7 @@ public class DefaultUriBuilderFactoryTests { factory.setDefaultUriVariables(singletonMap("host", "www.example.com")); UriBuilder uriBuilder = factory.uriString("https://{host}/user/{userId}/dashboard"); - assertEquals("https://www.example.com/user/john%3Bdoe/dashboard", - uriBuilder.build(singletonMap("userId", "john;doe")).toString()); + assertThat(uriBuilder.build(singletonMap("userId", "john;doe")).toString()).isEqualTo("https://www.example.com/user/john%3Bdoe/dashboard"); } @Test @@ -154,15 +152,15 @@ public class DefaultUriBuilderFactoryTests { String id = "c%2Fd"; String expected = "/foo/a%2Fb/c%2Fd"; - assertEquals(expected, uriBuilder.build(id).toString()); - assertEquals(expected, uriBuilder.build(singletonMap("id", id)).toString()); + assertThat(uriBuilder.build(id).toString()).isEqualTo(expected); + assertThat(uriBuilder.build(singletonMap("id", id)).toString()).isEqualTo(expected); } @Test public void parsePathWithDefaultSettings() { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory("/foo/{bar}"); URI uri = factory.uriString("/baz/{id}").build("a/b", "c/d"); - assertEquals("/foo/a%2Fb/baz/c%2Fd", uri.toString()); + assertThat(uri.toString()).isEqualTo("/foo/a%2Fb/baz/c%2Fd"); } @Test @@ -171,21 +169,21 @@ public class DefaultUriBuilderFactoryTests { factory.setEncodingMode(EncodingMode.URI_COMPONENT); factory.setParsePath(false); URI uri = factory.uriString("/baz/{id}").build("a/b", "c/d"); - assertEquals("/foo/a/b/baz/c/d", uri.toString()); + assertThat(uri.toString()).isEqualTo("/foo/a/b/baz/c/d"); } @Test // SPR-15201 public void pathWithTrailingSlash() { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(); URI uri = factory.expand("https://localhost:8080/spring/"); - assertEquals("https://localhost:8080/spring/", uri.toString()); + assertThat(uri.toString()).isEqualTo("https://localhost:8080/spring/"); } @Test public void pathWithDuplicateSlashes() { DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(); URI uri = factory.expand("/foo/////////bar"); - assertEquals("/foo/bar", uri.toString()); + assertThat(uri.toString()).isEqualTo("/foo/bar"); } } diff --git a/spring-web/src/test/java/org/springframework/web/util/DefaultUriTemplateHandlerTests.java b/spring-web/src/test/java/org/springframework/web/util/DefaultUriTemplateHandlerTests.java index 35ccae937e2..9d5ff94e306 100644 --- a/spring-web/src/test/java/org/springframework/web/util/DefaultUriTemplateHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/DefaultUriTemplateHandlerTests.java @@ -22,7 +22,7 @@ import java.util.Map; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link DefaultUriTemplateHandler}. @@ -40,7 +40,7 @@ public class DefaultUriTemplateHandlerTests { this.handler.setBaseUrl("http://localhost:8080"); URI actual = this.handler.expand("/myapiresource"); - assertEquals("http://localhost:8080/myapiresource", actual.toString()); + assertThat(actual.toString()).isEqualTo("http://localhost:8080/myapiresource"); } @Test @@ -48,7 +48,7 @@ public class DefaultUriTemplateHandlerTests { this.handler.setBaseUrl("http://localhost:8080/context"); URI actual = this.handler.expand("/myapiresource"); - assertEquals("http://localhost:8080/context/myapiresource", actual.toString()); + assertThat(actual.toString()).isEqualTo("http://localhost:8080/context/myapiresource"); } @Test // SPR-14147 @@ -64,7 +64,7 @@ public class DefaultUriTemplateHandlerTests { String template = "https://{host}:{port}/v42/customers/{id}"; URI actual = this.handler.expand(template, vars); - assertEquals("https://api.example.com:443/v42/customers/123", actual.toString()); + assertThat(actual.toString()).isEqualTo("https://api.example.com:443/v42/customers/123"); } @Test @@ -76,7 +76,7 @@ public class DefaultUriTemplateHandlerTests { String template = "https://example.com/hotels/{hotel}/pic/{publicpath}"; URI actual = this.handler.expand(template, vars); - assertEquals("https://example.com/hotels/1/pic/pics/logo.png", actual.toString()); + assertThat(actual.toString()).isEqualTo("https://example.com/hotels/1/pic/pics/logo.png"); } @Test @@ -89,7 +89,7 @@ public class DefaultUriTemplateHandlerTests { String template = "https://example.com/hotels/{hotel}/pic/{publicpath}/size/{scale}"; URI actual = this.handler.expand(template, vars); - assertEquals("https://example.com/hotels/1/pic/pics%2Flogo.png/size/150x150", actual.toString()); + assertThat(actual.toString()).isEqualTo("https://example.com/hotels/1/pic/pics%2Flogo.png/size/150x150"); } @Test @@ -100,7 +100,7 @@ public class DefaultUriTemplateHandlerTests { String template = "https://www.example.com/user/{userId}/dashboard"; URI actual = this.handler.expand(template, vars); - assertEquals("https://www.example.com/user/john;doe/dashboard", actual.toString()); + assertThat(actual.toString()).isEqualTo("https://www.example.com/user/john;doe/dashboard"); } @Test @@ -109,7 +109,7 @@ public class DefaultUriTemplateHandlerTests { String template = "https://www.example.com/user/{userId}/dashboard"; URI actual = this.handler.expand(template, "john;doe"); - assertEquals("https://www.example.com/user/john;doe/dashboard", actual.toString()); + assertThat(actual.toString()).isEqualTo("https://www.example.com/user/john;doe/dashboard"); } @Test @@ -120,7 +120,7 @@ public class DefaultUriTemplateHandlerTests { String template = "https://www.example.com/user/{userId}/dashboard"; URI actual = this.handler.expand(template, vars); - assertEquals("https://www.example.com/user/john%3Bdoe/dashboard", actual.toString()); + assertThat(actual.toString()).isEqualTo("https://www.example.com/user/john%3Bdoe/dashboard"); } @Test @@ -129,7 +129,7 @@ public class DefaultUriTemplateHandlerTests { String template = "https://www.example.com/user/{userId}/dashboard"; URI actual = this.handler.expand(template, "john;doe"); - assertEquals("https://www.example.com/user/john%3Bdoe/dashboard", actual.toString()); + assertThat(actual.toString()).isEqualTo("https://www.example.com/user/john%3Bdoe/dashboard"); } @Test // SPR-14147 @@ -145,7 +145,7 @@ public class DefaultUriTemplateHandlerTests { String template = "https://{host}/user/{userId}/dashboard"; URI actual = this.handler.expand(template, vars); - assertEquals("https://www.example.com/user/john%3Bdoe/dashboard", actual.toString()); + assertThat(actual.toString()).isEqualTo("https://www.example.com/user/john%3Bdoe/dashboard"); } } diff --git a/spring-web/src/test/java/org/springframework/web/util/HtmlCharacterEntityReferencesTests.java b/spring-web/src/test/java/org/springframework/web/util/HtmlCharacterEntityReferencesTests.java index 41a51089f03..726808a2277 100644 --- a/spring-web/src/test/java/org/springframework/web/util/HtmlCharacterEntityReferencesTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/HtmlCharacterEntityReferencesTests.java @@ -26,10 +26,7 @@ import java.util.Map; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Martin Kersten @@ -41,42 +38,44 @@ public class HtmlCharacterEntityReferencesTests { @Test public void testSupportsAllCharacterEntityReferencesDefinedByHtml() { - HtmlCharacterEntityReferences entityReferences = new HtmlCharacterEntityReferences(); - Map referenceCharactersMap = getReferenceCharacterMap(); - + HtmlCharacterEntityReferences references = new HtmlCharacterEntityReferences(); + Map charactersMap = getReferenceCharacterMap(); for (int character = 0; character < 10000; character++) { - String referenceName = referenceCharactersMap.get(character); + String referenceName = charactersMap.get(character); if (referenceName != null) { - String fullReference = - HtmlCharacterEntityReferences.REFERENCE_START + - referenceName + - HtmlCharacterEntityReferences.REFERENCE_END; - assertTrue("The unicode character " + character + " should be mapped to a reference", - entityReferences.isMappedToReference((char) character)); - assertEquals("The reference of unicode character " + character + " should be entity " + referenceName, - fullReference, entityReferences.convertToReference((char) character)); - assertEquals("The entity reference [" + referenceName + "] should be mapped to unicode character " + - character, (char) character, entityReferences.convertToCharacter(referenceName)); + String fullReference = HtmlCharacterEntityReferences.REFERENCE_START + referenceName + HtmlCharacterEntityReferences.REFERENCE_END; + assertThat(references.isMappedToReference((char) character)) + .as("The unicode character " + character + " should be mapped to a reference") + .isTrue(); + assertThat(references.convertToReference((char) character)) + .as("The reference of unicode character " + character + " should be entity " + referenceName) + .isEqualTo(fullReference); + assertThat(references.convertToCharacter(referenceName)) + .as("The entity reference [" + referenceName + "] should be mapped to unicode character " + character) + .isEqualTo((char) character); } else if (character == 39) { - assertTrue(entityReferences.isMappedToReference((char) character)); - assertEquals("'", entityReferences.convertToReference((char) character)); + assertThat(references.isMappedToReference((char) character)).isTrue(); + assertThat(references.convertToReference((char) character)).isEqualTo("'"); } else { - assertFalse("The unicode character " + character + " should not be mapped to a reference", - entityReferences.isMappedToReference((char) character)); - assertNull("No entity reference of unicode character " + character + " should exist", - entityReferences.convertToReference((char) character)); + assertThat(references.isMappedToReference((char) character)) + .as("The unicode character " + character + " should not be mapped to a reference") + .isFalse(); + assertThat(references.convertToReference((char) character)) + .as("No entity reference of unicode character " + character + " should exist") + .isNull(); } } - - assertEquals("The registered entity count of entityReferences should match the number of entity references", - referenceCharactersMap.size() + 1, entityReferences.getSupportedReferenceCount()); - assertEquals("The HTML 4.0 Standard defines 252+1 entity references so do entityReferences", - 252 + 1, entityReferences.getSupportedReferenceCount()); - - assertEquals("Invalid entity reference names should not be convertible", - (char) -1, entityReferences.convertToCharacter("invalid")); + assertThat(references.getSupportedReferenceCount()) + .as("The registered entity count of entityReferences should match the number of entity references") + .isEqualTo(charactersMap.size() + 1); + assertThat(references.getSupportedReferenceCount()).as( + "The HTML 4.0 Standard defines 252+1 entity references so do entityReferences") + .isEqualTo(252 + 1); + assertThat((int) references.convertToCharacter("invalid")) + .as("Invalid entity reference names should not be convertible") + .isEqualTo((char) -1); } // SPR-9293 @@ -84,13 +83,13 @@ public class HtmlCharacterEntityReferencesTests { public void testConvertToReferenceUTF8() { HtmlCharacterEntityReferences entityReferences = new HtmlCharacterEntityReferences(); String utf8 = "UTF-8"; - assertEquals("<", entityReferences.convertToReference('<', utf8)); - assertEquals(">", entityReferences.convertToReference('>', utf8)); - assertEquals("&", entityReferences.convertToReference('&', utf8)); - assertEquals(""", entityReferences.convertToReference('"', utf8)); - assertEquals("'", entityReferences.convertToReference('\'', utf8)); - assertNull(entityReferences.convertToReference((char) 233, utf8)); - assertNull(entityReferences.convertToReference((char) 934, utf8)); + assertThat(entityReferences.convertToReference('<', utf8)).isEqualTo("<"); + assertThat(entityReferences.convertToReference('>', utf8)).isEqualTo(">"); + assertThat(entityReferences.convertToReference('&', utf8)).isEqualTo("&"); + assertThat(entityReferences.convertToReference('"', utf8)).isEqualTo("""); + assertThat(entityReferences.convertToReference('\'', utf8)).isEqualTo("'"); + assertThat(entityReferences.convertToReference((char) 233, utf8)).isNull(); + assertThat(entityReferences.convertToReference((char) 934, utf8)).isNull(); } private Map getReferenceCharacterMap() { diff --git a/spring-web/src/test/java/org/springframework/web/util/HtmlUtilsTests.java b/spring-web/src/test/java/org/springframework/web/util/HtmlUtilsTests.java index 3b3500871dd..256f309a342 100644 --- a/spring-web/src/test/java/org/springframework/web/util/HtmlUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/HtmlUtilsTests.java @@ -18,7 +18,7 @@ package org.springframework.web.util; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Alef Arendsen @@ -31,108 +31,76 @@ public class HtmlUtilsTests { public void testHtmlEscape() { String unescaped = "\"This is a quote'"; String escaped = HtmlUtils.htmlEscape(unescaped); - assertEquals(""This is a quote'", escaped); + assertThat(escaped).isEqualTo(""This is a quote'"); escaped = HtmlUtils.htmlEscapeDecimal(unescaped); - assertEquals(""This is a quote'", escaped); + assertThat(escaped).isEqualTo(""This is a quote'"); escaped = HtmlUtils.htmlEscapeHex(unescaped); - assertEquals(""This is a quote'", escaped); + assertThat(escaped).isEqualTo(""This is a quote'"); } @Test public void testHtmlUnescape() { String escaped = ""This is a quote'"; String unescaped = HtmlUtils.htmlUnescape(escaped); - assertEquals("\"This is a quote'", unescaped); + assertThat(unescaped).isEqualTo("\"This is a quote'"); } @Test public void testEncodeIntoHtmlCharacterSet() { - assertEquals("An empty string should be converted to an empty string", - "", HtmlUtils.htmlEscape("")); - assertEquals("A string containing no special characters should not be affected", - "A sentence containing no special characters.", - HtmlUtils.htmlEscape("A sentence containing no special characters.")); + assertThat(HtmlUtils.htmlEscape("")).as("An empty string should be converted to an empty string").isEqualTo(""); + assertThat(HtmlUtils.htmlEscape("A sentence containing no special characters.")).as("A string containing no special characters should not be affected").isEqualTo("A sentence containing no special characters."); - assertEquals("'< >' should be encoded to '< >'", - "< >", HtmlUtils.htmlEscape("< >")); - assertEquals("'< >' should be encoded to '< >'", - "< >", HtmlUtils.htmlEscapeDecimal("< >")); + assertThat(HtmlUtils.htmlEscape("< >")).as("'< >' should be encoded to '< >'").isEqualTo("< >"); + assertThat(HtmlUtils.htmlEscapeDecimal("< >")).as("'< >' should be encoded to '< >'").isEqualTo("< >"); - assertEquals("The special character 8709 should be encoded to '∅'", - "∅", HtmlUtils.htmlEscape("" + (char) 8709)); - assertEquals("The special character 8709 should be encoded to '∅'", - "∅", HtmlUtils.htmlEscapeDecimal("" + (char) 8709)); + assertThat(HtmlUtils.htmlEscape("" + (char) 8709)).as("The special character 8709 should be encoded to '∅'").isEqualTo("∅"); + assertThat(HtmlUtils.htmlEscapeDecimal("" + (char) 8709)).as("The special character 8709 should be encoded to '∅'").isEqualTo("∅"); - assertEquals("The special character 977 should be encoded to 'ϑ'", - "ϑ", HtmlUtils.htmlEscape("" + (char) 977)); - assertEquals("The special character 977 should be encoded to 'ϑ'", - "ϑ", HtmlUtils.htmlEscapeDecimal("" + (char) 977)); + assertThat(HtmlUtils.htmlEscape("" + (char) 977)).as("The special character 977 should be encoded to 'ϑ'").isEqualTo("ϑ"); + assertThat(HtmlUtils.htmlEscapeDecimal("" + (char) 977)).as("The special character 977 should be encoded to 'ϑ'").isEqualTo("ϑ"); } // SPR-9293 @Test public void testEncodeIntoHtmlCharacterSetFromUtf8() { String utf8 = ("UTF-8"); - assertEquals("An empty string should be converted to an empty string", - "", HtmlUtils.htmlEscape("", utf8)); - assertEquals("A string containing no special characters should not be affected", - "A sentence containing no special characters.", - HtmlUtils.htmlEscape("A sentence containing no special characters.")); + assertThat(HtmlUtils.htmlEscape("", utf8)).as("An empty string should be converted to an empty string").isEqualTo(""); + assertThat(HtmlUtils.htmlEscape("A sentence containing no special characters.")).as("A string containing no special characters should not be affected").isEqualTo("A sentence containing no special characters."); - assertEquals("'< >' should be encoded to '< >'", - "< >", HtmlUtils.htmlEscape("< >", utf8)); - assertEquals("'< >' should be encoded to '< >'", - "< >", HtmlUtils.htmlEscapeDecimal("< >", utf8)); + assertThat(HtmlUtils.htmlEscape("< >", utf8)).as("'< >' should be encoded to '< >'").isEqualTo("< >"); + assertThat(HtmlUtils.htmlEscapeDecimal("< >", utf8)).as("'< >' should be encoded to '< >'").isEqualTo("< >"); - assertEquals("UTF-8 supported chars should not be escaped", - "Μερικοί Ελληνικοί "χαρακτήρες"", - HtmlUtils.htmlEscape("Μερικοί Ελληνικοί \"χαρακτήρες\"", utf8)); + assertThat(HtmlUtils.htmlEscape("Μερικοί Ελληνικοί \"χαρακτήρες\"", utf8)).as("UTF-8 supported chars should not be escaped").isEqualTo("Μερικοί Ελληνικοί "χαρακτήρες""); } @Test public void testDecodeFromHtmlCharacterSet() { - assertEquals("An empty string should be converted to an empty string", - "", HtmlUtils.htmlUnescape("")); - assertEquals("A string containing no special characters should not be affected", - "This is a sentence containing no special characters.", - HtmlUtils.htmlUnescape("This is a sentence containing no special characters.")); + assertThat(HtmlUtils.htmlUnescape("")).as("An empty string should be converted to an empty string").isEqualTo(""); + assertThat(HtmlUtils.htmlUnescape("This is a sentence containing no special characters.")).as("A string containing no special characters should not be affected").isEqualTo("This is a sentence containing no special characters."); - assertEquals("'A B' should be decoded to 'A B'", - "A" + (char) 160 + "B", HtmlUtils.htmlUnescape("A B")); + assertThat(HtmlUtils.htmlUnescape("A B")).as("'A B' should be decoded to 'A B'").isEqualTo(("A" + (char) 160 + "B")); - assertEquals("'< >' should be decoded to '< >'", - "< >", HtmlUtils.htmlUnescape("< >")); - assertEquals("'< >' should be decoded to '< >'", - "< >", HtmlUtils.htmlUnescape("< >")); + assertThat(HtmlUtils.htmlUnescape("< >")).as("'< >' should be decoded to '< >'").isEqualTo("< >"); + assertThat(HtmlUtils.htmlUnescape("< >")).as("'< >' should be decoded to '< >'").isEqualTo("< >"); - assertEquals("'ABC' should be decoded to 'ABC'", - "ABC", HtmlUtils.htmlUnescape("ABC")); + assertThat(HtmlUtils.htmlUnescape("ABC")).as("'ABC' should be decoded to 'ABC'").isEqualTo("ABC"); - assertEquals("'φ' should be decoded to uni-code character 966", - "" + (char) 966, HtmlUtils.htmlUnescape("φ")); + assertThat(HtmlUtils.htmlUnescape("φ")).as("'φ' should be decoded to uni-code character 966").isEqualTo(("" + (char) 966)); - assertEquals("'″' should be decoded to uni-code character 8243", - "" + (char) 8243, HtmlUtils.htmlUnescape("″")); + assertThat(HtmlUtils.htmlUnescape("″")).as("'″' should be decoded to uni-code character 8243").isEqualTo(("" + (char) 8243)); - assertEquals("A not supported named reference leads should be ignored", - "&prIme;", HtmlUtils.htmlUnescape("&prIme;")); + assertThat(HtmlUtils.htmlUnescape("&prIme;")).as("A not supported named reference leads should be ignored").isEqualTo("&prIme;"); - assertEquals("An empty reference '&;' should be survive the decoding", - "&;", HtmlUtils.htmlUnescape("&;")); + assertThat(HtmlUtils.htmlUnescape("&;")).as("An empty reference '&;' should be survive the decoding").isEqualTo("&;"); - assertEquals("The longest character entity reference 'ϑ' should be processable", - "" + (char) 977, HtmlUtils.htmlUnescape("ϑ")); + assertThat(HtmlUtils.htmlUnescape("ϑ")).as("The longest character entity reference 'ϑ' should be processable").isEqualTo(("" + (char) 977)); - assertEquals("A malformed decimal reference should survive the decoding", - "&#notADecimalNumber;", HtmlUtils.htmlUnescape("&#notADecimalNumber;")); - assertEquals("A malformed hex reference should survive the decoding", - "&#XnotAHexNumber;", HtmlUtils.htmlUnescape("&#XnotAHexNumber;")); + assertThat(HtmlUtils.htmlUnescape("&#notADecimalNumber;")).as("A malformed decimal reference should survive the decoding").isEqualTo("&#notADecimalNumber;"); + assertThat(HtmlUtils.htmlUnescape("&#XnotAHexNumber;")).as("A malformed hex reference should survive the decoding").isEqualTo("&#XnotAHexNumber;"); - assertEquals("The numerical reference '' should be converted to char 1", - "" + (char) 1, HtmlUtils.htmlUnescape("")); + assertThat(HtmlUtils.htmlUnescape("")).as("The numerical reference '' should be converted to char 1").isEqualTo(("" + (char) 1)); - assertEquals("The malformed hex reference '&#x;' should remain '&#x;'", - "&#x;", HtmlUtils.htmlUnescape("&#x;")); + assertThat(HtmlUtils.htmlUnescape("&#x;")).as("The malformed hex reference '&#x;' should remain '&#x;'").isEqualTo("&#x;"); } } diff --git a/spring-web/src/test/java/org/springframework/web/util/JavaScriptUtilsTests.java b/spring-web/src/test/java/org/springframework/web/util/JavaScriptUtilsTests.java index 115a89b8d16..43b7d853bc6 100644 --- a/spring-web/src/test/java/org/springframework/web/util/JavaScriptUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/JavaScriptUtilsTests.java @@ -20,7 +20,7 @@ import java.io.UnsupportedEncodingException; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link JavaScriptUtils}. @@ -42,7 +42,7 @@ public class JavaScriptUtilsTests { sb.append("\f"); sb.append("\b"); sb.append("\013"); - assertEquals("\\\"\\'\\\\\\/\\t\\n\\n\\f\\b\\v", JavaScriptUtils.javaScriptEscape(sb.toString())); + assertThat(JavaScriptUtils.javaScriptEscape(sb.toString())).isEqualTo("\\\"\\'\\\\\\/\\t\\n\\n\\f\\b\\v"); } // SPR-9983 @@ -54,14 +54,14 @@ public class JavaScriptUtilsTests { sb.append('\u2029'); String result = JavaScriptUtils.javaScriptEscape(sb.toString()); - assertEquals("\\u2028\\u2029", result); + assertThat(result).isEqualTo("\\u2028\\u2029"); } // SPR-9983 @Test public void escapeLessThanGreaterThanSigns() throws UnsupportedEncodingException { - assertEquals("\\u003C\\u003E", JavaScriptUtils.javaScriptEscape("<>")); + assertThat(JavaScriptUtils.javaScriptEscape("<>")).isEqualTo("\\u003C\\u003E"); } } diff --git a/spring-web/src/test/java/org/springframework/web/util/ServletContextPropertyUtilsTests.java b/spring-web/src/test/java/org/springframework/web/util/ServletContextPropertyUtilsTests.java index 97be92f84ea..c682b8df810 100644 --- a/spring-web/src/test/java/org/springframework/web/util/ServletContextPropertyUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/ServletContextPropertyUtilsTests.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockServletContext; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Marten Deinum @@ -33,7 +33,7 @@ public class ServletContextPropertyUtilsTests { MockServletContext servletContext = new MockServletContext(); servletContext.setInitParameter("test.prop", "bar"); String resolved = ServletContextPropertyUtils.resolvePlaceholders("${test.prop:foo}", servletContext); - assertEquals("bar", resolved); + assertThat(resolved).isEqualTo("bar"); } @Test @@ -42,7 +42,7 @@ public class ServletContextPropertyUtilsTests { System.setProperty("test.prop", "bar"); try { String resolved = ServletContextPropertyUtils.resolvePlaceholders("${test.prop:foo}", servletContext); - assertEquals("bar", resolved); + assertThat(resolved).isEqualTo("bar"); } finally { System.clearProperty("test.prop"); diff --git a/spring-web/src/test/java/org/springframework/web/util/TagUtilsTests.java b/spring-web/src/test/java/org/springframework/web/util/TagUtilsTests.java index de4a8a5d4ab..0f4d4e0b857 100644 --- a/spring-web/src/test/java/org/springframework/web/util/TagUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/TagUtilsTests.java @@ -22,11 +22,9 @@ import javax.servlet.jsp.tagext.TagSupport; 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Unit tests for the {@link TagUtils} class. @@ -38,20 +36,19 @@ public class TagUtilsTests { @Test public void getScopeSunnyDay() { - assertEquals("page", TagUtils.SCOPE_PAGE); - assertEquals("application", TagUtils.SCOPE_APPLICATION); - assertEquals("session", TagUtils.SCOPE_SESSION); - assertEquals("request", TagUtils.SCOPE_REQUEST); + assertThat(TagUtils.SCOPE_PAGE).isEqualTo("page"); + assertThat(TagUtils.SCOPE_APPLICATION).isEqualTo("application"); + assertThat(TagUtils.SCOPE_SESSION).isEqualTo("session"); + assertThat(TagUtils.SCOPE_REQUEST).isEqualTo("request"); - assertEquals(PageContext.PAGE_SCOPE, TagUtils.getScope("page")); - assertEquals(PageContext.REQUEST_SCOPE, TagUtils.getScope("request")); - assertEquals(PageContext.SESSION_SCOPE, TagUtils.getScope("session")); - assertEquals(PageContext.APPLICATION_SCOPE, TagUtils.getScope("application")); + assertThat(TagUtils.getScope("page")).isEqualTo(PageContext.PAGE_SCOPE); + assertThat(TagUtils.getScope("request")).isEqualTo(PageContext.REQUEST_SCOPE); + assertThat(TagUtils.getScope("session")).isEqualTo(PageContext.SESSION_SCOPE); + assertThat(TagUtils.getScope("application")).isEqualTo(PageContext.APPLICATION_SCOPE); // non-existent scope - assertEquals("TagUtils.getScope(..) with a non-existent scope argument must " + - "just return the default scope (PageContext.PAGE_SCOPE).", PageContext.PAGE_SCOPE, - TagUtils.getScope("bla")); + assertThat(TagUtils.getScope("bla")).as("TagUtils.getScope(..) with a non-existent scope argument must " + + "just return the default scope (PageContext.PAGE_SCOPE).").isEqualTo(PageContext.PAGE_SCOPE); } @Test @@ -87,7 +84,7 @@ public class TagUtilsTests { a.setParent(b); b.setParent(c); - assertTrue(TagUtils.hasAncestorOfType(a, TagC.class)); + assertThat(TagUtils.hasAncestorOfType(a, TagC.class)).isTrue(); } @Test @@ -99,12 +96,12 @@ public class TagUtilsTests { a.setParent(b); b.setParent(anotherB); - assertFalse(TagUtils.hasAncestorOfType(a, TagC.class)); + assertThat(TagUtils.hasAncestorOfType(a, TagC.class)).isFalse(); } @Test public void hasAncestorOfTypeWhenTagHasNoParent() throws Exception { - assertFalse(TagUtils.hasAncestorOfType(new TagA(), TagC.class)); + assertThat(TagUtils.hasAncestorOfType(new TagA(), TagC.class)).isFalse(); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java index 107d547132b..c580a5beb9d 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java @@ -35,10 +35,6 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link UriComponentsBuilder}. @@ -59,14 +55,14 @@ public class UriComponentsBuilderTests { UriComponents result = builder.scheme("https").host("example.com") .path("foo").queryParam("bar").fragment("baz") .build(); - assertEquals("https", result.getScheme()); - assertEquals("example.com", result.getHost()); - assertEquals("foo", result.getPath()); - assertEquals("bar", result.getQuery()); - assertEquals("baz", result.getFragment()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("example.com"); + assertThat(result.getPath()).isEqualTo("foo"); + assertThat(result.getQuery()).isEqualTo("bar"); + assertThat(result.getFragment()).isEqualTo("baz"); URI expected = new URI("https://example.com/foo?bar#baz"); - assertEquals("Invalid result URI", expected, result.toUri()); + assertThat(result.toUri()).as("Invalid result URI").isEqualTo(expected); } @Test @@ -77,62 +73,62 @@ public class UriComponentsBuilderTests { builder = builder.pathSegment("foo2").queryParam("bar").fragment("baz"); UriComponents result2 = builder.build(); - assertEquals("https", result1.getScheme()); - assertEquals("example.com", result1.getHost()); - assertEquals("/foo", result1.getPath()); + assertThat(result1.getScheme()).isEqualTo("https"); + assertThat(result1.getHost()).isEqualTo("example.com"); + assertThat(result1.getPath()).isEqualTo("/foo"); URI expected = new URI("https://example.com/foo"); - assertEquals("Invalid result URI", expected, result1.toUri()); + assertThat(result1.toUri()).as("Invalid result URI").isEqualTo(expected); - assertEquals("https", result2.getScheme()); - assertEquals("example.com", result2.getHost()); - assertEquals("/foo/foo2", result2.getPath()); - assertEquals("bar", result2.getQuery()); - assertEquals("baz", result2.getFragment()); + assertThat(result2.getScheme()).isEqualTo("https"); + assertThat(result2.getHost()).isEqualTo("example.com"); + assertThat(result2.getPath()).isEqualTo("/foo/foo2"); + assertThat(result2.getQuery()).isEqualTo("bar"); + assertThat(result2.getFragment()).isEqualTo("baz"); expected = new URI("https://example.com/foo/foo2?bar#baz"); - assertEquals("Invalid result URI", expected, result2.toUri()); + assertThat(result2.toUri()).as("Invalid result URI").isEqualTo(expected); } @Test public void fromPath() throws URISyntaxException { UriComponents result = UriComponentsBuilder.fromPath("foo").queryParam("bar").fragment("baz").build(); - assertEquals("foo", result.getPath()); - assertEquals("bar", result.getQuery()); - assertEquals("baz", result.getFragment()); + assertThat(result.getPath()).isEqualTo("foo"); + assertThat(result.getQuery()).isEqualTo("bar"); + assertThat(result.getFragment()).isEqualTo("baz"); - assertEquals("Invalid result URI String", "foo?bar#baz", result.toUriString()); + assertThat(result.toUriString()).as("Invalid result URI String").isEqualTo("foo?bar#baz"); URI expected = new URI("foo?bar#baz"); - assertEquals("Invalid result URI", expected, result.toUri()); + assertThat(result.toUri()).as("Invalid result URI").isEqualTo(expected); result = UriComponentsBuilder.fromPath("/foo").build(); - assertEquals("/foo", result.getPath()); + assertThat(result.getPath()).isEqualTo("/foo"); expected = new URI("/foo"); - assertEquals("Invalid result URI", expected, result.toUri()); + assertThat(result.toUri()).as("Invalid result URI").isEqualTo(expected); } @Test public void fromHierarchicalUri() throws URISyntaxException { URI uri = new URI("https://example.com/foo?bar#baz"); UriComponents result = UriComponentsBuilder.fromUri(uri).build(); - assertEquals("https", result.getScheme()); - assertEquals("example.com", result.getHost()); - assertEquals("/foo", result.getPath()); - assertEquals("bar", result.getQuery()); - assertEquals("baz", result.getFragment()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("example.com"); + assertThat(result.getPath()).isEqualTo("/foo"); + assertThat(result.getQuery()).isEqualTo("bar"); + assertThat(result.getFragment()).isEqualTo("baz"); - assertEquals("Invalid result URI", uri, result.toUri()); + assertThat(result.toUri()).as("Invalid result URI").isEqualTo(uri); } @Test public void fromOpaqueUri() throws URISyntaxException { URI uri = new URI("mailto:foo@bar.com#baz"); UriComponents result = UriComponentsBuilder.fromUri(uri).build(); - assertEquals("mailto", result.getScheme()); - assertEquals("foo@bar.com", result.getSchemeSpecificPart()); - assertEquals("baz", result.getFragment()); + assertThat(result.getScheme()).isEqualTo("mailto"); + assertThat(result.getSchemeSpecificPart()).isEqualTo("foo@bar.com"); + assertThat(result.getFragment()).isEqualTo("baz"); - assertEquals("Invalid result URI", uri, result.toUri()); + assertThat(result.toUri()).as("Invalid result URI").isEqualTo(uri); } @Test // SPR-9317 @@ -142,53 +138,53 @@ public class UriComponentsBuilderTests { String fromUriString = UriComponentsBuilder.fromUriString(uri.toString()) .build().getQueryParams().get("param").get(0); - assertEquals(fromUri, fromUriString); + assertThat(fromUriString).isEqualTo(fromUri); } @Test public void fromUriString() { UriComponents result = UriComponentsBuilder.fromUriString("https://www.ietf.org/rfc/rfc3986.txt").build(); - assertEquals("https", result.getScheme()); - assertNull(result.getUserInfo()); - assertEquals("www.ietf.org", result.getHost()); - assertEquals(-1, result.getPort()); - assertEquals("/rfc/rfc3986.txt", result.getPath()); - assertEquals(Arrays.asList("rfc", "rfc3986.txt"), result.getPathSegments()); - assertNull(result.getQuery()); - assertNull(result.getFragment()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getUserInfo()).isNull(); + assertThat(result.getHost()).isEqualTo("www.ietf.org"); + assertThat(result.getPort()).isEqualTo(-1); + assertThat(result.getPath()).isEqualTo("/rfc/rfc3986.txt"); + assertThat(result.getPathSegments()).isEqualTo(Arrays.asList("rfc", "rfc3986.txt")); + assertThat(result.getQuery()).isNull(); + assertThat(result.getFragment()).isNull(); String url = "https://arjen:foobar@java.sun.com:80" + "/javase/6/docs/api/java/util/BitSet.html?foo=bar#and(java.util.BitSet)"; result = UriComponentsBuilder.fromUriString(url).build(); - assertEquals("https", result.getScheme()); - assertEquals("arjen:foobar", result.getUserInfo()); - assertEquals("java.sun.com", result.getHost()); - assertEquals(80, result.getPort()); - assertEquals("/javase/6/docs/api/java/util/BitSet.html", result.getPath()); - assertEquals("foo=bar", result.getQuery()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getUserInfo()).isEqualTo("arjen:foobar"); + assertThat(result.getHost()).isEqualTo("java.sun.com"); + assertThat(result.getPort()).isEqualTo(80); + assertThat(result.getPath()).isEqualTo("/javase/6/docs/api/java/util/BitSet.html"); + assertThat(result.getQuery()).isEqualTo("foo=bar"); MultiValueMap expectedQueryParams = new LinkedMultiValueMap<>(1); expectedQueryParams.add("foo", "bar"); - assertEquals(expectedQueryParams, result.getQueryParams()); - assertEquals("and(java.util.BitSet)", result.getFragment()); + assertThat(result.getQueryParams()).isEqualTo(expectedQueryParams); + assertThat(result.getFragment()).isEqualTo("and(java.util.BitSet)"); result = UriComponentsBuilder.fromUriString("mailto:java-net@java.sun.com#baz").build(); - assertEquals("mailto", result.getScheme()); - assertNull(result.getUserInfo()); - assertNull(result.getHost()); - assertEquals(-1, result.getPort()); - assertEquals("java-net@java.sun.com", result.getSchemeSpecificPart()); - assertNull(result.getPath()); - assertNull(result.getQuery()); - assertEquals("baz", result.getFragment()); + assertThat(result.getScheme()).isEqualTo("mailto"); + assertThat(result.getUserInfo()).isNull(); + assertThat(result.getHost()).isNull(); + assertThat(result.getPort()).isEqualTo(-1); + assertThat(result.getSchemeSpecificPart()).isEqualTo("java-net@java.sun.com"); + assertThat(result.getPath()).isNull(); + assertThat(result.getQuery()).isNull(); + assertThat(result.getFragment()).isEqualTo("baz"); result = UriComponentsBuilder.fromUriString("docs/guide/collections/designfaq.html#28").build(); - assertNull(result.getScheme()); - assertNull(result.getUserInfo()); - assertNull(result.getHost()); - assertEquals(-1, result.getPort()); - assertEquals("docs/guide/collections/designfaq.html", result.getPath()); - assertNull(result.getQuery()); - assertEquals("28", result.getFragment()); + assertThat(result.getScheme()).isNull(); + assertThat(result.getUserInfo()).isNull(); + assertThat(result.getHost()).isNull(); + assertThat(result.getPort()).isEqualTo(-1); + assertThat(result.getPath()).isEqualTo("docs/guide/collections/designfaq.html"); + assertThat(result.getQuery()).isNull(); + assertThat(result.getFragment()).isEqualTo("28"); } @Test // SPR-9832 @@ -196,8 +192,8 @@ public class UriComponentsBuilderTests { String uri = "https://www.google.com/ig/calculator?q=1USD=?EUR"; UriComponents result = UriComponentsBuilder.fromUriString(uri).build(); - assertEquals("q=1USD=?EUR", result.getQuery()); - assertEquals("1USD=?EUR", result.getQueryParams().getFirst("q")); + assertThat(result.getQuery()).isEqualTo("q=1USD=?EUR"); + assertThat(result.getQueryParams().getFirst("q")).isEqualTo("1USD=?EUR"); } @Test // SPR-14828 @@ -205,13 +201,13 @@ public class UriComponentsBuilderTests { String httpUrl = "http://localhost:8080/test/print?value=%EA%B0%80+%EB%82%98"; URI uri = UriComponentsBuilder.fromHttpUrl(httpUrl).build(true).toUri(); - assertEquals(httpUrl, uri.toString()); + assertThat(uri.toString()).isEqualTo(httpUrl); } @Test // SPR-10779 public void fromHttpUrlStringCaseInsesitiveScheme() { - assertEquals("http", UriComponentsBuilder.fromHttpUrl("HTTP://www.google.com").build().getScheme()); - assertEquals("https", UriComponentsBuilder.fromHttpUrl("HTTPS://www.google.com").build().getScheme()); + assertThat(UriComponentsBuilder.fromHttpUrl("HTTP://www.google.com").build().getScheme()).isEqualTo("http"); + assertThat(UriComponentsBuilder.fromHttpUrl("HTTPS://www.google.com").build().getScheme()).isEqualTo("https"); } @Test // SPR-10539 @@ -224,24 +220,24 @@ public class UriComponentsBuilderTests { public void fromUriStringIPv6Host() { UriComponents result = UriComponentsBuilder .fromUriString("http://[1abc:2abc:3abc::5ABC:6abc]:8080/resource").build().encode(); - assertEquals("[1abc:2abc:3abc::5ABC:6abc]", result.getHost()); + assertThat(result.getHost()).isEqualTo("[1abc:2abc:3abc::5ABC:6abc]"); UriComponents resultWithScopeId = UriComponentsBuilder .fromUriString("http://[1abc:2abc:3abc::5ABC:6abc%eth0]:8080/resource").build().encode(); - assertEquals("[1abc:2abc:3abc::5ABC:6abc%25eth0]", resultWithScopeId.getHost()); + assertThat(resultWithScopeId.getHost()).isEqualTo("[1abc:2abc:3abc::5ABC:6abc%25eth0]"); UriComponents resultIPv4compatible = UriComponentsBuilder .fromUriString("http://[::192.168.1.1]:8080/resource").build().encode(); - assertEquals("[::192.168.1.1]", resultIPv4compatible.getHost()); + assertThat(resultIPv4compatible.getHost()).isEqualTo("[::192.168.1.1]"); } @Test // SPR-11970 public void fromUriStringNoPathWithReservedCharInQuery() { UriComponents result = UriComponentsBuilder.fromUriString("https://example.com?foo=bar@baz").build(); - assertTrue(StringUtils.isEmpty(result.getUserInfo())); - assertEquals("example.com", result.getHost()); - assertTrue(result.getQueryParams().containsKey("foo")); - assertEquals("bar@baz", result.getQueryParams().getFirst("foo")); + assertThat(StringUtils.isEmpty(result.getUserInfo())).isTrue(); + assertThat(result.getHost()).isEqualTo("example.com"); + assertThat(result.getQueryParams().containsKey("foo")).isTrue(); + assertThat(result.getQueryParams().getFirst("foo")).isEqualTo("bar@baz"); } @Test @@ -254,11 +250,11 @@ public class UriComponentsBuilderTests { request.setQueryString("a=1"); UriComponents result = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)).build(); - assertEquals("http", result.getScheme()); - assertEquals("localhost", result.getHost()); - assertEquals(-1, result.getPort()); - assertEquals("/path", result.getPath()); - assertEquals("a=1", result.getQuery()); + assertThat(result.getScheme()).isEqualTo("http"); + assertThat(result.getHost()).isEqualTo("localhost"); + assertThat(result.getPort()).isEqualTo(-1); + assertThat(result.getPath()).isEqualTo("/path"); + assertThat(result.getQuery()).isEqualTo("a=1"); } @Test // SPR-12771 @@ -275,10 +271,10 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https", result.getScheme()); - assertEquals("84.198.58.199", result.getHost()); - assertEquals(-1, result.getPort()); - assertEquals("/rest/mobile/users/1", result.getPath()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("84.198.58.199"); + assertThat(result.getPort()).isEqualTo(-1); + assertThat(result.getPath()).isEqualTo("/rest/mobile/users/1"); } @Test // SPR-14761 @@ -293,7 +289,7 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https://192.168.0.1/mvc-showcase", result.toString()); + assertThat(result.toString()).isEqualTo("https://192.168.0.1/mvc-showcase"); } @Test // SPR-14761 @@ -308,7 +304,7 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("http://[1abc:2abc:3abc::5ABC:6abc]/mvc-showcase", result.toString()); + assertThat(result.toString()).isEqualTo("http://[1abc:2abc:3abc::5ABC:6abc]/mvc-showcase"); } @Test // SPR-14761 @@ -323,7 +319,7 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("http://[1abc:2abc:3abc::5ABC:6abc]/mvc-showcase", result.toString()); + assertThat(result.toString()).isEqualTo("http://[1abc:2abc:3abc::5ABC:6abc]/mvc-showcase"); } @Test // SPR-14761 @@ -338,7 +334,7 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("http://[1abc:2abc:3abc::5ABC:6abc]:8080/mvc-showcase", result.toString()); + assertThat(result.toString()).isEqualTo("http://[1abc:2abc:3abc::5ABC:6abc]:8080/mvc-showcase"); } @Test @@ -353,7 +349,7 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https://anotherHost/mvc-showcase", result.toString()); + assertThat(result.toString()).isEqualTo("https://anotherHost/mvc-showcase"); } @Test // SPR-10701 @@ -368,8 +364,8 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("webtest.foo.bar.com", result.getHost()); - assertEquals(443, result.getPort()); + assertThat(result.getHost()).isEqualTo("webtest.foo.bar.com"); + assertThat(result.getPort()).isEqualTo(443); } @Test // SPR-11140 @@ -383,8 +379,8 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("a.example.org", result.getHost()); - assertEquals(-1, result.getPort()); + assertThat(result.getHost()).isEqualTo("a.example.org"); + assertThat(result.getPort()).isEqualTo(-1); } @Test // SPR-11855 @@ -399,8 +395,8 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("foobarhost", result.getHost()); - assertEquals(9090, result.getPort()); + assertThat(result.getHost()).isEqualTo("foobarhost"); + assertThat(result.getPort()).isEqualTo(9090); } @Test // SPR-11872 @@ -414,8 +410,8 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("example.org", result.getHost()); - assertEquals(-1, result.getPort()); + assertThat(result.getHost()).isEqualTo("example.org"); + assertThat(result.getPort()).isEqualTo(-1); } @Test // SPR-16262 @@ -429,9 +425,9 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https", result.getScheme()); - assertEquals("example.org", result.getHost()); - assertEquals(-1, result.getPort()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("example.org"); + assertThat(result.getPort()).isEqualTo(-1); } @Test // SPR-16863 @@ -445,9 +441,9 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https", result.getScheme()); - assertEquals("example.org", result.getHost()); - assertEquals(-1, result.getPort()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("example.org"); + assertThat(result.getPort()).isEqualTo(-1); } @Test @@ -462,9 +458,9 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("example.org", result.getHost()); - assertEquals("https", result.getScheme()); - assertEquals(-1, result.getPort()); + assertThat(result.getHost()).isEqualTo("example.org"); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getPort()).isEqualTo(-1); } @Test // SPR-12771 @@ -481,7 +477,7 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https://84.198.58.199/mvc-showcase", result.toString()); + assertThat(result.toString()).isEqualTo("https://84.198.58.199/mvc-showcase"); } @Test // SPR-12813 @@ -497,7 +493,7 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("http://a.example.org/mvc-showcase", result.toString()); + assertThat(result.toString()).isEqualTo("http://a.example.org/mvc-showcase"); } @Test // SPR-12816 @@ -514,14 +510,14 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https://a.example.org/mvc-showcase", result.toString()); + assertThat(result.toString()).isEqualTo("https://a.example.org/mvc-showcase"); } @Test // SPR-12742 public void fromHttpRequestWithTrailingSlash() { UriComponents before = UriComponentsBuilder.fromPath("/foo/").build(); UriComponents after = UriComponentsBuilder.newInstance().uriComponents(before).build(); - assertEquals("/foo/", after.getPath()); + assertThat(after.getPath()).isEqualTo("/foo/"); } @Test // gh-19890 @@ -544,7 +540,7 @@ public class UriComponentsBuilderTests { }; UriComponents result = UriComponentsBuilder.fromHttpRequest(request).build(); - assertEquals("/", result.toString()); + assertThat(result.toString()).isEqualTo("/"); } @Test @@ -552,8 +548,8 @@ public class UriComponentsBuilderTests { UriComponentsBuilder builder = UriComponentsBuilder.fromPath("/foo/bar"); UriComponents result = builder.build(); - assertEquals("/foo/bar", result.getPath()); - assertEquals(Arrays.asList("foo", "bar"), result.getPathSegments()); + assertThat(result.getPath()).isEqualTo("/foo/bar"); + assertThat(result.getPathSegments()).isEqualTo(Arrays.asList("foo", "bar")); } @Test @@ -561,8 +557,8 @@ public class UriComponentsBuilderTests { UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); UriComponents result = builder.pathSegment("foo").pathSegment("bar").build(); - assertEquals("/foo/bar", result.getPath()); - assertEquals(Arrays.asList("foo", "bar"), result.getPathSegments()); + assertThat(result.getPath()).isEqualTo("/foo/bar"); + assertThat(result.getPathSegments()).isEqualTo(Arrays.asList("foo", "bar")); } @Test @@ -570,8 +566,8 @@ public class UriComponentsBuilderTests { UriComponentsBuilder builder = UriComponentsBuilder.fromPath("/foo/bar").path("ba/z"); UriComponents result = builder.build().encode(); - assertEquals("/foo/barba/z", result.getPath()); - assertEquals(Arrays.asList("foo", "barba", "z"), result.getPathSegments()); + assertThat(result.getPath()).isEqualTo("/foo/barba/z"); + assertThat(result.getPathSegments()).isEqualTo(Arrays.asList("foo", "barba", "z")); } @Test @@ -579,8 +575,8 @@ public class UriComponentsBuilderTests { UriComponentsBuilder builder = UriComponentsBuilder.fromPath("/foo/bar").pathSegment("ba/z"); UriComponents result = builder.build().encode(); - assertEquals("/foo/bar/ba%2Fz", result.getPath()); - assertEquals(Arrays.asList("foo", "bar", "ba%2Fz"), result.getPathSegments()); + assertThat(result.getPath()).isEqualTo("/foo/bar/ba%2Fz"); + assertThat(result.getPathSegments()).isEqualTo(Arrays.asList("foo", "bar", "ba%2Fz")); } @Test @@ -588,8 +584,8 @@ public class UriComponentsBuilderTests { UriComponentsBuilder builder = UriComponentsBuilder.newInstance().pathSegment("foo").pathSegment("bar"); UriComponents result = builder.build(); - assertEquals("/foo/bar", result.getPath()); - assertEquals(Arrays.asList("foo", "bar"), result.getPathSegments()); + assertThat(result.getPath()).isEqualTo("/foo/bar"); + assertThat(result.getPathSegments()).isEqualTo(Arrays.asList("foo", "bar")); } @Test @@ -597,8 +593,8 @@ public class UriComponentsBuilderTests { UriComponentsBuilder builder = UriComponentsBuilder.newInstance().pathSegment("foo").path("/"); UriComponents result = builder.build(); - assertEquals("/foo/", result.getPath()); - assertEquals(Collections.singletonList("foo"), result.getPathSegments()); + assertThat(result.getPath()).isEqualTo("/foo/"); + assertThat(result.getPathSegments()).isEqualTo(Collections.singletonList("foo")); } @Test @@ -606,14 +602,14 @@ public class UriComponentsBuilderTests { UriComponentsBuilder builder = UriComponentsBuilder.newInstance().pathSegment("", "foo", "", "bar"); UriComponents result = builder.build(); - assertEquals("/foo/bar", result.getPath()); - assertEquals(Arrays.asList("foo", "bar"), result.getPathSegments()); + assertThat(result.getPath()).isEqualTo("/foo/bar"); + assertThat(result.getPathSegments()).isEqualTo(Arrays.asList("foo", "bar")); } @Test // SPR-12398 public void pathWithDuplicateSlashes() { UriComponents uriComponents = UriComponentsBuilder.fromPath("/foo/////////bar").build(); - assertEquals("/foo/bar", uriComponents.getPath()); + assertThat(uriComponents.getPath()).isEqualTo("/foo/bar"); } @Test @@ -622,13 +618,13 @@ public class UriComponentsBuilderTests { builder.replacePath("/rfc/rfc3986.txt"); UriComponents result = builder.build(); - assertEquals("https://www.ietf.org/rfc/rfc3986.txt", result.toUriString()); + assertThat(result.toUriString()).isEqualTo("https://www.ietf.org/rfc/rfc3986.txt"); builder = UriComponentsBuilder.fromUriString("https://www.ietf.org/rfc/rfc2396.txt"); builder.replacePath(null); result = builder.build(); - assertEquals("https://www.ietf.org", result.toUriString()); + assertThat(result.toUriString()).isEqualTo("https://www.ietf.org"); } @Test @@ -637,13 +633,13 @@ public class UriComponentsBuilderTests { builder.replaceQuery("baz=42"); UriComponents result = builder.build(); - assertEquals("https://example.com/foo?baz=42", result.toUriString()); + assertThat(result.toUriString()).isEqualTo("https://example.com/foo?baz=42"); builder = UriComponentsBuilder.fromUriString("https://example.com/foo?foo=bar&baz=qux"); builder.replaceQuery(null); result = builder.build(); - assertEquals("https://example.com/foo", result.toUriString()); + assertThat(result.toUriString()).isEqualTo("https://example.com/foo"); } @Test @@ -651,11 +647,11 @@ public class UriComponentsBuilderTests { UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); UriComponents result = builder.queryParam("baz", "qux", 42).build(); - assertEquals("baz=qux&baz=42", result.getQuery()); + assertThat(result.getQuery()).isEqualTo("baz=qux&baz=42"); MultiValueMap expectedQueryParams = new LinkedMultiValueMap<>(2); expectedQueryParams.add("baz", "qux"); expectedQueryParams.add("baz", "42"); - assertEquals(expectedQueryParams, result.getQueryParams()); + assertThat(result.getQueryParams()).isEqualTo(expectedQueryParams); } @Test @@ -663,10 +659,10 @@ public class UriComponentsBuilderTests { UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); UriComponents result = builder.queryParam("baz").build(); - assertEquals("baz", result.getQuery()); + assertThat(result.getQuery()).isEqualTo("baz"); MultiValueMap expectedQueryParams = new LinkedMultiValueMap<>(2); expectedQueryParams.add("baz", null); - assertEquals(expectedQueryParams, result.getQueryParams()); + assertThat(result.getQueryParams()).isEqualTo(expectedQueryParams); } @Test @@ -675,38 +671,38 @@ public class UriComponentsBuilderTests { builder.replaceQueryParam("baz", "xuq", 24); UriComponents result = builder.build(); - assertEquals("baz=xuq&baz=24", result.getQuery()); + assertThat(result.getQuery()).isEqualTo("baz=xuq&baz=24"); builder = UriComponentsBuilder.newInstance().queryParam("baz", "qux", 42); builder.replaceQueryParam("baz"); result = builder.build(); - assertNull("Query param should have been deleted", result.getQuery()); + assertThat(result.getQuery()).as("Query param should have been deleted").isNull(); } @Test public void buildAndExpandHierarchical() { UriComponents result = UriComponentsBuilder.fromPath("/{foo}").buildAndExpand("fooValue"); - assertEquals("/fooValue", result.toUriString()); + assertThat(result.toUriString()).isEqualTo("/fooValue"); Map values = new HashMap<>(); values.put("foo", "fooValue"); values.put("bar", "barValue"); result = UriComponentsBuilder.fromPath("/{foo}/{bar}").buildAndExpand(values); - assertEquals("/fooValue/barValue", result.toUriString()); + assertThat(result.toUriString()).isEqualTo("/fooValue/barValue"); } @Test public void buildAndExpandOpaque() { UriComponents result = UriComponentsBuilder.fromUriString("mailto:{user}@{domain}") .buildAndExpand("foo", "example.com"); - assertEquals("mailto:foo@example.com", result.toUriString()); + assertThat(result.toUriString()).isEqualTo("mailto:foo@example.com"); Map values = new HashMap<>(); values.put("user", "foo"); values.put("domain", "example.com"); UriComponentsBuilder.fromUriString("mailto:{user}@{domain}").buildAndExpand(values); - assertEquals("mailto:foo@example.com", result.toUriString()); + assertThat(result.toUriString()).isEqualTo("mailto:foo@example.com"); } @Test @@ -790,18 +786,18 @@ public class UriComponentsBuilderTests { builder2.scheme("https").host("e2.com").path("p2").pathSegment("{ps2}").queryParam("q2").fragment("f2"); UriComponents result1 = builder1.build(); - assertEquals("http", result1.getScheme()); - assertEquals("e1.com", result1.getHost()); - assertEquals("/p1/ps1", result1.getPath()); - assertEquals("q1", result1.getQuery()); - assertEquals("f1", result1.getFragment()); + assertThat(result1.getScheme()).isEqualTo("http"); + assertThat(result1.getHost()).isEqualTo("e1.com"); + assertThat(result1.getPath()).isEqualTo("/p1/ps1"); + assertThat(result1.getQuery()).isEqualTo("q1"); + assertThat(result1.getFragment()).isEqualTo("f1"); UriComponents result2 = builder2.buildAndExpand("ps2;a"); - assertEquals("https", result2.getScheme()); - assertEquals("e2.com", result2.getHost()); - assertEquals("/p1/ps1/p2/ps2%3Ba", result2.getPath()); - assertEquals("q1&q2", result2.getQuery()); - assertEquals("f2", result2.getFragment()); + assertThat(result2.getScheme()).isEqualTo("https"); + assertThat(result2.getHost()).isEqualTo("e2.com"); + assertThat(result2.getPath()).isEqualTo("/p1/ps1/p2/ps2%3Ba"); + assertThat(result2.getQuery()).isEqualTo("q1&q2"); + assertThat(result2.getFragment()).isEqualTo("f2"); } @Test // SPR-11856 @@ -815,9 +811,9 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https", result.getScheme()); - assertEquals("84.198.58.199", result.getHost()); - assertEquals("/rest/mobile/users/1", result.getPath()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("84.198.58.199"); + assertThat(result.getPath()).isEqualTo("/rest/mobile/users/1"); } @Test @@ -831,9 +827,9 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https", result.getScheme()); - assertEquals("84.198.58.199", result.getHost()); - assertEquals("/rest/mobile/users/1", result.getPath()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("84.198.58.199"); + assertThat(result.getPath()).isEqualTo("/rest/mobile/users/1"); } @Test @@ -848,9 +844,9 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https", result.getScheme()); - assertEquals("84.198.58.199", result.getHost()); - assertEquals("/rest/mobile/users/1", result.getPath()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("84.198.58.199"); + assertThat(result.getPath()).isEqualTo("/rest/mobile/users/1"); } @Test @@ -864,9 +860,9 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https", result.getScheme()); - assertEquals("84.198.58.199", result.getHost()); - assertEquals("/rest/mobile/users/1", result.getPath()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("84.198.58.199"); + assertThat(result.getPath()).isEqualTo("/rest/mobile/users/1"); } @Test @@ -880,11 +876,11 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https", result.getScheme()); - assertEquals("84.198.58.199", result.getHost()); - assertEquals("/rest/mobile/users/1", result.getPath()); - assertEquals(9090, result.getPort()); - assertEquals("https://84.198.58.199:9090/rest/mobile/users/1", result.toUriString()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("84.198.58.199"); + assertThat(result.getPath()).isEqualTo("/rest/mobile/users/1"); + assertThat(result.getPort()).isEqualTo(9090); + assertThat(result.toUriString()).isEqualTo("https://84.198.58.199:9090/rest/mobile/users/1"); } @Test @@ -899,11 +895,11 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https", result.getScheme()); - assertEquals("84.198.58.199", result.getHost()); - assertEquals("/rest/mobile/users/1", result.getPath()); - assertEquals(9090, result.getPort()); - assertEquals("https://84.198.58.199:9090/rest/mobile/users/1", result.toUriString()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("84.198.58.199"); + assertThat(result.getPath()).isEqualTo("/rest/mobile/users/1"); + assertThat(result.getPort()).isEqualTo(9090); + assertThat(result.toUriString()).isEqualTo("https://84.198.58.199:9090/rest/mobile/users/1"); } @Test @@ -918,11 +914,11 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https", result.getScheme()); - assertEquals("84.198.58.199", result.getHost()); - assertEquals("/rest/mobile/users/1", result.getPath()); - assertEquals(-1, result.getPort()); - assertEquals("https://84.198.58.199/rest/mobile/users/1", result.toUriString()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("84.198.58.199"); + assertThat(result.getPath()).isEqualTo("/rest/mobile/users/1"); + assertThat(result.getPort()).isEqualTo(-1); + assertThat(result.toUriString()).isEqualTo("https://84.198.58.199/rest/mobile/users/1"); } @Test // SPR-16262 @@ -937,11 +933,11 @@ public class UriComponentsBuilderTests { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); - assertEquals("https", result.getScheme()); - assertEquals("example.com", result.getHost()); - assertEquals("/rest/mobile/users/1", result.getPath()); - assertEquals(-1, result.getPort()); - assertEquals("https://example.com/rest/mobile/users/1", result.toUriString()); + assertThat(result.getScheme()).isEqualTo("https"); + assertThat(result.getHost()).isEqualTo("example.com"); + assertThat(result.getPath()).isEqualTo("/rest/mobile/users/1"); + assertThat(result.getPort()).isEqualTo(-1); + assertThat(result.toUriString()).isEqualTo("https://example.com/rest/mobile/users/1"); } @Test // SPR-16364 @@ -949,9 +945,9 @@ public class UriComponentsBuilderTests { UriComponents uri1 = UriComponentsBuilder.fromUriString("http://test.com").build().normalize(); UriComponents uri2 = UriComponentsBuilder.fromUriString("http://test.com/").build(); - assertTrue(uri1.getPathSegments().isEmpty()); - assertTrue(uri2.getPathSegments().isEmpty()); - assertNotEquals(uri1, uri2); + assertThat(uri1.getPathSegments().isEmpty()).isTrue(); + assertThat(uri2.getPathSegments().isEmpty()).isTrue(); + assertThat(uri2).isNotEqualTo(uri1); } @Test // SPR-17256 @@ -960,12 +956,11 @@ public class UriComponentsBuilderTests { .uriComponents(UriComponentsBuilder.fromUriString("/{path}?sort={sort}").build()) .queryParam("sort", "another_value").build().toString(); - assertEquals("http://localhost:8081/{path}?sort={sort}&sort=another_value", uri); + assertThat(uri).isEqualTo("http://localhost:8081/{path}?sort={sort}&sort=another_value"); } @Test // SPR-17630 public void toUriStringWithCurlyBraces() { - assertEquals("/path?q=%7Basa%7Dasa", - UriComponentsBuilder.fromUriString("/path?q={asa}asa").toUriString()); + assertThat(UriComponentsBuilder.fromUriString("/path?q={asa}asa").toUriString()).isEqualTo("/path?q=%7Basa%7Dasa"); } } diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java index 93429843dd3..6fb68437003 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java @@ -30,7 +30,6 @@ 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.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; import static org.springframework.web.util.UriComponentsBuilder.fromUriString; /** @@ -49,7 +48,7 @@ public class UriComponentsTests { .fromPath("/hotel list/{city} specials").queryParam("q", "{value}").build() .expand("Z\u00fcrich", "a+b").encode(); - assertEquals("/hotel%20list/Z%C3%BCrich%20specials?q=a+b", uri.toString()); + assertThat(uri.toString()).isEqualTo("/hotel%20list/Z%C3%BCrich%20specials?q=a+b"); } @Test @@ -59,7 +58,7 @@ public class UriComponentsTests { .fromPath("/hotel list/{city} specials").queryParam("q", "{value}").encode().build() .expand("Z\u00fcrich", "a+b"); - assertEquals("/hotel%20list/Z%C3%BCrich%20specials?q=a%2Bb", uri.toString()); + assertThat(uri.toString()).isEqualTo("/hotel%20list/Z%C3%BCrich%20specials?q=a%2Bb"); } @Test @@ -70,27 +69,27 @@ public class UriComponentsTests { .uriVariables(Collections.singletonMap("city", "Z\u00fcrich")) .build(); - assertEquals("/hotel%20list/Z%C3%BCrich%20specials?q=a%2Bb", uri.expand("a+b").toString()); + assertThat(uri.expand("a+b").toString()).isEqualTo("/hotel%20list/Z%C3%BCrich%20specials?q=a%2Bb"); } @Test // SPR-17168 public void encodeAndExpandWithDollarSign() { UriComponents uri = UriComponentsBuilder.fromPath("/path").queryParam("q", "{value}").encode().build(); - assertEquals("/path?q=JavaClass%241.class", uri.expand("JavaClass$1.class").toString()); + assertThat(uri.expand("JavaClass$1.class").toString()).isEqualTo("/path?q=JavaClass%241.class"); } @Test public void toUriEncoded() throws URISyntaxException { UriComponents uriComponents = UriComponentsBuilder.fromUriString( "https://example.com/hotel list/Z\u00fcrich").build(); - assertEquals(new URI("https://example.com/hotel%20list/Z%C3%BCrich"), uriComponents.encode().toUri()); + assertThat(uriComponents.encode().toUri()).isEqualTo(new URI("https://example.com/hotel%20list/Z%C3%BCrich")); } @Test public void toUriNotEncoded() throws URISyntaxException { UriComponents uriComponents = UriComponentsBuilder.fromUriString( "https://example.com/hotel list/Z\u00fcrich").build(); - assertEquals(new URI("https://example.com/hotel%20list/Z\u00fcrich"), uriComponents.toUri()); + assertThat(uriComponents.toUri()).isEqualTo(new URI("https://example.com/hotel%20list/Z\u00fcrich")); } @Test @@ -98,7 +97,7 @@ public class UriComponentsTests { UriComponents uriComponents = UriComponentsBuilder.fromUriString( "https://example.com/hotel%20list/Z%C3%BCrich").build(true); UriComponents encoded = uriComponents.encode(); - assertEquals(new URI("https://example.com/hotel%20list/Z%C3%BCrich"), encoded.toUri()); + assertThat(encoded.toUri()).isEqualTo(new URI("https://example.com/hotel%20list/Z%C3%BCrich")); } @Test @@ -106,7 +105,7 @@ public class UriComponentsTests { UriComponents uriComponents = UriComponentsBuilder.fromUriString( "http://[1abc:2abc:3abc::5ABC:6abc]:8080/hotel%20list/Z%C3%BCrich").build(true); UriComponents encoded = uriComponents.encode(); - assertEquals(new URI("http://[1abc:2abc:3abc::5ABC:6abc]:8080/hotel%20list/Z%C3%BCrich"), encoded.toUri()); + assertThat(encoded.toUri()).isEqualTo(new URI("http://[1abc:2abc:3abc::5ABC:6abc]:8080/hotel%20list/Z%C3%BCrich")); } @Test @@ -114,8 +113,8 @@ public class UriComponentsTests { UriComponents uriComponents = UriComponentsBuilder.fromUriString( "https://example.com").path("/{foo} {bar}").build(); uriComponents = uriComponents.expand("1 2", "3 4"); - assertEquals("/1 2 3 4", uriComponents.getPath()); - assertEquals("https://example.com/1 2 3 4", uriComponents.toUriString()); + assertThat(uriComponents.getPath()).isEqualTo("/1 2 3 4"); + assertThat(uriComponents.toUriString()).isEqualTo("https://example.com/1 2 3 4"); } @Test // SPR-13311 @@ -123,13 +122,12 @@ public class UriComponentsTests { String template = "/myurl/{name:[a-z]{1,5}}/show"; UriComponents uriComponents = UriComponentsBuilder.fromUriString(template).build(); uriComponents = uriComponents.expand(Collections.singletonMap("name", "test")); - assertEquals("/myurl/test/show", uriComponents.getPath()); + assertThat(uriComponents.getPath()).isEqualTo("/myurl/test/show"); } @Test // SPR-17630 public void uirTemplateExpandWithMismatchedCurlyBraces() { - assertEquals("/myurl/?q=%7B%7B%7B%7B", - UriComponentsBuilder.fromUriString("/myurl/?q={{{{").encode().build().toUriString()); + assertThat(UriComponentsBuilder.fromUriString("/myurl/?q={{{{").encode().build().toUriString()).isEqualTo("/myurl/?q=%7B%7B%7B%7B"); } @Test // gh-22447 @@ -138,7 +136,7 @@ public class UriComponentsTests { .fromUriString("https://{host}/{path}#{fragment}").build() .expand("example.com", "foo", "bar"); - assertEquals("https://example.com/foo#bar", uriComponents.toUriString()); + assertThat(uriComponents.toUriString()).isEqualTo("https://example.com/foo#bar"); } @Test // SPR-12123 @@ -147,14 +145,14 @@ public class UriComponentsTests { UriComponents uri2 = fromUriString("https://example.com/bar").port(8080).build(); UriComponents uri3 = fromUriString("https://example.com/bar").port("{port}").build().expand(8080); UriComponents uri4 = fromUriString("https://example.com/bar").port("808{digit}").build().expand(0); - assertEquals(8080, uri1.getPort()); - assertEquals("https://example.com:8080/bar", uri1.toUriString()); - assertEquals(8080, uri2.getPort()); - assertEquals("https://example.com:8080/bar", uri2.toUriString()); - assertEquals(8080, uri3.getPort()); - assertEquals("https://example.com:8080/bar", uri3.toUriString()); - assertEquals(8080, uri4.getPort()); - assertEquals("https://example.com:8080/bar", uri4.toUriString()); + assertThat(uri1.getPort()).isEqualTo(8080); + assertThat(uri1.toUriString()).isEqualTo("https://example.com:8080/bar"); + assertThat(uri2.getPort()).isEqualTo(8080); + assertThat(uri2.toUriString()).isEqualTo("https://example.com:8080/bar"); + assertThat(uri3.getPort()).isEqualTo(8080); + assertThat(uri3.toUriString()).isEqualTo("https://example.com:8080/bar"); + assertThat(uri4.getPort()).isEqualTo(8080); + assertThat(uri4.toUriString()).isEqualTo("https://example.com:8080/bar"); } @Test @@ -178,7 +176,7 @@ public class UriComponentsTests { @Test public void normalize() { UriComponents uriComponents = UriComponentsBuilder.fromUriString("https://example.com/foo/../bar").build(); - assertEquals("https://example.com/bar", uriComponents.normalize().toString()); + assertThat(uriComponents.normalize().toString()).isEqualTo("https://example.com/bar"); } @Test @@ -199,8 +197,8 @@ public class UriComponentsTests { UriComponentsBuilder targetBuilder = UriComponentsBuilder.newInstance(); source.copyToUriComponentsBuilder(targetBuilder); UriComponents result = targetBuilder.build().encode(); - assertEquals("/foo/bar/ba%2Fz", result.getPath()); - assertEquals(Arrays.asList("foo", "bar", "ba%2Fz"), result.getPathSegments()); + assertThat(result.getPath()).isEqualTo("/foo/bar/ba%2Fz"); + assertThat(result.getPathSegments()).isEqualTo(Arrays.asList("foo", "bar", "ba%2Fz")); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/util/UriTemplateTests.java b/spring-web/src/test/java/org/springframework/web/util/UriTemplateTests.java index 7e8f5664394..9c31f6f6ddc 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriTemplateTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriTemplateTests.java @@ -25,10 +25,8 @@ import java.util.Map; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; 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 Arjen Poutsma @@ -41,14 +39,14 @@ public class UriTemplateTests { public void getVariableNames() throws Exception { UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); List variableNames = template.getVariableNames(); - assertEquals("Invalid variable names", Arrays.asList("hotel", "booking"), variableNames); + assertThat(variableNames).as("Invalid variable names").isEqualTo(Arrays.asList("hotel", "booking")); } @Test public void expandVarArgs() throws Exception { UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); URI result = template.expand("1", "42"); - assertEquals("Invalid expanded template", new URI("/hotels/1/bookings/42"), result); + assertThat(result).as("Invalid expanded template").isEqualTo(new URI("/hotels/1/bookings/42")); } // SPR-9712 @@ -57,7 +55,7 @@ public class UriTemplateTests { public void expandVarArgsWithArrayValue() throws Exception { UriTemplate template = new UriTemplate("/sum?numbers={numbers}"); URI result = template.expand(new int[] {1, 2, 3}); - assertEquals(new URI("/sum?numbers=1,2,3"), result); + assertThat(result).isEqualTo(new URI("/sum?numbers=1,2,3")); } @Test @@ -74,15 +72,15 @@ public class UriTemplateTests { uriVariables.put("hotel", "1"); UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); URI result = template.expand(uriVariables); - assertEquals("Invalid expanded template", new URI("/hotels/1/bookings/42"), result); + assertThat(result).as("Invalid expanded template").isEqualTo(new URI("/hotels/1/bookings/42")); } @Test public void expandMapDuplicateVariables() throws Exception { UriTemplate template = new UriTemplate("/order/{c}/{c}/{c}"); - assertEquals(Arrays.asList("c", "c", "c"), template.getVariableNames()); + assertThat(template.getVariableNames()).isEqualTo(Arrays.asList("c", "c", "c")); URI result = template.expand(Collections.singletonMap("c", "cheeseburger")); - assertEquals(new URI("/order/cheeseburger/cheeseburger/cheeseburger"), result); + assertThat(result).isEqualTo(new URI("/order/cheeseburger/cheeseburger/cheeseburger")); } @Test @@ -92,7 +90,7 @@ public class UriTemplateTests { uriVariables.put("hotel", 1); UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); URI result = template.expand(uriVariables); - assertEquals("Invalid expanded template", new URI("/hotels/1/bookings/42"), result); + assertThat(result).as("Invalid expanded template").isEqualTo(new URI("/hotels/1/bookings/42")); } @Test @@ -100,7 +98,7 @@ public class UriTemplateTests { Map uriVariables = Collections.singletonMap("hotel", "Z\u00fcrich"); UriTemplate template = new UriTemplate("/hotel list/{hotel}"); URI result = template.expand(uriVariables); - assertEquals("Invalid expanded template", new URI("/hotel%20list/Z%C3%BCrich"), result); + assertThat(result).as("Invalid expanded template").isEqualTo(new URI("/hotel%20list/Z%C3%BCrich")); } @Test @@ -117,23 +115,23 @@ public class UriTemplateTests { public void expandEncoded() throws Exception { UriTemplate template = new UriTemplate("/hotel list/{hotel}"); URI result = template.expand("Z\u00fcrich"); - assertEquals("Invalid expanded template", new URI("/hotel%20list/Z%C3%BCrich"), result); + assertThat(result).as("Invalid expanded template").isEqualTo(new URI("/hotel%20list/Z%C3%BCrich")); } @Test public void matches() throws Exception { UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); - assertTrue("UriTemplate does not match", template.matches("/hotels/1/bookings/42")); - assertFalse("UriTemplate matches", template.matches("/hotels/bookings")); - assertFalse("UriTemplate matches", template.matches("")); - assertFalse("UriTemplate matches", template.matches(null)); + assertThat(template.matches("/hotels/1/bookings/42")).as("UriTemplate does not match").isTrue(); + assertThat(template.matches("/hotels/bookings")).as("UriTemplate matches").isFalse(); + assertThat(template.matches("")).as("UriTemplate matches").isFalse(); + assertThat(template.matches(null)).as("UriTemplate matches").isFalse(); } @Test public void matchesCustomRegex() throws Exception { UriTemplate template = new UriTemplate("/hotels/{hotel:\\d+}"); - assertTrue("UriTemplate does not match", template.matches("/hotels/42")); - assertFalse("UriTemplate matches", template.matches("/hotels/foo")); + assertThat(template.matches("/hotels/42")).as("UriTemplate does not match").isTrue(); + assertThat(template.matches("/hotels/foo")).as("UriTemplate matches").isFalse(); } @Test @@ -144,7 +142,7 @@ public class UriTemplateTests { UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); Map result = template.match("/hotels/1/bookings/42"); - assertEquals("Invalid match", expected, result); + assertThat(result).as("Invalid match").isEqualTo(expected); } @Test @@ -155,14 +153,14 @@ public class UriTemplateTests { UriTemplate template = new UriTemplate("/hotels/{hotel:\\d}/bookings/{booking:\\d+}"); Map result = template.match("/hotels/1/bookings/42"); - assertEquals("Invalid match", expected, result); + assertThat(result).as("Invalid match").isEqualTo(expected); } @Test // SPR-13627 public void matchCustomRegexWithNestedCurlyBraces() throws Exception { UriTemplate template = new UriTemplate("/site.{domain:co.[a-z]{2}}"); Map result = template.match("/site.co.eu"); - assertEquals("Invalid match", Collections.singletonMap("domain", "co.eu"), result); + assertThat(result).as("Invalid match").isEqualTo(Collections.singletonMap("domain", "co.eu")); } @Test @@ -170,7 +168,7 @@ public class UriTemplateTests { UriTemplate template = new UriTemplate("/order/{c}/{c}/{c}"); Map result = template.match("/order/cheeseburger/cheeseburger/cheeseburger"); Map expected = Collections.singletonMap("c", "cheeseburger"); - assertEquals("Invalid match", expected, result); + assertThat(result).as("Invalid match").isEqualTo(expected); } @Test @@ -180,48 +178,48 @@ public class UriTemplateTests { Map expected = new HashMap<>(2); expected.put("foo", "12"); expected.put("bar", "34"); - assertEquals("Invalid match", expected, result); + assertThat(result).as("Invalid match").isEqualTo(expected); } @Test // SPR-16169 public void matchWithMultipleSegmentsAtTheEnd() { UriTemplate template = new UriTemplate("/account/{accountId}"); - assertFalse(template.matches("/account/15/alias/5")); + assertThat(template.matches("/account/15/alias/5")).isFalse(); } @Test public void queryVariables() throws Exception { UriTemplate template = new UriTemplate("/search?q={query}"); - assertTrue(template.matches("/search?q=foo")); + assertThat(template.matches("/search?q=foo")).isTrue(); } @Test public void fragments() throws Exception { UriTemplate template = new UriTemplate("/search#{fragment}"); - assertTrue(template.matches("/search#foo")); + assertThat(template.matches("/search#foo")).isTrue(); template = new UriTemplate("/search?query={query}#{fragment}"); - assertTrue(template.matches("/search?query=foo#bar")); + assertThat(template.matches("/search?query=foo#bar")).isTrue(); } @Test // SPR-13705 public void matchesWithSlashAtTheEnd() { UriTemplate uriTemplate = new UriTemplate("/test/"); - assertTrue(uriTemplate.matches("/test/")); + assertThat(uriTemplate.matches("/test/")).isTrue(); } @Test public void expandWithDollar() { UriTemplate template = new UriTemplate("/{a}"); URI uri = template.expand("$replacement"); - assertEquals("/$replacement", uri.toString()); + assertThat(uri.toString()).isEqualTo("/$replacement"); } @Test public void expandWithAtSign() { UriTemplate template = new UriTemplate("http://localhost/query={query}"); URI uri = template.expand("foo@bar"); - assertEquals("http://localhost/query=foo@bar", uri.toString()); + assertThat(uri.toString()).isEqualTo("http://localhost/query=foo@bar"); } } diff --git a/spring-web/src/test/java/org/springframework/web/util/UriUtilsTests.java b/spring-web/src/test/java/org/springframework/web/util/UriUtilsTests.java index 1fc05ed5491..d3da7707a9b 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriUtilsTests.java @@ -21,8 +21,8 @@ import java.nio.charset.StandardCharsets; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @author Arjen Poutsma @@ -36,78 +36,77 @@ public class UriUtilsTests { @Test public void encodeScheme() { - assertEquals("Invalid encoded result", "foobar+-.", UriUtils.encodeScheme("foobar+-.", CHARSET)); - assertEquals("Invalid encoded result", "foo%20bar", UriUtils.encodeScheme("foo bar", CHARSET)); + assertThat(UriUtils.encodeScheme("foobar+-.", CHARSET)).as("Invalid encoded result").isEqualTo("foobar+-."); + assertThat(UriUtils.encodeScheme("foo bar", CHARSET)).as("Invalid encoded result").isEqualTo("foo%20bar"); } @Test public void encodeUserInfo() { - assertEquals("Invalid encoded result", "foobar:", UriUtils.encodeUserInfo("foobar:", CHARSET)); - assertEquals("Invalid encoded result", "foo%20bar", UriUtils.encodeUserInfo("foo bar", CHARSET)); + assertThat(UriUtils.encodeUserInfo("foobar:", CHARSET)).as("Invalid encoded result").isEqualTo("foobar:"); + assertThat(UriUtils.encodeUserInfo("foo bar", CHARSET)).as("Invalid encoded result").isEqualTo("foo%20bar"); } @Test public void encodeHost() { - assertEquals("Invalid encoded result", "foobar", UriUtils.encodeHost("foobar", CHARSET)); - assertEquals("Invalid encoded result", "foo%20bar", UriUtils.encodeHost("foo bar", CHARSET)); + assertThat(UriUtils.encodeHost("foobar", CHARSET)).as("Invalid encoded result").isEqualTo("foobar"); + assertThat(UriUtils.encodeHost("foo bar", CHARSET)).as("Invalid encoded result").isEqualTo("foo%20bar"); } @Test public void encodePort() { - assertEquals("Invalid encoded result", "80", UriUtils.encodePort("80", CHARSET)); + assertThat(UriUtils.encodePort("80", CHARSET)).as("Invalid encoded result").isEqualTo("80"); } @Test public void encodePath() { - assertEquals("Invalid encoded result", "/foo/bar", UriUtils.encodePath("/foo/bar", CHARSET)); - assertEquals("Invalid encoded result", "/foo%20bar", UriUtils.encodePath("/foo bar", CHARSET)); - assertEquals("Invalid encoded result", "/Z%C3%BCrich", UriUtils.encodePath("/Z\u00fcrich", CHARSET)); + assertThat(UriUtils.encodePath("/foo/bar", CHARSET)).as("Invalid encoded result").isEqualTo("/foo/bar"); + assertThat(UriUtils.encodePath("/foo bar", CHARSET)).as("Invalid encoded result").isEqualTo("/foo%20bar"); + assertThat(UriUtils.encodePath("/Z\u00fcrich", CHARSET)).as("Invalid encoded result").isEqualTo("/Z%C3%BCrich"); } @Test public void encodePathSegment() { - assertEquals("Invalid encoded result", "foobar", UriUtils.encodePathSegment("foobar", CHARSET)); - assertEquals("Invalid encoded result", "%2Ffoo%2Fbar", UriUtils.encodePathSegment("/foo/bar", CHARSET)); + assertThat(UriUtils.encodePathSegment("foobar", CHARSET)).as("Invalid encoded result").isEqualTo("foobar"); + assertThat(UriUtils.encodePathSegment("/foo/bar", CHARSET)).as("Invalid encoded result").isEqualTo("%2Ffoo%2Fbar"); } @Test public void encodeQuery() { - assertEquals("Invalid encoded result", "foobar", UriUtils.encodeQuery("foobar", CHARSET)); - assertEquals("Invalid encoded result", "foo%20bar", UriUtils.encodeQuery("foo bar", CHARSET)); - assertEquals("Invalid encoded result", "foobar/+", UriUtils.encodeQuery("foobar/+", CHARSET)); - assertEquals("Invalid encoded result", "T%C5%8Dky%C5%8D", UriUtils.encodeQuery("T\u014dky\u014d", CHARSET)); + assertThat(UriUtils.encodeQuery("foobar", CHARSET)).as("Invalid encoded result").isEqualTo("foobar"); + assertThat(UriUtils.encodeQuery("foo bar", CHARSET)).as("Invalid encoded result").isEqualTo("foo%20bar"); + assertThat(UriUtils.encodeQuery("foobar/+", CHARSET)).as("Invalid encoded result").isEqualTo("foobar/+"); + assertThat(UriUtils.encodeQuery("T\u014dky\u014d", CHARSET)).as("Invalid encoded result").isEqualTo("T%C5%8Dky%C5%8D"); } @Test public void encodeQueryParam() { - assertEquals("Invalid encoded result", "foobar", UriUtils.encodeQueryParam("foobar", CHARSET)); - assertEquals("Invalid encoded result", "foo%20bar", UriUtils.encodeQueryParam("foo bar", CHARSET)); - assertEquals("Invalid encoded result", "foo%26bar", UriUtils.encodeQueryParam("foo&bar", CHARSET)); + assertThat(UriUtils.encodeQueryParam("foobar", CHARSET)).as("Invalid encoded result").isEqualTo("foobar"); + assertThat(UriUtils.encodeQueryParam("foo bar", CHARSET)).as("Invalid encoded result").isEqualTo("foo%20bar"); + assertThat(UriUtils.encodeQueryParam("foo&bar", CHARSET)).as("Invalid encoded result").isEqualTo("foo%26bar"); } @Test public void encodeFragment() { - assertEquals("Invalid encoded result", "foobar", UriUtils.encodeFragment("foobar", CHARSET)); - assertEquals("Invalid encoded result", "foo%20bar", UriUtils.encodeFragment("foo bar", CHARSET)); - assertEquals("Invalid encoded result", "foobar/", UriUtils.encodeFragment("foobar/", CHARSET)); + assertThat(UriUtils.encodeFragment("foobar", CHARSET)).as("Invalid encoded result").isEqualTo("foobar"); + assertThat(UriUtils.encodeFragment("foo bar", CHARSET)).as("Invalid encoded result").isEqualTo("foo%20bar"); + assertThat(UriUtils.encodeFragment("foobar/", CHARSET)).as("Invalid encoded result").isEqualTo("foobar/"); } @Test public void encode() { - assertEquals("Invalid encoded result", "foo", UriUtils.encode("foo", CHARSET)); - assertEquals("Invalid encoded result", "https%3A%2F%2Fexample.com%2Ffoo%20bar", - UriUtils.encode("https://example.com/foo bar", CHARSET)); + assertThat(UriUtils.encode("foo", CHARSET)).as("Invalid encoded result").isEqualTo("foo"); + assertThat(UriUtils.encode("https://example.com/foo bar", CHARSET)).as("Invalid encoded result").isEqualTo("https%3A%2F%2Fexample.com%2Ffoo%20bar"); } @Test public void decode() { - assertEquals("Invalid encoded URI", "", UriUtils.decode("", CHARSET)); - assertEquals("Invalid encoded URI", "foobar", UriUtils.decode("foobar", CHARSET)); - assertEquals("Invalid encoded URI", "foo bar", UriUtils.decode("foo%20bar", CHARSET)); - assertEquals("Invalid encoded URI", "foo+bar", UriUtils.decode("foo%2bbar", CHARSET)); - assertEquals("Invalid encoded result", "T\u014dky\u014d", UriUtils.decode("T%C5%8Dky%C5%8D", CHARSET)); - assertEquals("Invalid encoded result", "/Z\u00fcrich", UriUtils.decode("/Z%C3%BCrich", CHARSET)); - assertEquals("Invalid encoded result", "T\u014dky\u014d", UriUtils.decode("T\u014dky\u014d", CHARSET)); + assertThat(UriUtils.decode("", CHARSET)).as("Invalid encoded URI").isEqualTo(""); + assertThat(UriUtils.decode("foobar", CHARSET)).as("Invalid encoded URI").isEqualTo("foobar"); + assertThat(UriUtils.decode("foo%20bar", CHARSET)).as("Invalid encoded URI").isEqualTo("foo bar"); + assertThat(UriUtils.decode("foo%2bbar", CHARSET)).as("Invalid encoded URI").isEqualTo("foo+bar"); + assertThat(UriUtils.decode("T%C5%8Dky%C5%8D", CHARSET)).as("Invalid encoded result").isEqualTo("T\u014dky\u014d"); + assertThat(UriUtils.decode("/Z%C3%BCrich", CHARSET)).as("Invalid encoded result").isEqualTo("/Z\u00fcrich"); + assertThat(UriUtils.decode("T\u014dky\u014d", CHARSET)).as("Invalid encoded result").isEqualTo("T\u014dky\u014d"); } @Test @@ -118,22 +117,22 @@ public class UriUtilsTests { @Test public void extractFileExtension() { - assertEquals("html", UriUtils.extractFileExtension("index.html")); - assertEquals("html", UriUtils.extractFileExtension("/index.html")); - assertEquals("html", UriUtils.extractFileExtension("/products/view.html")); - assertEquals("html", UriUtils.extractFileExtension("/products/view.html#/a")); - assertEquals("html", UriUtils.extractFileExtension("/products/view.html#/path/a")); - assertEquals("html", UriUtils.extractFileExtension("/products/view.html#/path/a.do")); - assertEquals("html", UriUtils.extractFileExtension("/products/view.html#aaa?bbb")); - assertEquals("html", UriUtils.extractFileExtension("/products/view.html#aaa.xml?bbb")); - assertEquals("html", UriUtils.extractFileExtension("/products/view.html?param=a")); - assertEquals("html", UriUtils.extractFileExtension("/products/view.html?param=/path/a")); - assertEquals("html", UriUtils.extractFileExtension("/products/view.html?param=/path/a.do")); - assertEquals("html", UriUtils.extractFileExtension("/products/view.html?param=/path/a#/path/a")); - assertEquals("html", UriUtils.extractFileExtension("/products/view.html?param=/path/a.do#/path/a.do")); - assertEquals("html", UriUtils.extractFileExtension("/products;q=11/view.html?param=/path/a.do")); - assertEquals("html", UriUtils.extractFileExtension("/products;q=11/view.html;r=22?param=/path/a.do")); - assertEquals("html", UriUtils.extractFileExtension("/products;q=11/view.html;r=22;s=33?param=/path/a.do")); + assertThat(UriUtils.extractFileExtension("index.html")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/index.html")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products/view.html")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products/view.html#/a")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products/view.html#/path/a")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products/view.html#/path/a.do")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products/view.html#aaa?bbb")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products/view.html#aaa.xml?bbb")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products/view.html?param=a")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products/view.html?param=/path/a")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products/view.html?param=/path/a.do")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products/view.html?param=/path/a#/path/a")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products/view.html?param=/path/a.do#/path/a.do")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products;q=11/view.html?param=/path/a.do")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products;q=11/view.html;r=22?param=/path/a.do")).isEqualTo("html"); + assertThat(UriUtils.extractFileExtension("/products;q=11/view.html;r=22;s=33?param=/path/a.do")).isEqualTo("html"); } } diff --git a/spring-web/src/test/java/org/springframework/web/util/UrlPathHelperTests.java b/spring-web/src/test/java/org/springframework/web/util/UrlPathHelperTests.java index 9309a65b7f8..0308ea0b6f9 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UrlPathHelperTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UrlPathHelperTests.java @@ -23,8 +23,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link UrlPathHelper}. @@ -47,7 +46,7 @@ public class UrlPathHelperTests { request.setContextPath("/petclinic"); request.setRequestURI("/petclinic/welcome.html"); - assertEquals("Incorrect path returned", "/welcome.html", helper.getPathWithinApplication(request)); + assertThat(helper.getPathWithinApplication(request)).as("Incorrect path returned").isEqualTo("/welcome.html"); } @Test @@ -55,7 +54,7 @@ public class UrlPathHelperTests { request.setContextPath("/petclinic"); request.setRequestURI("/petclinic"); - assertEquals("Incorrect root path returned", "/", helper.getPathWithinApplication(request)); + assertThat(helper.getPathWithinApplication(request)).as("Incorrect root path returned").isEqualTo("/"); } @Test @@ -63,7 +62,7 @@ public class UrlPathHelperTests { request.setContextPath("/"); request.setRequestURI("/welcome.html"); - assertEquals("Incorrect path returned", "/welcome.html", helper.getPathWithinApplication(request)); + assertThat(helper.getPathWithinApplication(request)).as("Incorrect path returned").isEqualTo("/welcome.html"); } @Test @@ -72,7 +71,7 @@ public class UrlPathHelperTests { request.setServletPath("/main"); request.setRequestURI("/petclinic/main/welcome.html"); - assertEquals("Incorrect path returned", "/welcome.html", helper.getPathWithinServletMapping(request)); + assertThat(helper.getPathWithinServletMapping(request)).as("Incorrect path returned").isEqualTo("/welcome.html"); } @Test @@ -82,7 +81,7 @@ public class UrlPathHelperTests { request.setServletPath("/main"); request.setRequestURI("/petclinic/main/welcome.html"); - assertEquals("Incorrect path returned", "/main/welcome.html", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).as("Incorrect path returned").isEqualTo("/main/welcome.html"); } // SPR-11101 @@ -96,19 +95,19 @@ public class UrlPathHelperTests { helper.setUrlDecode(false); String actual = helper.getPathWithinServletMapping(request); - assertEquals("/test_url_decoding/a%2Fb", actual); + assertThat(actual).isEqualTo("/test_url_decoding/a%2Fb"); } @Test public void getRequestUri() { request.setRequestURI("/welcome.html"); - assertEquals("Incorrect path returned", "/welcome.html", helper.getRequestUri(request)); + assertThat(helper.getRequestUri(request)).as("Incorrect path returned").isEqualTo("/welcome.html"); request.setRequestURI("/foo%20bar"); - assertEquals("Incorrect path returned", "/foo bar", helper.getRequestUri(request)); + assertThat(helper.getRequestUri(request)).as("Incorrect path returned").isEqualTo("/foo bar"); request.setRequestURI("/foo+bar"); - assertEquals("Incorrect path returned", "/foo+bar", helper.getRequestUri(request)); + assertThat(helper.getRequestUri(request)).as("Incorrect path returned").isEqualTo("/foo+bar"); } @Test @@ -116,14 +115,14 @@ public class UrlPathHelperTests { helper.setRemoveSemicolonContent(true); request.setRequestURI("/foo;f=F;o=O;o=O/bar;b=B;a=A;r=R"); - assertEquals("/foo/bar", helper.getRequestUri(request)); + assertThat(helper.getRequestUri(request)).isEqualTo("/foo/bar"); // SPR-13455 request.setServletPath("/foo/1"); request.setRequestURI("/foo/;test/1"); - assertEquals("/foo/1", helper.getRequestUri(request)); + assertThat(helper.getRequestUri(request)).isEqualTo("/foo/1"); } @Test @@ -131,18 +130,18 @@ public class UrlPathHelperTests { helper.setRemoveSemicolonContent(false); request.setRequestURI("/foo;a=b;c=d"); - assertEquals("/foo;a=b;c=d", helper.getRequestUri(request)); + assertThat(helper.getRequestUri(request)).isEqualTo("/foo;a=b;c=d"); request.setRequestURI("/foo;jsessionid=c0o7fszeb1"); - assertEquals("jsessionid should always be removed", "/foo", helper.getRequestUri(request)); + assertThat(helper.getRequestUri(request)).as("jsessionid should always be removed").isEqualTo("/foo"); request.setRequestURI("/foo;a=b;jsessionid=c0o7fszeb1;c=d"); - assertEquals("jsessionid should always be removed", "/foo;a=b;c=d", helper.getRequestUri(request)); + assertThat(helper.getRequestUri(request)).as("jsessionid should always be removed").isEqualTo("/foo;a=b;c=d"); // SPR-10398 request.setRequestURI("/foo;a=b;JSESSIONID=c0o7fszeb1;c=d"); - assertEquals("JSESSIONID should always be removed", "/foo;a=b;c=d", helper.getRequestUri(request)); + assertThat(helper.getRequestUri(request)).as("JSESSIONID should always be removed").isEqualTo("/foo;a=b;c=d"); } @Test @@ -153,7 +152,7 @@ public class UrlPathHelperTests { request.setServletPath("/main"); request.setRequestURI("/petclinic;a=b/main;b=c/welcome.html;c=d"); - assertEquals("/welcome.html;c=d", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/welcome.html;c=d"); } @Test @@ -164,7 +163,7 @@ public class UrlPathHelperTests { request.setServletPath("/welcome.html"); request.setRequestURI("/petclinic;a=b/welcome.html;c=d"); - assertEquals("/welcome.html;c=d", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/welcome.html;c=d"); } @@ -184,7 +183,7 @@ public class UrlPathHelperTests { request.setPathInfo(null); request.setServletPath("/"); request.setRequestURI("/test/"); - assertEquals("/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/"); } @Test @@ -194,7 +193,7 @@ public class UrlPathHelperTests { request.setServletPath("/foo"); request.setRequestURI("/test/foo"); - assertEquals("/foo", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo"); } @Test @@ -204,7 +203,7 @@ public class UrlPathHelperTests { request.setServletPath("/foo/"); request.setRequestURI("/test/foo/"); - assertEquals("/foo/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/"); } //SPR-12372 & SPR-13455 @@ -215,18 +214,18 @@ public class UrlPathHelperTests { request.setServletPath("/foo/bar/"); request.setRequestURI("/SPR-12372/foo//bar/"); - assertEquals("/foo/bar/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/bar/"); request.setServletPath("/foo/bar/"); request.setRequestURI("/SPR-12372/foo/bar//"); - assertEquals("/foo/bar/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/bar/"); // "normal" case request.setServletPath("/foo/bar//"); request.setRequestURI("/SPR-12372/foo/bar//"); - assertEquals("/foo/bar//", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/bar//"); } @Test @@ -237,7 +236,7 @@ public class UrlPathHelperTests { request.setRequestURI("/test/"); request.setAttribute(WEBSPHERE_URI_ATTRIBUTE, "/test/"); - assertEquals("/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/"); } @Test @@ -254,7 +253,7 @@ public class UrlPathHelperTests { request.setRequestURI("/test/foo"); request.setAttribute(WEBSPHERE_URI_ATTRIBUTE, "/test/foo"); - assertEquals("/foo", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo"); } @Test @@ -271,7 +270,7 @@ public class UrlPathHelperTests { request.setRequestURI("/test/foo/"); request.setAttribute(WEBSPHERE_URI_ATTRIBUTE, "/test/foo/"); - assertEquals("/foo/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/"); } @Test @@ -298,7 +297,7 @@ public class UrlPathHelperTests { request.setServletPath("/foo"); request.setRequestURI("/test/foo/"); - assertEquals("/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/"); } // test the root mapping for /foo/* w/o a trailing slash - //foo @@ -309,7 +308,7 @@ public class UrlPathHelperTests { request.setServletPath("/foo"); request.setRequestURI("/test/foo"); - assertEquals("/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/"); } @Test @@ -319,7 +318,7 @@ public class UrlPathHelperTests { request.setServletPath("/foo"); request.setRequestURI("/test/foo/foo"); - assertEquals("/foo", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo"); } @Test @@ -329,7 +328,7 @@ public class UrlPathHelperTests { request.setServletPath("/foo"); request.setRequestURI("/test/foo/foo/"); - assertEquals("/foo/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/"); } @Test @@ -340,7 +339,7 @@ public class UrlPathHelperTests { request.setRequestURI("/test/foo/"); request.setAttribute(WEBSPHERE_URI_ATTRIBUTE, "/test/foo/"); - assertEquals("/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/"); } @Test @@ -359,7 +358,7 @@ public class UrlPathHelperTests { request.setRequestURI("/test/foo"); request.setAttribute(WEBSPHERE_URI_ATTRIBUTE, "/test/foo"); - assertEquals("/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/"); } @Ignore @@ -377,7 +376,7 @@ public class UrlPathHelperTests { request.setRequestURI("/test/foo/foo"); request.setAttribute(WEBSPHERE_URI_ATTRIBUTE, "/test/foo/foo"); - assertEquals("/foo", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo"); } @Test @@ -394,7 +393,7 @@ public class UrlPathHelperTests { request.setRequestURI("/test/foo/foo/"); request.setAttribute(WEBSPHERE_URI_ATTRIBUTE, "/test/foo/foo/"); - assertEquals("/foo/", helper.getLookupPathForRequest(request)); + assertThat(helper.getLookupPathForRequest(request)).isEqualTo("/foo/"); } @Test @@ -407,20 +406,20 @@ public class UrlPathHelperTests { public void getOriginatingRequestUri() { request.setAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE, "/path"); request.setRequestURI("/forwarded"); - assertEquals("/path", helper.getOriginatingRequestUri(request)); + assertThat(helper.getOriginatingRequestUri(request)).isEqualTo("/path"); } @Test public void getOriginatingRequestUriWebsphere() { request.setAttribute(WEBSPHERE_URI_ATTRIBUTE, "/path"); request.setRequestURI("/forwarded"); - assertEquals("/path", helper.getOriginatingRequestUri(request)); + assertThat(helper.getOriginatingRequestUri(request)).isEqualTo("/path"); } @Test public void getOriginatingRequestUriDefault() { request.setRequestURI("/forwarded"); - assertEquals("/forwarded", helper.getOriginatingRequestUri(request)); + assertThat(helper.getOriginatingRequestUri(request)).isEqualTo("/forwarded"); } @Test @@ -428,20 +427,20 @@ public class UrlPathHelperTests { request.setQueryString("forward=on"); request.setAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE, "/path"); request.setAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE, "original=on"); - assertEquals("original=on", this.helper.getOriginatingQueryString(request)); + assertThat(this.helper.getOriginatingQueryString(request)).isEqualTo("original=on"); } @Test public void getOriginatingQueryStringNotPresent() { request.setQueryString("forward=true"); - assertEquals("forward=true", this.helper.getOriginatingQueryString(request)); + assertThat(this.helper.getOriginatingQueryString(request)).isEqualTo("forward=true"); } @Test public void getOriginatingQueryStringIsNull() { request.setQueryString("forward=true"); request.setAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE, "/path"); - assertNull(this.helper.getOriginatingQueryString(request)); + assertThat(this.helper.getOriginatingQueryString(request)).isNull(); } } diff --git a/spring-web/src/test/java/org/springframework/web/util/WebUtilsTests.java b/spring-web/src/test/java/org/springframework/web/util/WebUtilsTests.java index 30f34117cd3..ebc09086d18 100644 --- a/spring-web/src/test/java/org/springframework/web/util/WebUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/WebUtilsTests.java @@ -34,10 +34,7 @@ import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.util.MultiValueMap; import org.springframework.web.filter.ForwardedHeaderFilter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -55,11 +52,11 @@ public class WebUtilsTests { params.put("myKey3_myValue3.x", "xxx"); params.put("myKey4_myValue4.y", new String[] {"yyy"}); - assertNull(WebUtils.findParameterValue(params, "myKey0")); - assertEquals("myValue1", WebUtils.findParameterValue(params, "myKey1")); - assertEquals("myValue2", WebUtils.findParameterValue(params, "myKey2")); - assertEquals("myValue3", WebUtils.findParameterValue(params, "myKey3")); - assertEquals("myValue4", WebUtils.findParameterValue(params, "myKey4")); + assertThat(WebUtils.findParameterValue(params, "myKey0")).isNull(); + assertThat(WebUtils.findParameterValue(params, "myKey1")).isEqualTo("myValue1"); + assertThat(WebUtils.findParameterValue(params, "myKey2")).isEqualTo("myValue2"); + assertThat(WebUtils.findParameterValue(params, "myKey3")).isEqualTo("myValue3"); + assertThat(WebUtils.findParameterValue(params, "myKey4")).isEqualTo("myValue4"); } @Test @@ -67,82 +64,82 @@ public class WebUtilsTests { MultiValueMap variables; variables = WebUtils.parseMatrixVariables(null); - assertEquals(0, variables.size()); + assertThat(variables.size()).isEqualTo(0); variables = WebUtils.parseMatrixVariables("year"); - assertEquals(1, variables.size()); - assertEquals("", variables.getFirst("year")); + assertThat(variables.size()).isEqualTo(1); + assertThat(variables.getFirst("year")).isEqualTo(""); variables = WebUtils.parseMatrixVariables("year=2012"); - assertEquals(1, variables.size()); - assertEquals("2012", variables.getFirst("year")); + assertThat(variables.size()).isEqualTo(1); + assertThat(variables.getFirst("year")).isEqualTo("2012"); variables = WebUtils.parseMatrixVariables("year=2012;colors=red,blue,green"); - assertEquals(2, variables.size()); - assertEquals(Arrays.asList("red", "blue", "green"), variables.get("colors")); - assertEquals("2012", variables.getFirst("year")); + assertThat(variables.size()).isEqualTo(2); + assertThat(variables.get("colors")).isEqualTo(Arrays.asList("red", "blue", "green")); + assertThat(variables.getFirst("year")).isEqualTo("2012"); variables = WebUtils.parseMatrixVariables(";year=2012;colors=red,blue,green;"); - assertEquals(2, variables.size()); - assertEquals(Arrays.asList("red", "blue", "green"), variables.get("colors")); - assertEquals("2012", variables.getFirst("year")); + assertThat(variables.size()).isEqualTo(2); + assertThat(variables.get("colors")).isEqualTo(Arrays.asList("red", "blue", "green")); + assertThat(variables.getFirst("year")).isEqualTo("2012"); variables = WebUtils.parseMatrixVariables("colors=red;colors=blue;colors=green"); - assertEquals(1, variables.size()); - assertEquals(Arrays.asList("red", "blue", "green"), variables.get("colors")); + assertThat(variables.size()).isEqualTo(1); + assertThat(variables.get("colors")).isEqualTo(Arrays.asList("red", "blue", "green")); } @Test public void isValidOrigin() { List allowed = Collections.emptyList(); - assertTrue(checkValidOrigin("mydomain1.com", -1, "http://mydomain1.com", allowed)); - assertFalse(checkValidOrigin("mydomain1.com", -1, "http://mydomain2.com", allowed)); + assertThat(checkValidOrigin("mydomain1.com", -1, "http://mydomain1.com", allowed)).isTrue(); + assertThat(checkValidOrigin("mydomain1.com", -1, "http://mydomain2.com", allowed)).isFalse(); allowed = Collections.singletonList("*"); - assertTrue(checkValidOrigin("mydomain1.com", -1, "http://mydomain2.com", allowed)); + assertThat(checkValidOrigin("mydomain1.com", -1, "http://mydomain2.com", allowed)).isTrue(); allowed = Collections.singletonList("http://mydomain1.com"); - assertTrue(checkValidOrigin("mydomain2.com", -1, "http://mydomain1.com", allowed)); - assertFalse(checkValidOrigin("mydomain2.com", -1, "http://mydomain3.com", allowed)); + assertThat(checkValidOrigin("mydomain2.com", -1, "http://mydomain1.com", allowed)).isTrue(); + assertThat(checkValidOrigin("mydomain2.com", -1, "http://mydomain3.com", allowed)).isFalse(); } @Test public void isSameOrigin() { - assertTrue(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com")); - assertTrue(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com:80")); - assertTrue(checkSameOrigin("https", "mydomain1.com", 443, "https://mydomain1.com")); - assertTrue(checkSameOrigin("https", "mydomain1.com", 443, "https://mydomain1.com:443")); - assertTrue(checkSameOrigin("http", "mydomain1.com", 123, "http://mydomain1.com:123")); - assertTrue(checkSameOrigin("ws", "mydomain1.com", -1, "ws://mydomain1.com")); - assertTrue(checkSameOrigin("wss", "mydomain1.com", 443, "wss://mydomain1.com")); + assertThat(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com")).isTrue(); + assertThat(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com:80")).isTrue(); + assertThat(checkSameOrigin("https", "mydomain1.com", 443, "https://mydomain1.com")).isTrue(); + assertThat(checkSameOrigin("https", "mydomain1.com", 443, "https://mydomain1.com:443")).isTrue(); + assertThat(checkSameOrigin("http", "mydomain1.com", 123, "http://mydomain1.com:123")).isTrue(); + assertThat(checkSameOrigin("ws", "mydomain1.com", -1, "ws://mydomain1.com")).isTrue(); + assertThat(checkSameOrigin("wss", "mydomain1.com", 443, "wss://mydomain1.com")).isTrue(); - assertFalse(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain2.com")); - assertFalse(checkSameOrigin("http", "mydomain1.com", -1, "https://mydomain1.com")); - assertFalse(checkSameOrigin("http", "mydomain1.com", -1, "invalid-origin")); - assertFalse(checkSameOrigin("https", "mydomain1.com", -1, "http://mydomain1.com")); + assertThat(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain2.com")).isFalse(); + assertThat(checkSameOrigin("http", "mydomain1.com", -1, "https://mydomain1.com")).isFalse(); + assertThat(checkSameOrigin("http", "mydomain1.com", -1, "invalid-origin")).isFalse(); + assertThat(checkSameOrigin("https", "mydomain1.com", -1, "http://mydomain1.com")).isFalse(); // Handling of invalid origins as described in SPR-13478 - assertTrue(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com/")); - assertTrue(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com:80/")); - assertTrue(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com/path")); - assertTrue(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com:80/path")); - assertFalse(checkSameOrigin("http", "mydomain2.com", -1, "http://mydomain1.com/")); - assertFalse(checkSameOrigin("http", "mydomain2.com", -1, "http://mydomain1.com:80/")); - assertFalse(checkSameOrigin("http", "mydomain2.com", -1, "http://mydomain1.com/path")); - assertFalse(checkSameOrigin("http", "mydomain2.com", -1, "http://mydomain1.com:80/path")); + assertThat(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com/")).isTrue(); + assertThat(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com:80/")).isTrue(); + assertThat(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com/path")).isTrue(); + assertThat(checkSameOrigin("http", "mydomain1.com", -1, "http://mydomain1.com:80/path")).isTrue(); + assertThat(checkSameOrigin("http", "mydomain2.com", -1, "http://mydomain1.com/")).isFalse(); + assertThat(checkSameOrigin("http", "mydomain2.com", -1, "http://mydomain1.com:80/")).isFalse(); + assertThat(checkSameOrigin("http", "mydomain2.com", -1, "http://mydomain1.com/path")).isFalse(); + assertThat(checkSameOrigin("http", "mydomain2.com", -1, "http://mydomain1.com:80/path")).isFalse(); // Handling of IPv6 hosts as described in SPR-13525 - assertTrue(checkSameOrigin("http", "[::1]", -1, "http://[::1]")); - assertTrue(checkSameOrigin("http", "[::1]", 8080, "http://[::1]:8080")); - assertTrue(checkSameOrigin("http", + assertThat(checkSameOrigin("http", "[::1]", -1, "http://[::1]")).isTrue(); + assertThat(checkSameOrigin("http", "[::1]", 8080, "http://[::1]:8080")).isTrue(); + assertThat(checkSameOrigin("http", "[2001:0db8:0000:85a3:0000:0000:ac1f:8001]", -1, - "http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]")); - assertTrue(checkSameOrigin("http", + "http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]")).isTrue(); + assertThat(checkSameOrigin("http", "[2001:0db8:0000:85a3:0000:0000:ac1f:8001]", 8080, - "http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]:8080")); - assertFalse(checkSameOrigin("http", "[::1]", -1, "http://[::1]:8080")); - assertFalse(checkSameOrigin("http", "[::1]", 8080, - "http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]:8080")); + "http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]:8080")).isTrue(); + assertThat(checkSameOrigin("http", "[::1]", -1, "http://[::1]:8080")).isFalse(); + assertThat(checkSameOrigin("http", "[::1]", 8080, + "http://[2001:0db8:0000:85a3:0000:0000:ac1f:8001]:8080")).isFalse(); } @Test // SPR-16262 @@ -213,7 +210,7 @@ public class WebUtilsTests { HttpServletRequest requestToUse = adaptFromForwardedHeaders(request); ServerHttpRequest httpRequest = new ServletServerHttpRequest(requestToUse); - assertTrue(WebUtils.isSameOrigin(httpRequest)); + assertThat(WebUtils.isSameOrigin(httpRequest)).isTrue(); } private void testWithForwardedHeader(String serverName, int port, String forwardedHeader, @@ -230,7 +227,7 @@ public class WebUtilsTests { HttpServletRequest requestToUse = adaptFromForwardedHeaders(request); ServerHttpRequest httpRequest = new ServletServerHttpRequest(requestToUse); - assertTrue(WebUtils.isSameOrigin(httpRequest)); + assertThat(WebUtils.isSameOrigin(httpRequest)).isTrue(); } // SPR-16668 diff --git a/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternParserTests.java b/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternParserTests.java index cf4f2e53266..a3256b2e610 100644 --- a/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternParserTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternParserTests.java @@ -28,11 +28,7 @@ import org.springframework.web.util.pattern.PatternParseException.PatternMessage import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; /** * Exercise the {@link PathPatternParser}. @@ -71,20 +67,20 @@ public class PathPatternParserTests { @Test public void toStringTests() { - assertEquals("CaptureTheRest(/{*foobar})", checkStructure("/{*foobar}").toChainString()); - assertEquals("CaptureVariable({foobar})", checkStructure("{foobar}").toChainString()); - assertEquals("Literal(abc)", checkStructure("abc").toChainString()); - assertEquals("Regex({a}_*_{b})", checkStructure("{a}_*_{b}").toChainString()); - assertEquals("Separator(/)", checkStructure("/").toChainString()); - assertEquals("SingleCharWildcarded(?a?b?c)", checkStructure("?a?b?c").toChainString()); - assertEquals("Wildcard(*)", checkStructure("*").toChainString()); - assertEquals("WildcardTheRest(/**)", checkStructure("/**").toChainString()); + assertThat(checkStructure("/{*foobar}").toChainString()).isEqualTo("CaptureTheRest(/{*foobar})"); + assertThat(checkStructure("{foobar}").toChainString()).isEqualTo("CaptureVariable({foobar})"); + assertThat(checkStructure("abc").toChainString()).isEqualTo("Literal(abc)"); + assertThat(checkStructure("{a}_*_{b}").toChainString()).isEqualTo("Regex({a}_*_{b})"); + assertThat(checkStructure("/").toChainString()).isEqualTo("Separator(/)"); + assertThat(checkStructure("?a?b?c").toChainString()).isEqualTo("SingleCharWildcarded(?a?b?c)"); + assertThat(checkStructure("*").toChainString()).isEqualTo("Wildcard(*)"); + assertThat(checkStructure("/**").toChainString()).isEqualTo("WildcardTheRest(/**)"); } @Test public void captureTheRestPatterns() { pathPattern = parse("{*foobar}"); - assertEquals("/{*foobar}", pathPattern.computePatternString()); + assertThat(pathPattern.computePatternString()).isEqualTo("/{*foobar}"); assertPathElements(pathPattern, CaptureTheRestPathElement.class); pathPattern = checkStructure("/{*foobar}"); assertPathElements(pathPattern, CaptureTheRestPathElement.class); @@ -107,15 +103,15 @@ public class PathPatternParserTests { PathPattern pp1 = caseInsensitiveParser.parse("/abc"); PathPattern pp2 = caseInsensitiveParser.parse("/abc"); PathPattern pp3 = caseInsensitiveParser.parse("/def"); - assertEquals(pp1, pp2); - assertEquals(pp1.hashCode(), pp2.hashCode()); - assertNotEquals(pp1, pp3); - assertFalse(pp1.equals("abc")); + assertThat(pp2).isEqualTo(pp1); + assertThat(pp2.hashCode()).isEqualTo(pp1.hashCode()); + assertThat(pp3).isNotEqualTo(pp1); + assertThat(pp1.equals("abc")).isFalse(); pp1 = caseInsensitiveParser.parse("/abc"); pp2 = caseSensitiveParser.parse("/abc"); - assertFalse(pp1.equals(pp2)); - assertNotEquals(pp1.hashCode(), pp2.hashCode()); + assertThat(pp1.equals(pp2)).isFalse(); + assertThat(pp2.hashCode()).isNotEqualTo((long) pp1.hashCode()); } @Test @@ -126,65 +122,65 @@ public class PathPatternParserTests { pathPattern = checkStructure("/{var:\\\\}"); PathElement next = pathPattern.getHeadSection().next; - assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName()); + assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); assertMatches(pathPattern,"/\\"); pathPattern = checkStructure("/{var:\\/}"); next = pathPattern.getHeadSection().next; - assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName()); + assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); assertNoMatch(pathPattern,"/aaa"); pathPattern = checkStructure("/{var:a{1,2}}"); next = pathPattern.getHeadSection().next; - assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName()); + assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); pathPattern = checkStructure("/{var:[^\\/]*}"); next = pathPattern.getHeadSection().next; - assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName()); + assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); PathPattern.PathMatchInfo result = matchAndExtract(pathPattern,"/foo"); - assertEquals("foo", result.getUriVariables().get("var")); + assertThat(result.getUriVariables().get("var")).isEqualTo("foo"); pathPattern = checkStructure("/{var:\\[*}"); next = pathPattern.getHeadSection().next; - assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName()); + assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); result = matchAndExtract(pathPattern,"/[[["); - assertEquals("[[[", result.getUriVariables().get("var")); + assertThat(result.getUriVariables().get("var")).isEqualTo("[[["); pathPattern = checkStructure("/{var:[\\{]*}"); next = pathPattern.getHeadSection().next; - assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName()); + assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); result = matchAndExtract(pathPattern,"/{{{"); - assertEquals("{{{", result.getUriVariables().get("var")); + assertThat(result.getUriVariables().get("var")).isEqualTo("{{{"); pathPattern = checkStructure("/{var:[\\}]*}"); next = pathPattern.getHeadSection().next; - assertEquals(CaptureVariablePathElement.class.getName(), next.getClass().getName()); + assertThat(next.getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); result = matchAndExtract(pathPattern,"/}}}"); - assertEquals("}}}", result.getUriVariables().get("var")); + assertThat(result.getUriVariables().get("var")).isEqualTo("}}}"); pathPattern = checkStructure("*"); - assertEquals(WildcardPathElement.class.getName(), pathPattern.getHeadSection().getClass().getName()); + assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(WildcardPathElement.class.getName()); checkStructure("/*"); checkStructure("/*/"); checkStructure("*/"); checkStructure("/*/"); pathPattern = checkStructure("/*a*/"); next = pathPattern.getHeadSection().next; - assertEquals(RegexPathElement.class.getName(), next.getClass().getName()); + assertThat(next.getClass().getName()).isEqualTo(RegexPathElement.class.getName()); pathPattern = checkStructure("*/"); - assertEquals(WildcardPathElement.class.getName(), pathPattern.getHeadSection().getClass().getName()); + assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(WildcardPathElement.class.getName()); checkError("{foo}_{foo}", 0, PatternMessage.ILLEGAL_DOUBLE_CAPTURE, "foo"); checkError("/{bar}/{bar}", 7, PatternMessage.ILLEGAL_DOUBLE_CAPTURE, "bar"); checkError("/{bar}/{bar}_{foo}", 7, PatternMessage.ILLEGAL_DOUBLE_CAPTURE, "bar"); pathPattern = checkStructure("{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.]+}.jar"); - assertEquals(RegexPathElement.class.getName(), pathPattern.getHeadSection().getClass().getName()); + assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(RegexPathElement.class.getName()); } @Test public void completeCapturingPatterns() { pathPattern = checkStructure("{foo}"); - assertEquals(CaptureVariablePathElement.class.getName(), pathPattern.getHeadSection().getClass().getName()); + assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(CaptureVariablePathElement.class.getName()); checkStructure("/{foo}"); checkStructure("/{f}/"); checkStructure("/{foo}/{bar}/{wibble}"); @@ -194,13 +190,13 @@ public class PathPatternParserTests { public void noEncoding() { // Check no encoding of expressions or constraints PathPattern pp = parse("/{var:f o}"); - assertEquals("Separator(/) CaptureVariable({var:f o})",pp.toChainString()); + assertThat(pp.toChainString()).isEqualTo("Separator(/) CaptureVariable({var:f o})"); pp = parse("/{var:f o}_"); - assertEquals("Separator(/) Regex({var:f o}_)",pp.toChainString()); + assertThat(pp.toChainString()).isEqualTo("Separator(/) Regex({var:f o}_)"); pp = parse("{foo:f o}_ _{bar:b\\|o}"); - assertEquals("Regex({foo:f o}_ _{bar:b\\|o})",pp.toChainString()); + assertThat(pp.toChainString()).isEqualTo("Regex({foo:f o}_ _{bar:b\\|o})"); } @Test @@ -215,7 +211,7 @@ public class PathPatternParserTests { @Test public void partialCapturingPatterns() { pathPattern = checkStructure("{foo}abc"); - assertEquals(RegexPathElement.class.getName(), pathPattern.getHeadSection().getClass().getName()); + assertThat(pathPattern.getHeadSection().getClass().getName()).isEqualTo(RegexPathElement.class.getName()); checkStructure("abc{foo}"); checkStructure("/abc{foo}"); checkStructure("{foo}def/"); @@ -266,61 +262,62 @@ public class PathPatternParserTests { @Test public void patternPropertyGetCaptureCountTests() { // Test all basic section types - assertEquals(1, parse("{foo}").getCapturedVariableCount()); - assertEquals(0, parse("foo").getCapturedVariableCount()); - assertEquals(1, parse("{*foobar}").getCapturedVariableCount()); - assertEquals(1, parse("/{*foobar}").getCapturedVariableCount()); - assertEquals(0, parse("/**").getCapturedVariableCount()); - assertEquals(1, parse("{abc}asdf").getCapturedVariableCount()); - assertEquals(1, parse("{abc}_*").getCapturedVariableCount()); - assertEquals(2, parse("{abc}_{def}").getCapturedVariableCount()); - assertEquals(0, parse("/").getCapturedVariableCount()); - assertEquals(0, parse("a?b").getCapturedVariableCount()); - assertEquals(0, parse("*").getCapturedVariableCount()); + assertThat(parse("{foo}").getCapturedVariableCount()).isEqualTo(1); + assertThat(parse("foo").getCapturedVariableCount()).isEqualTo(0); + assertThat(parse("{*foobar}").getCapturedVariableCount()).isEqualTo(1); + assertThat(parse("/{*foobar}").getCapturedVariableCount()).isEqualTo(1); + assertThat(parse("/**").getCapturedVariableCount()).isEqualTo(0); + assertThat(parse("{abc}asdf").getCapturedVariableCount()).isEqualTo(1); + assertThat(parse("{abc}_*").getCapturedVariableCount()).isEqualTo(1); + assertThat(parse("{abc}_{def}").getCapturedVariableCount()).isEqualTo(2); + assertThat(parse("/").getCapturedVariableCount()).isEqualTo(0); + assertThat(parse("a?b").getCapturedVariableCount()).isEqualTo(0); + assertThat(parse("*").getCapturedVariableCount()).isEqualTo(0); // Test on full templates - assertEquals(0, parse("/foo/bar").getCapturedVariableCount()); - assertEquals(1, parse("/{foo}").getCapturedVariableCount()); - assertEquals(2, parse("/{foo}/{bar}").getCapturedVariableCount()); - assertEquals(4, parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getCapturedVariableCount()); + assertThat(parse("/foo/bar").getCapturedVariableCount()).isEqualTo(0); + assertThat(parse("/{foo}").getCapturedVariableCount()).isEqualTo(1); + assertThat(parse("/{foo}/{bar}").getCapturedVariableCount()).isEqualTo(2); + assertThat(parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getCapturedVariableCount()).isEqualTo(4); } @Test public void patternPropertyGetWildcardCountTests() { // Test all basic section types - assertEquals(computeScore(1, 0), parse("{foo}").getScore()); - assertEquals(computeScore(0, 0), parse("foo").getScore()); - assertEquals(computeScore(0, 0), parse("{*foobar}").getScore()); -// assertEquals(1,parse("/**").getScore()); - assertEquals(computeScore(1, 0), parse("{abc}asdf").getScore()); - assertEquals(computeScore(1, 1), parse("{abc}_*").getScore()); - assertEquals(computeScore(2, 0), parse("{abc}_{def}").getScore()); - assertEquals(computeScore(0, 0), parse("/").getScore()); - assertEquals(computeScore(0, 0), parse("a?b").getScore()); // currently deliberate - assertEquals(computeScore(0, 1), parse("*").getScore()); + assertThat(parse("{foo}").getScore()).isEqualTo(computeScore(1, 0)); + assertThat(parse("foo").getScore()).isEqualTo(computeScore(0, 0)); + assertThat(parse("{*foobar}").getScore()).isEqualTo(computeScore(0, 0)); + // assertEquals(1,parse("/**").getScore()); + assertThat(parse("{abc}asdf").getScore()).isEqualTo(computeScore(1, 0)); + assertThat(parse("{abc}_*").getScore()).isEqualTo(computeScore(1, 1)); + assertThat(parse("{abc}_{def}").getScore()).isEqualTo(computeScore(2, 0)); + assertThat(parse("/").getScore()).isEqualTo(computeScore(0, 0)); + // currently deliberate + assertThat(parse("a?b").getScore()).isEqualTo(computeScore(0, 0)); + assertThat(parse("*").getScore()).isEqualTo(computeScore(0, 1)); // Test on full templates - assertEquals(computeScore(0, 0), parse("/foo/bar").getScore()); - assertEquals(computeScore(1, 0), parse("/{foo}").getScore()); - assertEquals(computeScore(2, 0), parse("/{foo}/{bar}").getScore()); - assertEquals(computeScore(4, 0), parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getScore()); - assertEquals(computeScore(4, 3), parse("/{foo}/*/*_*/{bar}_{goo}_{wibble}/abc/bar").getScore()); + assertThat(parse("/foo/bar").getScore()).isEqualTo(computeScore(0, 0)); + assertThat(parse("/{foo}").getScore()).isEqualTo(computeScore(1, 0)); + assertThat(parse("/{foo}/{bar}").getScore()).isEqualTo(computeScore(2, 0)); + assertThat(parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getScore()).isEqualTo(computeScore(4, 0)); + assertThat(parse("/{foo}/*/*_*/{bar}_{goo}_{wibble}/abc/bar").getScore()).isEqualTo(computeScore(4, 3)); } @Test public void multipleSeparatorPatterns() { pathPattern = checkStructure("///aaa"); - assertEquals(6, pathPattern.getNormalizedLength()); + assertThat(pathPattern.getNormalizedLength()).isEqualTo(6); assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, LiteralPathElement.class); pathPattern = checkStructure("///aaa////aaa/b"); - assertEquals(15, pathPattern.getNormalizedLength()); + assertThat(pathPattern.getNormalizedLength()).isEqualTo(15); assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, LiteralPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, LiteralPathElement.class, SeparatorPathElement.class, LiteralPathElement.class); pathPattern = checkStructure("/////**"); - assertEquals(5, pathPattern.getNormalizedLength()); + assertThat(pathPattern.getNormalizedLength()).isEqualTo(5); assertPathElements(pathPattern, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, SeparatorPathElement.class, WildcardTheRestPathElement.class); } @@ -328,23 +325,23 @@ public class PathPatternParserTests { @Test public void patternPropertyGetLengthTests() { // Test all basic section types - assertEquals(1, parse("{foo}").getNormalizedLength()); - assertEquals(3, parse("foo").getNormalizedLength()); - assertEquals(1, parse("{*foobar}").getNormalizedLength()); - assertEquals(1, parse("/{*foobar}").getNormalizedLength()); - assertEquals(1, parse("/**").getNormalizedLength()); - assertEquals(5, parse("{abc}asdf").getNormalizedLength()); - assertEquals(3, parse("{abc}_*").getNormalizedLength()); - assertEquals(3, parse("{abc}_{def}").getNormalizedLength()); - assertEquals(1, parse("/").getNormalizedLength()); - assertEquals(3, parse("a?b").getNormalizedLength()); - assertEquals(1, parse("*").getNormalizedLength()); + assertThat(parse("{foo}").getNormalizedLength()).isEqualTo(1); + assertThat(parse("foo").getNormalizedLength()).isEqualTo(3); + assertThat(parse("{*foobar}").getNormalizedLength()).isEqualTo(1); + assertThat(parse("/{*foobar}").getNormalizedLength()).isEqualTo(1); + assertThat(parse("/**").getNormalizedLength()).isEqualTo(1); + assertThat(parse("{abc}asdf").getNormalizedLength()).isEqualTo(5); + assertThat(parse("{abc}_*").getNormalizedLength()).isEqualTo(3); + assertThat(parse("{abc}_{def}").getNormalizedLength()).isEqualTo(3); + assertThat(parse("/").getNormalizedLength()).isEqualTo(1); + assertThat(parse("a?b").getNormalizedLength()).isEqualTo(3); + assertThat(parse("*").getNormalizedLength()).isEqualTo(1); // Test on full templates - assertEquals(8, parse("/foo/bar").getNormalizedLength()); - assertEquals(2, parse("/{foo}").getNormalizedLength()); - assertEquals(4, parse("/{foo}/{bar}").getNormalizedLength()); - assertEquals(16, parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getNormalizedLength()); + assertThat(parse("/foo/bar").getNormalizedLength()).isEqualTo(8); + assertThat(parse("/{foo}").getNormalizedLength()).isEqualTo(2); + assertThat(parse("/{foo}/{bar}").getNormalizedLength()).isEqualTo(4); + assertThat(parse("/{foo}/{bar}_{goo}_{wibble}/abc/bar").getNormalizedLength()).isEqualTo(16); } @Test @@ -355,59 +352,60 @@ public class PathPatternParserTests { p1 = parse("{a}"); p2 = parse("{a}/{b}"); p3 = parse("{a}/{b}/{c}"); - assertEquals(-1, p1.compareTo(p2)); // Based on number of captures + // Based on number of captures + assertThat(p1.compareTo(p2)).isEqualTo(-1); List patterns = new ArrayList<>(); patterns.add(p2); patterns.add(p3); patterns.add(p1); Collections.sort(patterns); - assertEquals(p1, patterns.get(0)); + assertThat(patterns.get(0)).isEqualTo(p1); // Based purely on length p1 = parse("/a/b/c"); p2 = parse("/a/boo/c/doo"); p3 = parse("/asdjflaksjdfjasdf"); - assertEquals(1, p1.compareTo(p2)); + assertThat(p1.compareTo(p2)).isEqualTo(1); patterns = new ArrayList<>(); patterns.add(p2); patterns.add(p3); patterns.add(p1); Collections.sort(patterns); - assertEquals(p3, patterns.get(0)); + assertThat(patterns.get(0)).isEqualTo(p3); // Based purely on 'wildness' p1 = parse("/*"); p2 = parse("/*/*"); p3 = parse("/*/*/*_*"); - assertEquals(-1, p1.compareTo(p2)); + assertThat(p1.compareTo(p2)).isEqualTo(-1); patterns = new ArrayList<>(); patterns.add(p2); patterns.add(p3); patterns.add(p1); Collections.sort(patterns); - assertEquals(p1, patterns.get(0)); + assertThat(patterns.get(0)).isEqualTo(p1); // Based purely on catchAll p1 = parse("{*foobar}"); p2 = parse("{*goo}"); - assertTrue(p1.compareTo(p2) != 0); + assertThat(p1.compareTo(p2) != 0).isTrue(); p1 = parse("/{*foobar}"); p2 = parse("/abc/{*ww}"); - assertEquals(+1, p1.compareTo(p2)); - assertEquals(-1, p2.compareTo(p1)); + assertThat(p1.compareTo(p2)).isEqualTo(+1); + assertThat(p2.compareTo(p1)).isEqualTo(-1); p3 = parse("/this/that/theother"); - assertTrue(p1.isCatchAll()); - assertTrue(p2.isCatchAll()); - assertFalse(p3.isCatchAll()); + assertThat(p1.isCatchAll()).isTrue(); + assertThat(p2.isCatchAll()).isTrue(); + assertThat(p3.isCatchAll()).isFalse(); patterns = new ArrayList<>(); patterns.add(p2); patterns.add(p3); patterns.add(p1); Collections.sort(patterns); - assertEquals(p3, patterns.get(0)); - assertEquals(p2, patterns.get(1)); + assertThat(patterns.get(0)).isEqualTo(p3); + assertThat(patterns.get(1)).isEqualTo(p2); } private PathPattern parse(String pattern) { @@ -420,7 +418,7 @@ public class PathPatternParserTests { */ private PathPattern checkStructure(String pattern) { PathPattern pp = parse(pattern); - assertEquals(pattern, pp.computePatternString()); + assertThat(pp.computePatternString()).isEqualTo(pattern); return pp; } @@ -430,8 +428,8 @@ public class PathPatternParserTests { assertThatExceptionOfType(PatternParseException.class).isThrownBy(() -> pathPattern = parse(pattern)) .satisfies(ex -> { - assertEquals(ex.toDetailedString(), expectedPos, ex.getPosition()); - assertEquals(ex.toDetailedString(), expectedMessage, ex.getMessageType()); + assertThat(ex.getPosition()).as(ex.toDetailedString()).isEqualTo(expectedPos); + assertThat(ex.getMessageType()).as(ex.toDetailedString()).isEqualTo(expectedMessage); if (expectedInserts.length != 0) { assertThat(ex.getInserts()).isEqualTo(expectedInserts); } @@ -445,8 +443,7 @@ public class PathPatternParserTests { if (head == null) { fail("Ran out of data in parsed pattern. Pattern is: " + p.toChainString()); } - assertEquals("Not expected section type. Pattern is: " + p.toChainString(), - sectionClass.getSimpleName(), head.getClass().getSimpleName()); + assertThat(head.getClass().getSimpleName()).as("Not expected section type. Pattern is: " + p.toChainString()).isEqualTo(sectionClass.getSimpleName()); head = head.next; } } @@ -457,11 +454,11 @@ public class PathPatternParserTests { } private void assertMatches(PathPattern pp, String path) { - assertTrue(pp.matches(PathPatternTests.toPathContainer(path))); + assertThat(pp.matches(PathPatternTests.toPathContainer(path))).isTrue(); } private void assertNoMatch(PathPattern pp, String path) { - assertFalse(pp.matches(PathPatternTests.toPathContainer(path))); + assertThat(pp.matches(PathPatternTests.toPathContainer(path))).isFalse(); } private PathPattern.PathMatchInfo matchAndExtract(PathPattern pp, String path) { diff --git a/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternTests.java b/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternTests.java index 42843dbfc93..2337f01be7a 100644 --- a/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternTests.java @@ -32,11 +32,6 @@ import org.springframework.web.util.pattern.PathPattern.PathRemainingMatchInfo; import static org.assertj.core.api.Assertions.assertThat; 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; -import static org.junit.Assert.assertTrue; /** * Exercise matching of {@link PathPattern} objects. @@ -47,22 +42,22 @@ public class PathPatternTests { @Test public void pathContainer() { - assertEquals("[/][abc][/][def]",elementsToString(toPathContainer("/abc/def").elements())); - assertEquals("[abc][/][def]",elementsToString(toPathContainer("abc/def").elements())); - assertEquals("[abc][/][def][/]",elementsToString(toPathContainer("abc/def/").elements())); - assertEquals("[abc][/][/][def][/][/]",elementsToString(toPathContainer("abc//def//").elements())); - assertEquals("[/]",elementsToString(toPathContainer("/").elements())); - assertEquals("[/][/][/]",elementsToString(toPathContainer("///").elements())); + assertThat(elementsToString(toPathContainer("/abc/def").elements())).isEqualTo("[/][abc][/][def]"); + assertThat(elementsToString(toPathContainer("abc/def").elements())).isEqualTo("[abc][/][def]"); + assertThat(elementsToString(toPathContainer("abc/def/").elements())).isEqualTo("[abc][/][def][/]"); + assertThat(elementsToString(toPathContainer("abc//def//").elements())).isEqualTo("[abc][/][/][def][/][/]"); + assertThat(elementsToString(toPathContainer("/").elements())).isEqualTo("[/]"); + assertThat(elementsToString(toPathContainer("///").elements())).isEqualTo("[/][/][/]"); } @Test public void hasPatternSyntax() { PathPatternParser parser = new PathPatternParser(); - assertTrue(parser.parse("/foo/*").hasPatternSyntax()); - assertTrue(parser.parse("/foo/**/bar").hasPatternSyntax()); - assertTrue(parser.parse("/f?o").hasPatternSyntax()); - assertTrue(parser.parse("/foo/{bar}/baz").hasPatternSyntax()); - assertFalse(parser.parse("/foo/bar").hasPatternSyntax()); + assertThat(parser.parse("/foo/*").hasPatternSyntax()).isTrue(); + assertThat(parser.parse("/foo/**/bar").hasPatternSyntax()).isTrue(); + assertThat(parser.parse("/f?o").hasPatternSyntax()).isTrue(); + assertThat(parser.parse("/foo/{bar}/baz").hasPatternSyntax()).isTrue(); + assertThat(parser.parse("/foo/bar").hasPatternSyntax()).isFalse(); } @Test @@ -95,11 +90,11 @@ public class PathPatternTests { } private void assertMatches(PathPattern pp, String path) { - assertTrue(pp.matches(toPathContainer(path))); + assertThat(pp.matches(toPathContainer(path))).isTrue(); } private void assertNoMatch(PathPattern pp, String path) { - assertFalse(pp.matches(toPathContainer(path))); + assertThat(pp.matches(toPathContainer(path))).isFalse(); } @Test @@ -131,26 +126,26 @@ public class PathPatternTests { // CaptureVariablePathElement pp = parse("/{var}"); assertMatches(pp,"/resource"); - assertEquals("resource",pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")).isEqualTo("resource"); assertMatches(pp,"/resource/"); - assertEquals("resource",pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")).isEqualTo("resource"); assertNoMatch(pp,"/resource//"); pp = parse("/{var}/"); assertNoMatch(pp,"/resource"); assertMatches(pp,"/resource/"); - assertEquals("resource",pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")).isEqualTo("resource"); assertNoMatch(pp,"/resource//"); // CaptureTheRestPathElement pp = parse("/{*var}"); assertMatches(pp,"/resource"); - assertEquals("/resource",pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")).isEqualTo("/resource"); assertMatches(pp,"/resource/"); - assertEquals("/resource/",pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")).isEqualTo("/resource/"); assertMatches(pp,"/resource//"); - assertEquals("/resource//",pp.matchAndExtract(toPathContainer("/resource//")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("/resource//")).getUriVariables().get("var")).isEqualTo("/resource//"); assertMatches(pp,"//resource//"); - assertEquals("//resource//",pp.matchAndExtract(toPathContainer("//resource//")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("//resource//")).getUriVariables().get("var")).isEqualTo("//resource//"); // WildcardTheRestPathElement pp = parse("/**"); @@ -172,17 +167,17 @@ public class PathPatternTests { // RegexPathElement pp = parse("/{var1}_{var2}"); assertMatches(pp,"/res1_res2"); - assertEquals("res1",pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var1")); - assertEquals("res2",pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var2")); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var1")).isEqualTo("res1"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var2")).isEqualTo("res2"); assertMatches(pp,"/res1_res2/"); - assertEquals("res1",pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var1")); - assertEquals("res2",pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var2")); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var1")).isEqualTo("res1"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var2")).isEqualTo("res2"); assertNoMatch(pp,"/res1_res2//"); pp = parse("/{var1}_{var2}/"); assertNoMatch(pp,"/res1_res2"); assertMatches(pp,"/res1_res2/"); - assertEquals("res1",pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var1")); - assertEquals("res2",pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var2")); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var1")).isEqualTo("res1"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var2")).isEqualTo("res2"); assertNoMatch(pp,"/res1_res2//"); pp = parse("/{var1}*"); assertMatches(pp,"/a"); @@ -216,25 +211,25 @@ public class PathPatternTests { // CaptureVariablePathElement pp = parser.parse("/{var}"); assertMatches(pp,"/resource"); - assertEquals("resource",pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")).isEqualTo("resource"); assertNoMatch(pp,"/resource/"); assertNoMatch(pp,"/resource//"); pp = parser.parse("/{var}/"); assertNoMatch(pp,"/resource"); assertMatches(pp,"/resource/"); - assertEquals("resource",pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")).isEqualTo("resource"); assertNoMatch(pp,"/resource//"); // CaptureTheRestPathElement pp = parser.parse("/{*var}"); assertMatches(pp,"/resource"); - assertEquals("/resource",pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")).isEqualTo("/resource"); assertMatches(pp,"/resource/"); - assertEquals("/resource/",pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")).isEqualTo("/resource/"); assertMatches(pp,"/resource//"); - assertEquals("/resource//",pp.matchAndExtract(toPathContainer("/resource//")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("/resource//")).getUriVariables().get("var")).isEqualTo("/resource//"); assertMatches(pp,"//resource//"); - assertEquals("//resource//",pp.matchAndExtract(toPathContainer("//resource//")).getUriVariables().get("var")); + assertThat(pp.matchAndExtract(toPathContainer("//resource//")).getUriVariables().get("var")).isEqualTo("//resource//"); // WildcardTheRestPathElement pp = parser.parse("/**"); @@ -256,15 +251,15 @@ public class PathPatternTests { // RegexPathElement pp = parser.parse("/{var1}_{var2}"); assertMatches(pp,"/res1_res2"); - assertEquals("res1",pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var1")); - assertEquals("res2",pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var2")); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var1")).isEqualTo("res1"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var2")).isEqualTo("res2"); assertNoMatch(pp,"/res1_res2/"); assertNoMatch(pp,"/res1_res2//"); pp = parser.parse("/{var1}_{var2}/"); assertNoMatch(pp,"/res1_res2"); assertMatches(pp,"/res1_res2/"); - assertEquals("res1",pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var1")); - assertEquals("res2",pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var2")); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var1")).isEqualTo("res1"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var2")).isEqualTo("res2"); assertNoMatch(pp,"/res1_res2//"); pp = parser.parse("/{var1}*"); assertMatches(pp,"/a"); @@ -276,22 +271,22 @@ public class PathPatternTests { @Test public void pathRemainderBasicCases_spr15336() { // Cover all PathElement kinds - assertEquals("/bar", getPathRemaining("/foo","/foo/bar").getPathRemaining().value()); - assertEquals("/", getPathRemaining("/foo","/foo/").getPathRemaining().value()); - assertEquals("/bar",getPathRemaining("/foo*","/foo/bar").getPathRemaining().value()); - assertEquals("/bar", getPathRemaining("/*","/foo/bar").getPathRemaining().value()); - assertEquals("/bar", getPathRemaining("/{foo}","/foo/bar").getPathRemaining().value()); - assertNull(getPathRemaining("/foo","/bar/baz")); - assertEquals("",getPathRemaining("/**","/foo/bar").getPathRemaining().value()); - assertEquals("",getPathRemaining("/{*bar}","/foo/bar").getPathRemaining().value()); - assertEquals("/bar",getPathRemaining("/a?b/d?e","/aab/dde/bar").getPathRemaining().value()); - assertEquals("/bar",getPathRemaining("/{abc}abc","/xyzabc/bar").getPathRemaining().value()); - assertEquals("/bar",getPathRemaining("/*y*","/xyzxyz/bar").getPathRemaining().value()); - assertEquals("",getPathRemaining("/","/").getPathRemaining().value()); - assertEquals("a",getPathRemaining("/","/a").getPathRemaining().value()); - assertEquals("a/",getPathRemaining("/","/a/").getPathRemaining().value()); - assertEquals("/bar",getPathRemaining("/a{abc}","/a/bar").getPathRemaining().value()); - assertEquals("/bar", getPathRemaining("/foo//","/foo///bar").getPathRemaining().value()); + assertThat(getPathRemaining("/foo", "/foo/bar").getPathRemaining().value()).isEqualTo("/bar"); + assertThat(getPathRemaining("/foo", "/foo/").getPathRemaining().value()).isEqualTo("/"); + assertThat(getPathRemaining("/foo*", "/foo/bar").getPathRemaining().value()).isEqualTo("/bar"); + assertThat(getPathRemaining("/*", "/foo/bar").getPathRemaining().value()).isEqualTo("/bar"); + assertThat(getPathRemaining("/{foo}", "/foo/bar").getPathRemaining().value()).isEqualTo("/bar"); + assertThat(getPathRemaining("/foo","/bar/baz")).isNull(); + assertThat(getPathRemaining("/**", "/foo/bar").getPathRemaining().value()).isEqualTo(""); + assertThat(getPathRemaining("/{*bar}", "/foo/bar").getPathRemaining().value()).isEqualTo(""); + assertThat(getPathRemaining("/a?b/d?e", "/aab/dde/bar").getPathRemaining().value()).isEqualTo("/bar"); + assertThat(getPathRemaining("/{abc}abc", "/xyzabc/bar").getPathRemaining().value()).isEqualTo("/bar"); + assertThat(getPathRemaining("/*y*", "/xyzxyz/bar").getPathRemaining().value()).isEqualTo("/bar"); + assertThat(getPathRemaining("/", "/").getPathRemaining().value()).isEqualTo(""); + assertThat(getPathRemaining("/", "/a").getPathRemaining().value()).isEqualTo("a"); + assertThat(getPathRemaining("/", "/a/").getPathRemaining().value()).isEqualTo("a/"); + assertThat(getPathRemaining("/a{abc}", "/a/bar").getPathRemaining().value()).isEqualTo("/bar"); + assertThat(getPathRemaining("/foo//", "/foo///bar").getPathRemaining().value()).isEqualTo("/bar"); } @Test @@ -327,43 +322,43 @@ public class PathPatternTests { @Test public void pathRemainingCornerCases_spr15336() { // No match when the literal path element is a longer form of the segment in the pattern - assertNull(parse("/foo").matchStartOfPath(toPathContainer("/footastic/bar"))); - assertNull(parse("/f?o").matchStartOfPath(toPathContainer("/footastic/bar"))); - assertNull(parse("/f*o*p").matchStartOfPath(toPathContainer("/flooptastic/bar"))); - assertNull(parse("/{abc}abc").matchStartOfPath(toPathContainer("/xyzabcbar/bar"))); + assertThat((Object) parse("/foo").matchStartOfPath(toPathContainer("/footastic/bar"))).isNull(); + assertThat((Object) parse("/f?o").matchStartOfPath(toPathContainer("/footastic/bar"))).isNull(); + assertThat((Object) parse("/f*o*p").matchStartOfPath(toPathContainer("/flooptastic/bar"))).isNull(); + assertThat((Object) parse("/{abc}abc").matchStartOfPath(toPathContainer("/xyzabcbar/bar"))).isNull(); // With a /** on the end have to check if there is any more data post // 'the match' it starts with a separator - assertNull(parse("/resource/**").matchStartOfPath(toPathContainer("/resourceX"))); - assertEquals("",parse("/resource/**") - .matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value()); + assertThat(parse("/resource/**").matchStartOfPath(toPathContainer("/resourceX"))).isNull(); + assertThat(parse("/resource/**") + .matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value()).isEqualTo(""); // Similar to above for the capture-the-rest variant - assertNull(parse("/resource/{*foo}").matchStartOfPath(toPathContainer("/resourceX"))); - assertEquals("", parse("/resource/{*foo}") - .matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value()); + assertThat(parse("/resource/{*foo}").matchStartOfPath(toPathContainer("/resourceX"))).isNull(); + assertThat(parse("/resource/{*foo}") + .matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value()).isEqualTo(""); PathPattern.PathRemainingMatchInfo pri = parse("/aaa/{bbb}/c?d/e*f/*/g") .matchStartOfPath(toPathContainer("/aaa/b/ccd/ef/x/g/i")); - assertNotNull(pri); - assertEquals("/i",pri.getPathRemaining().value()); - assertEquals("b",pri.getUriVariables().get("bbb")); + assertThat(pri).isNotNull(); + assertThat(pri.getPathRemaining().value()).isEqualTo("/i"); + assertThat(pri.getUriVariables().get("bbb")).isEqualTo("b"); pri = parse("/aaa/{bbb}/c?d/e*f/*/g/").matchStartOfPath(toPathContainer("/aaa/b/ccd/ef/x/g/i")); - assertNotNull(pri); - assertEquals("i",pri.getPathRemaining().value()); - assertEquals("b",pri.getUriVariables().get("bbb")); + assertThat(pri).isNotNull(); + assertThat(pri.getPathRemaining().value()).isEqualTo("i"); + assertThat(pri.getUriVariables().get("bbb")).isEqualTo("b"); pri = parse("/{aaa}_{bbb}/e*f/{x}/g").matchStartOfPath(toPathContainer("/aa_bb/ef/x/g/i")); - assertNotNull(pri); - assertEquals("/i",pri.getPathRemaining().value()); - assertEquals("aa",pri.getUriVariables().get("aaa")); - assertEquals("bb",pri.getUriVariables().get("bbb")); - assertEquals("x",pri.getUriVariables().get("x")); + assertThat(pri).isNotNull(); + assertThat(pri.getPathRemaining().value()).isEqualTo("/i"); + assertThat(pri.getUriVariables().get("aaa")).isEqualTo("aa"); + assertThat(pri.getUriVariables().get("bbb")).isEqualTo("bb"); + assertThat(pri.getUriVariables().get("x")).isEqualTo("x"); - assertNull(parse("/a/b").matchStartOfPath(toPathContainer(""))); - assertEquals("/a/b",parse("").matchStartOfPath(toPathContainer("/a/b")).getPathRemaining().value()); - assertEquals("",parse("").matchStartOfPath(toPathContainer("")).getPathRemaining().value()); + assertThat(parse("/a/b").matchStartOfPath(toPathContainer(""))).isNull(); + assertThat(parse("").matchStartOfPath(toPathContainer("/a/b")).getPathRemaining().value()).isEqualTo("/a/b"); + assertThat(parse("").matchStartOfPath(toPathContainer("")).getPathRemaining().value()).isEqualTo(""); } @Test @@ -406,10 +401,9 @@ public class PathPatternTests { @Test public void multipleSeparatorsInPattern() { PathPattern pp = parse("a//b//c"); - assertEquals("Literal(a) Separator(/) Separator(/) Literal(b) Separator(/) Separator(/) Literal(c)", - pp.toChainString()); + assertThat(pp.toChainString()).isEqualTo("Literal(a) Separator(/) Separator(/) Literal(b) Separator(/) Separator(/) Literal(c)"); assertMatches(pp,"a//b//c"); - assertEquals("Literal(a) Separator(/) WildcardTheRest(/**)",parse("a//**").toChainString()); + assertThat(parse("a//**").toChainString()).isEqualTo("Literal(a) Separator(/) WildcardTheRest(/**)"); checkMatches("///abc", "///abc"); checkNoMatch("///abc", "/abc"); checkNoMatch("//", "/"); @@ -462,7 +456,7 @@ public class PathPatternTests { checkMatches("a/*", "a/a/"); // trailing slash, so is allowed PathPatternParser ppp = new PathPatternParser(); ppp.setMatchOptionalTrailingSeparator(false); - assertFalse(ppp.parse("a/*").matches(toPathContainer("a//"))); + assertThat(ppp.parse("a/*").matches(toPathContainer("a//"))).isFalse(); checkMatches("a/*", "a/a"); checkMatches("a/*", "a/a/"); // trailing slash is optional checkMatches("/resource/**", "/resource"); @@ -560,31 +554,31 @@ public class PathPatternTests { // It would be nice to partially match a path and get any bound variables in one step pp = parse("/{this}/{one}/{here}"); pri = getPathRemaining(pp, "/foo/bar/goo/boo"); - assertEquals("/boo",pri.getPathRemaining().value()); - assertEquals("foo",pri.getUriVariables().get("this")); - assertEquals("bar",pri.getUriVariables().get("one")); - assertEquals("goo",pri.getUriVariables().get("here")); + assertThat(pri.getPathRemaining().value()).isEqualTo("/boo"); + assertThat(pri.getUriVariables().get("this")).isEqualTo("foo"); + assertThat(pri.getUriVariables().get("one")).isEqualTo("bar"); + assertThat(pri.getUriVariables().get("here")).isEqualTo("goo"); pp = parse("/aaa/{foo}"); pri = getPathRemaining(pp, "/aaa/bbb"); - assertEquals("",pri.getPathRemaining().value()); - assertEquals("bbb",pri.getUriVariables().get("foo")); + assertThat(pri.getPathRemaining().value()).isEqualTo(""); + assertThat(pri.getUriVariables().get("foo")).isEqualTo("bbb"); pp = parse("/aaa/bbb"); pri = getPathRemaining(pp, "/aaa/bbb"); - assertEquals("",pri.getPathRemaining().value()); - assertEquals(0,pri.getUriVariables().size()); + assertThat(pri.getPathRemaining().value()).isEqualTo(""); + assertThat(pri.getUriVariables().size()).isEqualTo(0); pp = parse("/*/{foo}/b*"); pri = getPathRemaining(pp, "/foo"); - assertNull(pri); + assertThat((Object) pri).isNull(); pri = getPathRemaining(pp, "/abc/def/bhi"); - assertEquals("",pri.getPathRemaining().value()); - assertEquals("def",pri.getUriVariables().get("foo")); + assertThat(pri.getPathRemaining().value()).isEqualTo(""); + assertThat(pri.getUriVariables().get("foo")).isEqualTo("def"); pri = getPathRemaining(pp, "/abc/def/bhi/jkl"); - assertEquals("/jkl",pri.getPathRemaining().value()); - assertEquals("def",pri.getUriVariables().get("foo")); + assertThat(pri.getPathRemaining().value()).isEqualTo("/jkl"); + assertThat(pri.getUriVariables().get("foo")).isEqualTo("def"); } @Test @@ -762,15 +756,15 @@ public class PathPatternTests { assertMatches(pp,"//"); // Confirming AntPathMatcher behaviour: - assertFalse(new AntPathMatcher().match("/{foo}", "/")); - assertTrue(new AntPathMatcher().match("/{foo}", "/a")); - assertTrue(new AntPathMatcher().match("/{foo}{bar}", "/a")); - assertFalse(new AntPathMatcher().match("/{foo}*", "/")); - assertTrue(new AntPathMatcher().match("/*", "/")); - assertFalse(new AntPathMatcher().match("/*{foo}", "/")); + assertThat(new AntPathMatcher().match("/{foo}", "/")).isFalse(); + assertThat(new AntPathMatcher().match("/{foo}", "/a")).isTrue(); + assertThat(new AntPathMatcher().match("/{foo}{bar}", "/a")).isTrue(); + assertThat(new AntPathMatcher().match("/{foo}*", "/")).isFalse(); + assertThat(new AntPathMatcher().match("/*", "/")).isTrue(); + assertThat(new AntPathMatcher().match("/*{foo}", "/")).isFalse(); Map vars = new AntPathMatcher().extractUriTemplateVariables("/{foo}{bar}", "/a"); - assertEquals("a",vars.get("foo")); - assertEquals("",vars.get("bar")); + assertThat(vars.get("foo")).isEqualTo("a"); + assertThat(vars.get("bar")).isEqualTo(""); } @Test @@ -787,10 +781,10 @@ public class PathPatternTests { checkCapture("/A-{B}-C", "/A-b-C", "B", "b"); checkCapture("/{name}.{extension}", "/test.html", "name", "test", "extension", "html"); - assertNull(checkCapture("/{one}/", "//")); - assertNull(checkCapture("", "/abc")); + assertThat((Object) checkCapture("/{one}/", "//")).isNull(); + assertThat((Object) checkCapture("", "/abc")).isNull(); - assertEquals(0, checkCapture("", "").getUriVariables().size()); + assertThat(checkCapture("", "").getUriVariables().size()).isEqualTo(0); checkCapture("{id}", "99", "id", "99"); checkCapture("/customer/{customerId}", "/customer/78", "customerId", "78"); checkCapture("/customer/{customerId}/banana", "/customer/42/banana", "customerId", @@ -800,7 +794,7 @@ public class PathPatternTests { "apple"); checkCapture("/{bla}.*", "/testing.html", "bla", "testing"); PathPattern.PathMatchInfo extracted = checkCapture("/abc", "/abc"); - assertEquals(0, extracted.getUriVariables().size()); + assertThat(extracted.getUriVariables().size()).isEqualTo(0); checkCapture("/{bla}/foo","/a/foo"); } @@ -811,13 +805,13 @@ public class PathPatternTests { p = pp.parse("{symbolicName:[\\w\\.]+}-{version:[\\w\\.]+}.jar"); PathPattern.PathMatchInfo result = matchAndExtract(p, "com.example-1.0.0.jar"); - assertEquals("com.example", result.getUriVariables().get("symbolicName")); - assertEquals("1.0.0", result.getUriVariables().get("version")); + assertThat(result.getUriVariables().get("symbolicName")).isEqualTo("com.example"); + assertThat(result.getUriVariables().get("version")).isEqualTo("1.0.0"); p = pp.parse("{symbolicName:[\\w\\.]+}-sources-{version:[\\w\\.]+}.jar"); result = matchAndExtract(p, "com.example-sources-1.0.0.jar"); - assertEquals("com.example", result.getUriVariables().get("symbolicName")); - assertEquals("1.0.0", result.getUriVariables().get("version")); + assertThat(result.getUriVariables().get("symbolicName")).isEqualTo("com.example"); + assertThat(result.getUriVariables().get("version")).isEqualTo("1.0.0"); } @Test @@ -826,22 +820,22 @@ public class PathPatternTests { PathPattern p = pp.parse("{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.]+}.jar"); PathPattern.PathMatchInfo result = p.matchAndExtract(toPathContainer("com.example-sources-1.0.0.jar")); - assertEquals("com.example", result.getUriVariables().get("symbolicName")); - assertEquals("1.0.0", result.getUriVariables().get("version")); + assertThat(result.getUriVariables().get("symbolicName")).isEqualTo("com.example"); + assertThat(result.getUriVariables().get("version")).isEqualTo("1.0.0"); p = pp.parse("{symbolicName:[\\w\\.]+}-sources-" + "{version:[\\d\\.]+}-{year:\\d{4}}{month:\\d{2}}{day:\\d{2}}.jar"); result = matchAndExtract(p,"com.example-sources-1.0.0-20100220.jar"); - assertEquals("com.example", result.getUriVariables().get("symbolicName")); - assertEquals("1.0.0", result.getUriVariables().get("version")); - assertEquals("2010", result.getUriVariables().get("year")); - assertEquals("02", result.getUriVariables().get("month")); - assertEquals("20", result.getUriVariables().get("day")); + assertThat(result.getUriVariables().get("symbolicName")).isEqualTo("com.example"); + assertThat(result.getUriVariables().get("version")).isEqualTo("1.0.0"); + assertThat(result.getUriVariables().get("year")).isEqualTo("2010"); + assertThat(result.getUriVariables().get("month")).isEqualTo("02"); + assertThat(result.getUriVariables().get("day")).isEqualTo("20"); p = pp.parse("{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.\\{\\}]+}.jar"); result = matchAndExtract(p, "com.example-sources-1.0.0.{12}.jar"); - assertEquals("com.example", result.getUriVariables().get("symbolicName")); - assertEquals("1.0.0.{12}", result.getUriVariables().get("version")); + assertThat(result.getUriVariables().get("symbolicName")).isEqualTo("com.example"); + assertThat(result.getUriVariables().get("version")).isEqualTo("1.0.0.{12}"); } @Test @@ -856,40 +850,43 @@ public class PathPatternTests { @Test public void combine() { TestPathCombiner pathMatcher = new TestPathCombiner(); - assertEquals("", pathMatcher.combine("", "")); - assertEquals("/hotels", pathMatcher.combine("/hotels", "")); - assertEquals("/hotels", pathMatcher.combine("", "/hotels")); - assertEquals("/hotels/booking", pathMatcher.combine("/hotels/*", "booking")); - assertEquals("/hotels/booking", pathMatcher.combine("/hotels/*", "/booking")); - assertEquals("/hotels/**/booking", pathMatcher.combine("/hotels/**", "booking")); - assertEquals("/hotels/**/booking", pathMatcher.combine("/hotels/**", "/booking")); - assertEquals("/hotels/booking", pathMatcher.combine("/hotels", "/booking")); - assertEquals("/hotels/booking", pathMatcher.combine("/hotels", "booking")); - assertEquals("/hotels/booking", pathMatcher.combine("/hotels/", "booking")); - assertEquals("/hotels/{hotel}", pathMatcher.combine("/hotels/*", "{hotel}")); - assertEquals("/hotels/**/{hotel}", pathMatcher.combine("/hotels/**", "{hotel}")); - assertEquals("/hotels/{hotel}", pathMatcher.combine("/hotels", "{hotel}")); - assertEquals("/hotels/{hotel}.*", pathMatcher.combine("/hotels", "{hotel}.*")); - assertEquals("/hotels/*/booking/{booking}", - pathMatcher.combine("/hotels/*/booking", "{booking}")); - assertEquals("/hotel.html", pathMatcher.combine("/*.html", "/hotel.html")); - assertEquals("/hotel.html", pathMatcher.combine("/*.html", "/hotel")); - assertEquals("/hotel.html", pathMatcher.combine("/*.html", "/hotel.*")); + assertThat(pathMatcher.combine("", "")).isEqualTo(""); + assertThat(pathMatcher.combine("/hotels", "")).isEqualTo("/hotels"); + assertThat(pathMatcher.combine("", "/hotels")).isEqualTo("/hotels"); + assertThat(pathMatcher.combine("/hotels/*", "booking")).isEqualTo("/hotels/booking"); + assertThat(pathMatcher.combine("/hotels/*", "/booking")).isEqualTo("/hotels/booking"); + assertThat(pathMatcher.combine("/hotels/**", "booking")).isEqualTo("/hotels/**/booking"); + assertThat(pathMatcher.combine("/hotels/**", "/booking")).isEqualTo("/hotels/**/booking"); + assertThat(pathMatcher.combine("/hotels", "/booking")).isEqualTo("/hotels/booking"); + assertThat(pathMatcher.combine("/hotels", "booking")).isEqualTo("/hotels/booking"); + assertThat(pathMatcher.combine("/hotels/", "booking")).isEqualTo("/hotels/booking"); + assertThat(pathMatcher.combine("/hotels/*", "{hotel}")).isEqualTo("/hotels/{hotel}"); + assertThat(pathMatcher.combine("/hotels/**", "{hotel}")).isEqualTo("/hotels/**/{hotel}"); + assertThat(pathMatcher.combine("/hotels", "{hotel}")).isEqualTo("/hotels/{hotel}"); + assertThat(pathMatcher.combine("/hotels", "{hotel}.*")).isEqualTo("/hotels/{hotel}.*"); + assertThat(pathMatcher.combine("/hotels/*/booking", "{booking}")).isEqualTo("/hotels/*/booking/{booking}"); + assertThat(pathMatcher.combine("/*.html", "/hotel.html")).isEqualTo("/hotel.html"); + assertThat(pathMatcher.combine("/*.html", "/hotel")).isEqualTo("/hotel.html"); + assertThat(pathMatcher.combine("/*.html", "/hotel.*")).isEqualTo("/hotel.html"); // TODO this seems rather bogus, should we eagerly show an error? - assertEquals("/d/e/f/hotel.html", pathMatcher.combine("/a/b/c/*.html", "/d/e/f/hotel.*")); - assertEquals("/*.html", pathMatcher.combine("/**", "/*.html")); - assertEquals("/*.html", pathMatcher.combine("/*", "/*.html")); - assertEquals("/*.html", pathMatcher.combine("/*.*", "/*.html")); - assertEquals("/{foo}/bar", pathMatcher.combine("/{foo}", "/bar")); // SPR-8858 - assertEquals("/user/user", pathMatcher.combine("/user", "/user")); // SPR-7970 - assertEquals("/{foo:.*[^0-9].*}/edit/", - pathMatcher.combine("/{foo:.*[^0-9].*}", "/edit/")); // SPR-10062 - assertEquals("/1.0/foo/test", pathMatcher.combine("/1.0", "/foo/test")); + assertThat(pathMatcher.combine("/a/b/c/*.html", "/d/e/f/hotel.*")).isEqualTo("/d/e/f/hotel.html"); + assertThat(pathMatcher.combine("/**", "/*.html")).isEqualTo("/*.html"); + assertThat(pathMatcher.combine("/*", "/*.html")).isEqualTo("/*.html"); + assertThat(pathMatcher.combine("/*.*", "/*.html")).isEqualTo("/*.html"); + // SPR-8858 + assertThat(pathMatcher.combine("/{foo}", "/bar")).isEqualTo("/{foo}/bar"); + // SPR-7970 + assertThat(pathMatcher.combine("/user", "/user")).isEqualTo("/user/user"); + // SPR-10062 + assertThat(pathMatcher.combine("/{foo:.*[^0-9].*}", "/edit/")).isEqualTo("/{foo:.*[^0-9].*}/edit/"); + assertThat(pathMatcher.combine("/1.0", "/foo/test")).isEqualTo("/1.0/foo/test"); // SPR-10554 - assertEquals("/hotel", pathMatcher.combine("/", "/hotel")); // SPR-12975 - assertEquals("/hotel/booking", pathMatcher.combine("/hotel/", "/booking")); // SPR-12975 - assertEquals("/hotel", pathMatcher.combine("", "/hotel")); - assertEquals("/hotel", pathMatcher.combine("/hotel", "")); + // SPR-12975 + assertThat(pathMatcher.combine("/", "/hotel")).isEqualTo("/hotel"); + // SPR-12975 + assertThat(pathMatcher.combine("/hotel/", "/booking")).isEqualTo("/hotel/booking"); + assertThat(pathMatcher.combine("", "/hotel")).isEqualTo("/hotel"); + assertThat(pathMatcher.combine("/hotel", "")).isEqualTo("/hotel"); // TODO Do we need special handling when patterns contain multiple dots? } @@ -904,63 +901,57 @@ public class PathPatternTests { public void patternComparator() { Comparator comparator = PathPattern.SPECIFICITY_COMPARATOR; - assertEquals(0, comparator.compare(parse("/hotels/new"), parse("/hotels/new"))); + assertThat(comparator.compare(parse("/hotels/new"), parse("/hotels/new"))).isEqualTo(0); - assertEquals(-1, comparator.compare(parse("/hotels/new"), parse("/hotels/*"))); - assertEquals(1, comparator.compare(parse("/hotels/*"), parse("/hotels/new"))); - assertEquals(0, comparator.compare(parse("/hotels/*"), parse("/hotels/*"))); + assertThat(comparator.compare(parse("/hotels/new"), parse("/hotels/*"))).isEqualTo(-1); + assertThat(comparator.compare(parse("/hotels/*"), parse("/hotels/new"))).isEqualTo(1); + assertThat(comparator.compare(parse("/hotels/*"), parse("/hotels/*"))).isEqualTo(0); - assertEquals(-1, - comparator.compare(parse("/hotels/new"), parse("/hotels/{hotel}"))); - assertEquals(1, - comparator.compare(parse("/hotels/{hotel}"), parse("/hotels/new"))); - assertEquals(0, - comparator.compare(parse("/hotels/{hotel}"), parse("/hotels/{hotel}"))); - assertEquals(-1, comparator.compare(parse("/hotels/{hotel}/booking"), - parse("/hotels/{hotel}/bookings/{booking}"))); - assertEquals(1, comparator.compare(parse("/hotels/{hotel}/bookings/{booking}"), - parse("/hotels/{hotel}/booking"))); + assertThat(comparator.compare(parse("/hotels/new"), parse("/hotels/{hotel}"))).isEqualTo(-1); + assertThat(comparator.compare(parse("/hotels/{hotel}"), parse("/hotels/new"))).isEqualTo(1); + assertThat(comparator.compare(parse("/hotels/{hotel}"), parse("/hotels/{hotel}"))).isEqualTo(0); + assertThat(comparator.compare(parse("/hotels/{hotel}/booking"), + parse("/hotels/{hotel}/bookings/{booking}"))).isEqualTo(-1); + assertThat(comparator.compare(parse("/hotels/{hotel}/bookings/{booking}"), + parse("/hotels/{hotel}/booking"))).isEqualTo(1); - assertEquals(-1, - comparator.compare( + assertThat(comparator.compare( parse("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}"), - parse("/**"))); - assertEquals(1, comparator.compare(parse("/**"), - parse("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}"))); - assertEquals(0, comparator.compare(parse("/**"), parse("/**"))); + parse("/**"))).isEqualTo(-1); + assertThat(comparator.compare(parse("/**"), + parse("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}"))).isEqualTo(1); + assertThat(comparator.compare(parse("/**"), parse("/**"))).isEqualTo(0); - assertEquals(-1, - comparator.compare(parse("/hotels/{hotel}"), parse("/hotels/*"))); - assertEquals(1, comparator.compare(parse("/hotels/*"), parse("/hotels/{hotel}"))); + assertThat(comparator.compare(parse("/hotels/{hotel}"), parse("/hotels/*"))).isEqualTo(-1); + assertThat(comparator.compare(parse("/hotels/*"), parse("/hotels/{hotel}"))).isEqualTo(1); - assertEquals(-1, comparator.compare(parse("/hotels/*"), parse("/hotels/*/**"))); - assertEquals(1, comparator.compare(parse("/hotels/*/**"), parse("/hotels/*"))); + assertThat(comparator.compare(parse("/hotels/*"), parse("/hotels/*/**"))).isEqualTo(-1); + assertThat(comparator.compare(parse("/hotels/*/**"), parse("/hotels/*"))).isEqualTo(1); // TODO: shouldn't the wildcard lower the score? // assertEquals(-1, // comparator.compare(parse("/hotels/new"), parse("/hotels/new.*"))); // SPR-6741 - assertEquals(-1, - comparator.compare( + assertThat(comparator.compare( parse("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}"), - parse("/hotels/**"))); - assertEquals(1, comparator.compare(parse("/hotels/**"), - parse("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}"))); - assertEquals(1, comparator.compare(parse("/hotels/foo/bar/**"), - parse("/hotels/{hotel}"))); - assertEquals(-1, comparator.compare(parse("/hotels/{hotel}"), - parse("/hotels/foo/bar/**"))); + parse("/hotels/**"))).isEqualTo(-1); + assertThat(comparator.compare(parse("/hotels/**"), + parse("/hotels/{hotel}/bookings/{booking}/cutomers/{customer}"))).isEqualTo(1); + assertThat(comparator.compare(parse("/hotels/foo/bar/**"), + parse("/hotels/{hotel}"))).isEqualTo(1); + assertThat(comparator.compare(parse("/hotels/{hotel}"), + parse("/hotels/foo/bar/**"))).isEqualTo(-1); // SPR-8683 - assertEquals(1, comparator.compare(parse("/**"), parse("/hotels/{hotel}"))); + assertThat(comparator.compare(parse("/**"), parse("/hotels/{hotel}"))).isEqualTo(1); // longer is better - assertEquals(1, comparator.compare(parse("/hotels"), parse("/hotels2"))); + assertThat(comparator.compare(parse("/hotels"), parse("/hotels2"))).isEqualTo(1); // SPR-13139 - assertEquals(-1, comparator.compare(parse("*"), parse("*/**"))); - assertEquals(1, comparator.compare(parse("*/**"), parse("*"))); + assertThat(comparator.compare(parse("*"), parse("*/**"))).isEqualTo(-1); + assertThat(comparator.compare(parse("*/**"), parse("*"))).isEqualTo(1); } @Test @@ -972,8 +963,8 @@ public class PathPatternTests { PathPattern.PathMatchInfo r2 = matchAndExtract(p2, "/file.txt"); // works fine - assertEquals("file.txt", r1.getUriVariables().get("foo")); - assertEquals("file", r2.getUriVariables().get("foo")); + assertThat(r1.getUriVariables().get("foo")).isEqualTo("file.txt"); + assertThat(r2.getUriVariables().get("foo")).isEqualTo("file"); // This produces 2 (see comments in https://jira.spring.io/browse/SPR-14544 ) // Comparator patternComparator = new AntPathMatcher().getPatternComparator(""); @@ -984,9 +975,9 @@ public class PathPatternTests { @Test public void patternCompareWithNull() { - assertTrue(PathPattern.SPECIFICITY_COMPARATOR.compare(null, null) == 0); - assertTrue(PathPattern.SPECIFICITY_COMPARATOR.compare(parse("/abc"), null) < 0); - assertTrue(PathPattern.SPECIFICITY_COMPARATOR.compare(null, parse("/abc")) > 0); + assertThat(PathPattern.SPECIFICITY_COMPARATOR.compare(null, null) == 0).isTrue(); + assertThat(PathPattern.SPECIFICITY_COMPARATOR.compare(parse("/abc"), null) < 0).isTrue(); + assertThat(PathPattern.SPECIFICITY_COMPARATOR.compare(null, parse("/abc")) > 0).isTrue(); } @Test @@ -998,74 +989,74 @@ public class PathPatternTests { paths.add(null); paths.add(null); paths.sort(comparator); - assertNull(paths.get(0)); - assertNull(paths.get(1)); + assertThat((Object) paths.get(0)).isNull(); + assertThat((Object) paths.get(1)).isNull(); paths.clear(); paths.add(null); paths.add(pp.parse("/hotels/new")); paths.sort(comparator); - assertEquals("/hotels/new", paths.get(0).getPatternString()); - assertNull(paths.get(1)); + assertThat(paths.get(0).getPatternString()).isEqualTo("/hotels/new"); + assertThat(paths.get(1)).isNull(); paths.clear(); paths.add(pp.parse("/hotels/*")); paths.add(pp.parse("/hotels/new")); paths.sort(comparator); - assertEquals("/hotels/new", paths.get(0).getPatternString()); - assertEquals("/hotels/*", paths.get(1).getPatternString()); + assertThat(paths.get(0).getPatternString()).isEqualTo("/hotels/new"); + assertThat(paths.get(1).getPatternString()).isEqualTo("/hotels/*"); paths.clear(); paths.add(pp.parse("/hotels/new")); paths.add(pp.parse("/hotels/*")); paths.sort(comparator); - assertEquals("/hotels/new", paths.get(0).getPatternString()); - assertEquals("/hotels/*", paths.get(1).getPatternString()); + assertThat(paths.get(0).getPatternString()).isEqualTo("/hotels/new"); + assertThat(paths.get(1).getPatternString()).isEqualTo("/hotels/*"); paths.clear(); paths.add(pp.parse("/hotels/**")); paths.add(pp.parse("/hotels/*")); paths.sort(comparator); - assertEquals("/hotels/*", paths.get(0).getPatternString()); - assertEquals("/hotels/**", paths.get(1).getPatternString()); + assertThat(paths.get(0).getPatternString()).isEqualTo("/hotels/*"); + assertThat(paths.get(1).getPatternString()).isEqualTo("/hotels/**"); paths.clear(); paths.add(pp.parse("/hotels/*")); paths.add(pp.parse("/hotels/**")); paths.sort(comparator); - assertEquals("/hotels/*", paths.get(0).getPatternString()); - assertEquals("/hotels/**", paths.get(1).getPatternString()); + assertThat(paths.get(0).getPatternString()).isEqualTo("/hotels/*"); + assertThat(paths.get(1).getPatternString()).isEqualTo("/hotels/**"); paths.clear(); paths.add(pp.parse("/hotels/{hotel}")); paths.add(pp.parse("/hotels/new")); paths.sort(comparator); - assertEquals("/hotels/new", paths.get(0).getPatternString()); - assertEquals("/hotels/{hotel}", paths.get(1).getPatternString()); + assertThat(paths.get(0).getPatternString()).isEqualTo("/hotels/new"); + assertThat(paths.get(1).getPatternString()).isEqualTo("/hotels/{hotel}"); paths.clear(); paths.add(pp.parse("/hotels/new")); paths.add(pp.parse("/hotels/{hotel}")); paths.sort(comparator); - assertEquals("/hotels/new", paths.get(0).getPatternString()); - assertEquals("/hotels/{hotel}", paths.get(1).getPatternString()); + assertThat(paths.get(0).getPatternString()).isEqualTo("/hotels/new"); + assertThat(paths.get(1).getPatternString()).isEqualTo("/hotels/{hotel}"); paths.clear(); paths.add(pp.parse("/hotels/*")); paths.add(pp.parse("/hotels/{hotel}")); paths.add(pp.parse("/hotels/new")); paths.sort(comparator); - assertEquals("/hotels/new", paths.get(0).getPatternString()); - assertEquals("/hotels/{hotel}", paths.get(1).getPatternString()); - assertEquals("/hotels/*", paths.get(2).getPatternString()); + assertThat(paths.get(0).getPatternString()).isEqualTo("/hotels/new"); + assertThat(paths.get(1).getPatternString()).isEqualTo("/hotels/{hotel}"); + assertThat(paths.get(2).getPatternString()).isEqualTo("/hotels/*"); paths.clear(); paths.add(pp.parse("/hotels/ne*")); paths.add(pp.parse("/hotels/n*")); Collections.shuffle(paths); paths.sort(comparator); - assertEquals("/hotels/ne*", paths.get(0).getPatternString()); - assertEquals("/hotels/n*", paths.get(1).getPatternString()); + assertThat(paths.get(0).getPatternString()).isEqualTo("/hotels/ne*"); + assertThat(paths.get(1).getPatternString()).isEqualTo("/hotels/n*"); paths.clear(); // comparator = new PatternComparatorConsideringPath("/hotels/new.html"); @@ -1084,8 +1075,8 @@ public class PathPatternTests { paths.add(pp.parse("/*/login.*")); paths.add(pp.parse("/*/endUser/action/login.*")); paths.sort(comparator); - assertEquals("/*/endUser/action/login.*", paths.get(0).getPatternString()); - assertEquals("/*/login.*", paths.get(1).getPatternString()); + assertThat(paths.get(0).getPatternString()).isEqualTo("/*/endUser/action/login.*"); + assertThat(paths.get(1).getPatternString()).isEqualTo("/*/login.*"); paths.clear(); } @@ -1103,37 +1094,37 @@ public class PathPatternTests { public void parameters() { // CaptureVariablePathElement PathPattern.PathMatchInfo result = matchAndExtract("/abc/{var}","/abc/one;two=three;four=five"); - assertEquals("one",result.getUriVariables().get("var")); - assertEquals("three",result.getMatrixVariables().get("var").getFirst("two")); - assertEquals("five",result.getMatrixVariables().get("var").getFirst("four")); + assertThat(result.getUriVariables().get("var")).isEqualTo("one"); + assertThat(result.getMatrixVariables().get("var").getFirst("two")).isEqualTo("three"); + assertThat(result.getMatrixVariables().get("var").getFirst("four")).isEqualTo("five"); // RegexPathElement result = matchAndExtract("/abc/{var1}_{var2}","/abc/123_456;a=b;c=d"); - assertEquals("123",result.getUriVariables().get("var1")); - assertEquals("456",result.getUriVariables().get("var2")); + assertThat(result.getUriVariables().get("var1")).isEqualTo("123"); + assertThat(result.getUriVariables().get("var2")).isEqualTo("456"); // vars associated with second variable - assertNull(result.getMatrixVariables().get("var1")); - assertNull(result.getMatrixVariables().get("var1")); - assertEquals("b",result.getMatrixVariables().get("var2").getFirst("a")); - assertEquals("d",result.getMatrixVariables().get("var2").getFirst("c")); + assertThat(result.getMatrixVariables().get("var1")).isNull(); + assertThat(result.getMatrixVariables().get("var1")).isNull(); + assertThat(result.getMatrixVariables().get("var2").getFirst("a")).isEqualTo("b"); + assertThat(result.getMatrixVariables().get("var2").getFirst("c")).isEqualTo("d"); // CaptureTheRestPathElement result = matchAndExtract("/{*var}","/abc/123_456;a=b;c=d"); - assertEquals("/abc/123_456",result.getUriVariables().get("var")); - assertEquals("b",result.getMatrixVariables().get("var").getFirst("a")); - assertEquals("d",result.getMatrixVariables().get("var").getFirst("c")); + assertThat(result.getUriVariables().get("var")).isEqualTo("/abc/123_456"); + assertThat(result.getMatrixVariables().get("var").getFirst("a")).isEqualTo("b"); + assertThat(result.getMatrixVariables().get("var").getFirst("c")).isEqualTo("d"); result = matchAndExtract("/{*var}","/abc/123_456;a=b;c=d/789;a=e;f=g"); - assertEquals("/abc/123_456/789",result.getUriVariables().get("var")); - assertEquals("[b, e]",result.getMatrixVariables().get("var").get("a").toString()); - assertEquals("d",result.getMatrixVariables().get("var").getFirst("c")); - assertEquals("g",result.getMatrixVariables().get("var").getFirst("f")); + assertThat(result.getUriVariables().get("var")).isEqualTo("/abc/123_456/789"); + assertThat(result.getMatrixVariables().get("var").get("a").toString()).isEqualTo("[b, e]"); + assertThat(result.getMatrixVariables().get("var").getFirst("c")).isEqualTo("d"); + assertThat(result.getMatrixVariables().get("var").getFirst("f")).isEqualTo("g"); result = matchAndExtract("/abc/{var}","/abc/one"); - assertEquals("one",result.getUriVariables().get("var")); - assertNull(result.getMatrixVariables().get("var")); + assertThat(result.getUriVariables().get("var")).isEqualTo("one"); + assertThat(result.getMatrixVariables().get("var")).isNull(); result = matchAndExtract("",""); - assertNotNull(result); + assertThat(result).isNotNull(); result = matchAndExtract("","/"); - assertNotNull(result); + assertThat(result).isNotNull(); } private PathPattern.PathMatchInfo matchAndExtract(String pattern, String path) { @@ -1158,14 +1149,14 @@ public class PathPatternTests { parser.setMatchOptionalTrailingSeparator(true); PathPattern p = parser.parse(uriTemplate); PathContainer pc = toPathContainer(path); - assertTrue(p.matches(pc)); + assertThat(p.matches(pc)).isTrue(); } private void checkNoMatch(String uriTemplate, String path) { PathPatternParser p = new PathPatternParser(); PathPattern pattern = p.parse(uriTemplate); PathContainer PathContainer = toPathContainer(path); - assertFalse(pattern.matches(PathContainer)); + assertThat(pattern.matches(PathContainer)).isFalse(); } private PathPattern.PathMatchInfo checkCapture(String uriTemplate, String path, String... keyValues) { @@ -1187,7 +1178,7 @@ public class PathPatternTests { PathPatternParser ppp = new PathPatternParser(); PathPattern pp = ppp.parse(pattern); String s = pp.extractPathWithinPattern(toPathContainer(path)).value(); - assertEquals(expected, s); + assertThat(s).isEqualTo(expected); } private PathRemainingMatchInfo getPathRemaining(String pattern, String path) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java index f28e9b397ac..db9e2690ab9 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerErrorTests.java @@ -51,9 +51,6 @@ import org.springframework.web.server.WebHandler; import org.springframework.web.server.handler.ExceptionHandlingWebHandler; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; import static org.springframework.http.MediaType.APPLICATION_JSON; /** @@ -94,7 +91,7 @@ public class DispatcherHandlerErrorTests { // SPR-17475 AtomicReference exceptionRef = new AtomicReference<>(); StepVerifier.create(mono).consumeErrorWith(exceptionRef::set).verify(); - StepVerifier.create(mono).consumeErrorWith(ex -> assertNotSame(exceptionRef.get(), ex)).verify(); + StepVerifier.create(mono).consumeErrorWith(ex -> assertThat(ex).isNotSameAs(exceptionRef.get())).verify(); } @Test @@ -103,7 +100,7 @@ public class DispatcherHandlerErrorTests { Mono publisher = this.dispatcherHandler.handle(exchange); StepVerifier.create(publisher) - .consumeErrorWith(error -> assertSame(EXCEPTION, error)) + .consumeErrorWith(error -> assertThat(error).isSameAs(EXCEPTION)) .verify(); } @@ -113,7 +110,7 @@ public class DispatcherHandlerErrorTests { Mono publisher = this.dispatcherHandler.handle(exchange); StepVerifier.create(publisher) - .consumeErrorWith(error -> assertSame(EXCEPTION, error)) + .consumeErrorWith(error -> assertThat(error).isSameAs(EXCEPTION)) .verify(); } @@ -150,7 +147,7 @@ public class DispatcherHandlerErrorTests { Mono publisher = this.dispatcherHandler.handle(exchange); StepVerifier.create(publisher) - .consumeErrorWith(error -> assertSame(EXCEPTION, error)) + .consumeErrorWith(error -> assertThat(error).isSameAs(EXCEPTION)) .verify(); } @@ -162,7 +159,7 @@ public class DispatcherHandlerErrorTests { WebHandler webHandler = new ExceptionHandlingWebHandler(this.dispatcherHandler, handlers); webHandler.handle(exchange).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, exchange.getResponse().getStatusCode()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerTests.java index c89c92dd828..4a978fb9e56 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/DispatcherHandlerTests.java @@ -33,7 +33,7 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.method.ResolvableMethod; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -69,7 +69,7 @@ public class DispatcherHandlerTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); dispatcherHandler.handle(exchange).block(Duration.ofSeconds(0)); - assertEquals("1", exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(5))); + assertThat(exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(5))).isEqualTo("1"); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/FlushingIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/FlushingIntegrationTests.java index c057d790193..67bf56d4526 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/FlushingIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/FlushingIntegrationTests.java @@ -32,7 +32,7 @@ import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.web.reactive.function.client.WebClient; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for server response flushing behavior. @@ -77,7 +77,7 @@ public class FlushingIntegrationTests extends AbstractHttpHandlerIntegrationTest try { StepVerifier.create(result) - .consumeNextWith(value -> assertEquals(64 * 1024, value.length())) + .consumeNextWith(value -> assertThat(value.length()).isEqualTo((64 * 1024))) .expectComplete() .verify(Duration.ofSeconds(10L)); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/accept/HeaderContentTypeResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/accept/HeaderContentTypeResolverTests.java index 01441a5ab3a..f3fe5cd851e 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/accept/HeaderContentTypeResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/accept/HeaderContentTypeResolverTests.java @@ -25,8 +25,8 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.NotAcceptableStatusException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link HeaderContentTypeResolver}. @@ -44,11 +44,11 @@ public class HeaderContentTypeResolverTests { List mediaTypes = this.resolver.resolveMediaTypes( MockServerWebExchange.from(MockServerHttpRequest.get("/").header("accept", header))); - assertEquals(4, mediaTypes.size()); - assertEquals("text/html", mediaTypes.get(0).toString()); - assertEquals("text/x-c", mediaTypes.get(1).toString()); - assertEquals("text/x-dvi;q=0.8", mediaTypes.get(2).toString()); - assertEquals("text/plain;q=0.5", mediaTypes.get(3).toString()); + assertThat(mediaTypes.size()).isEqualTo(4); + assertThat(mediaTypes.get(0).toString()).isEqualTo("text/html"); + assertThat(mediaTypes.get(1).toString()).isEqualTo("text/x-c"); + assertThat(mediaTypes.get(2).toString()).isEqualTo("text/x-dvi;q=0.8"); + assertThat(mediaTypes.get(3).toString()).isEqualTo("text/plain;q=0.5"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/accept/ParameterContentTypeResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/accept/ParameterContentTypeResolverTests.java index 54f40f3dcd4..411b4693353 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/accept/ParameterContentTypeResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/accept/ParameterContentTypeResolverTests.java @@ -27,8 +27,8 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.NotAcceptableStatusException; import org.springframework.web.server.ServerWebExchange; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link ParameterContentTypeResolver}. @@ -42,7 +42,7 @@ public class ParameterContentTypeResolverTests { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); List mediaTypes = resolver.resolveMediaTypes(exchange); - assertEquals(RequestedContentTypeResolver.MEDIA_TYPE_ALL_LIST, mediaTypes); + assertThat(mediaTypes).isEqualTo(RequestedContentTypeResolver.MEDIA_TYPE_ALL_LIST); } @Test @@ -59,12 +59,12 @@ public class ParameterContentTypeResolverTests { Map mapping = Collections.emptyMap(); RequestedContentTypeResolver resolver = new ParameterContentTypeResolver(mapping); List mediaTypes = resolver.resolveMediaTypes(exchange); - assertEquals(Collections.singletonList(new MediaType("text", "html")), mediaTypes); + assertThat(mediaTypes).isEqualTo(Collections.singletonList(new MediaType("text", "html"))); mapping = Collections.singletonMap("HTML", MediaType.APPLICATION_XHTML_XML); resolver = new ParameterContentTypeResolver(mapping); mediaTypes = resolver.resolveMediaTypes(exchange); - assertEquals(Collections.singletonList(new MediaType("application", "xhtml+xml")), mediaTypes); + assertThat(mediaTypes).isEqualTo(Collections.singletonList(new MediaType("application", "xhtml+xml"))); } @Test @@ -73,7 +73,7 @@ public class ParameterContentTypeResolverTests { RequestedContentTypeResolver resolver = new ParameterContentTypeResolver(Collections.emptyMap()); List mediaTypes = resolver.resolveMediaTypes(exchange); - assertEquals(Collections.singletonList(new MediaType("application", "vnd.ms-excel")), mediaTypes); + assertThat(mediaTypes).isEqualTo(Collections.singletonList(new MediaType("application", "vnd.ms-excel"))); } @Test // SPR-13747 @@ -83,7 +83,7 @@ public class ParameterContentTypeResolverTests { ParameterContentTypeResolver resolver = new ParameterContentTypeResolver(mapping); List mediaTypes = resolver.resolveMediaTypes(exchange); - assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), mediaTypes); + assertThat(mediaTypes).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); } private MockServerWebExchange createExchange(String format) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/accept/RequestedContentTypeResolverBuilderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/accept/RequestedContentTypeResolverBuilderTests.java index 7344e832d71..e67016f15e3 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/accept/RequestedContentTypeResolverBuilderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/accept/RequestedContentTypeResolverBuilderTests.java @@ -24,7 +24,7 @@ import org.springframework.http.MediaType; import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link RequestedContentTypeResolverBuilder}. @@ -40,7 +40,7 @@ public class RequestedContentTypeResolverBuilderTests { MockServerHttpRequest.get("/flower").accept(MediaType.IMAGE_GIF)); List mediaTypes = resolver.resolveMediaTypes(exchange); - assertEquals(Collections.singletonList(MediaType.IMAGE_GIF), mediaTypes); + assertThat(mediaTypes).isEqualTo(Collections.singletonList(MediaType.IMAGE_GIF)); } @Test @@ -53,7 +53,7 @@ public class RequestedContentTypeResolverBuilderTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/flower?format=json")); List mediaTypes = resolver.resolveMediaTypes(exchange); - assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), mediaTypes); + assertThat(mediaTypes).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); } @Test @@ -66,7 +66,7 @@ public class RequestedContentTypeResolverBuilderTests { List mediaTypes = resolver.resolveMediaTypes( MockServerWebExchange.from(MockServerHttpRequest.get("/flower?s=json"))); - assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), mediaTypes); + assertThat(mediaTypes).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); } @Test // SPR-10513 @@ -79,7 +79,7 @@ public class RequestedContentTypeResolverBuilderTests { List mediaTypes = resolver.resolveMediaTypes( MockServerWebExchange.from(MockServerHttpRequest.get("/").accept(MediaType.ALL))); - assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), mediaTypes); + assertThat(mediaTypes).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); } @Test // SPR-12286 @@ -91,11 +91,11 @@ public class RequestedContentTypeResolverBuilderTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); List mediaTypes = resolver.resolveMediaTypes(exchange); - assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), mediaTypes); + assertThat(mediaTypes).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").accept(MediaType.ALL)); mediaTypes = resolver.resolveMediaTypes(exchange); - assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), mediaTypes); + assertThat(mediaTypes).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/config/CorsRegistryTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/config/CorsRegistryTests.java index e5c8f869054..6912238e02f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/config/CorsRegistryTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/config/CorsRegistryTests.java @@ -23,8 +23,7 @@ import org.junit.Test; import org.springframework.web.cors.CorsConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with a {@link CorsRegistry}. @@ -38,14 +37,14 @@ public class CorsRegistryTests { @Test public void noMapping() { - assertTrue(this.registry.getCorsConfigurations().isEmpty()); + assertThat(this.registry.getCorsConfigurations().isEmpty()).isTrue(); } @Test public void multipleMappings() { this.registry.addMapping("/foo"); this.registry.addMapping("/bar"); - assertEquals(2, this.registry.getCorsConfigurations().size()); + assertThat(this.registry.getCorsConfigurations().size()).isEqualTo(2); } @Test @@ -54,14 +53,14 @@ public class CorsRegistryTests { .allowedMethods("DELETE").allowCredentials(false).allowedHeaders("header1", "header2") .exposedHeaders("header3", "header4").maxAge(3600); Map configs = this.registry.getCorsConfigurations(); - assertEquals(1, configs.size()); + assertThat(configs.size()).isEqualTo(1); CorsConfiguration config = configs.get("/foo"); - assertEquals(Arrays.asList("https://domain2.com", "https://domain2.com"), config.getAllowedOrigins()); - assertEquals(Arrays.asList("DELETE"), config.getAllowedMethods()); - assertEquals(Arrays.asList("header1", "header2"), config.getAllowedHeaders()); - assertEquals(Arrays.asList("header3", "header4"), config.getExposedHeaders()); - assertEquals(false, config.getAllowCredentials()); - assertEquals(Long.valueOf(3600), config.getMaxAge()); + assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("https://domain2.com", "https://domain2.com")); + assertThat(config.getAllowedMethods()).isEqualTo(Arrays.asList("DELETE")); + assertThat(config.getAllowedHeaders()).isEqualTo(Arrays.asList("header1", "header2")); + assertThat(config.getExposedHeaders()).isEqualTo(Arrays.asList("header3", "header4")); + assertThat(config.getAllowCredentials()).isEqualTo(false); + assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(3600)); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/config/DelegatingWebFluxConfigurationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/config/DelegatingWebFluxConfigurationTests.java index 79c38848159..8be8f224719 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/config/DelegatingWebFluxConfigurationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/config/DelegatingWebFluxConfigurationTests.java @@ -37,10 +37,7 @@ import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willAnswer; @@ -106,10 +103,11 @@ public class DelegatingWebFluxConfigurationTests { verify(webFluxConfigurer).addFormatters(formatterRegistry.capture()); verify(webFluxConfigurer).configureArgumentResolvers(any()); - assertNotNull(initializer); - assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean); - assertSame(formatterRegistry.getValue(), initializer.getConversionService()); - assertEquals(13, codecsConfigurer.getValue().getReaders().size()); + assertThat(initializer).isNotNull(); + boolean condition = initializer.getValidator() instanceof LocalValidatorFactoryBean; + assertThat(condition).isTrue(); + assertThat(initializer.getConversionService()).isSameAs(formatterRegistry.getValue()); + assertThat(codecsConfigurer.getValue().getReaders().size()).isEqualTo(13); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/config/ResourceHandlerRegistryTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/config/ResourceHandlerRegistryTests.java index 491e954ea12..be51c6a5eda 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/config/ResourceHandlerRegistryTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/config/ResourceHandlerRegistryTests.java @@ -49,10 +49,6 @@ import org.springframework.web.reactive.resource.VersionResourceResolver; import org.springframework.web.reactive.resource.WebJarsResourceResolver; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link ResourceHandlerRegistry}. @@ -77,7 +73,7 @@ public class ResourceHandlerRegistryTests { @Test public void noResourceHandlers() throws Exception { this.registry = new ResourceHandlerRegistry(new GenericApplicationContext()); - assertNull(this.registry.getHandlerMapping()); + assertThat((Object) this.registry.getHandlerMapping()).isNull(); } @Test @@ -90,8 +86,7 @@ public class ResourceHandlerRegistryTests { handler.handle(exchange).block(Duration.ofSeconds(5)); StepVerifier.create(exchange.getResponse().getBody()) - .consumeNextWith(buf -> assertEquals("test stylesheet content", - DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8))) + .consumeNextWith(buf -> assertThat(DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8)).isEqualTo("test stylesheet content")) .expectComplete() .verify(); } @@ -107,16 +102,16 @@ public class ResourceHandlerRegistryTests { @Test public void order() { - assertEquals(Integer.MAX_VALUE -1, this.registry.getHandlerMapping().getOrder()); + assertThat(this.registry.getHandlerMapping().getOrder()).isEqualTo(Integer.MAX_VALUE -1); this.registry.setOrder(0); - assertEquals(0, this.registry.getHandlerMapping().getOrder()); + assertThat(this.registry.getHandlerMapping().getOrder()).isEqualTo(0); } @Test public void hasMappingForPattern() { - assertTrue(this.registry.hasMappingForPattern("/resources/**")); - assertFalse(this.registry.hasMappingForPattern("/whatever")); + assertThat(this.registry.hasMappingForPattern("/resources/**")).isTrue(); + assertThat(this.registry.hasMappingForPattern("/whatever")).isFalse(); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/config/ViewResolverRegistryTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/config/ViewResolverRegistryTests.java index fd410c4e6ac..04b9f5d4819 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/config/ViewResolverRegistryTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/config/ViewResolverRegistryTests.java @@ -32,11 +32,7 @@ import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigu import org.springframework.web.reactive.result.view.script.ScriptTemplateConfigurer; import org.springframework.web.reactive.result.view.script.ScriptTemplateViewResolver; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ViewResolverRegistry}. @@ -60,22 +56,22 @@ public class ViewResolverRegistryTests { @Test public void order() { - assertEquals(Ordered.LOWEST_PRECEDENCE, this.registry.getOrder()); + assertThat(this.registry.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); } @Test public void hasRegistrations() { - assertFalse(this.registry.hasRegistrations()); + assertThat(this.registry.hasRegistrations()).isFalse(); this.registry.freeMarker(); - assertTrue(this.registry.hasRegistrations()); + assertThat(this.registry.hasRegistrations()).isTrue(); } @Test public void noResolvers() { - assertNotNull(this.registry.getViewResolvers()); - assertEquals(0, this.registry.getViewResolvers().size()); - assertFalse(this.registry.hasRegistrations()); + assertThat(this.registry.getViewResolvers()).isNotNull(); + assertThat(this.registry.getViewResolvers().size()).isEqualTo(0); + assertThat(this.registry.hasRegistrations()).isFalse(); } @Test @@ -83,8 +79,8 @@ public class ViewResolverRegistryTests { UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); this.registry.viewResolver(viewResolver); - assertSame(viewResolver, this.registry.getViewResolvers().get(0)); - assertEquals(1, this.registry.getViewResolvers().size()); + assertThat(this.registry.getViewResolvers().get(0)).isSameAs(viewResolver); + assertThat(this.registry.getViewResolvers().size()).isEqualTo(1); } @Test @@ -92,8 +88,8 @@ public class ViewResolverRegistryTests { View view = new HttpMessageWriterView(new Jackson2JsonEncoder()); this.registry.defaultViews(view); - assertEquals(1, this.registry.getDefaultViews().size()); - assertSame(view, this.registry.getDefaultViews().get(0)); + assertThat(this.registry.getDefaultViews().size()).isEqualTo(1); + assertThat(this.registry.getDefaultViews().get(0)).isSameAs(view); } @Test // SPR-16431 @@ -101,11 +97,11 @@ public class ViewResolverRegistryTests { this.registry.scriptTemplate().prefix("/").suffix(".html"); List viewResolvers = this.registry.getViewResolvers(); - assertEquals(1, viewResolvers.size()); - assertEquals(ScriptTemplateViewResolver.class, viewResolvers.get(0).getClass()); + assertThat(viewResolvers.size()).isEqualTo(1); + assertThat(viewResolvers.get(0).getClass()).isEqualTo(ScriptTemplateViewResolver.class); DirectFieldAccessor accessor = new DirectFieldAccessor(viewResolvers.get(0)); - assertEquals("/", accessor.getPropertyValue("prefix")); - assertEquals(".html", accessor.getPropertyValue("suffix")); + assertThat(accessor.getPropertyValue("prefix")).isEqualTo("/"); + assertThat(accessor.getPropertyValue("suffix")).isEqualTo(".html"); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/config/WebFluxConfigurationSupportTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/config/WebFluxConfigurationSupportTests.java index fee6032e94c..11f9dd1f52f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/config/WebFluxConfigurationSupportTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/config/WebFluxConfigurationSupportTests.java @@ -76,11 +76,7 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebHandler; import org.springframework.web.util.pattern.PathPatternParser; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.springframework.core.ResolvableType.forClass; import static org.springframework.core.ResolvableType.forClassWithGenerics; @@ -107,21 +103,21 @@ public class WebFluxConfigurationSupportTests { String name = "requestMappingHandlerMapping"; RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class); - assertNotNull(mapping); + assertThat(mapping).isNotNull(); - assertEquals(0, mapping.getOrder()); + assertThat(mapping.getOrder()).isEqualTo(0); PathPatternParser patternParser = mapping.getPathPatternParser(); - assertNotNull(patternParser); + assertThat(patternParser).isNotNull(); boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser); - assertTrue(matchOptionalTrailingSlash); + assertThat(matchOptionalTrailingSlash).isTrue(); name = "webFluxContentTypeResolver"; RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class); - assertSame(resolver, mapping.getContentTypeResolver()); + assertThat(mapping.getContentTypeResolver()).isSameAs(resolver); ServerWebExchange exchange = MockServerWebExchange.from(get("/path").accept(MediaType.APPLICATION_JSON)); - assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), resolver.resolveMediaTypes(exchange)); + assertThat(resolver.resolveMediaTypes(exchange)).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); } @Test @@ -132,17 +128,16 @@ public class WebFluxConfigurationSupportTests { String name = "requestMappingHandlerMapping"; RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class); - assertNotNull(mapping); + assertThat(mapping).isNotNull(); PathPatternParser patternParser = mapping.getPathPatternParser(); - assertNotNull(patternParser); + assertThat(patternParser).isNotNull(); boolean matchOptionalTrailingSlash = (boolean) ReflectionUtils.getField(field, patternParser); - assertFalse(matchOptionalTrailingSlash); + assertThat(matchOptionalTrailingSlash).isFalse(); Map map = mapping.getHandlerMethods(); - assertEquals(1, map.size()); - assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")), - map.keySet().iterator().next().getPatternsCondition().getPatterns()); + assertThat(map.size()).isEqualTo(1); + assertThat(map.keySet().iterator().next().getPatternsCondition().getPatterns()).isEqualTo(Collections.singleton(new PathPatternParser().parse("/api/user/{id}"))); } @Test @@ -151,10 +146,10 @@ public class WebFluxConfigurationSupportTests { String name = "requestMappingHandlerAdapter"; RequestMappingHandlerAdapter adapter = context.getBean(name, RequestMappingHandlerAdapter.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); List> readers = adapter.getMessageReaders(); - assertEquals(13, readers.size()); + assertThat(readers.size()).isEqualTo(13); ResolvableType multiValueMapType = forClassWithGenerics(MultiValueMap.class, String.class, String.class); @@ -170,17 +165,17 @@ public class WebFluxConfigurationSupportTests { assertHasMessageReader(readers, forClass(TestBean.class), null); WebBindingInitializer bindingInitializer = adapter.getWebBindingInitializer(); - assertNotNull(bindingInitializer); + assertThat(bindingInitializer).isNotNull(); WebExchangeDataBinder binder = new WebExchangeDataBinder(new Object()); bindingInitializer.initBinder(binder); name = "webFluxConversionService"; ConversionService service = context.getBean(name, ConversionService.class); - assertSame(service, binder.getConversionService()); + assertThat(binder.getConversionService()).isSameAs(service); name = "webFluxValidator"; Validator validator = context.getBean(name, Validator.class); - assertSame(validator, binder.getValidator()); + assertThat(binder.getValidator()).isSameAs(validator); } @Test @@ -189,10 +184,10 @@ public class WebFluxConfigurationSupportTests { String name = "requestMappingHandlerAdapter"; RequestMappingHandlerAdapter adapter = context.getBean(name, RequestMappingHandlerAdapter.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); List> messageReaders = adapter.getMessageReaders(); - assertEquals(2, messageReaders.size()); + assertThat(messageReaders.size()).isEqualTo(2); assertHasMessageReader(messageReaders, forClass(String.class), TEXT_PLAIN); assertHasMessageReader(messageReaders, forClass(TestBean.class), APPLICATION_XML); @@ -204,12 +199,12 @@ public class WebFluxConfigurationSupportTests { String name = "responseEntityResultHandler"; ResponseEntityResultHandler handler = context.getBean(name, ResponseEntityResultHandler.class); - assertNotNull(handler); + assertThat(handler).isNotNull(); - assertEquals(0, handler.getOrder()); + assertThat(handler.getOrder()).isEqualTo(0); List> writers = handler.getMessageWriters(); - assertEquals(11, writers.size()); + assertThat(writers.size()).isEqualTo(11); assertHasMessageWriter(writers, forClass(byte[].class), APPLICATION_OCTET_STREAM); assertHasMessageWriter(writers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM); @@ -223,7 +218,7 @@ public class WebFluxConfigurationSupportTests { name = "webFluxContentTypeResolver"; RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class); - assertSame(resolver, handler.getContentTypeResolver()); + assertThat(handler.getContentTypeResolver()).isSameAs(resolver); } @Test @@ -232,12 +227,12 @@ public class WebFluxConfigurationSupportTests { String name = "responseBodyResultHandler"; ResponseBodyResultHandler handler = context.getBean(name, ResponseBodyResultHandler.class); - assertNotNull(handler); + assertThat(handler).isNotNull(); - assertEquals(100, handler.getOrder()); + assertThat(handler.getOrder()).isEqualTo(100); List> writers = handler.getMessageWriters(); - assertEquals(11, writers.size()); + assertThat(writers.size()).isEqualTo(11); assertHasMessageWriter(writers, forClass(byte[].class), APPLICATION_OCTET_STREAM); assertHasMessageWriter(writers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM); @@ -251,7 +246,7 @@ public class WebFluxConfigurationSupportTests { name = "webFluxContentTypeResolver"; RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class); - assertSame(resolver, handler.getContentTypeResolver()); + assertThat(handler.getContentTypeResolver()).isSameAs(resolver); } @Test @@ -260,19 +255,19 @@ public class WebFluxConfigurationSupportTests { String name = "viewResolutionResultHandler"; ViewResolutionResultHandler handler = context.getBean(name, ViewResolutionResultHandler.class); - assertNotNull(handler); + assertThat(handler).isNotNull(); - assertEquals(Ordered.LOWEST_PRECEDENCE, handler.getOrder()); + assertThat(handler.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); List resolvers = handler.getViewResolvers(); - assertEquals(1, resolvers.size()); - assertEquals(FreeMarkerViewResolver.class, resolvers.get(0).getClass()); + assertThat(resolvers.size()).isEqualTo(1); + assertThat(resolvers.get(0).getClass()).isEqualTo(FreeMarkerViewResolver.class); List views = handler.getDefaultViews(); - assertEquals(1, views.size()); + assertThat(views.size()).isEqualTo(1); MimeType type = MimeTypeUtils.parseMimeType("application/json"); - assertEquals(type, views.get(0).getSupportedMediaTypes().get(0)); + assertThat(views.get(0).getSupportedMediaTypes().get(0)).isEqualTo(type); } @Test @@ -281,13 +276,13 @@ public class WebFluxConfigurationSupportTests { String name = "resourceHandlerMapping"; AbstractUrlHandlerMapping handlerMapping = context.getBean(name, AbstractUrlHandlerMapping.class); - assertNotNull(handlerMapping); + assertThat(handlerMapping).isNotNull(); - assertEquals(Ordered.LOWEST_PRECEDENCE - 1, handlerMapping.getOrder()); + assertThat(handlerMapping.getOrder()).isEqualTo((Ordered.LOWEST_PRECEDENCE - 1)); SimpleUrlHandlerMapping urlHandlerMapping = (SimpleUrlHandlerMapping) handlerMapping; WebHandler webHandler = (WebHandler) urlHandlerMapping.getUrlMap().get("/images/**"); - assertNotNull(webHandler); + assertThat(webHandler).isNotNull(); } @Test @@ -296,16 +291,16 @@ public class WebFluxConfigurationSupportTests { String name = "resourceUrlProvider"; ResourceUrlProvider resourceUrlProvider = context.getBean(name, ResourceUrlProvider.class); - assertNotNull(resourceUrlProvider); + assertThat(resourceUrlProvider).isNotNull(); } private void assertHasMessageReader(List> readers, ResolvableType type, MediaType mediaType) { - assertTrue(readers.stream().anyMatch(c -> mediaType == null || c.canRead(type, mediaType))); + assertThat(readers.stream().anyMatch(c -> mediaType == null || c.canRead(type, mediaType))).isTrue(); } private void assertHasMessageWriter(List> writers, ResolvableType type, MediaType mediaType) { - assertTrue(writers.stream().anyMatch(c -> mediaType == null || c.canWrite(type, mediaType))); + assertThat(writers.stream().anyMatch(c -> mediaType == null || c.canWrite(type, mediaType))).isTrue(); } private ApplicationContext loadConfig(Class... configurationClasses) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyExtractorsTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyExtractorsTests.java index 8fc483adb9f..f3ef2faee6b 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyExtractorsTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyExtractorsTests.java @@ -63,10 +63,8 @@ import org.springframework.mock.http.client.reactive.test.MockClientHttpResponse import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.springframework.http.codec.json.Jackson2CodecSupport.JSON_VIEW_HINT; /** @@ -175,8 +173,8 @@ public class BodyExtractorsTests { StepVerifier.create(result) .consumeNextWith(user -> { - assertEquals("foo", user.getUsername()); - assertNull(user.getPassword()); + assertThat(user.getUsername()).isEqualTo("foo"); + assertThat(user.getPassword()).isNull(); }) .expectComplete() .verify(); @@ -266,12 +264,12 @@ public class BodyExtractorsTests { StepVerifier.create(result) .consumeNextWith(user -> { - assertEquals("foo", user.getUsername()); - assertNull(user.getPassword()); + assertThat(user.getUsername()).isEqualTo("foo"); + assertThat(user.getPassword()).isNull(); }) .consumeNextWith(user -> { - assertEquals("bar", user.getUsername()); - assertNull(user.getPassword()); + assertThat(user.getUsername()).isEqualTo("bar"); + assertThat(user.getPassword()).isNull(); }) .expectComplete() .verify(); @@ -328,13 +326,13 @@ public class BodyExtractorsTests { StepVerifier.create(result) .consumeNextWith(form -> { - assertEquals("Invalid result", 3, form.size()); - assertEquals("Invalid result", "value 1", form.getFirst("name 1")); + assertThat(form.size()).as("Invalid result").isEqualTo(3); + assertThat(form.getFirst("name 1")).as("Invalid result").isEqualTo("value 1"); List values = form.get("name 2"); - assertEquals("Invalid result", 2, values.size()); - assertEquals("Invalid result", "value 2+1", values.get(0)); - assertEquals("Invalid result", "value 2+2", values.get(1)); - assertNull("Invalid result", form.getFirst("name 3")); + assertThat(values.size()).as("Invalid result").isEqualTo(2); + assertThat(values.get(0)).as("Invalid result").isEqualTo("value 2+1"); + assertThat(values.get(1)).as("Invalid result").isEqualTo("value 2+2"); + assertThat(form.getFirst("name 3")).as("Invalid result").isNull(); }) .expectComplete() .verify(); @@ -375,24 +373,27 @@ public class BodyExtractorsTests { StepVerifier.create(result) .consumeNextWith(part -> { - assertEquals("text", part.name()); - assertTrue(part instanceof FormFieldPart); + assertThat(part.name()).isEqualTo("text"); + boolean condition = part instanceof FormFieldPart; + assertThat(condition).isTrue(); FormFieldPart formFieldPart = (FormFieldPart) part; - assertEquals("text default", formFieldPart.value()); + assertThat(formFieldPart.value()).isEqualTo("text default"); }) .consumeNextWith(part -> { - assertEquals("file1", part.name()); - assertTrue(part instanceof FilePart); + assertThat(part.name()).isEqualTo("file1"); + boolean condition = part instanceof FilePart; + assertThat(condition).isTrue(); FilePart filePart = (FilePart) part; - assertEquals("a.txt", filePart.filename()); - assertEquals(MediaType.TEXT_PLAIN, filePart.headers().getContentType()); + assertThat(filePart.filename()).isEqualTo("a.txt"); + assertThat(filePart.headers().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); }) .consumeNextWith(part -> { - assertEquals("file2", part.name()); - assertTrue(part instanceof FilePart); + assertThat(part.name()).isEqualTo("file2"); + boolean condition = part instanceof FilePart; + assertThat(condition).isTrue(); FilePart filePart = (FilePart) part; - assertEquals("a.html", filePart.filename()); - assertEquals(MediaType.TEXT_HTML, filePart.headers().getContentType()); + assertThat(filePart.filename()).isEqualTo("a.html"); + assertThat(filePart.headers().getContentType()).isEqualTo(MediaType.TEXT_HTML); }) .expectComplete() .verify(); @@ -433,7 +434,8 @@ public class BodyExtractorsTests { body.emit(buffer); }) .expectErrorSatisfies(throwable -> { - assertTrue(throwable instanceof UnsupportedMediaTypeException); + boolean condition = throwable instanceof UnsupportedMediaTypeException; + assertThat(condition).isTrue(); assertThatExceptionOfType(IllegalReferenceCountException.class).isThrownBy( buffer::release); body.assertCancelled(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyInsertersTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyInsertersTests.java index 079231ed613..39076cac077 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyInsertersTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyInsertersTests.java @@ -68,8 +68,6 @@ import org.springframework.util.MultiValueMap; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; import static org.springframework.http.codec.json.Jackson2CodecSupport.JSON_VIEW_HINT; /** @@ -126,7 +124,7 @@ public class BodyInsertersTests { StepVerifier.create(response.getBody()) .consumeNextWith(buf -> { String actual = DataBufferTestUtils.dumpString(buf, UTF_8); - assertEquals("foo", actual); + assertThat(actual).isEqualTo("foo"); }) .expectComplete() .verify(); @@ -172,7 +170,7 @@ public class BodyInsertersTests { StepVerifier.create(response.getBody()) .consumeNextWith(buf -> { String actual = DataBufferTestUtils.dumpString(buf, UTF_8); - assertEquals("foo", actual); + assertThat(actual).isEqualTo("foo"); }) .expectComplete() .verify(); @@ -194,7 +192,7 @@ public class BodyInsertersTests { byte[] resultBytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(resultBytes); DataBufferUtils.release(dataBuffer); - assertArrayEquals(expectedBytes, resultBytes); + assertThat(resultBytes).isEqualTo(expectedBytes); }) .expectComplete() .verify(); @@ -237,7 +235,7 @@ public class BodyInsertersTests { byte[] resultBytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(resultBytes); DataBufferUtils.release(dataBuffer); - assertArrayEquals(expectedBytes, resultBytes); + assertThat(resultBytes).isEqualTo(expectedBytes); }) .expectComplete() .verify(); @@ -275,8 +273,7 @@ public class BodyInsertersTests { byte[] resultBytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(resultBytes); DataBufferUtils.release(dataBuffer); - assertArrayEquals("name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3".getBytes(StandardCharsets.UTF_8), - resultBytes); + assertThat(resultBytes).isEqualTo("name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3".getBytes(StandardCharsets.UTF_8)); }) .expectComplete() .verify(); @@ -300,8 +297,7 @@ public class BodyInsertersTests { byte[] resultBytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(resultBytes); DataBufferUtils.release(dataBuffer); - assertArrayEquals("name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3".getBytes(StandardCharsets.UTF_8), - resultBytes); + assertThat(resultBytes).isEqualTo("name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3".getBytes(StandardCharsets.UTF_8)); }) .expectComplete() .verify(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/MultipartIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/MultipartIntegrationTests.java index 548f6e1437a..8893b7e6a66 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/MultipartIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/MultipartIntegrationTests.java @@ -37,7 +37,7 @@ import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.server.RequestPredicates.POST; import static org.springframework.web.reactive.function.server.RouterFunctions.route; @@ -59,7 +59,7 @@ public class MultipartIntegrationTests extends AbstractRouterFunctionIntegration StepVerifier .create(result) - .consumeNextWith(response -> assertEquals(HttpStatus.OK, response.statusCode())) + .consumeNextWith(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK)) .verifyComplete(); } @@ -73,7 +73,7 @@ public class MultipartIntegrationTests extends AbstractRouterFunctionIntegration StepVerifier .create(result) - .consumeNextWith(response -> assertEquals(HttpStatus.OK, response.statusCode())) + .consumeNextWith(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK)) .verifyComplete(); } @@ -100,9 +100,9 @@ public class MultipartIntegrationTests extends AbstractRouterFunctionIntegration .flatMap(map -> { Map parts = map.toSingleValueMap(); try { - assertEquals(2, parts.size()); - assertEquals("foo.txt", ((FilePart) parts.get("fooPart")).filename()); - assertEquals("bar", ((FormFieldPart) parts.get("barPart")).value()); + assertThat(parts.size()).isEqualTo(2); + assertThat(((FilePart) parts.get("fooPart")).filename()).isEqualTo("foo.txt"); + assertThat(((FormFieldPart) parts.get("barPart")).value()).isEqualTo("bar"); } catch(Exception e) { return Mono.error(e); @@ -115,9 +115,9 @@ public class MultipartIntegrationTests extends AbstractRouterFunctionIntegration return request.body(BodyExtractors.toParts()).collectList() .flatMap(parts -> { try { - assertEquals(2, parts.size()); - assertEquals("foo.txt", ((FilePart) parts.get(0)).filename()); - assertEquals("bar", ((FormFieldPart) parts.get(1)).value()); + assertThat(parts.size()).isEqualTo(2); + assertThat(((FilePart) parts.get(0)).filename()).isEqualTo("foo.txt"); + assertThat(((FormFieldPart) parts.get(1)).value()).isEqualTo("bar"); } catch(Exception e) { return Mono.error(e); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java index 0b5bea0318d..6148cd4a993 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java @@ -37,8 +37,7 @@ import org.springframework.mock.http.client.reactive.test.MockClientHttpRequest; import org.springframework.web.reactive.function.BodyInserter; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.http.HttpMethod.DELETE; @@ -60,22 +59,22 @@ public class DefaultClientRequestBuilderTests { .headers(httpHeaders -> httpHeaders.set("foo", "baar")) .cookies(cookies -> cookies.set("baz", "quux")) .build(); - assertEquals(new URI("https://example.com"), result.url()); - assertEquals(GET, result.method()); - assertEquals(1, result.headers().size()); - assertEquals("baar", result.headers().getFirst("foo")); - assertEquals(1, result.cookies().size()); - assertEquals("quux", result.cookies().getFirst("baz")); + assertThat(result.url()).isEqualTo(new URI("https://example.com")); + assertThat(result.method()).isEqualTo(GET); + assertThat(result.headers().size()).isEqualTo(1); + assertThat(result.headers().getFirst("foo")).isEqualTo("baar"); + assertThat(result.cookies().size()).isEqualTo(1); + assertThat(result.cookies().getFirst("baz")).isEqualTo("quux"); } @Test public void method() throws URISyntaxException { URI url = new URI("https://example.com"); ClientRequest.Builder builder = ClientRequest.create(DELETE, url); - assertEquals(DELETE, builder.build().method()); + assertThat(builder.build().method()).isEqualTo(DELETE); builder.method(OPTIONS); - assertEquals(OPTIONS, builder.build().method()); + assertThat(builder.build().method()).isEqualTo(OPTIONS); } @Test @@ -83,17 +82,17 @@ public class DefaultClientRequestBuilderTests { URI url1 = new URI("https://example.com/foo"); URI url2 = new URI("https://example.com/bar"); ClientRequest.Builder builder = ClientRequest.create(DELETE, url1); - assertEquals(url1, builder.build().url()); + assertThat(builder.build().url()).isEqualTo(url1); builder.url(url2); - assertEquals(url2, builder.build().url()); + assertThat(builder.build().url()).isEqualTo(url2); } @Test public void cookie() { ClientRequest result = ClientRequest.create(GET, URI.create("https://example.com")) .cookie("foo", "bar").build(); - assertEquals("bar", result.cookies().getFirst("foo")); + assertThat(result.cookies().getFirst("foo")).isEqualTo("bar"); } @Test @@ -108,8 +107,8 @@ public class DefaultClientRequestBuilderTests { result.writeTo(request, strategies).block(); - assertEquals("MyValue", request.getHeaders().getFirst("MyKey")); - assertEquals("bar", request.getCookies().getFirst("foo").getValue()); + assertThat(request.getHeaders().getFirst("MyKey")).isEqualTo("MyValue"); + assertThat(request.getCookies().getFirst("foo").getValue()).isEqualTo("bar"); StepVerifier.create(request.getBody()).expectComplete().verify(); } @@ -135,7 +134,7 @@ public class DefaultClientRequestBuilderTests { MockClientHttpRequest request = new MockClientHttpRequest(GET, "/"); result.writeTo(request, strategies).block(); - assertNotNull(request.getBody()); + assertThat(request.getBody()).isNotNull(); StepVerifier.create(request.getBody()) .expectNextCount(1) @@ -157,7 +156,7 @@ public class DefaultClientRequestBuilderTests { MockClientHttpRequest request = new MockClientHttpRequest(GET, "/"); result.writeTo(request, strategies).block(); - assertNotNull(request.getBody()); + assertThat(request.getBody()).isNotNull(); StepVerifier.create(request.getBody()) .expectNextCount(1) @@ -180,7 +179,7 @@ public class DefaultClientRequestBuilderTests { MockClientHttpRequest request = new MockClientHttpRequest(GET, "/"); result.writeTo(request, strategies).block(); - assertNotNull(request.getBody()); + assertThat(request.getBody()).isNotNull(); StepVerifier.create(request.getBody()) .expectNextCount(1) diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilderTests.java index 6484ce056ea..f6a2da2f35f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilderTests.java @@ -30,8 +30,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseCookie; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -57,11 +56,11 @@ public class DefaultClientResponseBuilderTests { .body(body) .build(); - assertEquals(HttpStatus.BAD_GATEWAY, response.statusCode()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_GATEWAY); HttpHeaders responseHeaders = response.headers().asHttpHeaders(); - assertEquals("bar", responseHeaders.getFirst("foo")); - assertNotNull("qux", response.cookies().getFirst("baz")); - assertEquals("qux", response.cookies().getFirst("baz").getValue()); + assertThat(responseHeaders.getFirst("foo")).isEqualTo("bar"); + assertThat(response.cookies().getFirst("baz")).as("qux").isNotNull(); + assertThat(response.cookies().getFirst("baz").getValue()).isEqualTo("qux"); StepVerifier.create(response.bodyToFlux(String.class)) .expectNext("baz") @@ -90,11 +89,11 @@ public class DefaultClientResponseBuilderTests { .body(body) .build(); - assertEquals(HttpStatus.BAD_REQUEST, result.statusCode()); - assertEquals(1, result.headers().asHttpHeaders().size()); - assertEquals("baar", result.headers().asHttpHeaders().getFirst("foo")); - assertEquals(1, result.cookies().size()); - assertEquals("quux", result.cookies().getFirst("baz").getValue()); + assertThat(result.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(result.headers().asHttpHeaders().size()).isEqualTo(1); + assertThat(result.headers().asHttpHeaders().getFirst("foo")).isEqualTo("baar"); + assertThat(result.cookies().size()).isEqualTo(1); + assertThat(result.cookies().getFirst("baz").getValue()).isEqualTo("quux"); StepVerifier.create(result.bodyToFlux(String.class)) .expectNext("baz") diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseTests.java index 905d1642dd9..86f9c4cc982 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientResponseTests.java @@ -46,9 +46,8 @@ import org.springframework.http.codec.HttpMessageReader; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.web.reactive.function.BodyExtractors.toMono; @@ -79,7 +78,7 @@ public class DefaultClientResponseTests { HttpStatus status = HttpStatus.CONTINUE; given(mockResponse.getStatusCode()).willReturn(status); - assertEquals(status, defaultClientResponse.statusCode()); + assertThat(defaultClientResponse.statusCode()).isEqualTo(status); } @Test @@ -87,7 +86,7 @@ public class DefaultClientResponseTests { int status = 999; given(mockResponse.getRawStatusCode()).willReturn(status); - assertEquals(status, defaultClientResponse.rawStatusCode()); + assertThat(defaultClientResponse.rawStatusCode()).isEqualTo(status); } @Test @@ -105,9 +104,9 @@ public class DefaultClientResponseTests { given(mockResponse.getHeaders()).willReturn(httpHeaders); ClientResponse.Headers headers = defaultClientResponse.headers(); - assertEquals(OptionalLong.of(contentLength), headers.contentLength()); - assertEquals(Optional.of(contentType), headers.contentType()); - assertEquals(httpHeaders, headers.asHttpHeaders()); + assertThat(headers.contentLength()).isEqualTo(OptionalLong.of(contentLength)); + assertThat(headers.contentType()).isEqualTo(Optional.of(contentType)); + assertThat(headers.asHttpHeaders()).isEqualTo(httpHeaders); } @Test @@ -118,7 +117,7 @@ public class DefaultClientResponseTests { given(mockResponse.getCookies()).willReturn(cookies); - assertSame(cookies, defaultClientResponse.cookies()); + assertThat(defaultClientResponse.cookies()).isSameAs(cookies); } @@ -135,7 +134,7 @@ public class DefaultClientResponseTests { given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders); Mono resultMono = defaultClientResponse.body(toMono(String.class)); - assertEquals("foo", resultMono.block()); + assertThat(resultMono.block()).isEqualTo("foo"); } @Test @@ -151,7 +150,7 @@ public class DefaultClientResponseTests { given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders); Mono resultMono = defaultClientResponse.bodyToMono(String.class); - assertEquals("foo", resultMono.block()); + assertThat(resultMono.block()).isEqualTo("foo"); } @Test @@ -169,7 +168,7 @@ public class DefaultClientResponseTests { Mono resultMono = defaultClientResponse.bodyToMono(new ParameterizedTypeReference() { }); - assertEquals("foo", resultMono.block()); + assertThat(resultMono.block()).isEqualTo("foo"); } @Test @@ -186,7 +185,7 @@ public class DefaultClientResponseTests { Flux resultFlux = defaultClientResponse.bodyToFlux(String.class); Mono> result = resultFlux.collectList(); - assertEquals(Collections.singletonList("foo"), result.block()); + assertThat(result.block()).isEqualTo(Collections.singletonList("foo")); } @Test @@ -205,7 +204,7 @@ public class DefaultClientResponseTests { defaultClientResponse.bodyToFlux(new ParameterizedTypeReference() { }); Mono> result = resultFlux.collectList(); - assertEquals(Collections.singletonList("foo"), result.block()); + assertThat(result.block()).isEqualTo(Collections.singletonList("foo")); } @Test @@ -221,10 +220,10 @@ public class DefaultClientResponseTests { given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders); ResponseEntity result = defaultClientResponse.toEntity(String.class).block(); - assertEquals("foo", result.getBody()); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals(HttpStatus.OK.value(), result.getStatusCodeValue()); - assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); + assertThat(result.getBody()).isEqualTo("foo"); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value()); + assertThat(result.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); } @Test @@ -246,11 +245,11 @@ public class DefaultClientResponseTests { given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders); ResponseEntity result = defaultClientResponse.toEntity(String.class).block(); - assertEquals("foo", result.getBody()); + assertThat(result.getBody()).isEqualTo("foo"); assertThatIllegalArgumentException().isThrownBy( result::getStatusCode); - assertEquals(999, result.getStatusCodeValue()); - assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); + assertThat(result.getStatusCodeValue()).isEqualTo(999); + assertThat(result.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); } @Test @@ -268,10 +267,10 @@ public class DefaultClientResponseTests { ResponseEntity result = defaultClientResponse.toEntity( new ParameterizedTypeReference() { }).block(); - assertEquals("foo", result.getBody()); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals(HttpStatus.OK.value(), result.getStatusCodeValue()); - assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); + assertThat(result.getBody()).isEqualTo("foo"); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value()); + assertThat(result.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); } @Test @@ -287,10 +286,10 @@ public class DefaultClientResponseTests { given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders); ResponseEntity> result = defaultClientResponse.toEntityList(String.class).block(); - assertEquals(Collections.singletonList("foo"), result.getBody()); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals(HttpStatus.OK.value(), result.getStatusCodeValue()); - assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); + assertThat(result.getBody()).isEqualTo(Collections.singletonList("foo")); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value()); + assertThat(result.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); } @Test @@ -312,11 +311,11 @@ public class DefaultClientResponseTests { given(mockExchangeStrategies.messageReaders()).willReturn(messageReaders); ResponseEntity> result = defaultClientResponse.toEntityList(String.class).block(); - assertEquals(Collections.singletonList("foo"), result.getBody()); + assertThat(result.getBody()).isEqualTo(Collections.singletonList("foo")); assertThatIllegalArgumentException().isThrownBy( result::getStatusCode); - assertEquals(999, result.getStatusCodeValue()); - assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); + assertThat(result.getStatusCodeValue()).isEqualTo(999); + assertThat(result.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); } @Test @@ -335,10 +334,10 @@ public class DefaultClientResponseTests { ResponseEntity> result = defaultClientResponse.toEntityList( new ParameterizedTypeReference() { }).block(); - assertEquals(Collections.singletonList("foo"), result.getBody()); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals(HttpStatus.OK.value(), result.getStatusCodeValue()); - assertEquals(MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); + assertThat(result.getBody()).isEqualTo(Collections.singletonList("foo")); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value()); + assertThat(result.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java index ae15ab348e0..58c9d59a0cd 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java @@ -34,10 +34,8 @@ import org.springframework.core.NamedThreadLocal; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -76,9 +74,9 @@ public class DefaultWebClientTests { .exchange().block(Duration.ofSeconds(10)); ClientRequest request = verifyAndGetRequest(); - assertEquals("/base/path", request.url().toString()); - assertEquals(new HttpHeaders(), request.headers()); - assertEquals(Collections.emptyMap(), request.cookies()); + assertThat(request.url().toString()).isEqualTo("/base/path"); + assertThat(request.headers()).isEqualTo(new HttpHeaders()); + assertThat(request.cookies()).isEqualTo(Collections.emptyMap()); } @Test @@ -88,7 +86,7 @@ public class DefaultWebClientTests { .exchange().block(Duration.ofSeconds(10)); ClientRequest request = verifyAndGetRequest(); - assertEquals("/base/path?q=12", request.url().toString()); + assertThat(request.url().toString()).isEqualTo("/base/path?q=12"); } @Test // gh-22705 @@ -98,8 +96,8 @@ public class DefaultWebClientTests { .exchange().block(Duration.ofSeconds(10)); ClientRequest request = verifyAndGetRequest(); - assertEquals("/base/path/identifier?q=12", request.url().toString()); - assertEquals("/path/{id}", request.attribute(WebClient.class.getName() + ".uriTemplate").get()); + assertThat(request.url().toString()).isEqualTo("/base/path/identifier?q=12"); + assertThat(request.attribute(WebClient.class.getName() + ".uriTemplate").get()).isEqualTo("/path/{id}"); } @Test @@ -109,7 +107,7 @@ public class DefaultWebClientTests { .exchange().block(Duration.ofSeconds(10)); ClientRequest request = verifyAndGetRequest(); - assertEquals("/path", request.url().toString()); + assertThat(request.url().toString()).isEqualTo("/path"); } @Test @@ -119,8 +117,8 @@ public class DefaultWebClientTests { .exchange().block(Duration.ofSeconds(10)); ClientRequest request = verifyAndGetRequest(); - assertEquals("application/json", request.headers().getFirst("Accept")); - assertEquals("123", request.cookies().getFirst("id")); + assertThat(request.headers().getFirst("Accept")).isEqualTo("application/json"); + assertThat(request.cookies().getFirst("id")).isEqualTo("123"); } @Test @@ -132,8 +130,8 @@ public class DefaultWebClientTests { client.get().uri("/path").exchange().block(Duration.ofSeconds(10)); ClientRequest request = verifyAndGetRequest(); - assertEquals("application/json", request.headers().getFirst("Accept")); - assertEquals("123", request.cookies().getFirst("id")); + assertThat(request.headers().getFirst("Accept")).isEqualTo("application/json"); + assertThat(request.cookies().getFirst("id")).isEqualTo("123"); } @Test @@ -149,8 +147,8 @@ public class DefaultWebClientTests { .exchange().block(Duration.ofSeconds(10)); ClientRequest request = verifyAndGetRequest(); - assertEquals("application/xml", request.headers().getFirst("Accept")); - assertEquals("456", request.cookies().getFirst("id")); + assertThat(request.headers().getFirst("Accept")).isEqualTo("application/xml"); + assertThat(request.cookies().getFirst("id")).isEqualTo("456"); } @Test @@ -177,7 +175,7 @@ public class DefaultWebClientTests { context.remove(); } - assertEquals("bar", actual.get("foo")); + assertThat(actual.get("foo")).isEqualTo("bar"); } @Test @@ -214,19 +212,19 @@ public class DefaultWebClientTests { // Now, verify what each client has.. WebClient.Builder builder1 = client1.mutate(); - builder1.filters(filters -> assertEquals(1, filters.size())); - builder1.defaultHeaders(headers -> assertEquals(1, headers.size())); - builder1.defaultCookies(cookies -> assertEquals(1, cookies.size())); + builder1.filters(filters -> assertThat(filters.size()).isEqualTo(1)); + builder1.defaultHeaders(headers -> assertThat(headers.size()).isEqualTo(1)); + builder1.defaultCookies(cookies -> assertThat(cookies.size()).isEqualTo(1)); WebClient.Builder builder2 = client2.mutate(); - builder2.filters(filters -> assertEquals(2, filters.size())); - builder2.defaultHeaders(headers -> assertEquals(2, headers.size())); - builder2.defaultCookies(cookies -> assertEquals(2, cookies.size())); + builder2.filters(filters -> assertThat(filters.size()).isEqualTo(2)); + builder2.defaultHeaders(headers -> assertThat(headers.size()).isEqualTo(2)); + builder2.defaultCookies(cookies -> assertThat(cookies.size()).isEqualTo(2)); WebClient.Builder builder1a = client1a.mutate(); - builder1a.filters(filters -> assertEquals(2, filters.size())); - builder1a.defaultHeaders(headers -> assertEquals(2, headers.size())); - builder1a.defaultCookies(cookies -> assertEquals(2, cookies.size())); + builder1a.filters(filters -> assertThat(filters.size()).isEqualTo(2)); + builder1a.defaultHeaders(headers -> assertThat(headers.size()).isEqualTo(2)); + builder1a.defaultCookies(cookies -> assertThat(cookies.size()).isEqualTo(2)); } @Test @@ -242,10 +240,10 @@ public class DefaultWebClientTests { .attribute("foo", "bar") .exchange().block(Duration.ofSeconds(10)); - assertEquals("bar", actual.get("foo")); + assertThat(actual.get("foo")).isEqualTo("bar"); ClientRequest request = verifyAndGetRequest(); - assertEquals("bar", request.attribute("foo").get()); + assertThat(request.attribute("foo").get()).isEqualTo("bar"); } @Test @@ -261,10 +259,10 @@ public class DefaultWebClientTests { .attribute("foo", null) .exchange().block(Duration.ofSeconds(10)); - assertNull(actual.get("foo")); + assertThat(actual.get("foo")).isNull(); ClientRequest request = verifyAndGetRequest(); - assertFalse(request.attribute("foo").isPresent()); + assertThat(request.attribute("foo").isPresent()).isFalse(); } @Test @@ -278,8 +276,8 @@ public class DefaultWebClientTests { client.get().uri("/path").exchange().block(Duration.ofSeconds(10)); ClientRequest request = verifyAndGetRequest(); - assertEquals("application/json", request.headers().getFirst("Accept")); - assertEquals("123", request.cookies().getFirst("id")); + assertThat(request.headers().getFirst("Accept")).isEqualTo("application/json"); + assertThat(request.cookies().getFirst("id")).isEqualTo("123"); } @Test @@ -306,7 +304,7 @@ public class DefaultWebClientTests { verifyZeroInteractions(this.exchangeFunction); exchange.block(Duration.ofSeconds(10)); ClientRequest request = verifyAndGetRequest(); - assertEquals("value", request.headers().getFirst("Custom")); + assertThat(request.headers().getFirst("Custom")).isEqualTo("value"); } private ClientRequest verifyAndGetRequest() { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeFilterFunctionsTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeFilterFunctionsTests.java index 2516dbc5179..0f16e698be7 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeFilterFunctionsTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeFilterFunctionsTests.java @@ -33,10 +33,8 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.web.reactive.function.BodyExtractors; +import static org.assertj.core.api.Assertions.assertThat; 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.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -58,15 +56,15 @@ public class ExchangeFilterFunctionsTests { boolean[] filtersInvoked = new boolean[2]; ExchangeFilterFunction filter1 = (r, n) -> { - assertFalse(filtersInvoked[0]); - assertFalse(filtersInvoked[1]); + assertThat(filtersInvoked[0]).isFalse(); + assertThat(filtersInvoked[1]).isFalse(); filtersInvoked[0] = true; - assertFalse(filtersInvoked[1]); + assertThat(filtersInvoked[1]).isFalse(); return n.exchange(r); }; ExchangeFilterFunction filter2 = (r, n) -> { - assertTrue(filtersInvoked[0]); - assertFalse(filtersInvoked[1]); + assertThat(filtersInvoked[0]).isTrue(); + assertThat(filtersInvoked[1]).isFalse(); filtersInvoked[1] = true; return n.exchange(r); }; @@ -74,10 +72,10 @@ public class ExchangeFilterFunctionsTests { ClientResponse result = filter.filter(request, exchange).block(); - assertEquals(response, result); + assertThat(result).isEqualTo(response); - assertTrue(filtersInvoked[0]); - assertTrue(filtersInvoked[1]); + assertThat(filtersInvoked[0]).isTrue(); + assertThat(filtersInvoked[1]).isTrue(); } @Test @@ -88,15 +86,15 @@ public class ExchangeFilterFunctionsTests { boolean[] filterInvoked = new boolean[1]; ExchangeFilterFunction filter = (r, n) -> { - assertFalse(filterInvoked[0]); + assertThat(filterInvoked[0]).isFalse(); filterInvoked[0] = true; return n.exchange(r); }; ExchangeFunction filteredExchange = filter.apply(exchange); ClientResponse result = filteredExchange.exchange(request).block(); - assertEquals(response, result); - assertTrue(filterInvoked[0]); + assertThat(result).isEqualTo(response); + assertThat(filterInvoked[0]).isTrue(); } @Test @@ -105,15 +103,15 @@ public class ExchangeFilterFunctionsTests { ClientResponse response = mock(ClientResponse.class); ExchangeFunction exchange = r -> { - assertTrue(r.headers().containsKey(HttpHeaders.AUTHORIZATION)); - assertTrue(r.headers().getFirst(HttpHeaders.AUTHORIZATION).startsWith("Basic ")); + assertThat(r.headers().containsKey(HttpHeaders.AUTHORIZATION)).isTrue(); + assertThat(r.headers().getFirst(HttpHeaders.AUTHORIZATION).startsWith("Basic ")).isTrue(); return Mono.just(response); }; ExchangeFilterFunction auth = ExchangeFilterFunctions.basicAuthentication("foo", "bar"); - assertFalse(request.headers().containsKey(HttpHeaders.AUTHORIZATION)); + assertThat(request.headers().containsKey(HttpHeaders.AUTHORIZATION)).isFalse(); ClientResponse result = auth.filter(request, exchange).block(); - assertEquals(response, result); + assertThat(result).isEqualTo(response); } @Test @@ -135,15 +133,15 @@ public class ExchangeFilterFunctionsTests { ClientResponse response = mock(ClientResponse.class); ExchangeFunction exchange = r -> { - assertTrue(r.headers().containsKey(HttpHeaders.AUTHORIZATION)); - assertTrue(r.headers().getFirst(HttpHeaders.AUTHORIZATION).startsWith("Basic ")); + assertThat(r.headers().containsKey(HttpHeaders.AUTHORIZATION)).isTrue(); + assertThat(r.headers().getFirst(HttpHeaders.AUTHORIZATION).startsWith("Basic ")).isTrue(); return Mono.just(response); }; ExchangeFilterFunction auth = ExchangeFilterFunctions.basicAuthentication(); - assertFalse(request.headers().containsKey(HttpHeaders.AUTHORIZATION)); + assertThat(request.headers().containsKey(HttpHeaders.AUTHORIZATION)).isFalse(); ClientResponse result = auth.filter(request, exchange).block(); - assertEquals(response, result); + assertThat(result).isEqualTo(response); } @Test @@ -153,14 +151,14 @@ public class ExchangeFilterFunctionsTests { ClientResponse response = mock(ClientResponse.class); ExchangeFunction exchange = r -> { - assertFalse(r.headers().containsKey(HttpHeaders.AUTHORIZATION)); + assertThat(r.headers().containsKey(HttpHeaders.AUTHORIZATION)).isFalse(); return Mono.just(response); }; ExchangeFilterFunction auth = ExchangeFilterFunctions.basicAuthentication(); - assertFalse(request.headers().containsKey(HttpHeaders.AUTHORIZATION)); + assertThat(request.headers().containsKey(HttpHeaders.AUTHORIZATION)).isFalse(); ClientResponse result = auth.filter(request, exchange).block(); - assertEquals(response, result); + assertThat(result).isEqualTo(response); } @Test @@ -211,8 +209,8 @@ public class ExchangeFilterFunctionsTests { .filter(request, req -> Mono.just(response)); StepVerifier.create(result.flatMapMany(res -> res.body(BodyExtractors.toDataBuffers()))) - .consumeNextWith(buffer -> assertEquals("foo", string(buffer))) - .consumeNextWith(buffer -> assertEquals("ba", string(buffer))) + .consumeNextWith(buffer -> assertThat(string(buffer)).isEqualTo("foo")) + .consumeNextWith(buffer -> assertThat(string(buffer)).isEqualTo("ba")) .expectComplete() .verify(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeStrategiesTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeStrategiesTests.java index 3becc02939f..365b6b5f11d 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeStrategiesTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/ExchangeStrategiesTests.java @@ -18,8 +18,7 @@ package org.springframework.web.reactive.function.client; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -29,15 +28,15 @@ public class ExchangeStrategiesTests { @Test public void empty() { ExchangeStrategies strategies = ExchangeStrategies.empty().build(); - assertTrue(strategies.messageReaders().isEmpty()); - assertTrue(strategies.messageWriters().isEmpty()); + assertThat(strategies.messageReaders().isEmpty()).isTrue(); + assertThat(strategies.messageWriters().isEmpty()).isTrue(); } @Test public void withDefaults() { ExchangeStrategies strategies = ExchangeStrategies.withDefaults(); - assertFalse(strategies.messageReaders().isEmpty()); - assertFalse(strategies.messageWriters().isEmpty()); + assertThat(strategies.messageReaders().isEmpty()).isFalse(); + assertThat(strategies.messageWriters().isEmpty()).isFalse(); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientDataBufferAllocatingTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientDataBufferAllocatingTests.java index 3155c7cf4d4..d12c7fc467b 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientDataBufferAllocatingTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientDataBufferAllocatingTests.java @@ -38,8 +38,7 @@ import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.http.client.reactive.ReactorResourceFactory; import org.springframework.web.reactive.function.UnsupportedMediaTypeException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * WebClient integration tests focusing on data buffer management. @@ -105,7 +104,7 @@ public class WebClientDataBufferAllocatingTests extends AbstractDataBufferAlloca .bodyToMono(Void.class); StepVerifier.create(mono).expectComplete().verify(Duration.ofSeconds(3)); - assertEquals(1, this.server.getRequestCount()); + assertThat(this.server.getRequestCount()).isEqualTo(1); } @Test // SPR-17482 @@ -121,7 +120,7 @@ public class WebClientDataBufferAllocatingTests extends AbstractDataBufferAlloca .bodyToMono(new ParameterizedTypeReference>() {}); StepVerifier.create(mono).expectError(UnsupportedMediaTypeException.class).verify(Duration.ofSeconds(3)); - assertEquals(1, this.server.getRequestCount()); + assertThat(this.server.getRequestCount()).isEqualTo(1); } @Test @@ -164,8 +163,8 @@ public class WebClientDataBufferAllocatingTests extends AbstractDataBufferAlloca .onStatus(status -> status.equals(errorStatus), exceptionFunction) .bodyToMono(String.class); - StepVerifier.create(mono).expectErrorSatisfies(actual -> assertSame(expected, actual)).verify(DELAY); - assertEquals(1, this.server.getRequestCount()); + StepVerifier.create(mono).expectErrorSatisfies(actual -> assertThat(actual).isSameAs(expected)).verify(DELAY); + assertThat(this.server.getRequestCount()).isEqualTo(1); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java index 28eea503a0a..12cb207b46f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java @@ -56,10 +56,6 @@ import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.http.codec.Pojo; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Integration tests using an {@link ExchangeFunction} through {@link WebClient}. @@ -118,15 +114,15 @@ public class WebClientIntegrationTests { StepVerifier.create(result) .consumeNextWith( httpHeaders -> { - assertEquals(MediaType.TEXT_PLAIN, httpHeaders.getContentType()); - assertEquals(13L, httpHeaders.getContentLength()); + assertThat(httpHeaders.getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(httpHeaders.getContentLength()).isEqualTo(13L); }) .expectComplete().verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("/greeting?name=Spring", request.getPath()); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo("/greeting?name=Spring"); }); } @@ -146,9 +142,9 @@ public class WebClientIntegrationTests { expectRequestCount(1); expectRequest(request -> { - assertEquals("testvalue", request.getHeader("X-Test-Header")); - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("/greeting?name=Spring", request.getPath()); + assertThat(request.getHeader("X-Test-Header")).isEqualTo("testvalue"); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo("/greeting?name=Spring"); }); } @@ -168,9 +164,9 @@ public class WebClientIntegrationTests { expectRequestCount(1); expectRequest(request -> { - assertEquals("testvalue", request.getHeader("X-Test-Header")); - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("/greeting?name=Spring", request.getPath()); + assertThat(request.getHeader("X-Test-Header")).isEqualTo("testvalue"); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo("/greeting?name=Spring"); }); } @@ -191,8 +187,8 @@ public class WebClientIntegrationTests { expectRequestCount(1); expectRequest(request -> { - assertEquals("/json", request.getPath()); - assertEquals("application/json", request.getHeader(HttpHeaders.ACCEPT)); + assertThat(request.getPath()).isEqualTo("/json"); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("application/json"); }); } @@ -210,15 +206,15 @@ public class WebClientIntegrationTests { StepVerifier.create(result) .assertNext(valueContainer -> { Foo foo = valueContainer.getContainerValue(); - assertNotNull(foo); - assertEquals("bar", foo.getFooValue()); + assertThat(foo).isNotNull(); + assertThat(foo.getFooValue()).isEqualTo("bar"); }) .expectComplete().verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { - assertEquals("/json", request.getPath()); - assertEquals("application/json", request.getHeader(HttpHeaders.ACCEPT)); + assertThat(request.getPath()).isEqualTo("/json"); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("application/json"); }); } @@ -235,17 +231,17 @@ public class WebClientIntegrationTests { StepVerifier.create(result) .consumeNextWith(entity -> { - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(MediaType.APPLICATION_JSON, entity.getHeaders().getContentType()); - assertEquals(31, entity.getHeaders().getContentLength()); - assertEquals(content, entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON); + assertThat(entity.getHeaders().getContentLength()).isEqualTo(31); + assertThat(entity.getBody()).isEqualTo(content); }) .expectComplete().verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { - assertEquals("/json", request.getPath()); - assertEquals("application/json", request.getHeader(HttpHeaders.ACCEPT)); + assertThat(request.getPath()).isEqualTo("/json"); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("application/json"); }); } @@ -262,19 +258,19 @@ public class WebClientIntegrationTests { StepVerifier.create(result) .consumeNextWith(entity -> { - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(MediaType.APPLICATION_JSON, entity.getHeaders().getContentType()); - assertEquals(58, entity.getHeaders().getContentLength()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON); + assertThat(entity.getHeaders().getContentLength()).isEqualTo(58); Pojo pojo1 = new Pojo("foo1", "bar1"); Pojo pojo2 = new Pojo("foo2", "bar2"); - assertEquals(Arrays.asList(pojo1, pojo2), entity.getBody()); + assertThat(entity.getBody()).isEqualTo(Arrays.asList(pojo1, pojo2)); }) .expectComplete().verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { - assertEquals("/json", request.getPath()); - assertEquals("application/json", request.getHeader(HttpHeaders.ACCEPT)); + assertThat(request.getPath()).isEqualTo("/json"); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("application/json"); }); } @@ -295,8 +291,8 @@ public class WebClientIntegrationTests { expectRequestCount(1); expectRequest(request -> { - assertEquals("/json", request.getPath()); - assertEquals("application/json", request.getHeader(HttpHeaders.ACCEPT)); + assertThat(request.getPath()).isEqualTo("/json"); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("application/json"); }); } @@ -313,14 +309,14 @@ public class WebClientIntegrationTests { .bodyToMono(Pojo.class); StepVerifier.create(result) - .consumeNextWith(p -> assertEquals("barbar", p.getBar())) + .consumeNextWith(p -> assertThat(p.getBar()).isEqualTo("barbar")) .expectComplete() .verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { - assertEquals("/pojo", request.getPath()); - assertEquals("application/json", request.getHeader(HttpHeaders.ACCEPT)); + assertThat(request.getPath()).isEqualTo("/pojo"); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("application/json"); }); } @@ -344,8 +340,8 @@ public class WebClientIntegrationTests { expectRequestCount(1); expectRequest(request -> { - assertEquals("/pojos", request.getPath()); - assertEquals("application/json", request.getHeader(HttpHeaders.ACCEPT)); + assertThat(request.getPath()).isEqualTo("/pojos"); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("application/json"); }); } @@ -363,17 +359,17 @@ public class WebClientIntegrationTests { .bodyToMono(Pojo.class); StepVerifier.create(result) - .consumeNextWith(p -> assertEquals("BARBAR", p.getBar())) + .consumeNextWith(p -> assertThat(p.getBar()).isEqualTo("BARBAR")) .expectComplete() .verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { - assertEquals("/pojo/capitalize", request.getPath()); - assertEquals("{\"foo\":\"foofoo\",\"bar\":\"barbar\"}", request.getBody().readUtf8()); - assertEquals("31", request.getHeader(HttpHeaders.CONTENT_LENGTH)); - assertEquals("application/json", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("application/json", request.getHeader(HttpHeaders.CONTENT_TYPE)); + assertThat(request.getPath()).isEqualTo("/pojo/capitalize"); + assertThat(request.getBody().readUtf8()).isEqualTo("{\"foo\":\"foofoo\",\"bar\":\"barbar\"}"); + assertThat(request.getHeader(HttpHeaders.CONTENT_LENGTH)).isEqualTo("31"); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("application/json"); + assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo("application/json"); }); } @@ -395,8 +391,8 @@ public class WebClientIntegrationTests { expectRequestCount(1); expectRequest(request -> { - assertEquals("/test", request.getPath()); - assertEquals("testkey=testvalue", request.getHeader(HttpHeaders.COOKIE)); + assertThat(request.getPath()).isEqualTo("/test"); + assertThat(request.getHeader(HttpHeaders.COOKIE)).isEqualTo("testkey=testvalue"); }); } @@ -423,8 +419,8 @@ public class WebClientIntegrationTests { catch (IOException ex) { throw new IllegalStateException(ex); } - assertEquals(expected.length, actual.size()); - assertEquals(hash(expected), hash(actual.toByteArray())); + assertThat(actual.size()).isEqualTo(expected.length); + assertThat(hash(actual.toByteArray())).isEqualTo(hash(expected)); }); } @@ -442,14 +438,14 @@ public class WebClientIntegrationTests { Mono result = this.webClient.get().uri("/greeting?name=Spring").exchange(); StepVerifier.create(result) - .consumeNextWith(response -> assertEquals(HttpStatus.NOT_FOUND, response.statusCode())) + .consumeNextWith(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.NOT_FOUND)) .expectComplete() .verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("/greeting?name=Spring", request.getPath()); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo("/greeting?name=Spring"); }); } @@ -469,8 +465,8 @@ public class WebClientIntegrationTests { expectRequestCount(1); expectRequest(request -> { - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("/greeting?name=Spring", request.getPath()); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo("/greeting?name=Spring"); }); } @@ -489,8 +485,8 @@ public class WebClientIntegrationTests { expectRequestCount(1); expectRequest(request -> { - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("/greeting", request.getPath()); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo("/greeting"); }); } @@ -508,33 +504,32 @@ public class WebClientIntegrationTests { StepVerifier.create(result) .expectErrorSatisfies(throwable -> { - assertTrue(throwable instanceof WebClientResponseException); + assertThat(throwable instanceof WebClientResponseException).isTrue(); WebClientResponseException ex = (WebClientResponseException) throwable; - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, ex.getStatusCode()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getRawStatusCode()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), - ex.getStatusText()); - assertEquals(MediaType.TEXT_PLAIN, ex.getHeaders().getContentType()); - assertEquals(errorMessage, ex.getResponseBodyAsString()); + assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + assertThat(ex.getRawStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value()); + assertThat(ex.getStatusText()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()); + assertThat(ex.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(ex.getResponseBodyAsString()).isEqualTo(errorMessage); HttpRequest request = ex.getRequest(); - assertEquals(HttpMethod.GET, request.getMethod()); - assertEquals(URI.create(this.server.url(path).toString()), request.getURI()); - assertNotNull(request.getHeaders()); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); + assertThat(request.getURI()).isEqualTo(URI.create(this.server.url(path).toString())); + assertThat(request.getHeaders()).isNotNull(); }) .verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals(path, request.getPath()); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo(path); }); } @Test public void shouldSupportUnknownStatusCode() { int errorStatus = 555; - assertNull(HttpStatus.resolve(errorStatus)); + assertThat((Object) HttpStatus.resolve(errorStatus)).isNull(); String errorMessage = "Something went wrong"; prepareResponse(response -> response.setResponseCode(errorStatus) .setHeader("Content-Type", "text/plain").setBody(errorMessage)); @@ -544,21 +539,21 @@ public class WebClientIntegrationTests { .exchange(); StepVerifier.create(result) - .consumeNextWith(response -> assertEquals(555, response.rawStatusCode())) + .consumeNextWith(response -> assertThat(response.rawStatusCode()).isEqualTo(555)) .expectComplete() .verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("/unknownPage", request.getPath()); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo("/unknownPage"); }); } @Test public void shouldGetErrorSignalWhenRetrievingUnknownStatusCode() { int errorStatus = 555; - assertNull(HttpStatus.resolve(errorStatus)); + assertThat((Object) HttpStatus.resolve(errorStatus)).isNull(); String errorMessage = "Something went wrong"; prepareResponse(response -> response.setResponseCode(errorStatus) .setHeader("Content-Type", "text/plain").setBody(errorMessage)); @@ -570,20 +565,20 @@ public class WebClientIntegrationTests { StepVerifier.create(result) .expectErrorSatisfies(throwable -> { - assertTrue(throwable instanceof UnknownHttpStatusCodeException); + assertThat(throwable instanceof UnknownHttpStatusCodeException).isTrue(); UnknownHttpStatusCodeException ex = (UnknownHttpStatusCodeException) throwable; - assertEquals("Unknown status code ["+errorStatus+"]", ex.getMessage()); - assertEquals(errorStatus, ex.getRawStatusCode()); - assertEquals("", ex.getStatusText()); - assertEquals(MediaType.TEXT_PLAIN, ex.getHeaders().getContentType()); - assertEquals(errorMessage, ex.getResponseBodyAsString()); + assertThat(ex.getMessage()).isEqualTo(("Unknown status code ["+errorStatus+"]")); + assertThat(ex.getRawStatusCode()).isEqualTo(errorStatus); + assertThat(ex.getStatusText()).isEqualTo(""); + assertThat(ex.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(ex.getResponseBodyAsString()).isEqualTo(errorMessage); }) .verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("/unknownPage", request.getPath()); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo("/unknownPage"); }); } @@ -604,8 +599,8 @@ public class WebClientIntegrationTests { expectRequestCount(1); expectRequest(request -> { - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("/greeting?name=Spring", request.getPath()); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo("/greeting?name=Spring"); }); } @@ -626,8 +621,8 @@ public class WebClientIntegrationTests { expectRequestCount(1); expectRequest(request -> { - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("/greeting?name=Spring", request.getPath()); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo("/greeting?name=Spring"); }); } @@ -642,14 +637,14 @@ public class WebClientIntegrationTests { .flatMap(response -> response.toEntity(String.class)); StepVerifier.create(result) - .consumeNextWith(response -> assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode())) + .consumeNextWith(response -> assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)) .expectComplete() .verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { - assertEquals("*/*", request.getHeader(HttpHeaders.ACCEPT)); - assertEquals("/greeting?name=Spring", request.getPath()); + assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("*/*"); + assertThat(request.getPath()).isEqualTo("/greeting?name=Spring"); }); } @@ -677,7 +672,7 @@ public class WebClientIntegrationTests { .verify(Duration.ofSeconds(3)); expectRequestCount(1); - expectRequest(request -> assertEquals("bar", request.getHeader("foo"))); + expectRequest(request -> assertThat(request.getHeader("foo")).isEqualTo("bar")); } @Test @@ -733,7 +728,7 @@ public class WebClientIntegrationTests { .flatMap(response -> response.toEntity(Void.class)); StepVerifier.create(result).assertNext(r -> - assertTrue(r.getStatusCode().is2xxSuccessful()) + assertThat(r.getStatusCode().is2xxSuccessful()).isTrue() ).verifyComplete(); } @@ -764,7 +759,7 @@ public class WebClientIntegrationTests { } private void expectRequestCount(int count) { - assertEquals(count, this.server.getRequestCount()); + assertThat(this.server.getRequestCount()).isEqualTo(count); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/support/ClientResponseWrapperTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/support/ClientResponseWrapperTests.java index 7196f48742c..7190ea6c61e 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/support/ClientResponseWrapperTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/support/ClientResponseWrapperTests.java @@ -34,8 +34,7 @@ import org.springframework.web.reactive.function.BodyExtractors; import org.springframework.web.reactive.function.client.ClientResponse; import static java.util.Collections.singletonList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -56,7 +55,7 @@ public class ClientResponseWrapperTests { @Test public void response() { - assertSame(mockResponse, wrapper.response()); + assertThat(wrapper.response()).isSameAs(mockResponse); } @Test @@ -64,7 +63,7 @@ public class ClientResponseWrapperTests { HttpStatus status = HttpStatus.BAD_REQUEST; given(mockResponse.statusCode()).willReturn(status); - assertSame(status, wrapper.statusCode()); + assertThat(wrapper.statusCode()).isSameAs(status); } @Test @@ -72,7 +71,7 @@ public class ClientResponseWrapperTests { int status = 999; given(mockResponse.rawStatusCode()).willReturn(status); - assertEquals(status, wrapper.rawStatusCode()); + assertThat(wrapper.rawStatusCode()).isEqualTo(status); } @Test @@ -80,7 +79,7 @@ public class ClientResponseWrapperTests { ClientResponse.Headers headers = mock(ClientResponse.Headers.class); given(mockResponse.headers()).willReturn(headers); - assertSame(headers, wrapper.headers()); + assertThat(wrapper.headers()).isSameAs(headers); } @Test @@ -89,7 +88,7 @@ public class ClientResponseWrapperTests { MultiValueMap cookies = mock(MultiValueMap.class); given(mockResponse.cookies()).willReturn(cookies); - assertSame(cookies, wrapper.cookies()); + assertThat(wrapper.cookies()).isSameAs(cookies); } @Test @@ -98,7 +97,7 @@ public class ClientResponseWrapperTests { BodyExtractor, ReactiveHttpInputMessage> extractor = BodyExtractors.toMono(String.class); given(mockResponse.body(extractor)).willReturn(result); - assertSame(result, wrapper.body(extractor)); + assertThat(wrapper.body(extractor)).isSameAs(result); } @Test @@ -106,7 +105,7 @@ public class ClientResponseWrapperTests { Mono result = Mono.just("foo"); given(mockResponse.bodyToMono(String.class)).willReturn(result); - assertSame(result, wrapper.bodyToMono(String.class)); + assertThat(wrapper.bodyToMono(String.class)).isSameAs(result); } @Test @@ -115,7 +114,7 @@ public class ClientResponseWrapperTests { ParameterizedTypeReference reference = new ParameterizedTypeReference() {}; given(mockResponse.bodyToMono(reference)).willReturn(result); - assertSame(result, wrapper.bodyToMono(reference)); + assertThat(wrapper.bodyToMono(reference)).isSameAs(result); } @Test @@ -123,7 +122,7 @@ public class ClientResponseWrapperTests { Flux result = Flux.just("foo"); given(mockResponse.bodyToFlux(String.class)).willReturn(result); - assertSame(result, wrapper.bodyToFlux(String.class)); + assertThat(wrapper.bodyToFlux(String.class)).isSameAs(result); } @Test @@ -132,7 +131,7 @@ public class ClientResponseWrapperTests { ParameterizedTypeReference reference = new ParameterizedTypeReference() {}; given(mockResponse.bodyToFlux(reference)).willReturn(result); - assertSame(result, wrapper.bodyToFlux(reference)); + assertThat(wrapper.bodyToFlux(reference)).isSameAs(result); } @Test @@ -140,7 +139,7 @@ public class ClientResponseWrapperTests { Mono> result = Mono.just(new ResponseEntity<>("foo", HttpStatus.OK)); given(mockResponse.toEntity(String.class)).willReturn(result); - assertSame(result, wrapper.toEntity(String.class)); + assertThat(wrapper.toEntity(String.class)).isSameAs(result); } @Test @@ -149,7 +148,7 @@ public class ClientResponseWrapperTests { ParameterizedTypeReference reference = new ParameterizedTypeReference() {}; given(mockResponse.toEntity(reference)).willReturn(result); - assertSame(result, wrapper.toEntity(reference)); + assertThat(wrapper.toEntity(reference)).isSameAs(result); } @Test @@ -157,7 +156,7 @@ public class ClientResponseWrapperTests { Mono>> result = Mono.just(new ResponseEntity<>(singletonList("foo"), HttpStatus.OK)); given(mockResponse.toEntityList(String.class)).willReturn(result); - assertSame(result, wrapper.toEntityList(String.class)); + assertThat(wrapper.toEntityList(String.class)).isSameAs(result); } @Test @@ -166,7 +165,7 @@ public class ClientResponseWrapperTests { ParameterizedTypeReference reference = new ParameterizedTypeReference() {}; given(mockResponse.toEntityList(reference)).willReturn(result); - assertSame(result, wrapper.toEntityList(reference)); + assertThat(wrapper.toEntityList(reference)).isSameAs(result); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultEntityResponseBuilderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultEntityResponseBuilderTests.java index 1f5f57be54a..81ed266c560 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultEntityResponseBuilderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultEntityResponseBuilderTests.java @@ -47,9 +47,7 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.result.view.ViewResolver; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -60,14 +58,14 @@ public class DefaultEntityResponseBuilderTests { public void fromObject() { String body = "foo"; EntityResponse response = EntityResponse.fromObject(body).build().block(); - assertSame(body, response.entity()); + assertThat(response.entity()).isSameAs(body); } @Test public void fromPublisherClass() { Flux body = Flux.just("foo", "bar"); EntityResponse> response = EntityResponse.fromPublisher(body, String.class).build().block(); - assertSame(body, response.entity()); + assertThat(response.entity()).isSameAs(body); } @Test @@ -75,7 +73,7 @@ public class DefaultEntityResponseBuilderTests { Flux body = Flux.just("foo", "bar"); ParameterizedTypeReference typeReference = new ParameterizedTypeReference() {}; EntityResponse> response = EntityResponse.fromPublisher(body, typeReference).build().block(); - assertSame(body, response.entity()); + assertThat(response.entity()).isSameAs(body); } @Test @@ -218,7 +216,7 @@ public class DefaultEntityResponseBuilderTests { .expectComplete() .verify(); - assertNotNull(exchange.getResponse().getBody()); + assertThat(exchange.getResponse().getBody()).isNotNull(); } @Test @@ -237,7 +235,7 @@ public class DefaultEntityResponseBuilderTests { responseMono.writeTo(exchange, DefaultServerResponseBuilderTests.EMPTY_CONTEXT); MockServerHttpResponse response = exchange.getResponse(); - assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_MODIFIED); StepVerifier.create(response.getBody()) .expectError(IllegalStateException.class) .verify(); @@ -262,7 +260,7 @@ public class DefaultEntityResponseBuilderTests { responseMono.writeTo(exchange, DefaultServerResponseBuilderTests.EMPTY_CONTEXT); MockServerHttpResponse response = exchange.getResponse(); - assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_MODIFIED); StepVerifier.create(response.getBody()) .expectError(IllegalStateException.class) .verify(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultRenderingResponseTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultRenderingResponseTests.java index b6e30dba198..35715d861f2 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultRenderingResponseTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultRenderingResponseTests.java @@ -45,7 +45,7 @@ import org.springframework.web.reactive.result.view.ViewResolver; import org.springframework.web.reactive.result.view.ViewResolverSupport; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -173,7 +173,7 @@ public class DefaultRenderingResponseTests { StepVerifier.create(result.flatMap(response -> response.writeTo(exchange, context))) .verifyComplete(); - assertEquals(ViewResolverSupport.DEFAULT_CONTENT_TYPE, exchange.getResponse().getHeaders().getContentType()); + assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(ViewResolverSupport.DEFAULT_CONTENT_TYPE); } @@ -204,7 +204,7 @@ public class DefaultRenderingResponseTests { responseMono.writeTo(exchange, DefaultServerResponseBuilderTests.EMPTY_CONTEXT); MockServerHttpResponse response = exchange.getResponse(); - assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_MODIFIED); StepVerifier.create(response.getBody()) .expectError(IllegalStateException.class) .verify(); @@ -229,7 +229,7 @@ public class DefaultRenderingResponseTests { responseMono.writeTo(exchange, DefaultServerResponseBuilderTests.EMPTY_CONTEXT); MockServerHttpResponse response = exchange.getResponse(); - assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_MODIFIED); StepVerifier.create(response.getBody()) .expectError(IllegalStateException.class) .verify(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestBuilderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestBuilderTests.java index baa3615c3bb..d2452195b9a 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestBuilderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestBuilderTests.java @@ -30,7 +30,7 @@ import org.springframework.http.ResponseCookie; import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -61,11 +61,11 @@ public class DefaultServerRequestBuilderTests { .body(body) .build(); - assertEquals(HttpMethod.HEAD, result.method()); - assertEquals(1, result.headers().asHttpHeaders().size()); - assertEquals("baar", result.headers().asHttpHeaders().getFirst("foo")); - assertEquals(1, result.cookies().size()); - assertEquals("quux", result.cookies().getFirst("baz").getValue()); + assertThat(result.method()).isEqualTo(HttpMethod.HEAD); + assertThat(result.headers().asHttpHeaders().size()).isEqualTo(1); + assertThat(result.headers().asHttpHeaders().getFirst("foo")).isEqualTo("baar"); + assertThat(result.cookies().size()).isEqualTo(1); + assertThat(result.cookies().getFirst("baz").getValue()).isEqualTo("quux"); StepVerifier.create(result.bodyToFlux(String.class)) .expectNext("baz") diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java index 35fcd2fb9d6..10123cafbec 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java @@ -56,9 +56,8 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.server.ServerWebInputException; import org.springframework.web.server.UnsupportedMediaTypeStatusException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.springframework.web.reactive.function.BodyExtractors.toMono; /** @@ -78,7 +77,7 @@ public class DefaultServerRequestTests { MockServerWebExchange.from(MockServerHttpRequest.method(method, "https://example.com")), this.messageReaders); - assertEquals(method, request.method()); + assertThat(request.method()).isEqualTo(method); } @Test @@ -89,7 +88,7 @@ public class DefaultServerRequestTests { MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, uri)), this.messageReaders); - assertEquals(uri, request.uri()); + assertThat(request.uri()).isEqualTo(uri); } @Test @@ -101,11 +100,11 @@ public class DefaultServerRequestTests { URI result = request.uriBuilder().build(); - assertEquals("http", result.getScheme()); - assertEquals("localhost", result.getHost()); - assertEquals(-1, result.getPort()); - assertEquals("/path", result.getPath()); - assertEquals("a=1", result.getQuery()); + assertThat(result.getScheme()).isEqualTo("http"); + assertThat(result.getHost()).isEqualTo("localhost"); + assertThat(result.getPort()).isEqualTo(-1); + assertThat(result.getPath()).isEqualTo("/path"); + assertThat(result.getQuery()).isEqualTo("a=1"); } @Test @@ -116,7 +115,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(exchange, messageReaders); - assertEquals(Optional.of("bar"), request.attribute("foo")); + assertThat(request.attribute("foo")).isEqualTo(Optional.of("bar")); } @Test @@ -125,7 +124,7 @@ public class DefaultServerRequestTests { MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, "https://example.com?foo=bar")), this.messageReaders); - assertEquals(Optional.of("bar"), request.queryParam("foo")); + assertThat(request.queryParam("foo")).isEqualTo(Optional.of("bar")); } @Test @@ -134,7 +133,7 @@ public class DefaultServerRequestTests { MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, "https://example.com?foo")), this.messageReaders); - assertEquals(Optional.of(""), request.queryParam("foo")); + assertThat(request.queryParam("foo")).isEqualTo(Optional.of("")); } @Test @@ -143,7 +142,7 @@ public class DefaultServerRequestTests { MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, "https://example.com?foo")), this.messageReaders); - assertEquals(Optional.empty(), request.queryParam("bar")); + assertThat(request.queryParam("bar")).isEqualTo(Optional.empty()); } @Test @@ -154,7 +153,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(exchange, messageReaders); - assertEquals("bar", request.pathVariable("foo")); + assertThat(request.pathVariable("foo")).isEqualTo("bar"); } @@ -178,7 +177,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(exchange, messageReaders); - assertEquals(pathVariables, request.pathVariables()); + assertThat(request.pathVariables()).isEqualTo(pathVariables); } @Test @@ -205,11 +204,11 @@ public class DefaultServerRequestTests { this.messageReaders); ServerRequest.Headers headers = request.headers(); - assertEquals(accept, headers.accept()); - assertEquals(acceptCharset, headers.acceptCharset()); - assertEquals(OptionalLong.of(contentLength), headers.contentLength()); - assertEquals(Optional.of(contentType), headers.contentType()); - assertEquals(httpHeaders, headers.asHttpHeaders()); + assertThat(headers.accept()).isEqualTo(accept); + assertThat(headers.acceptCharset()).isEqualTo(acceptCharset); + assertThat(headers.contentLength()).isEqualTo(OptionalLong.of(contentLength)); + assertThat(headers.contentType()).isEqualTo(Optional.of(contentType)); + assertThat(headers.asHttpHeaders()).isEqualTo(httpHeaders); } @Test @@ -223,7 +222,7 @@ public class DefaultServerRequestTests { MultiValueMap expected = new LinkedMultiValueMap<>(); expected.add("foo", cookie); - assertEquals(expected, request.cookies()); + assertThat(request.cookies()).isEqualTo(expected); } @@ -244,7 +243,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), messageReaders); Mono resultMono = request.body(toMono(String.class)); - assertEquals("foo", resultMono.block()); + assertThat(resultMono.block()).isEqualTo("foo"); } @Test @@ -263,7 +262,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), messageReaders); Mono resultMono = request.bodyToMono(String.class); - assertEquals("foo", resultMono.block()); + assertThat(resultMono.block()).isEqualTo("foo"); } @Test @@ -283,7 +282,7 @@ public class DefaultServerRequestTests { ParameterizedTypeReference typeReference = new ParameterizedTypeReference() {}; Mono resultMono = request.bodyToMono(typeReference); - assertEquals("foo", resultMono.block()); + assertThat(resultMono.block()).isEqualTo("foo"); } @Test @@ -324,7 +323,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), messageReaders); Flux resultFlux = request.bodyToFlux(String.class); - assertEquals(Collections.singletonList("foo"), resultFlux.collectList().block()); + assertThat(resultFlux.collectList().block()).isEqualTo(Collections.singletonList("foo")); } @Test @@ -344,7 +343,7 @@ public class DefaultServerRequestTests { ParameterizedTypeReference typeReference = new ParameterizedTypeReference() {}; Flux resultFlux = request.bodyToFlux(typeReference); - assertEquals(Collections.singletonList("foo"), resultFlux.collectList().block()); + assertThat(resultFlux.collectList().block()).isEqualTo(Collections.singletonList("foo")); } @Test @@ -386,9 +385,9 @@ public class DefaultServerRequestTests { Mono> resultData = request.formData(); StepVerifier.create(resultData) .consumeNextWith(formData -> { - assertEquals(2, formData.size()); - assertEquals("bar", formData.getFirst("foo")); - assertEquals("qux", formData.getFirst("baz")); + assertThat(formData.size()).isEqualTo(2); + assertThat(formData.getFirst("foo")).isEqualTo("bar"); + assertThat(formData.getFirst("baz")).isEqualTo("qux"); }) .verifyComplete(); } @@ -420,17 +419,19 @@ public class DefaultServerRequestTests { Mono> resultData = request.multipartData(); StepVerifier.create(resultData) .consumeNextWith(formData -> { - assertEquals(2, formData.size()); + assertThat(formData.size()).isEqualTo(2); Part part = formData.getFirst("foo"); - assertTrue(part instanceof FormFieldPart); + boolean condition1 = part instanceof FormFieldPart; + assertThat(condition1).isTrue(); FormFieldPart formFieldPart = (FormFieldPart) part; - assertEquals("bar", formFieldPart.value()); + assertThat(formFieldPart.value()).isEqualTo("bar"); part = formData.getFirst("baz"); - assertTrue(part instanceof FormFieldPart); + boolean condition = part instanceof FormFieldPart; + assertThat(condition).isTrue(); formFieldPart = (FormFieldPart) part; - assertEquals("qux", formFieldPart.value()); + assertThat(formFieldPart.value()).isEqualTo("qux"); }) .verifyComplete(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerResponseBuilderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerResponseBuilderTests.java index 0293dfea4b9..5c0bed8cf14 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerResponseBuilderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerResponseBuilderTests.java @@ -44,9 +44,8 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.result.view.ViewResolver; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; /** * @author Arjen Poutsma @@ -311,14 +310,14 @@ public class DefaultServerResponseBuilderTests { .cookie(ResponseCookie.from("foo", "bar").build()) .syncBody("body"); - assertFalse(serverResponse.block().cookies().isEmpty()); + assertThat(serverResponse.block().cookies().isEmpty()).isFalse(); serverResponse = ServerResponse.ok() .cookie(ResponseCookie.from("foo", "bar").build()) .body(BodyInserters.fromObject("body")); - assertFalse(serverResponse.block().cookies().isEmpty()); + assertThat(serverResponse.block().cookies().isEmpty()).isFalse(); } @@ -336,9 +335,9 @@ public class DefaultServerResponseBuilderTests { result.flatMap(res -> res.writeTo(exchange, EMPTY_CONTEXT)).block(); MockServerHttpResponse response = exchange.getResponse(); - assertEquals(HttpStatus.CREATED, response.getStatusCode()); - assertEquals("MyValue", response.getHeaders().getFirst("MyKey")); - assertEquals("value", response.getCookies().getFirst("name").getValue()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); + assertThat(response.getHeaders().getFirst("MyKey")).isEqualTo("MyValue"); + assertThat(response.getCookies().getFirst("name").getValue()).isEqualTo("value"); StepVerifier.create(response.getBody()).expectComplete().verify(); } @@ -380,7 +379,7 @@ public class DefaultServerResponseBuilderTests { responseMono.writeTo(exchange, EMPTY_CONTEXT); MockServerHttpResponse response = exchange.getResponse(); - assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_MODIFIED); StepVerifier.create(response.getBody()) .expectError(IllegalStateException.class) .verify(); @@ -405,7 +404,7 @@ public class DefaultServerResponseBuilderTests { responseMono.writeTo(exchange, EMPTY_CONTEXT); MockServerHttpResponse response = exchange.getResponse(); - assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_MODIFIED); StepVerifier.create(response.getBody()) .expectError(IllegalStateException.class) .verify(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DispatcherHandlerIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DispatcherHandlerIntegrationTests.java index 3cb98671bb8..a981d8fd60f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DispatcherHandlerIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DispatcherHandlerIntegrationTests.java @@ -42,9 +42,7 @@ import org.springframework.web.reactive.config.EnableWebFlux; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import org.springframework.web.util.pattern.PathPattern; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.BodyInserters.fromPublisher; import static org.springframework.web.reactive.function.server.RouterFunctions.nest; import static org.springframework.web.reactive.function.server.RouterFunctions.route; @@ -80,8 +78,8 @@ public class DispatcherHandlerIntegrationTests extends AbstractHttpHandlerIntegr ResponseEntity result = this.restTemplate.getForEntity("http://localhost:" + this.port + "/mono", Person.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("John", result.getBody().getName()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody().getName()).isEqualTo("John"); } @Test @@ -91,11 +89,11 @@ public class DispatcherHandlerIntegrationTests extends AbstractHttpHandlerIntegr this.restTemplate .exchange("http://localhost:" + this.port + "/flux", HttpMethod.GET, null, reference); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); List body = result.getBody(); - assertEquals(2, body.size()); - assertEquals("John", body.get(0).getName()); - assertEquals("Jane", body.get(1).getName()); + assertThat(body.size()).isEqualTo(2); + assertThat(body.get(0).getName()).isEqualTo("John"); + assertThat(body.get(1).getName()).isEqualTo("Jane"); } @Test @@ -103,8 +101,8 @@ public class DispatcherHandlerIntegrationTests extends AbstractHttpHandlerIntegr ResponseEntity result = this.restTemplate.getForEntity("http://localhost:" + this.port + "/controller", Person.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("John", result.getBody().getName()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody().getName()).isEqualTo("John"); } @Test @@ -113,7 +111,7 @@ public class DispatcherHandlerIntegrationTests extends AbstractHttpHandlerIntegr this.restTemplate .getForEntity("http://localhost:" + this.port + "/attributes/bar", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -174,31 +172,31 @@ public class DispatcherHandlerIntegrationTests extends AbstractHttpHandlerIntegr @SuppressWarnings("unchecked") public Mono attributes(ServerRequest request) { - assertTrue(request.attributes().containsKey(RouterFunctions.REQUEST_ATTRIBUTE)); - assertTrue(request.attributes().containsKey(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)); + assertThat(request.attributes().containsKey(RouterFunctions.REQUEST_ATTRIBUTE)).isTrue(); + assertThat(request.attributes().containsKey(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)).isTrue(); Map pathVariables = (Map) request.attributes().get(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE); - assertNotNull(pathVariables); - assertEquals(1, pathVariables.size()); - assertEquals("bar", pathVariables.get("foo")); + assertThat(pathVariables).isNotNull(); + assertThat(pathVariables.size()).isEqualTo(1); + assertThat(pathVariables.get("foo")).isEqualTo("bar"); pathVariables = (Map) request.attributes().get(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); - assertNotNull(pathVariables); - assertEquals(1, pathVariables.size()); - assertEquals("bar", pathVariables.get("foo")); + assertThat(pathVariables).isNotNull(); + assertThat(pathVariables.size()).isEqualTo(1); + assertThat(pathVariables.get("foo")).isEqualTo("bar"); PathPattern pattern = (PathPattern) request.attributes().get(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE); - assertNotNull(pattern); - assertEquals("/attributes/{foo}", pattern.getPatternString()); + assertThat(pattern).isNotNull(); + assertThat(pattern.getPatternString()).isEqualTo("/attributes/{foo}"); pattern = (PathPattern) request.attributes() .get(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); - assertNotNull(pattern); - assertEquals("/attributes/{foo}", pattern.getPatternString()); + assertThat(pattern).isNotNull(); + assertThat(pattern.getPatternString()).isEqualTo("/attributes/{foo}"); return ServerResponse.ok().build(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/HandlerStrategiesTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/HandlerStrategiesTests.java index 23ad8c4e570..d41a64227a2 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/HandlerStrategiesTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/HandlerStrategiesTests.java @@ -18,8 +18,7 @@ package org.springframework.web.reactive.function.server; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -29,17 +28,17 @@ public class HandlerStrategiesTests { @Test public void empty() { HandlerStrategies strategies = HandlerStrategies.empty().build(); - assertTrue(strategies.messageReaders().isEmpty()); - assertTrue(strategies.messageWriters().isEmpty()); - assertTrue(strategies.viewResolvers().isEmpty()); + assertThat(strategies.messageReaders().isEmpty()).isTrue(); + assertThat(strategies.messageWriters().isEmpty()).isTrue(); + assertThat(strategies.viewResolvers().isEmpty()).isTrue(); } @Test public void withDefaults() { HandlerStrategies strategies = HandlerStrategies.withDefaults(); - assertFalse(strategies.messageReaders().isEmpty()); - assertFalse(strategies.messageWriters().isEmpty()); - assertTrue(strategies.viewResolvers().isEmpty()); + assertThat(strategies.messageReaders().isEmpty()).isFalse(); + assertThat(strategies.messageWriters().isEmpty()).isFalse(); + assertThat(strategies.viewResolvers().isEmpty()).isTrue(); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/HeadersWrapperTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/HeadersWrapperTests.java index 25f31c17b30..619dd5f9fc7 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/HeadersWrapperTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/HeadersWrapperTests.java @@ -32,7 +32,7 @@ import org.springframework.http.HttpRange; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.server.support.ServerRequestWrapper; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -58,7 +58,7 @@ public class HeadersWrapperTests { List accept = Collections.singletonList(MediaType.APPLICATION_JSON); given(mockHeaders.accept()).willReturn(accept); - assertSame(accept, wrapper.accept()); + assertThat(wrapper.accept()).isSameAs(accept); } @Test @@ -66,7 +66,7 @@ public class HeadersWrapperTests { List acceptCharset = Collections.singletonList(StandardCharsets.UTF_8); given(mockHeaders.acceptCharset()).willReturn(acceptCharset); - assertSame(acceptCharset, wrapper.acceptCharset()); + assertThat(wrapper.acceptCharset()).isSameAs(acceptCharset); } @Test @@ -74,7 +74,7 @@ public class HeadersWrapperTests { OptionalLong contentLength = OptionalLong.of(42L); given(mockHeaders.contentLength()).willReturn(contentLength); - assertSame(contentLength, wrapper.contentLength()); + assertThat(wrapper.contentLength()).isSameAs(contentLength); } @Test @@ -82,7 +82,7 @@ public class HeadersWrapperTests { Optional contentType = Optional.of(MediaType.APPLICATION_JSON); given(mockHeaders.contentType()).willReturn(contentType); - assertSame(contentType, wrapper.contentType()); + assertThat(wrapper.contentType()).isSameAs(contentType); } @Test @@ -90,7 +90,7 @@ public class HeadersWrapperTests { InetSocketAddress host = InetSocketAddress.createUnresolved("example.com", 42); given(mockHeaders.host()).willReturn(host); - assertSame(host, wrapper.host()); + assertThat(wrapper.host()).isSameAs(host); } @Test @@ -98,7 +98,7 @@ public class HeadersWrapperTests { List range = Collections.singletonList(HttpRange.createByteRange(42)); given(mockHeaders.range()).willReturn(range); - assertSame(range, wrapper.range()); + assertThat(wrapper.range()).isSameAs(range); } @Test @@ -107,7 +107,7 @@ public class HeadersWrapperTests { List value = Collections.singletonList("bar"); given(mockHeaders.header(name)).willReturn(value); - assertSame(value, wrapper.header(name)); + assertThat(wrapper.header(name)).isSameAs(value); } @Test @@ -115,7 +115,7 @@ public class HeadersWrapperTests { HttpHeaders httpHeaders = new HttpHeaders(); given(mockHeaders.asHttpHeaders()).willReturn(httpHeaders); - assertSame(httpHeaders, wrapper.asHttpHeaders()); + assertThat(wrapper.asHttpHeaders()).isSameAs(httpHeaders); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/InvalidHttpMethodIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/InvalidHttpMethodIntegrationTests.java index 7e83e234e8c..206f0f7abff 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/InvalidHttpMethodIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/InvalidHttpMethodIntegrationTests.java @@ -23,7 +23,7 @@ import okhttp3.Request; import okhttp3.Response; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -47,7 +47,7 @@ public class InvalidHttpMethodIntegrationTests extends AbstractRouterFunctionInt .build(); try (Response response = client.newCall(request).execute()) { - assertEquals("BAR", response.body().string()); + assertThat(response.body().string()).isEqualTo("BAR"); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/LocaleContextResolverIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/LocaleContextResolverIntegrationTests.java index a18a79c2269..11157cdce6b 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/LocaleContextResolverIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/LocaleContextResolverIntegrationTests.java @@ -35,7 +35,7 @@ import org.springframework.web.reactive.result.view.ViewResolver; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.i18n.FixedLocaleContextResolver; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze @@ -73,8 +73,8 @@ public class LocaleContextResolverIntegrationTests extends AbstractRouterFunctio StepVerifier .create(result) .consumeNextWith(response -> { - assertEquals(HttpStatus.OK, response.statusCode()); - assertEquals(Locale.GERMANY, response.headers().asHttpHeaders().getContentLanguage()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.headers().asHttpHeaders().getContentLanguage()).isEqualTo(Locale.GERMANY); }) .verifyComplete(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/NestedRouteIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/NestedRouteIntegrationTests.java index b2fe7584044..93873d62e33 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/NestedRouteIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/NestedRouteIntegrationTests.java @@ -29,8 +29,7 @@ import org.springframework.lang.Nullable; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.pattern.PathPattern; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.all; import static org.springframework.web.reactive.function.server.RequestPredicates.method; @@ -66,8 +65,8 @@ public class NestedRouteIntegrationTests extends AbstractRouterFunctionIntegrati ResponseEntity result = restTemplate.getForEntity("http://localhost:" + port + "/foo/bar", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/foo/bar", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("/foo/bar"); } @Test @@ -75,8 +74,8 @@ public class NestedRouteIntegrationTests extends AbstractRouterFunctionIntegrati ResponseEntity result = restTemplate.getForEntity("http://localhost:" + port + "/foo/baz", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/foo/baz", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("/foo/baz"); } @Test @@ -84,8 +83,8 @@ public class NestedRouteIntegrationTests extends AbstractRouterFunctionIntegrati ResponseEntity result = restTemplate.getForEntity("http://localhost:" + port + "/1/2/3", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/{foo}/{bar}/{baz}\n{foo=1, bar=2, baz=3}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("/{foo}/{bar}/{baz}\n{foo=1, bar=2, baz=3}"); } // SPR-16868 @@ -94,8 +93,8 @@ public class NestedRouteIntegrationTests extends AbstractRouterFunctionIntegrati ResponseEntity result = restTemplate.getForEntity("http://localhost:" + port + "/1/bar", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/{foo}/bar\n{foo=1}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("/{foo}/bar\n{foo=1}"); } @@ -105,8 +104,8 @@ public class NestedRouteIntegrationTests extends AbstractRouterFunctionIntegrati ResponseEntity result = restTemplate.getForEntity("http://localhost:" + port + "/qux/quux", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("/{qux}/quux\n{qux=qux}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("/{qux}/quux\n{qux=qux}"); } @@ -116,8 +115,8 @@ public class NestedRouteIntegrationTests extends AbstractRouterFunctionIntegrati ResponseEntity result = restTemplate.postForEntity("http://localhost:" + port + "/qux/quux", "", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("{}", result.getBody()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody()).isEqualTo("{}"); } @@ -134,8 +133,8 @@ public class NestedRouteIntegrationTests extends AbstractRouterFunctionIntegrati Map pathVariables = request.pathVariables(); Map attributePathVariables = (Map) request.attributes().get(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE); - assertTrue( (pathVariables.equals(attributePathVariables)) - || (pathVariables.isEmpty() && (attributePathVariables == null))); + assertThat((pathVariables.equals(attributePathVariables)) + || (pathVariables.isEmpty() && (attributePathVariables == null))).isTrue(); PathPattern pathPattern = matchingPattern(request); String pattern = pathPattern != null ? pathPattern.getPatternString() : ""; diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/PublisherHandlerFunctionIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/PublisherHandlerFunctionIntegrationTests.java index 9925e421369..99f6c9f7998 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/PublisherHandlerFunctionIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/PublisherHandlerFunctionIntegrationTests.java @@ -30,7 +30,7 @@ import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.BodyExtractors.toMono; import static org.springframework.web.reactive.function.BodyInserters.fromPublisher; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; @@ -59,8 +59,8 @@ public class PublisherHandlerFunctionIntegrationTests extends AbstractRouterFunc ResponseEntity result = restTemplate.getForEntity("http://localhost:" + port + "/mono", Person.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("John", result.getBody().getName()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody().getName()).isEqualTo("John"); } @Test @@ -69,11 +69,11 @@ public class PublisherHandlerFunctionIntegrationTests extends AbstractRouterFunc ResponseEntity> result = restTemplate.exchange("http://localhost:" + port + "/flux", HttpMethod.GET, null, reference); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); List body = result.getBody(); - assertEquals(2, body.size()); - assertEquals("John", body.get(0).getName()); - assertEquals("Jane", body.get(1).getName()); + assertThat(body.size()).isEqualTo(2); + assertThat(body.get(0).getName()).isEqualTo("John"); + assertThat(body.get(1).getName()).isEqualTo("Jane"); } @Test @@ -83,8 +83,8 @@ public class PublisherHandlerFunctionIntegrationTests extends AbstractRouterFunc RequestEntity requestEntity = RequestEntity.post(uri).body(person); ResponseEntity result = restTemplate.exchange(requestEntity, Person.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - assertEquals("Jack", result.getBody().getName()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.getBody().getName()).isEqualTo("Jack"); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RenderingResponseIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RenderingResponseIntegrationTests.java index f3b1e474313..77bcdc1d7c1 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RenderingResponseIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RenderingResponseIntegrationTests.java @@ -37,7 +37,7 @@ import org.springframework.web.reactive.result.view.View; import org.springframework.web.reactive.result.view.ViewResolver; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.server.HandlerFilterFunction.ofResponseProcessor; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RouterFunctions.route; @@ -77,11 +77,11 @@ public class RenderingResponseIntegrationTests extends AbstractRouterFunctionInt ResponseEntity result = restTemplate.getForEntity("http://localhost:" + port + "/normal", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); Map body = parseBody(result.getBody()); - assertEquals(2, body.size()); - assertEquals("foo", body.get("name")); - assertEquals("baz", body.get("bar")); + assertThat(body.size()).isEqualTo(2); + assertThat(body.get("name")).isEqualTo("foo"); + assertThat(body.get("bar")).isEqualTo("baz"); } @Test @@ -89,12 +89,12 @@ public class RenderingResponseIntegrationTests extends AbstractRouterFunctionInt ResponseEntity result = restTemplate.getForEntity("http://localhost:" + port + "/filter", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); Map body = parseBody(result.getBody()); - assertEquals(3, body.size()); - assertEquals("foo", body.get("name")); - assertEquals("baz", body.get("bar")); - assertEquals("quux", body.get("qux")); + assertThat(body.size()).isEqualTo(3); + assertThat(body.get("name")).isEqualTo("foo"); + assertThat(body.get("bar")).isEqualTo("baz"); + assertThat(body.get("qux")).isEqualTo("quux"); } private Map parseBody(String body) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicateAttributesTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicateAttributesTests.java index 582c062663a..1b290b4ac3a 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicateAttributesTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicateAttributesTests.java @@ -26,9 +26,7 @@ import org.springframework.http.codec.DecoderHttpMessageReader; import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -54,10 +52,10 @@ public class RequestPredicateAttributesTests { RequestPredicate predicate = new AddAttributePredicate(false, "predicate", "baz").negate(); boolean result = predicate.test(this.request); - assertTrue(result); + assertThat(result).isTrue(); - assertEquals("bar", this.request.attributes().get("exchange")); - assertEquals("baz", this.request.attributes().get("predicate")); + assertThat(this.request.attributes().get("exchange")).isEqualTo("bar"); + assertThat(this.request.attributes().get("predicate")).isEqualTo("baz"); } @Test @@ -65,10 +63,10 @@ public class RequestPredicateAttributesTests { RequestPredicate predicate = new AddAttributePredicate(true, "predicate", "baz").negate(); boolean result = predicate.test(this.request); - assertFalse(result); + assertThat(result).isFalse(); - assertEquals("bar", this.request.attributes().get("exchange")); - assertFalse(this.request.attributes().containsKey("baz")); + assertThat(this.request.attributes().get("exchange")).isEqualTo("bar"); + assertThat(this.request.attributes().containsKey("baz")).isFalse(); } @Test @@ -78,11 +76,11 @@ public class RequestPredicateAttributesTests { RequestPredicate predicate = new RequestPredicates.AndRequestPredicate(left, right); boolean result = predicate.test(this.request); - assertTrue(result); + assertThat(result).isTrue(); - assertEquals("bar", this.request.attributes().get("exchange")); - assertEquals("baz", this.request.attributes().get("left")); - assertEquals("qux", this.request.attributes().get("right")); + assertThat(this.request.attributes().get("exchange")).isEqualTo("bar"); + assertThat(this.request.attributes().get("left")).isEqualTo("baz"); + assertThat(this.request.attributes().get("right")).isEqualTo("qux"); } @Test @@ -92,11 +90,11 @@ public class RequestPredicateAttributesTests { RequestPredicate predicate = new RequestPredicates.AndRequestPredicate(left, right); boolean result = predicate.test(this.request); - assertFalse(result); + assertThat(result).isFalse(); - assertEquals("bar", this.request.attributes().get("exchange")); - assertFalse(this.request.attributes().containsKey("left")); - assertFalse(this.request.attributes().containsKey("right")); + assertThat(this.request.attributes().get("exchange")).isEqualTo("bar"); + assertThat(this.request.attributes().containsKey("left")).isFalse(); + assertThat(this.request.attributes().containsKey("right")).isFalse(); } @Test @@ -106,11 +104,11 @@ public class RequestPredicateAttributesTests { RequestPredicate predicate = new RequestPredicates.AndRequestPredicate(left, right); boolean result = predicate.test(this.request); - assertFalse(result); + assertThat(result).isFalse(); - assertEquals("bar", this.request.attributes().get("exchange")); - assertFalse(this.request.attributes().containsKey("left")); - assertFalse(this.request.attributes().containsKey("right")); + assertThat(this.request.attributes().get("exchange")).isEqualTo("bar"); + assertThat(this.request.attributes().containsKey("left")).isFalse(); + assertThat(this.request.attributes().containsKey("right")).isFalse(); } @Test @@ -120,11 +118,11 @@ public class RequestPredicateAttributesTests { RequestPredicate predicate = new RequestPredicates.AndRequestPredicate(left, right); boolean result = predicate.test(this.request); - assertFalse(result); + assertThat(result).isFalse(); - assertEquals("bar", this.request.attributes().get("exchange")); - assertFalse(this.request.attributes().containsKey("left")); - assertFalse(this.request.attributes().containsKey("right")); + assertThat(this.request.attributes().get("exchange")).isEqualTo("bar"); + assertThat(this.request.attributes().containsKey("left")).isFalse(); + assertThat(this.request.attributes().containsKey("right")).isFalse(); } @Test @@ -134,11 +132,11 @@ public class RequestPredicateAttributesTests { RequestPredicate predicate = new RequestPredicates.OrRequestPredicate(left, right); boolean result = predicate.test(this.request); - assertTrue(result); + assertThat(result).isTrue(); - assertEquals("bar", this.request.attributes().get("exchange")); - assertEquals("baz", this.request.attributes().get("left")); - assertFalse(this.request.attributes().containsKey("right")); + assertThat(this.request.attributes().get("exchange")).isEqualTo("bar"); + assertThat(this.request.attributes().get("left")).isEqualTo("baz"); + assertThat(this.request.attributes().containsKey("right")).isFalse(); } @Test @@ -148,11 +146,11 @@ public class RequestPredicateAttributesTests { RequestPredicate predicate = new RequestPredicates.OrRequestPredicate(left, right); boolean result = predicate.test(this.request); - assertTrue(result); + assertThat(result).isTrue(); - assertEquals("bar", this.request.attributes().get("exchange")); - assertEquals("baz", this.request.attributes().get("left")); - assertFalse(this.request.attributes().containsKey("right")); + assertThat(this.request.attributes().get("exchange")).isEqualTo("bar"); + assertThat(this.request.attributes().get("left")).isEqualTo("baz"); + assertThat(this.request.attributes().containsKey("right")).isFalse(); } @Test @@ -162,11 +160,11 @@ public class RequestPredicateAttributesTests { RequestPredicate predicate = new RequestPredicates.OrRequestPredicate(left, right); boolean result = predicate.test(this.request); - assertTrue(result); + assertThat(result).isTrue(); - assertEquals("bar", this.request.attributes().get("exchange")); - assertFalse(this.request.attributes().containsKey("left")); - assertEquals("qux", this.request.attributes().get("right")); + assertThat(this.request.attributes().get("exchange")).isEqualTo("bar"); + assertThat(this.request.attributes().containsKey("left")).isFalse(); + assertThat(this.request.attributes().get("right")).isEqualTo("qux"); } @Test @@ -176,11 +174,11 @@ public class RequestPredicateAttributesTests { RequestPredicate predicate = new RequestPredicates.OrRequestPredicate(left, right); boolean result = predicate.test(this.request); - assertFalse(result); + assertThat(result).isFalse(); - assertEquals("bar", this.request.attributes().get("exchange")); - assertFalse(this.request.attributes().containsKey("baz")); - assertFalse(this.request.attributes().containsKey("quux")); + assertThat(this.request.attributes().get("exchange")).isEqualTo("bar"); + assertThat(this.request.attributes().containsKey("baz")).isFalse(); + assertThat(this.request.attributes().containsKey("quux")).isFalse(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicateTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicateTests.java index 6707ea0a2fb..8529f39d67f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicateTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicateTests.java @@ -18,8 +18,7 @@ package org.springframework.web.reactive.function.server; import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -33,9 +32,9 @@ public class RequestPredicateTests { RequestPredicate predicate3 = request -> false; MockServerRequest request = MockServerRequest.builder().build(); - assertTrue(predicate1.and(predicate2).test(request)); - assertTrue(predicate2.and(predicate1).test(request)); - assertFalse(predicate1.and(predicate3).test(request)); + assertThat(predicate1.and(predicate2).test(request)).isTrue(); + assertThat(predicate2.and(predicate1).test(request)).isTrue(); + assertThat(predicate1.and(predicate3).test(request)).isFalse(); } @Test @@ -44,12 +43,12 @@ public class RequestPredicateTests { RequestPredicate negated = predicate.negate(); MockServerRequest mockRequest = MockServerRequest.builder().build(); - assertTrue(negated.test(mockRequest)); + assertThat(negated.test(mockRequest)).isTrue(); predicate = request -> true; negated = predicate.negate(); - assertFalse(negated.test(mockRequest)); + assertThat(negated.test(mockRequest)).isFalse(); } @Test @@ -59,9 +58,9 @@ public class RequestPredicateTests { RequestPredicate predicate3 = request -> false; MockServerRequest request = MockServerRequest.builder().build(); - assertTrue(predicate1.or(predicate2).test(request)); - assertTrue(predicate2.or(predicate1).test(request)); - assertFalse(predicate2.or(predicate3).test(request)); + assertThat(predicate1.or(predicate2).test(request)).isTrue(); + assertThat(predicate2.or(predicate1).test(request)).isTrue(); + assertThat(predicate2.or(predicate3).test(request)).isFalse(); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicatesTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicatesTests.java index 85766041129..4f521e0e555 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicatesTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicatesTests.java @@ -26,8 +26,7 @@ import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.web.util.pattern.PathPatternParser; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -38,7 +37,7 @@ public class RequestPredicatesTests { public void all() { RequestPredicate predicate = RequestPredicates.all(); MockServerRequest request = MockServerRequest.builder().build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); } @Test @@ -46,23 +45,23 @@ public class RequestPredicatesTests { HttpMethod httpMethod = HttpMethod.GET; RequestPredicate predicate = RequestPredicates.method(httpMethod); MockServerRequest request = MockServerRequest.builder().method(httpMethod).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); request = MockServerRequest.builder().method(HttpMethod.POST).build(); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test public void methods() { RequestPredicate predicate = RequestPredicates.methods(HttpMethod.GET, HttpMethod.HEAD); MockServerRequest request = MockServerRequest.builder().method(HttpMethod.GET).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); request = MockServerRequest.builder().method(HttpMethod.HEAD).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); request = MockServerRequest.builder().method(HttpMethod.POST).build(); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -71,31 +70,31 @@ public class RequestPredicatesTests { RequestPredicate predicate = RequestPredicates.GET("/p*"); MockServerRequest request = MockServerRequest.builder().method(HttpMethod.GET).uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.HEAD("/p*"); request = MockServerRequest.builder().method(HttpMethod.HEAD).uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.POST("/p*"); request = MockServerRequest.builder().method(HttpMethod.POST).uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.PUT("/p*"); request = MockServerRequest.builder().method(HttpMethod.PUT).uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.PATCH("/p*"); request = MockServerRequest.builder().method(HttpMethod.PATCH).uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.DELETE("/p*"); request = MockServerRequest.builder().method(HttpMethod.DELETE).uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.OPTIONS("/p*"); request = MockServerRequest.builder().method(HttpMethod.OPTIONS).uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); } @Test @@ -103,10 +102,10 @@ public class RequestPredicatesTests { URI uri = URI.create("http://localhost/path"); RequestPredicate predicate = RequestPredicates.path("/p*"); MockServerRequest request = MockServerRequest.builder().uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); request = MockServerRequest.builder().build(); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -114,7 +113,7 @@ public class RequestPredicatesTests { URI uri = URI.create("http://localhost/path"); RequestPredicate predicate = RequestPredicates.path("p*"); MockServerRequest request = MockServerRequest.builder().uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); } @Test @@ -122,10 +121,10 @@ public class RequestPredicatesTests { URI uri = URI.create("http://localhost/foo%20bar"); RequestPredicate predicate = RequestPredicates.path("/foo bar"); MockServerRequest request = MockServerRequest.builder().uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); request = MockServerRequest.builder().build(); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -137,7 +136,7 @@ public class RequestPredicatesTests { URI uri = URI.create("http://localhost/path"); RequestPredicate predicate = pathPredicates.apply("/P*"); MockServerRequest request = MockServerRequest.builder().uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); } @Test @@ -148,10 +147,10 @@ public class RequestPredicatesTests { RequestPredicates.headers( headers -> headers.header(name).equals(Collections.singletonList(value))); MockServerRequest request = MockServerRequest.builder().header(name, value).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); request = MockServerRequest.builder().build(); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -159,10 +158,10 @@ public class RequestPredicatesTests { MediaType json = MediaType.APPLICATION_JSON; RequestPredicate predicate = RequestPredicates.contentType(json); MockServerRequest request = MockServerRequest.builder().header("Content-Type", json.toString()).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); request = MockServerRequest.builder().build(); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -170,10 +169,10 @@ public class RequestPredicatesTests { MediaType json = MediaType.APPLICATION_JSON; RequestPredicate predicate = RequestPredicates.accept(json); MockServerRequest request = MockServerRequest.builder().header("Accept", json.toString()).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); request = MockServerRequest.builder().header("Accept", MediaType.TEXT_XML_VALUE).build(); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -182,28 +181,28 @@ public class RequestPredicatesTests { URI uri = URI.create("http://localhost/file.txt"); MockServerRequest request = MockServerRequest.builder().uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); uri = URI.create("http://localhost/FILE.TXT"); request = MockServerRequest.builder().uri(uri).build(); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.pathExtension("bar"); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); uri = URI.create("http://localhost/file.foo"); request = MockServerRequest.builder().uri(uri).build(); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test public void queryParam() { MockServerRequest request = MockServerRequest.builder().queryParam("foo", "bar").build(); RequestPredicate predicate = RequestPredicates.queryParam("foo", s -> s.equals("bar")); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.queryParam("foo", s -> s.equals("baz")); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/ResourceHandlerFunctionTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/ResourceHandlerFunctionTests.java index fc00eb59bfa..e2586186337 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/ResourceHandlerFunctionTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/ResourceHandlerFunctionTests.java @@ -37,9 +37,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.reactive.result.view.ViewResolver; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -80,12 +78,13 @@ public class ResourceHandlerFunctionTests { Mono responseMono = this.handlerFunction.handle(request); Mono result = responseMono.flatMap(response -> { - assertEquals(HttpStatus.OK, response.statusCode()); - assertTrue(response instanceof EntityResponse); - @SuppressWarnings("unchecked") + assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); + boolean condition = response instanceof EntityResponse; + assertThat(condition).isTrue(); + @SuppressWarnings("unchecked") EntityResponse entityResponse = (EntityResponse) response; - assertEquals(this.resource, entityResponse.entity()); - return response.writeTo(exchange, context); + assertThat(entityResponse.entity()).isEqualTo(this.resource); + return response.writeTo(exchange, context); }); StepVerifier.create(result) @@ -98,12 +97,12 @@ public class ResourceHandlerFunctionTests { .consumeNextWith(dataBuffer -> { byte[] resultBytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(resultBytes); - assertArrayEquals(expectedBytes, resultBytes); + assertThat(resultBytes).isEqualTo(expectedBytes); }) .expectComplete() .verify(); - assertEquals(MediaType.TEXT_PLAIN, mockResponse.getHeaders().getContentType()); - assertEquals(this.resource.contentLength(), mockResponse.getHeaders().getContentLength()); + assertThat(mockResponse.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(mockResponse.getHeaders().getContentLength()).isEqualTo(this.resource.contentLength()); } @Test @@ -116,19 +115,20 @@ public class ResourceHandlerFunctionTests { Mono responseMono = this.handlerFunction.handle(request); Mono result = responseMono.flatMap(response -> { - assertEquals(HttpStatus.OK, response.statusCode()); - assertTrue(response instanceof EntityResponse); + assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); + boolean condition = response instanceof EntityResponse; + assertThat(condition).isTrue(); @SuppressWarnings("unchecked") EntityResponse entityResponse = (EntityResponse) response; - assertEquals(this.resource.getFilename(), entityResponse.entity().getFilename()); + assertThat(entityResponse.entity().getFilename()).isEqualTo(this.resource.getFilename()); return response.writeTo(exchange, context); }); StepVerifier.create(result).expectComplete().verify(); StepVerifier.create(mockResponse.getBody()).expectComplete().verify(); - assertEquals(MediaType.TEXT_PLAIN, mockResponse.getHeaders().getContentType()); - assertEquals(this.resource.contentLength(), mockResponse.getHeaders().getContentLength()); + assertThat(mockResponse.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(mockResponse.getHeaders().getContentLength()).isEqualTo(this.resource.contentLength()); } @Test @@ -140,9 +140,8 @@ public class ResourceHandlerFunctionTests { Mono responseMono = this.handlerFunction.handle(request); Mono result = responseMono.flatMap(response -> { - assertEquals(HttpStatus.OK, response.statusCode()); - assertEquals(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS), - response.headers().getAllow()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.headers().getAllow()).isEqualTo(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS)); return response.writeTo(exchange, context); }); @@ -150,9 +149,8 @@ public class ResourceHandlerFunctionTests { StepVerifier.create(result) .expectComplete() .verify(); - assertEquals(HttpStatus.OK, mockResponse.getStatusCode()); - assertEquals(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS), - mockResponse.getHeaders().getAllow()); + assertThat(mockResponse.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(mockResponse.getHeaders().getAllow()).isEqualTo(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS)); StepVerifier.create(mockResponse.getBody()).expectComplete().verify(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionBuilderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionBuilderTests.java index e81285aeadd..65cb2b32f93 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionBuilderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionBuilderTests.java @@ -29,8 +29,7 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.server.RequestPredicates.HEAD; /** @@ -107,7 +106,7 @@ public class RouterFunctionBuilderTests { @Test public void resources() { Resource resource = new ClassPathResource("/org/springframework/web/reactive/function/server/"); - assertTrue(resource.exists()); + assertThat(resource.exists()).isTrue(); RouterFunction route = RouterFunctions.route() .resources("/resources/**", resource) @@ -175,20 +174,20 @@ public class RouterFunctionBuilderTests { .GET("/bar", request -> Mono.error(new IllegalStateException())) .before(request -> { int count = filterCount.getAndIncrement(); - assertEquals(0, count); + assertThat(count).isEqualTo(0); return request; }) .after((request, response) -> { int count = filterCount.getAndIncrement(); - assertEquals(3, count); + assertThat(count).isEqualTo(3); return response; }) .filter((request, next) -> { int count = filterCount.getAndIncrement(); - assertEquals(1, count); + assertThat(count).isEqualTo(1); Mono responseMono = next.handle(request); count = filterCount.getAndIncrement(); - assertEquals(2, count); + assertThat(count).isEqualTo(2); return responseMono; }) .onError(IllegalStateException.class, (e, request) -> ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build()) @@ -204,8 +203,7 @@ public class RouterFunctionBuilderTests { StepVerifier.create(fooResponseMono) - .consumeNextWith(serverResponse -> - assertEquals(4, filterCount.get()) + .consumeNextWith(serverResponse -> assertThat(filterCount.get()).isEqualTo(4) ) .verifyComplete(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionTests.java index 53766310efc..1963fc53fd4 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionTests.java @@ -20,13 +20,12 @@ import org.junit.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.BodyInserters.fromObject; /** * @author Arjen Poutsma */ -@SuppressWarnings("unchecked") public class RouterFunctionTests { @Test @@ -36,7 +35,7 @@ public class RouterFunctionTests { RouterFunction routerFunction2 = request -> Mono.just(handlerFunction); RouterFunction result = routerFunction1.and(routerFunction2); - assertNotNull(result); + assertThat(result).isNotNull(); MockServerRequest request = MockServerRequest.builder().build(); Mono> resultHandlerFunction = result.route(request); @@ -56,7 +55,7 @@ public class RouterFunctionTests { request -> Mono.just(handlerFunction); RouterFunction result = routerFunction1.andOther(routerFunction2); - assertNotNull(result); + assertThat(result).isNotNull(); MockServerRequest request = MockServerRequest.builder().build(); Mono> resultHandlerFunction = result.route(request); @@ -73,7 +72,7 @@ public class RouterFunctionTests { RequestPredicate requestPredicate = request -> true; RouterFunction result = routerFunction1.andRoute(requestPredicate, this::handlerMethod); - assertNotNull(result); + assertThat(result).isNotNull(); MockServerRequest request = MockServerRequest.builder().build(); Mono> resultHandlerFunction = result.route(request); @@ -101,7 +100,7 @@ public class RouterFunctionTests { }); RouterFunction>> result = routerFunction.filter(filterFunction); - assertNotNull(result); + assertThat(result).isNotNull(); MockServerRequest request = MockServerRequest.builder().build(); Mono>> responseMono = diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionsTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionsTests.java index 8c952ca19af..1491cfe49a7 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionsTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionsTests.java @@ -36,9 +36,7 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -46,7 +44,6 @@ import static org.mockito.Mockito.mock; * @author Arjen Poutsma * @since 5.0 */ -@SuppressWarnings("unchecked") public class RouterFunctionsTests { @Test @@ -59,7 +56,7 @@ public class RouterFunctionsTests { RouterFunction result = RouterFunctions.route(requestPredicate, handlerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); Mono> resultHandlerFunction = result.route(request); @@ -78,7 +75,7 @@ public class RouterFunctionsTests { given(requestPredicate.test(request)).willReturn(false); RouterFunction result = RouterFunctions.route(requestPredicate, handlerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); Mono> resultHandlerFunction = result.route(request); StepVerifier.create(resultHandlerFunction) @@ -96,7 +93,7 @@ public class RouterFunctionsTests { given(requestPredicate.nest(request)).willReturn(Optional.of(request)); RouterFunction result = RouterFunctions.nest(requestPredicate, routerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); Mono> resultHandlerFunction = result.route(request); StepVerifier.create(resultHandlerFunction) @@ -115,7 +112,7 @@ public class RouterFunctionsTests { given(requestPredicate.nest(request)).willReturn(Optional.empty()); RouterFunction result = RouterFunctions.nest(requestPredicate, routerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); Mono> resultHandlerFunction = result.route(request); StepVerifier.create(resultHandlerFunction) @@ -130,12 +127,12 @@ public class RouterFunctionsTests { RouterFunctions.route(RequestPredicates.all(), handlerFunction); HttpHandler result = RouterFunctions.toHttpHandler(routerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build(); MockServerHttpResponse httpResponse = new MockServerHttpResponse(); result.handle(httpRequest, httpResponse).block(); - assertEquals(HttpStatus.ACCEPTED, httpResponse.getStatusCode()); + assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED); } @Test @@ -148,12 +145,12 @@ public class RouterFunctionsTests { RouterFunctions.route(RequestPredicates.all(), handlerFunction); HttpHandler result = RouterFunctions.toHttpHandler(routerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build(); MockServerHttpResponse httpResponse = new MockServerHttpResponse(); result.handle(httpRequest, httpResponse).block(); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, httpResponse.getStatusCode()); + assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @Test @@ -164,12 +161,12 @@ public class RouterFunctionsTests { RouterFunctions.route(RequestPredicates.all(), handlerFunction); HttpHandler result = RouterFunctions.toHttpHandler(routerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build(); MockServerHttpResponse httpResponse = new MockServerHttpResponse(); result.handle(httpRequest, httpResponse).block(); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, httpResponse.getStatusCode()); + assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @Test @@ -180,12 +177,12 @@ public class RouterFunctionsTests { RouterFunctions.route(RequestPredicates.all(), handlerFunction); HttpHandler result = RouterFunctions.toHttpHandler(routerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build(); MockServerHttpResponse httpResponse = new MockServerHttpResponse(); result.handle(httpRequest, httpResponse).block(); - assertEquals(HttpStatus.NOT_FOUND, httpResponse.getStatusCode()); + assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test @@ -214,12 +211,12 @@ public class RouterFunctionsTests { RouterFunctions.route(RequestPredicates.all(), handlerFunction); HttpHandler result = RouterFunctions.toHttpHandler(routerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build(); MockServerHttpResponse httpResponse = new MockServerHttpResponse(); result.handle(httpRequest, httpResponse).block(); - assertEquals(HttpStatus.NOT_FOUND, httpResponse.getStatusCode()); + assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test @@ -248,12 +245,12 @@ public class RouterFunctionsTests { RouterFunctions.route(RequestPredicates.all(), handlerFunction); HttpHandler result = RouterFunctions.toHttpHandler(routerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build(); MockServerHttpResponse httpResponse = new MockServerHttpResponse(); result.handle(httpRequest, httpResponse).block(); - assertEquals(HttpStatus.NOT_FOUND, httpResponse.getStatusCode()); + assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test @@ -276,14 +273,14 @@ public class RouterFunctionsTests { .webFilter(webFilter).build(); HttpHandler result = RouterFunctions.toHttpHandler(routerFunction, handlerStrategies); - assertNotNull(result); + assertThat(result).isNotNull(); MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build(); MockServerHttpResponse httpResponse = new MockServerHttpResponse(); result.handle(httpRequest, httpResponse).block(); - assertEquals(HttpStatus.ACCEPTED, httpResponse.getStatusCode()); + assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED); - assertTrue(filterInvoked.get()); + assertThat(filterInvoked.get()).isTrue(); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/SseHandlerFunctionIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/SseHandlerFunctionIntegrationTests.java index b3be9c9b544..a55ca9afa6c 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/SseHandlerFunctionIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/SseHandlerFunctionIntegrationTests.java @@ -29,8 +29,7 @@ import org.springframework.http.MediaType; import org.springframework.http.codec.ServerSentEvent; import org.springframework.web.reactive.function.client.WebClient; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.http.MediaType.TEXT_EVENT_STREAM; import static org.springframework.web.reactive.function.BodyInserters.fromServerSentEvents; import static org.springframework.web.reactive.function.server.RouterFunctions.route; @@ -98,18 +97,18 @@ public class SseHandlerFunctionIntegrationTests extends AbstractRouterFunctionIn StepVerifier.create(result) .consumeNextWith( event -> { - assertEquals("0", event.id()); - assertEquals("foo", event.data()); - assertEquals("bar", event.comment()); - assertNull(event.event()); - assertNull(event.retry()); + assertThat(event.id()).isEqualTo("0"); + assertThat(event.data()).isEqualTo("foo"); + assertThat(event.comment()).isEqualTo("bar"); + assertThat(event.event()).isNull(); + assertThat(event.retry()).isNull(); }) .consumeNextWith( event -> { - assertEquals("1", event.id()); - assertEquals("foo", event.data()); - assertEquals("bar", event.comment()); - assertNull(event.event()); - assertNull(event.retry()); + assertThat(event.id()).isEqualTo("1"); + assertThat(event.data()).isEqualTo("foo"); + assertThat(event.comment()).isEqualTo("bar"); + assertThat(event.event()).isNull(); + assertThat(event.retry()).isNull(); }) .expectComplete() .verify(Duration.ofSeconds(5L)); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/ToStringVisitorTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/ToStringVisitorTests.java index 08801e1724b..988f06693a2 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/ToStringVisitorTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/ToStringVisitorTests.java @@ -22,7 +22,7 @@ import reactor.core.publisher.Mono; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.accept; import static org.springframework.web.reactive.function.server.RequestPredicates.contentType; @@ -58,7 +58,7 @@ public class ToStringVisitorTests { " (GET && /baz) -> \n" + " }\n" + "}"; - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); } @Test @@ -94,7 +94,7 @@ public class ToStringVisitorTests { predicate.accept(visitor); String result = visitor.toString(); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/support/DispatcherHandlerIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/support/DispatcherHandlerIntegrationTests.java index 484809e0cb5..7f142141639 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/support/DispatcherHandlerIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/support/DispatcherHandlerIntegrationTests.java @@ -34,7 +34,7 @@ import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.server.RequestPredicates.accept; import static org.springframework.web.reactive.function.server.RouterFunctions.route; @@ -61,7 +61,7 @@ public class DispatcherHandlerIntegrationTests extends AbstractHttpHandlerIntegr ResponseEntity result = this.restTemplate .getForEntity("http://localhost:" + this.port + "/foo/bar", String.class); - assertEquals(200, result.getStatusCodeValue()); + assertThat(result.getStatusCodeValue()).isEqualTo(200); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/support/ServerRequestWrapperTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/support/ServerRequestWrapperTests.java index b9480a6931e..1a7bef6f3b9 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/support/ServerRequestWrapperTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/server/support/ServerRequestWrapperTests.java @@ -35,8 +35,7 @@ import org.springframework.web.reactive.function.BodyExtractor; import org.springframework.web.reactive.function.BodyExtractors; import org.springframework.web.reactive.function.server.ServerRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -52,7 +51,7 @@ public class ServerRequestWrapperTests { @Test public void request() { - assertSame(mockRequest, wrapper.request()); + assertThat(wrapper.request()).isSameAs(mockRequest); } @Test @@ -60,7 +59,7 @@ public class ServerRequestWrapperTests { HttpMethod method = HttpMethod.POST; given(mockRequest.method()).willReturn(method); - assertSame(method, wrapper.method()); + assertThat(wrapper.method()).isSameAs(method); } @Test @@ -68,7 +67,7 @@ public class ServerRequestWrapperTests { URI uri = URI.create("https://example.com"); given(mockRequest.uri()).willReturn(uri); - assertSame(uri, wrapper.uri()); + assertThat(wrapper.uri()).isSameAs(uri); } @Test @@ -76,7 +75,7 @@ public class ServerRequestWrapperTests { String path = "/foo/bar"; given(mockRequest.path()).willReturn(path); - assertSame(path, wrapper.path()); + assertThat(wrapper.path()).isSameAs(path); } @Test @@ -84,7 +83,7 @@ public class ServerRequestWrapperTests { ServerRequest.Headers headers = mock(ServerRequest.Headers.class); given(mockRequest.headers()).willReturn(headers); - assertSame(headers, wrapper.headers()); + assertThat(wrapper.headers()).isSameAs(headers); } @Test @@ -93,7 +92,7 @@ public class ServerRequestWrapperTests { String value = "bar"; given(mockRequest.attribute(name)).willReturn(Optional.of(value)); - assertEquals(Optional.of(value), wrapper.attribute(name)); + assertThat(wrapper.attribute(name)).isEqualTo(Optional.of(value)); } @Test @@ -102,7 +101,7 @@ public class ServerRequestWrapperTests { String value = "bar"; given(mockRequest.queryParam(name)).willReturn(Optional.of(value)); - assertEquals(Optional.of(value), wrapper.queryParam(name)); + assertThat(wrapper.queryParam(name)).isEqualTo(Optional.of(value)); } @Test @@ -111,7 +110,7 @@ public class ServerRequestWrapperTests { value.add("foo", "bar"); given(mockRequest.queryParams()).willReturn(value); - assertSame(value, wrapper.queryParams()); + assertThat(wrapper.queryParams()).isSameAs(value); } @Test @@ -120,7 +119,7 @@ public class ServerRequestWrapperTests { String value = "bar"; given(mockRequest.pathVariable(name)).willReturn(value); - assertEquals(value, wrapper.pathVariable(name)); + assertThat(wrapper.pathVariable(name)).isEqualTo(value); } @Test @@ -128,7 +127,7 @@ public class ServerRequestWrapperTests { Map pathVariables = Collections.singletonMap("foo", "bar"); given(mockRequest.pathVariables()).willReturn(pathVariables); - assertSame(pathVariables, wrapper.pathVariables()); + assertThat(wrapper.pathVariables()).isSameAs(pathVariables); } @Test @@ -137,7 +136,7 @@ public class ServerRequestWrapperTests { MultiValueMap cookies = mock(MultiValueMap.class); given(mockRequest.cookies()).willReturn(cookies); - assertSame(cookies, wrapper.cookies()); + assertThat(wrapper.cookies()).isSameAs(cookies); } @Test @@ -146,7 +145,7 @@ public class ServerRequestWrapperTests { BodyExtractor, ReactiveHttpInputMessage> extractor = BodyExtractors.toMono(String.class); given(mockRequest.body(extractor)).willReturn(result); - assertSame(result, wrapper.body(extractor)); + assertThat(wrapper.body(extractor)).isSameAs(result); } @Test @@ -154,7 +153,7 @@ public class ServerRequestWrapperTests { Mono result = Mono.just("foo"); given(mockRequest.bodyToMono(String.class)).willReturn(result); - assertSame(result, wrapper.bodyToMono(String.class)); + assertThat(wrapper.bodyToMono(String.class)).isSameAs(result); } @Test @@ -163,7 +162,7 @@ public class ServerRequestWrapperTests { ParameterizedTypeReference reference = new ParameterizedTypeReference() {}; given(mockRequest.bodyToMono(reference)).willReturn(result); - assertSame(result, wrapper.bodyToMono(reference)); + assertThat(wrapper.bodyToMono(reference)).isSameAs(result); } @Test @@ -171,7 +170,7 @@ public class ServerRequestWrapperTests { Flux result = Flux.just("foo"); given(mockRequest.bodyToFlux(String.class)).willReturn(result); - assertSame(result, wrapper.bodyToFlux(String.class)); + assertThat(wrapper.bodyToFlux(String.class)).isSameAs(result); } @Test @@ -180,7 +179,7 @@ public class ServerRequestWrapperTests { ParameterizedTypeReference reference = new ParameterizedTypeReference() {}; given(mockRequest.bodyToFlux(reference)).willReturn(result); - assertSame(result, wrapper.bodyToFlux(reference)); + assertThat(wrapper.bodyToFlux(reference)).isSameAs(result); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/handler/CorsUrlHandlerMappingTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/handler/CorsUrlHandlerMappingTests.java index ca03dd92441..b7553d62512 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/handler/CorsUrlHandlerMappingTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/handler/CorsUrlHandlerMappingTests.java @@ -28,10 +28,7 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsConfigurationSource; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for CORS support at {@link AbstractUrlHandlerMapping} level. @@ -62,8 +59,8 @@ public class CorsUrlHandlerMappingTests { ServerWebExchange exchange = createExchange(HttpMethod.GET, "/welcome.html", origin); Object actual = this.handlerMapping.getHandler(exchange).block(); - assertNotNull(actual); - assertSame(this.welcomeController, actual); + assertThat(actual).isNotNull(); + assertThat(actual).isSameAs(this.welcomeController); } @Test @@ -72,8 +69,8 @@ public class CorsUrlHandlerMappingTests { ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", origin); Object actual = this.handlerMapping.getHandler(exchange).block(); - assertNotNull(actual); - assertSame(this.welcomeController, actual); + assertThat(actual).isNotNull(); + assertThat(actual).isSameAs(this.welcomeController); } @Test @@ -82,9 +79,9 @@ public class CorsUrlHandlerMappingTests { ServerWebExchange exchange = createExchange(HttpMethod.GET, "/cors.html", origin); Object actual = this.handlerMapping.getHandler(exchange).block(); - assertNotNull(actual); - assertSame(this.corsController, actual); - assertEquals("*", exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(actual).isNotNull(); + assertThat(actual).isSameAs(this.corsController); + assertThat(exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*"); } @Test @@ -93,9 +90,9 @@ public class CorsUrlHandlerMappingTests { ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/cors.html", origin); Object actual = this.handlerMapping.getHandler(exchange).block(); - assertNotNull(actual); - assertNotSame(this.corsController, actual); - assertEquals("*", exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(actual).isNotNull(); + assertThat(actual).isNotSameAs(this.corsController); + assertThat(exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*"); } @Test @@ -108,9 +105,9 @@ public class CorsUrlHandlerMappingTests { ServerWebExchange exchange = createExchange(HttpMethod.GET, "/welcome.html", origin); Object actual = this.handlerMapping.getHandler(exchange).block(); - assertNotNull(actual); - assertSame(this.welcomeController, actual); - assertEquals("*", exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(actual).isNotNull(); + assertThat(actual).isSameAs(this.welcomeController); + assertThat(exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*"); } @Test @@ -123,9 +120,9 @@ public class CorsUrlHandlerMappingTests { ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", origin); Object actual = this.handlerMapping.getHandler(exchange).block(); - assertNotNull(actual); - assertNotSame(this.welcomeController, actual); - assertEquals("*", exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + assertThat(actual).isNotNull(); + assertThat(actual).isNotSameAs(this.welcomeController); + assertThat(exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*"); } @Test @@ -136,12 +133,12 @@ public class CorsUrlHandlerMappingTests { ServerWebExchange exchange = createExchange(HttpMethod.GET, "/welcome.html", origin); Object actual = this.handlerMapping.getHandler(exchange).block(); - assertNotNull(actual); - assertSame(this.welcomeController, actual); - assertEquals("https://domain2.com", exchange.getResponse().getHeaders() - .getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("true", exchange.getResponse().getHeaders() - .getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assertThat(actual).isNotNull(); + assertThat(actual).isSameAs(this.welcomeController); + assertThat(exchange.getResponse().getHeaders() + .getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(exchange.getResponse().getHeaders() + .getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isEqualTo("true"); } @Test @@ -152,12 +149,12 @@ public class CorsUrlHandlerMappingTests { ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", origin); Object actual = this.handlerMapping.getHandler(exchange).block(); - assertNotNull(actual); - assertNotSame(this.welcomeController, actual); - assertEquals("https://domain2.com", exchange.getResponse().getHeaders() - .getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); - assertEquals("true", exchange.getResponse().getHeaders() - .getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)); + assertThat(actual).isNotNull(); + assertThat(actual).isNotSameAs(this.welcomeController); + assertThat(exchange.getResponse().getHeaders() + .getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("https://domain2.com"); + assertThat(exchange.getResponse().getHeaders() + .getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isEqualTo("true"); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/handler/SimpleUrlHandlerMappingTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/handler/SimpleUrlHandlerMappingTests.java index 319fbd42307..db055651db4 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/handler/SimpleUrlHandlerMappingTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/handler/SimpleUrlHandlerMappingTests.java @@ -31,10 +31,7 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.server.ServerWebExchange; -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.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE; /** @@ -106,15 +103,15 @@ public class SimpleUrlHandlerMappingTests { ServerWebExchange exchange = MockServerWebExchange.from(request); Object actual = handlerMapping.getHandler(exchange).block(); if (bean != null) { - assertNotNull(actual); - assertSame(bean, actual); + assertThat(actual).isNotNull(); + assertThat(actual).isSameAs(bean); //noinspection OptionalGetWithoutIsPresent PathContainer path = exchange.getAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); - assertNotNull(path); - assertEquals(pathWithinMapping, path.value()); + assertThat(path).isNotNull(); + assertThat(path.value()).isEqualTo(pathWithinMapping); } else { - assertNull(actual); + assertThat(actual).isNull(); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/handler/WebFluxResponseStatusExceptionHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/handler/WebFluxResponseStatusExceptionHandlerTests.java index 32ede970248..6e6705d0ef3 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/handler/WebFluxResponseStatusExceptionHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/handler/WebFluxResponseStatusExceptionHandlerTests.java @@ -25,7 +25,7 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.server.handler.ResponseStatusExceptionHandler; import org.springframework.web.server.handler.ResponseStatusExceptionHandlerTests; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link WebFluxResponseStatusExceptionHandler}. @@ -45,14 +45,14 @@ public class WebFluxResponseStatusExceptionHandlerTests extends ResponseStatusEx public void handleAnnotatedException() { Throwable ex = new CustomException(); this.handler.handle(this.exchange, ex).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.I_AM_A_TEAPOT, this.exchange.getResponse().getStatusCode()); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.I_AM_A_TEAPOT); } @Test public void handleNestedAnnotatedException() { Throwable ex = new Exception(new CustomException()); this.handler.handle(this.exchange, ex).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.I_AM_A_TEAPOT, this.exchange.getResponse().getStatusCode()); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.I_AM_A_TEAPOT); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/AppCacheManifestTransformerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/AppCacheManifestTransformerTests.java index 51b88f80161..bc790c1b234 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/AppCacheManifestTransformerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/AppCacheManifestTransformerTests.java @@ -30,9 +30,6 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; /** @@ -81,7 +78,7 @@ public class AppCacheManifestTransformerTests { Resource expected = getResource("foo.css"); Resource actual = this.transformer.transform(exchange, expected, this.chain).block(TIMEOUT); - assertSame(expected, actual); + assertThat(actual).isSameAs(expected); } @Test @@ -90,7 +87,7 @@ public class AppCacheManifestTransformerTests { Resource expected = getResource("error.appcache"); Resource actual = this.transformer.transform(exchange, expected, this.chain).block(TIMEOUT); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -99,7 +96,7 @@ public class AppCacheManifestTransformerTests { Resource resource = getResource("test.appcache"); Resource actual = this.transformer.transform(exchange, resource, this.chain).block(TIMEOUT); - assertNotNull(actual); + assertThat(actual).isNotNull(); byte[] bytes = FileCopyUtils.copyToByteArray(actual.getInputStream()); String content = new String(bytes, "UTF-8"); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/CachingResourceResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/CachingResourceResolverTests.java index 3b841573d8b..5fd210c3f74 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/CachingResourceResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/CachingResourceResolverTests.java @@ -31,10 +31,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.mock.web.test.server.MockServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; /** @@ -75,8 +72,8 @@ public class CachingResourceResolverTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("")); Resource actual = this.chain.resolveResource(exchange, "bar.css", this.locations).block(TIMEOUT); - assertNotSame(expected, actual); - assertEquals(expected, actual); + assertThat(actual).isNotSameAs(expected); + assertThat(actual).isEqualTo(expected); } @Test @@ -87,13 +84,13 @@ public class CachingResourceResolverTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("")); Resource actual = this.chain.resolveResource(exchange, "bar.css", this.locations).block(TIMEOUT); - assertSame(expected, actual); + assertThat(actual).isSameAs(expected); } @Test public void resolveResourceInternalNoMatch() { MockServerWebExchange exchange = MockServerWebExchange.from(get("")); - assertNull(this.chain.resolveResource(exchange, "invalid.css", this.locations).block(TIMEOUT)); + assertThat(this.chain.resolveResource(exchange, "invalid.css", this.locations).block(TIMEOUT)).isNull(); } @Test @@ -101,7 +98,7 @@ public class CachingResourceResolverTests { String expected = "/foo.css"; String actual = this.chain.resolveUrlPath(expected, this.locations).block(TIMEOUT); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -110,12 +107,12 @@ public class CachingResourceResolverTests { this.cache.put(CachingResourceResolver.RESOLVED_URL_PATH_CACHE_KEY_PREFIX + "imaginary.css", expected); String actual = this.chain.resolveUrlPath("imaginary.css", this.locations).block(TIMEOUT); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void resolverUrlPathNoMatch() { - assertNull(this.chain.resolveUrlPath("invalid.css", this.locations).block(TIMEOUT)); + assertThat(this.chain.resolveUrlPath("invalid.css", this.locations).block(TIMEOUT)).isNull(); } @Test @@ -130,7 +127,7 @@ public class CachingResourceResolverTests { Resource expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT); String cacheKey = resourceKey(file); - assertSame(expected, this.cache.get(cacheKey).get()); + assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); // 2. Resolve with Accept-Encoding @@ -140,7 +137,7 @@ public class CachingResourceResolverTests { expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT); cacheKey = resourceKey(file + "+encoding=br,gzip"); - assertSame(expected, this.cache.get(cacheKey).get()); + assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); // 3. Resolve with Accept-Encoding but no matching codings @@ -148,7 +145,7 @@ public class CachingResourceResolverTests { expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT); cacheKey = resourceKey(file); - assertSame(expected, this.cache.get(cacheKey).get()); + assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); } @Test @@ -160,7 +157,7 @@ public class CachingResourceResolverTests { String cacheKey = resourceKey(file); Object actual = this.cache.get(cacheKey).get(); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -172,10 +169,10 @@ public class CachingResourceResolverTests { String file = "bar.css"; MockServerWebExchange exchange = MockServerWebExchange.from(get(file)); - assertSame(resource, this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT)); + assertThat(this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT)).isSameAs(resource); exchange = MockServerWebExchange.from(get(file).header("Accept-Encoding", "gzip")); - assertSame(gzipped, this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT)); + assertThat(this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT)).isSameAs(gzipped); } private static String resourceKey(String key) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ContentBasedVersionStrategyTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ContentBasedVersionStrategyTests.java index ca2c74697c2..b66907b45cd 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ContentBasedVersionStrategyTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ContentBasedVersionStrategyTests.java @@ -26,8 +26,7 @@ import org.springframework.core.io.Resource; import org.springframework.util.DigestUtils; import org.springframework.util.FileCopyUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ContentVersionStrategy}. @@ -50,8 +49,8 @@ public class ContentBasedVersionStrategyTests { String hash = "7fbe76cdac6093784895bb4989203e5a"; String path = "font-awesome/css/font-awesome.min-" + hash + ".css"; - assertEquals(hash, this.strategy.extractVersion(path)); - assertNull(this.strategy.extractVersion("foo/bar.css")); + assertThat(this.strategy.extractVersion(path)).isEqualTo(hash); + assertThat(this.strategy.extractVersion("foo/bar.css")).isNull(); } @Test @@ -59,8 +58,7 @@ public class ContentBasedVersionStrategyTests { String hash = "7fbe76cdac6093784895bb4989203e5a"; String path = "font-awesome/css/font-awesome.min%s%s.css"; - assertEquals(String.format(path, "", ""), - this.strategy.removeVersion(String.format(path, "-", hash), hash)); + assertThat(this.strategy.removeVersion(String.format(path, "-", hash), hash)).isEqualTo(String.format(path, "", "")); } @Test @@ -68,12 +66,12 @@ public class ContentBasedVersionStrategyTests { Resource expected = new ClassPathResource("test/bar.css", getClass()); String hash = DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(expected.getInputStream())); - assertEquals(hash, this.strategy.getResourceVersion(expected).block()); + assertThat(this.strategy.getResourceVersion(expected).block()).isEqualTo(hash); } @Test public void addVersionToUrl() { - assertEquals("test/bar-123.css", this.strategy.addVersion("test/bar.css", "123")); + assertThat(this.strategy.addVersion("test/bar.css", "123")).isEqualTo("test/bar-123.css"); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/CssLinkResourceTransformerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/CssLinkResourceTransformerTests.java index 9fea87a3d26..0ccefb99590 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/CssLinkResourceTransformerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/CssLinkResourceTransformerTests.java @@ -32,8 +32,7 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.util.StringUtils; import org.springframework.web.reactive.resource.EncodedResourceResolver.EncodedResource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; /** @@ -91,7 +90,7 @@ public class CssLinkResourceTransformerTests { .consumeNextWith(transformedResource -> { String result = new String(transformedResource.getByteArray(), StandardCharsets.UTF_8); result = StringUtils.deleteAny(result, "\r"); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); }) .expectComplete() .verify(); @@ -103,7 +102,7 @@ public class CssLinkResourceTransformerTests { Resource expected = getResource("foo.css"); StepVerifier.create(this.transformerChain.transform(exchange, expected)) - .consumeNextWith(resource -> assertSame(expected, resource)) + .consumeNextWith(resource -> assertThat(resource).isSameAs(expected)) .expectComplete().verify(); } @@ -125,7 +124,7 @@ public class CssLinkResourceTransformerTests { .consumeNextWith(transformedResource -> { String result = new String(transformedResource.getByteArray(), StandardCharsets.UTF_8); result = StringUtils.deleteAny(result, "\r"); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); }) .expectComplete() .verify(); @@ -176,7 +175,7 @@ public class CssLinkResourceTransformerTests { .consumeNextWith(transformedResource -> { String result = new String(transformedResource.getByteArray(), StandardCharsets.UTF_8); result = StringUtils.deleteAny(result, "\r"); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); }) .expectComplete() .verify(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/EncodedResourceResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/EncodedResourceResolverTests.java index 0ada874fa78..2b249d533ee 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/EncodedResourceResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/EncodedResourceResolverTests.java @@ -42,9 +42,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.util.FileCopyUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link EncodedResourceResolver}. @@ -110,13 +108,14 @@ public class EncodedResourceResolverTests { String file = "js/foo.js"; Resource actual = this.resolver.resolveResource(exchange, file, this.locations).block(TIMEOUT); - assertEquals(getResource(file + ".gz").getDescription(), actual.getDescription()); - assertEquals(getResource(file).getFilename(), actual.getFilename()); + assertThat(actual.getDescription()).isEqualTo(getResource(file + ".gz").getDescription()); + assertThat(actual.getFilename()).isEqualTo(getResource(file).getFilename()); - assertTrue(actual instanceof HttpResource); + boolean condition = actual instanceof HttpResource; + assertThat(condition).isTrue(); HttpHeaders headers = ((HttpResource) actual).getResponseHeaders(); - assertEquals("gzip", headers.getFirst(HttpHeaders.CONTENT_ENCODING)); - assertEquals("Accept-Encoding", headers.getFirst(HttpHeaders.VARY)); + assertThat(headers.getFirst(HttpHeaders.CONTENT_ENCODING)).isEqualTo("gzip"); + assertThat(headers.getFirst(HttpHeaders.VARY)).isEqualTo("Accept-Encoding"); } @Test @@ -128,9 +127,10 @@ public class EncodedResourceResolverTests { String file = "foo-e36d2e05253c6c7085a91522ce43a0b4.css"; Resource actual = this.resolver.resolveResource(exchange, file, this.locations).block(TIMEOUT); - assertEquals(getResource("foo.css.gz").getDescription(), actual.getDescription()); - assertEquals(getResource("foo.css").getFilename(), actual.getFilename()); - assertTrue(actual instanceof HttpResource); + assertThat(actual.getDescription()).isEqualTo(getResource("foo.css.gz").getDescription()); + assertThat(actual.getFilename()).isEqualTo(getResource("foo.css").getFilename()); + boolean condition = actual instanceof HttpResource; + assertThat(condition).isTrue(); } @Test @@ -144,18 +144,20 @@ public class EncodedResourceResolverTests { String file = "js/foo.js"; Resource resolved = this.resolver.resolveResource(exchange, file, this.locations).block(TIMEOUT); - assertEquals(getResource(file + ".gz").getDescription(), resolved.getDescription()); - assertEquals(getResource(file).getFilename(), resolved.getFilename()); - assertTrue(resolved instanceof HttpResource); + assertThat(resolved.getDescription()).isEqualTo(getResource(file + ".gz").getDescription()); + assertThat(resolved.getFilename()).isEqualTo(getResource(file).getFilename()); + boolean condition = resolved instanceof HttpResource; + assertThat(condition).isTrue(); // 2. Resolve unencoded resource exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/js/foo.js")); resolved = this.resolver.resolveResource(exchange, file, this.locations).block(TIMEOUT); - assertEquals(getResource(file).getDescription(), resolved.getDescription()); - assertEquals(getResource(file).getFilename(), resolved.getFilename()); - assertFalse(resolved instanceof HttpResource); + assertThat(resolved.getDescription()).isEqualTo(getResource(file).getDescription()); + assertThat(resolved.getFilename()).isEqualTo(getResource(file).getFilename()); + boolean condition1 = resolved instanceof HttpResource; + assertThat(condition1).isFalse(); } @Test // SPR-13149 @@ -164,8 +166,8 @@ public class EncodedResourceResolverTests { String file = "js/foo.js"; Resource resolved = this.resolver.resolveResource(null, file, this.locations).block(TIMEOUT); - assertEquals(getResource(file).getDescription(), resolved.getDescription()); - assertEquals(getResource(file).getFilename(), resolved.getFilename()); + assertThat(resolved.getDescription()).isEqualTo(getResource(file).getDescription()); + assertThat(resolved.getFilename()).isEqualTo(getResource(file).getFilename()); } private Resource getResource(String filePath) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/FixedVersionStrategyTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/FixedVersionStrategyTests.java index d9b63830fc6..3d91832279c 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/FixedVersionStrategyTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/FixedVersionStrategyTests.java @@ -19,9 +19,8 @@ package org.springframework.web.reactive.resource; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * Unit tests for {@link FixedVersionStrategy}. @@ -52,24 +51,24 @@ public class FixedVersionStrategyTests { @Test public void extractVersion() { - assertEquals(VERSION, this.strategy.extractVersion(VERSION + "/" + PATH)); - assertNull(this.strategy.extractVersion(PATH)); + assertThat(this.strategy.extractVersion(VERSION + "/" + PATH)).isEqualTo(VERSION); + assertThat(this.strategy.extractVersion(PATH)).isNull(); } @Test public void removeVersion() { - assertEquals("/" + PATH, this.strategy.removeVersion(VERSION + "/" + PATH, VERSION)); + assertThat(this.strategy.removeVersion(VERSION + "/" + PATH, VERSION)).isEqualTo(("/" + PATH)); } @Test public void addVersion() { - assertEquals(VERSION + "/" + PATH, this.strategy.addVersion("/" + PATH, VERSION)); + assertThat(this.strategy.addVersion("/" + PATH, VERSION)).isEqualTo((VERSION + "/" + PATH)); } @Test // SPR-13727 public void addVersionRelativePath() { String relativePath = "../" + PATH; - assertEquals(relativePath, this.strategy.addVersion(relativePath, VERSION)); + assertThat(this.strategy.addVersion(relativePath, VERSION)).isEqualTo(relativePath); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/PathResourceResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/PathResourceResolverTests.java index 4afd4c07659..fedbf992b4c 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/PathResourceResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/PathResourceResolverTests.java @@ -27,11 +27,8 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import static java.util.Collections.singletonList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * Unit tests for {@link PathResourceResolver}. @@ -52,7 +49,7 @@ public class PathResourceResolverTests { List locations = singletonList(location); Resource actual = this.resolver.resolveResource(null, path, locations, null).block(TIMEOUT); - assertEquals(location.createRelative(path), actual); + assertThat(actual).isEqualTo(location.createRelative(path)); } @Test @@ -62,7 +59,7 @@ public class PathResourceResolverTests { List locations = singletonList(location); Resource actual = this.resolver.resolveResource(null, path, locations, null).block(TIMEOUT); - assertNotNull(actual); + assertThat(actual).isNotNull(); } @Test // gh-22272 @@ -77,8 +74,8 @@ public class PathResourceResolverTests { List locations = singletonList(location); Resource actual = this.resolver.resolveResource(null, path, locations, null).block(TIMEOUT); - assertNotNull(actual); - assertEquals("foo foo.txt", actual.getFile().getName()); + assertThat(actual).isNotNull(); + assertThat(actual.getFile().getName()).isEqualTo("foo foo.txt"); } @Test @@ -106,7 +103,7 @@ public class PathResourceResolverTests { if (!location.createRelative(requestPath).exists() && !requestPath.contains(":")) { fail(requestPath + " doesn't actually exist as a relative path"); } - assertNull(actual); + assertThat(actual).isNull(); } @Test @@ -120,7 +117,7 @@ public class PathResourceResolverTests { String actual = this.resolver.resolveUrlPath("../testalternatepath/bar.css", singletonList(location), null).block(TIMEOUT); - assertEquals("../testalternatepath/bar.css", actual); + assertThat(actual).isEqualTo("../testalternatepath/bar.css"); } @Test // SPR-12624 @@ -128,13 +125,13 @@ public class PathResourceResolverTests { String locationUrl= new UrlResource(getClass().getResource("./test/")).getURL().toExternalForm(); Resource location = new UrlResource(locationUrl.replace("/springframework","/../org/springframework")); List locations = singletonList(location); - assertNotNull(this.resolver.resolveResource(null, "main.css", locations, null).block(TIMEOUT)); + assertThat(this.resolver.resolveResource(null, "main.css", locations, null).block(TIMEOUT)).isNotNull(); } @Test // SPR-12747 public void checkFileLocation() throws Exception { Resource resource = getResource("main.css"); - assertTrue(this.resolver.checkResource(resource, resource)); + assertThat(this.resolver.checkResource(resource, resource)).isTrue(); } @Test // SPR-13241 @@ -143,7 +140,7 @@ public class PathResourceResolverTests { String path = this.resolver.resolveUrlPathInternal( "", singletonList(webjarsLocation), null).block(TIMEOUT); - assertNull(path); + assertThat(path).isNull(); } private Resource getResource(String filePath) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceTransformerSupportTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceTransformerSupportTests.java index 425d75167a6..bee7282f2ec 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceTransformerSupportTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceTransformerSupportTests.java @@ -31,7 +31,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@code ResourceTransformerSupport}. @@ -84,8 +84,8 @@ public class ResourceTransformerSupportTests { Resource resource = getResource("main.css"); String actual = this.transformer.resolveUrlPath(resourcePath, exchange, resource, this.chain).block(TIMEOUT); - assertEquals("/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", actual); - assertEquals("/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", actual); + assertThat(actual).isEqualTo("/resources/bar-11e16cf79faee7ac698c805cf28248d2.css"); + assertThat(actual).isEqualTo("/resources/bar-11e16cf79faee7ac698c805cf28248d2.css"); } @Test @@ -94,7 +94,7 @@ public class ResourceTransformerSupportTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); String actual = this.transformer.resolveUrlPath("bar.css", exchange, resource, this.chain).block(TIMEOUT); - assertEquals("bar-11e16cf79faee7ac698c805cf28248d2.css", actual); + assertThat(actual).isEqualTo("bar-11e16cf79faee7ac698c805cf28248d2.css"); } @Test @@ -103,17 +103,17 @@ public class ResourceTransformerSupportTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); String actual = this.transformer.resolveUrlPath("../bar.css", exchange, resource, this.chain).block(TIMEOUT); - assertEquals("../bar-11e16cf79faee7ac698c805cf28248d2.css", actual); + assertThat(actual).isEqualTo("../bar-11e16cf79faee7ac698c805cf28248d2.css"); } @Test public void toAbsolutePath() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/resources/main.css")); String absolute = this.transformer.toAbsolutePath("img/image.png", exchange); - assertEquals("/resources/img/image.png", absolute); + assertThat(absolute).isEqualTo("/resources/img/image.png"); absolute = this.transformer.toAbsolutePath("/img/image.png", exchange); - assertEquals("/img/image.png", absolute); + assertThat(absolute).isEqualTo("/img/image.png"); } private Resource getResource(String filePath) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java index 4a61937313f..0ac197beb8d 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java @@ -38,7 +38,6 @@ import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; import org.springframework.web.util.pattern.PathPattern; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; /** @@ -78,7 +77,7 @@ public class ResourceUrlProviderTests { String expected = "/resources/foo.css"; String actual = this.urlProvider.getForUriString(expected, this.exchange).block(TIMEOUT); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test // SPR-13374 @@ -86,11 +85,11 @@ public class ResourceUrlProviderTests { String url = "/resources/foo.css?foo=bar&url=https://example.org"; String resolvedUrl = this.urlProvider.getForUriString(url, this.exchange).block(TIMEOUT); - assertEquals(url, resolvedUrl); + assertThat(resolvedUrl).isEqualTo(url); url = "/resources/foo.css#hash"; resolvedUrl = this.urlProvider.getForUriString(url, this.exchange).block(TIMEOUT); - assertEquals(url, resolvedUrl); + assertThat(resolvedUrl).isEqualTo(url); } @Test @@ -105,7 +104,7 @@ public class ResourceUrlProviderTests { String path = "/resources/foo.css"; String url = this.urlProvider.getForUriString(path, this.exchange).block(TIMEOUT); - assertEquals("/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css", url); + assertThat(url).isEqualTo("/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css"); } @Test // SPR-12647 @@ -125,7 +124,7 @@ public class ResourceUrlProviderTests { String path = "/resources/foo.css"; String url = this.urlProvider.getForUriString(path, this.exchange).block(TIMEOUT); - assertEquals("/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css", url); + assertThat(url).isEqualTo("/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css"); } @Test // SPR-12592 diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java index e85321a6dd8..d9f88365934 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java @@ -58,12 +58,7 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -104,13 +99,13 @@ public class ResourceWebHandlerTests { this.handler.handle(exchange).block(TIMEOUT); HttpHeaders headers = exchange.getResponse().getHeaders(); - assertEquals(MediaType.parseMediaType("text/css"), headers.getContentType()); - assertEquals(17, headers.getContentLength()); - assertEquals("max-age=3600", headers.getCacheControl()); - assertTrue(headers.containsKey("Last-Modified")); - assertEquals(headers.getLastModified() / 1000, resourceLastModifiedDate("test/foo.css") / 1000); - assertEquals("bytes", headers.getFirst("Accept-Ranges")); - assertEquals(1, headers.get("Accept-Ranges").size()); + assertThat(headers.getContentType()).isEqualTo(MediaType.parseMediaType("text/css")); + assertThat(headers.getContentLength()).isEqualTo(17); + assertThat(headers.getCacheControl()).isEqualTo("max-age=3600"); + assertThat(headers.containsKey("Last-Modified")).isTrue(); + assertThat(resourceLastModifiedDate("test/foo.css") / 1000).isEqualTo(headers.getLastModified() / 1000); + assertThat(headers.getFirst("Accept-Ranges")).isEqualTo("bytes"); + assertThat(headers.get("Accept-Ranges").size()).isEqualTo(1); assertResponseBody(exchange, "h1 { color:red; }"); } @@ -120,15 +115,15 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.css"); this.handler.handle(exchange).block(TIMEOUT); - assertNull(exchange.getResponse().getStatusCode()); + assertThat((Object) exchange.getResponse().getStatusCode()).isNull(); HttpHeaders headers = exchange.getResponse().getHeaders(); - assertEquals(MediaType.parseMediaType("text/css"), headers.getContentType()); - assertEquals(17, headers.getContentLength()); - assertEquals("max-age=3600", headers.getCacheControl()); - assertTrue(headers.containsKey("Last-Modified")); - assertEquals(headers.getLastModified() / 1000, resourceLastModifiedDate("test/foo.css") / 1000); - assertEquals("bytes", headers.getFirst("Accept-Ranges")); - assertEquals(1, headers.get("Accept-Ranges").size()); + assertThat(headers.getContentType()).isEqualTo(MediaType.parseMediaType("text/css")); + assertThat(headers.getContentLength()).isEqualTo(17); + assertThat(headers.getCacheControl()).isEqualTo("max-age=3600"); + assertThat(headers.containsKey("Last-Modified")).isTrue(); + assertThat(resourceLastModifiedDate("test/foo.css") / 1000).isEqualTo(headers.getLastModified() / 1000); + assertThat(headers.getFirst("Accept-Ranges")).isEqualTo("bytes"); + assertThat(headers.get("Accept-Ranges").size()).isEqualTo(1); StepVerifier.create(exchange.getResponse().getBody()) .expectErrorMatches(ex -> ex.getMessage().startsWith("No content was written")) @@ -141,8 +136,8 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.css"); this.handler.handle(exchange).block(TIMEOUT); - assertNull(exchange.getResponse().getStatusCode()); - assertEquals("GET,HEAD,OPTIONS", exchange.getResponse().getHeaders().getFirst("Allow")); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + assertThat(exchange.getResponse().getHeaders().getFirst("Allow")).isEqualTo("GET,HEAD,OPTIONS"); } @Test @@ -153,11 +148,11 @@ public class ResourceWebHandlerTests { this.handler.handle(exchange).block(TIMEOUT); MockServerHttpResponse response = exchange.getResponse(); - assertEquals("no-store", response.getHeaders().getCacheControl()); - assertTrue(response.getHeaders().containsKey("Last-Modified")); - assertEquals(response.getHeaders().getLastModified() / 1000, resourceLastModifiedDate("test/foo.css") / 1000); - assertEquals("bytes", response.getHeaders().getFirst("Accept-Ranges")); - assertEquals(1, response.getHeaders().get("Accept-Ranges").size()); + assertThat(response.getHeaders().getCacheControl()).isEqualTo("no-store"); + assertThat(response.getHeaders().containsKey("Last-Modified")).isTrue(); + assertThat(resourceLastModifiedDate("test/foo.css") / 1000).isEqualTo(response.getHeaders().getLastModified() / 1000); + assertThat(response.getHeaders().getFirst("Accept-Ranges")).isEqualTo("bytes"); + assertThat(response.getHeaders().get("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -171,9 +166,9 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "versionString/foo.css"); this.handler.handle(exchange).block(TIMEOUT); - assertEquals("\"versionString\"", exchange.getResponse().getHeaders().getETag()); - assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges")); - assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size()); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo("\"versionString\""); + assertThat(exchange.getResponse().getHeaders().getFirst("Accept-Ranges")).isEqualTo("bytes"); + assertThat(exchange.getResponse().getHeaders().get("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -183,12 +178,12 @@ public class ResourceWebHandlerTests { this.handler.handle(exchange).block(TIMEOUT); HttpHeaders headers = exchange.getResponse().getHeaders(); - assertEquals(MediaType.TEXT_HTML, headers.getContentType()); - assertEquals("max-age=3600", headers.getCacheControl()); - assertTrue(headers.containsKey("Last-Modified")); - assertEquals(headers.getLastModified() / 1000, resourceLastModifiedDate("test/foo.html") / 1000); - assertEquals("bytes", headers.getFirst("Accept-Ranges")); - assertEquals(1, headers.get("Accept-Ranges").size()); + assertThat(headers.getContentType()).isEqualTo(MediaType.TEXT_HTML); + assertThat(headers.getCacheControl()).isEqualTo("max-age=3600"); + assertThat(headers.containsKey("Last-Modified")).isTrue(); + assertThat(resourceLastModifiedDate("test/foo.html") / 1000).isEqualTo(headers.getLastModified() / 1000); + assertThat(headers.getFirst("Accept-Ranges")).isEqualTo("bytes"); + assertThat(headers.get("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -198,13 +193,13 @@ public class ResourceWebHandlerTests { this.handler.handle(exchange).block(TIMEOUT); HttpHeaders headers = exchange.getResponse().getHeaders(); - assertEquals(MediaType.parseMediaType("text/css"), headers.getContentType()); - assertEquals(17, headers.getContentLength()); - assertEquals("max-age=3600", headers.getCacheControl()); - assertTrue(headers.containsKey("Last-Modified")); - assertEquals(headers.getLastModified() / 1000, resourceLastModifiedDate("testalternatepath/baz.css") / 1000); - assertEquals("bytes", headers.getFirst("Accept-Ranges")); - assertEquals(1, headers.get("Accept-Ranges").size()); + assertThat(headers.getContentType()).isEqualTo(MediaType.parseMediaType("text/css")); + assertThat(headers.getContentLength()).isEqualTo(17); + assertThat(headers.getCacheControl()).isEqualTo("max-age=3600"); + assertThat(headers.containsKey("Last-Modified")).isTrue(); + assertThat(resourceLastModifiedDate("testalternatepath/baz.css") / 1000).isEqualTo(headers.getLastModified() / 1000); + assertThat(headers.getFirst("Accept-Ranges")).isEqualTo("bytes"); + assertThat(headers.get("Accept-Ranges").size()).isEqualTo(1); assertResponseBody(exchange, "h1 { color:red; }"); } @@ -214,8 +209,7 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "js/foo.js"); this.handler.handle(exchange).block(TIMEOUT); - assertEquals(MediaType.parseMediaType("application/javascript"), - exchange.getResponse().getHeaders().getContentType()); + assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.parseMediaType("application/javascript")); assertResponseBody(exchange, "function foo() { console.log(\"hello world\"); }"); } @@ -226,7 +220,7 @@ public class ResourceWebHandlerTests { this.handler.handle(exchange).block(TIMEOUT); HttpHeaders headers = exchange.getResponse().getHeaders(); - assertEquals(MediaType.parseMediaType("application/javascript"), headers.getContentType()); + assertThat(headers.getContentType()).isEqualTo(MediaType.parseMediaType("application/javascript")); assertResponseBody(exchange, "function foo() { console.log(\"hello world\"); }"); } @@ -242,7 +236,7 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.html"); handler.handle(exchange).block(TIMEOUT); - assertEquals(MediaType.TEXT_HTML, exchange.getResponse().getHeaders().getContentType()); + assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_HTML); } @Test @@ -287,7 +281,7 @@ public class ResourceWebHandlerTests { StepVerifier.create(handler.handle(exchange)) .expectErrorSatisfies(err -> { assertThat(err).isInstanceOf(ResponseStatusException.class); - assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); + assertThat(((ResponseStatusException) err).getStatus()).isEqualTo(HttpStatus.NOT_FOUND); }).verify(TIMEOUT); } @@ -333,7 +327,7 @@ public class ResourceWebHandlerTests { StepVerifier.create(this.handler.handle(exchange)) .expectErrorSatisfies(err -> { assertThat(err).isInstanceOf(ResponseStatusException.class); - assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); + assertThat(((ResponseStatusException) err).getStatus()).isEqualTo(HttpStatus.NOT_FOUND); }) .verify(TIMEOUT); if (!location.createRelative(requestPath).exists() && !requestPath.contains(":")) { @@ -343,31 +337,31 @@ public class ResourceWebHandlerTests { @Test public void processPath() { - assertSame("/foo/bar", this.handler.processPath("/foo/bar")); - assertSame("foo/bar", this.handler.processPath("foo/bar")); + assertThat(this.handler.processPath("/foo/bar")).isSameAs("/foo/bar"); + assertThat(this.handler.processPath("foo/bar")).isSameAs("foo/bar"); // leading whitespace control characters (00-1F) - assertEquals("/foo/bar", this.handler.processPath(" /foo/bar")); - assertEquals("/foo/bar", this.handler.processPath((char) 1 + "/foo/bar")); - assertEquals("/foo/bar", this.handler.processPath((char) 31 + "/foo/bar")); - assertEquals("foo/bar", this.handler.processPath(" foo/bar")); - assertEquals("foo/bar", this.handler.processPath((char) 31 + "foo/bar")); + assertThat(this.handler.processPath(" /foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath((char) 1 + "/foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath((char) 31 + "/foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath(" foo/bar")).isEqualTo("foo/bar"); + assertThat(this.handler.processPath((char) 31 + "foo/bar")).isEqualTo("foo/bar"); // leading control character 0x7F (DEL) - assertEquals("/foo/bar", this.handler.processPath((char) 127 + "/foo/bar")); - assertEquals("/foo/bar", this.handler.processPath((char) 127 + "/foo/bar")); + assertThat(this.handler.processPath((char) 127 + "/foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath((char) 127 + "/foo/bar")).isEqualTo("/foo/bar"); // leading control and '/' characters - assertEquals("/foo/bar", this.handler.processPath(" / foo/bar")); - assertEquals("/foo/bar", this.handler.processPath(" / / foo/bar")); - assertEquals("/foo/bar", this.handler.processPath(" // /// //// foo/bar")); - assertEquals("/foo/bar", this.handler.processPath((char) 1 + " / " + (char) 127 + " // foo/bar")); + assertThat(this.handler.processPath(" / foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath(" / / foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath(" // /// //// foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath((char) 1 + " / " + (char) 127 + " // foo/bar")).isEqualTo("/foo/bar"); // root or empty path - assertEquals("", this.handler.processPath(" ")); - assertEquals("/", this.handler.processPath("/")); - assertEquals("/", this.handler.processPath("///")); - assertEquals("/", this.handler.processPath("/ / / ")); + assertThat(this.handler.processPath(" ")).isEqualTo(""); + assertThat(this.handler.processPath("/")).isEqualTo("/"); + assertThat(this.handler.processPath("///")).isEqualTo("/"); + assertThat(this.handler.processPath("/ / / ")).isEqualTo("/"); } @Test @@ -375,10 +369,10 @@ public class ResourceWebHandlerTests { PathResourceResolver resolver = (PathResourceResolver) this.handler.getResourceResolvers().get(0); Resource[] locations = resolver.getAllowedLocations(); - assertEquals(3, locations.length); - assertEquals("test/", ((ClassPathResource) locations[0]).getPath()); - assertEquals("testalternatepath/", ((ClassPathResource) locations[1]).getPath()); - assertEquals("META-INF/resources/webjars/", ((ClassPathResource) locations[2]).getPath()); + assertThat(locations.length).isEqualTo(3); + assertThat(((ClassPathResource) locations[0]).getPath()).isEqualTo("test/"); + assertThat(((ClassPathResource) locations[1]).getPath()).isEqualTo("testalternatepath/"); + assertThat(((ClassPathResource) locations[2]).getPath()).isEqualTo("META-INF/resources/webjars/"); } @Test @@ -395,8 +389,8 @@ public class ResourceWebHandlerTests { handler.afterPropertiesSet(); Resource[] locations = pathResolver.getAllowedLocations(); - assertEquals(1, locations.length); - assertEquals("test/", ((ClassPathResource) locations[0]).getPath()); + assertThat(locations.length).isEqualTo(1); + assertThat(((ClassPathResource) locations[0]).getPath()).isEqualTo("test/"); } @Test @@ -406,7 +400,7 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.css"); this.handler.handle(exchange).block(TIMEOUT); - assertEquals(HttpStatus.NOT_MODIFIED, exchange.getResponse().getStatusCode()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_MODIFIED); } @Test @@ -417,7 +411,7 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.css"); this.handler.handle(exchange).block(TIMEOUT); - assertNull(exchange.getResponse().getStatusCode()); + assertThat((Object) exchange.getResponse().getStatusCode()).isNull(); assertResponseBody(exchange, "h1 { color:red; }"); } @@ -428,7 +422,7 @@ public class ResourceWebHandlerTests { StepVerifier.create(this.handler.handle(exchange)) .expectErrorSatisfies(err -> { assertThat(err).isInstanceOf(ResponseStatusException.class); - assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); + assertThat(((ResponseStatusException) err).getStatus()).isEqualTo(HttpStatus.NOT_FOUND); }).verify(TIMEOUT); } @@ -439,7 +433,7 @@ public class ResourceWebHandlerTests { StepVerifier.create(this.handler.handle(exchange)) .expectErrorSatisfies(err -> { assertThat(err).isInstanceOf(ResponseStatusException.class); - assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); + assertThat(((ResponseStatusException) err).getStatus()).isEqualTo(HttpStatus.NOT_FOUND); }).verify(TIMEOUT); } @@ -450,7 +444,7 @@ public class ResourceWebHandlerTests { StepVerifier.create(this.handler.handle(exchange)) .expectErrorSatisfies(err -> { assertThat(err).isInstanceOf(ResponseStatusException.class); - assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); + assertThat(((ResponseStatusException) err).getStatus()).isEqualTo(HttpStatus.NOT_FOUND); }).verify(TIMEOUT); } @@ -485,13 +479,13 @@ public class ResourceWebHandlerTests { StepVerifier.create(mono) .expectErrorSatisfies(err -> { assertThat(err).isInstanceOf(ResponseStatusException.class); - assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus()); + assertThat(((ResponseStatusException) err).getStatus()).isEqualTo(HttpStatus.NOT_FOUND); }).verify(TIMEOUT); // SPR-17475 AtomicReference exceptionRef = new AtomicReference<>(); StepVerifier.create(mono).consumeErrorWith(exceptionRef::set).verify(); - StepVerifier.create(mono).consumeErrorWith(ex -> assertNotSame(exceptionRef.get(), ex)).verify(); + StepVerifier.create(mono).consumeErrorWith(ex -> assertThat(ex).isNotSameAs(exceptionRef.get())).verify(); } @Test @@ -501,12 +495,12 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.txt"); this.handler.handle(exchange).block(TIMEOUT); - assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode()); - assertEquals(MediaType.TEXT_PLAIN, exchange.getResponse().getHeaders().getContentType()); - assertEquals(2, exchange.getResponse().getHeaders().getContentLength()); - assertEquals("bytes 0-1/10", exchange.getResponse().getHeaders().getFirst("Content-Range")); - assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges")); - assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.PARTIAL_CONTENT); + assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(exchange.getResponse().getHeaders().getContentLength()).isEqualTo(2); + assertThat(exchange.getResponse().getHeaders().getFirst("Content-Range")).isEqualTo("bytes 0-1/10"); + assertThat(exchange.getResponse().getHeaders().getFirst("Accept-Ranges")).isEqualTo("bytes"); + assertThat(exchange.getResponse().getHeaders().get("Accept-Ranges").size()).isEqualTo(1); assertResponseBody(exchange, "So"); } @@ -517,12 +511,12 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.txt"); this.handler.handle(exchange).block(TIMEOUT); - assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode()); - assertEquals(MediaType.TEXT_PLAIN, exchange.getResponse().getHeaders().getContentType()); - assertEquals(1, exchange.getResponse().getHeaders().getContentLength()); - assertEquals("bytes 9-9/10", exchange.getResponse().getHeaders().getFirst("Content-Range")); - assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges")); - assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.PARTIAL_CONTENT); + assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(exchange.getResponse().getHeaders().getContentLength()).isEqualTo(1); + assertThat(exchange.getResponse().getHeaders().getFirst("Content-Range")).isEqualTo("bytes 9-9/10"); + assertThat(exchange.getResponse().getHeaders().getFirst("Accept-Ranges")).isEqualTo("bytes"); + assertThat(exchange.getResponse().getHeaders().get("Accept-Ranges").size()).isEqualTo(1); assertResponseBody(exchange, "."); } @@ -533,12 +527,12 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.txt"); this.handler.handle(exchange).block(TIMEOUT); - assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode()); - assertEquals(MediaType.TEXT_PLAIN, exchange.getResponse().getHeaders().getContentType()); - assertEquals(1, exchange.getResponse().getHeaders().getContentLength()); - assertEquals("bytes 9-9/10", exchange.getResponse().getHeaders().getFirst("Content-Range")); - assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges")); - assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.PARTIAL_CONTENT); + assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(exchange.getResponse().getHeaders().getContentLength()).isEqualTo(1); + assertThat(exchange.getResponse().getHeaders().getFirst("Content-Range")).isEqualTo("bytes 9-9/10"); + assertThat(exchange.getResponse().getHeaders().getFirst("Accept-Ranges")).isEqualTo("bytes"); + assertThat(exchange.getResponse().getHeaders().get("Accept-Ranges").size()).isEqualTo(1); assertResponseBody(exchange, "."); } @@ -549,12 +543,12 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.txt"); this.handler.handle(exchange).block(TIMEOUT); - assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode()); - assertEquals(MediaType.TEXT_PLAIN, exchange.getResponse().getHeaders().getContentType()); - assertEquals(1, exchange.getResponse().getHeaders().getContentLength()); - assertEquals("bytes 9-9/10", exchange.getResponse().getHeaders().getFirst("Content-Range")); - assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges")); - assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.PARTIAL_CONTENT); + assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(exchange.getResponse().getHeaders().getContentLength()).isEqualTo(1); + assertThat(exchange.getResponse().getHeaders().getFirst("Content-Range")).isEqualTo("bytes 9-9/10"); + assertThat(exchange.getResponse().getHeaders().getFirst("Accept-Ranges")).isEqualTo("bytes"); + assertThat(exchange.getResponse().getHeaders().get("Accept-Ranges").size()).isEqualTo(1); assertResponseBody(exchange, "."); } @@ -565,12 +559,12 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.txt"); this.handler.handle(exchange).block(TIMEOUT); - assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode()); - assertEquals(MediaType.TEXT_PLAIN, exchange.getResponse().getHeaders().getContentType()); - assertEquals(10, exchange.getResponse().getHeaders().getContentLength()); - assertEquals("bytes 0-9/10", exchange.getResponse().getHeaders().getFirst("Content-Range")); - assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges")); - assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.PARTIAL_CONTENT); + assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); + assertThat(exchange.getResponse().getHeaders().getContentLength()).isEqualTo(10); + assertThat(exchange.getResponse().getHeaders().getFirst("Content-Range")).isEqualTo("bytes 0-9/10"); + assertThat(exchange.getResponse().getHeaders().getFirst("Accept-Ranges")).isEqualTo("bytes"); + assertThat(exchange.getResponse().getHeaders().get("Accept-Ranges").size()).isEqualTo(1); assertResponseBody(exchange, "Some text."); } @@ -585,8 +579,8 @@ public class ResourceWebHandlerTests { .expectComplete() .verify(); - assertEquals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE, exchange.getResponse().getStatusCode()); - assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges")); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE); + assertThat(exchange.getResponse().getHeaders().getFirst("Accept-Ranges")).isEqualTo("bytes"); } @Test @@ -596,9 +590,9 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.txt"); this.handler.handle(exchange).block(TIMEOUT); - assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode()); - assertTrue(exchange.getResponse().getHeaders().getContentType().toString() - .startsWith("multipart/byteranges;boundary=")); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.PARTIAL_CONTENT); + assertThat(exchange.getResponse().getHeaders().getContentType().toString() + .startsWith("multipart/byteranges;boundary=")).isTrue(); String boundary = "--" + exchange.getResponse().getHeaders().getContentType().toString().substring(30); @@ -614,20 +608,20 @@ public class ResourceWebHandlerTests { String content = DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8); String[] ranges = StringUtils.tokenizeToStringArray(content, "\r\n", false, true); - assertEquals(boundary, ranges[0]); - assertEquals("Content-Type: text/plain", ranges[1]); - assertEquals("Content-Range: bytes 0-1/10", ranges[2]); - assertEquals("So", ranges[3]); + assertThat(ranges[0]).isEqualTo(boundary); + assertThat(ranges[1]).isEqualTo("Content-Type: text/plain"); + assertThat(ranges[2]).isEqualTo("Content-Range: bytes 0-1/10"); + assertThat(ranges[3]).isEqualTo("So"); - assertEquals(boundary, ranges[4]); - assertEquals("Content-Type: text/plain", ranges[5]); - assertEquals("Content-Range: bytes 4-5/10", ranges[6]); - assertEquals(" t", ranges[7]); + assertThat(ranges[4]).isEqualTo(boundary); + assertThat(ranges[5]).isEqualTo("Content-Type: text/plain"); + assertThat(ranges[6]).isEqualTo("Content-Range: bytes 4-5/10"); + assertThat(ranges[7]).isEqualTo(" t"); - assertEquals(boundary, ranges[8]); - assertEquals("Content-Type: text/plain", ranges[9]); - assertEquals("Content-Range: bytes 8-9/10", ranges[10]); - assertEquals("t.", ranges[11]); + assertThat(ranges[8]).isEqualTo(boundary); + assertThat(ranges[9]).isEqualTo("Content-Type: text/plain"); + assertThat(ranges[10]).isEqualTo("Content-Range: bytes 8-9/10"); + assertThat(ranges[11]).isEqualTo("t."); }) .expectComplete() .verify(); @@ -640,7 +634,7 @@ public class ResourceWebHandlerTests { setPathWithinHandlerMapping(exchange, "foo.css"); this.handler.handle(exchange).block(TIMEOUT); - assertEquals("max-age=3600", exchange.getResponse().getHeaders().getCacheControl()); + assertThat(exchange.getResponse().getHeaders().getCacheControl()).isEqualTo("max-age=3600"); } @@ -659,8 +653,7 @@ public class ResourceWebHandlerTests { private void assertResponseBody(MockServerWebExchange exchange, String responseBody) { StepVerifier.create(exchange.getResponse().getBody()) - .consumeNextWith(buf -> assertEquals(responseBody, - DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8))) + .consumeNextWith(buf -> assertThat(DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8)).isEqualTo(responseBody)) .expectComplete() .verify(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/VersionResourceResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/VersionResourceResolverTests.java index 1251f44181c..295732c61bf 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/VersionResourceResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/VersionResourceResolverTests.java @@ -34,8 +34,6 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -80,7 +78,7 @@ public class VersionResourceResolverTests { .resolveResourceInternal(null, file, this.locations, this.chain) .block(Duration.ofMillis(5000)); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); verify(this.chain, times(1)).resolveResource(null, file, this.locations); verify(this.versionStrategy, never()).extractVersion(file); } @@ -95,7 +93,7 @@ public class VersionResourceResolverTests { .resolveResourceInternal(null, file, this.locations, this.chain) .block(Duration.ofMillis(5000)); - assertNull(actual); + assertThat((Object) actual).isNull(); verify(this.chain, times(1)).resolveResource(null, file, this.locations); } @@ -110,7 +108,7 @@ public class VersionResourceResolverTests { .resolveResourceInternal(null, file, this.locations, this.chain) .block(Duration.ofMillis(5000)); - assertNull(actual); + assertThat((Object) actual).isNull(); verify(this.chain, times(1)).resolveResource(null, file, this.locations); verify(this.versionStrategy, times(1)).extractVersion(file); } @@ -130,7 +128,7 @@ public class VersionResourceResolverTests { .resolveResourceInternal(null, versionFile, this.locations, this.chain) .block(Duration.ofMillis(5000)); - assertNull(actual); + assertThat((Object) actual).isNull(); verify(this.versionStrategy, times(1)).removeVersion(versionFile, version); } @@ -151,7 +149,7 @@ public class VersionResourceResolverTests { .resolveResourceInternal(null, versionFile, this.locations, this.chain) .block(Duration.ofMillis(5000)); - assertNull(actual); + assertThat((Object) actual).isNull(); verify(this.versionStrategy, times(1)).getResourceVersion(expected); } @@ -174,10 +172,10 @@ public class VersionResourceResolverTests { .resolveResourceInternal(exchange, versionFile, this.locations, this.chain) .block(Duration.ofMillis(5000)); - assertEquals(expected.getFilename(), actual.getFilename()); + assertThat(actual.getFilename()).isEqualTo(expected.getFilename()); verify(this.versionStrategy, times(1)).getResourceVersion(expected); assertThat(actual).isInstanceOf(HttpResource.class); - assertEquals("\"" + version + "\"", ((HttpResource)actual).getResponseHeaders().getETag()); + assertThat(((HttpResource) actual).getResponseHeaders().getETag()).isEqualTo(("\"" + version + "\"")); } @Test @@ -189,10 +187,10 @@ public class VersionResourceResolverTests { strategies.put("/**/*.js", jsStrategy); this.resolver.setStrategyMap(strategies); - assertEquals(catchAllStrategy, this.resolver.getStrategyForPath("foo.css")); - assertEquals(catchAllStrategy, this.resolver.getStrategyForPath("foo-js.css")); - assertEquals(jsStrategy, this.resolver.getStrategyForPath("foo.js")); - assertEquals(jsStrategy, this.resolver.getStrategyForPath("bar/foo.js")); + assertThat(this.resolver.getStrategyForPath("foo.css")).isEqualTo(catchAllStrategy); + assertThat(this.resolver.getStrategyForPath("foo-js.css")).isEqualTo(catchAllStrategy); + assertThat(this.resolver.getStrategyForPath("foo.js")).isEqualTo(jsStrategy); + assertThat(this.resolver.getStrategyForPath("bar/foo.js")).isEqualTo(jsStrategy); } @Test // SPR-13883 diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/WebJarsResourceResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/WebJarsResourceResolverTests.java index 2f521121e58..8222c23c71e 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/WebJarsResourceResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/WebJarsResourceResolverTests.java @@ -30,8 +30,7 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static java.util.Collections.singletonList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -76,7 +75,7 @@ public class WebJarsResourceResolverTests { String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).block(TIMEOUT); - assertEquals(file, actual); + assertThat(actual).isEqualTo(file); verify(this.chain, times(1)).resolveUrlPath(file, this.locations); } @@ -88,7 +87,7 @@ public class WebJarsResourceResolverTests { String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).block(TIMEOUT); - assertNull(actual); + assertThat(actual).isNull(); verify(this.chain, times(1)).resolveUrlPath(file, this.locations); verify(this.chain, never()).resolveUrlPath("foo/2.3/foo.txt", this.locations); } @@ -102,7 +101,7 @@ public class WebJarsResourceResolverTests { String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).block(TIMEOUT); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); verify(this.chain, times(1)).resolveUrlPath(file, this.locations); verify(this.chain, times(1)).resolveUrlPath(expected, this.locations); } @@ -114,7 +113,7 @@ public class WebJarsResourceResolverTests { String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).block(TIMEOUT); - assertNull(actual); + assertThat(actual).isNull(); verify(this.chain, times(1)).resolveUrlPath(file, this.locations); verify(this.chain, never()).resolveUrlPath(null, this.locations); } @@ -130,7 +129,7 @@ public class WebJarsResourceResolverTests { .resolveResource(this.exchange, file, this.locations, this.chain) .block(TIMEOUT); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); verify(this.chain, times(1)).resolveResource(this.exchange, file, this.locations); } @@ -143,7 +142,7 @@ public class WebJarsResourceResolverTests { .resolveResource(this.exchange, file, this.locations, this.chain) .block(TIMEOUT); - assertNull(actual); + assertThat(actual).isNull(); verify(this.chain, times(1)).resolveResource(this.exchange, file, this.locations); verify(this.chain, never()).resolveResource(this.exchange, null, this.locations); } @@ -165,7 +164,7 @@ public class WebJarsResourceResolverTests { .resolveResource(this.exchange, file, this.locations, this.chain) .block(TIMEOUT); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); verify(this.chain, times(1)).resolveResource(this.exchange, file, this.locations); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/HandlerResultHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/HandlerResultHandlerTests.java index efcf8c8c085..e47ddfbf2b7 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/HandlerResultHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/HandlerResultHandlerTests.java @@ -31,7 +31,7 @@ import org.springframework.web.reactive.accept.FixedContentTypeResolver; import org.springframework.web.reactive.accept.HeaderContentTypeResolver; import org.springframework.web.reactive.accept.RequestedContentTypeResolver; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.http.MediaType.ALL; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM; @@ -57,7 +57,7 @@ public class HandlerResultHandlerTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path")); MediaType actual = resultHandler.selectMediaType(exchange, () -> mediaTypes); - assertEquals(IMAGE_GIF, actual); + assertThat(actual).isEqualTo(IMAGE_GIF); } @Test @@ -68,7 +68,7 @@ public class HandlerResultHandlerTests { List mediaTypes = Arrays.asList(IMAGE_JPEG, IMAGE_GIF, IMAGE_PNG); MediaType actual = resultHandler.selectMediaType(exchange, () -> mediaTypes); - assertEquals(IMAGE_GIF, actual); + assertThat(actual).isEqualTo(IMAGE_GIF); } @Test // SPR-9160 @@ -79,7 +79,7 @@ public class HandlerResultHandlerTests { List mediaTypes = Arrays.asList(TEXT_PLAIN, APPLICATION_JSON); MediaType actual = this.resultHandler.selectMediaType(exchange, () -> mediaTypes); - assertEquals(APPLICATION_JSON, actual); + assertThat(actual).isEqualTo(APPLICATION_JSON); } @Test @@ -89,7 +89,7 @@ public class HandlerResultHandlerTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path").accept(text8859)); MediaType actual = this.resultHandler.selectMediaType(exchange, () -> Collections.singletonList(textUtf8)); - assertEquals(text8859, actual); + assertThat(actual).isEqualTo(text8859); } @Test // SPR-12894 @@ -98,7 +98,7 @@ public class HandlerResultHandlerTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path")); MediaType actual = this.resultHandler.selectMediaType(exchange, () -> producible); - assertEquals(APPLICATION_OCTET_STREAM, actual); + assertThat(actual).isEqualTo(APPLICATION_OCTET_STREAM); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/SimpleUrlHandlerMappingIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/SimpleUrlHandlerMappingIntegrationTests.java index 613068a388b..422e8725e2f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/SimpleUrlHandlerMappingIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/SimpleUrlHandlerMappingIntegrationTests.java @@ -44,8 +44,7 @@ import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import org.springframework.web.server.handler.ResponseStatusExceptionHandler; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests with requests mapped via @@ -73,8 +72,8 @@ public class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandler RequestEntity request = RequestEntity.get(url).build(); ResponseEntity response = new RestTemplate().exchange(request, byte[].class); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertArrayEquals("foo".getBytes("UTF-8"), response.getBody()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).isEqualTo("foo".getBytes("UTF-8")); } @Test @@ -83,8 +82,8 @@ public class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandler RequestEntity request = RequestEntity.get(url).build(); ResponseEntity response = new RestTemplate().exchange(request, byte[].class); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertArrayEquals("bar".getBytes("UTF-8"), response.getBody()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).isEqualTo("bar".getBytes("UTF-8")); } @Test @@ -93,8 +92,8 @@ public class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandler RequestEntity request = RequestEntity.get(url).build(); ResponseEntity response = new RestTemplate().exchange(request, byte[].class); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertEquals("bar", response.getHeaders().getFirst("foo")); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getHeaders().getFirst("foo")).isEqualTo("bar"); } @Test @@ -105,7 +104,7 @@ public class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandler new RestTemplate().exchange(request, byte[].class); } catch (HttpClientErrorException ex) { - assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode()); + assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/CompositeRequestConditionTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/CompositeRequestConditionTests.java index e807d988e47..22da61c77e9 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/CompositeRequestConditionTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/CompositeRequestConditionTests.java @@ -23,10 +23,8 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.bind.annotation.RequestMethod; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for {@link CompositeRequestCondition}. @@ -62,7 +60,7 @@ public class CompositeRequestConditionTests { CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param2, this.header2); CompositeRequestCondition cond3 = new CompositeRequestCondition(this.param3, this.header3); - assertEquals(cond3, cond1.combine(cond2)); + assertThat(cond1.combine(cond2)).isEqualTo(cond3); } @Test @@ -70,9 +68,9 @@ public class CompositeRequestConditionTests { CompositeRequestCondition empty = new CompositeRequestCondition(); CompositeRequestCondition notEmpty = new CompositeRequestCondition(this.param1); - assertSame(empty, empty.combine(empty)); - assertSame(notEmpty, notEmpty.combine(empty)); - assertSame(notEmpty, empty.combine(notEmpty)); + assertThat(empty.combine(empty)).isSameAs(empty); + assertThat(notEmpty.combine(empty)).isSameAs(notEmpty); + assertThat(empty.combine(notEmpty)).isSameAs(notEmpty); } @Test @@ -94,19 +92,19 @@ public class CompositeRequestConditionTests { CompositeRequestCondition composite1 = new CompositeRequestCondition(this.param1, condition1); CompositeRequestCondition composite2 = new CompositeRequestCondition(this.param1, condition2); - assertEquals(composite2, composite1.getMatchingCondition(exchange)); + assertThat(composite1.getMatchingCondition(exchange)).isEqualTo(composite2); } @Test public void noMatch() { CompositeRequestCondition cond = new CompositeRequestCondition(this.param1); - assertNull(cond.getMatchingCondition(MockServerWebExchange.from(MockServerHttpRequest.get("/")))); + assertThat(cond.getMatchingCondition(MockServerWebExchange.from(MockServerHttpRequest.get("/")))).isNull(); } @Test public void matchEmpty() { CompositeRequestCondition empty = new CompositeRequestCondition(); - assertSame(empty, empty.getMatchingCondition(MockServerWebExchange.from(MockServerHttpRequest.get("/")))); + assertThat(empty.getMatchingCondition(MockServerWebExchange.from(MockServerHttpRequest.get("/")))).isSameAs(empty); } @Test @@ -115,8 +113,8 @@ public class CompositeRequestConditionTests { CompositeRequestCondition cond3 = new CompositeRequestCondition(this.param3); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); - assertEquals(1, cond1.compareTo(cond3, exchange)); - assertEquals(-1, cond3.compareTo(cond1, exchange)); + assertThat(cond1.compareTo(cond3, exchange)).isEqualTo(1); + assertThat(cond3.compareTo(cond1, exchange)).isEqualTo(-1); } @Test @@ -125,9 +123,9 @@ public class CompositeRequestConditionTests { CompositeRequestCondition notEmpty = new CompositeRequestCondition(this.param1); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); - assertEquals(0, empty.compareTo(empty, exchange)); - assertEquals(-1, notEmpty.compareTo(empty, exchange)); - assertEquals(1, empty.compareTo(notEmpty, exchange)); + assertThat(empty.compareTo(empty, exchange)).isEqualTo(0); + assertThat(notEmpty.compareTo(empty, exchange)).isEqualTo(-1); + assertThat(empty.compareTo(notEmpty, exchange)).isEqualTo(1); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ConsumesRequestConditionTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ConsumesRequestConditionTests.java index ff6264646b3..e0e479f42c7 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ConsumesRequestConditionTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ConsumesRequestConditionTests.java @@ -26,11 +26,8 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.reactive.result.condition.ConsumesRequestCondition.ConsumeMediaTypeExpression; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * @author Arjen Poutsma @@ -42,7 +39,7 @@ public class ConsumesRequestConditionTests { MockServerWebExchange exchange = postExchange("text/plain"); ConsumesRequestCondition condition = new ConsumesRequestCondition("text/plain"); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } @Test @@ -50,13 +47,13 @@ public class ConsumesRequestConditionTests { MockServerWebExchange exchange = postExchange("text/plain"); ConsumesRequestCondition condition = new ConsumesRequestCondition("!text/plain"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test public void getConsumableMediaTypesNegatedExpression() throws Exception { ConsumesRequestCondition condition = new ConsumesRequestCondition("!application/xml"); - assertEquals(Collections.emptySet(), condition.getConsumableMediaTypes()); + assertThat(condition.getConsumableMediaTypes()).isEqualTo(Collections.emptySet()); } @Test @@ -64,7 +61,7 @@ public class ConsumesRequestConditionTests { MockServerWebExchange exchange = postExchange("text/plain"); ConsumesRequestCondition condition = new ConsumesRequestCondition("text/*"); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } @Test @@ -72,7 +69,7 @@ public class ConsumesRequestConditionTests { MockServerWebExchange exchange = postExchange("text/plain"); ConsumesRequestCondition condition = new ConsumesRequestCondition("text/plain", "application/xml"); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } @Test @@ -80,7 +77,7 @@ public class ConsumesRequestConditionTests { MockServerWebExchange exchange = postExchange("application/xml"); ConsumesRequestCondition condition = new ConsumesRequestCondition("text/plain"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test @@ -88,7 +85,7 @@ public class ConsumesRequestConditionTests { MockServerWebExchange exchange = postExchange("01"); ConsumesRequestCondition condition = new ConsumesRequestCondition("text/plain"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test @@ -96,7 +93,7 @@ public class ConsumesRequestConditionTests { MockServerWebExchange exchange = postExchange("01"); ConsumesRequestCondition condition = new ConsumesRequestCondition("!text/plain"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test // gh-22010 @@ -105,16 +102,16 @@ public class ConsumesRequestConditionTests { condition.setBodyRequired(false); MockServerHttpRequest request = MockServerHttpRequest.get("/").build(); - assertNotNull(condition.getMatchingCondition(MockServerWebExchange.from(request))); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(request))).isNotNull(); request = MockServerHttpRequest.get("/").header(HttpHeaders.CONTENT_LENGTH, "0").build(); - assertNotNull(condition.getMatchingCondition(MockServerWebExchange.from(request))); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(request))).isNotNull(); request = MockServerHttpRequest.get("/").header(HttpHeaders.CONTENT_LENGTH, "21").build(); - assertNull(condition.getMatchingCondition(MockServerWebExchange.from(request))); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(request))).isNull(); request = MockServerHttpRequest.get("/").header(HttpHeaders.TRANSFER_ENCODING, "chunked").build(); - assertNull(condition.getMatchingCondition(MockServerWebExchange.from(request))); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(request))).isNull(); } @Test @@ -125,10 +122,10 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition("text/*"); int result = condition1.compareTo(condition2, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, exchange); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @Test @@ -139,10 +136,10 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition("text/*", "text/plain;q=0.7"); int result = condition1.compareTo(condition2, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, exchange); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @@ -152,7 +149,7 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition("application/xml"); ConsumesRequestCondition result = condition1.combine(condition2); - assertEquals(condition2, result); + assertThat(result).isEqualTo(condition2); } @Test @@ -161,7 +158,7 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition(); ConsumesRequestCondition result = condition1.combine(condition2); - assertEquals(condition1, result); + assertThat(result).isEqualTo(condition1); } @Test @@ -183,12 +180,12 @@ public class ConsumesRequestConditionTests { condition = new ConsumesRequestCondition("application/xml"); result = condition.getMatchingCondition(exchange); - assertNull(result); + assertThat(result).isNull(); } private void assertConditions(ConsumesRequestCondition condition, String... expected) { Collection expressions = condition.getContent(); - assertEquals("Invalid amount of conditions", expressions.size(), expected.length); + assertThat(expected.length).as("Invalid amount of conditions").isEqualTo(expressions.size()); for (String s : expected) { boolean found = false; for (ConsumeMediaTypeExpression expr : expressions) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/HeadersRequestConditionTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/HeadersRequestConditionTests.java index 83c84dfccc2..150424fe23c 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/HeadersRequestConditionTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/HeadersRequestConditionTests.java @@ -23,11 +23,7 @@ import org.junit.Test; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; /** @@ -39,11 +35,11 @@ public class HeadersRequestConditionTests { @Test public void headerEquals() { - assertEquals(new HeadersRequestCondition("foo"), new HeadersRequestCondition("foo")); - assertEquals(new HeadersRequestCondition("foo"), new HeadersRequestCondition("FOO")); - assertNotEquals(new HeadersRequestCondition("foo"), new HeadersRequestCondition("bar")); - assertEquals(new HeadersRequestCondition("foo=bar"), new HeadersRequestCondition("foo=bar")); - assertEquals(new HeadersRequestCondition("foo=bar"), new HeadersRequestCondition("FOO=bar")); + assertThat(new HeadersRequestCondition("foo")).isEqualTo(new HeadersRequestCondition("foo")); + assertThat(new HeadersRequestCondition("FOO")).isEqualTo(new HeadersRequestCondition("foo")); + assertThat(new HeadersRequestCondition("bar")).isNotEqualTo(new HeadersRequestCondition("foo")); + assertThat(new HeadersRequestCondition("foo=bar")).isEqualTo(new HeadersRequestCondition("foo=bar")); + assertThat(new HeadersRequestCondition("FOO=bar")).isEqualTo(new HeadersRequestCondition("foo=bar")); } @Test @@ -51,7 +47,7 @@ public class HeadersRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", "")); HeadersRequestCondition condition = new HeadersRequestCondition("accept"); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } @Test @@ -59,7 +55,7 @@ public class HeadersRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("bar", "")); HeadersRequestCondition condition = new HeadersRequestCondition("foo"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test @@ -67,7 +63,7 @@ public class HeadersRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/")); HeadersRequestCondition condition = new HeadersRequestCondition("!accept"); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } @Test @@ -75,7 +71,7 @@ public class HeadersRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("foo", "bar")); HeadersRequestCondition condition = new HeadersRequestCondition("foo=bar"); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } @Test @@ -83,7 +79,7 @@ public class HeadersRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("foo", "bazz")); HeadersRequestCondition condition = new HeadersRequestCondition("foo=bar"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test @@ -91,7 +87,7 @@ public class HeadersRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("foo", "bar")); HeadersRequestCondition condition = new HeadersRequestCondition("foo=Bar"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test @@ -99,7 +95,7 @@ public class HeadersRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("foo", "baz")); HeadersRequestCondition condition = new HeadersRequestCondition("foo!=bar"); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } @Test @@ -107,7 +103,7 @@ public class HeadersRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("foo", "bar")); HeadersRequestCondition condition = new HeadersRequestCondition("foo!=bar"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test @@ -118,10 +114,10 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition2 = new HeadersRequestCondition("foo=a", "bar"); int result = condition1.compareTo(condition2, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, exchange); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @Test // SPR-16674 @@ -132,7 +128,7 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition2 = new HeadersRequestCondition("foo"); int result = condition1.compareTo(condition2, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); } @Test @@ -142,8 +138,7 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition1 = new HeadersRequestCondition("foo!=a"); HeadersRequestCondition condition2 = new HeadersRequestCondition("foo"); - assertEquals("Negated match should not count as more specific", - 0, condition1.compareTo(condition2, exchange)); + assertThat(condition1.compareTo(condition2, exchange)).as("Negated match should not count as more specific").isEqualTo(0); } @Test @@ -153,7 +148,7 @@ public class HeadersRequestConditionTests { HeadersRequestCondition result = condition1.combine(condition2); Collection conditions = result.getContent(); - assertEquals(2, conditions.size()); + assertThat(conditions.size()).isEqualTo(2); } @Test @@ -162,12 +157,12 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition = new HeadersRequestCondition("foo"); HeadersRequestCondition result = condition.getMatchingCondition(exchange); - assertEquals(condition, result); + assertThat(result).isEqualTo(condition); condition = new HeadersRequestCondition("bar"); result = condition.getMatchingCondition(exchange); - assertNull(result); + assertThat(result).isNull(); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ParamsRequestConditionTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ParamsRequestConditionTests.java index f78ed6cbfe8..ae6100926c4 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ParamsRequestConditionTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ParamsRequestConditionTests.java @@ -23,11 +23,7 @@ import org.junit.Test; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; /** @@ -38,47 +34,47 @@ public class ParamsRequestConditionTests { @Test public void paramEquals() { - assertEquals(new ParamsRequestCondition("foo"), new ParamsRequestCondition("foo")); - assertFalse(new ParamsRequestCondition("foo").equals(new ParamsRequestCondition("bar"))); - assertFalse(new ParamsRequestCondition("foo").equals(new ParamsRequestCondition("FOO"))); - assertEquals(new ParamsRequestCondition("foo=bar"), new ParamsRequestCondition("foo=bar")); - assertFalse(new ParamsRequestCondition("foo=bar").equals(new ParamsRequestCondition("FOO=bar"))); + assertThat(new ParamsRequestCondition("foo")).isEqualTo(new ParamsRequestCondition("foo")); + assertThat(new ParamsRequestCondition("foo").equals(new ParamsRequestCondition("bar"))).isFalse(); + assertThat(new ParamsRequestCondition("foo").equals(new ParamsRequestCondition("FOO"))).isFalse(); + assertThat(new ParamsRequestCondition("foo=bar")).isEqualTo(new ParamsRequestCondition("foo=bar")); + assertThat(new ParamsRequestCondition("foo=bar").equals(new ParamsRequestCondition("FOO=bar"))).isFalse(); } @Test public void paramPresent() throws Exception { ParamsRequestCondition condition = new ParamsRequestCondition("foo"); - assertNotNull(condition.getMatchingCondition(MockServerWebExchange.from(get("/path?foo=")))); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(get("/path?foo=")))).isNotNull(); } @Test // SPR-15831 public void paramPresentNullValue() throws Exception { ParamsRequestCondition condition = new ParamsRequestCondition("foo"); - assertNotNull(condition.getMatchingCondition(MockServerWebExchange.from(get("/path?foo")))); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(get("/path?foo")))).isNotNull(); } @Test public void paramPresentNoMatch() throws Exception { ParamsRequestCondition condition = new ParamsRequestCondition("foo"); - assertNull(condition.getMatchingCondition(MockServerWebExchange.from(get("/path?bar=")))); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(get("/path?bar=")))).isNull(); } @Test public void paramNotPresent() throws Exception { MockServerWebExchange exchange = MockServerWebExchange.from(get("/")); - assertNotNull(new ParamsRequestCondition("!foo").getMatchingCondition(exchange)); + assertThat(new ParamsRequestCondition("!foo").getMatchingCondition(exchange)).isNotNull(); } @Test public void paramValueMatch() throws Exception { ParamsRequestCondition condition = new ParamsRequestCondition("foo=bar"); - assertNotNull(condition.getMatchingCondition(MockServerWebExchange.from(get("/path?foo=bar")))); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(get("/path?foo=bar")))).isNotNull(); } @Test public void paramValueNoMatch() throws Exception { ParamsRequestCondition condition = new ParamsRequestCondition("foo=bar"); - assertNull(condition.getMatchingCondition(MockServerWebExchange.from(get("/path?foo=bazz")))); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(get("/path?foo=bazz")))).isNull(); } @Test @@ -89,10 +85,10 @@ public class ParamsRequestConditionTests { ParamsRequestCondition condition2 = new ParamsRequestCondition("foo", "bar"); int result = condition1.compareTo(condition2, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, exchange); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @Test // SPR-16674 @@ -103,7 +99,7 @@ public class ParamsRequestConditionTests { ParamsRequestCondition condition2 = new ParamsRequestCondition("response_type"); int result = condition1.compareTo(condition2, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); } @Test @@ -113,8 +109,7 @@ public class ParamsRequestConditionTests { ParamsRequestCondition condition1 = new ParamsRequestCondition("response_type!=code"); ParamsRequestCondition condition2 = new ParamsRequestCondition("response_type"); - assertEquals("Negated match should not count as more specific", - 0, condition1.compareTo(condition2, exchange)); + assertThat(condition1.compareTo(condition2, exchange)).as("Negated match should not count as more specific").isEqualTo(0); } @Test @@ -124,7 +119,7 @@ public class ParamsRequestConditionTests { ParamsRequestCondition result = condition1.combine(condition2); Collection conditions = result.getContent(); - assertEquals(2, conditions.size()); + assertThat(conditions.size()).isEqualTo(2); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/PatternsRequestConditionTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/PatternsRequestConditionTests.java index c1add468a8b..216c54d3363 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/PatternsRequestConditionTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/PatternsRequestConditionTests.java @@ -27,9 +27,7 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.util.pattern.PathPattern; import org.springframework.web.util.pattern.PathPatternParser; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; /** @@ -44,8 +42,7 @@ public class PatternsRequestConditionTests { @Test public void prependNonEmptyPatternsOnly() { PatternsRequestCondition c = createPatternsCondition(""); - assertEquals("Do not prepend empty patterns (SPR-8255)", "", - c.getPatterns().iterator().next().getPatternString()); + assertThat(c.getPatterns().iterator().next().getPatternString()).as("Do not prepend empty patterns (SPR-8255)").isEqualTo(""); } @Test @@ -53,7 +50,7 @@ public class PatternsRequestConditionTests { PatternsRequestCondition c1 = new PatternsRequestCondition(); PatternsRequestCondition c2 = new PatternsRequestCondition(); - assertEquals(createPatternsCondition(), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(createPatternsCondition()); } @Test @@ -61,12 +58,12 @@ public class PatternsRequestConditionTests { PatternsRequestCondition c1 = createPatternsCondition("/type1", "/type2"); PatternsRequestCondition c2 = new PatternsRequestCondition(); - assertEquals(createPatternsCondition("/type1", "/type2"), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(createPatternsCondition("/type1", "/type2")); c1 = new PatternsRequestCondition(); c2 = createPatternsCondition("/method1", "/method2"); - assertEquals(createPatternsCondition("/method1", "/method2"), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(createPatternsCondition("/method1", "/method2")); } @Test @@ -74,7 +71,7 @@ public class PatternsRequestConditionTests { PatternsRequestCondition c1 = createPatternsCondition("/t1", "/t2"); PatternsRequestCondition c2 = createPatternsCondition("/m1", "/m2"); - assertEquals(createPatternsCondition("/t1/m1", "/t1/m2", "/t2/m1", "/t2/m2"), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(createPatternsCondition("/t1/m1", "/t1/m2", "/t2/m1", "/t2/m2")); } @Test @@ -83,7 +80,7 @@ public class PatternsRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/foo")); PatternsRequestCondition match = condition.getMatchingCondition(exchange); - assertNotNull(match); + assertThat(match).isNotNull(); } @Test @@ -92,7 +89,7 @@ public class PatternsRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/foo/bar")); PatternsRequestCondition match = condition.getMatchingCondition(exchange); - assertNotNull(match); + assertThat(match).isNotNull(); } @Test @@ -102,7 +99,7 @@ public class PatternsRequestConditionTests { PatternsRequestCondition match = condition.getMatchingCondition(exchange); PatternsRequestCondition expected = createPatternsCondition("/foo/bar", "/foo/*", "/*/*"); - assertEquals(expected, match); + assertThat(match).isEqualTo(expected); } @Test @@ -112,23 +109,21 @@ public class PatternsRequestConditionTests { PatternsRequestCondition condition = createPatternsCondition("/foo"); PatternsRequestCondition match = condition.getMatchingCondition(exchange); - assertNotNull(match); - assertEquals("Should match by default", "/foo", - match.getPatterns().iterator().next().getPatternString()); + assertThat(match).isNotNull(); + assertThat(match.getPatterns().iterator().next().getPatternString()).as("Should match by default").isEqualTo("/foo"); condition = createPatternsCondition("/foo"); match = condition.getMatchingCondition(exchange); - assertNotNull(match); - assertEquals("Trailing slash should be insensitive to useSuffixPatternMatch settings (SPR-6164, SPR-5636)", - "/foo", match.getPatterns().iterator().next().getPatternString()); + assertThat(match).isNotNull(); + assertThat(match.getPatterns().iterator().next().getPatternString()).as("Trailing slash should be insensitive to useSuffixPatternMatch settings (SPR-6164, SPR-5636)").isEqualTo("/foo"); PathPatternParser parser = new PathPatternParser(); parser.setMatchOptionalTrailingSeparator(false); condition = new PatternsRequestCondition(parser.parse("/foo")); match = condition.getMatchingCondition(MockServerWebExchange.from(get("/foo/"))); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -137,20 +132,20 @@ public class PatternsRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/foo.html")); PatternsRequestCondition match = condition.getMatchingCondition(exchange); - assertNull(match); + assertThat(match).isNull(); } @Test // gh-22543 public void matchWithEmptyPatterns() { PatternsRequestCondition condition = new PatternsRequestCondition(); - assertEquals(new PatternsRequestCondition(this.parser.parse("")), condition); - assertNotNull(condition.getMatchingCondition(MockServerWebExchange.from(get("")))); - assertNull(condition.getMatchingCondition(MockServerWebExchange.from(get("/anything")))); + assertThat(condition).isEqualTo(new PatternsRequestCondition(this.parser.parse(""))); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(get("")))).isNotNull(); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(get("/anything")))).isNull(); condition = condition.combine(new PatternsRequestCondition()); - assertEquals(new PatternsRequestCondition(this.parser.parse("")), condition); - assertNotNull(condition.getMatchingCondition(MockServerWebExchange.from(get("")))); - assertNull(condition.getMatchingCondition(MockServerWebExchange.from(get("/anything")))); + assertThat(condition).isEqualTo(new PatternsRequestCondition(this.parser.parse(""))); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(get("")))).isNotNull(); + assertThat(condition.getMatchingCondition(MockServerWebExchange.from(get("/anything")))).isNull(); } @Test @@ -158,16 +153,16 @@ public class PatternsRequestConditionTests { PatternsRequestCondition c1 = createPatternsCondition("/foo*"); PatternsRequestCondition c2 = createPatternsCondition("/foo*"); - assertEquals(0, c1.compareTo(c2, MockServerWebExchange.from(get("/foo")))); + assertThat(c1.compareTo(c2, MockServerWebExchange.from(get("/foo")))).isEqualTo(0); } @Test public void equallyMatchingPatternsAreBothPresent() throws Exception { PatternsRequestCondition c = createPatternsCondition("/a", "/b"); - assertEquals(2, c.getPatterns().size()); + assertThat(c.getPatterns().size()).isEqualTo(2); Iterator itr = c.getPatterns().iterator(); - assertEquals("/a", itr.next().getPatternString()); - assertEquals("/b", itr.next().getPatternString()); + assertThat(itr.next().getPatternString()).isEqualTo("/a"); + assertThat(itr.next().getPatternString()).isEqualTo("/b"); } @Test @@ -177,12 +172,12 @@ public class PatternsRequestConditionTests { PatternsRequestCondition c1 = createPatternsCondition("/fo*"); PatternsRequestCondition c2 = createPatternsCondition("/foo"); - assertEquals(1, c1.compareTo(c2, exchange)); + assertThat(c1.compareTo(c2, exchange)).isEqualTo(1); c1 = createPatternsCondition("/fo*"); c2 = createPatternsCondition("/*oo"); - assertEquals("Patterns are equally specific even if not the same", 0, c1.compareTo(c2, exchange)); + assertThat(c1.compareTo(c2, exchange)).as("Patterns are equally specific even if not the same").isEqualTo(0); } @Test @@ -195,8 +190,8 @@ public class PatternsRequestConditionTests { PatternsRequestCondition match1 = c1.getMatchingCondition(exchange); PatternsRequestCondition match2 = c2.getMatchingCondition(exchange); - assertNotNull(match1); - assertEquals(1, match1.compareTo(match2, exchange)); + assertThat(match1).isNotNull(); + assertThat(match1.compareTo(match2, exchange)).isEqualTo(1); } private PatternsRequestCondition createPatternsCondition(String... patterns) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ProducesRequestConditionTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ProducesRequestConditionTests.java index d1cc689b166..81addd26037 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ProducesRequestConditionTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/ProducesRequestConditionTests.java @@ -27,11 +27,8 @@ import org.springframework.web.reactive.accept.RequestedContentTypeResolver; import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; /** @@ -46,7 +43,7 @@ public class ProducesRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", "text/plain")); ProducesRequestCondition condition = new ProducesRequestCondition("text/plain"); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } @Test @@ -54,13 +51,13 @@ public class ProducesRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", "text/plain")); ProducesRequestCondition condition = new ProducesRequestCondition("!text/plain"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test public void getProducibleMediaTypes() { ProducesRequestCondition condition = new ProducesRequestCondition("!application/xml"); - assertEquals(Collections.emptySet(), condition.getProducibleMediaTypes()); + assertThat(condition.getProducibleMediaTypes()).isEqualTo(Collections.emptySet()); } @Test @@ -68,7 +65,7 @@ public class ProducesRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", "text/plain")); ProducesRequestCondition condition = new ProducesRequestCondition("text/*"); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } @Test @@ -76,7 +73,7 @@ public class ProducesRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", "text/plain")); ProducesRequestCondition condition = new ProducesRequestCondition("text/plain", "application/xml"); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } @Test @@ -84,7 +81,7 @@ public class ProducesRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", "application/xml")); ProducesRequestCondition condition = new ProducesRequestCondition("text/plain"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test // gh-21670 @@ -92,22 +89,19 @@ public class ProducesRequestConditionTests { String base = "application/atom+xml"; ProducesRequestCondition condition = new ProducesRequestCondition(base + ";type=feed"); MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", base + ";type=feed")); - assertNotNull("Declared parameter value must match if present in request", - condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).as("Declared parameter value must match if present in request").isNotNull(); condition = new ProducesRequestCondition(base + ";type=feed"); exchange = MockServerWebExchange.from(get("/").header("Accept", base + ";type=entry")); - assertNull("Declared parameter value must match if present in request", - condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).as("Declared parameter value must match if present in request").isNull(); condition = new ProducesRequestCondition(base + ";type=feed"); exchange = MockServerWebExchange.from(get("/").header("Accept", base)); - assertNotNull("Declared parameter has no impact if not present in request", - condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).as("Declared parameter has no impact if not present in request").isNotNull(); condition = new ProducesRequestCondition(base); exchange = MockServerWebExchange.from(get("/").header("Accept", base + ";type=feed")); - assertNotNull("No impact from other parameters in request", condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).as("No impact from other parameters in request").isNotNull(); } @Test @@ -115,7 +109,7 @@ public class ProducesRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", "bogus")); ProducesRequestCondition condition = new ProducesRequestCondition("text/plain"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test @@ -123,7 +117,7 @@ public class ProducesRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", "bogus")); ProducesRequestCondition condition = new ProducesRequestCondition("!text/plain"); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } @Test // SPR-17550 @@ -133,7 +127,7 @@ public class ProducesRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } @Test // gh-22853 @@ -151,7 +145,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition noneMatch = none.getMatchingCondition(exchange); ProducesRequestCondition htmlMatch = html.getMatchingCondition(exchange); - assertEquals(1, noneMatch.compareTo(htmlMatch, exchange)); + assertThat(noneMatch.compareTo(htmlMatch, exchange)).isEqualTo(1); } @Test @@ -163,31 +157,31 @@ public class ProducesRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/") .header("Accept", "application/xml, text/html")); - assertTrue(html.compareTo(xml, exchange) > 0); - assertTrue(xml.compareTo(html, exchange) < 0); - assertTrue(xml.compareTo(none, exchange) < 0); - assertTrue(none.compareTo(xml, exchange) > 0); - assertTrue(html.compareTo(none, exchange) < 0); - assertTrue(none.compareTo(html, exchange) > 0); + assertThat(html.compareTo(xml, exchange) > 0).isTrue(); + assertThat(xml.compareTo(html, exchange) < 0).isTrue(); + assertThat(xml.compareTo(none, exchange) < 0).isTrue(); + assertThat(none.compareTo(xml, exchange) > 0).isTrue(); + assertThat(html.compareTo(none, exchange) < 0).isTrue(); + assertThat(none.compareTo(html, exchange) > 0).isTrue(); exchange = MockServerWebExchange.from( get("/").header("Accept", "application/xml, text/*")); - assertTrue(html.compareTo(xml, exchange) > 0); - assertTrue(xml.compareTo(html, exchange) < 0); + assertThat(html.compareTo(xml, exchange) > 0).isTrue(); + assertThat(xml.compareTo(html, exchange) < 0).isTrue(); exchange = MockServerWebExchange.from( get("/").header("Accept", "application/pdf")); - assertEquals(0, html.compareTo(xml, exchange)); - assertEquals(0, xml.compareTo(html, exchange)); + assertThat(html.compareTo(xml, exchange)).isEqualTo(0); + assertThat(xml.compareTo(html, exchange)).isEqualTo(0); // See SPR-7000 exchange = MockServerWebExchange.from( get("/").header("Accept", "text/html;q=0.9,application/xml")); - assertTrue(html.compareTo(xml, exchange) > 0); - assertTrue(xml.compareTo(html, exchange) < 0); + assertThat(html.compareTo(xml, exchange) > 0).isTrue(); + assertThat(xml.compareTo(html, exchange) < 0).isTrue(); } @Test @@ -198,10 +192,10 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition("text/*"); int result = condition1.compareTo(condition2, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, exchange); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @Test @@ -212,10 +206,10 @@ public class ProducesRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/").header("Accept", "text/plain")); int result = condition1.compareTo(condition2, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, exchange); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @Test @@ -227,19 +221,19 @@ public class ProducesRequestConditionTests { get("/").header("Accept", "text/plain", "application/xml")); int result = condition1.compareTo(condition2, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, exchange); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); exchange = MockServerWebExchange.from( get("/").header("Accept", "application/xml", "text/plain")); result = condition1.compareTo(condition2, exchange); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); } // SPR-8536 @@ -251,16 +245,14 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition1 = new ProducesRequestCondition(); ProducesRequestCondition condition2 = new ProducesRequestCondition("application/json"); - assertTrue("Should have picked '*/*' condition as an exact match", - condition1.compareTo(condition2, exchange) < 0); - assertTrue("Should have picked '*/*' condition as an exact match", - condition2.compareTo(condition1, exchange) > 0); + assertThat(condition1.compareTo(condition2, exchange) < 0).as("Should have picked '*/*' condition as an exact match").isTrue(); + assertThat(condition2.compareTo(condition1, exchange) > 0).as("Should have picked '*/*' condition as an exact match").isTrue(); condition1 = new ProducesRequestCondition("*/*"); condition2 = new ProducesRequestCondition("application/json"); - assertTrue(condition1.compareTo(condition2, exchange) < 0); - assertTrue(condition2.compareTo(condition1, exchange) > 0); + assertThat(condition1.compareTo(condition2, exchange) < 0).isTrue(); + assertThat(condition2.compareTo(condition1, exchange) > 0).isTrue(); exchange = MockServerWebExchange.from( get("/").header("Accept", "*/*")); @@ -268,14 +260,14 @@ public class ProducesRequestConditionTests { condition1 = new ProducesRequestCondition(); condition2 = new ProducesRequestCondition("application/json"); - assertTrue(condition1.compareTo(condition2, exchange) < 0); - assertTrue(condition2.compareTo(condition1, exchange) > 0); + assertThat(condition1.compareTo(condition2, exchange) < 0).isTrue(); + assertThat(condition2.compareTo(condition1, exchange) > 0).isTrue(); condition1 = new ProducesRequestCondition("*/*"); condition2 = new ProducesRequestCondition("application/json"); - assertTrue(condition1.compareTo(condition2, exchange) < 0); - assertTrue(condition2.compareTo(condition1, exchange) > 0); + assertThat(condition1.compareTo(condition2, exchange) < 0).isTrue(); + assertThat(condition2.compareTo(condition1, exchange) > 0).isTrue(); } // SPR-9021 @@ -287,8 +279,8 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition1 = new ProducesRequestCondition(); ProducesRequestCondition condition2 = new ProducesRequestCondition("application/json"); - assertTrue(condition1.compareTo(condition2, exchange) < 0); - assertTrue(condition2.compareTo(condition1, exchange) > 0); + assertThat(condition1.compareTo(condition2, exchange) < 0).isTrue(); + assertThat(condition2.compareTo(condition1, exchange) > 0).isTrue(); } @Test @@ -299,10 +291,10 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition("text/xhtml"); int result = condition1.compareTo(condition2, exchange); - assertTrue("Should have used MediaType.equals(Object) to break the match", result < 0); + assertThat(result < 0).as("Should have used MediaType.equals(Object) to break the match").isTrue(); result = condition2.compareTo(condition1, exchange); - assertTrue("Should have used MediaType.equals(Object) to break the match", result > 0); + assertThat(result > 0).as("Should have used MediaType.equals(Object) to break the match").isTrue(); } @Test @@ -311,7 +303,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition("application/xml"); ProducesRequestCondition result = condition1.combine(condition2); - assertEquals(condition2, result); + assertThat(result).isEqualTo(condition2); } @Test @@ -320,7 +312,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition(); ProducesRequestCondition result = condition1.combine(condition2); - assertEquals(condition1, result); + assertThat(result).isEqualTo(condition1); } @Test @@ -344,12 +336,12 @@ public class ProducesRequestConditionTests { condition = new ProducesRequestCondition("application/xml"); result = condition.getMatchingCondition(exchange); - assertNull(result); + assertThat(result).isNull(); } private void assertConditions(ProducesRequestCondition condition, String... expected) { Collection expressions = condition.getContent(); - assertEquals("Invalid number of conditions", expressions.size(), expected.length); + assertThat(expected.length).as("Invalid number of conditions").isEqualTo(expressions.size()); for (String s : expected) { boolean found = false; for (ProducesRequestCondition.ProduceMediaTypeExpression expr : expressions) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestConditionHolderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestConditionHolderTests.java index dd41b1fbab6..491d232d488 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestConditionHolderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestConditionHolderTests.java @@ -22,11 +22,8 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.bind.annotation.RequestMethod; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for {@link RequestConditionHolder}. @@ -44,7 +41,7 @@ public class RequestConditionHolderTests { RequestConditionHolder params2 = new RequestConditionHolder(new ParamsRequestCondition("name2")); RequestConditionHolder expected = new RequestConditionHolder(new ParamsRequestCondition("name1", "name2")); - assertEquals(expected, params1.combine(params2)); + assertThat(params1.combine(params2)).isEqualTo(expected); } @Test @@ -52,9 +49,9 @@ public class RequestConditionHolderTests { RequestConditionHolder empty = new RequestConditionHolder(null); RequestConditionHolder notEmpty = new RequestConditionHolder(new ParamsRequestCondition("name")); - assertSame(empty, empty.combine(empty)); - assertSame(notEmpty, notEmpty.combine(empty)); - assertSame(notEmpty, empty.combine(notEmpty)); + assertThat(empty.combine(empty)).isSameAs(empty); + assertThat(notEmpty.combine(empty)).isSameAs(notEmpty); + assertThat(empty.combine(notEmpty)).isSameAs(notEmpty); } @Test @@ -72,8 +69,8 @@ public class RequestConditionHolderTests { RequestMethodsRequestCondition expected = new RequestMethodsRequestCondition(RequestMethod.GET); RequestConditionHolder holder = custom.getMatchingCondition(this.exchange); - assertNotNull(holder); - assertEquals(expected, holder.getCondition()); + assertThat(holder).isNotNull(); + assertThat(holder.getCondition()).isEqualTo(expected); } @Test @@ -81,13 +78,13 @@ public class RequestConditionHolderTests { RequestMethodsRequestCondition rm = new RequestMethodsRequestCondition(RequestMethod.POST); RequestConditionHolder custom = new RequestConditionHolder(rm); - assertNull(custom.getMatchingCondition(this.exchange)); + assertThat(custom.getMatchingCondition(this.exchange)).isNull(); } @Test public void matchEmpty() { RequestConditionHolder empty = new RequestConditionHolder(null); - assertSame(empty, empty.getMatchingCondition(this.exchange)); + assertThat(empty.getMatchingCondition(this.exchange)).isSameAs(empty); } @Test @@ -95,8 +92,8 @@ public class RequestConditionHolderTests { RequestConditionHolder params11 = new RequestConditionHolder(new ParamsRequestCondition("1")); RequestConditionHolder params12 = new RequestConditionHolder(new ParamsRequestCondition("1", "2")); - assertEquals(1, params11.compareTo(params12, this.exchange)); - assertEquals(-1, params12.compareTo(params11, this.exchange)); + assertThat(params11.compareTo(params12, this.exchange)).isEqualTo(1); + assertThat(params12.compareTo(params11, this.exchange)).isEqualTo(-1); } @Test @@ -105,9 +102,9 @@ public class RequestConditionHolderTests { RequestConditionHolder empty2 = new RequestConditionHolder(null); RequestConditionHolder notEmpty = new RequestConditionHolder(new ParamsRequestCondition("name")); - assertEquals(0, empty.compareTo(empty2, this.exchange)); - assertEquals(-1, notEmpty.compareTo(empty, this.exchange)); - assertEquals(1, empty.compareTo(notEmpty, this.exchange)); + assertThat(empty.compareTo(empty2, this.exchange)).isEqualTo(0); + assertThat(notEmpty.compareTo(empty, this.exchange)).isEqualTo(-1); + assertThat(empty.compareTo(notEmpty, this.exchange)).isEqualTo(1); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestMappingInfoTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestMappingInfoTests.java index 2ec83a8c874..aa412511165 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestMappingInfoTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestMappingInfoTests.java @@ -36,12 +36,8 @@ import org.springframework.web.util.pattern.PathPatternParser; import org.springframework.web.util.pattern.PatternParseException; import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.springframework.web.reactive.result.method.RequestMappingInfo.paths; /** @@ -59,13 +55,13 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths().build(); PathPattern emptyPattern = (new PathPatternParser()).parse(""); - assertEquals(Collections.singleton(emptyPattern), info.getPatternsCondition().getPatterns()); - assertEquals(0, info.getMethodsCondition().getMethods().size()); - assertEquals(true, info.getConsumesCondition().isEmpty()); - assertEquals(true, info.getProducesCondition().isEmpty()); - assertNotNull(info.getParamsCondition()); - assertNotNull(info.getHeadersCondition()); - assertNull(info.getCustomCondition()); + assertThat(info.getPatternsCondition().getPatterns()).isEqualTo(Collections.singleton(emptyPattern)); + assertThat(info.getMethodsCondition().getMethods().size()).isEqualTo(0); + assertThat(info.getConsumesCondition().isEmpty()).isEqualTo(true); + assertThat(info.getProducesCondition().isEmpty()).isEqualTo(true); + assertThat(info.getParamsCondition()).isNotNull(); + assertThat(info.getHeadersCondition()).isNotNull(); + assertThat(info.getCustomCondition()).isNull(); } @Test @@ -79,8 +75,8 @@ public class RequestMappingInfoTests { public void prependPatternWithSlash() { RequestMappingInfo actual = paths("foo").build(); List patterns = new ArrayList<>(actual.getPatternsCondition().getPatterns()); - assertEquals(1, patterns.size()); - assertEquals("/foo", patterns.get(0).getPatternString()); + assertThat(patterns.size()).isEqualTo(1); + assertThat(patterns.get(0).getPatternString()).isEqualTo("/foo"); } @Test @@ -90,12 +86,12 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo*", "/bar").build(); RequestMappingInfo expected = paths("/foo*").build(); - assertEquals(expected, info.getMatchingCondition(exchange)); + assertThat(info.getMatchingCondition(exchange)).isEqualTo(expected); info = paths("/**", "/foo*", "/foo").build(); expected = paths("/foo", "/foo*", "/**").build(); - assertEquals(expected, info.getMatchingCondition(exchange)); + assertThat(info.getMatchingCondition(exchange)).isEqualTo(expected); } @Test @@ -105,12 +101,12 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").params("foo=bar").build(); RequestMappingInfo match = info.getMatchingCondition(exchange); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").params("foo!=bar").build(); match = info.getMatchingCondition(exchange); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -121,12 +117,12 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").headers("foo=bar").build(); RequestMappingInfo match = info.getMatchingCondition(exchange); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").headers("foo!=bar").build(); match = info.getMatchingCondition(exchange); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -137,12 +133,12 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").consumes("text/plain").build(); RequestMappingInfo match = info.getMatchingCondition(exchange); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").consumes("application/xml").build(); match = info.getMatchingCondition(exchange); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -153,12 +149,12 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").produces("text/plain").build(); RequestMappingInfo match = info.getMatchingCondition(exchange); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").produces("application/xml").build(); match = info.getMatchingCondition(exchange); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -168,14 +164,14 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").params("foo=bar").build(); RequestMappingInfo match = info.getMatchingCondition(exchange); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").params("foo!=bar") .customCondition(new ParamsRequestCondition("foo!=bar")).build(); match = info.getMatchingCondition(exchange); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -191,9 +187,9 @@ public class RequestMappingInfoTests { Collections.shuffle(list); list.sort(comparator); - assertEquals(oneMethodOneParam, list.get(0)); - assertEquals(oneMethod, list.get(1)); - assertEquals(none, list.get(2)); + assertThat(list.get(0)).isEqualTo(oneMethodOneParam); + assertThat(list.get(1)).isEqualTo(oneMethod); + assertThat(list.get(2)).isEqualTo(none); } @Test @@ -210,8 +206,8 @@ public class RequestMappingInfoTests { .customCondition(new ParamsRequestCondition("customFoo=customBar")) .build(); - assertEquals(info1, info2); - assertEquals(info1.hashCode(), info2.hashCode()); + assertThat(info2).isEqualTo(info1); + assertThat(info2.hashCode()).isEqualTo(info1.hashCode()); info2 = paths("/foo", "/NOOOOOO").methods(RequestMethod.GET) .params("foo=bar").headers("foo=bar") @@ -219,8 +215,8 @@ public class RequestMappingInfoTests { .customCondition(new ParamsRequestCondition("customFoo=customBar")) .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(RequestMethod.GET, RequestMethod.POST) .params("foo=bar").headers("foo=bar") @@ -228,8 +224,8 @@ public class RequestMappingInfoTests { .customCondition(new ParamsRequestCondition("customFoo=customBar")) .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(RequestMethod.GET) .params("/NOOOOOO").headers("foo=bar") @@ -237,8 +233,8 @@ public class RequestMappingInfoTests { .customCondition(new ParamsRequestCondition("customFoo=customBar")) .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(RequestMethod.GET) .params("foo=bar").headers("/NOOOOOO") @@ -246,8 +242,8 @@ public class RequestMappingInfoTests { .customCondition(new ParamsRequestCondition("customFoo=customBar")) .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(RequestMethod.GET) .params("foo=bar").headers("foo=bar") @@ -255,8 +251,8 @@ public class RequestMappingInfoTests { .customCondition(new ParamsRequestCondition("customFoo=customBar")) .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(RequestMethod.GET) .params("foo=bar").headers("foo=bar") @@ -264,8 +260,8 @@ public class RequestMappingInfoTests { .customCondition(new ParamsRequestCondition("customFoo=customBar")) .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(RequestMethod.GET) .params("foo=bar").headers("foo=bar") @@ -273,8 +269,8 @@ public class RequestMappingInfoTests { .customCondition(new ParamsRequestCondition("customFoo=NOOOOOO")) .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); } @Test @@ -287,11 +283,11 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").methods(RequestMethod.POST).build(); RequestMappingInfo match = info.getMatchingCondition(exchange); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").methods(RequestMethod.OPTIONS).build(); match = info.getMatchingCondition(exchange); - assertNull("Pre-flight should match the ACCESS_CONTROL_REQUEST_METHOD", match); + assertThat(match).as("Pre-flight should match the ACCESS_CONTROL_REQUEST_METHOD").isNull(); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestMethodsRequestConditionTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestMethodsRequestConditionTests.java index ae0be2e0c47..1a775156077 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestMethodsRequestConditionTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestMethodsRequestConditionTests.java @@ -29,10 +29,7 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.bind.annotation.RequestMethod.DELETE; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.HEAD; @@ -69,7 +66,7 @@ public class RequestMethodsRequestConditionTests { for (RequestMethod method : RequestMethod.values()) { if (method != OPTIONS) { ServerWebExchange exchange = getExchange(method.name()); - assertNotNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNotNull(); } } testNoMatch(condition, OPTIONS); @@ -79,8 +76,8 @@ public class RequestMethodsRequestConditionTests { @Ignore public void getMatchingConditionWithCustomMethod() throws Exception { ServerWebExchange exchange = getExchange("PROPFIND"); - assertNotNull(new RequestMethodsRequestCondition().getMatchingCondition(exchange)); - assertNull(new RequestMethodsRequestCondition(GET, POST).getMatchingCondition(exchange)); + assertThat(new RequestMethodsRequestCondition().getMatchingCondition(exchange)).isNotNull(); + assertThat(new RequestMethodsRequestCondition(GET, POST).getMatchingCondition(exchange)).isNull(); } @Test @@ -90,9 +87,9 @@ public class RequestMethodsRequestConditionTests { exchange.getRequest().getHeaders().add("Origin", "https://example.com"); exchange.getRequest().getHeaders().add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PUT"); - assertNotNull(new RequestMethodsRequestCondition().getMatchingCondition(exchange)); - assertNotNull(new RequestMethodsRequestCondition(PUT).getMatchingCondition(exchange)); - assertNull(new RequestMethodsRequestCondition(DELETE).getMatchingCondition(exchange)); + assertThat(new RequestMethodsRequestCondition().getMatchingCondition(exchange)).isNotNull(); + assertThat(new RequestMethodsRequestCondition(PUT).getMatchingCondition(exchange)).isNotNull(); + assertThat(new RequestMethodsRequestCondition(DELETE).getMatchingCondition(exchange)).isNull(); } @Test @@ -104,16 +101,16 @@ public class RequestMethodsRequestConditionTests { ServerWebExchange exchange = getExchange("GET"); int result = c1.compareTo(c2, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = c2.compareTo(c1, exchange); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); result = c2.compareTo(c3, exchange); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = c1.compareTo(c1, exchange); - assertEquals("Invalid comparison result ", 0, result); + assertThat(result).as("Invalid comparison result ").isEqualTo(0); } @Test @@ -122,20 +119,20 @@ public class RequestMethodsRequestConditionTests { RequestMethodsRequestCondition condition2 = new RequestMethodsRequestCondition(POST); RequestMethodsRequestCondition result = condition1.combine(condition2); - assertEquals(2, result.getContent().size()); + assertThat(result.getContent().size()).isEqualTo(2); } private void testMatch(RequestMethodsRequestCondition condition, RequestMethod method) throws Exception { ServerWebExchange exchange = getExchange(method.name()); RequestMethodsRequestCondition actual = condition.getMatchingCondition(exchange); - assertNotNull(actual); - assertEquals(Collections.singleton(method), actual.getContent()); + assertThat(actual).isNotNull(); + assertThat(actual.getContent()).isEqualTo(Collections.singleton(method)); } private void testNoMatch(RequestMethodsRequestCondition condition, RequestMethod method) throws Exception { ServerWebExchange exchange = getExchange(method.name()); - assertNull(condition.getMatchingCondition(exchange)); + assertThat(condition.getMatchingCondition(exchange)).isNull(); } private ServerWebExchange getExchange(String method) throws URISyntaxException { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/HandlerMethodMappingTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/HandlerMethodMappingTests.java index ee500e65300..45c2ab0e9db 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/HandlerMethodMappingTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/HandlerMethodMappingTests.java @@ -37,9 +37,6 @@ import org.springframework.web.util.pattern.PathPatternParser; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; /** * Unit tests for {@link AbstractHandlerMethodMapping}. @@ -81,7 +78,7 @@ public class HandlerMethodMappingTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(key)); Mono result = this.mapping.getHandler(exchange); - assertEquals(this.method1, ((HandlerMethod) result.block()).getMethod()); + assertThat(((HandlerMethod) result.block()).getMethod()).isEqualTo(this.method1); } @Test @@ -91,7 +88,7 @@ public class HandlerMethodMappingTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/foo")); Mono result = this.mapping.getHandler(exchange); - assertEquals(this.method1, ((HandlerMethod) result.block()).getMethod()); + assertThat(((HandlerMethod) result.block()).getMethod()).isEqualTo(this.method1); } @Test @@ -134,12 +131,12 @@ public class HandlerMethodMappingTests { this.mapping.registerMapping(key, this.handler, this.method1); Mono result = this.mapping.getHandler(MockServerWebExchange.from(MockServerHttpRequest.get(key))); - assertNotNull(result.block()); + assertThat(result.block()).isNotNull(); this.mapping.unregisterMapping(key); result = this.mapping.getHandler(MockServerWebExchange.from(MockServerHttpRequest.get(key))); - assertNull(result.block()); + assertThat(result.block()).isNull(); assertThat(this.mapping.getMappingRegistry().getMappings().keySet()).isNotEqualTo(Matchers.contains(key)); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/InvocableHandlerMethodTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/InvocableHandlerMethodTests.java index 7101f20b013..4feff4680de 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/InvocableHandlerMethodTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/InvocableHandlerMethodTests.java @@ -45,8 +45,6 @@ import org.springframework.web.server.UnsupportedMediaTypeStatusException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -167,8 +165,8 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(TestController.class).mockCall(c -> c.response(response)).method(); HandlerResult result = invokeForResult(new TestController(), method); - assertNull("Expected no result (i.e. fully handled)", result); - assertEquals("bar", this.exchange.getResponse().getHeaders().getFirst("foo")); + assertThat(result).as("Expected no result (i.e. fully handled)").isNull(); + assertThat(this.exchange.getResponse().getHeaders().getFirst("foo")).isEqualTo("bar"); } @Test @@ -178,8 +176,8 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(TestController.class).mockCall(c -> c.responseMonoVoid(response)).method(); HandlerResult result = invokeForResult(new TestController(), method); - assertNull("Expected no result (i.e. fully handled)", result); - assertEquals("body", this.exchange.getResponse().getBodyAsString().block(Duration.ZERO)); + assertThat(result).as("Expected no result (i.e. fully handled)").isNull(); + assertThat(this.exchange.getResponse().getBodyAsString().block(Duration.ZERO)).isEqualTo("body"); } @Test @@ -188,8 +186,8 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(TestController.class).mockCall(c -> c.exchange(exchange)).method(); HandlerResult result = invokeForResult(new TestController(), method); - assertNull("Expected no result (i.e. fully handled)", result); - assertEquals("bar", this.exchange.getResponse().getHeaders().getFirst("foo")); + assertThat(result).as("Expected no result (i.e. fully handled)").isNull(); + assertThat(this.exchange.getResponse().getHeaders().getFirst("foo")).isEqualTo("bar"); } @Test @@ -198,8 +196,8 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(TestController.class).mockCall(c -> c.exchangeMonoVoid(exchange)).method(); HandlerResult result = invokeForResult(new TestController(), method); - assertNull("Expected no result (i.e. fully handled)", result); - assertEquals("body", this.exchange.getResponse().getBodyAsString().block(Duration.ZERO)); + assertThat(result).as("Expected no result (i.e. fully handled)").isNull(); + assertThat(this.exchange.getResponse().getBodyAsString().block(Duration.ZERO)).isEqualTo("body"); } @Test @@ -210,7 +208,7 @@ public class InvocableHandlerMethodTests { Method method = ResolvableMethod.on(TestController.class).mockCall(c -> c.notModified(exchange)).method(); HandlerResult result = invokeForResult(new TestController(), method); - assertNull("Expected no result (i.e. fully handled)", result); + assertThat(result).as("Expected no result (i.e. fully handled)").isNull(); } @@ -238,7 +236,7 @@ public class InvocableHandlerMethodTests { private void assertHandlerResultValue(Mono mono, String expected) { StepVerifier.create(mono) - .consumeNextWith(result -> assertEquals(expected, result.getReturnValue())) + .consumeNextWith(result -> assertThat(result.getReturnValue()).isEqualTo(expected)) .expectComplete() .verify(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMappingTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMappingTests.java index 3f25dbcc177..395d3d1906b 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMappingTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMappingTests.java @@ -59,10 +59,6 @@ import org.springframework.web.server.UnsupportedMediaTypeStatusException; import org.springframework.web.util.pattern.PathPattern; import static org.assertj.core.api.Assertions.assertThat; -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.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.method; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.post; @@ -104,7 +100,7 @@ public class RequestMappingInfoHandlerMappingTests { ServerWebExchange exchange = MockServerWebExchange.from(get("/foo")); HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(exchange).block(); - assertEquals(expected, hm.getMethod()); + assertThat(hm.getMethod()).isEqualTo(expected); } @Test @@ -113,7 +109,7 @@ public class RequestMappingInfoHandlerMappingTests { ServerWebExchange exchange = MockServerWebExchange.from(get("/bar")); HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(exchange).block(); - assertEquals(expected, hm.getMethod()); + assertThat(hm.getMethod()).isEqualTo(expected); } @Test @@ -121,11 +117,11 @@ public class RequestMappingInfoHandlerMappingTests { Method expected = on(TestController.class).annot(requestMapping("")).resolveMethod(); ServerWebExchange exchange = MockServerWebExchange.from(get("")); HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(exchange).block(); - assertEquals(expected, hm.getMethod()); + assertThat(hm.getMethod()).isEqualTo(expected); exchange = MockServerWebExchange.from(get("/")); hm = (HandlerMethod) this.handlerMapping.getHandler(exchange).block(); - assertEquals(expected, hm.getMethod()); + assertThat(hm.getMethod()).isEqualTo(expected); } @Test @@ -134,7 +130,7 @@ public class RequestMappingInfoHandlerMappingTests { ServerWebExchange exchange = MockServerWebExchange.from(get("/foo?p=anything")); HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(exchange).block(); - assertEquals(expected, hm.getMethod()); + assertThat(hm.getMethod()).isEqualTo(expected); } @Test @@ -143,7 +139,7 @@ public class RequestMappingInfoHandlerMappingTests { Mono mono = this.handlerMapping.getHandler(exchange); assertError(mono, MethodNotAllowedException.class, - ex -> assertEquals(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD), ex.getSupportedMethods())); + ex -> assertThat(ex.getSupportedMethods()).isEqualTo(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD))); } @Test // SPR-9603 @@ -171,8 +167,8 @@ public class RequestMappingInfoHandlerMappingTests { Mono mono = this.handlerMapping.getHandler(exchange); assertError(mono, UnsupportedMediaTypeStatusException.class, - ex -> assertEquals("415 UNSUPPORTED_MEDIA_TYPE " + - "\"Invalid mime type \"bogus\": does not contain '/'\"", ex.getMessage())); + ex -> assertThat(ex.getMessage()).isEqualTo(("415 UNSUPPORTED_MEDIA_TYPE " + + "\"Invalid mime type \"bogus\": does not contain '/'\""))); } @Test // SPR-8462 @@ -208,13 +204,12 @@ public class RequestMappingInfoHandlerMappingTests { this.handlerMapping.getHandler(exchange).block(); String name = HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE; - assertEquals(Collections.singleton(MediaType.APPLICATION_XML), exchange.getAttributes().get(name)); + assertThat(exchange.getAttributes().get(name)).isEqualTo(Collections.singleton(MediaType.APPLICATION_XML)); exchange = MockServerWebExchange.from(get("/content").accept(MediaType.APPLICATION_JSON)); this.handlerMapping.getHandler(exchange).block(); - assertNull("Negated expression shouldn't be listed as producible type", - exchange.getAttributes().get(name)); + assertThat(exchange.getAttributes().get(name)).as("Negated expression shouldn't be listed as producible type").isNull(); } @Test @@ -228,9 +223,9 @@ public class RequestMappingInfoHandlerMappingTests { String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE; Map uriVariables = (Map) exchange.getAttributes().get(name); - assertNotNull(uriVariables); - assertEquals("1", uriVariables.get("path1")); - assertEquals("2", uriVariables.get("path2")); + assertThat(uriVariables).isNotNull(); + assertThat(uriVariables.get("path1")).isEqualTo("1"); + assertThat(uriVariables.get("path2")).isEqualTo("2"); } @Test // SPR-9098 @@ -245,9 +240,9 @@ public class RequestMappingInfoHandlerMappingTests { @SuppressWarnings("unchecked") Map uriVariables = (Map) exchange.getAttributes().get(name); - assertNotNull(uriVariables); - assertEquals("group", uriVariables.get("group")); - assertEquals("a/b", uriVariables.get("identifier")); + assertThat(uriVariables).isNotNull(); + assertThat(uriVariables.get("group")).isEqualTo("group"); + assertThat(uriVariables.get("identifier")).isEqualTo("a/b"); } @Test @@ -257,10 +252,10 @@ public class RequestMappingInfoHandlerMappingTests { this.handlerMapping.handleMatch(key, handlerMethod, exchange); PathPattern bestMatch = (PathPattern) exchange.getAttributes().get(BEST_MATCHING_PATTERN_ATTRIBUTE); - assertEquals("/{path1}/2", bestMatch.getPatternString()); + assertThat(bestMatch.getPatternString()).isEqualTo("/{path1}/2"); HandlerMethod mapped = (HandlerMethod) exchange.getAttributes().get(BEST_MATCHING_HANDLER_ATTRIBUTE); - assertSame(handlerMethod, mapped); + assertThat(mapped).isSameAs(handlerMethod); } @Test // gh-22543 @@ -268,7 +263,7 @@ public class RequestMappingInfoHandlerMappingTests { ServerWebExchange exchange = MockServerWebExchange.from(get("")); this.handlerMapping.handleMatch(paths().build(), handlerMethod, exchange); PathPattern pattern = (PathPattern) exchange.getAttributes().get(BEST_MATCHING_PATTERN_ATTRIBUTE); - assertEquals("", pattern.getPatternString()); + assertThat(pattern.getPatternString()).isEqualTo(""); } @Test @@ -282,10 +277,10 @@ public class RequestMappingInfoHandlerMappingTests { matrixVariables = getMatrixVariables(exchange, "cars"); uriVariables = getUriTemplateVariables(exchange); - assertNotNull(matrixVariables); - assertEquals(Arrays.asList("red", "blue", "green"), matrixVariables.get("colors")); - assertEquals("2012", matrixVariables.getFirst("year")); - assertEquals("cars", uriVariables.get("cars")); + assertThat(matrixVariables).isNotNull(); + assertThat(matrixVariables.get("colors")).isEqualTo(Arrays.asList("red", "blue", "green")); + assertThat(matrixVariables.getFirst("year")).isEqualTo("2012"); + assertThat(uriVariables.get("cars")).isEqualTo("cars"); // SPR-11897 exchange = MockServerWebExchange.from(get("/a=42;b=c")); @@ -298,10 +293,10 @@ public class RequestMappingInfoHandlerMappingTests { // "/foo/{ids}" and URL "/foo/id=1;id=2;id=3" where the whole path // segment is a sequence of name-value pairs. - assertNotNull(matrixVariables); - assertEquals(1, matrixVariables.size()); - assertEquals("c", matrixVariables.getFirst("b")); - assertEquals("a=42", uriVariables.get("foo")); + assertThat(matrixVariables).isNotNull(); + assertThat(matrixVariables.size()).isEqualTo(1); + assertThat(matrixVariables.getFirst("b")).isEqualTo("c"); + assertThat(uriVariables.get("foo")).isEqualTo("a=42"); } @Test @@ -313,9 +308,9 @@ public class RequestMappingInfoHandlerMappingTests { MultiValueMap matrixVariables = getMatrixVariables(exchange, "cars"); Map uriVariables = getUriTemplateVariables(exchange); - assertNotNull(matrixVariables); - assertEquals(Collections.singletonList("a/b"), matrixVariables.get("mvar")); - assertEquals("cars", uriVariables.get("cars")); + assertThat(matrixVariables).isNotNull(); + assertThat(matrixVariables.get("mvar")).isEqualTo(Collections.singletonList("a/b")); + assertThat(uriVariables.get("cars")).isEqualTo("cars"); } @@ -323,7 +318,7 @@ public class RequestMappingInfoHandlerMappingTests { private void assertError(Mono mono, final Class exceptionClass, final Consumer consumer) { StepVerifier.create(mono) .consumeErrorWith(error -> { - assertEquals(exceptionClass, error.getClass()); + assertThat(error.getClass()).isEqualTo(exceptionClass); consumer.accept((T) error); }) .verify(); @@ -334,10 +329,7 @@ public class RequestMappingInfoHandlerMappingTests { ServerWebExchange exchange = MockServerWebExchange.from(request); Mono mono = this.handlerMapping.getHandler(exchange); - assertError(mono, UnsupportedMediaTypeStatusException.class, ex -> - assertEquals("Invalid supported consumable media types", - Collections.singletonList(new MediaType("application", "xml")), - ex.getSupportedMediaTypes())); + assertError(mono, UnsupportedMediaTypeStatusException.class, ex -> assertThat(ex.getSupportedMediaTypes()).as("Invalid supported consumable media types").isEqualTo(Collections.singletonList(new MediaType("application", "xml")))); } private void testHttpOptions(String requestURI, Set allowedMethods) { @@ -349,22 +341,19 @@ public class RequestMappingInfoHandlerMappingTests { Mono mono = invocable.invoke(exchange, bindingContext); HandlerResult result = mono.block(); - assertNotNull(result); + assertThat(result).isNotNull(); Object value = result.getReturnValue(); - assertNotNull(value); - assertEquals(HttpHeaders.class, value.getClass()); - assertEquals(allowedMethods, ((HttpHeaders) value).getAllow()); + assertThat(value).isNotNull(); + assertThat(value.getClass()).isEqualTo(HttpHeaders.class); + assertThat(((HttpHeaders) value).getAllow()).isEqualTo(allowedMethods); } private void testMediaTypeNotAcceptable(String url) { ServerWebExchange exchange = MockServerWebExchange.from(get(url).accept(MediaType.APPLICATION_JSON)); Mono mono = this.handlerMapping.getHandler(exchange); - assertError(mono, NotAcceptableStatusException.class, ex -> - assertEquals("Invalid supported producible media types", - Collections.singletonList(new MediaType("application", "xml")), - ex.getSupportedMediaTypes())); + assertError(mono, NotAcceptableStatusException.class, ex -> assertThat(ex.getSupportedMediaTypes()).as("Invalid supported producible media types").isEqualTo(Collections.singletonList(new MediaType("application", "xml")))); } private void handleMatch(ServerWebExchange exchange, String pattern) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ContextPathIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ContextPathIntegrationTests.java index 9776e46a801..ba16cfbf57b 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ContextPathIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ContextPathIntegrationTests.java @@ -32,7 +32,7 @@ import org.springframework.web.client.RestTemplate; import org.springframework.web.reactive.config.EnableWebFlux; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests related to the use of context paths. @@ -67,11 +67,11 @@ public class ContextPathIntegrationTests { String url = "http://localhost:" + server.getPort() + "/webApp1/test"; actual = restTemplate.getForObject(url, String.class); - assertEquals("Tested in /webApp1", actual); + assertThat(actual).isEqualTo("Tested in /webApp1"); url = "http://localhost:" + server.getPort() + "/webApp2/test"; actual = restTemplate.getForObject(url, String.class); - assertEquals("Tested in /webApp2", actual); + assertThat(actual).isEqualTo("Tested in /webApp2"); } finally { server.stop(); @@ -101,7 +101,7 @@ public class ContextPathIntegrationTests { String url = "http://localhost:" + server.getPort() + "/app/api/test"; actual = restTemplate.getForObject(url, String.class); - assertEquals("Tested in /app/api", actual); + assertThat(actual).isEqualTo("Tested in /app/api"); } finally { server.stop(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerAdviceTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerAdviceTests.java index 9cbc03f4c79..9a4da6ecfe5 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerAdviceTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerAdviceTests.java @@ -45,7 +45,7 @@ import org.springframework.web.method.HandlerMethod; import org.springframework.web.reactive.BindingContext; import org.springframework.web.reactive.HandlerResult; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -95,7 +95,7 @@ public class ControllerAdviceTests { controller.setException(exception); Object actual = handle(adapter, controller, "handle").getReturnValue(); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -106,9 +106,9 @@ public class ControllerAdviceTests { Model model = handle(adapter, controller, "handle").getModel(); - assertEquals(2, model.asMap().size()); - assertEquals("lAttr1", model.asMap().get("attr1")); - assertEquals("gAttr2", model.asMap().get("attr2")); + assertThat(model.asMap().size()).isEqualTo(2); + assertThat(model.asMap().get("attr1")).isEqualTo("lAttr1"); + assertThat(model.asMap().get("attr2")).isEqualTo("gAttr2"); } @Test @@ -123,7 +123,7 @@ public class ControllerAdviceTests { BindingContext bindingContext = handle(adapter, controller, "handle").getBindingContext(); WebExchangeDataBinder binder = bindingContext.createDataBinder(this.exchange, "name"); - assertEquals(Collections.singletonList(validator), binder.getValidators()); + assertThat(binder.getValidators()).isEqualTo(Collections.singletonList(validator)); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerInputIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerInputIntegrationTests.java index eb81e8dd970..7cf3c12413b 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerInputIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerInputIntegrationTests.java @@ -30,7 +30,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.config.EnableWebFlux; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * {@code @RequestMapping} integration focusing on controller method parameters. @@ -55,20 +55,20 @@ public class ControllerInputIntegrationTests extends AbstractRequestMappingInteg @Test public void handleWithParam() throws Exception { String expected = "Hello George!"; - assertEquals(expected, performGet("/param?name=George", new HttpHeaders(), String.class).getBody()); + assertThat(performGet("/param?name=George", new HttpHeaders(), String.class).getBody()).isEqualTo(expected); } @Test // SPR-15140 public void handleWithEncodedParam() throws Exception { String expected = "Hello + \u00e0!"; - assertEquals(expected, performGet("/param?name=%20%2B+%C3%A0", new HttpHeaders(), String.class).getBody()); + assertThat(performGet("/param?name=%20%2B+%C3%A0", new HttpHeaders(), String.class).getBody()).isEqualTo(expected); } @Test public void matrixVariable() throws Exception { String expected = "p=11, q2=22, q4=44"; String url = "/first;p=11/second;q=22/third-fourth;q=44"; - assertEquals(expected, performGet(url, new HttpHeaders(), String.class).getBody()); + assertThat(performGet(url, new HttpHeaders(), String.class).getBody()).isEqualTo(expected); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerMethodResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerMethodResolverTests.java index f3efd8e3419..dcce6653b83 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerMethodResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ControllerMethodResolverTests.java @@ -47,8 +47,7 @@ import org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ControllerMethodResolver}. @@ -90,73 +89,73 @@ public class ControllerMethodResolverTests { List resolvers = invocable.getResolvers(); AtomicInteger index = new AtomicInteger(-1); - assertEquals(RequestParamMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestParamMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(PathVariableMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(PathVariableMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(MatrixVariableMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(MatrixVariableMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestBodyMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestPartMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ModelAttributeMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestHeaderMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestHeaderMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(CookieValueMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ExpressionValueMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(SessionAttributeMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestAttributeMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(PathVariableMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(PathVariableMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(MatrixVariableMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(MatrixVariableMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestBodyMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestPartMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ModelAttributeMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestHeaderMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestHeaderMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(CookieValueMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ExpressionValueMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(SessionAttributeMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestAttributeMethodArgumentResolver.class); - assertEquals(ContinuationHandlerMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(HttpEntityMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ModelMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ErrorsMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ServerWebExchangeMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(PrincipalMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(SessionStatusMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(WebSessionMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(ContinuationHandlerMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(HttpEntityMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ModelMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ErrorsMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ServerWebExchangeMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(PrincipalMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(SessionStatusMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(WebSessionMethodArgumentResolver.class); - assertEquals(CustomArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(CustomSyncArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(CustomArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(CustomSyncArgumentResolver.class); - assertEquals(RequestParamMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ModelAttributeMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ModelAttributeMethodArgumentResolver.class); } @Test public void modelAttributeArgumentResolvers() { List methods = this.methodResolver.getModelAttributeMethods(this.handlerMethod); - assertEquals("Expected one each from Controller + ControllerAdvice", 2, methods.size()); + assertThat(methods.size()).as("Expected one each from Controller + ControllerAdvice").isEqualTo(2); InvocableHandlerMethod invocable = methods.get(0); List resolvers = invocable.getResolvers(); AtomicInteger index = new AtomicInteger(-1); - assertEquals(RequestParamMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestParamMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(PathVariableMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(PathVariableMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(MatrixVariableMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(MatrixVariableMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ModelAttributeMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestHeaderMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestHeaderMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(CookieValueMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ExpressionValueMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(SessionAttributeMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestAttributeMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(PathVariableMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(PathVariableMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(MatrixVariableMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(MatrixVariableMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ModelAttributeMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestHeaderMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestHeaderMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(CookieValueMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ExpressionValueMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(SessionAttributeMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestAttributeMethodArgumentResolver.class); - assertEquals(ContinuationHandlerMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ModelMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ErrorsMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ServerWebExchangeMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(PrincipalMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(WebSessionMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(ContinuationHandlerMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ModelMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ErrorsMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ServerWebExchangeMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(PrincipalMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(WebSessionMethodArgumentResolver.class); - assertEquals(CustomArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(CustomSyncArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(CustomArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(CustomSyncArgumentResolver.class); - assertEquals(RequestParamMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ModelAttributeMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ModelAttributeMethodArgumentResolver.class); } @Test @@ -164,29 +163,29 @@ public class ControllerMethodResolverTests { List methods = this.methodResolver.getInitBinderMethods(this.handlerMethod); - assertEquals("Expected one each from Controller + ControllerAdvice", 2, methods.size()); + assertThat(methods.size()).as("Expected one each from Controller + ControllerAdvice").isEqualTo(2); SyncInvocableHandlerMethod invocable = methods.get(0); List resolvers = invocable.getResolvers(); AtomicInteger index = new AtomicInteger(-1); - assertEquals(RequestParamMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestParamMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(PathVariableMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(PathVariableMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(MatrixVariableMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(MatrixVariableMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestHeaderMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestHeaderMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(CookieValueMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ExpressionValueMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestAttributeMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(PathVariableMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(PathVariableMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(MatrixVariableMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(MatrixVariableMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestHeaderMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestHeaderMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(CookieValueMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ExpressionValueMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestAttributeMethodArgumentResolver.class); - assertEquals(ModelMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ServerWebExchangeMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(ModelMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ServerWebExchangeMethodArgumentResolver.class); - assertEquals(CustomSyncArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(CustomSyncArgumentResolver.class); - assertEquals(RequestParamMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMethodArgumentResolver.class); } @Test @@ -194,34 +193,34 @@ public class ControllerMethodResolverTests { InvocableHandlerMethod invocable = this.methodResolver.getExceptionHandlerMethod( new ResponseStatusException(HttpStatus.BAD_REQUEST, "reason"), this.handlerMethod); - assertNotNull("No match", invocable); - assertEquals(TestController.class, invocable.getBeanType()); + assertThat(invocable).as("No match").isNotNull(); + assertThat(invocable.getBeanType()).isEqualTo(TestController.class); List resolvers = invocable.getResolvers(); AtomicInteger index = new AtomicInteger(-1); - assertEquals(RequestParamMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestParamMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(PathVariableMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(PathVariableMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(MatrixVariableMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(MatrixVariableMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestHeaderMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestHeaderMapMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(CookieValueMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ExpressionValueMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(SessionAttributeMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(RequestAttributeMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(PathVariableMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(PathVariableMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(MatrixVariableMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(MatrixVariableMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestHeaderMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestHeaderMapMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(CookieValueMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ExpressionValueMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(SessionAttributeMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestAttributeMethodArgumentResolver.class); - assertEquals(ContinuationHandlerMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ModelMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(ServerWebExchangeMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(PrincipalMethodArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(WebSessionMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(ContinuationHandlerMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ModelMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(ServerWebExchangeMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(PrincipalMethodArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(WebSessionMethodArgumentResolver.class); - assertEquals(CustomArgumentResolver.class, next(resolvers, index).getClass()); - assertEquals(CustomSyncArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(CustomArgumentResolver.class); + assertThat(next(resolvers, index).getClass()).isEqualTo(CustomSyncArgumentResolver.class); - assertEquals(RequestParamMethodArgumentResolver.class, next(resolvers, index).getClass()); + assertThat(next(resolvers, index).getClass()).isEqualTo(RequestParamMethodArgumentResolver.class); } @Test @@ -229,8 +228,8 @@ public class ControllerMethodResolverTests { InvocableHandlerMethod invocable = this.methodResolver.getExceptionHandlerMethod( new IllegalStateException("reason"), this.handlerMethod); - assertNotNull(invocable); - assertEquals(TestControllerAdvice.class, invocable.getBeanType()); + assertThat(invocable).isNotNull(); + assertThat(invocable.getBeanType()).isEqualTo(TestControllerAdvice.class); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CookieValueMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CookieValueMethodArgumentResolverTests.java index dd26fd5837f..e9715d81a82 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CookieValueMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CookieValueMethodArgumentResolverTests.java @@ -35,10 +35,8 @@ import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Test fixture with {@link CookieValueMethodArgumentResolver}. @@ -77,13 +75,13 @@ public class CookieValueMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter(this.cookieParameter)); - assertTrue(this.resolver.supportsParameter(this.cookieStringParameter)); + assertThat(this.resolver.supportsParameter(this.cookieParameter)).isTrue(); + assertThat(this.resolver.supportsParameter(this.cookieStringParameter)).isTrue(); } @Test public void doesNotSupportParameter() { - assertFalse(this.resolver.supportsParameter(this.stringParameter)); + assertThat(this.resolver.supportsParameter(this.stringParameter)).isFalse(); assertThatIllegalStateException().isThrownBy(() -> this.resolver.supportsParameter(this.cookieMonoParameter)) .withMessageStartingWith("CookieValueMethodArgumentResolver does not support reactive type wrapper"); @@ -97,7 +95,7 @@ public class CookieValueMethodArgumentResolverTests { Mono mono = this.resolver.resolveArgument( this.cookieParameter, this.bindingContext, exchange); - assertEquals(expected, mono.block()); + assertThat(mono.block()).isEqualTo(expected); } @Test @@ -108,7 +106,7 @@ public class CookieValueMethodArgumentResolverTests { Mono mono = this.resolver.resolveArgument( this.cookieStringParameter, this.bindingContext, exchange); - assertEquals("Invalid result", cookie.getValue(), mono.block()); + assertThat(mono.block()).as("Invalid result").isEqualTo(cookie.getValue()); } @Test @@ -116,8 +114,9 @@ public class CookieValueMethodArgumentResolverTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); Object result = this.resolver.resolveArgument(this.cookieStringParameter, this.bindingContext, exchange).block(); - assertTrue(result instanceof String); - assertEquals("bar", result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo("bar"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CrossOriginAnnotationIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CrossOriginAnnotationIntegrationTests.java index 559a9d684b0..2f039a2405d 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CrossOriginAnnotationIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/CrossOriginAnnotationIntegrationTests.java @@ -41,11 +41,7 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import org.springframework.web.reactive.config.EnableWebFlux; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests with {@code @CrossOrigin} and {@code @RequestMapping} @@ -89,55 +85,55 @@ public class CrossOriginAnnotationIntegrationTests extends AbstractRequestMappin @Test public void actualGetRequestWithoutAnnotation() throws Exception { ResponseEntity entity = performGet("/no", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertNull(entity.getHeaders().getAccessControlAllowOrigin()); - assertEquals("no", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isNull(); + assertThat(entity.getBody()).isEqualTo("no"); } @Test public void actualPostRequestWithoutAnnotation() throws Exception { ResponseEntity entity = performPost("/no", this.headers, null, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertNull(entity.getHeaders().getAccessControlAllowOrigin()); - assertEquals("no-post", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isNull(); + assertThat(entity.getBody()).isEqualTo("no-post"); } @Test public void actualRequestWithDefaultAnnotation() throws Exception { ResponseEntity entity = performGet("/default", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("*", entity.getHeaders().getAccessControlAllowOrigin()); - assertFalse(entity.getHeaders().getAccessControlAllowCredentials()); - assertEquals("default", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("*"); + assertThat(entity.getHeaders().getAccessControlAllowCredentials()).isFalse(); + assertThat(entity.getBody()).isEqualTo("default"); } @Test public void preflightRequestWithDefaultAnnotation() throws Exception { this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); ResponseEntity entity = performOptions("/default", this.headers, Void.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("*", entity.getHeaders().getAccessControlAllowOrigin()); - assertEquals(1800, entity.getHeaders().getAccessControlMaxAge()); - assertFalse(entity.getHeaders().getAccessControlAllowCredentials()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("*"); + assertThat(entity.getHeaders().getAccessControlMaxAge()).isEqualTo(1800); + assertThat(entity.getHeaders().getAccessControlAllowCredentials()).isFalse(); } @Test public void actualRequestWithDefaultAnnotationAndNoOrigin() throws Exception { HttpHeaders headers = new HttpHeaders(); ResponseEntity entity = performGet("/default", headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertNull(entity.getHeaders().getAccessControlAllowOrigin()); - assertEquals("default", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isNull(); + assertThat(entity.getBody()).isEqualTo("default"); } @Test public void actualRequestWithCustomizedAnnotation() throws Exception { ResponseEntity entity = performGet("/customized", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("https://site1.com", entity.getHeaders().getAccessControlAllowOrigin()); - assertFalse(entity.getHeaders().getAccessControlAllowCredentials()); - assertEquals(-1, entity.getHeaders().getAccessControlMaxAge()); - assertEquals("customized", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("https://site1.com"); + assertThat(entity.getHeaders().getAccessControlAllowCredentials()).isFalse(); + assertThat(entity.getHeaders().getAccessControlMaxAge()).isEqualTo(-1); + assertThat(entity.getBody()).isEqualTo("customized"); } @Test @@ -146,53 +142,50 @@ public class CrossOriginAnnotationIntegrationTests extends AbstractRequestMappin this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "header1, header2"); ResponseEntity entity = performOptions("/customized", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("https://site1.com", entity.getHeaders().getAccessControlAllowOrigin()); - assertArrayEquals(new HttpMethod[] {HttpMethod.GET}, - entity.getHeaders().getAccessControlAllowMethods().toArray()); - assertArrayEquals(new String[] {"header1", "header2"}, - entity.getHeaders().getAccessControlAllowHeaders().toArray()); - assertArrayEquals(new String[] {"header3", "header4"}, - entity.getHeaders().getAccessControlExposeHeaders().toArray()); - assertFalse(entity.getHeaders().getAccessControlAllowCredentials()); - assertEquals(123, entity.getHeaders().getAccessControlMaxAge()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("https://site1.com"); + assertThat(entity.getHeaders().getAccessControlAllowMethods().toArray()).isEqualTo(new HttpMethod[] {HttpMethod.GET}); + assertThat(entity.getHeaders().getAccessControlAllowHeaders().toArray()).isEqualTo(new String[] {"header1", "header2"}); + assertThat(entity.getHeaders().getAccessControlExposeHeaders().toArray()).isEqualTo(new String[] {"header3", "header4"}); + assertThat(entity.getHeaders().getAccessControlAllowCredentials()).isFalse(); + assertThat(entity.getHeaders().getAccessControlMaxAge()).isEqualTo(123); } @Test public void customOriginDefinedViaValueAttribute() throws Exception { ResponseEntity entity = performGet("/origin-value-attribute", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("https://site1.com", entity.getHeaders().getAccessControlAllowOrigin()); - assertEquals("value-attribute", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("https://site1.com"); + assertThat(entity.getBody()).isEqualTo("value-attribute"); } @Test public void customOriginDefinedViaPlaceholder() throws Exception { ResponseEntity entity = performGet("/origin-placeholder", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("https://site1.com", entity.getHeaders().getAccessControlAllowOrigin()); - assertEquals("placeholder", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("https://site1.com"); + assertThat(entity.getBody()).isEqualTo("placeholder"); } @Test public void classLevel() throws Exception { ResponseEntity entity = performGet("/foo", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("*", entity.getHeaders().getAccessControlAllowOrigin()); - assertFalse(entity.getHeaders().getAccessControlAllowCredentials()); - assertEquals("foo", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("*"); + assertThat(entity.getHeaders().getAccessControlAllowCredentials()).isFalse(); + assertThat(entity.getBody()).isEqualTo("foo"); entity = performGet("/bar", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("*", entity.getHeaders().getAccessControlAllowOrigin()); - assertFalse(entity.getHeaders().getAccessControlAllowCredentials()); - assertEquals("bar", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("*"); + assertThat(entity.getHeaders().getAccessControlAllowCredentials()).isFalse(); + assertThat(entity.getBody()).isEqualTo("bar"); entity = performGet("/baz", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("https://site1.com", entity.getHeaders().getAccessControlAllowOrigin()); - assertTrue(entity.getHeaders().getAccessControlAllowCredentials()); - assertEquals("baz", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("https://site1.com"); + assertThat(entity.getHeaders().getAccessControlAllowCredentials()).isTrue(); + assertThat(entity.getBody()).isEqualTo("baz"); } @Test @@ -201,13 +194,11 @@ public class CrossOriginAnnotationIntegrationTests extends AbstractRequestMappin this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "header1"); ResponseEntity entity = performOptions("/ambiguous-header", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("https://site1.com", entity.getHeaders().getAccessControlAllowOrigin()); - assertArrayEquals(new HttpMethod[] {HttpMethod.GET}, - entity.getHeaders().getAccessControlAllowMethods().toArray()); - assertArrayEquals(new String[] {"header1"}, - entity.getHeaders().getAccessControlAllowHeaders().toArray()); - assertTrue(entity.getHeaders().getAccessControlAllowCredentials()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("https://site1.com"); + assertThat(entity.getHeaders().getAccessControlAllowMethods().toArray()).isEqualTo(new HttpMethod[] {HttpMethod.GET}); + assertThat(entity.getHeaders().getAccessControlAllowHeaders().toArray()).isEqualTo(new String[] {"header1"}); + assertThat(entity.getHeaders().getAccessControlAllowCredentials()).isTrue(); } @Test @@ -215,11 +206,10 @@ public class CrossOriginAnnotationIntegrationTests extends AbstractRequestMappin this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); ResponseEntity entity = performOptions("/ambiguous-produces", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("https://site1.com", entity.getHeaders().getAccessControlAllowOrigin()); - assertArrayEquals(new HttpMethod[] {HttpMethod.GET}, - entity.getHeaders().getAccessControlAllowMethods().toArray()); - assertTrue(entity.getHeaders().getAccessControlAllowCredentials()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("https://site1.com"); + assertThat(entity.getHeaders().getAccessControlAllowMethods().toArray()).isEqualTo(new HttpMethod[] {HttpMethod.GET}); + assertThat(entity.getHeaders().getAccessControlAllowCredentials()).isTrue(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ErrorsMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ErrorsMethodArgumentResolverTests.java index a933c19a36e..6b98a95dd22 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ErrorsMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ErrorsMethodArgumentResolverTests.java @@ -34,10 +34,8 @@ import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.method.ResolvableMethod; import org.springframework.web.reactive.BindingContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link ErrorsMethodArgumentResolver}. @@ -60,16 +58,16 @@ public class ErrorsMethodArgumentResolverTests { @Test public void supports() { MethodParameter parameter = this.testMethod.arg(Errors.class); - assertTrue(this.resolver.supportsParameter(parameter)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); parameter = this.testMethod.arg(BindingResult.class); - assertTrue(this.resolver.supportsParameter(parameter)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); parameter = this.testMethod.arg(ResolvableType.forClassWithGenerics(Mono.class, Errors.class)); - assertTrue(this.resolver.supportsParameter(parameter)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); parameter = this.testMethod.arg(String.class); - assertFalse(this.resolver.supportsParameter(parameter)); + assertThat(this.resolver.supportsParameter(parameter)).isFalse(); } @Test @@ -81,7 +79,7 @@ public class ErrorsMethodArgumentResolverTests { Object actual = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .block(Duration.ofMillis(5000)); - assertSame(bindingResult, actual); + assertThat(actual).isSameAs(bindingResult); } private BindingResult createBindingResult(Foo target, String name) { @@ -100,7 +98,7 @@ public class ErrorsMethodArgumentResolverTests { Object actual = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .block(Duration.ofMillis(5000)); - assertSame(bindingResult, actual); + assertThat(actual).isSameAs(bindingResult); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ExpressionValueMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ExpressionValueMethodArgumentResolverTests.java index 341ae7f794d..2fe03f8b4f4 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ExpressionValueMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ExpressionValueMethodArgumentResolverTests.java @@ -31,10 +31,8 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.util.ReflectionUtils; import org.springframework.web.reactive.BindingContext; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for {@link ExpressionValueMethodArgumentResolver}. @@ -69,12 +67,12 @@ public class ExpressionValueMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter(this.paramSystemProperty)); + assertThat(this.resolver.supportsParameter(this.paramSystemProperty)).isTrue(); } @Test public void doesNotSupport() { - assertFalse(this.resolver.supportsParameter(this.paramNotSupported)); + assertThat(this.resolver.supportsParameter(this.paramNotSupported)).isFalse(); assertThatIllegalStateException().isThrownBy(() -> this.resolver.supportsParameter(this.paramAlsoNotSupported)) .withMessageStartingWith("ExpressionValueMethodArgumentResolver does not support reactive type wrapper"); @@ -88,7 +86,7 @@ public class ExpressionValueMethodArgumentResolverTests { this.paramSystemProperty, new BindingContext(), this.exchange); Object value = mono.block(); - assertEquals(22, value); + assertThat(value).isEqualTo(22); } finally { System.clearProperty("systemProperty"); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java index 7a0cab866f8..658c22301b2 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java @@ -38,8 +38,6 @@ import org.springframework.web.reactive.config.WebFluxConfigurationSupport; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * @@ -80,9 +78,9 @@ public class GlobalCorsConfigIntegrationTests extends AbstractRequestMappingInte @Test public void actualRequestWithCorsEnabled() throws Exception { ResponseEntity entity = performGet("/cors", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("*", entity.getHeaders().getAccessControlAllowOrigin()); - assertEquals("cors", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("*"); + assertThat(entity.getBody()).isEqualTo("cors"); } @Test @@ -95,25 +93,25 @@ public class GlobalCorsConfigIntegrationTests extends AbstractRequestMappingInte @Test public void actualRequestWithoutCorsEnabled() throws Exception { ResponseEntity entity = performGet("/welcome", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertNull(entity.getHeaders().getAccessControlAllowOrigin()); - assertEquals("welcome", entity.getBody()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isNull(); + assertThat(entity.getBody()).isEqualTo("welcome"); } @Test public void actualRequestWithAmbiguousMapping() throws Exception { this.headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE); ResponseEntity entity = performGet("/ambiguous", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("*", entity.getHeaders().getAccessControlAllowOrigin()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("*"); } @Test public void preFlightRequestWithCorsEnabled() throws Exception { this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); ResponseEntity entity = performOptions("/cors", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("*", entity.getHeaders().getAccessControlAllowOrigin()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("*"); assertThat(entity.getHeaders().getAccessControlAllowMethods()) .containsExactly(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.POST); } @@ -139,8 +137,8 @@ public class GlobalCorsConfigIntegrationTests extends AbstractRequestMappingInte this.headers.set(HttpHeaders.ORIGIN, "https://foo"); this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); ResponseEntity entity = performOptions("/cors-restricted", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("https://foo", entity.getHeaders().getAccessControlAllowOrigin()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("https://foo"); assertThat(entity.getHeaders().getAccessControlAllowMethods()) .containsExactly(HttpMethod.GET, HttpMethod.POST); } @@ -149,11 +147,11 @@ public class GlobalCorsConfigIntegrationTests extends AbstractRequestMappingInte public void preFlightRequestWithAmbiguousMapping() throws Exception { this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); ResponseEntity entity = performOptions("/ambiguous", this.headers, String.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals("http://localhost:9000", entity.getHeaders().getAccessControlAllowOrigin()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(entity.getHeaders().getAccessControlAllowOrigin()).isEqualTo("http://localhost:9000"); assertThat(entity.getHeaders().getAccessControlAllowMethods()) .containsExactly(HttpMethod.GET); - assertEquals(true, entity.getHeaders().getAccessControlAllowCredentials()); + assertThat(entity.getHeaders().getAccessControlAllowCredentials()).isEqualTo(true); assertThat(entity.getHeaders().get(HttpHeaders.VARY)) .containsExactly(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/HttpEntityMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/HttpEntityMethodArgumentResolverTests.java index d520c85b9fb..1bc9d5db350 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/HttpEntityMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/HttpEntityMethodArgumentResolverTests.java @@ -47,12 +47,8 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.springframework.core.ResolvableType.forClassWithGenerics; import static org.springframework.http.MediaType.TEXT_PLAIN; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.post; @@ -95,13 +91,13 @@ public class HttpEntityMethodArgumentResolverTests { } private void testSupports(MethodParameter parameter) { - assertTrue(this.resolver.supportsParameter(parameter)); + assertThat(this.resolver.supportsParameter(parameter)).isTrue(); } @Test public void doesNotSupport() { - assertFalse(this.resolver.supportsParameter(this.testMethod.arg(Mono.class, String.class))); - assertFalse(this.resolver.supportsParameter(this.testMethod.arg(String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(Mono.class, String.class))).isFalse(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(String.class))).isFalse(); assertThatIllegalStateException().isThrownBy(() -> this.resolver.supportsParameter(this.testMethod.arg(Mono.class, httpEntityType(String.class)))) .withMessageStartingWith("HttpEntityMethodArgumentResolver does not support reactive type wrapper"); @@ -112,7 +108,7 @@ public class HttpEntityMethodArgumentResolverTests { ResolvableType type = httpEntityType(String.class); HttpEntity entity = resolveValueWithEmptyBody(type); - assertNull(entity.getBody()); + assertThat(entity.getBody()).isNull(); } @Test @@ -203,8 +199,8 @@ public class HttpEntityMethodArgumentResolverTests { HttpEntity> entity = resolveValueWithEmptyBody(type); entity.getBody().whenComplete((body, ex) -> { - assertNull(body); - assertNull(ex); + assertThat(body).isNull(); + assertThat(ex).isNull(); }); } @@ -214,8 +210,8 @@ public class HttpEntityMethodArgumentResolverTests { ResolvableType type = httpEntityType(String.class); HttpEntity httpEntity = resolveValue(exchange, type); - assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders()); - assertEquals("line1", httpEntity.getBody()); + assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders()); + assertThat(httpEntity.getBody()).isEqualTo("line1"); } @Test @@ -224,8 +220,8 @@ public class HttpEntityMethodArgumentResolverTests { ResolvableType type = httpEntityType(Mono.class, String.class); HttpEntity> httpEntity = resolveValue(exchange, type); - assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders()); - assertEquals("line1", httpEntity.getBody().block()); + assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders()); + assertThat(httpEntity.getBody().block()).isEqualTo("line1"); } @Test @@ -234,8 +230,8 @@ public class HttpEntityMethodArgumentResolverTests { ResolvableType type = httpEntityType(Single.class, String.class); HttpEntity> httpEntity = resolveValue(exchange, type); - assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders()); - assertEquals("line1", httpEntity.getBody().toBlocking().value()); + assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders()); + assertThat(httpEntity.getBody().toBlocking().value()).isEqualTo("line1"); } @Test @@ -244,8 +240,8 @@ public class HttpEntityMethodArgumentResolverTests { ResolvableType type = httpEntityType(io.reactivex.Single.class, String.class); HttpEntity> httpEntity = resolveValue(exchange, type); - assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders()); - assertEquals("line1", httpEntity.getBody().blockingGet()); + assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders()); + assertThat(httpEntity.getBody().blockingGet()).isEqualTo("line1"); } @Test @@ -254,8 +250,8 @@ public class HttpEntityMethodArgumentResolverTests { ResolvableType type = httpEntityType(Maybe.class, String.class); HttpEntity> httpEntity = resolveValue(exchange, type); - assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders()); - assertEquals("line1", httpEntity.getBody().blockingGet()); + assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders()); + assertThat(httpEntity.getBody().blockingGet()).isEqualTo("line1"); } @Test @@ -264,8 +260,8 @@ public class HttpEntityMethodArgumentResolverTests { ResolvableType type = httpEntityType(CompletableFuture.class, String.class); HttpEntity> httpEntity = resolveValue(exchange, type); - assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders()); - assertEquals("line1", httpEntity.getBody().get()); + assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders()); + assertThat(httpEntity.getBody().get()).isEqualTo("line1"); } @Test @@ -274,7 +270,7 @@ public class HttpEntityMethodArgumentResolverTests { ResolvableType type = httpEntityType(Flux.class, String.class); HttpEntity> httpEntity = resolveValue(exchange, type); - assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders()); + assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders()); StepVerifier.create(httpEntity.getBody()) .expectNext("line1") .expectNext("line2") @@ -289,10 +285,10 @@ public class HttpEntityMethodArgumentResolverTests { ResolvableType type = forClassWithGenerics(RequestEntity.class, String.class); RequestEntity requestEntity = resolveValue(exchange, type); - assertEquals(exchange.getRequest().getMethod(), requestEntity.getMethod()); - assertEquals(exchange.getRequest().getURI(), requestEntity.getUrl()); - assertEquals(exchange.getRequest().getHeaders(), requestEntity.getHeaders()); - assertEquals("line1", requestEntity.getBody()); + assertThat(requestEntity.getMethod()).isEqualTo(exchange.getRequest().getMethod()); + assertThat(requestEntity.getUrl()).isEqualTo(exchange.getRequest().getURI()); + assertThat(requestEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders()); + assertThat(requestEntity.getBody()).isEqualTo("line1"); } @@ -313,9 +309,8 @@ public class HttpEntityMethodArgumentResolverTests { Mono result = this.resolver.resolveArgument(param, new BindingContext(), exchange); Object value = result.block(Duration.ofSeconds(5)); - assertNotNull(value); - assertTrue("Unexpected return value type: " + value.getClass(), - param.getParameterType().isAssignableFrom(value.getClass())); + assertThat(value).isNotNull(); + assertThat(param.getParameterType().isAssignableFrom(value.getClass())).as("Unexpected return value type: " + value.getClass()).isTrue(); return (T) value; } @@ -327,7 +322,7 @@ public class HttpEntityMethodArgumentResolverTests { Mono result = this.resolver.resolveArgument(param, new BindingContext(), exchange); HttpEntity httpEntity = (HttpEntity) result.block(Duration.ofSeconds(5)); - assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders()); + assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders()); return (HttpEntity) httpEntity; } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/InitBinderBindingContextTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/InitBinderBindingContextTests.java index fda5b3844ce..dd4e91ff4e2 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/InitBinderBindingContextTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/InitBinderBindingContextTests.java @@ -37,11 +37,8 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.reactive.result.method.SyncHandlerMethodArgumentResolver; import org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; /** * Unit tests for {@link InitBinderBindingContext}. @@ -61,8 +58,8 @@ public class InitBinderBindingContextTests { BindingContext context = createBindingContext("initBinder", WebDataBinder.class); WebDataBinder dataBinder = context.createDataBinder(exchange, null, null); - assertNotNull(dataBinder.getDisallowedFields()); - assertEquals("id", dataBinder.getDisallowedFields()[0]); + assertThat(dataBinder.getDisallowedFields()).isNotNull(); + assertThat(dataBinder.getDisallowedFields()[0]).isEqualTo("id"); } @Test @@ -74,7 +71,7 @@ public class InitBinderBindingContextTests { BindingContext context = createBindingContext("initBinder", WebDataBinder.class); WebDataBinder dataBinder = context.createDataBinder(exchange, null, null); - assertSame(conversionService, dataBinder.getConversionService()); + assertThat(dataBinder.getConversionService()).isSameAs(conversionService); } @Test @@ -83,8 +80,8 @@ public class InitBinderBindingContextTests { BindingContext context = createBindingContext("initBinderWithAttributeName", WebDataBinder.class); WebDataBinder dataBinder = context.createDataBinder(exchange, null, "foo"); - assertNotNull(dataBinder.getDisallowedFields()); - assertEquals("id", dataBinder.getDisallowedFields()[0]); + assertThat(dataBinder.getDisallowedFields()).isNotNull(); + assertThat(dataBinder.getDisallowedFields()[0]).isEqualTo("id"); } @Test @@ -93,7 +90,7 @@ public class InitBinderBindingContextTests { BindingContext context = createBindingContext("initBinderWithAttributeName", WebDataBinder.class); WebDataBinder dataBinder = context.createDataBinder(exchange, null, "invalidName"); - assertNull(dataBinder.getDisallowedFields()); + assertThat(dataBinder.getDisallowedFields()).isNull(); } @Test @@ -102,7 +99,7 @@ public class InitBinderBindingContextTests { BindingContext context = createBindingContext("initBinderWithAttributeName", WebDataBinder.class); WebDataBinder dataBinder = context.createDataBinder(exchange, null, null); - assertNull(dataBinder.getDisallowedFields()); + assertThat(dataBinder.getDisallowedFields()).isNull(); } @Test @@ -123,8 +120,8 @@ public class InitBinderBindingContextTests { BindingContext context = createBindingContext("initBinderTypeConversion", WebDataBinder.class, int.class); WebDataBinder dataBinder = context.createDataBinder(exchange, null, "foo"); - assertNotNull(dataBinder.getDisallowedFields()); - assertEquals("requestParam-22", dataBinder.getDisallowedFields()[0]); + assertThat(dataBinder.getDisallowedFields()).isNotNull(); + assertThat(dataBinder.getDisallowedFields()[0]).isEqualTo("requestParam-22"); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/JacksonHintsIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/JacksonHintsIntegrationTests.java index 8a056dabfe0..314f9fcec9d 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/JacksonHintsIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/JacksonHintsIntegrationTests.java @@ -37,7 +37,7 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.config.EnableWebFlux; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze @@ -56,47 +56,47 @@ public class JacksonHintsIntegrationTests extends AbstractRequestMappingIntegrat @Test public void jsonViewResponse() throws Exception { String expected = "{\"withView1\":\"with\"}"; - assertEquals(expected, performGet("/response/raw", MediaType.APPLICATION_JSON, String.class).getBody()); + assertThat(performGet("/response/raw", MediaType.APPLICATION_JSON, String.class).getBody()).isEqualTo(expected); } @Test public void jsonViewWithMonoResponse() throws Exception { String expected = "{\"withView1\":\"with\"}"; - assertEquals(expected, performGet("/response/mono", MediaType.APPLICATION_JSON, String.class).getBody()); + assertThat(performGet("/response/mono", MediaType.APPLICATION_JSON, String.class).getBody()).isEqualTo(expected); } @Test // SPR-16098 public void jsonViewWithMonoResponseEntity() throws Exception { String expected = "{\"withView1\":\"with\"}"; - assertEquals(expected, performGet("/response/entity", MediaType.APPLICATION_JSON, String.class).getBody()); + assertThat(performGet("/response/entity", MediaType.APPLICATION_JSON, String.class).getBody()).isEqualTo(expected); } @Test public void jsonViewWithFluxResponse() throws Exception { String expected = "[{\"withView1\":\"with\"},{\"withView1\":\"with\"}]"; - assertEquals(expected, performGet("/response/flux", MediaType.APPLICATION_JSON, String.class).getBody()); + assertThat(performGet("/response/flux", MediaType.APPLICATION_JSON, String.class).getBody()).isEqualTo(expected); } @Test public void jsonViewWithRequest() throws Exception { String expected = "{\"withView1\":\"with\",\"withView2\":null,\"withoutView\":null}"; - assertEquals(expected, performPost("/request/raw", MediaType.APPLICATION_JSON, - new JacksonViewBean("with", "with", "without"), MediaType.APPLICATION_JSON, String.class).getBody()); + assertThat(performPost("/request/raw", MediaType.APPLICATION_JSON, + new JacksonViewBean("with", "with", "without"), MediaType.APPLICATION_JSON, String.class).getBody()).isEqualTo(expected); } @Test public void jsonViewWithMonoRequest() throws Exception { String expected = "{\"withView1\":\"with\",\"withView2\":null,\"withoutView\":null}"; - assertEquals(expected, performPost("/request/mono", MediaType.APPLICATION_JSON, - new JacksonViewBean("with", "with", "without"), MediaType.APPLICATION_JSON, String.class).getBody()); + assertThat(performPost("/request/mono", MediaType.APPLICATION_JSON, + new JacksonViewBean("with", "with", "without"), MediaType.APPLICATION_JSON, String.class).getBody()).isEqualTo(expected); } @Test // SPR-16098 public void jsonViewWithEntityMonoRequest() throws Exception { String expected = "{\"withView1\":\"with\",\"withView2\":null,\"withoutView\":null}"; - assertEquals(expected, performPost("/request/entity/mono", MediaType.APPLICATION_JSON, + assertThat(performPost("/request/entity/mono", MediaType.APPLICATION_JSON, new JacksonViewBean("with", "with", "without"), - MediaType.APPLICATION_JSON, String.class).getBody()); + MediaType.APPLICATION_JSON, String.class).getBody()).isEqualTo(expected); } @Test // SPR-16098 @@ -104,10 +104,10 @@ public class JacksonHintsIntegrationTests extends AbstractRequestMappingIntegrat String expected = "[" + "{\"withView1\":\"with\",\"withView2\":null,\"withoutView\":null}," + "{\"withView1\":\"with\",\"withView2\":null,\"withoutView\":null}]"; - assertEquals(expected, performPost("/request/entity/flux", MediaType.APPLICATION_JSON, + assertThat(performPost("/request/entity/flux", MediaType.APPLICATION_JSON, Arrays.asList(new JacksonViewBean("with", "with", "without"), new JacksonViewBean("with", "with", "without")), - MediaType.APPLICATION_JSON, String.class).getBody()); + MediaType.APPLICATION_JSON, String.class).getBody()).isEqualTo(expected); } @Test @@ -118,8 +118,8 @@ public class JacksonHintsIntegrationTests extends AbstractRequestMappingIntegrat List beans = Arrays.asList( new JacksonViewBean("with", "with", "without"), new JacksonViewBean("with", "with", "without")); - assertEquals(expected, performPost("/request/flux", MediaType.APPLICATION_JSON, beans, - MediaType.APPLICATION_JSON, String.class).getBody()); + assertThat(performPost("/request/flux", MediaType.APPLICATION_JSON, beans, + MediaType.APPLICATION_JSON, String.class).getBody()).isEqualTo(expected); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMapMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMapMethodArgumentResolverTests.java index 23f42666675..9886efad896 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMapMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMapMethodArgumentResolverTests.java @@ -35,10 +35,7 @@ import org.springframework.web.method.ResolvableMethod; import org.springframework.web.reactive.BindingContext; import org.springframework.web.reactive.HandlerMapping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.method.MvcAnnotationPredicates.matrixAttribute; /** @@ -65,19 +62,19 @@ public class MatrixVariablesMapMethodArgumentResolverTests { @Test public void supportsParameter() { - assertFalse(this.resolver.supportsParameter(this.testMethod.arg(String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(String.class))).isFalse(); - assertTrue(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().noName()) - .arg(Map.class, String.class, String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().noName()) + .arg(Map.class, String.class, String.class))).isTrue(); - assertTrue(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().noPathVar()) - .arg(MultiValueMap.class, String.class, String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().noPathVar()) + .arg(MultiValueMap.class, String.class, String.class))).isTrue(); - assertTrue(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().pathVar("cars")) - .arg(MultiValueMap.class, String.class, String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().pathVar("cars")) + .arg(MultiValueMap.class, String.class, String.class))).isTrue(); - assertFalse(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().name("name")) - .arg(Map.class, String.class, String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().name("name")) + .arg(Map.class, String.class, String.class))).isFalse(); } @Test @@ -96,8 +93,8 @@ public class MatrixVariablesMapMethodArgumentResolverTests { (Map) this.resolver.resolveArgument( param, new BindingContext(), this.exchange).block(Duration.ZERO); - assertNotNull(map); - assertEquals("red", map.get("colors")); + assertThat(map).isNotNull(); + assertThat(map.get("colors")).isEqualTo("red"); param = this.testMethod .annot(matrixAttribute().noPathVar()) @@ -108,7 +105,7 @@ public class MatrixVariablesMapMethodArgumentResolverTests { (MultiValueMap) this.resolver.resolveArgument( param, new BindingContext(), this.exchange).block(Duration.ZERO); - assertEquals(Arrays.asList("red", "green", "blue"), multivalueMap.get("colors")); + assertThat(multivalueMap.get("colors")).isEqualTo(Arrays.asList("red", "green", "blue")); } @Test @@ -125,11 +122,11 @@ public class MatrixVariablesMapMethodArgumentResolverTests { .arg(MultiValueMap.class, String.class, String.class); @SuppressWarnings("unchecked") - Map mapForPathVar = (Map) + Map mapForPathVar = (Map) this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO); - assertNotNull(mapForPathVar); - assertEquals(Arrays.asList("red", "purple"), mapForPathVar.get("colors")); + assertThat(mapForPathVar).isNotNull(); + assertThat(mapForPathVar.get("colors")).isEqualTo(Arrays.asList("red", "purple")); param = this.testMethod.annot(matrixAttribute().noName()).arg(Map.class, String.class, String.class); @@ -137,8 +134,8 @@ public class MatrixVariablesMapMethodArgumentResolverTests { Map mapAll = (Map) this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO); - assertNotNull(mapAll); - assertEquals("red", mapAll.get("colors")); + assertThat(mapAll).isNotNull(); + assertThat(mapAll.get("colors")).isEqualTo("red"); } @Test @@ -151,7 +148,7 @@ public class MatrixVariablesMapMethodArgumentResolverTests { Map map = (Map) this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO); - assertEquals(Collections.emptyMap(), map); + assertThat(map).isEqualTo(Collections.emptyMap()); } @Test @@ -167,11 +164,10 @@ public class MatrixVariablesMapMethodArgumentResolverTests { Map map = (Map) this.resolver.resolveArgument( param, new BindingContext(), this.exchange).block(Duration.ZERO); - assertEquals(Collections.emptyMap(), map); + assertThat(map).isEqualTo(Collections.emptyMap()); } - @SuppressWarnings("unchecked") private MultiValueMap getMatrixVariables(String pathVarName) { Map> matrixVariables = this.exchange.getAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMethodArgumentResolverTests.java index 391f0c98578..3c118f0589e 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MatrixVariablesMethodArgumentResolverTests.java @@ -37,10 +37,8 @@ import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.server.ServerErrorException; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.springframework.web.method.MvcAnnotationPredicates.matrixAttribute; /** @@ -67,13 +65,13 @@ public class MatrixVariablesMethodArgumentResolverTests { @Test public void supportsParameter() { - assertFalse(this.resolver.supportsParameter(this.testMethod.arg(String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(String.class))).isFalse(); - assertTrue(this.resolver.supportsParameter(this.testMethod - .annot(matrixAttribute().noName()).arg(List.class, String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod + .annot(matrixAttribute().noName()).arg(List.class, String.class))).isTrue(); - assertTrue(this.resolver.supportsParameter(this.testMethod - .annot(matrixAttribute().name("year")).arg(int.class))); + assertThat(this.resolver.supportsParameter(this.testMethod + .annot(matrixAttribute().name("year")).arg(int.class))).isTrue(); } @Test @@ -84,8 +82,7 @@ public class MatrixVariablesMethodArgumentResolverTests { params.add("colors", "blue"); MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class); - assertEquals(Arrays.asList("red", "green", "blue"), - this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO)); + assertThat(this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO)).isEqualTo(Arrays.asList("red", "green", "blue")); } @Test @@ -95,14 +92,14 @@ public class MatrixVariablesMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(matrixAttribute().name("year")).arg(int.class); Object actual = this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO); - assertEquals(2006, actual); + assertThat(actual).isEqualTo(2006); } @Test public void resolveArgumentDefaultValue() throws Exception { MethodParameter param = this.testMethod.annot(matrixAttribute().name("year")).arg(int.class); Object actual = this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO); - assertEquals(2013, actual); + assertThat(actual).isEqualTo(2013); } @Test @@ -129,10 +126,9 @@ public class MatrixVariablesMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(matrixAttribute().name("year")).arg(int.class); Object actual = this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO); - assertEquals(2013, actual); + assertThat(actual).isEqualTo(2013); } - @SuppressWarnings("unchecked") private MultiValueMap getVariablesFor(String pathVarName) { Map> matrixVariables = this.exchange.getAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageReaderArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageReaderArgumentResolverTests.java index 5cbf46ee71c..405a566d60a 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageReaderArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageReaderArgumentResolverTests.java @@ -59,10 +59,7 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; import org.springframework.web.server.UnsupportedMediaTypeStatusException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.ResolvableType.forClassWithGenerics; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.post; @@ -122,7 +119,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(type); Mono mono = resolveValue(param, body); - assertEquals(new TestBean("FOOFOO", "BARBAR"), mono.block()); + assertThat(mono.block()).isEqualTo(new TestBean("FOOFOO", "BARBAR")); } @Test @@ -132,8 +129,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(type); Flux flux = resolveValue(param, body); - assertEquals(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2")), - flux.collectList().block()); + assertThat(flux.collectList().block()).isEqualTo(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2"))); } @Test @@ -143,7 +139,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(type); Single single = resolveValue(param, body); - assertEquals(new TestBean("f1", "b1"), single.toBlocking().value()); + assertThat(single.toBlocking().value()).isEqualTo(new TestBean("f1", "b1")); } @Test @@ -153,7 +149,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(type); io.reactivex.Single single = resolveValue(param, body); - assertEquals(new TestBean("f1", "b1"), single.blockingGet()); + assertThat(single.blockingGet()).isEqualTo(new TestBean("f1", "b1")); } @Test @@ -163,7 +159,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(type); Maybe maybe = resolveValue(param, body); - assertEquals(new TestBean("f1", "b1"), maybe.blockingGet()); + assertThat(maybe.blockingGet()).isEqualTo(new TestBean("f1", "b1")); } @Test @@ -173,8 +169,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(type); Observable observable = resolveValue(param, body); - assertEquals(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2")), - observable.toList().toBlocking().first()); + assertThat(observable.toList().toBlocking().first()).isEqualTo(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2"))); } @Test @@ -184,8 +179,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(type); io.reactivex.Observable observable = resolveValue(param, body); - assertEquals(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2")), - observable.toList().blockingGet()); + assertThat(observable.toList().blockingGet()).isEqualTo(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2"))); } @Test @@ -195,8 +189,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(type); Flowable flowable = resolveValue(param, body); - assertEquals(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2")), - flowable.toList().blockingGet()); + assertThat(flowable.toList().blockingGet()).isEqualTo(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2"))); } @Test @@ -206,7 +199,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(type); CompletableFuture future = resolveValue(param, body); - assertEquals(new TestBean("f1", "b1"), future.get()); + assertThat(future.get()).isEqualTo(new TestBean("f1", "b1")); } @Test @@ -215,7 +208,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(TestBean.class); TestBean value = resolveValue(param, body); - assertEquals(new TestBean("f1", "b1"), value); + assertThat(value).isEqualTo(new TestBean("f1", "b1")); } @Test @@ -228,7 +221,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(type); Map actual = resolveValue(param, body); - assertEquals(map, actual); + assertThat(actual).isEqualTo(map); } @Test @@ -238,7 +231,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(type); List list = resolveValue(param, body); - assertEquals(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2")), list); + assertThat(list).isEqualTo(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2"))); } @Test @@ -249,7 +242,7 @@ public class MessageReaderArgumentResolverTests { Mono mono = resolveValue(param, body); List list = (List) mono.block(Duration.ofSeconds(5)); - assertEquals(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2")), list); + assertThat(list).isEqualTo(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2"))); } @Test @@ -258,11 +251,10 @@ public class MessageReaderArgumentResolverTests { MethodParameter param = this.testMethod.arg(TestBean[].class); TestBean[] value = resolveValue(param, body); - assertArrayEquals(new TestBean[] {new TestBean("f1", "b1"), new TestBean("f2", "b2")}, value); + assertThat(value).isEqualTo(new TestBean[] {new TestBean("f1", "b1"), new TestBean("f2", "b2")}); } @Test - @SuppressWarnings("unchecked") public void validateMonoTestBean() throws Exception { String body = "{\"bar\":\"b1\"}"; ResolvableType type = forClassWithGenerics(Mono.class, TestBean.class); @@ -273,7 +265,6 @@ public class MessageReaderArgumentResolverTests { } @Test - @SuppressWarnings("unchecked") public void validateFluxTestBean() throws Exception { String body = "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\"}]"; ResolvableType type = forClassWithGenerics(Flux.class, TestBean.class); @@ -293,7 +284,7 @@ public class MessageReaderArgumentResolverTests { MethodParameter methodParam = handlerMethod.getMethodParameters()[0]; SimpleBean simpleBean = resolveValue(methodParam, "{\"name\" : \"Jad\"}"); - assertEquals("Jad", simpleBean.getName()); + assertThat(simpleBean.getName()).isEqualTo("Jad"); } @@ -304,9 +295,8 @@ public class MessageReaderArgumentResolverTests { Mono result = this.resolver.readBody(param, true, this.bindingContext, exchange); Object value = result.block(Duration.ofSeconds(5)); - assertNotNull(value); - assertTrue("Unexpected return value type: " + value, - param.getParameterType().isAssignableFrom(value.getClass())); + assertThat(value).isNotNull(); + assertThat(param.getParameterType().isAssignableFrom(value.getClass())).as("Unexpected return value type: " + value).isTrue(); return (T) value; } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageWriterResultHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageWriterResultHandlerTests.java index e240e86e0b3..e9264284327 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageWriterResultHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageWriterResultHandlerTests.java @@ -53,8 +53,7 @@ import org.springframework.util.ObjectUtils; import org.springframework.web.reactive.accept.RequestedContentTypeResolver; import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.io.buffer.support.DataBufferTestUtils.dumpString; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.web.method.ResolvableMethod.on; @@ -96,7 +95,7 @@ public class MessageWriterResultHandlerTests { MethodParameter type = on(TestController.class).resolveReturnType(Resource.class); this.resultHandler.writeBody(body, type, this.exchange).block(Duration.ofSeconds(5)); - assertEquals("image/png", this.exchange.getResponse().getHeaders().getFirst("Content-Type")); + assertThat(this.exchange.getResponse().getHeaders().getFirst("Content-Type")).isEqualTo("image/png"); } @Test // SPR-13631 @@ -108,7 +107,7 @@ public class MessageWriterResultHandlerTests { MethodParameter type = on(TestController.class).resolveReturnType(String.class); this.resultHandler.writeBody(body, type, this.exchange).block(Duration.ofSeconds(5)); - assertEquals(MediaType.parseMediaType("application/json;charset=UTF-8"), this.exchange.getResponse().getHeaders().getContentType()); + assertThat(this.exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.parseMediaType("application/json;charset=UTF-8")); } @Test @@ -132,7 +131,7 @@ public class MessageWriterResultHandlerTests { private void testVoid(Object body, MethodParameter returnType) { this.resultHandler.writeBody(body, returnType, this.exchange).block(Duration.ofSeconds(5)); - assertNull(this.exchange.getResponse().getHeaders().get("Content-Type")); + assertThat(this.exchange.getResponse().getHeaders().get("Content-Type")).isNull(); StepVerifier.create(this.exchange.getResponse().getBody()) .expectErrorMatches(ex -> ex.getMessage().startsWith("No content was written")).verify(); } @@ -155,7 +154,7 @@ public class MessageWriterResultHandlerTests { List body = Arrays.asList(new Foo("foo"), new Bar("bar")); this.resultHandler.writeBody(body, returnType, this.exchange).block(Duration.ofSeconds(5)); - assertEquals(APPLICATION_JSON, this.exchange.getResponse().getHeaders().getContentType()); + assertThat(this.exchange.getResponse().getHeaders().getContentType()).isEqualTo(APPLICATION_JSON); assertResponseBody("[{\"type\":\"foo\",\"parentProperty\":\"foo\"}," + "{\"type\":\"bar\",\"parentProperty\":\"bar\"}]"); } @@ -166,7 +165,7 @@ public class MessageWriterResultHandlerTests { MethodParameter type = on(TestController.class).resolveReturnType(Identifiable.class); this.resultHandler.writeBody(body, type, this.exchange).block(Duration.ofSeconds(5)); - assertEquals(APPLICATION_JSON, this.exchange.getResponse().getHeaders().getContentType()); + assertThat(this.exchange.getResponse().getHeaders().getContentType()).isEqualTo(APPLICATION_JSON); assertResponseBody("{\"id\":123,\"name\":\"foo\"}"); } @@ -178,14 +177,14 @@ public class MessageWriterResultHandlerTests { List body = Arrays.asList(new SimpleBean(123L, "foo"), new SimpleBean(456L, "bar")); this.resultHandler.writeBody(body, returnType, this.exchange).block(Duration.ofSeconds(5)); - assertEquals(APPLICATION_JSON, this.exchange.getResponse().getHeaders().getContentType()); + assertThat(this.exchange.getResponse().getHeaders().getContentType()).isEqualTo(APPLICATION_JSON); assertResponseBody("[{\"id\":123,\"name\":\"foo\"},{\"id\":456,\"name\":\"bar\"}]"); } private void assertResponseBody(String responseBody) { StepVerifier.create(this.exchange.getResponse().getBody()) - .consumeNextWith(buf -> assertEquals(responseBody, dumpString(buf, StandardCharsets.UTF_8))) + .consumeNextWith(buf -> assertThat(dumpString(buf, StandardCharsets.UTF_8)).isEqualTo(responseBody)) .expectComplete() .verify(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelAttributeMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelAttributeMethodArgumentResolverTests.java index 564a317f2af..323cdb97c22 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelAttributeMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelAttributeMethodArgumentResolverTests.java @@ -43,11 +43,7 @@ import org.springframework.web.method.ResolvableMethod; import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ModelAttributeMethodArgumentResolver}. @@ -78,16 +74,16 @@ public class ModelAttributeMethodArgumentResolverTests { new ModelAttributeMethodArgumentResolver(ReactiveAdapterRegistry.getSharedInstance(), false); MethodParameter param = this.testMethod.annotPresent(ModelAttribute.class).arg(Foo.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(ModelAttribute.class).arg(Mono.class, Foo.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotNotPresent(ModelAttribute.class).arg(Foo.class); - assertFalse(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isFalse(); param = this.testMethod.annotNotPresent(ModelAttribute.class).arg(Mono.class, Foo.class); - assertFalse(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isFalse(); } @Test @@ -96,22 +92,22 @@ public class ModelAttributeMethodArgumentResolverTests { new ModelAttributeMethodArgumentResolver(ReactiveAdapterRegistry.getSharedInstance(), true); MethodParameter param = this.testMethod.annotNotPresent(ModelAttribute.class).arg(Foo.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotNotPresent(ModelAttribute.class).arg(Mono.class, Foo.class); - assertTrue(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotNotPresent(ModelAttribute.class).arg(String.class); - assertFalse(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isFalse(); param = this.testMethod.annotNotPresent(ModelAttribute.class).arg(Mono.class, String.class); - assertFalse(resolver.supportsParameter(param)); + assertThat(resolver.supportsParameter(param)).isFalse(); } @Test public void createAndBind() throws Exception { testBindFoo("foo", this.testMethod.annotPresent(ModelAttribute.class).arg(Foo.class), value -> { - assertEquals(Foo.class, value.getClass()); + assertThat(value.getClass()).isEqualTo(Foo.class); return (Foo) value; }); } @@ -122,9 +118,10 @@ public class ModelAttributeMethodArgumentResolverTests { .annotNotPresent(ModelAttribute.class).arg(Mono.class, Foo.class); testBindFoo("fooMono", parameter, mono -> { - assertTrue(mono.getClass().getName(), mono instanceof Mono); + boolean condition = mono instanceof Mono; + assertThat(condition).as(mono.getClass().getName()).isTrue(); Object value = ((Mono) mono).block(Duration.ofSeconds(5)); - assertEquals(Foo.class, value.getClass()); + assertThat(value.getClass()).isEqualTo(Foo.class); return (Foo) value; }); } @@ -135,9 +132,10 @@ public class ModelAttributeMethodArgumentResolverTests { .annotPresent(ModelAttribute.class).arg(Single.class, Foo.class); testBindFoo("fooSingle", parameter, single -> { - assertTrue(single.getClass().getName(), single instanceof Single); + boolean condition = single instanceof Single; + assertThat(condition).as(single.getClass().getName()).isTrue(); Object value = ((Single) single).toBlocking().value(); - assertEquals(Foo.class, value.getClass()); + assertThat(value.getClass()).isEqualTo(Foo.class); return (Foo) value; }); } @@ -150,11 +148,11 @@ public class ModelAttributeMethodArgumentResolverTests { MethodParameter parameter = this.testMethod.annotNotPresent(ModelAttribute.class).arg(Foo.class); testBindFoo("foo", parameter, value -> { - assertEquals(Foo.class, value.getClass()); + assertThat(value.getClass()).isEqualTo(Foo.class); return (Foo) value; }); - assertSame(foo, this.bindContext.getModel().asMap().get("foo")); + assertThat(this.bindContext.getModel().asMap().get("foo")).isSameAs(foo); } @Test @@ -165,11 +163,11 @@ public class ModelAttributeMethodArgumentResolverTests { MethodParameter parameter = this.testMethod.annotNotPresent(ModelAttribute.class).arg(Foo.class); testBindFoo("foo", parameter, value -> { - assertEquals(Foo.class, value.getClass()); + assertThat(value.getClass()).isEqualTo(Foo.class); return (Foo) value; }); - assertSame(foo, this.bindContext.getModel().asMap().get("foo")); + assertThat(this.bindContext.getModel().asMap().get("foo")).isSameAs(foo); } @Test @@ -180,11 +178,11 @@ public class ModelAttributeMethodArgumentResolverTests { MethodParameter parameter = this.testMethod.annotNotPresent(ModelAttribute.class).arg(Foo.class); testBindFoo("foo", parameter, value -> { - assertEquals(Foo.class, value.getClass()); + assertThat(value.getClass()).isEqualTo(Foo.class); return (Foo) value; }); - assertSame(foo, this.bindContext.getModel().asMap().get("foo")); + assertThat(this.bindContext.getModel().asMap().get("foo")).isSameAs(foo); } @Test @@ -198,9 +196,10 @@ public class ModelAttributeMethodArgumentResolverTests { .annotNotPresent(ModelAttribute.class).arg(Mono.class, Foo.class); testBindFoo(modelKey, parameter, mono -> { - assertTrue(mono.getClass().getName(), mono instanceof Mono); + boolean condition = mono instanceof Mono; + assertThat(condition).as(mono.getClass().getName()).isTrue(); Object value = ((Mono) mono).block(Duration.ofSeconds(5)); - assertEquals(Foo.class, value.getClass()); + assertThat(value.getClass()).isEqualTo(Foo.class); return (Foo) value; }); } @@ -213,16 +212,17 @@ public class ModelAttributeMethodArgumentResolverTests { .block(Duration.ZERO); Foo foo = valueExtractor.apply(value); - assertEquals("Robert", foo.getName()); - assertEquals(25, foo.getAge()); + assertThat(foo.getName()).isEqualTo("Robert"); + assertThat(foo.getAge()).isEqualTo(25); String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + modelKey; Map map = bindContext.getModel().asMap(); - assertEquals(map.toString(), 2, map.size()); - assertSame(foo, map.get(modelKey)); - assertNotNull(map.get(bindingResultKey)); - assertTrue(map.get(bindingResultKey) instanceof BindingResult); + assertThat(map.size()).as(map.toString()).isEqualTo(2); + assertThat(map.get(modelKey)).isSameAs(foo); + assertThat(map.get(bindingResultKey)).isNotNull(); + boolean condition = map.get(bindingResultKey) instanceof BindingResult; + assertThat(condition).isTrue(); } @Test @@ -232,7 +232,6 @@ public class ModelAttributeMethodArgumentResolverTests { } @Test - @SuppressWarnings("unchecked") public void validationErrorToMono() throws Exception { MethodParameter parameter = this.testMethod .annotNotPresent(ModelAttribute.class).arg(Mono.class, Foo.class); @@ -240,8 +239,9 @@ public class ModelAttributeMethodArgumentResolverTests { testValidationError(parameter, resolvedArgumentMono -> { Object value = resolvedArgumentMono.block(Duration.ofSeconds(5)); - assertNotNull(value); - assertTrue(value instanceof Mono); + assertThat(value).isNotNull(); + boolean condition = value instanceof Mono; + assertThat(condition).isTrue(); return (Mono) value; }); } @@ -254,8 +254,9 @@ public class ModelAttributeMethodArgumentResolverTests { testValidationError(parameter, resolvedArgumentMono -> { Object value = resolvedArgumentMono.block(Duration.ofSeconds(5)); - assertNotNull(value); - assertTrue(value instanceof Single); + assertThat(value).isNotNull(); + boolean condition = value instanceof Single; + assertThat(condition).isTrue(); return Mono.from(RxReactiveStreams.toPublisher((Single) value)); }); } @@ -269,10 +270,11 @@ public class ModelAttributeMethodArgumentResolverTests { StepVerifier.create(mono) .consumeErrorWith(ex -> { - assertTrue(ex instanceof WebExchangeBindException); + boolean condition = ex instanceof WebExchangeBindException; + assertThat(condition).isTrue(); WebExchangeBindException bindException = (WebExchangeBindException) ex; - assertEquals(1, bindException.getErrorCount()); - assertTrue(bindException.hasFieldErrors("age")); + assertThat(bindException.getErrorCount()).isEqualTo(1); + assertThat(bindException.hasFieldErrors("age")).isTrue(); }) .verify(); } @@ -288,18 +290,19 @@ public class ModelAttributeMethodArgumentResolverTests { .block(Duration.ZERO); Bar bar = (Bar) value; - assertEquals("Robert", bar.getName()); - assertEquals(25, bar.getAge()); - assertEquals(1, bar.getCount()); + assertThat(bar.getName()).isEqualTo("Robert"); + assertThat(bar.getAge()).isEqualTo(25); + assertThat(bar.getCount()).isEqualTo(1); String key = "bar"; String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + key; Map map = bindContext.getModel().asMap(); - assertEquals(map.toString(), 2, map.size()); - assertSame(bar, map.get(key)); - assertNotNull(map.get(bindingResultKey)); - assertTrue(map.get(bindingResultKey) instanceof BindingResult); + assertThat(map.size()).as(map.toString()).isEqualTo(2); + assertThat(map.get(key)).isSameAs(bar); + assertThat(map.get(bindingResultKey)).isNotNull(); + boolean condition = map.get(bindingResultKey) instanceof BindingResult; + assertThat(condition).isTrue(); } // TODO: SPR-15871, SPR-15542 diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelInitializerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelInitializerTests.java index 85ab2d28f84..65caa3d6722 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelInitializerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelInitializerTests.java @@ -53,9 +53,8 @@ import org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebSession; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; /** @@ -97,7 +96,7 @@ public class ModelInitializerTests { this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000)); WebExchangeDataBinder binder = context.createDataBinder(this.exchange, "name"); - assertEquals(Collections.singletonList(validator), binder.getValidators()); + assertThat(binder.getValidators()).isEqualTo(Collections.singletonList(validator)); } @SuppressWarnings("unchecked") @@ -111,22 +110,22 @@ public class ModelInitializerTests { this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000)); Map model = context.getModel().asMap(); - assertEquals(5, model.size()); + assertThat(model.size()).isEqualTo(5); Object value = model.get("bean"); - assertEquals("Bean", ((TestBean) value).getName()); + assertThat(((TestBean) value).getName()).isEqualTo("Bean"); value = model.get("monoBean"); - assertEquals("Mono Bean", ((Mono) value).block(Duration.ofMillis(5000)).getName()); + assertThat(((Mono) value).block(Duration.ofMillis(5000)).getName()).isEqualTo("Mono Bean"); value = model.get("singleBean"); - assertEquals("Single Bean", ((Single) value).toBlocking().value().getName()); + assertThat(((Single) value).toBlocking().value().getName()).isEqualTo("Single Bean"); value = model.get("voidMethodBean"); - assertEquals("Void Method Bean", ((TestBean) value).getName()); + assertThat(((TestBean) value).getName()).isEqualTo("Void Method Bean"); value = model.get("voidMonoMethodBean"); - assertEquals("Void Mono Method Bean", ((TestBean) value).getName()); + assertThat(((TestBean) value).getName()).isEqualTo("Void Mono Method Bean"); } @Test @@ -139,18 +138,18 @@ public class ModelInitializerTests { this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000)); WebSession session = this.exchange.getSession().block(Duration.ZERO); - assertNotNull(session); - assertEquals(0, session.getAttributes().size()); + assertThat(session).isNotNull(); + assertThat(session.getAttributes().size()).isEqualTo(0); context.saveModel(); - assertEquals(1, session.getAttributes().size()); - assertEquals("Bean", ((TestBean) session.getRequiredAttribute("bean")).getName()); + assertThat(session.getAttributes().size()).isEqualTo(1); + assertThat(((TestBean) session.getRequiredAttribute("bean")).getName()).isEqualTo("Bean"); } @Test public void retrieveModelAttributeFromSession() { WebSession session = this.exchange.getSession().block(Duration.ZERO); - assertNotNull(session); + assertThat(session).isNotNull(); TestBean testBean = new TestBean("Session Bean"); session.getAttributes().put("bean", testBean); @@ -163,8 +162,8 @@ public class ModelInitializerTests { this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000)); context.saveModel(); - assertEquals(1, session.getAttributes().size()); - assertEquals("Session Bean", ((TestBean) session.getRequiredAttribute("bean")).getName()); + assertThat(session.getAttributes().size()).isEqualTo(1); + assertThat(((TestBean) session.getRequiredAttribute("bean")).getName()).isEqualTo("Session Bean"); } @Test @@ -182,7 +181,7 @@ public class ModelInitializerTests { @Test public void clearModelAttributeFromSession() { WebSession session = this.exchange.getSession().block(Duration.ZERO); - assertNotNull(session); + assertThat(session).isNotNull(); TestBean testBean = new TestBean("Session Bean"); session.getAttributes().put("bean", testBean); @@ -197,7 +196,7 @@ public class ModelInitializerTests { context.getSessionStatus().setComplete(); context.saveModel(); - assertEquals(0, session.getAttributes().size()); + assertThat(session.getAttributes().size()).isEqualTo(0); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelMethodArgumentResolverTests.java index 351da01bb14..a1c8e6ceac4 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ModelMethodArgumentResolverTests.java @@ -31,9 +31,7 @@ import org.springframework.web.method.ResolvableMethod; import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; /** @@ -53,14 +51,14 @@ public class ModelMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter(this.resolvable.arg(Model.class))); - assertTrue(this.resolver.supportsParameter(this.resolvable.arg(ModelMap.class))); - assertTrue(this.resolver.supportsParameter( - this.resolvable.annotNotPresent().arg(Map.class, String.class, Object.class))); + assertThat(this.resolver.supportsParameter(this.resolvable.arg(Model.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.resolvable.arg(ModelMap.class))).isTrue(); + assertThat(this.resolver.supportsParameter( + this.resolvable.annotNotPresent().arg(Map.class, String.class, Object.class))).isTrue(); - assertFalse(this.resolver.supportsParameter(this.resolvable.arg(Object.class))); - assertFalse(this.resolver.supportsParameter( - this.resolvable.annotPresent(RequestBody.class).arg(Map.class, String.class, Object.class))); + assertThat(this.resolver.supportsParameter(this.resolvable.arg(Object.class))).isFalse(); + assertThat(this.resolver.supportsParameter( + this.resolvable.annotPresent(RequestBody.class).arg(Map.class, String.class, Object.class))).isFalse(); } @Test @@ -73,7 +71,7 @@ public class ModelMethodArgumentResolverTests { private void testResolveArgument(MethodParameter parameter) { BindingContext context = new BindingContext(); Object result = this.resolver.resolveArgument(parameter, context, this.exchange).block(Duration.ZERO); - assertSame(context.getModel(), result); + assertThat(result).isSameAs(context.getModel()); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartIntegrationTests.java index 4cfb50b1503..7a6b102b3e8 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartIntegrationTests.java @@ -52,7 +52,7 @@ import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class MultipartIntegrationTests extends AbstractHttpHandlerIntegrationTests { @@ -85,7 +85,7 @@ public class MultipartIntegrationTests extends AbstractHttpHandlerIntegrationTes StepVerifier .create(result) - .consumeNextWith(response -> assertEquals(HttpStatus.OK, response.statusCode())) + .consumeNextWith(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK)) .verifyComplete(); } @@ -99,8 +99,7 @@ public class MultipartIntegrationTests extends AbstractHttpHandlerIntegrationTes .bodyToMono(String.class); StepVerifier.create(result) - .consumeNextWith(body -> assertEquals( - "Map[[fieldPart],[fileParts:foo.txt,fileParts:logo.png],[jsonPart]]", body)) + .consumeNextWith(body -> assertThat(body).isEqualTo("Map[[fieldPart],[fileParts:foo.txt,fileParts:logo.png],[jsonPart]]")) .verifyComplete(); } @@ -114,8 +113,7 @@ public class MultipartIntegrationTests extends AbstractHttpHandlerIntegrationTes .bodyToMono(String.class); StepVerifier.create(result) - .consumeNextWith(body -> assertEquals( - "[fieldPart,fileParts:foo.txt,fileParts:logo.png,jsonPart]", body)) + .consumeNextWith(body -> assertThat(body).isEqualTo("[fieldPart,fileParts:foo.txt,fileParts:logo.png,jsonPart]")) .verifyComplete(); } @@ -129,8 +127,7 @@ public class MultipartIntegrationTests extends AbstractHttpHandlerIntegrationTes .bodyToMono(String.class); StepVerifier.create(result) - .consumeNextWith(body -> assertEquals( - "[fileParts:foo.txt,fileParts:logo.png]", body)) + .consumeNextWith(body -> assertThat(body).isEqualTo("[fileParts:foo.txt,fileParts:logo.png]")) .verifyComplete(); } @@ -144,8 +141,7 @@ public class MultipartIntegrationTests extends AbstractHttpHandlerIntegrationTes .bodyToMono(String.class); StepVerifier.create(result) - .consumeNextWith(body -> assertEquals( - "[fileParts:foo.txt]", body)) + .consumeNextWith(body -> assertThat(body).isEqualTo("[fileParts:foo.txt]")) .verifyComplete(); } @@ -159,8 +155,7 @@ public class MultipartIntegrationTests extends AbstractHttpHandlerIntegrationTes .bodyToMono(String.class); StepVerifier.create(result) - .consumeNextWith(body -> assertEquals( - "FormBean[fieldValue,[fileParts:foo.txt,fileParts:logo.png]]", body)) + .consumeNextWith(body -> assertThat(body).isEqualTo("FormBean[fieldValue,[fileParts:foo.txt,fileParts:logo.png]]")) .verifyComplete(); } @@ -194,11 +189,11 @@ public class MultipartIntegrationTests extends AbstractHttpHandlerIntegrationTes @RequestPart("fileParts") FilePart fileParts, @RequestPart("jsonPart") Mono personMono) { - assertEquals("fieldValue", fieldPart.value()); - assertEquals("fileParts:foo.txt", partDescription(fileParts)); + assertThat(fieldPart.value()).isEqualTo("fieldValue"); + assertThat(partDescription(fileParts)).isEqualTo("fileParts:foo.txt"); StepVerifier.create(personMono) - .consumeNextWith(p -> assertEquals("Jason", p.getName())) + .consumeNextWith(p -> assertThat(p.getName()).isEqualTo("Jason")) .verifyComplete(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMapMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMapMethodArgumentResolverTests.java index f537b056ae3..b91265f7023 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMapMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMapMethodArgumentResolverTests.java @@ -34,10 +34,8 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.reactive.BindingContext; import org.springframework.web.reactive.HandlerMapping; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for {@link PathVariableMapMethodArgumentResolver}. @@ -70,9 +68,9 @@ public class PathVariableMapMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(resolver.supportsParameter(paramMap)); - assertFalse(resolver.supportsParameter(paramNamedMap)); - assertFalse(resolver.supportsParameter(paramMapNoAnnot)); + assertThat(resolver.supportsParameter(paramMap)).isTrue(); + assertThat(resolver.supportsParameter(paramNamedMap)).isFalse(); + assertThat(resolver.supportsParameter(paramMapNoAnnot)).isFalse(); assertThatIllegalStateException().isThrownBy(() -> this.resolver.supportsParameter(this.paramMonoMap)) .withMessageStartingWith("PathVariableMapMethodArgumentResolver does not support reactive type wrapper"); @@ -88,7 +86,7 @@ public class PathVariableMapMethodArgumentResolverTests { Mono mono = this.resolver.resolveArgument(this.paramMap, new BindingContext(), this.exchange); Object result = mono.block(); - assertEquals(uriTemplateVars, result); + assertThat(result).isEqualTo(uriTemplateVars); } @Test @@ -96,7 +94,7 @@ public class PathVariableMapMethodArgumentResolverTests { Mono mono = this.resolver.resolveArgument(this.paramMap, new BindingContext(), this.exchange); Object result = mono.block(); - assertEquals(Collections.emptyMap(), result); + assertThat(result).isEqualTo(Collections.emptyMap()); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMethodArgumentResolverTests.java index e121d2411d7..4c8b9d5c2e0 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PathVariableMethodArgumentResolverTests.java @@ -39,10 +39,8 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.server.ServerErrorException; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for {@link PathVariableMethodArgumentResolver}. @@ -78,8 +76,8 @@ public class PathVariableMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter(this.paramNamedString)); - assertFalse(this.resolver.supportsParameter(this.paramString)); + assertThat(this.resolver.supportsParameter(this.paramNamedString)).isTrue(); + assertThat(this.resolver.supportsParameter(this.paramString)).isFalse(); assertThatIllegalStateException().isThrownBy(() -> this.resolver.supportsParameter(this.paramMono)) .withMessageStartingWith("PathVariableMethodArgumentResolver does not support reactive type wrapper"); @@ -94,7 +92,7 @@ public class PathVariableMethodArgumentResolverTests { BindingContext bindingContext = new BindingContext(); Mono mono = this.resolver.resolveArgument(this.paramNamedString, bindingContext, this.exchange); Object result = mono.block(); - assertEquals("value", result); + assertThat(result).isEqualTo("value"); } @Test @@ -106,7 +104,7 @@ public class PathVariableMethodArgumentResolverTests { BindingContext bindingContext = new BindingContext(); Mono mono = this.resolver.resolveArgument(this.paramNotRequired, bindingContext, this.exchange); Object result = mono.block(); - assertEquals("value", result); + assertThat(result).isEqualTo("value"); } @Test @@ -121,7 +119,7 @@ public class PathVariableMethodArgumentResolverTests { Mono mono = this.resolver.resolveArgument(this.paramOptional, bindingContext, this.exchange); Object result = mono.block(); - assertEquals(Optional.of("value"), result); + assertThat(result).isEqualTo(Optional.of("value")); } @Test @@ -151,8 +149,9 @@ public class PathVariableMethodArgumentResolverTests { StepVerifier.create(mono) .consumeNextWith(value -> { - assertTrue(value instanceof Optional); - assertFalse(((Optional) value).isPresent()); + boolean condition = value instanceof Optional; + assertThat(condition).isTrue(); + assertThat(((Optional) value).isPresent()).isFalse(); }) .expectComplete() .verify(); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PrincipalMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PrincipalMethodArgumentResolverTests.java index c460a9af83e..8eec4db8855 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PrincipalMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/PrincipalMethodArgumentResolverTests.java @@ -30,8 +30,7 @@ import org.springframework.web.method.ResolvableMethod; import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link PrincipalMethodArgumentResolver}. @@ -48,9 +47,9 @@ public class PrincipalMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(Principal.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(Mono.class, Principal.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(Single.class, Principal.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(Principal.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(Mono.class, Principal.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(Single.class, Principal.class))).isTrue(); } @@ -63,17 +62,17 @@ public class PrincipalMethodArgumentResolverTests { MethodParameter param = this.testMethod.arg(Principal.class); Object actual = this.resolver.resolveArgument(param, context, exchange).block(); - assertSame(user, actual); + assertThat(actual).isSameAs(user); param = this.testMethod.arg(Mono.class, Principal.class); actual = this.resolver.resolveArgument(param, context, exchange).block(); - assertTrue(Mono.class.isAssignableFrom(actual.getClass())); - assertSame(user, ((Mono) actual).block()); + assertThat(Mono.class.isAssignableFrom(actual.getClass())).isTrue(); + assertThat(((Mono) actual).block()).isSameAs(user); param = this.testMethod.arg(Single.class, Principal.class); actual = this.resolver.resolveArgument(param, context, exchange).block(); - assertTrue(Single.class.isAssignableFrom(actual.getClass())); - assertSame(user, ((Single) actual).blockingGet()); + assertThat(Single.class.isAssignableFrom(actual.getClass())).isTrue(); + assertThat(((Single) actual).blockingGet()).isSameAs(user); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ProtobufIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ProtobufIntegrationTests.java index 0721ca66e2d..a01da5da1ee 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ProtobufIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ProtobufIntegrationTests.java @@ -35,8 +35,7 @@ import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.protobuf.Msg; import org.springframework.web.reactive.protobuf.SecondMsg; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for Protobuf support. @@ -73,9 +72,9 @@ public class ProtobufIntegrationTests extends AbstractRequestMappingIntegrationT .uri("/message") .exchange() .doOnNext(response -> { - assertFalse(response.headers().contentType().get().getParameters().containsKey("delimited")); - assertEquals("sample.proto", response.headers().header("X-Protobuf-Schema").get(0)); - assertEquals("Msg", response.headers().header("X-Protobuf-Message").get(0)); + assertThat(response.headers().contentType().get().getParameters().containsKey("delimited")).isFalse(); + assertThat(response.headers().header("X-Protobuf-Schema").get(0)).isEqualTo("sample.proto"); + assertThat(response.headers().header("X-Protobuf-Message").get(0)).isEqualTo("Msg"); }) .flatMap(response -> response.bodyToMono(Msg.class)); @@ -90,9 +89,9 @@ public class ProtobufIntegrationTests extends AbstractRequestMappingIntegrationT .uri("/messages") .exchange() .doOnNext(response -> { - assertEquals("true", response.headers().contentType().get().getParameters().get("delimited")); - assertEquals("sample.proto", response.headers().header("X-Protobuf-Schema").get(0)); - assertEquals("Msg", response.headers().header("X-Protobuf-Message").get(0)); + assertThat(response.headers().contentType().get().getParameters().get("delimited")).isEqualTo("true"); + assertThat(response.headers().header("X-Protobuf-Schema").get(0)).isEqualTo("sample.proto"); + assertThat(response.headers().header("X-Protobuf-Message").get(0)).isEqualTo("Msg"); }) .flatMapMany(response -> response.bodyToFlux(Msg.class)); @@ -109,9 +108,9 @@ public class ProtobufIntegrationTests extends AbstractRequestMappingIntegrationT .uri("/message-stream") .exchange() .doOnNext(response -> { - assertEquals("true", response.headers().contentType().get().getParameters().get("delimited")); - assertEquals("sample.proto", response.headers().header("X-Protobuf-Schema").get(0)); - assertEquals("Msg", response.headers().header("X-Protobuf-Message").get(0)); + assertThat(response.headers().contentType().get().getParameters().get("delimited")).isEqualTo("true"); + assertThat(response.headers().header("X-Protobuf-Schema").get(0)).isEqualTo("sample.proto"); + assertThat(response.headers().header("X-Protobuf-Message").get(0)).isEqualTo("Msg"); }) .flatMapMany(response -> response.bodyToFlux(Msg.class)); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestAttributeMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestAttributeMethodArgumentResolverTests.java index ae9b34f9cc6..4b77047c528 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestAttributeMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestAttributeMethodArgumentResolverTests.java @@ -37,12 +37,7 @@ import org.springframework.web.method.ResolvableMethod; import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebInputException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.method.MvcAnnotationPredicates.requestAttribute; /** @@ -72,15 +67,15 @@ public class RequestAttributeMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter( - this.testMethod.annot(requestAttribute().noName()).arg(Foo.class))); + assertThat(this.resolver.supportsParameter( + this.testMethod.annot(requestAttribute().noName()).arg(Foo.class))).isTrue(); // SPR-16158 - assertTrue(this.resolver.supportsParameter( - this.testMethod.annotPresent(RequestAttribute.class).arg(Mono.class, Foo.class))); + assertThat(this.resolver.supportsParameter( + this.testMethod.annotPresent(RequestAttribute.class).arg(Mono.class, Foo.class))).isTrue(); - assertFalse(this.resolver.supportsParameter( - this.testMethod.annotNotPresent(RequestAttribute.class).arg())); + assertThat(this.resolver.supportsParameter( + this.testMethod.annotNotPresent(RequestAttribute.class).arg())).isFalse(); } @Test @@ -95,7 +90,7 @@ public class RequestAttributeMethodArgumentResolverTests { Foo foo = new Foo(); this.exchange.getAttributes().put("foo", foo); mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); - assertSame(foo, mono.block()); + assertThat(mono.block()).isSameAs(foo); } @Test @@ -104,19 +99,19 @@ public class RequestAttributeMethodArgumentResolverTests { Foo foo = new Foo(); this.exchange.getAttributes().put("specialFoo", foo); Mono mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); - assertSame(foo, mono.block()); + assertThat(mono.block()).isSameAs(foo); } @Test public void resolveNotRequired() { MethodParameter param = this.testMethod.annot(requestAttribute().name("foo").notRequired()).arg(); Mono mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); - assertNull(mono.block()); + assertThat(mono.block()).isNull(); Foo foo = new Foo(); this.exchange.getAttributes().put("foo", foo); mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); - assertSame(foo, mono.block()); + assertThat(mono.block()).isSameAs(foo); } @Test @@ -124,9 +119,9 @@ public class RequestAttributeMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestAttribute().name("foo")).arg(Optional.class, Foo.class); Mono mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); - assertNotNull(mono.block()); - assertEquals(Optional.class, mono.block().getClass()); - assertFalse(((Optional) mono.block()).isPresent()); + assertThat(mono.block()).isNotNull(); + assertThat(mono.block().getClass()).isEqualTo(Optional.class); + assertThat(((Optional) mono.block()).isPresent()).isFalse(); ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); initializer.setConversionService(new DefaultFormattingConversionService()); @@ -136,11 +131,11 @@ public class RequestAttributeMethodArgumentResolverTests { this.exchange.getAttributes().put("foo", foo); mono = this.resolver.resolveArgument(param, bindingContext, this.exchange); - assertNotNull(mono.block()); - assertEquals(Optional.class, mono.block().getClass()); + assertThat(mono.block()).isNotNull(); + assertThat(mono.block().getClass()).isEqualTo(Optional.class); Optional optional = (Optional) mono.block(); - assertTrue(optional.isPresent()); - assertSame(foo, optional.get()); + assertThat(optional.isPresent()).isTrue(); + assertThat(optional.get()).isSameAs(foo); } @Test // SPR-16158 @@ -152,7 +147,7 @@ public class RequestAttributeMethodArgumentResolverTests { Mono fooMono = Mono.just(foo); this.exchange.getAttributes().put("fooMono", fooMono); Mono mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); - assertSame(fooMono, mono.block(Duration.ZERO)); + assertThat(mono.block(Duration.ZERO)).isSameAs(fooMono); // RxJava Single attribute Single singleMono = Single.just(foo); @@ -160,13 +155,14 @@ public class RequestAttributeMethodArgumentResolverTests { this.exchange.getAttributes().put("fooMono", singleMono); mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); Object value = mono.block(Duration.ZERO); - assertTrue(value instanceof Mono); - assertSame(foo, ((Mono) value).block(Duration.ZERO)); + boolean condition = value instanceof Mono; + assertThat(condition).isTrue(); + assertThat(((Mono) value).block(Duration.ZERO)).isSameAs(foo); // No attribute --> Mono.empty this.exchange.getAttributes().clear(); mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); - assertSame(Mono.empty(), mono.block(Duration.ZERO)); + assertThat(mono.block(Duration.ZERO)).isSameAs(Mono.empty()); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyMethodArgumentResolverTests.java index f35c422e484..3ac90a11d58 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyMethodArgumentResolverTests.java @@ -45,12 +45,8 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertTrue; import static org.springframework.web.method.MvcAnnotationPredicates.requestBody; /** @@ -80,10 +76,10 @@ public class RequestBodyMethodArgumentResolverTests { MethodParameter param; param = this.testMethod.annot(requestBody()).arg(Mono.class, String.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotNotPresent(RequestBody.class).arg(String.class); - assertFalse(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isFalse(); } @Test @@ -92,7 +88,7 @@ public class RequestBodyMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestBody()).arg(String.class); String value = resolveValue(param, body); - assertEquals(body, value); + assertThat(value).isEqualTo(body); } @Test @@ -107,7 +103,7 @@ public class RequestBodyMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestBody().notRequired()).arg(String.class); String body = resolveValueWithEmptyBody(param); - assertNull(body); + assertThat(body).isNull(); } @Test // SPR-15758 @@ -115,7 +111,7 @@ public class RequestBodyMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestBody().notRequired()).arg(Map.class); String body = resolveValueWithEmptyBody(param); - assertNull(body); + assertThat(body).isNull(); } @Test @@ -206,15 +202,15 @@ public class RequestBodyMethodArgumentResolverTests { MethodParameter param = this.testMethod.annot(requestBody()).arg(CompletableFuture.class, String.class); CompletableFuture future = resolveValueWithEmptyBody(param); future.whenComplete((text, ex) -> { - assertNull(text); - assertNotNull(ex); + assertThat(text).isNull(); + assertThat(ex).isNotNull(); }); param = this.testMethod.annot(requestBody().notRequired()).arg(CompletableFuture.class, String.class); future = resolveValueWithEmptyBody(param); future.whenComplete((text, ex) -> { - assertNotNull(text); - assertNull(ex); + assertThat(text).isNotNull(); + assertThat(ex).isNull(); }); } @@ -224,9 +220,8 @@ public class RequestBodyMethodArgumentResolverTests { Mono result = this.resolver.readBody(param, true, new BindingContext(), exchange); Object value = result.block(Duration.ofSeconds(5)); - assertNotNull(value); - assertTrue("Unexpected return value type: " + value, - param.getParameterType().isAssignableFrom(value.getClass())); + assertThat(value).isNotNull(); + assertThat(param.getParameterType().isAssignableFrom(value.getClass())).as("Unexpected return value type: " + value).isTrue(); //no inspection unchecked return (T) value; @@ -239,8 +234,7 @@ public class RequestBodyMethodArgumentResolverTests { Object value = result.block(Duration.ofSeconds(5)); if (value != null) { - assertTrue("Unexpected parameter type: " + value, - param.getParameterType().isAssignableFrom(value.getClass())); + assertThat(param.getParameterType().isAssignableFrom(value.getClass())).as("Unexpected parameter type: " + value).isTrue(); } //no inspection unchecked diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java index 74ef384197c..ed6fdf915ec 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMapMethodArgumentResolverTests.java @@ -35,10 +35,8 @@ import org.springframework.util.MultiValueMap; import org.springframework.util.ReflectionUtils; import org.springframework.web.bind.annotation.RequestHeader; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Unit tests for {@link RequestHeaderMapMethodArgumentResolver}. @@ -72,10 +70,10 @@ public class RequestHeaderMapMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue("Map parameter not supported", resolver.supportsParameter(paramMap)); - assertTrue("MultiValueMap parameter not supported", resolver.supportsParameter(paramMultiValueMap)); - assertTrue("HttpHeaders parameter not supported", resolver.supportsParameter(paramHttpHeaders)); - assertFalse("non-@RequestParam map supported", resolver.supportsParameter(paramUnsupported)); + assertThat(resolver.supportsParameter(paramMap)).as("Map parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramMultiValueMap)).as("MultiValueMap parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramHttpHeaders)).as("HttpHeaders parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramUnsupported)).as("non-@RequestParam map supported").isFalse(); assertThatIllegalStateException().isThrownBy(() -> this.resolver.supportsParameter(this.paramAlsoUnsupported)) .withMessageStartingWith("RequestHeaderMapMethodArgumentResolver does not support reactive type wrapper"); @@ -92,11 +90,13 @@ public class RequestHeaderMapMethodArgumentResolverTests { Mono mono = resolver.resolveArgument(paramMap, null, exchange); Object result = mono.block(); - assertTrue(result instanceof Map); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof Map; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test + @SuppressWarnings("unchecked") public void resolveMultiValueMapArgument() { String name = "foo"; String value1 = "bar"; @@ -111,8 +111,8 @@ public class RequestHeaderMapMethodArgumentResolverTests { Mono mono = resolver.resolveArgument(paramMultiValueMap, null, exchange); Object result = mono.block(); - assertTrue(result instanceof MultiValueMap); - assertEquals("Invalid result", expected, result); + assertThat(result).isInstanceOf(MultiValueMap.class); + assertThat((MultiValueMap) result).containsExactlyEntriesOf(expected); } @Test @@ -130,8 +130,9 @@ public class RequestHeaderMapMethodArgumentResolverTests { Mono mono = resolver.resolveArgument(paramHttpHeaders, null, exchange); Object result = mono.block(); - assertTrue(result instanceof HttpHeaders); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof HttpHeaders; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMethodArgumentResolverTests.java index 42a9eb76782..0e5791fb6e2 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMethodArgumentResolverTests.java @@ -41,11 +41,8 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link RequestHeaderMethodArgumentResolver}. @@ -96,9 +93,9 @@ public class RequestHeaderMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue("String parameter not supported", resolver.supportsParameter(paramNamedDefaultValueStringHeader)); - assertTrue("String array parameter not supported", resolver.supportsParameter(paramNamedValueStringArray)); - assertFalse("non-@RequestParam parameter supported", resolver.supportsParameter(paramNamedValueMap)); + assertThat(resolver.supportsParameter(paramNamedDefaultValueStringHeader)).as("String parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramNamedValueStringArray)).as("String array parameter not supported").isTrue(); + assertThat(resolver.supportsParameter(paramNamedValueMap)).as("non-@RequestParam parameter supported").isFalse(); assertThatIllegalStateException().isThrownBy(() -> this.resolver.supportsParameter(this.paramMono)) .withMessageStartingWith("RequestHeaderMethodArgumentResolver does not support reactive type wrapper"); @@ -113,8 +110,9 @@ public class RequestHeaderMethodArgumentResolverTests { this.paramNamedDefaultValueStringHeader, this.bindingContext, exchange); Object result = mono.block(); - assertTrue(result instanceof String); - assertEquals(expected, result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(expected); } @Test @@ -126,8 +124,9 @@ public class RequestHeaderMethodArgumentResolverTests { this.paramNamedValueStringArray, this.bindingContext, exchange); Object result = mono.block(); - assertTrue(result instanceof String[]); - assertArrayEquals(new String[] {"foo", "bar"}, (String[]) result); + boolean condition = result instanceof String[]; + assertThat(condition).isTrue(); + assertThat((String[]) result).isEqualTo(new String[] {"foo", "bar"}); } @Test @@ -137,8 +136,9 @@ public class RequestHeaderMethodArgumentResolverTests { this.paramNamedDefaultValueStringHeader, this.bindingContext, exchange); Object result = mono.block(); - assertTrue(result instanceof String); - assertEquals("bar", result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo("bar"); } @Test @@ -150,8 +150,9 @@ public class RequestHeaderMethodArgumentResolverTests { MockServerWebExchange.from(MockServerHttpRequest.get("/"))); Object result = mono.block(); - assertTrue(result instanceof String); - assertEquals("bar", result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo("bar"); } finally { System.clearProperty("systemProperty"); @@ -170,8 +171,9 @@ public class RequestHeaderMethodArgumentResolverTests { this.paramResolvedNameWithExpression, this.bindingContext, exchange); Object result = mono.block(); - assertTrue(result instanceof String); - assertEquals(expected, result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(expected); } finally { System.clearProperty("systemProperty"); @@ -190,8 +192,9 @@ public class RequestHeaderMethodArgumentResolverTests { this.paramResolvedNameWithPlaceholder, this.bindingContext, exchange); Object result = mono.block(); - assertTrue(result instanceof String); - assertEquals(expected, result); + boolean condition = result instanceof String; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(expected); } finally { System.clearProperty("systemProperty"); @@ -220,8 +223,9 @@ public class RequestHeaderMethodArgumentResolverTests { Mono mono = this.resolver.resolveArgument(this.paramDate, this.bindingContext, exchange); Object result = mono.block(); - assertTrue(result instanceof Date); - assertEquals(new Date(rfc1123val), result); + boolean condition = result instanceof Date; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(new Date(rfc1123val)); } @Test @@ -233,8 +237,9 @@ public class RequestHeaderMethodArgumentResolverTests { Mono mono = this.resolver.resolveArgument(this.paramInstant, this.bindingContext, exchange); Object result = mono.block(); - assertTrue(result instanceof Instant); - assertEquals(Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(rfc1123val)), result); + boolean condition = result instanceof Instant; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(rfc1123val))); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingDataBindingIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingDataBindingIntegrationTests.java index 6790cee043c..3bf91f0f357 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingDataBindingIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingDataBindingIntegrationTests.java @@ -42,7 +42,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.config.EnableWebFlux; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Data binding and type conversion related integration tests for @@ -63,9 +63,8 @@ public class RequestMappingDataBindingIntegrationTests extends AbstractRequestMa @Test public void handleDateParam() throws Exception { - assertEquals("Processed date!", - performPost("/date-param?date=2016-10-31&date-pattern=YYYY-mm-dd", - new HttpHeaders(), null, String.class).getBody()); + assertThat(performPost("/date-param?date=2016-10-31&date-pattern=YYYY-mm-dd", + new HttpHeaders(), null, String.class).getBody()).isEqualTo("Processed date!"); } @Test @@ -75,9 +74,8 @@ public class RequestMappingDataBindingIntegrationTests extends AbstractRequestMa formData.add("name", "George"); formData.add("age", "5"); - assertEquals("Processed form: Foo[id=1, name='George', age=5]", - performPost("/foos/1", MediaType.APPLICATION_FORM_URLENCODED, formData, - MediaType.TEXT_PLAIN, String.class).getBody()); + assertThat(performPost("/foos/1", MediaType.APPLICATION_FORM_URLENCODED, formData, + MediaType.TEXT_PLAIN, String.class).getBody()).isEqualTo("Processed form: Foo[id=1, name='George', age=5]"); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java index 3df686f3cd2..414d1c5a0c2 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java @@ -37,8 +37,8 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.reactive.config.EnableWebFlux; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * {@code @RequestMapping} integration tests with exception handling scenarios. @@ -91,14 +91,14 @@ public class RequestMappingExceptionHandlingIntegrationTests extends AbstractReq assertThatExceptionOfType(HttpStatusCodeException.class).isThrownBy(() -> performGet("/SPR-16318", headers, String.class).getBody()) .satisfies(ex -> { - assertEquals(500, ex.getRawStatusCode()); - assertEquals("application/problem+json", ex.getResponseHeaders().getContentType().toString()); - assertEquals("{\"reason\":\"error\"}", ex.getResponseBodyAsString()); + assertThat(ex.getRawStatusCode()).isEqualTo(500); + assertThat(ex.getResponseHeaders().getContentType().toString()).isEqualTo("application/problem+json"); + assertThat(ex.getResponseBodyAsString()).isEqualTo("{\"reason\":\"error\"}"); }); } private void doTest(String url, String expected) throws Exception { - assertEquals(expected, performGet(url, new HttpHeaders(), String.class).getBody()); + assertThat(performGet(url, new HttpHeaders(), String.class).getBody()).isEqualTo(expected); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingHandlerMappingTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingHandlerMappingTests.java index f24a5cfa992..ebd1d2f1d48 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingHandlerMappingTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingHandlerMappingTests.java @@ -49,10 +49,7 @@ import org.springframework.web.reactive.result.method.RequestMappingInfo; import org.springframework.web.util.pattern.PathPattern; import org.springframework.web.util.pattern.PathPatternParser; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -80,7 +77,7 @@ public class RequestMappingHandlerMappingTests { String[] patterns = new String[] { "/foo", "/${pattern}/bar" }; String[] result = this.handlerMapping.resolveEmbeddedValuesInPatterns(patterns); - assertArrayEquals(new String[] { "/foo", "/foo/bar" }, result); + assertThat(result).isEqualTo(new String[] { "/foo", "/foo/bar" }); } @Test @@ -92,19 +89,16 @@ public class RequestMappingHandlerMappingTests { Method method = UserController.class.getMethod("getUser"); RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class); - assertNotNull(info); - assertEquals(Collections.singleton(new PathPatternParser().parse("/api/user/{id}")), - info.getPatternsCondition().getPatterns()); + assertThat(info).isNotNull(); + assertThat(info.getPatternsCondition().getPatterns()).isEqualTo(Collections.singleton(new PathPatternParser().parse("/api/user/{id}"))); } @Test public void resolveRequestMappingViaComposedAnnotation() throws Exception { RequestMappingInfo info = assertComposedAnnotationMapping("postJson", "/postJson", RequestMethod.POST); - assertEquals(MediaType.APPLICATION_JSON_VALUE, - info.getConsumesCondition().getConsumableMediaTypes().iterator().next().toString()); - assertEquals(MediaType.APPLICATION_JSON_VALUE, - info.getProducesCondition().getProducibleMediaTypes().iterator().next().toString()); + assertThat(info.getConsumesCondition().getConsumableMediaTypes().iterator().next().toString()).isEqualTo(MediaType.APPLICATION_JSON_VALUE); + assertThat(info.getProducesCondition().getProducibleMediaTypes().iterator().next().toString()).isEqualTo(MediaType.APPLICATION_JSON_VALUE); } @Test // SPR-14988 @@ -112,7 +106,7 @@ public class RequestMappingHandlerMappingTests { RequestMappingInfo requestMappingInfo = assertComposedAnnotationMapping(RequestMethod.POST); ConsumesRequestCondition condition = requestMappingInfo.getConsumesCondition(); - assertEquals(Collections.singleton(MediaType.APPLICATION_XML), condition.getConsumableMediaTypes()); + assertThat(condition.getConsumableMediaTypes()).isEqualTo(Collections.singleton(MediaType.APPLICATION_XML)); } @Test // gh-22010 @@ -128,7 +122,7 @@ public class RequestMappingHandlerMappingTests { .findFirst() .orElseThrow(() -> new AssertionError("No /post")); - assertFalse(info.getConsumesCondition().isBodyRequired()); + assertThat(info.getConsumesCondition().isBodyRequired()).isFalse(); } @Test @@ -171,15 +165,15 @@ public class RequestMappingHandlerMappingTests { Method method = ClassUtils.getMethod(clazz, methodName, (Class[]) null); RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, clazz); - assertNotNull(info); + assertThat(info).isNotNull(); Set paths = info.getPatternsCondition().getPatterns(); - assertEquals(1, paths.size()); - assertEquals(path, paths.iterator().next().getPatternString()); + assertThat(paths.size()).isEqualTo(1); + assertThat(paths.iterator().next().getPatternString()).isEqualTo(path); Set methods = info.getMethodsCondition().getMethods(); - assertEquals(1, methods.size()); - assertEquals(requestMethod, methods.iterator().next()); + assertThat(methods.size()).isEqualTo(1); + assertThat(methods.iterator().next()).isEqualTo(requestMethod); return info; } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingIntegrationTests.java index fd22a3cce7b..8963198ae75 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingIntegrationTests.java @@ -37,9 +37,7 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.config.EnableWebFlux; import org.springframework.web.server.adapter.ForwardedHeaderTransformer; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests with {@code @RequestMapping} handler methods. @@ -67,9 +65,9 @@ public class RequestMappingIntegrationTests extends AbstractRequestMappingIntegr String url = "http://localhost:" + this.port + "/text"; HttpHeaders headers = getRestTemplate().headForHeaders(url); String contentType = headers.getFirst("Content-Type"); - assertNotNull(contentType); - assertEquals("text/html;charset=utf-8", contentType.toLowerCase()); - assertEquals(3, headers.getContentLength()); + assertThat(contentType).isNotNull(); + assertThat(contentType.toLowerCase()).isEqualTo("text/html;charset=utf-8"); + assertThat(headers.getContentLength()).isEqualTo(3); } @Test @@ -83,13 +81,13 @@ public class RequestMappingIntegrationTests extends AbstractRequestMappingIntegr .header("Forwarded", "host=84.198.58.199;proto=https") .build(); ResponseEntity entity = getRestTemplate().exchange(request, String.class); - assertEquals("https://84.198.58.199/uri", entity.getBody()); + assertThat(entity.getBody()).isEqualTo("https://84.198.58.199/uri"); } @Test public void stream() throws Exception { String[] expected = {"0", "1", "2", "3", "4"}; - assertArrayEquals(expected, performGet("/stream", new HttpHeaders(), String[].class).getBody()); + assertThat(performGet("/stream", new HttpHeaders(), String[].class).getBody()).isEqualTo(expected); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java index e166fa53c24..9f26e329d7d 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java @@ -60,9 +60,7 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.config.EnableWebFlux; import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.http.MediaType.APPLICATION_XML; /** @@ -91,101 +89,101 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq @Test public void byteBufferResponseBodyWithPublisher() throws Exception { Person expected = new Person("Robert"); - assertEquals(expected, performGet("/raw-response/publisher", JSON, Person.class).getBody()); + assertThat(performGet("/raw-response/publisher", JSON, Person.class).getBody()).isEqualTo(expected); } @Test public void byteBufferResponseBodyWithFlux() throws Exception { String expected = "Hello!"; - assertEquals(expected, performGet("/raw-response/flux", new HttpHeaders(), String.class).getBody()); + assertThat(performGet("/raw-response/flux", new HttpHeaders(), String.class).getBody()).isEqualTo(expected); } @Test public void byteBufferResponseBodyWithMono() throws Exception { String expected = "Hello!"; ResponseEntity responseEntity = performGet("/raw-response/mono", new HttpHeaders(), String.class); - assertEquals(6, responseEntity.getHeaders().getContentLength()); - assertEquals(expected, responseEntity.getBody()); + assertThat(responseEntity.getHeaders().getContentLength()).isEqualTo(6); + assertThat(responseEntity.getBody()).isEqualTo(expected); } @Test public void byteBufferResponseBodyWithObservable() throws Exception { String expected = "Hello!"; - assertEquals(expected, performGet("/raw-response/observable", new HttpHeaders(), String.class).getBody()); + assertThat(performGet("/raw-response/observable", new HttpHeaders(), String.class).getBody()).isEqualTo(expected); } @Test public void byteBufferResponseBodyWithRxJava2Observable() throws Exception { String expected = "Hello!"; - assertEquals(expected, performGet("/raw-response/rxjava2-observable", - new HttpHeaders(), String.class).getBody()); + assertThat(performGet("/raw-response/rxjava2-observable", + new HttpHeaders(), String.class).getBody()).isEqualTo(expected); } @Test public void byteBufferResponseBodyWithFlowable() throws Exception { String expected = "Hello!"; - assertEquals(expected, performGet("/raw-response/flowable", new HttpHeaders(), String.class).getBody()); + assertThat(performGet("/raw-response/flowable", new HttpHeaders(), String.class).getBody()).isEqualTo(expected); } @Test public void personResponseBody() throws Exception { Person expected = new Person("Robert"); ResponseEntity responseEntity = performGet("/person-response/person", JSON, Person.class); - assertEquals(17, responseEntity.getHeaders().getContentLength()); - assertEquals(expected, responseEntity.getBody()); + assertThat(responseEntity.getHeaders().getContentLength()).isEqualTo(17); + assertThat(responseEntity.getBody()).isEqualTo(expected); } @Test public void personResponseBodyWithCompletableFuture() throws Exception { Person expected = new Person("Robert"); ResponseEntity responseEntity = performGet("/person-response/completable-future", JSON, Person.class); - assertEquals(17, responseEntity.getHeaders().getContentLength()); - assertEquals(expected, responseEntity.getBody()); + assertThat(responseEntity.getHeaders().getContentLength()).isEqualTo(17); + assertThat(responseEntity.getBody()).isEqualTo(expected); } @Test public void personResponseBodyWithMono() throws Exception { Person expected = new Person("Robert"); ResponseEntity responseEntity = performGet("/person-response/mono", JSON, Person.class); - assertEquals(17, responseEntity.getHeaders().getContentLength()); - assertEquals(expected, responseEntity.getBody()); + assertThat(responseEntity.getHeaders().getContentLength()).isEqualTo(17); + assertThat(responseEntity.getBody()).isEqualTo(expected); } @Test // SPR-17506 public void personResponseBodyWithEmptyMono() throws Exception { ResponseEntity responseEntity = performGet("/person-response/mono-empty", JSON, Person.class); - assertEquals(0, responseEntity.getHeaders().getContentLength()); - assertNull(responseEntity.getBody()); + assertThat(responseEntity.getHeaders().getContentLength()).isEqualTo(0); + assertThat(responseEntity.getBody()).isNull(); // As we're on the same connection, the 2nd request proves server response handling // did complete after the 1st request.. responseEntity = performGet("/person-response/mono-empty", JSON, Person.class); - assertEquals(0, responseEntity.getHeaders().getContentLength()); - assertNull(responseEntity.getBody()); + assertThat(responseEntity.getHeaders().getContentLength()).isEqualTo(0); + assertThat(responseEntity.getBody()).isNull(); } @Test public void personResponseBodyWithMonoDeclaredAsObject() throws Exception { Person expected = new Person("Robert"); ResponseEntity entity = performGet("/person-response/mono-declared-as-object", JSON, Person.class); - assertEquals(17, entity.getHeaders().getContentLength()); - assertEquals(expected, entity.getBody()); + assertThat(entity.getHeaders().getContentLength()).isEqualTo(17); + assertThat(entity.getBody()).isEqualTo(expected); } @Test public void personResponseBodyWithSingle() throws Exception { Person expected = new Person("Robert"); ResponseEntity entity = performGet("/person-response/single", JSON, Person.class); - assertEquals(17, entity.getHeaders().getContentLength()); - assertEquals(expected, entity.getBody()); + assertThat(entity.getHeaders().getContentLength()).isEqualTo(17); + assertThat(entity.getBody()).isEqualTo(expected); } @Test public void personResponseBodyWithMonoResponseEntity() throws Exception { Person expected = new Person("Robert"); ResponseEntity entity = performGet("/person-response/mono-response-entity", JSON, Person.class); - assertEquals(17, entity.getHeaders().getContentLength()); - assertEquals(expected, entity.getBody()); + assertThat(entity.getHeaders().getContentLength()).isEqualTo(17); + assertThat(entity.getBody()).isEqualTo(expected); } @Test // SPR-16172 @@ -195,132 +193,125 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq ResponseEntity entity = performGet(url, new HttpHeaders(), String.class); String actual = entity.getBody(); - assertEquals(91, entity.getHeaders().getContentLength()); - assertEquals("" + - "Robert", actual); + assertThat(entity.getHeaders().getContentLength()).isEqualTo(91); + assertThat(actual).isEqualTo(("" + + "Robert")); } @Test public void personResponseBodyWithList() throws Exception { List expected = asList(new Person("Robert"), new Person("Marie")); ResponseEntity> entity = performGet("/person-response/list", JSON, PERSON_LIST); - assertEquals(36, entity.getHeaders().getContentLength()); - assertEquals(expected, entity.getBody()); + assertThat(entity.getHeaders().getContentLength()).isEqualTo(36); + assertThat(entity.getBody()).isEqualTo(expected); } @Test public void personResponseBodyWithPublisher() throws Exception { List expected = asList(new Person("Robert"), new Person("Marie")); ResponseEntity> entity = performGet("/person-response/publisher", JSON, PERSON_LIST); - assertEquals(-1, entity.getHeaders().getContentLength()); - assertEquals(expected, entity.getBody()); + assertThat(entity.getHeaders().getContentLength()).isEqualTo(-1); + assertThat(entity.getBody()).isEqualTo(expected); } @Test public void personResponseBodyWithFlux() throws Exception { List expected = asList(new Person("Robert"), new Person("Marie")); - assertEquals(expected, performGet("/person-response/flux", JSON, PERSON_LIST).getBody()); + assertThat(performGet("/person-response/flux", JSON, PERSON_LIST).getBody()).isEqualTo(expected); } @Test public void personResponseBodyWithObservable() throws Exception { List expected = asList(new Person("Robert"), new Person("Marie")); - assertEquals(expected, performGet("/person-response/observable", JSON, PERSON_LIST).getBody()); + assertThat(performGet("/person-response/observable", JSON, PERSON_LIST).getBody()).isEqualTo(expected); } @Test public void resource() throws Exception { ResponseEntity response = performGet("/resource", new HttpHeaders(), byte[].class); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertTrue(response.hasBody()); - assertEquals(951, response.getHeaders().getContentLength()); - assertEquals(951, response.getBody().length); - assertEquals(new MediaType("image", "png"), response.getHeaders().getContentType()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.hasBody()).isTrue(); + assertThat(response.getHeaders().getContentLength()).isEqualTo(951); + assertThat(response.getBody().length).isEqualTo(951); + assertThat(response.getHeaders().getContentType()).isEqualTo(new MediaType("image", "png")); } @Test public void personTransform() throws Exception { - assertEquals(new Person("ROBERT"), - performPost("/person-transform/person", JSON, new Person("Robert"), - JSON, Person.class).getBody()); + assertThat(performPost("/person-transform/person", JSON, new Person("Robert"), + JSON, Person.class).getBody()).isEqualTo(new Person("ROBERT")); } @Test public void personTransformWithCompletableFuture() throws Exception { - assertEquals(new Person("ROBERT"), - performPost("/person-transform/completable-future", JSON, new Person("Robert"), - JSON, Person.class).getBody()); + assertThat(performPost("/person-transform/completable-future", JSON, new Person("Robert"), + JSON, Person.class).getBody()).isEqualTo(new Person("ROBERT")); } @Test public void personTransformWithMono() throws Exception { - assertEquals(new Person("ROBERT"), - performPost("/person-transform/mono", JSON, new Person("Robert"), - JSON, Person.class).getBody()); + assertThat(performPost("/person-transform/mono", JSON, new Person("Robert"), + JSON, Person.class).getBody()).isEqualTo(new Person("ROBERT")); } @Test // SPR-16759 public void personTransformWithMonoAndXml() throws Exception { - assertEquals(new Person("ROBERT"), - performPost("/person-transform/mono", MediaType.APPLICATION_XML, new Person("Robert"), - MediaType.APPLICATION_XML, Person.class).getBody()); + assertThat(performPost("/person-transform/mono", MediaType.APPLICATION_XML, new Person("Robert"), + MediaType.APPLICATION_XML, Person.class).getBody()).isEqualTo(new Person("ROBERT")); } @Test public void personTransformWithSingle() throws Exception { - assertEquals(new Person("ROBERT"), - performPost("/person-transform/single", JSON, new Person("Robert"), - JSON, Person.class).getBody()); + assertThat(performPost("/person-transform/single", JSON, new Person("Robert"), + JSON, Person.class).getBody()).isEqualTo(new Person("ROBERT")); } @Test public void personTransformWithRxJava2Single() throws Exception { - assertEquals(new Person("ROBERT"), - performPost("/person-transform/rxjava2-single", JSON, new Person("Robert"), - JSON, Person.class).getBody()); + assertThat(performPost("/person-transform/rxjava2-single", JSON, new Person("Robert"), + JSON, Person.class).getBody()).isEqualTo(new Person("ROBERT")); } @Test public void personTransformWithRxJava2Maybe() throws Exception { - assertEquals(new Person("ROBERT"), - performPost("/person-transform/rxjava2-maybe", JSON, new Person("Robert"), - JSON, Person.class).getBody()); + assertThat(performPost("/person-transform/rxjava2-maybe", JSON, new Person("Robert"), + JSON, Person.class).getBody()).isEqualTo(new Person("ROBERT")); } @Test public void personTransformWithPublisher() throws Exception { List req = asList(new Person("Robert"), new Person("Marie")); List res = asList(new Person("ROBERT"), new Person("MARIE")); - assertEquals(res, performPost("/person-transform/publisher", JSON, req, JSON, PERSON_LIST).getBody()); + assertThat(performPost("/person-transform/publisher", JSON, req, JSON, PERSON_LIST).getBody()).isEqualTo(res); } @Test public void personTransformWithFlux() throws Exception { List req = asList(new Person("Robert"), new Person("Marie")); List res = asList(new Person("ROBERT"), new Person("MARIE")); - assertEquals(res, performPost("/person-transform/flux", JSON, req, JSON, PERSON_LIST).getBody()); + assertThat(performPost("/person-transform/flux", JSON, req, JSON, PERSON_LIST).getBody()).isEqualTo(res); } @Test public void personTransformWithObservable() throws Exception { List req = asList(new Person("Robert"), new Person("Marie")); List res = asList(new Person("ROBERT"), new Person("MARIE")); - assertEquals(res, performPost("/person-transform/observable", JSON, req, JSON, PERSON_LIST).getBody()); + assertThat(performPost("/person-transform/observable", JSON, req, JSON, PERSON_LIST).getBody()).isEqualTo(res); } @Test public void personTransformWithRxJava2Observable() throws Exception { List req = asList(new Person("Robert"), new Person("Marie")); List res = asList(new Person("ROBERT"), new Person("MARIE")); - assertEquals(res, performPost("/person-transform/rxjava2-observable", JSON, req, JSON, PERSON_LIST).getBody()); + assertThat(performPost("/person-transform/rxjava2-observable", JSON, req, JSON, PERSON_LIST).getBody()).isEqualTo(res); } @Test public void personTransformWithFlowable() throws Exception { List req = asList(new Person("Robert"), new Person("Marie")); List res = asList(new Person("ROBERT"), new Person("MARIE")); - assertEquals(res, performPost("/person-transform/flowable", JSON, req, JSON, PERSON_LIST).getBody()); + assertThat(performPost("/person-transform/flowable", JSON, req, JSON, PERSON_LIST).getBody()).isEqualTo(res); } @Test @@ -328,8 +319,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq ResponseEntity entity = performPost("/person-create/publisher", JSON, asList(new Person("Robert"), new Person("Marie")), null, Void.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(2); } @Test @@ -337,8 +328,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq People people = new People(new Person("Robert"), new Person("Marie")); ResponseEntity response = performPost("/person-create/publisher", APPLICATION_XML, people, null, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(2); } @Test @@ -346,8 +337,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq ResponseEntity entity = performPost( "/person-create/mono", JSON, new Person("Robert"), null, Void.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(1, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(1); } @Test @@ -355,8 +346,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq ResponseEntity entity = performPost( "/person-create/single", JSON, new Person("Robert"), null, Void.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(1, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(1); } @Test @@ -364,8 +355,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq ResponseEntity entity = performPost( "/person-create/rxjava2-single", JSON, new Person("Robert"), null, Void.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(1, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(1); } @Test @@ -373,8 +364,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq ResponseEntity entity = performPost("/person-create/flux", JSON, asList(new Person("Robert"), new Person("Marie")), null, Void.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(2); } @Test @@ -382,8 +373,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq People people = new People(new Person("Robert"), new Person("Marie")); ResponseEntity response = performPost("/person-create/flux", APPLICATION_XML, people, null, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(2); } @Test @@ -391,8 +382,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq ResponseEntity entity = performPost("/person-create/observable", JSON, asList(new Person("Robert"), new Person("Marie")), null, Void.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(2); } @Test @@ -400,8 +391,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq ResponseEntity entity = performPost("/person-create/rxjava2-observable", JSON, asList(new Person("Robert"), new Person("Marie")), null, Void.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(2); } @Test @@ -409,8 +400,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq People people = new People(new Person("Robert"), new Person("Marie")); ResponseEntity response = performPost("/person-create/observable", APPLICATION_XML, people, null, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(2); } @Test @@ -419,8 +410,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq String url = "/person-create/rxjava2-observable"; ResponseEntity response = performPost(url, APPLICATION_XML, people, null, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(2); } @Test @@ -428,8 +419,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq ResponseEntity entity = performPost("/person-create/flowable", JSON, asList(new Person("Robert"), new Person("Marie")), null, Void.class); - assertEquals(HttpStatus.OK, entity.getStatusCode()); - assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(2); } @Test @@ -437,8 +428,8 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq People people = new People(new Person("Robert"), new Person("Marie")); ResponseEntity response = performPost("/person-create/flowable", APPLICATION_XML, people, null, Void.class); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(getApplicationContext().getBean(PersonCreateController.class).persons.size()).isEqualTo(2); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingViewResolutionIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingViewResolutionIntegrationTests.java index 1ca50887c1a..277b13a057a 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingViewResolutionIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingViewResolutionIntegrationTests.java @@ -43,8 +43,7 @@ import org.springframework.web.reactive.config.WebFluxConfigurer; import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * {@code @RequestMapping} integration tests with view resolution scenarios. @@ -65,7 +64,7 @@ public class RequestMappingViewResolutionIntegrationTests extends AbstractReques @Test public void html() throws Exception { String expected = "Hello: Jason!"; - assertEquals(expected, performGet("/html?name=Jason", MediaType.TEXT_HTML, String.class).getBody()); + assertThat(performGet("/html?name=Jason", MediaType.TEXT_HTML, String.class).getBody()).isEqualTo(expected); } @Test @@ -74,8 +73,8 @@ public class RequestMappingViewResolutionIntegrationTests extends AbstractReques RequestEntity request = RequestEntity.get(uri).ifNoneMatch("\"deadb33f8badf00d\"").build(); ResponseEntity response = getRestTemplate().exchange(request, String.class); - assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode()); - assertNull(response.getBody()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_MODIFIED); + assertThat(response.getBody()).isNull(); } @Test // SPR-15291 @@ -92,8 +91,8 @@ public class RequestMappingViewResolutionIntegrationTests extends AbstractReques RequestEntity request = RequestEntity.get(uri).accept(MediaType.ALL).build(); ResponseEntity response = new RestTemplate(factory).exchange(request, Void.class); - assertEquals(HttpStatus.SEE_OTHER, response.getStatusCode()); - assertEquals("/", response.getHeaders().getLocation().toString()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SEE_OTHER); + assertThat(response.getHeaders().getLocation().toString()).isEqualTo("/"); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMapMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMapMethodArgumentResolverTests.java index 3c98d59d206..cd405014021 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMapMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMapMethodArgumentResolverTests.java @@ -33,10 +33,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.method.ResolvableMethod; import org.springframework.web.server.ServerWebExchange; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.springframework.web.method.MvcAnnotationPredicates.requestParam; /** @@ -55,16 +53,16 @@ public class RequestParamMapMethodArgumentResolverTests { @Test public void supportsParameter() { MethodParameter param = this.testMethod.annot(requestParam().name("")).arg(Map.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(MultiValueMap.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestParam().name("name")).arg(Map.class); - assertFalse(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isFalse(); param = this.testMethod.annotNotPresent(RequestParam.class).arg(Map.class); - assertFalse(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isFalse(); assertThatIllegalStateException().isThrownBy(() -> this.resolver.supportsParameter(this.testMethod.annot(requestParam()).arg(Mono.class, Map.class))) @@ -75,8 +73,9 @@ public class RequestParamMapMethodArgumentResolverTests { public void resolveMapArgumentWithQueryString() { MethodParameter param = this.testMethod.annot(requestParam().name("")).arg(Map.class); Object result= resolve(param, MockServerWebExchange.from(MockServerHttpRequest.get("/path?foo=bar"))); - assertTrue(result instanceof Map); - assertEquals(Collections.singletonMap("foo", "bar"), result); + boolean condition = result instanceof Map; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(Collections.singletonMap("foo", "bar")); } @Test @@ -85,8 +84,9 @@ public class RequestParamMapMethodArgumentResolverTests { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path?foo=bar&foo=baz")); Object result= resolve(param, exchange); - assertTrue(result instanceof MultiValueMap); - assertEquals(Collections.singletonMap("foo", Arrays.asList("bar", "baz")), result); + boolean condition = result instanceof MultiValueMap; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(Collections.singletonMap("foo", Arrays.asList("bar", "baz"))); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMethodArgumentResolverTests.java index d9744cc35d5..dd184c83297 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMethodArgumentResolverTests.java @@ -37,12 +37,8 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.springframework.core.ResolvableType.forClassWithGenerics; import static org.springframework.web.method.MvcAnnotationPredicates.requestParam; @@ -76,25 +72,25 @@ public class RequestParamMethodArgumentResolverTests { public void supportsParameter() { MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotPresent(RequestParam.class).arg(String[].class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestParam().name("name")).arg(Map.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestParam().name("")).arg(Map.class); - assertFalse(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isFalse(); param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestParam()).arg(String.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestParam().notRequired()).arg(String.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); } @@ -104,7 +100,7 @@ public class RequestParamMethodArgumentResolverTests { this.resolver = new RequestParamMethodArgumentResolver(null, adapterRegistry, false); MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class); - assertFalse(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isFalse(); } @Test @@ -121,7 +117,7 @@ public class RequestParamMethodArgumentResolverTests { public void resolveWithQueryString() { MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path?name=foo")); - assertEquals("foo", resolve(param, exchange)); + assertThat(resolve(param, exchange)).isEqualTo("foo"); } @Test @@ -129,14 +125,15 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(String[].class); MockServerHttpRequest request = MockServerHttpRequest.get("/path?name=foo&name=bar").build(); Object result = resolve(param, MockServerWebExchange.from(request)); - assertTrue(result instanceof String[]); - assertArrayEquals(new String[] {"foo", "bar"}, (String[]) result); + boolean condition = result instanceof String[]; + assertThat(condition).isTrue(); + assertThat((String[]) result).isEqualTo(new String[] {"foo", "bar"}); } @Test public void resolveDefaultValue() { MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class); - assertEquals("bar", resolve(param, MockServerWebExchange.from(MockServerHttpRequest.get("/")))); + assertThat(resolve(param, MockServerWebExchange.from(MockServerHttpRequest.get("/")))).isEqualTo("bar"); } @Test // SPR-17050 @@ -144,7 +141,7 @@ public class RequestParamMethodArgumentResolverTests { MethodParameter param = this.testMethod .annot(requestParam().notRequired()) .arg(Integer.class); - assertNull(resolve(param, MockServerWebExchange.from(MockServerHttpRequest.get("/?nullParam=")))); + assertThat(resolve(param, MockServerWebExchange.from(MockServerHttpRequest.get("/?nullParam=")))).isNull(); } @Test @@ -166,13 +163,13 @@ public class RequestParamMethodArgumentResolverTests { ServerWebExchange exchange = MockServerWebExchange.from(request); MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class); Object result = resolve(param, exchange); - assertEquals("plainValue", result); + assertThat(result).isEqualTo("plainValue"); } @Test // SPR-8561 public void resolveSimpleTypeParamToNull() { MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class); - assertNull(resolve(param, MockServerWebExchange.from(MockServerHttpRequest.get("/")))); + assertThat(resolve(param, MockServerWebExchange.from(MockServerHttpRequest.get("/")))).isNull(); } @Test // SPR-10180 @@ -180,21 +177,21 @@ public class RequestParamMethodArgumentResolverTests { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path?name=")); MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class); Object result = resolve(param, exchange); - assertEquals("bar", result); + assertThat(result).isEqualTo("bar"); } @Test public void resolveEmptyValueWithoutDefault() { MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class); MockServerHttpRequest request = MockServerHttpRequest.get("/path?stringNotAnnot=").build(); - assertEquals("", resolve(param, MockServerWebExchange.from(request))); + assertThat(resolve(param, MockServerWebExchange.from(request))).isEqualTo(""); } @Test public void resolveEmptyValueRequiredWithoutDefault() { MethodParameter param = this.testMethod.annot(requestParam()).arg(String.class); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path?name=")); - assertEquals("", resolve(param, exchange)); + assertThat(resolve(param, exchange)).isEqualTo(""); } @Test @@ -202,15 +199,15 @@ public class RequestParamMethodArgumentResolverTests { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); MethodParameter param = this.testMethod.arg(forClassWithGenerics(Optional.class, Integer.class)); Object result = resolve(param, exchange); - assertEquals(Optional.empty(), result); + assertThat(result).isEqualTo(Optional.empty()); exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path?name=123")); result = resolve(param, exchange); - assertEquals(Optional.class, result.getClass()); + assertThat(result.getClass()).isEqualTo(Optional.class); Optional value = (Optional) result; - assertTrue(value.isPresent()); - assertEquals(123, value.get()); + assertThat(value.isPresent()).isTrue(); + assertThat(value.get()).isEqualTo(123); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestPartMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestPartMethodArgumentResolverTests.java index 54f65fc7e0e..67fab0358f8 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestPartMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestPartMethodArgumentResolverTests.java @@ -53,10 +53,7 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.ResolvableType.forClass; import static org.springframework.web.method.MvcAnnotationPredicates.requestPart; @@ -90,25 +87,25 @@ public class RequestPartMethodArgumentResolverTests { MethodParameter param; param = this.testMethod.annot(requestPart()).arg(Person.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestPart()).arg(Mono.class, Person.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestPart()).arg(Flux.class, Person.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestPart()).arg(Part.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestPart()).arg(Mono.class, Part.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annot(requestPart()).arg(Flux.class, Part.class); - assertTrue(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isTrue(); param = this.testMethod.annotNotPresent(RequestPart.class).arg(Person.class); - assertFalse(this.resolver.supportsParameter(param)); + assertThat(this.resolver.supportsParameter(param)).isFalse(); } @@ -119,7 +116,7 @@ public class RequestPartMethodArgumentResolverTests { bodyBuilder.part("name", new Person("Jones")); Person actual = resolveArgument(param, bodyBuilder); - assertEquals("Jones", actual.getName()); + assertThat(actual.getName()).isEqualTo("Jones"); } @Test @@ -130,8 +127,8 @@ public class RequestPartMethodArgumentResolverTests { bodyBuilder.part("name", new Person("James")); List actual = resolveArgument(param, bodyBuilder); - assertEquals("Jones", actual.get(0).getName()); - assertEquals("James", actual.get(1).getName()); + assertThat(actual.get(0).getName()).isEqualTo("Jones"); + assertThat(actual.get(1).getName()).isEqualTo("James"); } @Test @@ -141,7 +138,7 @@ public class RequestPartMethodArgumentResolverTests { bodyBuilder.part("name", new Person("Jones")); Mono actual = resolveArgument(param, bodyBuilder); - assertEquals("Jones", actual.block().getName()); + assertThat(actual.block().getName()).isEqualTo("Jones"); } @Test @@ -153,8 +150,8 @@ public class RequestPartMethodArgumentResolverTests { Flux actual = resolveArgument(param, bodyBuilder); List persons = actual.collectList().block(); - assertEquals("Jones", persons.get(0).getName()); - assertEquals("James", persons.get(1).getName()); + assertThat(persons.get(0).getName()).isEqualTo("Jones"); + assertThat(persons.get(1).getName()).isEqualTo("James"); } @Test @@ -165,7 +162,7 @@ public class RequestPartMethodArgumentResolverTests { Part actual = resolveArgument(param, bodyBuilder); DataBuffer buffer = DataBufferUtils.join(actual.content()).block(); - assertEquals("{\"name\":\"Jones\"}", DataBufferTestUtils.dumpString(buffer, StandardCharsets.UTF_8)); + assertThat(DataBufferTestUtils.dumpString(buffer, StandardCharsets.UTF_8)).isEqualTo("{\"name\":\"Jones\"}"); } @Test @@ -176,8 +173,8 @@ public class RequestPartMethodArgumentResolverTests { bodyBuilder.part("name", new Person("James")); List actual = resolveArgument(param, bodyBuilder); - assertEquals("{\"name\":\"Jones\"}", partToUtf8String(actual.get(0))); - assertEquals("{\"name\":\"James\"}", partToUtf8String(actual.get(1))); + assertThat(partToUtf8String(actual.get(0))).isEqualTo("{\"name\":\"Jones\"}"); + assertThat(partToUtf8String(actual.get(1))).isEqualTo("{\"name\":\"James\"}"); } @Test @@ -188,7 +185,7 @@ public class RequestPartMethodArgumentResolverTests { Mono actual = resolveArgument(param, bodyBuilder); Part part = actual.block(); - assertEquals("{\"name\":\"Jones\"}", partToUtf8String(part)); + assertThat(partToUtf8String(part)).isEqualTo("{\"name\":\"Jones\"}"); } @Test @@ -200,8 +197,8 @@ public class RequestPartMethodArgumentResolverTests { Flux actual = resolveArgument(param, bodyBuilder); List parts = actual.collectList().block(); - assertEquals("{\"name\":\"Jones\"}", partToUtf8String(parts.get(0))); - assertEquals("{\"name\":\"James\"}", partToUtf8String(parts.get(1))); + assertThat(partToUtf8String(parts.get(0))).isEqualTo("{\"name\":\"Jones\"}"); + assertThat(partToUtf8String(parts.get(1))).isEqualTo("{\"name\":\"James\"}"); } @Test @@ -247,8 +244,8 @@ public class RequestPartMethodArgumentResolverTests { Mono result = this.resolver.resolveArgument(param, new BindingContext(), exchange); Object value = result.block(Duration.ofSeconds(5)); - assertNotNull(value); - assertTrue(param.getParameterType().isAssignableFrom(value.getClass())); + assertThat(value).isNotNull(); + assertThat(param.getParameterType().isAssignableFrom(value.getClass())).isTrue(); return (T) value; } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandlerTests.java index fb7e1320331..6f64c1389dd 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandlerTests.java @@ -41,9 +41,7 @@ import org.springframework.web.reactive.HandlerResult; import org.springframework.web.reactive.accept.RequestedContentTypeResolver; import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.method.ResolvableMethod.on; /** @@ -85,7 +83,7 @@ public class ResponseBodyResultHandlerTests { method = on(TestController.class).annotNotPresent(ResponseBody.class).resolveMethod("doWork"); HandlerResult handlerResult = getHandlerResult(controller, method); - assertFalse(this.resultHandler.supports(handlerResult)); + assertThat(this.resultHandler.supports(handlerResult)).isFalse(); } @Test @@ -108,7 +106,7 @@ public class ResponseBodyResultHandlerTests { private void testSupports(Object controller, Method method) { HandlerResult handlerResult = getHandlerResult(controller, method); - assertTrue(this.resultHandler.supports(handlerResult)); + assertThat(this.resultHandler.supports(handlerResult)).isTrue(); } private HandlerResult getHandlerResult(Object controller, Method method) { @@ -118,7 +116,7 @@ public class ResponseBodyResultHandlerTests { @Test public void defaultOrder() { - assertEquals(100, this.resultHandler.getOrder()); + assertThat(this.resultHandler.getOrder()).isEqualTo(100); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandlerTests.java index 8940f35ddb9..70ff0931501 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandlerTests.java @@ -57,9 +57,7 @@ import org.springframework.web.reactive.HandlerResult; import org.springframework.web.reactive.accept.RequestedContentTypeResolver; import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.ResolvableType.forClassWithGenerics; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.ResponseEntity.notFound; @@ -111,24 +109,24 @@ public class ResponseEntityResultHandlerTests { Object value = null; MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class)); - assertTrue(this.resultHandler.supports(handlerResult(value, returnType))); + assertThat(this.resultHandler.supports(handlerResult(value, returnType))).isTrue(); returnType = on(TestController.class).resolveReturnType(Mono.class, entity(String.class)); - assertTrue(this.resultHandler.supports(handlerResult(value, returnType))); + assertThat(this.resultHandler.supports(handlerResult(value, returnType))).isTrue(); returnType = on(TestController.class).resolveReturnType(Single.class, entity(String.class)); - assertTrue(this.resultHandler.supports(handlerResult(value, returnType))); + assertThat(this.resultHandler.supports(handlerResult(value, returnType))).isTrue(); returnType = on(TestController.class).resolveReturnType(CompletableFuture.class, entity(String.class)); - assertTrue(this.resultHandler.supports(handlerResult(value, returnType))); + assertThat(this.resultHandler.supports(handlerResult(value, returnType))).isTrue(); returnType = on(TestController.class).resolveReturnType(HttpHeaders.class); - assertTrue(this.resultHandler.supports(handlerResult(value, returnType))); + assertThat(this.resultHandler.supports(handlerResult(value, returnType))).isTrue(); // SPR-15785 value = ResponseEntity.ok("testing"); returnType = on(TestController.class).resolveReturnType(Object.class); - assertTrue(this.resultHandler.supports(handlerResult(value, returnType))); + assertThat(this.resultHandler.supports(handlerResult(value, returnType))).isTrue(); } @Test @@ -136,19 +134,19 @@ public class ResponseEntityResultHandlerTests { Object value = null; MethodParameter returnType = on(TestController.class).resolveReturnType(String.class); - assertFalse(this.resultHandler.supports(handlerResult(value, returnType))); + assertThat(this.resultHandler.supports(handlerResult(value, returnType))).isFalse(); returnType = on(TestController.class).resolveReturnType(Completable.class); - assertFalse(this.resultHandler.supports(handlerResult(value, returnType))); + assertThat(this.resultHandler.supports(handlerResult(value, returnType))).isFalse(); // SPR-15464 returnType = on(TestController.class).resolveReturnType(Flux.class); - assertFalse(this.resultHandler.supports(handlerResult(value, returnType))); + assertThat(this.resultHandler.supports(handlerResult(value, returnType))).isFalse(); } @Test public void defaultOrder() throws Exception { - assertEquals(0, this.resultHandler.getOrder()); + assertThat(this.resultHandler.getOrder()).isEqualTo(0); } @Test @@ -159,8 +157,8 @@ public class ResponseEntityResultHandlerTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/path")); this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.NO_CONTENT, exchange.getResponse().getStatusCode()); - assertEquals(0, exchange.getResponse().getHeaders().size()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); + assertThat(exchange.getResponse().getHeaders().size()).isEqualTo(0); assertResponseBodyIsEmpty(exchange); } @@ -173,9 +171,9 @@ public class ResponseEntityResultHandlerTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/path")); this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.OK, exchange.getResponse().getStatusCode()); - assertEquals(1, exchange.getResponse().getHeaders().size()); - assertEquals("GET,POST,OPTIONS", exchange.getResponse().getHeaders().getFirst("Allow")); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(exchange.getResponse().getHeaders().size()).isEqualTo(1); + assertThat(exchange.getResponse().getHeaders().getFirst("Allow")).isEqualTo("GET,POST,OPTIONS"); assertResponseBodyIsEmpty(exchange); } @@ -188,9 +186,9 @@ public class ResponseEntityResultHandlerTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/path")); this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.CREATED, exchange.getResponse().getStatusCode()); - assertEquals(1, exchange.getResponse().getHeaders().size()); - assertEquals(location, exchange.getResponse().getHeaders().getLocation()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.CREATED); + assertThat(exchange.getResponse().getHeaders().size()).isEqualTo(1); + assertThat(exchange.getResponse().getHeaders().getLocation()).isEqualTo(location); assertResponseBodyIsEmpty(exchange); } @@ -202,7 +200,7 @@ public class ResponseEntityResultHandlerTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/path")); this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.NOT_FOUND, exchange.getResponse().getStatusCode()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertResponseBodyIsEmpty(exchange); } @@ -265,7 +263,7 @@ public class ResponseEntityResultHandlerTests { HandlerResult result = handlerResult(entity, returnType); this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.OK, exchange.getResponse().getStatusCode()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.OK); assertResponseBody(exchange, "body"); } @@ -320,7 +318,7 @@ public class ResponseEntityResultHandlerTests { this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.OK, exchange.getResponse().getStatusCode()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.OK); assertResponseBody(exchange, "body"); } @@ -334,7 +332,7 @@ public class ResponseEntityResultHandlerTests { this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.NOT_FOUND, exchange.getResponse().getStatusCode()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertResponseBodyIsEmpty(exchange); } @@ -347,9 +345,9 @@ public class ResponseEntityResultHandlerTests { exchange.getResponse().getHeaders().setContentType(MediaType.TEXT_PLAIN); this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.OK, exchange.getResponse().getStatusCode()); - assertEquals(1, exchange.getResponse().getHeaders().size()); - assertEquals(MediaType.APPLICATION_JSON, exchange.getResponse().getHeaders().getContentType()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(exchange.getResponse().getHeaders().size()).isEqualTo(1); + assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON); assertResponseBodyIsEmpty(exchange); } @@ -360,8 +358,8 @@ public class ResponseEntityResultHandlerTests { HandlerResult result = handlerResult(returnValue, returnType); this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5)); - assertEquals(HttpStatus.OK, exchange.getResponse().getStatusCode()); - assertEquals("text/plain;charset=UTF-8", exchange.getResponse().getHeaders().getFirst("Content-Type")); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(exchange.getResponse().getHeaders().getFirst("Content-Type")).isEqualTo("text/plain;charset=UTF-8"); assertResponseBody(exchange, "abc"); } @@ -375,8 +373,7 @@ public class ResponseEntityResultHandlerTests { private void assertResponseBody(MockServerWebExchange exchange, String responseBody) { StepVerifier.create(exchange.getResponse().getBody()) - .consumeNextWith(buf -> assertEquals(responseBody, - DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8))) + .consumeNextWith(buf -> assertThat(DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8)).isEqualTo(responseBody)) .expectComplete() .verify(); } @@ -388,7 +385,7 @@ public class ResponseEntityResultHandlerTests { private void assertConditionalResponse(MockServerWebExchange exchange, HttpStatus status, String body, String etag, Instant lastModified) throws Exception { - assertEquals(status, exchange.getResponse().getStatusCode()); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(status); if (body != null) { assertResponseBody(exchange, body); } @@ -396,12 +393,12 @@ public class ResponseEntityResultHandlerTests { assertResponseBodyIsEmpty(exchange); } if (etag != null) { - assertEquals(1, exchange.getResponse().getHeaders().get(HttpHeaders.ETAG).size()); - assertEquals(etag, exchange.getResponse().getHeaders().getETag()); + assertThat(exchange.getResponse().getHeaders().get(HttpHeaders.ETAG).size()).isEqualTo(1); + assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo(etag); } if (lastModified.isAfter(Instant.EPOCH)) { - assertEquals(1, exchange.getResponse().getHeaders().get(HttpHeaders.LAST_MODIFIED).size()); - assertEquals(lastModified.toEpochMilli(), exchange.getResponse().getHeaders().getLastModified()); + assertThat(exchange.getResponse().getHeaders().get(HttpHeaders.LAST_MODIFIED).size()).isEqualTo(1); + assertThat(exchange.getResponse().getHeaders().getLastModified()).isEqualTo(lastModified.toEpochMilli()); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ServerWebExchangeMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ServerWebExchangeMethodArgumentResolverTests.java index b216d2ab7df..0e1334c2ea0 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ServerWebExchangeMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ServerWebExchangeMethodArgumentResolverTests.java @@ -37,11 +37,8 @@ import org.springframework.web.server.WebSession; import org.springframework.web.util.UriBuilder; import org.springframework.web.util.UriComponentsBuilder; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link ServerWebExchangeMethodArgumentResolver}. @@ -61,18 +58,18 @@ public class ServerWebExchangeMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerWebExchange.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerHttpRequest.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerHttpResponse.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(HttpMethod.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(Locale.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(TimeZone.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ZoneId.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(UriComponentsBuilder.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(UriBuilder.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(ServerWebExchange.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(ServerHttpRequest.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(ServerHttpResponse.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(HttpMethod.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(Locale.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(TimeZone.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(ZoneId.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(UriComponentsBuilder.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(UriBuilder.class))).isTrue(); - assertFalse(this.resolver.supportsParameter(this.testMethod.arg(WebSession.class))); - assertFalse(this.resolver.supportsParameter(this.testMethod.arg(String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(WebSession.class))).isFalse(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(String.class))).isFalse(); assertThatIllegalStateException().isThrownBy(() -> this.resolver.supportsParameter(this.testMethod.arg(Mono.class, ServerWebExchange.class))) .withMessageStartingWith("ServerWebExchangeMethodArgumentResolver does not support reactive type wrapper"); @@ -90,7 +87,7 @@ public class ServerWebExchangeMethodArgumentResolverTests { private void testResolveArgument(MethodParameter parameter, Object expected) { Mono mono = this.resolver.resolveArgument(parameter, new BindingContext(), this.exchange); - assertEquals(expected, mono.block()); + assertThat(mono.block()).isEqualTo(expected); } @Test @@ -98,9 +95,9 @@ public class ServerWebExchangeMethodArgumentResolverTests { MethodParameter param = this.testMethod.arg(UriComponentsBuilder.class); Object value = this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(); - assertNotNull(value); - assertEquals(UriComponentsBuilder.class, value.getClass()); - assertEquals("https://example.org:9999/next", ((UriComponentsBuilder) value).path("/next").toUriString()); + assertThat(value).isNotNull(); + assertThat(value.getClass()).isEqualTo(UriComponentsBuilder.class); + assertThat(((UriComponentsBuilder) value).path("/next").toUriString()).isEqualTo("https://example.org:9999/next"); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SessionAttributeMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SessionAttributeMethodArgumentResolverTests.java index 8c3d102705e..35aa709104c 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SessionAttributeMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SessionAttributeMethodArgumentResolverTests.java @@ -41,11 +41,7 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; import org.springframework.web.server.WebSession; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -79,8 +75,8 @@ public class SessionAttributeMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter(new MethodParameter(this.handleMethod, 0))); - assertFalse(this.resolver.supportsParameter(new MethodParameter(this.handleMethod, 4))); + assertThat(this.resolver.supportsParameter(new MethodParameter(this.handleMethod, 0))).isTrue(); + assertThat(this.resolver.supportsParameter(new MethodParameter(this.handleMethod, 4))).isFalse(); } @Test @@ -92,7 +88,7 @@ public class SessionAttributeMethodArgumentResolverTests { Foo foo = new Foo(); given(this.session.getAttribute("foo")).willReturn(foo); mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); - assertSame(foo, mono.block()); + assertThat(mono.block()).isSameAs(foo); } @Test @@ -101,19 +97,19 @@ public class SessionAttributeMethodArgumentResolverTests { Foo foo = new Foo(); given(this.session.getAttribute("specialFoo")).willReturn(foo); Mono mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); - assertSame(foo, mono.block()); + assertThat(mono.block()).isSameAs(foo); } @Test public void resolveNotRequired() { MethodParameter param = initMethodParameter(2); Mono mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); - assertNull(mono.block()); + assertThat(mono.block()).isNull(); Foo foo = new Foo(); given(this.session.getAttribute("foo")).willReturn(foo); mono = this.resolver.resolveArgument(param, new BindingContext(), this.exchange); - assertSame(foo, mono.block()); + assertThat(mono.block()).isSameAs(foo); } @SuppressWarnings("unchecked") @@ -123,8 +119,8 @@ public class SessionAttributeMethodArgumentResolverTests { Optional actual = (Optional) this.resolver .resolveArgument(param, new BindingContext(), this.exchange).block(); - assertNotNull(actual); - assertFalse(actual.isPresent()); + assertThat(actual).isNotNull(); + assertThat(actual.isPresent()).isFalse(); ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); initializer.setConversionService(new DefaultFormattingConversionService()); @@ -134,9 +130,9 @@ public class SessionAttributeMethodArgumentResolverTests { given(this.session.getAttribute("foo")).willReturn(foo); actual = (Optional) this.resolver.resolveArgument(param, bindingContext, this.exchange).block(); - assertNotNull(actual); - assertTrue(actual.isPresent()); - assertSame(foo, actual.get()); + assertThat(actual).isNotNull(); + assertThat(actual.isPresent()).isTrue(); + assertThat(actual.get()).isSameAs(foo); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SessionAttributesHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SessionAttributesHandlerTests.java index d4a0b857c8f..688245a31b9 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SessionAttributesHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SessionAttributesHandlerTests.java @@ -28,11 +28,7 @@ import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.server.WebSession; import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link SessionAttributesHandler}. @@ -46,10 +42,10 @@ public class SessionAttributesHandlerTests { @Test public void isSessionAttribute() { - assertTrue(this.sessionAttributesHandler.isHandlerSessionAttribute("attr1", String.class)); - assertTrue(this.sessionAttributesHandler.isHandlerSessionAttribute("attr2", String.class)); - assertTrue(this.sessionAttributesHandler.isHandlerSessionAttribute("simple", TestBean.class)); - assertFalse(this.sessionAttributesHandler.isHandlerSessionAttribute("simple", String.class)); + assertThat(this.sessionAttributesHandler.isHandlerSessionAttribute("attr1", String.class)).isTrue(); + assertThat(this.sessionAttributesHandler.isHandlerSessionAttribute("attr2", String.class)).isTrue(); + assertThat(this.sessionAttributesHandler.isHandlerSessionAttribute("simple", TestBean.class)).isTrue(); + assertThat(this.sessionAttributesHandler.isHandlerSessionAttribute("simple", String.class)).isFalse(); } @Test @@ -60,16 +56,12 @@ public class SessionAttributesHandlerTests { session.getAttributes().put("attr3", new TestBean()); session.getAttributes().put("attr4", new TestBean()); - assertEquals("Named attributes (attr1, attr2) should be 'known' right away", - new HashSet<>(asList("attr1", "attr2")), - sessionAttributesHandler.retrieveAttributes(session).keySet()); + assertThat(sessionAttributesHandler.retrieveAttributes(session).keySet()).as("Named attributes (attr1, attr2) should be 'known' right away").isEqualTo(new HashSet<>(asList("attr1", "attr2"))); // Resolve 'attr3' by type sessionAttributesHandler.isHandlerSessionAttribute("attr3", TestBean.class); - assertEquals("Named attributes (attr1, attr2) and resolved attribute (att3) should be 'known'", - new HashSet<>(asList("attr1", "attr2", "attr3")), - sessionAttributesHandler.retrieveAttributes(session).keySet()); + assertThat(sessionAttributesHandler.retrieveAttributes(session).keySet()).as("Named attributes (attr1, attr2) and resolved attribute (att3) should be 'known'").isEqualTo(new HashSet<>(asList("attr1", "attr2", "attr3"))); } @Test @@ -81,15 +73,15 @@ public class SessionAttributesHandlerTests { this.sessionAttributesHandler.cleanupAttributes(session); - assertNull(session.getAttributes().get("attr1")); - assertNull(session.getAttributes().get("attr2")); - assertNotNull(session.getAttributes().get("attr3")); + assertThat(session.getAttributes().get("attr1")).isNull(); + assertThat(session.getAttributes().get("attr2")).isNull(); + assertThat(session.getAttributes().get("attr3")).isNotNull(); // Resolve 'attr3' by type this.sessionAttributesHandler.isHandlerSessionAttribute("attr3", TestBean.class); this.sessionAttributesHandler.cleanupAttributes(session); - assertNull(session.getAttributes().get("attr3")); + assertThat(session.getAttributes().get("attr3")).isNull(); } @Test @@ -103,9 +95,10 @@ public class SessionAttributesHandlerTests { WebSession session = new MockWebSession(); sessionAttributesHandler.storeAttributes(session, model); - assertEquals("value1", session.getAttributes().get("attr1")); - assertEquals("value2", session.getAttributes().get("attr2")); - assertTrue(session.getAttributes().get("attr3") instanceof TestBean); + assertThat(session.getAttributes().get("attr1")).isEqualTo("value1"); + assertThat(session.getAttributes().get("attr2")).isEqualTo("value2"); + boolean condition = session.getAttributes().get("attr3") instanceof TestBean; + assertThat(condition).isTrue(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SseIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SseIntegrationTests.java index 264aa86fc53..e14cd35508f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SseIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/SseIntegrationTests.java @@ -49,8 +49,7 @@ import org.springframework.web.reactive.config.EnableWebFlux; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; import static org.springframework.http.MediaType.TEXT_EVENT_STREAM; @@ -160,18 +159,18 @@ public class SseIntegrationTests extends AbstractHttpHandlerIntegrationTests { private void verifyPersonEvents(Flux> result) { StepVerifier.create(result) .consumeNextWith( event -> { - assertEquals("0", event.id()); - assertEquals(new Person("foo 0"), event.data()); - assertEquals("bar 0", event.comment()); - assertNull(event.event()); - assertNull(event.retry()); + assertThat(event.id()).isEqualTo("0"); + assertThat(event.data()).isEqualTo(new Person("foo 0")); + assertThat(event.comment()).isEqualTo("bar 0"); + assertThat(event.event()).isNull(); + assertThat(event.retry()).isNull(); }) .consumeNextWith( event -> { - assertEquals("1", event.id()); - assertEquals(new Person("foo 1"), event.data()); - assertEquals("bar 1", event.comment()); - assertNull(event.event()); - assertNull(event.retry()); + assertThat(event.id()).isEqualTo("1"); + assertThat(event.data()).isEqualTo(new Person("foo 1")); + assertThat(event.comment()).isEqualTo("bar 1"); + assertThat(event.event()).isNull(); + assertThat(event.retry()).isNull(); }) .thenCancel() .verify(Duration.ofSeconds(5L)); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/WebSessionMethodArgumentResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/WebSessionMethodArgumentResolverTests.java index 581de97e333..8bc13e0ec22 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/WebSessionMethodArgumentResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/WebSessionMethodArgumentResolverTests.java @@ -28,9 +28,7 @@ import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebSession; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -48,9 +46,9 @@ public class WebSessionMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(WebSession.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(Mono.class, WebSession.class))); - assertTrue(this.resolver.supportsParameter(this.testMethod.arg(Single.class, WebSession.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(WebSession.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(Mono.class, WebSession.class))).isTrue(); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(Single.class, WebSession.class))).isTrue(); } @@ -64,19 +62,19 @@ public class WebSessionMethodArgumentResolverTests { MethodParameter param = this.testMethod.arg(WebSession.class); Object actual = this.resolver.resolveArgument(param, context, exchange).block(); - assertSame(session, actual); + assertThat(actual).isSameAs(session); param = this.testMethod.arg(Mono.class, WebSession.class); actual = this.resolver.resolveArgument(param, context, exchange).block(); - assertNotNull(actual); - assertTrue(Mono.class.isAssignableFrom(actual.getClass())); - assertSame(session, ((Mono) actual).block()); + assertThat(actual).isNotNull(); + assertThat(Mono.class.isAssignableFrom(actual.getClass())).isTrue(); + assertThat(((Mono) actual).block()).isSameAs(session); param = this.testMethod.arg(Single.class, WebSession.class); actual = this.resolver.resolveArgument(param, context, exchange).block(); - assertNotNull(actual); - assertTrue(Single.class.isAssignableFrom(actual.getClass())); - assertSame(session, ((Single) actual).blockingGet()); + assertThat(actual).isNotNull(); + assertThat(Single.class.isAssignableFrom(actual.getClass())).isTrue(); + assertThat(((Single) actual).blockingGet()).isSameAs(session); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/AbstractViewTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/AbstractViewTests.java index 0e770311358..f5ad6df3e31 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/AbstractViewTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/AbstractViewTests.java @@ -37,9 +37,7 @@ import org.springframework.validation.BindingResult; import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link AbstractView}. @@ -52,7 +50,6 @@ public class AbstractViewTests { @Test - @SuppressWarnings("unchecked") public void resolveAsyncAttributes() { TestBean testBean1 = new TestBean("Bean1"); @@ -71,17 +68,17 @@ public class AbstractViewTests { StepVerifier.create(view.render(inMap, null, this.exchange)).verifyComplete(); Map outMap = view.attributes; - assertEquals(testBean1, outMap.get("attr1")); - assertEquals(Arrays.asList(testBean1, testBean2), outMap.get("attr2")); - assertEquals(testBean2, outMap.get("attr3")); - assertEquals(Arrays.asList(testBean1, testBean2), outMap.get("attr4")); - assertNull(outMap.get("attr5")); + assertThat(outMap.get("attr1")).isEqualTo(testBean1); + assertThat(outMap.get("attr2")).isEqualTo(Arrays.asList(testBean1, testBean2)); + assertThat(outMap.get("attr3")).isEqualTo(testBean2); + assertThat(outMap.get("attr4")).isEqualTo(Arrays.asList(testBean1, testBean2)); + assertThat(outMap.get("attr5")).isNull(); - assertNotNull(outMap.get(BindingResult.MODEL_KEY_PREFIX + "attr1")); - assertNotNull(outMap.get(BindingResult.MODEL_KEY_PREFIX + "attr3")); - assertNull(outMap.get(BindingResult.MODEL_KEY_PREFIX + "attr2")); - assertNull(outMap.get(BindingResult.MODEL_KEY_PREFIX + "attr4")); - assertNull(outMap.get(BindingResult.MODEL_KEY_PREFIX + "attr5")); + assertThat(outMap.get(BindingResult.MODEL_KEY_PREFIX + "attr1")).isNotNull(); + assertThat(outMap.get(BindingResult.MODEL_KEY_PREFIX + "attr3")).isNotNull(); + assertThat(outMap.get(BindingResult.MODEL_KEY_PREFIX + "attr2")).isNull(); + assertThat(outMap.get(BindingResult.MODEL_KEY_PREFIX + "attr4")).isNull(); + assertThat(outMap.get(BindingResult.MODEL_KEY_PREFIX + "attr5")).isNull(); } private static class TestView extends AbstractView { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/DefaultRenderingBuilderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/DefaultRenderingBuilderTests.java index a955bea2298..e50581b09af 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/DefaultRenderingBuilderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/DefaultRenderingBuilderTests.java @@ -24,10 +24,7 @@ import org.junit.Test; import org.springframework.http.HttpHeaders; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link DefaultRenderingBuilder}. @@ -40,10 +37,10 @@ public class DefaultRenderingBuilderTests { public void defaultValues() { Rendering rendering = Rendering.view("abc").build(); - assertEquals("abc", rendering.view()); - assertEquals(Collections.emptyMap(), rendering.modelAttributes()); - assertNull(rendering.status()); - assertEquals(0, rendering.headers().size()); + assertThat(rendering.view()).isEqualTo("abc"); + assertThat(rendering.modelAttributes()).isEqualTo(Collections.emptyMap()); + assertThat(rendering.status()).isNull(); + assertThat(rendering.headers().size()).isEqualTo(0); } @Test @@ -51,17 +48,17 @@ public class DefaultRenderingBuilderTests { Rendering rendering = Rendering.redirectTo("abc").build(); Object view = rendering.view(); - assertEquals(RedirectView.class, view.getClass()); - assertEquals("abc", ((RedirectView) view).getUrl()); - assertTrue(((RedirectView) view).isContextRelative()); - assertFalse(((RedirectView) view).isPropagateQuery()); + assertThat(view.getClass()).isEqualTo(RedirectView.class); + assertThat(((RedirectView) view).getUrl()).isEqualTo("abc"); + assertThat(((RedirectView) view).isContextRelative()).isTrue(); + assertThat(((RedirectView) view).isPropagateQuery()).isFalse(); } @Test public void viewName() { Rendering rendering = Rendering.view("foo").build(); - assertEquals("foo", rendering.view()); + assertThat(rendering.view()).isEqualTo("foo"); } @Test @@ -69,7 +66,7 @@ public class DefaultRenderingBuilderTests { Foo foo = new Foo(); Rendering rendering = Rendering.view("foo").modelAttribute(foo).build(); - assertEquals(Collections.singletonMap("foo", foo), rendering.modelAttributes()); + assertThat(rendering.modelAttributes()).isEqualTo(Collections.singletonMap("foo", foo)); } @Test @@ -81,7 +78,7 @@ public class DefaultRenderingBuilderTests { Map map = new LinkedHashMap<>(2); map.put("foo", foo); map.put("bar", bar); - assertEquals(map, rendering.modelAttributes()); + assertThat(rendering.modelAttributes()).isEqualTo(map); } @Test @@ -91,15 +88,15 @@ public class DefaultRenderingBuilderTests { map.put("bar", new Bar()); Rendering rendering = Rendering.view("foo").model(map).build(); - assertEquals(map, rendering.modelAttributes()); + assertThat(rendering.modelAttributes()).isEqualTo(map); } @Test public void header() throws Exception { Rendering rendering = Rendering.view("foo").header("foo", "bar").build(); - assertEquals(1, rendering.headers().size()); - assertEquals(Collections.singletonList("bar"), rendering.headers().get("foo")); + assertThat(rendering.headers().size()).isEqualTo(1); + assertThat(rendering.headers().get("foo")).isEqualTo(Collections.singletonList("bar")); } @Test @@ -108,7 +105,7 @@ public class DefaultRenderingBuilderTests { headers.add("foo", "bar"); Rendering rendering = Rendering.view("foo").headers(headers).build(); - assertEquals(headers, rendering.headers()); + assertThat(rendering.headers()).isEqualTo(headers); } @Test @@ -116,8 +113,8 @@ public class DefaultRenderingBuilderTests { Rendering rendering = Rendering.redirectTo("foo").contextRelative(false).build(); Object view = rendering.view(); - assertEquals(RedirectView.class, view.getClass()); - assertFalse(((RedirectView) view).isContextRelative()); + assertThat(view.getClass()).isEqualTo(RedirectView.class); + assertThat(((RedirectView) view).isContextRelative()).isFalse(); } @Test @@ -125,8 +122,8 @@ public class DefaultRenderingBuilderTests { Rendering rendering = Rendering.redirectTo("foo").propagateQuery(true).build(); Object view = rendering.view(); - assertEquals(RedirectView.class, view.getClass()); - assertTrue(((RedirectView) view).isPropagateQuery()); + assertThat(view.getClass()).isEqualTo(RedirectView.class); + assertThat(((RedirectView) view).isPropagateQuery()).isTrue(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/HttpMessageWriterViewTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/HttpMessageWriterViewTests.java index 762322abe89..7684e6415af 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/HttpMessageWriterViewTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/HttpMessageWriterViewTests.java @@ -38,8 +38,8 @@ import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.ModelMap; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link HttpMessageWriterView}. @@ -56,10 +56,9 @@ public class HttpMessageWriterViewTests { @Test public void supportedMediaTypes() throws Exception { - assertEquals(Arrays.asList( + assertThat(this.view.getSupportedMediaTypes()).isEqualTo(Arrays.asList( MediaType.APPLICATION_JSON, - MediaType.parseMediaType("application/*+json")), - this.view.getSupportedMediaTypes()); + MediaType.parseMediaType("application/*+json"))); } @Test @@ -69,7 +68,7 @@ public class HttpMessageWriterViewTests { this.model.addAttribute("foo2", Collections.singleton("bar2")); this.model.addAttribute("foo3", Collections.singleton("bar3")); - assertEquals("[\"bar2\"]", doRender()); + assertThat(doRender()).isEqualTo("[\"bar2\"]"); } @Test @@ -77,7 +76,7 @@ public class HttpMessageWriterViewTests { this.view.setModelKeys(Collections.singleton("foo2")); this.model.addAttribute("foo1", "bar1"); - assertEquals("", doRender()); + assertThat(doRender()).isEqualTo(""); } @Test @@ -86,7 +85,7 @@ public class HttpMessageWriterViewTests { this.view.setModelKeys(new HashSet<>(Collections.singletonList("foo1"))); this.model.addAttribute("foo1", "bar1"); - assertEquals("", doRender()); + assertThat(doRender()).isEqualTo(""); } @Test @@ -96,7 +95,7 @@ public class HttpMessageWriterViewTests { this.model.addAttribute("foo2", Collections.singleton("bar2")); this.model.addAttribute("foo3", Collections.singleton("bar3")); - assertEquals("{\"foo1\":[\"bar1\"],\"foo2\":[\"bar2\"]}", doRender()); + assertThat(doRender()).isEqualTo("{\"foo1\":[\"bar1\"],\"foo2\":[\"bar2\"]}"); } @Test @@ -122,7 +121,7 @@ public class HttpMessageWriterViewTests { this.view.render(this.model, MediaType.APPLICATION_JSON, exchange).block(Duration.ZERO); StepVerifier.create(this.exchange.getResponse().getBody()) - .consumeNextWith(buf -> assertEquals("{\"foo\":\"f\",\"bar\":\"b\"}", dumpString(buf))) + .consumeNextWith(buf -> assertThat(dumpString(buf)).isEqualTo("{\"foo\":\"f\",\"bar\":\"b\"}")) .expectComplete() .verify(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/LocaleContextResolverIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/LocaleContextResolverIntegrationTests.java index c6b1439159a..efd9ec6983f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/LocaleContextResolverIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/LocaleContextResolverIntegrationTests.java @@ -43,7 +43,7 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.i18n.FixedLocaleContextResolver; import org.springframework.web.server.i18n.LocaleContextResolver; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Sebastien Deleuze @@ -70,8 +70,8 @@ public class LocaleContextResolverIntegrationTests extends AbstractRequestMappin StepVerifier.create(result) .consumeNextWith(response -> { - assertEquals(HttpStatus.OK, response.statusCode()); - assertEquals(Locale.GERMANY, response.headers().asHttpHeaders().getContentLanguage()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.headers().asHttpHeaders().getContentLanguage()).isEqualTo(Locale.GERMANY); }) .verifyComplete(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RedirectViewTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RedirectViewTests.java index b7c43a8f916..37782f9be7a 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RedirectViewTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RedirectViewTests.java @@ -30,10 +30,8 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; import org.springframework.web.reactive.HandlerMapping; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Tests for redirect view, and query string construction. @@ -64,8 +62,8 @@ public class RedirectViewTests { String url = "https://url.somewhere.com"; RedirectView view = new RedirectView(url); view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block(); - assertEquals(HttpStatus.SEE_OTHER, this.exchange.getResponse().getStatusCode()); - assertEquals(URI.create(url), this.exchange.getResponse().getHeaders().getLocation()); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.SEE_OTHER); + assertThat(this.exchange.getResponse().getHeaders().getLocation()).isEqualTo(URI.create(url)); } @Test @@ -73,8 +71,8 @@ public class RedirectViewTests { String url = "https://url.somewhere.com"; RedirectView view = new RedirectView(url, HttpStatus.FOUND); view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block(); - assertEquals(HttpStatus.FOUND, this.exchange.getResponse().getStatusCode()); - assertEquals(URI.create(url), this.exchange.getResponse().getHeaders().getLocation()); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FOUND); + assertThat(this.exchange.getResponse().getHeaders().getLocation()).isEqualTo(URI.create(url)); } @Test @@ -82,7 +80,7 @@ public class RedirectViewTests { String url = "/test.html"; RedirectView view = new RedirectView(url); view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block(); - assertEquals(URI.create("/context/test.html"), this.exchange.getResponse().getHeaders().getLocation()); + assertThat(this.exchange.getResponse().getHeaders().getLocation()).isEqualTo(URI.create("/context/test.html")); } @Test @@ -90,22 +88,22 @@ public class RedirectViewTests { String url = "/test.html?id=1"; RedirectView view = new RedirectView(url); view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block(); - assertEquals(URI.create("/context/test.html?id=1"), this.exchange.getResponse().getHeaders().getLocation()); + assertThat(this.exchange.getResponse().getHeaders().getLocation()).isEqualTo(URI.create("/context/test.html?id=1")); } @Test public void remoteHost() { RedirectView view = new RedirectView(""); - assertFalse(view.isRemoteHost("https://url.somewhere.com")); - assertFalse(view.isRemoteHost("/path")); - assertFalse(view.isRemoteHost("http://url.somewhereelse.com")); + assertThat(view.isRemoteHost("https://url.somewhere.com")).isFalse(); + assertThat(view.isRemoteHost("/path")).isFalse(); + assertThat(view.isRemoteHost("http://url.somewhereelse.com")).isFalse(); view.setHosts("url.somewhere.com"); - assertFalse(view.isRemoteHost("https://url.somewhere.com")); - assertFalse(view.isRemoteHost("/path")); - assertTrue(view.isRemoteHost("http://url.somewhereelse.com")); + assertThat(view.isRemoteHost("https://url.somewhere.com")).isFalse(); + assertThat(view.isRemoteHost("/path")).isFalse(); + assertThat(view.isRemoteHost("http://url.somewhereelse.com")).isTrue(); } @Test @@ -114,7 +112,7 @@ public class RedirectViewTests { Map model = Collections.singletonMap("foo", "bar"); RedirectView view = new RedirectView(url); view.render(model, MediaType.TEXT_HTML, this.exchange).block(); - assertEquals(URI.create("https://url.somewhere.com?foo=bar"), this.exchange.getResponse().getHeaders().getLocation()); + assertThat(this.exchange.getResponse().getHeaders().getLocation()).isEqualTo(URI.create("https://url.somewhere.com?foo=bar")); } @Test @@ -124,7 +122,7 @@ public class RedirectViewTests { this.exchange.getAttributes().put(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, attributes); RedirectView view = new RedirectView(url); view.render(new HashMap<>(), MediaType.TEXT_HTML, exchange).block(); - assertEquals(URI.create("https://url.somewhere.com?foo=bar"), this.exchange.getResponse().getHeaders().getLocation()); + assertThat(this.exchange.getResponse().getHeaders().getLocation()).isEqualTo(URI.create("https://url.somewhere.com?foo=bar")); } @Test @@ -133,9 +131,8 @@ public class RedirectViewTests { view.setPropagateQuery(true); this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("https://url.somewhere.com?a=b&c=d")); view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block(); - assertEquals(HttpStatus.SEE_OTHER, this.exchange.getResponse().getStatusCode()); - assertEquals(URI.create("https://url.somewhere.com?foo=bar&a=b&c=d#bazz"), - this.exchange.getResponse().getHeaders().getLocation()); + assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.SEE_OTHER); + assertThat(this.exchange.getResponse().getHeaders().getLocation()).isEqualTo(URI.create("https://url.somewhere.com?foo=bar&a=b&c=d#bazz")); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RequestContextTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RequestContextTests.java index 0bfb7568c69..1831e22b55e 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RequestContextTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/RequestContextTests.java @@ -26,7 +26,7 @@ import org.springframework.context.support.GenericApplicationContext; import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.web.test.server.MockServerWebExchange; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link RequestContext}. @@ -51,7 +51,7 @@ public class RequestContextTests { @Test public void testGetContextUrl() throws Exception { RequestContext context = new RequestContext(this.exchange, this.model, this.applicationContext); - assertEquals("/foo/bar", context.getContextUrl("bar")); + assertThat(context.getContextUrl("bar")).isEqualTo("/foo/bar"); } @Test @@ -60,7 +60,7 @@ public class RequestContextTests { Map map = new HashMap<>(); map.put("foo", "bar"); map.put("spam", "bucket"); - assertEquals("/foo/bar?spam=bucket", context.getContextUrl("{foo}?spam={spam}", map)); + assertThat(context.getContextUrl("{foo}?spam={spam}", map)).isEqualTo("/foo/bar?spam=bucket"); } @Test @@ -69,7 +69,7 @@ public class RequestContextTests { Map map = new HashMap<>(); map.put("foo", "bar baz"); map.put("spam", "&bucket="); - assertEquals("/foo/bar%20baz?spam=%26bucket%3D", context.getContextUrl("{foo}?spam={spam}", map)); + assertThat(context.getContextUrl("{foo}?spam={spam}", map)).isEqualTo("/foo/bar%20baz?spam=%26bucket%3D"); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/UrlBasedViewResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/UrlBasedViewResolverTests.java index d2c9ba50f6c..44e08d78ade 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/UrlBasedViewResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/UrlBasedViewResolverTests.java @@ -30,9 +30,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.server.ServerWebExchange; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link UrlBasedViewResolver}. @@ -60,10 +58,10 @@ public class UrlBasedViewResolverTests { this.resolver.setViewNames("my*"); Mono mono = this.resolver.resolveViewName("my-view", Locale.US); - assertNotNull(mono.block()); + assertThat(mono.block()).isNotNull(); mono = this.resolver.resolveViewName("not-my-view", Locale.US); - assertNull(mono.block()); + assertThat(mono.block()).isNull(); } @Test @@ -72,10 +70,10 @@ public class UrlBasedViewResolverTests { StepVerifier.create(mono) .consumeNextWith(view -> { - assertEquals(RedirectView.class, view.getClass()); + assertThat(view.getClass()).isEqualTo(RedirectView.class); RedirectView redirectView = (RedirectView) view; - assertEquals("foo", redirectView.getUrl()); - assertEquals(HttpStatus.SEE_OTHER, redirectView.getStatusCode()); + assertThat(redirectView.getUrl()).isEqualTo("foo"); + assertThat(redirectView.getStatusCode()).isEqualTo(HttpStatus.SEE_OTHER); }) .expectComplete() .verify(Duration.ZERO); @@ -88,10 +86,10 @@ public class UrlBasedViewResolverTests { StepVerifier.create(mono) .consumeNextWith(view -> { - assertEquals(RedirectView.class, view.getClass()); + assertThat(view.getClass()).isEqualTo(RedirectView.class); RedirectView redirectView = (RedirectView) view; - assertEquals("foo", redirectView.getUrl()); - assertEquals(HttpStatus.FOUND, redirectView.getStatusCode()); + assertThat(redirectView.getUrl()).isEqualTo("foo"); + assertThat(redirectView.getStatusCode()).isEqualTo(HttpStatus.FOUND); }) .expectComplete() .verify(Duration.ZERO); diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandlerTests.java index 858460c4e3a..bc60e853914 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandlerTests.java @@ -56,7 +56,7 @@ import org.springframework.web.server.NotAcceptableStatusException; import org.springframework.web.server.ServerWebExchange; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get; @@ -114,7 +114,7 @@ public class ViewResolutionResultHandlerTests { private void testSupports(MethodParameter returnType, boolean supports) { ViewResolutionResultHandler resultHandler = resultHandler(mock(ViewResolver.class)); HandlerResult handlerResult = new HandlerResult(new Object(), null, returnType, this.bindingContext); - assertEquals(supports, resultHandler.supports(handlerResult)); + assertThat(resultHandler.supports(handlerResult)).isEqualTo(supports); } @Test @@ -125,7 +125,7 @@ public class ViewResolutionResultHandlerTests { resolver2.setOrder(1); List resolvers = resultHandler(resolver1, resolver2).getViewResolvers(); - assertEquals(Arrays.asList(resolver2, resolver1), resolvers); + assertThat(resolvers).isEqualTo(Arrays.asList(resolver2, resolver1)); } @Test @@ -188,8 +188,8 @@ public class ViewResolutionResultHandlerTests { returnValue = Rendering.view("account").modelAttribute("a", "a1").status(status).header("h", "h1").build(); String expected = "account: {a=a1, id=123}"; ServerWebExchange exchange = testHandle("/path", returnType, returnValue, expected, resolver); - assertEquals(status, exchange.getResponse().getStatusCode()); - assertEquals("h1", exchange.getResponse().getHeaders().getFirst("h")); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(status); + assertThat(exchange.getResponse().getHeaders().getFirst("h")).isEqualTo("h1"); } @Test @@ -255,7 +255,7 @@ public class ViewResolutionResultHandlerTests { .handleResult(exchange, handlerResult) .block(Duration.ofSeconds(5)); - assertEquals(APPLICATION_JSON, exchange.getResponse().getHeaders().getContentType()); + assertThat(exchange.getResponse().getHeaders().getContentType()).isEqualTo(APPLICATION_JSON); assertResponseBody(exchange, "jsonView: {" + "org.springframework.validation.BindingResult.testBean=" + "org.springframework.validation.BeanPropertyBindingResult: 0 errors, " + @@ -293,8 +293,8 @@ public class ViewResolutionResultHandlerTests { resultHandler.handleResult(exchange, handlerResult).block(Duration.ZERO); MockServerHttpResponse response = exchange.getResponse(); - assertEquals(303, response.getStatusCode().value()); - assertEquals("/", response.getHeaders().getLocation().toString()); + assertThat(response.getStatusCode().value()).isEqualTo(303); + assertThat(response.getHeaders().getLocation().toString()).isEqualTo("/"); } @@ -325,7 +325,7 @@ public class ViewResolutionResultHandlerTests { private void assertResponseBody(MockServerWebExchange exchange, String responseBody) { StepVerifier.create(exchange.getResponse().getBody()) - .consumeNextWith(buf -> assertEquals(responseBody, DataBufferTestUtils.dumpString(buf, UTF_8))) + .consumeNextWith(buf -> assertThat(DataBufferTestUtils.dumpString(buf, UTF_8)).isEqualTo(responseBody)) .expectComplete() .verify(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/freemarker/FreeMarkerViewTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/freemarker/FreeMarkerViewTests.java index b8371c32d0c..e8cd4e902e5 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/freemarker/FreeMarkerViewTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/freemarker/FreeMarkerViewTests.java @@ -40,10 +40,9 @@ import org.springframework.web.server.adapter.DefaultServerWebExchange; import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; import org.springframework.web.server.session.DefaultWebSessionManager; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Rossen Stoyanchev @@ -99,7 +98,7 @@ public class FreeMarkerViewTests { view.setConfiguration(this.freeMarkerConfig); view.setUrl("test.ftl"); - assertTrue(view.checkResourceExists(Locale.US)); + assertThat(view.checkResourceExists(Locale.US)).isTrue(); } @Test @@ -113,7 +112,7 @@ public class FreeMarkerViewTests { view.render(model, null, this.exchange).block(Duration.ofMillis(5000)); StepVerifier.create(this.exchange.getResponse().getBody()) - .consumeNextWith(buf -> assertEquals("hi FreeMarker", asString(buf))) + .consumeNextWith(buf -> assertThat(asString(buf)).isEqualTo("hi FreeMarker")) .expectComplete() .verify(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/JRubyScriptTemplateTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/JRubyScriptTemplateTests.java index 87842121391..5e8042f621c 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/JRubyScriptTemplateTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/JRubyScriptTemplateTests.java @@ -30,7 +30,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse; import org.springframework.mock.web.test.server.MockServerWebExchange; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for ERB templates running on JRuby. @@ -47,8 +47,7 @@ public class JRubyScriptTemplateTests { model.put("body", "This is the body"); String url = "org/springframework/web/reactive/result/view/script/jruby/template.erb"; MockServerHttpResponse response = renderViewWithModel(url, model); - assertEquals("Layout example

This is the body

", - response.getBodyAsString().block()); + assertThat(response.getBodyAsString().block()).isEqualTo("Layout example

This is the body

"); } private MockServerHttpResponse renderViewWithModel(String viewUrl, Map model) throws Exception { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/JythonScriptTemplateTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/JythonScriptTemplateTests.java index 04d8eec2304..bb7c261fe0b 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/JythonScriptTemplateTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/JythonScriptTemplateTests.java @@ -29,7 +29,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse; import org.springframework.mock.web.test.server.MockServerWebExchange; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for String templates running on Jython. @@ -45,8 +45,7 @@ public class JythonScriptTemplateTests { model.put("body", "This is the body"); String url = "org/springframework/web/reactive/result/view/script/jython/template.html"; MockServerHttpResponse response = renderViewWithModel(url, model); - assertEquals("Layout example

This is the body

", - response.getBodyAsString().block()); + assertThat(response.getBodyAsString().block()).isEqualTo("Layout example

This is the body

"); } private MockServerHttpResponse renderViewWithModel(String viewUrl, Map model) throws Exception { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/KotlinScriptTemplateTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/KotlinScriptTemplateTests.java index 89a9427c081..1cb9e1ebb34 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/KotlinScriptTemplateTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/KotlinScriptTemplateTests.java @@ -32,7 +32,7 @@ import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse; import org.springframework.mock.web.test.server.MockServerWebExchange; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for Kotlin script templates running on Kotlin JSR-223 support. @@ -48,7 +48,7 @@ public class KotlinScriptTemplateTests { model.put("foo", "Foo"); String url = "org/springframework/web/reactive/result/view/script/kotlin/template.kts"; MockServerHttpResponse response = render(url, model, Locale.FRENCH, ScriptTemplatingConfiguration.class); - assertEquals("\n

Bonjour Foo

\n", response.getBodyAsString().block()); + assertThat(response.getBodyAsString().block()).isEqualTo("\n

Bonjour Foo

\n"); } @Ignore @@ -58,7 +58,7 @@ public class KotlinScriptTemplateTests { model.put("foo", "Foo"); String url = "org/springframework/web/reactive/result/view/script/kotlin/template.kts"; MockServerHttpResponse response = render(url, model, Locale.ENGLISH, ScriptTemplatingConfiguration.class); - assertEquals("\n

Hello Foo

\n", response.getBodyAsString().block()); + assertThat(response.getBodyAsString().block()).isEqualTo("\n

Hello Foo

\n"); } @Ignore @@ -72,8 +72,7 @@ public class KotlinScriptTemplateTests { String url = "org/springframework/web/reactive/result/view/script/kotlin/eval.kts"; Class configClass = ScriptTemplatingConfigurationWithoutRenderFunction.class; MockServerHttpResponse response = render(url, model, Locale.ENGLISH, configClass); - assertEquals("\n

Hello Foo

\n", - response.getBodyAsString().block()); + assertThat(response.getBodyAsString().block()).isEqualTo("\n

Hello Foo

\n"); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/NashornScriptTemplateTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/NashornScriptTemplateTests.java index bf23b96ceb8..719fe4bfb48 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/NashornScriptTemplateTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/NashornScriptTemplateTests.java @@ -35,7 +35,7 @@ import org.springframework.web.server.adapter.DefaultServerWebExchange; import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; import org.springframework.web.server.session.DefaultWebSessionManager; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for pure JavaScript templates running on Nashorn engine. @@ -51,8 +51,7 @@ public class NashornScriptTemplateTests { model.put("body", "This is the body"); String url = "org/springframework/web/reactive/result/view/script/nashorn/template.html"; MockServerHttpResponse response = render(url, model, ScriptTemplatingConfiguration.class); - assertEquals("Layout example

This is the body

", - response.getBodyAsString().block()); + assertThat(response.getBodyAsString().block()).isEqualTo("Layout example

This is the body

"); } @Test // SPR-13453 @@ -60,8 +59,7 @@ public class NashornScriptTemplateTests { String url = "org/springframework/web/reactive/result/view/script/nashorn/template.html"; Class configClass = ScriptTemplatingWithUrlConfiguration.class; MockServerHttpResponse response = render(url, null, configClass); - assertEquals("Check url parameter

" + url + "

", - response.getBodyAsString().block()); + assertThat(response.getBodyAsString().block()).isEqualTo(("Check url parameter

" + url + "

")); } @Test // gh-22754 diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/ScriptTemplateViewResolverTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/ScriptTemplateViewResolverTests.java index e77bbedfdd5..029e1f5bf8a 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/ScriptTemplateViewResolverTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/ScriptTemplateViewResolverTests.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ScriptTemplateViewResolver}. @@ -32,10 +32,10 @@ public class ScriptTemplateViewResolverTests { @Test public void viewClass() throws Exception { ScriptTemplateViewResolver resolver = new ScriptTemplateViewResolver(); - assertEquals(ScriptTemplateView.class, resolver.requiredViewClass()); + assertThat(resolver.requiredViewClass()).isEqualTo(ScriptTemplateView.class); DirectFieldAccessor viewAccessor = new DirectFieldAccessor(resolver); Class viewClass = (Class) viewAccessor.getPropertyValue("viewClass"); - assertEquals(ScriptTemplateView.class, viewClass); + assertThat(viewClass).isEqualTo(ScriptTemplateView.class); } } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/ScriptTemplateViewTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/ScriptTemplateViewTests.java index f3eee9b881a..fdacfcfd6e2 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/ScriptTemplateViewTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/ScriptTemplateViewTests.java @@ -33,13 +33,9 @@ import org.springframework.beans.DirectFieldAccessor; import org.springframework.context.ApplicationContextException; import org.springframework.context.support.StaticApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -74,7 +70,7 @@ public class ScriptTemplateViewTests { this.view.setEngine(mock(InvocableScriptEngine.class)); this.configurer.setRenderFunction("render"); this.view.setApplicationContext(this.context); - assertFalse(this.view.checkResourceExists(Locale.ENGLISH)); + assertThat(this.view.checkResourceExists(Locale.ENGLISH)).isFalse(); } @Test @@ -95,11 +91,11 @@ public class ScriptTemplateViewTests { DirectFieldAccessor accessor = new DirectFieldAccessor(this.view); this.view.setApplicationContext(this.context); - assertEquals(engine, accessor.getPropertyValue("engine")); - assertEquals("Template", accessor.getPropertyValue("renderObject")); - assertEquals("render", accessor.getPropertyValue("renderFunction")); - assertEquals(StandardCharsets.ISO_8859_1, accessor.getPropertyValue("defaultCharset")); - assertEquals(true, accessor.getPropertyValue("sharedEngine")); + assertThat(accessor.getPropertyValue("engine")).isEqualTo(engine); + assertThat(accessor.getPropertyValue("renderObject")).isEqualTo("Template"); + assertThat(accessor.getPropertyValue("renderFunction")).isEqualTo("render"); + assertThat(accessor.getPropertyValue("defaultCharset")).isEqualTo(StandardCharsets.ISO_8859_1); + assertThat(accessor.getPropertyValue("sharedEngine")).isEqualTo(true); } @Test @@ -110,11 +106,11 @@ public class ScriptTemplateViewTests { DirectFieldAccessor accessor = new DirectFieldAccessor(this.view); this.view.setApplicationContext(this.context); - assertEquals("nashorn", accessor.getPropertyValue("engineName")); - assertNotNull(accessor.getPropertyValue("engine")); - assertEquals("Template", accessor.getPropertyValue("renderObject")); - assertEquals("render", accessor.getPropertyValue("renderFunction")); - assertEquals(StandardCharsets.UTF_8, accessor.getPropertyValue("defaultCharset")); + assertThat(accessor.getPropertyValue("engineName")).isEqualTo("nashorn"); + assertThat(accessor.getPropertyValue("engine")).isNotNull(); + assertThat(accessor.getPropertyValue("renderObject")).isEqualTo("Template"); + assertThat(accessor.getPropertyValue("renderFunction")).isEqualTo("render"); + assertThat(accessor.getPropertyValue("defaultCharset")).isEqualTo(StandardCharsets.UTF_8); } @Test @@ -125,12 +121,12 @@ public class ScriptTemplateViewTests { this.view.setRenderFunction("render"); this.view.setApplicationContext(this.context); engine = this.view.getEngine(); - assertNotNull(engine); - assertEquals("value", engine.get("key")); + assertThat(engine).isNotNull(); + assertThat(engine.get("key")).isEqualTo("value"); DirectFieldAccessor accessor = new DirectFieldAccessor(this.view); - assertNull(accessor.getPropertyValue("renderObject")); - assertEquals("render", accessor.getPropertyValue("renderFunction")); - assertEquals(StandardCharsets.UTF_8, accessor.getPropertyValue("defaultCharset")); + assertThat(accessor.getPropertyValue("renderObject")).isNull(); + assertThat(accessor.getPropertyValue("renderFunction")).isEqualTo("render"); + assertThat(accessor.getPropertyValue("defaultCharset")).isEqualTo(StandardCharsets.UTF_8); } @Test @@ -145,9 +141,9 @@ public class ScriptTemplateViewTests { for (int i = 0; i < iterations; i++) { results.add(executor.submit(() -> view.getEngine() != null)); } - assertEquals(iterations, results.size()); + assertThat(results.size()).isEqualTo(iterations); for (int i = 0; i < iterations; i++) { - assertTrue(results.get(i).get()); + assertThat((boolean) results.get(i).get()).isTrue(); } executor.shutdown(); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/socket/WebSocketIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/socket/WebSocketIntegrationTests.java index 106c7dcfd95..f40381d2400 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/socket/WebSocketIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/socket/WebSocketIntegrationTests.java @@ -38,7 +38,6 @@ import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Integration tests with server-side {@link WebSocketHandler}s. @@ -71,7 +70,7 @@ public class WebSocketIntegrationTests extends AbstractWebSocketIntegrationTests .then()) .block(TIMEOUT); - assertEquals(input.collectList().block(TIMEOUT), output.collectList().block(TIMEOUT)); + assertThat(output.collectList().block(TIMEOUT)).isEqualTo(input.collectList().block(TIMEOUT)); } @Test @@ -99,9 +98,9 @@ public class WebSocketIntegrationTests extends AbstractWebSocketIntegrationTests HandshakeInfo info = infoRef.get(); assertThat(info.getHeaders().getFirst("Upgrade")).isEqualToIgnoringCase("websocket"); - assertEquals(protocol, info.getHeaders().getFirst("Sec-WebSocket-Protocol")); - assertEquals("Wrong protocol accepted", protocol, info.getSubProtocol()); - assertEquals("Wrong protocol detected on the server side", protocol, output.block(TIMEOUT)); + assertThat(info.getHeaders().getFirst("Sec-WebSocket-Protocol")).isEqualTo(protocol); + assertThat(info.getSubProtocol()).as("Wrong protocol accepted").isEqualTo(protocol); + assertThat(output.block(TIMEOUT)).as("Wrong protocol detected on the server side").isEqualTo(protocol); } @Test @@ -117,7 +116,7 @@ public class WebSocketIntegrationTests extends AbstractWebSocketIntegrationTests .then()) .block(TIMEOUT); - assertEquals("my-header:my-value", output.block(TIMEOUT)); + assertThat(output.block(TIMEOUT)).isEqualTo("my-header:my-value"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/socket/server/support/HandshakeWebSocketServiceTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/socket/server/support/HandshakeWebSocketServiceTests.java index c463211d1bc..75873929f77 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/socket/server/support/HandshakeWebSocketServiceTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/socket/server/support/HandshakeWebSocketServiceTests.java @@ -33,7 +33,6 @@ import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; /** @@ -62,7 +61,7 @@ public class HandshakeWebSocketServiceTests { service.handleRequest(exchange, mock(WebSocketHandler.class)).block(); HandshakeInfo info = upgradeStrategy.handshakeInfo; - assertNotNull(info); + assertThat(info).isNotNull(); Map attributes = info.getAttributes(); assertThat(attributes) diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/ContextLoaderTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/ContextLoaderTests.java index 56e66836c82..7f94bd7af08 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/ContextLoaderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/ContextLoaderTests.java @@ -47,11 +47,6 @@ import org.springframework.web.servlet.SimpleWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertTrue; /** * Tests for {@link ContextLoader} and {@link ContextLoaderListener}. @@ -75,19 +70,21 @@ public class ContextLoaderTests { listener.contextInitialized(event); String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE; WebApplicationContext context = (WebApplicationContext) sc.getAttribute(contextAttr); - assertTrue("Correct WebApplicationContext exposed in ServletContext", context instanceof XmlWebApplicationContext); - assertTrue(WebApplicationContextUtils.getRequiredWebApplicationContext(sc) instanceof XmlWebApplicationContext); + boolean condition1 = context instanceof XmlWebApplicationContext; + assertThat(condition1).as("Correct WebApplicationContext exposed in ServletContext").isTrue(); + assertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(sc) instanceof XmlWebApplicationContext).isTrue(); LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle"); - assertTrue("Has father", context.containsBean("father")); - assertTrue("Has rod", context.containsBean("rod")); - assertTrue("Has kerry", context.containsBean("kerry")); - assertTrue("Not destroyed", !lb.isDestroyed()); - assertFalse(context.containsBean("beans1.bean1")); - assertFalse(context.containsBean("beans1.bean2")); + assertThat(context.containsBean("father")).as("Has father").isTrue(); + assertThat(context.containsBean("rod")).as("Has rod").isTrue(); + assertThat(context.containsBean("kerry")).as("Has kerry").isTrue(); + boolean condition = !lb.isDestroyed(); + assertThat(condition).as("Not destroyed").isTrue(); + assertThat(context.containsBean("beans1.bean1")).isFalse(); + assertThat(context.containsBean("beans1.bean2")).isFalse(); listener.contextDestroyed(event); - assertTrue("Destroyed", lb.isDestroyed()); - assertNull(sc.getAttribute(contextAttr)); - assertNull(WebApplicationContextUtils.getWebApplicationContext(sc)); + assertThat(lb.isDestroyed()).as("Destroyed").isTrue(); + assertThat(sc.getAttribute(contextAttr)).isNull(); + assertThat(WebApplicationContextUtils.getWebApplicationContext(sc)).isNull(); } /** @@ -106,14 +103,14 @@ public class ContextLoaderTests { ServletContextListener listener = new ContextLoaderListener() { @Override protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) { - assertNotNull("The ServletContext should not be null.", sc); - assertEquals("Verifying that we received the expected ServletContext.", sc, sc); - assertFalse("The ApplicationContext should not yet have been refreshed.", wac.isActive()); + assertThat(sc).as("The ServletContext should not be null.").isNotNull(); + assertThat(sc).as("Verifying that we received the expected ServletContext.").isEqualTo(sc); + assertThat(wac.isActive()).as("The ApplicationContext should not yet have been refreshed.").isFalse(); buffer.append(expectedContents); } }; listener.contextInitialized(new ServletContextEvent(sc)); - assertEquals("customizeContext() should have been called.", expectedContents, buffer.toString()); + assertThat(buffer.toString()).as("customizeContext() should have been called.").isEqualTo(expectedContents); } @Test @@ -243,8 +240,8 @@ public class ContextLoaderTests { listener.contextInitialized(event); String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE; WebApplicationContext wc = (WebApplicationContext) sc.getAttribute(contextAttr); - assertTrue("Correct WebApplicationContext exposed in ServletContext", - wc instanceof SimpleWebApplicationContext); + boolean condition = wc instanceof SimpleWebApplicationContext; + assertThat(condition).as("Correct WebApplicationContext exposed in ServletContext").isTrue(); } @Test @@ -297,8 +294,8 @@ public class ContextLoaderTests { servlet.setContextConfigLocation("/org/springframework/web/context/WEB-INF/testNamespace.xml " + "/org/springframework/web/context/WEB-INF/context-addition.xml"); servlet.init(new MockServletConfig(new MockServletContext(""), "test")); - assertTrue(servlet.getWebApplicationContext().containsBean("kerry")); - assertTrue(servlet.getWebApplicationContext().containsBean("kerryX")); + assertThat(servlet.getWebApplicationContext().containsBean("kerry")).isTrue(); + assertThat(servlet.getWebApplicationContext().containsBean("kerryX")).isTrue(); } @Test @@ -306,18 +303,18 @@ public class ContextLoaderTests { public void testClassPathXmlApplicationContext() throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext( "/org/springframework/web/context/WEB-INF/applicationContext.xml"); - assertTrue("Has father", context.containsBean("father")); - assertTrue("Has rod", context.containsBean("rod")); - assertFalse("Hasn't kerry", context.containsBean("kerry")); - assertTrue("Doesn't have spouse", ((TestBean) context.getBean("rod")).getSpouse() == null); - assertTrue("myinit not evaluated", "Roderick".equals(((TestBean) context.getBean("rod")).getName())); + assertThat(context.containsBean("father")).as("Has father").isTrue(); + assertThat(context.containsBean("rod")).as("Has rod").isTrue(); + assertThat(context.containsBean("kerry")).as("Hasn't kerry").isFalse(); + assertThat(((TestBean) context.getBean("rod")).getSpouse() == null).as("Doesn't have spouse").isTrue(); + assertThat("Roderick".equals(((TestBean) context.getBean("rod")).getName())).as("myinit not evaluated").isTrue(); context = new ClassPathXmlApplicationContext(new String[] { "/org/springframework/web/context/WEB-INF/applicationContext.xml", "/org/springframework/web/context/WEB-INF/context-addition.xml" }); - assertTrue("Has father", context.containsBean("father")); - assertTrue("Has rod", context.containsBean("rod")); - assertTrue("Has kerry", context.containsBean("kerry")); + assertThat(context.containsBean("father")).as("Has father").isTrue(); + assertThat(context.containsBean("rod")).as("Has rod").isTrue(); + assertThat(context.containsBean("kerry")).as("Has kerry").isTrue(); } @Test @@ -335,7 +332,7 @@ public class ContextLoaderTests { } catch (BeanCreationException ex) { DefaultListableBeanFactory factory = (DefaultListableBeanFactory) getBeanFactory(); - assertEquals(0, factory.getSingletonCount()); + assertThat(factory.getSingletonCount()).isEqualTo(0); throw ex; } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/ServletContextAwareProcessorTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/ServletContextAwareProcessorTests.java index 7ca2d018f8e..0e32d59bf51 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/ServletContextAwareProcessorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/ServletContextAwareProcessorTests.java @@ -25,9 +25,7 @@ import org.springframework.mock.web.test.MockServletConfig; import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.context.support.ServletContextAwareProcessor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -40,10 +38,10 @@ public class ServletContextAwareProcessorTests { ServletContext servletContext = new MockServletContext(); ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext); ServletContextAwareBean bean = new ServletContextAwareBean(); - assertNull(bean.getServletContext()); + assertThat(bean.getServletContext()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("ServletContext should have been set", bean.getServletContext()); - assertEquals(servletContext, bean.getServletContext()); + assertThat(bean.getServletContext()).as("ServletContext should have been set").isNotNull(); + assertThat(bean.getServletContext()).isEqualTo(servletContext); } @Test @@ -52,10 +50,10 @@ public class ServletContextAwareProcessorTests { ServletConfig servletConfig = new MockServletConfig(servletContext); ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletConfig); ServletContextAwareBean bean = new ServletContextAwareBean(); - assertNull(bean.getServletContext()); + assertThat(bean.getServletContext()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("ServletContext should have been set", bean.getServletContext()); - assertEquals(servletContext, bean.getServletContext()); + assertThat(bean.getServletContext()).as("ServletContext should have been set").isNotNull(); + assertThat(bean.getServletContext()).isEqualTo(servletContext); } @Test @@ -64,10 +62,10 @@ public class ServletContextAwareProcessorTests { ServletConfig servletConfig = new MockServletConfig(servletContext); ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, servletConfig); ServletContextAwareBean bean = new ServletContextAwareBean(); - assertNull(bean.getServletContext()); + assertThat(bean.getServletContext()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("ServletContext should have been set", bean.getServletContext()); - assertEquals(servletContext, bean.getServletContext()); + assertThat(bean.getServletContext()).as("ServletContext should have been set").isNotNull(); + assertThat(bean.getServletContext()).isEqualTo(servletContext); } @Test @@ -76,10 +74,10 @@ public class ServletContextAwareProcessorTests { ServletConfig servletConfig = new MockServletConfig(servletContext); ServletContextAwareProcessor processor = new ServletContextAwareProcessor(null, servletConfig); ServletContextAwareBean bean = new ServletContextAwareBean(); - assertNull(bean.getServletContext()); + assertThat(bean.getServletContext()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("ServletContext should have been set", bean.getServletContext()); - assertEquals(servletContext, bean.getServletContext()); + assertThat(bean.getServletContext()).as("ServletContext should have been set").isNotNull(); + assertThat(bean.getServletContext()).isEqualTo(servletContext); } @Test @@ -87,10 +85,10 @@ public class ServletContextAwareProcessorTests { ServletContext servletContext = new MockServletContext(); ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, null); ServletContextAwareBean bean = new ServletContextAwareBean(); - assertNull(bean.getServletContext()); + assertThat(bean.getServletContext()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("ServletContext should have been set", bean.getServletContext()); - assertEquals(servletContext, bean.getServletContext()); + assertThat(bean.getServletContext()).as("ServletContext should have been set").isNotNull(); + assertThat(bean.getServletContext()).isEqualTo(servletContext); } @Test @@ -98,9 +96,9 @@ public class ServletContextAwareProcessorTests { ServletContext servletContext = null; ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext); ServletContextAwareBean bean = new ServletContextAwareBean(); - assertNull(bean.getServletContext()); + assertThat(bean.getServletContext()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNull(bean.getServletContext()); + assertThat(bean.getServletContext()).isNull(); } @Test @@ -108,9 +106,9 @@ public class ServletContextAwareProcessorTests { ServletContext servletContext = new MockServletContext(); ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext); ServletConfigAwareBean bean = new ServletConfigAwareBean(); - assertNull(bean.getServletConfig()); + assertThat(bean.getServletConfig()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNull(bean.getServletConfig()); + assertThat(bean.getServletConfig()).isNull(); } @Test @@ -119,10 +117,10 @@ public class ServletContextAwareProcessorTests { ServletConfig servletConfig = new MockServletConfig(servletContext); ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletConfig); ServletConfigAwareBean bean = new ServletConfigAwareBean(); - assertNull(bean.getServletConfig()); + assertThat(bean.getServletConfig()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("ServletConfig should have been set", bean.getServletConfig()); - assertEquals(servletConfig, bean.getServletConfig()); + assertThat(bean.getServletConfig()).as("ServletConfig should have been set").isNotNull(); + assertThat(bean.getServletConfig()).isEqualTo(servletConfig); } @Test @@ -131,10 +129,10 @@ public class ServletContextAwareProcessorTests { ServletConfig servletConfig = new MockServletConfig(servletContext); ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, servletConfig); ServletConfigAwareBean bean = new ServletConfigAwareBean(); - assertNull(bean.getServletConfig()); + assertThat(bean.getServletConfig()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("ServletConfig should have been set", bean.getServletConfig()); - assertEquals(servletConfig, bean.getServletConfig()); + assertThat(bean.getServletConfig()).as("ServletConfig should have been set").isNotNull(); + assertThat(bean.getServletConfig()).isEqualTo(servletConfig); } @Test @@ -143,10 +141,10 @@ public class ServletContextAwareProcessorTests { ServletConfig servletConfig = new MockServletConfig(servletContext); ServletContextAwareProcessor processor = new ServletContextAwareProcessor(null, servletConfig); ServletConfigAwareBean bean = new ServletConfigAwareBean(); - assertNull(bean.getServletConfig()); + assertThat(bean.getServletConfig()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("ServletConfig should have been set", bean.getServletConfig()); - assertEquals(servletConfig, bean.getServletConfig()); + assertThat(bean.getServletConfig()).as("ServletConfig should have been set").isNotNull(); + assertThat(bean.getServletConfig()).isEqualTo(servletConfig); } @Test @@ -154,9 +152,9 @@ public class ServletContextAwareProcessorTests { ServletContext servletContext = new MockServletContext(); ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, null); ServletConfigAwareBean bean = new ServletConfigAwareBean(); - assertNull(bean.getServletConfig()); + assertThat(bean.getServletConfig()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNull(bean.getServletConfig()); + assertThat(bean.getServletConfig()).isNull(); } @Test @@ -164,9 +162,9 @@ public class ServletContextAwareProcessorTests { ServletContext servletContext = null; ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext); ServletConfigAwareBean bean = new ServletConfigAwareBean(); - assertNull(bean.getServletConfig()); + assertThat(bean.getServletConfig()).isNull(); processor.postProcessBeforeInitialization(bean, "testBean"); - assertNull(bean.getServletConfig()); + assertThat(bean.getServletConfig()).isNull(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java index 69077621af1..66c11fe85db 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java @@ -38,8 +38,6 @@ import org.springframework.web.context.support.XmlWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -110,8 +108,7 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes @Test @Override public void count() { - assertTrue("should have 14 beans, not "+ this.applicationContext.getBeanDefinitionCount(), - this.applicationContext.getBeanDefinitionCount() == 14); + assertThat(this.applicationContext.getBeanDefinitionCount() == 14).as("should have 14 beans, not "+ this.applicationContext.getBeanDefinitionCount()).isTrue(); } @Test @@ -127,39 +124,39 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> wac.getMessage("someMessage", null, Locale.getDefault())); String msg = wac.getMessage("someMessage", null, "default", Locale.getDefault()); - assertTrue("Default message returned", "default".equals(msg)); + assertThat("default".equals(msg)).as("Default message returned").isTrue(); } @Test public void contextNesting() { TestBean father = (TestBean) this.applicationContext.getBean("father"); - assertTrue("Bean from root context", father != null); - assertTrue("Custom BeanPostProcessor applied", father.getFriends().contains("myFriend")); + assertThat(father != null).as("Bean from root context").isTrue(); + assertThat(father.getFriends().contains("myFriend")).as("Custom BeanPostProcessor applied").isTrue(); TestBean rod = (TestBean) this.applicationContext.getBean("rod"); - assertTrue("Bean from child context", "Rod".equals(rod.getName())); - assertTrue("Bean has external reference", rod.getSpouse() == father); - assertTrue("Custom BeanPostProcessor not applied", !rod.getFriends().contains("myFriend")); + assertThat("Rod".equals(rod.getName())).as("Bean from child context").isTrue(); + assertThat(rod.getSpouse() == father).as("Bean has external reference").isTrue(); + assertThat(!rod.getFriends().contains("myFriend")).as("Custom BeanPostProcessor not applied").isTrue(); rod = (TestBean) this.root.getBean("rod"); - assertTrue("Bean from root context", "Roderick".equals(rod.getName())); - assertTrue("Custom BeanPostProcessor applied", rod.getFriends().contains("myFriend")); + assertThat("Roderick".equals(rod.getName())).as("Bean from root context").isTrue(); + assertThat(rod.getFriends().contains("myFriend")).as("Custom BeanPostProcessor applied").isTrue(); } @Test public void initializingBeanAndInitMethod() throws Exception { - assertFalse(InitAndIB.constructed); + assertThat(InitAndIB.constructed).isFalse(); InitAndIB iib = (InitAndIB) this.applicationContext.getBean("init-and-ib"); - assertTrue(InitAndIB.constructed); - assertTrue(iib.afterPropertiesSetInvoked && iib.initMethodInvoked); - assertTrue(!iib.destroyed && !iib.customDestroyed); + assertThat(InitAndIB.constructed).isTrue(); + assertThat(iib.afterPropertiesSetInvoked && iib.initMethodInvoked).isTrue(); + assertThat(!iib.destroyed && !iib.customDestroyed).isTrue(); this.applicationContext.close(); - assertTrue(!iib.destroyed && !iib.customDestroyed); + assertThat(!iib.destroyed && !iib.customDestroyed).isTrue(); ConfigurableApplicationContext parent = (ConfigurableApplicationContext) this.applicationContext.getParent(); parent.close(); - assertTrue(iib.destroyed && iib.customDestroyed); + assertThat(iib.destroyed && iib.customDestroyed).isTrue(); parent.close(); - assertTrue(iib.destroyed && iib.customDestroyed); + assertThat(iib.destroyed && iib.customDestroyed).isTrue(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/support/HttpRequestHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/support/HttpRequestHandlerTests.java index 2d90ce75cd6..a1e248f69ab 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/support/HttpRequestHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/support/HttpRequestHandlerTests.java @@ -31,10 +31,9 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.HttpRequestHandler; import org.springframework.web.context.WebApplicationContext; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; /** * @author Juergen Hoeller @@ -53,8 +52,8 @@ public class HttpRequestHandlerTests { wac.getBeanFactory().registerSingleton("myHandler", new HttpRequestHandler() { @Override public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { - assertSame(request, req); - assertSame(response, res); + assertThat(req).isSameAs(request); + assertThat(res).isSameAs(response); String exception = request.getParameter("exception"); if ("ServletException".equals(exception)) { throw new ServletException("test"); @@ -73,7 +72,7 @@ public class HttpRequestHandlerTests { servlet.init(new MockServletConfig(servletContext, "myHandler")); servlet.service(request, response); - assertEquals("myResponse", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myResponse"); request.setParameter("exception", "ServletException"); assertThatExceptionOfType(ServletException.class).isThrownBy(() -> diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java index a8fbe156aef..e700b989fd8 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java @@ -31,10 +31,8 @@ import org.springframework.core.io.Resource; import org.springframework.mock.web.test.MockServletContext; 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Tests for various ServletContext-related support classes. @@ -59,7 +57,7 @@ public class ServletContextSupportTests { wac.refresh(); Object value = wac.getBean("importedAttr"); - assertEquals("myValue", value); + assertThat(value).isEqualTo("myValue"); } @Test @@ -93,7 +91,7 @@ public class ServletContextSupportTests { wac.refresh(); Object value = wac.getBean("importedParam"); - assertEquals("myValue", value); + assertThat(value).isEqualTo("myValue"); } @Test @@ -125,18 +123,18 @@ public class ServletContextSupportTests { exporter.setAttributes(attributes); exporter.setServletContext(sc); - assertEquals("value1", sc.getAttribute("attr1")); - assertSame(tb, sc.getAttribute("attr2")); + assertThat(sc.getAttribute("attr1")).isEqualTo("value1"); + assertThat(sc.getAttribute("attr2")).isSameAs(tb); } @Test public void testServletContextResourceLoader() { MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context"); ServletContextResourceLoader rl = new ServletContextResourceLoader(sc); - assertTrue(rl.getResource("/WEB-INF/web.xml").exists()); - assertTrue(rl.getResource("WEB-INF/web.xml").exists()); - assertTrue(rl.getResource("../context/WEB-INF/web.xml").exists()); - assertTrue(rl.getResource("/../context/WEB-INF/web.xml").exists()); + assertThat(rl.getResource("/WEB-INF/web.xml").exists()).isTrue(); + assertThat(rl.getResource("WEB-INF/web.xml").exists()).isTrue(); + assertThat(rl.getResource("../context/WEB-INF/web.xml").exists()).isTrue(); + assertThat(rl.getResource("/../context/WEB-INF/web.xml").exists()).isTrue(); } @Test @@ -161,9 +159,9 @@ public class ServletContextSupportTests { for (Resource resource : found) { foundPaths.add(((ServletContextResource) resource).getPath()); } - assertEquals(2, foundPaths.size()); - assertTrue(foundPaths.contains("/WEB-INF/context1.xml")); - assertTrue(foundPaths.contains("/WEB-INF/context2.xml")); + assertThat(foundPaths.size()).isEqualTo(2); + assertThat(foundPaths.contains("/WEB-INF/context1.xml")).isTrue(); + assertThat(foundPaths.contains("/WEB-INF/context2.xml")).isTrue(); } @Test @@ -194,9 +192,9 @@ public class ServletContextSupportTests { for (Resource resource : found) { foundPaths.add(((ServletContextResource) resource).getPath()); } - assertEquals(2, foundPaths.size()); - assertTrue(foundPaths.contains("/WEB-INF/mydir1/context1.xml")); - assertTrue(foundPaths.contains("/WEB-INF/mydir2/context2.xml")); + assertThat(foundPaths.size()).isEqualTo(2); + assertThat(foundPaths.contains("/WEB-INF/mydir1/context1.xml")).isTrue(); + assertThat(foundPaths.contains("/WEB-INF/mydir2/context2.xml")).isTrue(); } @Test @@ -234,10 +232,10 @@ public class ServletContextSupportTests { for (Resource resource : found) { foundPaths.add(((ServletContextResource) resource).getPath()); } - assertEquals(3, foundPaths.size()); - assertTrue(foundPaths.contains("/WEB-INF/mydir1/context1.xml")); - assertTrue(foundPaths.contains("/WEB-INF/mydir2/context2.xml")); - assertTrue(foundPaths.contains("/WEB-INF/mydir2/mydir3/context3.xml")); + assertThat(foundPaths.size()).isEqualTo(3); + assertThat(foundPaths.contains("/WEB-INF/mydir1/context1.xml")).isTrue(); + assertThat(foundPaths.contains("/WEB-INF/mydir2/context2.xml")).isTrue(); + assertThat(foundPaths.contains("/WEB-INF/mydir2/mydir3/context3.xml")).isTrue(); } @Test @@ -263,9 +261,9 @@ public class ServletContextSupportTests { for (Resource resource : found) { foundPaths.add(((ServletContextResource) resource).getPath()); } - assertEquals(2, foundPaths.size()); - assertTrue(foundPaths.contains("/WEB-INF/context1.xml")); - assertTrue(foundPaths.contains("/WEB-INF/context2.xml")); + assertThat(foundPaths.size()).isEqualTo(2); + assertThat(foundPaths.contains("/WEB-INF/context1.xml")).isTrue(); + assertThat(foundPaths.contains("/WEB-INF/context2.xml")).isTrue(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/support/WebApplicationObjectSupportTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/support/WebApplicationObjectSupportTests.java index b905553857b..95b641537bc 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/support/WebApplicationObjectSupportTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/support/WebApplicationObjectSupportTests.java @@ -25,8 +25,8 @@ import org.springframework.context.support.StaticApplicationContext; import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.util.WebUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; /** * @author Juergen Hoeller @@ -45,8 +45,8 @@ public class WebApplicationObjectSupportTests { wac.registerBeanDefinition("test", new RootBeanDefinition(TestWebApplicationObject.class)); wac.refresh(); WebApplicationObjectSupport wao = (WebApplicationObjectSupport) wac.getBean("test"); - assertEquals(wao.getServletContext(), wac.getServletContext()); - assertEquals(wao.getTempDir(), tempDir); + assertThat(wac.getServletContext()).isEqualTo(wao.getServletContext()); + assertThat(tempDir).isEqualTo(wao.getTempDir()); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java index e689c4a5b29..48ff7a6c4bb 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java @@ -61,13 +61,6 @@ import org.springframework.web.util.WebUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -114,18 +107,16 @@ public class DispatcherServletTests { @Test public void configuredDispatcherServlets() { - assertTrue("Correct namespace", - ("simple" + FrameworkServlet.DEFAULT_NAMESPACE_SUFFIX).equals(simpleDispatcherServlet.getNamespace())); - assertTrue("Correct attribute", (FrameworkServlet.SERVLET_CONTEXT_PREFIX + "simple").equals( - simpleDispatcherServlet.getServletContextAttributeName())); - assertTrue("Context published", simpleDispatcherServlet.getWebApplicationContext() == - getServletContext().getAttribute(FrameworkServlet.SERVLET_CONTEXT_PREFIX + "simple")); + assertThat(("simple" + FrameworkServlet.DEFAULT_NAMESPACE_SUFFIX).equals(simpleDispatcherServlet.getNamespace())).as("Correct namespace").isTrue(); + assertThat((FrameworkServlet.SERVLET_CONTEXT_PREFIX + "simple").equals( + simpleDispatcherServlet.getServletContextAttributeName())).as("Correct attribute").isTrue(); + assertThat(simpleDispatcherServlet.getWebApplicationContext() == + getServletContext().getAttribute(FrameworkServlet.SERVLET_CONTEXT_PREFIX + "simple")).as("Context published").isTrue(); - assertTrue("Correct namespace", "test".equals(complexDispatcherServlet.getNamespace())); - assertTrue("Correct attribute", (FrameworkServlet.SERVLET_CONTEXT_PREFIX + "complex").equals( - complexDispatcherServlet.getServletContextAttributeName())); - assertTrue("Context not published", - getServletContext().getAttribute(FrameworkServlet.SERVLET_CONTEXT_PREFIX + "complex") == null); + assertThat("test".equals(complexDispatcherServlet.getNamespace())).as("Correct namespace").isTrue(); + assertThat((FrameworkServlet.SERVLET_CONTEXT_PREFIX + "complex").equals( + complexDispatcherServlet.getServletContextAttributeName())).as("Correct attribute").isTrue(); + assertThat(getServletContext().getAttribute(FrameworkServlet.SERVLET_CONTEXT_PREFIX + "complex") == null).as("Context not published").isTrue(); simpleDispatcherServlet.destroy(); complexDispatcherServlet.destroy(); @@ -136,8 +127,8 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/invalid.do"); MockHttpServletResponse response = new MockHttpServletResponse(); simpleDispatcherServlet.service(request, response); - assertTrue("Not forwarded", response.getForwardedUrl() == null); - assertTrue("correct error code", response.getStatus() == HttpServletResponse.SC_NOT_FOUND); + assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); + assertThat(response.getStatus() == HttpServletResponse.SC_NOT_FOUND).as("correct error code").isTrue(); } @Test @@ -148,7 +139,7 @@ public class DispatcherServletTests { ComplexWebApplicationContext.TestApplicationListener listener = (ComplexWebApplicationContext.TestApplicationListener) complexDispatcherServlet .getWebApplicationContext().getBean("testListener"); - assertEquals(1, listener.counter); + assertThat(listener.counter).isEqualTo(1); } @Test @@ -160,7 +151,7 @@ public class DispatcherServletTests { ComplexWebApplicationContext.TestApplicationListener listener = (ComplexWebApplicationContext.TestApplicationListener) complexDispatcherServlet .getWebApplicationContext().getBean("testListener"); - assertEquals(0, listener.counter); + assertThat(listener.counter).isEqualTo(0); } @Test @@ -169,7 +160,7 @@ public class DispatcherServletTests { request.addUserRole("role1"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertTrue("forwarded to form", "myform.jsp".equals(response.getForwardedUrl())); + assertThat("myform.jsp".equals(response.getForwardedUrl())).as("forwarded to form").isTrue(); } @Test @@ -179,7 +170,7 @@ public class DispatcherServletTests { request.addParameter("noView", "true"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertTrue("Not forwarded", response.getForwardedUrl() == null); + assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); } @Test @@ -188,8 +179,8 @@ public class DispatcherServletTests { request.addPreferredLocale(Locale.CANADA); MockHttpServletResponse response = new MockHttpServletResponse(); simpleDispatcherServlet.service(request, response); - assertTrue("Not forwarded", response.getForwardedUrl() == null); - assertEquals("Wed, 01 Apr 2015 00:00:00 GMT", response.getHeader("Last-Modified")); + assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); + assertThat(response.getHeader("Last-Modified")).isEqualTo("Wed, 01 Apr 2015 00:00:00 GMT"); } @Test @@ -197,8 +188,8 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals("forwarded to failed", "failed0.jsp", response.getForwardedUrl()); - assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class)); + assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed0.jsp"); + assertThat(request.getAttribute("exception").getClass().equals(ServletException.class)).as("Exception exposed").isTrue(); } @Test @@ -209,17 +200,17 @@ public class DispatcherServletTests { MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertTrue("Not forwarded", response.getForwardedUrl() == null); - assertTrue(request.getAttribute("test1") != null); - assertTrue(request.getAttribute("test1x") == null); - assertTrue(request.getAttribute("test1y") == null); - assertTrue(request.getAttribute("test2") != null); - assertTrue(request.getAttribute("test2x") == null); - assertTrue(request.getAttribute("test2y") == null); - assertTrue(request.getAttribute("test3") != null); - assertTrue(request.getAttribute("test3x") != null); - assertTrue(request.getAttribute("test3y") != null); - assertEquals("Wed, 01 Apr 2015 00:00:01 GMT", response.getHeader("Last-Modified")); + assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); + assertThat(request.getAttribute("test1") != null).isTrue(); + assertThat(request.getAttribute("test1x") == null).isTrue(); + assertThat(request.getAttribute("test1y") == null).isTrue(); + assertThat(request.getAttribute("test2") != null).isTrue(); + assertThat(request.getAttribute("test2x") == null).isTrue(); + assertThat(request.getAttribute("test2y") == null).isTrue(); + assertThat(request.getAttribute("test3") != null).isTrue(); + assertThat(request.getAttribute("test3x") != null).isTrue(); + assertThat(request.getAttribute("test3y") != null).isTrue(); + assertThat(response.getHeader("Last-Modified")).isEqualTo("Wed, 01 Apr 2015 00:00:01 GMT"); } @Test @@ -234,8 +225,8 @@ public class DispatcherServletTests { MultipartHttpServletRequest multipartRequest = multipartResolver.resolveMultipart(request); complexDispatcherServlet.service(multipartRequest, response); multipartResolver.cleanupMultipart(multipartRequest); - assertNull(request.getAttribute(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)); - assertNotNull(request.getAttribute("cleanedUp")); + assertThat(request.getAttribute(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)).isNull(); + assertThat(request.getAttribute("cleanedUp")).isNotNull(); } @Test @@ -250,8 +241,8 @@ public class DispatcherServletTests { MultipartHttpServletRequest multipartRequest = multipartResolver.resolveMultipart(request); complexDispatcherServlet.service(new HttpServletRequestWrapper(multipartRequest), response); multipartResolver.cleanupMultipart(multipartRequest); - assertNull(request.getAttribute(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)); - assertNotNull(request.getAttribute("cleanedUp")); + assertThat(request.getAttribute(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)).isNull(); + assertThat(request.getAttribute("cleanedUp")).isNotNull(); } @Test @@ -262,10 +253,10 @@ public class DispatcherServletTests { request.setAttribute("fail", Boolean.TRUE); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertTrue("forwarded to failed", "failed0.jsp".equals(response.getForwardedUrl())); - assertEquals(200, response.getStatus()); - assertTrue("correct exception", request.getAttribute( - SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE) instanceof MaxUploadSizeExceededException); + assertThat("failed0.jsp".equals(response.getForwardedUrl())).as("forwarded to failed").isTrue(); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(request.getAttribute( + SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE) instanceof MaxUploadSizeExceededException).as("correct exception").isTrue(); } @Test @@ -276,13 +267,13 @@ public class DispatcherServletTests { request.addUserRole("role1"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertTrue("Not forwarded", response.getForwardedUrl() == null); - assertTrue(request.getAttribute("test1") != null); - assertTrue(request.getAttribute("test1x") != null); - assertTrue(request.getAttribute("test1y") == null); - assertTrue(request.getAttribute("test2") == null); - assertTrue(request.getAttribute("test2x") == null); - assertTrue(request.getAttribute("test2y") == null); + assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); + assertThat(request.getAttribute("test1") != null).isTrue(); + assertThat(request.getAttribute("test1x") != null).isTrue(); + assertThat(request.getAttribute("test1y") == null).isTrue(); + assertThat(request.getAttribute("test2") == null).isTrue(); + assertThat(request.getAttribute("test2x") == null).isTrue(); + assertThat(request.getAttribute("test2y") == null).isTrue(); } @Test @@ -293,8 +284,8 @@ public class DispatcherServletTests { request.addParameter("fail", "yes"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals(200, response.getStatus()); - assertTrue("forwarded to failed", "failed1.jsp".equals(response.getForwardedUrl())); + assertThat(response.getStatus()).isEqualTo(200); + assertThat("failed1.jsp".equals(response.getForwardedUrl())).as("forwarded to failed").isTrue(); } @Test @@ -305,9 +296,9 @@ public class DispatcherServletTests { request.addParameter("access", "yes"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("forwarded to failed", "failed2.jsp", response.getForwardedUrl()); - assertTrue("Exception exposed", request.getAttribute("exception") instanceof IllegalAccessException); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed2.jsp"); + assertThat(request.getAttribute("exception") instanceof IllegalAccessException).as("Exception exposed").isTrue(); } @Test @@ -318,9 +309,9 @@ public class DispatcherServletTests { request.addParameter("servlet", "yes"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("forwarded to failed", "failed3.jsp", response.getForwardedUrl()); - assertTrue("Exception exposed", request.getAttribute("exception") instanceof ServletException); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed3.jsp"); + assertThat(request.getAttribute("exception") instanceof ServletException).as("Exception exposed").isTrue(); } @Test @@ -331,9 +322,9 @@ public class DispatcherServletTests { request.addParameter("access", "yes"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals(500, response.getStatus()); - assertEquals("forwarded to failed", "failed1.jsp", response.getForwardedUrl()); - assertTrue("Exception exposed", request.getAttribute("exception") instanceof IllegalAccessException); + assertThat(response.getStatus()).isEqualTo(500); + assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed1.jsp"); + assertThat(request.getAttribute("exception") instanceof IllegalAccessException).as("Exception exposed").isTrue(); } @Test @@ -344,9 +335,9 @@ public class DispatcherServletTests { request.addParameter("servlet", "yes"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals(500, response.getStatus()); - assertEquals("forwarded to failed", "failed1.jsp", response.getForwardedUrl()); - assertTrue("Exception exposed", request.getAttribute("exception") instanceof ServletException); + assertThat(response.getStatus()).isEqualTo(500); + assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed1.jsp"); + assertThat(request.getAttribute("exception") instanceof ServletException).as("Exception exposed").isTrue(); } @Test @@ -357,9 +348,9 @@ public class DispatcherServletTests { request.addParameter("exception", "yes"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("forwarded to failed", "failed0.jsp", response.getForwardedUrl()); - assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(RuntimeException.class)); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed0.jsp"); + assertThat(request.getAttribute("exception").getClass().equals(RuntimeException.class)).as("Exception exposed").isTrue(); } @Test @@ -370,9 +361,9 @@ public class DispatcherServletTests { request.addParameter("locale", "en"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("forwarded to failed", "failed0.jsp", response.getForwardedUrl()); - assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class)); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed0.jsp"); + assertThat(request.getAttribute("exception").getClass().equals(ServletException.class)).as("Exception exposed").isTrue(); } @Test @@ -384,7 +375,7 @@ public class DispatcherServletTests { request.addParameter("locale2", "en_CA"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertTrue("Not forwarded", response.getForwardedUrl() == null); + assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); } @Test @@ -395,9 +386,9 @@ public class DispatcherServletTests { request.addParameter("theme", "mytheme"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("forwarded to failed", "failed0.jsp", response.getForwardedUrl()); - assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class)); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed0.jsp"); + assertThat(request.getAttribute("exception").getClass().equals(ServletException.class)).as("Exception exposed").isTrue(); } @Test @@ -409,7 +400,7 @@ public class DispatcherServletTests { request.addParameter("theme2", "theme"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertTrue("Not forwarded", response.getForwardedUrl() == null); + assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); } @Test @@ -418,7 +409,7 @@ public class DispatcherServletTests { request.addPreferredLocale(Locale.CANADA); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertTrue("Correct response", response.getStatus() == HttpServletResponse.SC_FORBIDDEN); + assertThat(response.getStatus() == HttpServletResponse.SC_FORBIDDEN).as("Correct response").isTrue(); } @Test @@ -426,12 +417,12 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "HEAD", "/head.do"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals(5, response.getContentLength()); + assertThat(response.getContentLength()).isEqualTo(5); request = new MockHttpServletRequest(getServletContext(), "GET", "/head.do"); response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals("", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo(""); } @Test @@ -439,12 +430,12 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "HEAD", "/body.do"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals(4, response.getContentLength()); + assertThat(response.getContentLength()).isEqualTo(4); request = new MockHttpServletRequest(getServletContext(), "GET", "/body.do"); response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals("body", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("body"); } @Test @@ -458,7 +449,7 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertTrue(response.getStatus() == HttpServletResponse.SC_NOT_FOUND); + assertThat(response.getStatus() == HttpServletResponse.SC_NOT_FOUND).isTrue(); } @Test @@ -472,7 +463,7 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", URL_KNOWN_ONLY_PARENT); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_NOT_FOUND); } @Test @@ -501,8 +492,7 @@ public class DispatcherServletTests { MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertFalse("Matched through parent controller/handler pair: not response=" + response.getStatus(), - response.getStatus() == HttpServletResponse.SC_NOT_FOUND); + assertThat(response.getStatus() == HttpServletResponse.SC_NOT_FOUND).as("Matched through parent controller/handler pair: not response=" + response.getStatus()).isFalse(); } @Test @@ -515,7 +505,7 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/servlet.do"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals("body", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("body"); request = new MockHttpServletRequest(getServletContext(), "GET", "/form.do"); response = new MockHttpServletResponse(); @@ -534,14 +524,14 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/servlet.do"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals("body", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("body"); // SimpleControllerHandlerAdapter not detected request = new MockHttpServletRequest(getServletContext(), "GET", "/form.do"); response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals("forwarded to failed", "failed0.jsp", response.getForwardedUrl()); - assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class)); + assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed0.jsp"); + assertThat(request.getAttribute("exception").getClass().equals(ServletException.class)).as("Exception exposed").isTrue(); } @Test @@ -586,7 +576,7 @@ public class DispatcherServletTests { MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertTrue("correct error code", response.getStatus() == HttpServletResponse.SC_NOT_FOUND); + assertThat(response.getStatus() == HttpServletResponse.SC_NOT_FOUND).as("correct error code").isTrue(); } // SPR-12984 @@ -596,8 +586,8 @@ public class DispatcherServletTests { HttpHeaders headers = new HttpHeaders(); headers.add("foo", "bar"); NoHandlerFoundException ex = new NoHandlerFoundException("GET", "/foo", headers); - assertTrue(!ex.getMessage().contains("bar")); - assertTrue(!ex.toString().contains("bar")); + assertThat(!ex.getMessage().contains("bar")).isTrue(); + assertThat(!ex.toString().contains("bar")).isTrue(); } @Test @@ -613,11 +603,11 @@ public class DispatcherServletTests { request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/form.do"); simpleDispatcherServlet.service(request, response); - assertEquals("value1", request.getAttribute("test1")); - assertEquals("value2", request.getAttribute("test2")); - assertEquals(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE)); - assertNull(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)); - assertNull(request.getAttribute("command")); + assertThat(request.getAttribute("test1")).isEqualTo("value1"); + assertThat(request.getAttribute("test2")).isEqualTo("value2"); + assertThat(request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isEqualTo(wac); + assertThat(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isNull(); + assertThat(request.getAttribute("command")).isNull(); } @Test @@ -635,9 +625,9 @@ public class DispatcherServletTests { request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/form.do"); simpleDispatcherServlet.service(request, response); - assertEquals("value1", request.getAttribute("test1")); - assertEquals("value2", request.getAttribute("test2")); - assertSame(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE)); + assertThat(request.getAttribute("test1")).isEqualTo("value1"); + assertThat(request.getAttribute("test2")).isEqualTo("value2"); + assertThat(request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isSameAs(wac); } @Test @@ -656,9 +646,9 @@ public class DispatcherServletTests { simpleDispatcherServlet.setCleanupAfterInclude(false); simpleDispatcherServlet.service(request, response); - assertEquals("value1", request.getAttribute("test1")); - assertEquals("value2", request.getAttribute("test2")); - assertSame(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE)); + assertThat(request.getAttribute("test1")).isEqualTo("value1"); + assertThat(request.getAttribute("test2")).isEqualTo("value2"); + assertThat(request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isSameAs(wac); } @Test @@ -666,13 +656,13 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/servlet.do"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals("body", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("body"); Servlet myServlet = (Servlet) complexDispatcherServlet.getWebApplicationContext().getBean("myServlet"); - assertEquals("complex", myServlet.getServletConfig().getServletName()); - assertEquals(getServletContext(), myServlet.getServletConfig().getServletContext()); + assertThat(myServlet.getServletConfig().getServletName()).isEqualTo("complex"); + assertThat(myServlet.getServletConfig().getServletContext()).isEqualTo(getServletContext()); complexDispatcherServlet.destroy(); - assertNull(myServlet.getServletConfig()); + assertThat((Object) myServlet.getServletConfig()).isNull(); } @Test @@ -682,7 +672,7 @@ public class DispatcherServletTests { MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals("noview.jsp", response.getForwardedUrl()); + assertThat(response.getForwardedUrl()).isEqualTo("noview.jsp"); } @Test @@ -692,7 +682,7 @@ public class DispatcherServletTests { MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertEquals("noview/simple.jsp", response.getForwardedUrl()); + assertThat(response.getForwardedUrl()).isEqualTo("noview/simple.jsp"); } @Test @@ -719,10 +709,10 @@ public class DispatcherServletTests { (ServletContextAwareBean) servlet.getWebApplicationContext().getBean("servletContextAwareBean"); ServletConfigAwareBean configBean = (ServletConfigAwareBean) servlet.getWebApplicationContext().getBean("servletConfigAwareBean"); - assertSame(servletContext, contextBean.getServletContext()); - assertSame(servlet.getServletConfig(), configBean.getServletConfig()); + assertThat(contextBean.getServletContext()).isSameAs(servletContext); + assertThat(configBean.getServletConfig()).isSameAs(servlet.getServletConfig()); MultipartResolver multipartResolver = servlet.getMultipartResolver(); - assertNotNull(multipartResolver); + assertThat(multipartResolver).isNotNull(); servlet.refresh(); @@ -730,12 +720,12 @@ public class DispatcherServletTests { (ServletContextAwareBean) servlet.getWebApplicationContext().getBean("servletContextAwareBean"); ServletConfigAwareBean configBean2 = (ServletConfigAwareBean) servlet.getWebApplicationContext().getBean("servletConfigAwareBean"); - assertSame(servletContext, contextBean2.getServletContext()); - assertSame(servlet.getServletConfig(), configBean2.getServletConfig()); - assertNotSame(contextBean, contextBean2); - assertNotSame(configBean, configBean2); + assertThat(contextBean2.getServletContext()).isSameAs(servletContext); + assertThat(configBean2.getServletConfig()).isSameAs(servlet.getServletConfig()); + assertThat(contextBean2).isNotSameAs(contextBean); + assertThat(configBean2).isNotSameAs(configBean); MultipartResolver multipartResolver2 = servlet.getMultipartResolver(); - assertNotSame(multipartResolver, multipartResolver2); + assertThat(multipartResolver2).isNotSameAs(multipartResolver); servlet.destroy(); } @@ -750,10 +740,10 @@ public class DispatcherServletTests { (ServletContextAwareBean) servlet.getWebApplicationContext().getBean("servletContextAwareBean"); ServletConfigAwareBean configBean = (ServletConfigAwareBean) servlet.getWebApplicationContext().getBean("servletConfigAwareBean"); - assertSame(servletContext, contextBean.getServletContext()); - assertSame(servlet.getServletConfig(), configBean.getServletConfig()); + assertThat(contextBean.getServletContext()).isSameAs(servletContext); + assertThat(configBean.getServletConfig()).isSameAs(servlet.getServletConfig()); MultipartResolver multipartResolver = servlet.getMultipartResolver(); - assertNotNull(multipartResolver); + assertThat(multipartResolver).isNotNull(); ((ConfigurableApplicationContext) servlet.getWebApplicationContext()).refresh(); @@ -761,12 +751,12 @@ public class DispatcherServletTests { (ServletContextAwareBean) servlet.getWebApplicationContext().getBean("servletContextAwareBean"); ServletConfigAwareBean configBean2 = (ServletConfigAwareBean) servlet.getWebApplicationContext().getBean("servletConfigAwareBean"); - assertSame(servletContext, contextBean2.getServletContext()); - assertSame(servlet.getServletConfig(), configBean2.getServletConfig()); - assertTrue(contextBean != contextBean2); - assertTrue(configBean != configBean2); + assertThat(contextBean2.getServletContext()).isSameAs(servletContext); + assertThat(configBean2.getServletConfig()).isSameAs(servlet.getServletConfig()); + assertThat(contextBean != contextBean2).isTrue(); + assertThat(configBean != configBean2).isTrue(); MultipartResolver multipartResolver2 = servlet.getMultipartResolver(); - assertTrue(multipartResolver != multipartResolver2); + assertThat(multipartResolver != multipartResolver2).isTrue(); servlet.destroy(); } @@ -809,8 +799,8 @@ public class DispatcherServletTests { servlet.setContextClass(SimpleWebApplicationContext.class); servlet.setContextInitializers(new TestWebContextInitializer(), new OtherWebContextInitializer()); servlet.init(servletConfig); - assertEquals("true", getServletContext().getAttribute("initialized")); - assertEquals("true", getServletContext().getAttribute("otherInitialized")); + assertThat(getServletContext().getAttribute("initialized")).isEqualTo("true"); + assertThat(getServletContext().getAttribute("otherInitialized")).isEqualTo("true"); } @Test @@ -820,8 +810,8 @@ public class DispatcherServletTests { servlet.setContextInitializerClasses( TestWebContextInitializer.class.getName() + "," + OtherWebContextInitializer.class.getName()); servlet.init(servletConfig); - assertEquals("true", getServletContext().getAttribute("initialized")); - assertEquals("true", getServletContext().getAttribute("otherInitialized")); + assertThat(getServletContext().getAttribute("initialized")).isEqualTo("true"); + assertThat(getServletContext().getAttribute("otherInitialized")).isEqualTo("true"); } @Test @@ -831,8 +821,8 @@ public class DispatcherServletTests { getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM, TestWebContextInitializer.class.getName() + "," + OtherWebContextInitializer.class.getName()); servlet.init(servletConfig); - assertEquals("true", getServletContext().getAttribute("initialized")); - assertEquals("true", getServletContext().getAttribute("otherInitialized")); + assertThat(getServletContext().getAttribute("initialized")).isEqualTo("true"); + assertThat(getServletContext().getAttribute("otherInitialized")).isEqualTo("true"); } @Test @@ -843,8 +833,8 @@ public class DispatcherServletTests { TestWebContextInitializer.class.getName()); servlet.setContextInitializerClasses(OtherWebContextInitializer.class.getName()); servlet.init(servletConfig); - assertEquals("true", getServletContext().getAttribute("initialized")); - assertEquals("true", getServletContext().getAttribute("otherInitialized")); + assertThat(getServletContext().getAttribute("initialized")).isEqualTo("true"); + assertThat(getServletContext().getAttribute("otherInitialized")).isEqualTo("true"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/FlashMapTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/FlashMapTests.java index a0e3a3e8657..45f7f39a06d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/FlashMapTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/FlashMapTests.java @@ -21,9 +21,7 @@ import org.junit.Test; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link FlashMap} tests. @@ -34,13 +32,13 @@ public class FlashMapTests { @Test public void isExpired() throws InterruptedException { - assertFalse(new FlashMap().isExpired()); + assertThat(new FlashMap().isExpired()).isFalse(); FlashMap flashMap = new FlashMap(); flashMap.startExpirationPeriod(0); Thread.sleep(100); - assertTrue(flashMap.isExpired()); + assertThat(flashMap.isExpired()).isTrue(); } @Test @@ -49,28 +47,28 @@ public class FlashMapTests { flashMap.startExpirationPeriod(10); Thread.sleep(100); - assertFalse(flashMap.isExpired()); + assertThat(flashMap.isExpired()).isFalse(); } @Test public void compareTo() { FlashMap flashMap1 = new FlashMap(); FlashMap flashMap2 = new FlashMap(); - assertEquals(0, flashMap1.compareTo(flashMap2)); + assertThat(flashMap1.compareTo(flashMap2)).isEqualTo(0); flashMap1.setTargetRequestPath("/path1"); - assertEquals(-1, flashMap1.compareTo(flashMap2)); - assertEquals(1, flashMap2.compareTo(flashMap1)); + assertThat(flashMap1.compareTo(flashMap2)).isEqualTo(-1); + assertThat(flashMap2.compareTo(flashMap1)).isEqualTo(1); flashMap2.setTargetRequestPath("/path2"); - assertEquals(0, flashMap1.compareTo(flashMap2)); + assertThat(flashMap1.compareTo(flashMap2)).isEqualTo(0); flashMap1.addTargetRequestParam("id", "1"); - assertEquals(-1, flashMap1.compareTo(flashMap2)); - assertEquals(1, flashMap2.compareTo(flashMap1)); + assertThat(flashMap1.compareTo(flashMap2)).isEqualTo(-1); + assertThat(flashMap2.compareTo(flashMap1)).isEqualTo(1); flashMap2.addTargetRequestParam("id", "2"); - assertEquals(0, flashMap1.compareTo(flashMap2)); + assertThat(flashMap1.compareTo(flashMap2)).isEqualTo(0); } @Test @@ -80,8 +78,8 @@ public class FlashMapTests { flashMap.addTargetRequestParam("empty", " "); flashMap.addTargetRequestParam("null", null); - assertEquals(1, flashMap.getTargetRequestParams().size()); - assertEquals("abc", flashMap.getTargetRequestParams().getFirst("text")); + assertThat(flashMap.getTargetRequestParams().size()).isEqualTo(1); + assertThat(flashMap.getTargetRequestParams().getFirst("text")).isEqualTo("abc"); } @Test @@ -94,9 +92,9 @@ public class FlashMapTests { FlashMap flashMap = new FlashMap(); flashMap.addTargetRequestParams(params); - assertEquals(1, flashMap.getTargetRequestParams().size()); - assertEquals(1, flashMap.getTargetRequestParams().get("key").size()); - assertEquals("abc", flashMap.getTargetRequestParams().getFirst("key")); + assertThat(flashMap.getTargetRequestParams().size()).isEqualTo(1); + assertThat(flashMap.getTargetRequestParams().get("key").size()).isEqualTo(1); + assertThat(flashMap.getTargetRequestParams().getFirst("key")).isEqualTo("abc"); } @Test @@ -105,7 +103,7 @@ public class FlashMapTests { flashMap.addTargetRequestParam(" ", "abc"); flashMap.addTargetRequestParam(null, "abc"); - assertTrue(flashMap.getTargetRequestParams().isEmpty()); + assertThat(flashMap.getTargetRequestParams().isEmpty()).isTrue(); } @Test @@ -117,7 +115,7 @@ public class FlashMapTests { FlashMap flashMap = new FlashMap(); flashMap.addTargetRequestParams(params); - assertTrue(flashMap.getTargetRequestParams().isEmpty()); + assertThat(flashMap.getTargetRequestParams().isEmpty()).isTrue(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java index 0a44ab9b5f9..f4bccf72abb 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -66,9 +65,9 @@ public class HandlerExecutionChainTests { this.chain.addInterceptor(this.interceptor1); this.chain.addInterceptor(this.interceptor2); - assertEquals(2, this.chain.getInterceptors().length); + assertThat(this.chain.getInterceptors().length).isEqualTo(2); this.chain.addInterceptor(this.interceptor3); - assertEquals(3, this.chain.getInterceptors().length); + assertThat(this.chain.getInterceptors().length).isEqualTo(3); } @@ -135,7 +134,7 @@ public class HandlerExecutionChainTests { this.chain.applyPreHandle(request, response); } catch (Exception actual) { - assertSame(ex, actual); + assertThat(actual).isSameAs(ex); } this.chain.triggerAfterCompletion(this.request, this.response, ex); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParserTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParserTests.java index 0dd97cb11ec..db37495d35e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParserTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParserTests.java @@ -50,11 +50,6 @@ import org.springframework.web.servlet.mvc.method.annotation.ServletWebArgumentR import org.springframework.web.util.UrlPathHelper; import static org.assertj.core.api.Assertions.assertThat; -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.assertTrue; /** * Test fixture for the configuration in mvc-config-annotation-driven.xml. @@ -71,24 +66,24 @@ public class AnnotationDrivenBeanDefinitionParserTests { public void testMessageCodesResolver() { loadBeanDefinitions("mvc-config-message-codes-resolver.xml"); RequestMappingHandlerAdapter adapter = this.appContext.getBean(RequestMappingHandlerAdapter.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); Object initializer = adapter.getWebBindingInitializer(); - assertNotNull(initializer); + assertThat(initializer).isNotNull(); MessageCodesResolver resolver = ((ConfigurableWebBindingInitializer) initializer).getMessageCodesResolver(); - assertNotNull(resolver); - assertEquals(TestMessageCodesResolver.class, resolver.getClass()); - assertEquals(false, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect")); + assertThat(resolver).isNotNull(); + assertThat(resolver.getClass()).isEqualTo(TestMessageCodesResolver.class); + assertThat(new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect")).isEqualTo(false); } @Test public void testPathMatchingConfiguration() { loadBeanDefinitions("mvc-config-path-matching.xml"); RequestMappingHandlerMapping hm = this.appContext.getBean(RequestMappingHandlerMapping.class); - assertNotNull(hm); - assertTrue(hm.useSuffixPatternMatch()); - assertFalse(hm.useTrailingSlashMatch()); - assertTrue(hm.useRegisteredSuffixPatternMatch()); + assertThat(hm).isNotNull(); + assertThat(hm.useSuffixPatternMatch()).isTrue(); + assertThat(hm.useTrailingSlashMatch()).isFalse(); + assertThat(hm.useRegisteredSuffixPatternMatch()).isTrue(); assertThat(hm.getUrlPathHelper()).isInstanceOf(TestPathHelper.class); assertThat(hm.getPathMatcher()).isInstanceOf(TestPathMatcher.class); List fileExtensions = hm.getContentNegotiationManager().getAllFileExtensions(); @@ -119,17 +114,17 @@ public class AnnotationDrivenBeanDefinitionParserTests { } private void testArgumentResolvers(Object bean) { - assertNotNull(bean); + assertThat(bean).isNotNull(); Object value = new DirectFieldAccessor(bean).getPropertyValue("customArgumentResolvers"); - assertNotNull(value); - assertTrue(value instanceof List); + assertThat(value).isNotNull(); + assertThat(value instanceof List).isTrue(); @SuppressWarnings("unchecked") List resolvers = (List) value; - assertEquals(3, resolvers.size()); - assertTrue(resolvers.get(0) instanceof ServletWebArgumentResolverAdapter); - assertTrue(resolvers.get(1) instanceof TestHandlerMethodArgumentResolver); - assertTrue(resolvers.get(2) instanceof TestHandlerMethodArgumentResolver); - assertNotSame(resolvers.get(1), resolvers.get(2)); + assertThat(resolvers.size()).isEqualTo(3); + assertThat(resolvers.get(0) instanceof ServletWebArgumentResolverAdapter).isTrue(); + assertThat(resolvers.get(1) instanceof TestHandlerMethodArgumentResolver).isTrue(); + assertThat(resolvers.get(2) instanceof TestHandlerMethodArgumentResolver).isTrue(); + assertThat(resolvers.get(2)).isNotSameAs(resolvers.get(1)); } @Test @@ -140,24 +135,24 @@ public class AnnotationDrivenBeanDefinitionParserTests { } private void testReturnValueHandlers(Object bean) { - assertNotNull(bean); + assertThat(bean).isNotNull(); Object value = new DirectFieldAccessor(bean).getPropertyValue("customReturnValueHandlers"); - assertNotNull(value); - assertTrue(value instanceof List); + assertThat(value).isNotNull(); + assertThat(value instanceof List).isTrue(); @SuppressWarnings("unchecked") List handlers = (List) value; - assertEquals(2, handlers.size()); - assertEquals(TestHandlerMethodReturnValueHandler.class, handlers.get(0).getClass()); - assertEquals(TestHandlerMethodReturnValueHandler.class, handlers.get(1).getClass()); - assertNotSame(handlers.get(0), handlers.get(1)); + assertThat(handlers.size()).isEqualTo(2); + assertThat(handlers.get(0).getClass()).isEqualTo(TestHandlerMethodReturnValueHandler.class); + assertThat(handlers.get(1).getClass()).isEqualTo(TestHandlerMethodReturnValueHandler.class); + assertThat(handlers.get(1)).isNotSameAs(handlers.get(0)); } @Test public void beanNameUrlHandlerMapping() { loadBeanDefinitions("mvc-config.xml"); BeanNameUrlHandlerMapping mapping = this.appContext.getBean(BeanNameUrlHandlerMapping.class); - assertNotNull(mapping); - assertEquals(2, mapping.getOrder()); + assertThat(mapping).isNotNull(); + assertThat(mapping.getOrder()).isEqualTo(2); } private void loadBeanDefinitions(String fileName) { @@ -169,40 +164,40 @@ public class AnnotationDrivenBeanDefinitionParserTests { @SuppressWarnings("unchecked") private void verifyMessageConverters(Object bean, boolean hasDefaultRegistrations) { - assertNotNull(bean); + assertThat(bean).isNotNull(); Object value = new DirectFieldAccessor(bean).getPropertyValue("messageConverters"); - assertNotNull(value); - assertTrue(value instanceof List); + assertThat(value).isNotNull(); + assertThat(value instanceof List).isTrue(); List> converters = (List>) value; if (hasDefaultRegistrations) { - assertTrue("Default and custom converter expected", converters.size() > 2); + assertThat(converters.size() > 2).as("Default and custom converter expected").isTrue(); } else { - assertTrue("Only custom converters expected", converters.size() == 2); + assertThat(converters.size() == 2).as("Only custom converters expected").isTrue(); } - assertTrue(converters.get(0) instanceof StringHttpMessageConverter); - assertTrue(converters.get(1) instanceof ResourceHttpMessageConverter); + assertThat(converters.get(0) instanceof StringHttpMessageConverter).isTrue(); + assertThat(converters.get(1) instanceof ResourceHttpMessageConverter).isTrue(); } @SuppressWarnings("unchecked") private void verifyResponseBodyAdvice(Object bean) { - assertNotNull(bean); + assertThat(bean).isNotNull(); Object value = new DirectFieldAccessor(bean).getPropertyValue("responseBodyAdvice"); - assertNotNull(value); - assertTrue(value instanceof List); + assertThat(value).isNotNull(); + assertThat(value instanceof List).isTrue(); List> converters = (List>) value; - assertTrue(converters.get(0) instanceof JsonViewResponseBodyAdvice); + assertThat(converters.get(0) instanceof JsonViewResponseBodyAdvice).isTrue(); } @SuppressWarnings("unchecked") private void verifyRequestResponseBodyAdvice(Object bean) { - assertNotNull(bean); + assertThat(bean).isNotNull(); Object value = new DirectFieldAccessor(bean).getPropertyValue("requestResponseBodyAdvice"); - assertNotNull(value); - assertTrue(value instanceof List); + assertThat(value).isNotNull(); + assertThat(value instanceof List).isTrue(); List> converters = (List>) value; - assertTrue(converters.get(0) instanceof JsonViewRequestBodyAdvice); - assertTrue(converters.get(1) instanceof JsonViewResponseBodyAdvice); + assertThat(converters.get(0) instanceof JsonViewRequestBodyAdvice).isTrue(); + assertThat(converters.get(1) instanceof JsonViewResponseBodyAdvice).isTrue(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java index 0218e0d2713..116c9566775 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java @@ -142,13 +142,6 @@ import org.springframework.web.util.UrlPathHelper; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * Tests loading actual MVC namespace configuration. @@ -195,38 +188,38 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config.xml"); RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class); - assertNotNull(mapping); - assertEquals(0, mapping.getOrder()); - assertTrue(mapping.getUrlPathHelper().shouldRemoveSemicolonContent()); + assertThat(mapping).isNotNull(); + assertThat(mapping.getOrder()).isEqualTo(0); + assertThat(mapping.getUrlPathHelper().shouldRemoveSemicolonContent()).isTrue(); mapping.setDefaultHandler(handlerMethod); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.json"); NativeWebRequest webRequest = new ServletWebRequest(request); ContentNegotiationManager manager = mapping.getContentNegotiationManager(); - assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), manager.resolveMediaTypes(webRequest)); + assertThat(manager.resolveMediaTypes(webRequest)).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class); - assertNotNull(adapter); - assertEquals(false, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect")); + assertThat(adapter).isNotNull(); + assertThat(new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect")).isEqualTo(false); List> converters = adapter.getMessageConverters(); - assertTrue(converters.size() > 0); + assertThat(converters.size() > 0).isTrue(); for (HttpMessageConverter converter : converters) { if (converter instanceof AbstractJackson2HttpMessageConverter) { ObjectMapper objectMapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper(); - assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); - assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); - assertFalse(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); + assertThat(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(objectMapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); if (converter instanceof MappingJackson2XmlHttpMessageConverter) { - assertEquals(XmlMapper.class, objectMapper.getClass()); + assertThat(objectMapper.getClass()).isEqualTo(XmlMapper.class); } } } - assertNotNull(appContext.getBean(FormattingConversionServiceFactoryBean.class)); - assertNotNull(appContext.getBean(ConversionService.class)); - assertNotNull(appContext.getBean(LocalValidatorFactoryBean.class)); - assertNotNull(appContext.getBean(Validator.class)); + assertThat(appContext.getBean(FormattingConversionServiceFactoryBean.class)).isNotNull(); + assertThat(appContext.getBean(ConversionService.class)).isNotNull(); + assertThat(appContext.getBean(LocalValidatorFactoryBean.class)).isNotNull(); + assertThat(appContext.getBean(Validator.class)).isNotNull(); // default web binding initializer behavior test request = new MockHttpServletRequest("GET", "/"); @@ -235,29 +228,29 @@ public class MvcNamespaceTests { MockHttpServletResponse response = new MockHttpServletResponse(); HandlerExecutionChain chain = mapping.getHandler(request); - assertEquals(1, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor); + assertThat(chain.getInterceptors().length).isEqualTo(1); + assertThat(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor).isTrue(); ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0]; interceptor.preHandle(request, response, handlerMethod); - assertSame(appContext.getBean(ConversionService.class), request.getAttribute(ConversionService.class.getName())); + assertThat(request.getAttribute(ConversionService.class.getName())).isSameAs(appContext.getBean(ConversionService.class)); adapter.handle(request, response, handlerMethod); - assertTrue(handler.recordedValidationError); - assertEquals(LocalDate.parse("2009-10-31").toDate(), handler.date); - assertEquals(Double.valueOf(0.9999), handler.percent); + assertThat(handler.recordedValidationError).isTrue(); + assertThat(handler.date).isEqualTo(LocalDate.parse("2009-10-31").toDate()); + assertThat(handler.percent).isEqualTo(Double.valueOf(0.9999)); CompositeUriComponentsContributor uriComponentsContributor = this.appContext.getBean( MvcUriComponentsBuilder.MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME, CompositeUriComponentsContributor.class); - assertNotNull(uriComponentsContributor); + assertThat(uriComponentsContributor).isNotNull(); String name = "mvcHandlerMappingIntrospector"; HandlerMappingIntrospector introspector = this.appContext.getBean(name, HandlerMappingIntrospector.class); - assertNotNull(introspector); - assertEquals(2, introspector.getHandlerMappings().size()); - assertSame(mapping, introspector.getHandlerMappings().get(0)); - assertEquals(BeanNameUrlHandlerMapping.class, introspector.getHandlerMappings().get(1).getClass()); + assertThat(introspector).isNotNull(); + assertThat(introspector.getHandlerMappings().size()).isEqualTo(2); + assertThat(introspector.getHandlerMappings().get(0)).isSameAs(mapping); + assertThat(introspector.getHandlerMappings().get(1).getClass()).isEqualTo(BeanNameUrlHandlerMapping.class); } @Test @@ -265,7 +258,7 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-custom-conversion-service.xml"); RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class); - assertNotNull(mapping); + assertThat(mapping).isNotNull(); mapping.setDefaultHandler(handlerMethod); // default web binding initializer behavior test @@ -275,14 +268,14 @@ public class MvcNamespaceTests { MockHttpServletResponse response = new MockHttpServletResponse(); HandlerExecutionChain chain = mapping.getHandler(request); - assertEquals(1, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor); + assertThat(chain.getInterceptors().length).isEqualTo(1); + assertThat(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor).isTrue(); ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0]; interceptor.preHandle(request, response, handler); - assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName())); + assertThat(request.getAttribute(ConversionService.class.getName())).isSameAs(appContext.getBean("conversionService")); RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() -> adapter.handle(request, response, handlerMethod)); } @@ -296,12 +289,12 @@ public class MvcNamespaceTests { loadBeanDefinitions(xml); RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class); - assertNotNull(mapping); - assertFalse(mapping.getUrlPathHelper().shouldRemoveSemicolonContent()); + assertThat(mapping).isNotNull(); + assertThat(mapping.getUrlPathHelper().shouldRemoveSemicolonContent()).isFalse(); RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class); - assertNotNull(adapter); - assertEquals(true, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect")); + assertThat(adapter).isNotNull(); + assertThat(new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect")).isEqualTo(true); // default web binding initializer behavior test MockHttpServletRequest request = new MockHttpServletRequest(); @@ -309,8 +302,8 @@ public class MvcNamespaceTests { MockHttpServletResponse response = new MockHttpServletResponse(); adapter.handle(request, response, handlerMethod); - assertTrue(appContext.getBean(TestValidator.class).validatorInvoked); - assertFalse(handler.recordedValidationError); + assertThat(appContext.getBean(TestValidator.class).validatorInvoked).isTrue(); + assertThat(handler.recordedValidationError).isFalse(); } @Test @@ -318,7 +311,7 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-interceptors.xml"); RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class); - assertNotNull(mapping); + assertThat(mapping).isNotNull(); mapping.setDefaultHandler(handlerMethod); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); @@ -327,50 +320,49 @@ public class MvcNamespaceTests { request.addParameter("theme", "green"); HandlerExecutionChain chain = mapping.getHandler(request); - assertEquals(4, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor); - assertTrue(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor); - assertTrue(chain.getInterceptors()[2] instanceof ThemeChangeInterceptor); - assertTrue(chain.getInterceptors()[3] instanceof UserRoleAuthorizationInterceptor); + assertThat(chain.getInterceptors().length).isEqualTo(4); + assertThat(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor).isTrue(); + assertThat(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor).isTrue(); + assertThat(chain.getInterceptors()[2] instanceof ThemeChangeInterceptor).isTrue(); + assertThat(chain.getInterceptors()[3] instanceof UserRoleAuthorizationInterceptor).isTrue(); request.setRequestURI("/admin/users"); chain = mapping.getHandler(request); - assertEquals(2, chain.getInterceptors().length); + assertThat(chain.getInterceptors().length).isEqualTo(2); request.setRequestURI("/logged/accounts/12345"); chain = mapping.getHandler(request); - assertEquals(3, chain.getInterceptors().length); + assertThat(chain.getInterceptors().length).isEqualTo(3); request.setRequestURI("/foo/logged"); chain = mapping.getHandler(request); - assertEquals(3, chain.getInterceptors().length); + assertThat(chain.getInterceptors().length).isEqualTo(3); } @Test - @SuppressWarnings("unchecked") public void testResources() throws Exception { loadBeanDefinitions("mvc-config-resources.xml"); HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class); ContentNegotiationManager manager = mapping.getContentNegotiationManager(); ResourceHttpRequestHandler handler = appContext.getBean(ResourceHttpRequestHandler.class); - assertNotNull(handler); - assertSame(manager, handler.getContentNegotiationManager()); + assertThat(handler).isNotNull(); + assertThat(handler.getContentNegotiationManager()).isSameAs(manager); SimpleUrlHandlerMapping resourceMapping = appContext.getBean(SimpleUrlHandlerMapping.class); - assertNotNull(resourceMapping); - assertEquals(Ordered.LOWEST_PRECEDENCE - 1, resourceMapping.getOrder()); + assertThat(resourceMapping).isNotNull(); + assertThat(resourceMapping.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE - 1); BeanNameUrlHandlerMapping beanNameMapping = appContext.getBean(BeanNameUrlHandlerMapping.class); - assertNotNull(beanNameMapping); - assertEquals(2, beanNameMapping.getOrder()); + assertThat(beanNameMapping).isNotNull(); + assertThat(beanNameMapping.getOrder()).isEqualTo(2); ResourceUrlProvider urlProvider = appContext.getBean(ResourceUrlProvider.class); - assertNotNull(urlProvider); + assertThat(urlProvider).isNotNull(); Map beans = appContext.getBeansOfType(MappedInterceptor.class); List> interceptors = beans.values().stream() @@ -384,15 +376,15 @@ public class MvcNamespaceTests { request.setMethod("GET"); HandlerExecutionChain chain = resourceMapping.getHandler(request); - assertNotNull(chain); - assertTrue(chain.getHandler() instanceof ResourceHttpRequestHandler); + assertThat(chain).isNotNull(); + assertThat(chain.getHandler() instanceof ResourceHttpRequestHandler).isTrue(); MockHttpServletResponse response = new MockHttpServletResponse(); for (HandlerInterceptor interceptor : chain.getInterceptors()) { interceptor.preHandle(request, response, chain.getHandler()); } ModelAndView mv = adapter.handle(request, response, chain.getHandler()); - assertNull(mv); + assertThat((Object) mv).isNull(); } @Test @@ -400,14 +392,14 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-resources-optional-attrs.xml"); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); - assertNotNull(mapping); - assertEquals(5, mapping.getOrder()); - assertNotNull(mapping.getUrlMap().get("/resources/**")); + assertThat(mapping).isNotNull(); + assertThat(mapping.getOrder()).isEqualTo(5); + assertThat(mapping.getUrlMap().get("/resources/**")).isNotNull(); ResourceHttpRequestHandler handler = appContext.getBean((String) mapping.getUrlMap().get("/resources/**"), ResourceHttpRequestHandler.class); - assertNotNull(handler); - assertEquals(3600, handler.getCacheSeconds()); + assertThat(handler).isNotNull(); + assertThat(handler.getCacheSeconds()).isEqualTo(3600); } @Test @@ -415,13 +407,13 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-resources-chain.xml"); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); - assertNotNull(mapping); - assertNotNull(mapping.getUrlMap().get("/resources/**")); + assertThat(mapping).isNotNull(); + assertThat(mapping.getUrlMap().get("/resources/**")).isNotNull(); String beanName = (String) mapping.getUrlMap().get("/resources/**"); ResourceHttpRequestHandler handler = appContext.getBean(beanName, ResourceHttpRequestHandler.class); - assertNotNull(handler); + assertThat(handler).isNotNull(); - assertNotNull(handler.getUrlPathHelper()); + assertThat(handler.getUrlPathHelper()).isNotNull(); List resolvers = handler.getResourceResolvers(); assertThat(resolvers).hasSize(4); @@ -432,7 +424,7 @@ public class MvcNamespaceTests { CachingResourceResolver cachingResolver = (CachingResourceResolver) resolvers.get(0); assertThat(cachingResolver.getCache()).isInstanceOf(ConcurrentMapCache.class); - assertEquals("test-resource-cache", cachingResolver.getCache().getName()); + assertThat(cachingResolver.getCache().getName()).isEqualTo("test-resource-cache"); VersionResourceResolver versionResolver = (VersionResourceResolver) resolvers.get(1); assertThat(versionResolver.getStrategyMap().get("/**/*.js")) @@ -442,8 +434,8 @@ public class MvcNamespaceTests { PathResourceResolver pathResolver = (PathResourceResolver) resolvers.get(3); Map locationCharsets = pathResolver.getLocationCharsets(); - assertEquals(1, locationCharsets.size()); - assertEquals(StandardCharsets.ISO_8859_1, locationCharsets.values().iterator().next()); + assertThat(locationCharsets.size()).isEqualTo(1); + assertThat(locationCharsets.values().iterator().next()).isEqualTo(StandardCharsets.ISO_8859_1); List transformers = handler.getResourceTransformers(); assertThat(transformers).hasSize(3); @@ -453,7 +445,7 @@ public class MvcNamespaceTests { CachingResourceTransformer cachingTransformer = (CachingResourceTransformer) transformers.get(0); assertThat(cachingTransformer.getCache()).isInstanceOf(ConcurrentMapCache.class); - assertEquals("test-resource-cache", cachingTransformer.getCache().getName()); + assertThat(cachingTransformer.getCache().getName()).isEqualTo("test-resource-cache"); } @Test @@ -461,11 +453,11 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-resources-chain-no-auto.xml"); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); - assertNotNull(mapping); - assertNotNull(mapping.getUrlMap().get("/resources/**")); + assertThat(mapping).isNotNull(); + assertThat(mapping.getUrlMap().get("/resources/**")).isNotNull(); ResourceHttpRequestHandler handler = appContext.getBean((String) mapping.getUrlMap().get("/resources/**"), ResourceHttpRequestHandler.class); - assertNotNull(handler); + assertThat(handler).isNotNull(); assertThat(handler.getCacheControl().getHeaderValue()) .isEqualTo(CacheControl.maxAge(1, TimeUnit.HOURS) @@ -494,25 +486,25 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-default-servlet.xml"); HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); DefaultServletHttpRequestHandler handler = appContext.getBean(DefaultServletHttpRequestHandler.class); - assertNotNull(handler); + assertThat(handler).isNotNull(); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); - assertNotNull(mapping); - assertEquals(Ordered.LOWEST_PRECEDENCE, mapping.getOrder()); + assertThat(mapping).isNotNull(); + assertThat(mapping.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo.css"); request.setMethod("GET"); HandlerExecutionChain chain = mapping.getHandler(request); - assertTrue(chain.getHandler() instanceof DefaultServletHttpRequestHandler); + assertThat(chain.getHandler() instanceof DefaultServletHttpRequestHandler).isTrue(); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = adapter.handle(request, response, chain.getHandler()); - assertNull(mv); + assertThat((Object) mv).isNull(); } @Test @@ -520,25 +512,25 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-default-servlet-optional-attrs.xml"); HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); DefaultServletHttpRequestHandler handler = appContext.getBean(DefaultServletHttpRequestHandler.class); - assertNotNull(handler); + assertThat(handler).isNotNull(); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); - assertNotNull(mapping); - assertEquals(Ordered.LOWEST_PRECEDENCE, mapping.getOrder()); + assertThat(mapping).isNotNull(); + assertThat(mapping.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo.css"); request.setMethod("GET"); HandlerExecutionChain chain = mapping.getHandler(request); - assertTrue(chain.getHandler() instanceof DefaultServletHttpRequestHandler); + assertThat(chain.getHandler() instanceof DefaultServletHttpRequestHandler).isTrue(); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = adapter.handle(request, response, chain.getHandler()); - assertNull(mv); + assertThat((Object) mv).isNull(); } @Test @@ -546,20 +538,20 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-bean-decoration.xml"); RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class); - assertNotNull(mapping); + assertThat(mapping).isNotNull(); mapping.setDefaultHandler(handlerMethod); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); HandlerExecutionChain chain = mapping.getHandler(request); - assertEquals(3, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor); - assertTrue(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor); - assertTrue(chain.getInterceptors()[2] instanceof ThemeChangeInterceptor); + assertThat(chain.getInterceptors().length).isEqualTo(3); + assertThat(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor).isTrue(); + assertThat(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor).isTrue(); + assertThat(chain.getInterceptors()[2] instanceof ThemeChangeInterceptor).isTrue(); LocaleChangeInterceptor interceptor = (LocaleChangeInterceptor) chain.getInterceptors()[1]; - assertEquals("lang", interceptor.getParamName()); + assertThat(interceptor.getParamName()).isEqualTo("lang"); ThemeChangeInterceptor interceptor2 = (ThemeChangeInterceptor) chain.getInterceptors()[2]; - assertEquals("style", interceptor2.getParamName()); + assertThat(interceptor2.getParamName()).isEqualTo("style"); } @Test @@ -567,58 +559,58 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-view-controllers.xml"); RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class); - assertNotNull(mapping); + assertThat(mapping).isNotNull(); mapping.setDefaultHandler(handlerMethod); BeanNameUrlHandlerMapping beanNameMapping = appContext.getBean(BeanNameUrlHandlerMapping.class); - assertNotNull(beanNameMapping); - assertEquals(2, beanNameMapping.getOrder()); + assertThat(beanNameMapping).isNotNull(); + assertThat(beanNameMapping.getOrder()).isEqualTo(2); MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("GET"); HandlerExecutionChain chain = mapping.getHandler(request); - assertEquals(3, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor); - assertTrue(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor); - assertTrue(chain.getInterceptors()[2] instanceof ThemeChangeInterceptor); + assertThat(chain.getInterceptors().length).isEqualTo(3); + assertThat(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor).isTrue(); + assertThat(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor).isTrue(); + assertThat(chain.getInterceptors()[2] instanceof ThemeChangeInterceptor).isTrue(); SimpleUrlHandlerMapping mapping2 = appContext.getBean(SimpleUrlHandlerMapping.class); - assertNotNull(mapping2); + assertThat(mapping2).isNotNull(); SimpleControllerHandlerAdapter adapter = appContext.getBean(SimpleControllerHandlerAdapter.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); request = new MockHttpServletRequest("GET", "/foo"); chain = mapping2.getHandler(request); - assertEquals(4, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor); - assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor); - assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor); + assertThat(chain.getInterceptors().length).isEqualTo(4); + assertThat(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor).isTrue(); + assertThat(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor).isTrue(); + assertThat(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor).isTrue(); ModelAndView mv = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); - assertNull(mv.getViewName()); + assertThat((Object) mv.getViewName()).isNull(); request = new MockHttpServletRequest("GET", "/myapp/app/bar"); request.setContextPath("/myapp"); request.setServletPath("/app"); chain = mapping2.getHandler(request); - assertEquals(4, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor); - assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor); - assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor); + assertThat(chain.getInterceptors().length).isEqualTo(4); + assertThat(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor).isTrue(); + assertThat(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor).isTrue(); + assertThat(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor).isTrue(); mv = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); - assertEquals("baz", mv.getViewName()); + assertThat(mv.getViewName()).isEqualTo("baz"); request = new MockHttpServletRequest("GET", "/myapp/app/"); request.setContextPath("/myapp"); request.setServletPath("/app"); chain = mapping2.getHandler(request); - assertEquals(4, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor); - assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor); - assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor); + assertThat(chain.getInterceptors().length).isEqualTo(4); + assertThat(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor).isTrue(); + assertThat(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor).isTrue(); + assertThat(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor).isTrue(); mv = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); - assertEquals("root", mv.getViewName()); + assertThat(mv.getViewName()).isEqualTo("root"); request = new MockHttpServletRequest("GET", "/myapp/app/old"); request.setContextPath("/myapp"); @@ -626,20 +618,20 @@ public class MvcNamespaceTests { request.setQueryString("a=b"); chain = mapping2.getHandler(request); mv = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); - assertNotNull(mv.getView()); - assertEquals(RedirectView.class, mv.getView().getClass()); + assertThat(mv.getView()).isNotNull(); + assertThat(mv.getView().getClass()).isEqualTo(RedirectView.class); RedirectView redirectView = (RedirectView) mv.getView(); MockHttpServletResponse response = new MockHttpServletResponse(); redirectView.render(Collections.emptyMap(), request, response); - assertEquals("/new?a=b", response.getRedirectedUrl()); - assertEquals(308, response.getStatus()); + assertThat(response.getRedirectedUrl()).isEqualTo("/new?a=b"); + assertThat(response.getStatus()).isEqualTo(308); request = new MockHttpServletRequest("GET", "/bad"); chain = mapping2.getHandler(request); response = new MockHttpServletResponse(); mv = adapter.handle(request, response, chain.getHandler()); - assertNull(mv); - assertEquals(404, response.getStatus()); + assertThat(mv).isNull(); + assertThat(response.getStatus()).isEqualTo(404); } /** WebSphere gives trailing servlet path slashes by default!! */ @@ -657,34 +649,34 @@ public class MvcNamespaceTests { request.setServletPath("/app/"); request.setAttribute("com.ibm.websphere.servlet.uri_non_decoded", "/myapp/app/bar"); HandlerExecutionChain chain = mapping2.getHandler(request); - assertEquals(4, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor); - assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor); - assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor); + assertThat(chain.getInterceptors().length).isEqualTo(4); + assertThat(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor).isTrue(); + assertThat(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor).isTrue(); + assertThat(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor).isTrue(); ModelAndView mv2 = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); - assertEquals("baz", mv2.getViewName()); + assertThat(mv2.getViewName()).isEqualTo("baz"); request.setRequestURI("/myapp/app/"); request.setContextPath("/myapp"); request.setServletPath("/app/"); chain = mapping2.getHandler(request); - assertEquals(4, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor); - assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor); - assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor); + assertThat(chain.getInterceptors().length).isEqualTo(4); + assertThat(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor).isTrue(); + assertThat(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor).isTrue(); + assertThat(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor).isTrue(); ModelAndView mv3 = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); - assertEquals("root", mv3.getViewName()); + assertThat(mv3.getViewName()).isEqualTo("root"); request.setRequestURI("/myapp/"); request.setContextPath("/myapp"); request.setServletPath("/"); chain = mapping2.getHandler(request); - assertEquals(4, chain.getInterceptors().length); - assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor); - assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor); - assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor); + assertThat(chain.getInterceptors().length).isEqualTo(4); + assertThat(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor).isTrue(); + assertThat(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor).isTrue(); + assertThat(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor).isTrue(); mv3 = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); - assertEquals("root", mv3.getViewName()); + assertThat(mv3.getViewName()).isEqualTo("root"); } @Test @@ -692,22 +684,22 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-view-controllers-minimal.xml"); SimpleUrlHandlerMapping hm = this.appContext.getBean(SimpleUrlHandlerMapping.class); - assertNotNull(hm); + assertThat(hm).isNotNull(); ParameterizableViewController viewController = (ParameterizableViewController) hm.getUrlMap().get("/path"); - assertNotNull(viewController); - assertEquals("home", viewController.getViewName()); + assertThat(viewController).isNotNull(); + assertThat(viewController.getViewName()).isEqualTo("home"); ParameterizableViewController redirectViewController = (ParameterizableViewController) hm.getUrlMap().get("/old"); - assertNotNull(redirectViewController); + assertThat(redirectViewController).isNotNull(); assertThat(redirectViewController.getView()).isInstanceOf(RedirectView.class); ParameterizableViewController statusViewController = (ParameterizableViewController) hm.getUrlMap().get("/bad"); - assertNotNull(statusViewController); - assertEquals(404, statusViewController.getStatusCode().value()); + assertThat(statusViewController).isNotNull(); + assertThat(statusViewController.getStatusCode().value()).isEqualTo(404); BeanNameUrlHandlerMapping beanNameMapping = this.appContext.getBean(BeanNameUrlHandlerMapping.class); - assertNotNull(beanNameMapping); - assertEquals(2, beanNameMapping.getOrder()); + assertThat(beanNameMapping).isNotNull(); + assertThat(beanNameMapping.getOrder()).isEqualTo(2); } @Test @@ -719,17 +711,16 @@ public class MvcNamespaceTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.xml"); NativeWebRequest webRequest = new ServletWebRequest(request); - assertEquals(Collections.singletonList(MediaType.valueOf("application/rss+xml")), - manager.resolveMediaTypes(webRequest)); + assertThat(manager.resolveMediaTypes(webRequest)).isEqualTo(Collections.singletonList(MediaType.valueOf("application/rss+xml"))); ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class); - assertNotNull(compositeResolver); - assertEquals("Actual: " + compositeResolver.getViewResolvers(), 1, compositeResolver.getViewResolvers().size()); + assertThat(compositeResolver).isNotNull(); + assertThat(compositeResolver.getViewResolvers().size()).as("Actual: " + compositeResolver.getViewResolvers()).isEqualTo(1); ViewResolver resolver = compositeResolver.getViewResolvers().get(0); - assertEquals(ContentNegotiatingViewResolver.class, resolver.getClass()); + assertThat(resolver.getClass()).isEqualTo(ContentNegotiatingViewResolver.class); ContentNegotiatingViewResolver cnvr = (ContentNegotiatingViewResolver) resolver; - assertSame(manager, cnvr.getContentNegotiationManager()); + assertThat(cnvr.getContentNegotiationManager()).isSameAs(manager); } @Test @@ -737,19 +728,19 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-async-support.xml"); RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter); - assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass()); - assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout")); + assertThat(fieldAccessor.getPropertyValue("taskExecutor").getClass()).isEqualTo(ConcurrentTaskExecutor.class); + assertThat(fieldAccessor.getPropertyValue("asyncRequestTimeout")).isEqualTo(2500L); CallableProcessingInterceptor[] callableInterceptors = (CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors"); - assertEquals(1, callableInterceptors.length); + assertThat(callableInterceptors.length).isEqualTo(1); DeferredResultProcessingInterceptor[] deferredResultInterceptors = (DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors"); - assertEquals(1, deferredResultInterceptors.length); + assertThat(deferredResultInterceptors.length).isEqualTo(1); } @Test @@ -757,78 +748,78 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-view-resolution.xml"); ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class); - assertNotNull(compositeResolver); - assertEquals("Actual: " + compositeResolver.getViewResolvers(), 8, compositeResolver.getViewResolvers().size()); - assertEquals(Ordered.LOWEST_PRECEDENCE, compositeResolver.getOrder()); + assertThat(compositeResolver).isNotNull(); + assertThat(compositeResolver.getViewResolvers().size()).as("Actual: " + compositeResolver.getViewResolvers()).isEqualTo(8); + assertThat(compositeResolver.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); List resolvers = compositeResolver.getViewResolvers(); - assertEquals(BeanNameViewResolver.class, resolvers.get(0).getClass()); + assertThat(resolvers.get(0).getClass()).isEqualTo(BeanNameViewResolver.class); ViewResolver resolver = resolvers.get(1); - assertEquals(InternalResourceViewResolver.class, resolver.getClass()); + assertThat(resolver.getClass()).isEqualTo(InternalResourceViewResolver.class); DirectFieldAccessor accessor = new DirectFieldAccessor(resolver); - assertEquals(InternalResourceView.class, accessor.getPropertyValue("viewClass")); + assertThat(accessor.getPropertyValue("viewClass")).isEqualTo(InternalResourceView.class); - assertEquals(TilesViewResolver.class, resolvers.get(2).getClass()); + assertThat(resolvers.get(2).getClass()).isEqualTo(TilesViewResolver.class); resolver = resolvers.get(3); assertThat(resolver).isInstanceOf(FreeMarkerViewResolver.class); accessor = new DirectFieldAccessor(resolver); - assertEquals("freemarker-", accessor.getPropertyValue("prefix")); - assertEquals(".freemarker", accessor.getPropertyValue("suffix")); - assertArrayEquals(new String[] {"my*", "*Report"}, (String[]) accessor.getPropertyValue("viewNames")); - assertEquals(1024, accessor.getPropertyValue("cacheLimit")); + assertThat(accessor.getPropertyValue("prefix")).isEqualTo("freemarker-"); + assertThat(accessor.getPropertyValue("suffix")).isEqualTo(".freemarker"); + assertThat((String[]) accessor.getPropertyValue("viewNames")).isEqualTo(new String[] {"my*", "*Report"}); + assertThat(accessor.getPropertyValue("cacheLimit")).isEqualTo(1024); resolver = resolvers.get(4); assertThat(resolver).isInstanceOf(GroovyMarkupViewResolver.class); accessor = new DirectFieldAccessor(resolver); - assertEquals("", accessor.getPropertyValue("prefix")); - assertEquals(".tpl", accessor.getPropertyValue("suffix")); - assertEquals(1024, accessor.getPropertyValue("cacheLimit")); + assertThat(accessor.getPropertyValue("prefix")).isEqualTo(""); + assertThat(accessor.getPropertyValue("suffix")).isEqualTo(".tpl"); + assertThat(accessor.getPropertyValue("cacheLimit")).isEqualTo(1024); resolver = resolvers.get(5); assertThat(resolver).isInstanceOf(ScriptTemplateViewResolver.class); accessor = new DirectFieldAccessor(resolver); - assertEquals("", accessor.getPropertyValue("prefix")); - assertEquals("", accessor.getPropertyValue("suffix")); - assertEquals(1024, accessor.getPropertyValue("cacheLimit")); + assertThat(accessor.getPropertyValue("prefix")).isEqualTo(""); + assertThat(accessor.getPropertyValue("suffix")).isEqualTo(""); + assertThat(accessor.getPropertyValue("cacheLimit")).isEqualTo(1024); - assertEquals(InternalResourceViewResolver.class, resolvers.get(6).getClass()); - assertEquals(InternalResourceViewResolver.class, resolvers.get(7).getClass()); + assertThat(resolvers.get(6).getClass()).isEqualTo(InternalResourceViewResolver.class); + assertThat(resolvers.get(7).getClass()).isEqualTo(InternalResourceViewResolver.class); TilesConfigurer tilesConfigurer = appContext.getBean(TilesConfigurer.class); - assertNotNull(tilesConfigurer); + assertThat(tilesConfigurer).isNotNull(); String[] definitions = { "/org/springframework/web/servlet/resource/tiles/tiles1.xml", "/org/springframework/web/servlet/resource/tiles/tiles2.xml" }; accessor = new DirectFieldAccessor(tilesConfigurer); - assertArrayEquals(definitions, (String[]) accessor.getPropertyValue("definitions")); - assertTrue((boolean) accessor.getPropertyValue("checkRefresh")); - assertEquals(UnresolvingLocaleDefinitionsFactory.class, accessor.getPropertyValue("definitionsFactoryClass")); - assertEquals(SpringBeanPreparerFactory.class, accessor.getPropertyValue("preparerFactoryClass")); + assertThat((String[]) accessor.getPropertyValue("definitions")).isEqualTo(definitions); + assertThat((boolean) accessor.getPropertyValue("checkRefresh")).isTrue(); + assertThat(accessor.getPropertyValue("definitionsFactoryClass")).isEqualTo(UnresolvingLocaleDefinitionsFactory.class); + assertThat(accessor.getPropertyValue("preparerFactoryClass")).isEqualTo(SpringBeanPreparerFactory.class); FreeMarkerConfigurer freeMarkerConfigurer = appContext.getBean(FreeMarkerConfigurer.class); - assertNotNull(freeMarkerConfigurer); + assertThat(freeMarkerConfigurer).isNotNull(); accessor = new DirectFieldAccessor(freeMarkerConfigurer); - assertArrayEquals(new String[] {"/", "/test"}, (String[]) accessor.getPropertyValue("templateLoaderPaths")); + assertThat((String[]) accessor.getPropertyValue("templateLoaderPaths")).isEqualTo(new String[] {"/", "/test"}); GroovyMarkupConfigurer groovyMarkupConfigurer = appContext.getBean(GroovyMarkupConfigurer.class); - assertNotNull(groovyMarkupConfigurer); - assertEquals("/test", groovyMarkupConfigurer.getResourceLoaderPath()); - assertTrue(groovyMarkupConfigurer.isAutoIndent()); - assertFalse(groovyMarkupConfigurer.isCacheTemplates()); + assertThat(groovyMarkupConfigurer).isNotNull(); + assertThat(groovyMarkupConfigurer.getResourceLoaderPath()).isEqualTo("/test"); + assertThat(groovyMarkupConfigurer.isAutoIndent()).isTrue(); + assertThat(groovyMarkupConfigurer.isCacheTemplates()).isFalse(); ScriptTemplateConfigurer scriptTemplateConfigurer = appContext.getBean(ScriptTemplateConfigurer.class); - assertNotNull(scriptTemplateConfigurer); - assertEquals("render", scriptTemplateConfigurer.getRenderFunction()); - assertEquals(MediaType.TEXT_PLAIN_VALUE, scriptTemplateConfigurer.getContentType()); - assertEquals(StandardCharsets.ISO_8859_1, scriptTemplateConfigurer.getCharset()); - assertEquals("classpath:", scriptTemplateConfigurer.getResourceLoaderPath()); - assertFalse(scriptTemplateConfigurer.isSharedEngine()); + assertThat(scriptTemplateConfigurer).isNotNull(); + assertThat(scriptTemplateConfigurer.getRenderFunction()).isEqualTo("render"); + assertThat(scriptTemplateConfigurer.getContentType()).isEqualTo(MediaType.TEXT_PLAIN_VALUE); + assertThat(scriptTemplateConfigurer.getCharset()).isEqualTo(StandardCharsets.ISO_8859_1); + assertThat(scriptTemplateConfigurer.getResourceLoaderPath()).isEqualTo("classpath:"); + assertThat(scriptTemplateConfigurer.isSharedEngine()).isFalse(); String[] scripts = { "org/springframework/web/servlet/view/script/nashorn/render.js" }; accessor = new DirectFieldAccessor(scriptTemplateConfigurer); - assertArrayEquals(scripts, (String[]) accessor.getPropertyValue("scripts")); + assertThat((String[]) accessor.getPropertyValue("scripts")).isEqualTo(scripts); } @Test @@ -836,23 +827,23 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-view-resolution-content-negotiation.xml"); ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class); - assertNotNull(compositeResolver); - assertEquals(1, compositeResolver.getViewResolvers().size()); - assertEquals(Ordered.HIGHEST_PRECEDENCE, compositeResolver.getOrder()); + assertThat(compositeResolver).isNotNull(); + assertThat(compositeResolver.getViewResolvers().size()).isEqualTo(1); + assertThat(compositeResolver.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); List resolvers = compositeResolver.getViewResolvers(); - assertEquals(ContentNegotiatingViewResolver.class, resolvers.get(0).getClass()); + assertThat(resolvers.get(0).getClass()).isEqualTo(ContentNegotiatingViewResolver.class); ContentNegotiatingViewResolver cnvr = (ContentNegotiatingViewResolver) resolvers.get(0); - assertEquals(6, cnvr.getViewResolvers().size()); - assertEquals(1, cnvr.getDefaultViews().size()); - assertTrue(cnvr.isUseNotAcceptableStatusCode()); + assertThat(cnvr.getViewResolvers().size()).isEqualTo(6); + assertThat(cnvr.getDefaultViews().size()).isEqualTo(1); + assertThat(cnvr.isUseNotAcceptableStatusCode()).isTrue(); String beanName = "contentNegotiationManager"; DirectFieldAccessor accessor = new DirectFieldAccessor(cnvr); ContentNegotiationManager manager = (ContentNegotiationManager) accessor.getPropertyValue(beanName); - assertNotNull(manager); - assertSame(manager, this.appContext.getBean(ContentNegotiationManager.class)); - assertSame(manager, this.appContext.getBean("mvcContentNegotiationManager")); + assertThat(manager).isNotNull(); + assertThat(this.appContext.getBean(ContentNegotiationManager.class)).isSameAs(manager); + assertThat(this.appContext.getBean("mvcContentNegotiationManager")).isSameAs(manager); } @Test @@ -860,9 +851,9 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-view-resolution-custom-order.xml"); ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class); - assertNotNull(compositeResolver); - assertEquals("Actual: " + compositeResolver.getViewResolvers(), 1, compositeResolver.getViewResolvers().size()); - assertEquals(123, compositeResolver.getOrder()); + assertThat(compositeResolver).isNotNull(); + assertThat(compositeResolver.getViewResolvers().size()).as("Actual: " + compositeResolver.getViewResolvers()).isEqualTo(1); + assertThat(compositeResolver.getOrder()).isEqualTo(123); } @Test @@ -870,19 +861,19 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-path-matching-mappings.xml"); RequestMappingHandlerMapping requestMapping = appContext.getBean(RequestMappingHandlerMapping.class); - assertNotNull(requestMapping); - assertEquals(TestPathHelper.class, requestMapping.getUrlPathHelper().getClass()); - assertEquals(TestPathMatcher.class, requestMapping.getPathMatcher().getClass()); + assertThat(requestMapping).isNotNull(); + assertThat(requestMapping.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class); + assertThat(requestMapping.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class); SimpleUrlHandlerMapping viewController = appContext.getBean(VIEWCONTROLLER_BEAN_NAME, SimpleUrlHandlerMapping.class); - assertNotNull(viewController); - assertEquals(TestPathHelper.class, viewController.getUrlPathHelper().getClass()); - assertEquals(TestPathMatcher.class, viewController.getPathMatcher().getClass()); + assertThat(viewController).isNotNull(); + assertThat(viewController.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class); + assertThat(viewController.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class); for (SimpleUrlHandlerMapping handlerMapping : appContext.getBeansOfType(SimpleUrlHandlerMapping.class).values()) { - assertNotNull(handlerMapping); - assertEquals(TestPathHelper.class, handlerMapping.getUrlPathHelper().getClass()); - assertEquals(TestPathMatcher.class, handlerMapping.getPathMatcher().getClass()); + assertThat(handlerMapping).isNotNull(); + assertThat(handlerMapping.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class); + assertThat(handlerMapping.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class); } } @@ -891,23 +882,23 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-cors-minimal.xml"); String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class); - assertEquals(2, beanNames.length); + assertThat(beanNames.length).isEqualTo(2); for (String beanName : beanNames) { AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping)appContext.getBean(beanName); - assertNotNull(handlerMapping); + assertThat(handlerMapping).isNotNull(); DirectFieldAccessor accessor = new DirectFieldAccessor(handlerMapping); Map configs = ((UrlBasedCorsConfigurationSource) accessor .getPropertyValue("corsConfigurationSource")).getCorsConfigurations(); - assertNotNull(configs); - assertEquals(1, configs.size()); + assertThat(configs).isNotNull(); + assertThat(configs.size()).isEqualTo(1); CorsConfiguration config = configs.get("/**"); - assertNotNull(config); - assertArrayEquals(new String[]{"*"}, config.getAllowedOrigins().toArray()); - assertArrayEquals(new String[]{"GET", "HEAD", "POST"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray()); - assertNull(config.getExposedHeaders()); - assertNull(config.getAllowCredentials()); - assertEquals(Long.valueOf(1800), config.getMaxAge()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[]{"*"}); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[]{"GET", "HEAD", "POST"}); + assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[]{"*"}); + assertThat(config.getExposedHeaders()).isNull(); + assertThat(config.getAllowCredentials()).isNull(); + assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(1800)); } } @@ -916,30 +907,30 @@ public class MvcNamespaceTests { loadBeanDefinitions("mvc-config-cors.xml"); String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class); - assertEquals(2, beanNames.length); + assertThat(beanNames.length).isEqualTo(2); for (String beanName : beanNames) { AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping)appContext.getBean(beanName); - assertNotNull(handlerMapping); + assertThat(handlerMapping).isNotNull(); DirectFieldAccessor accessor = new DirectFieldAccessor(handlerMapping); Map configs = ((UrlBasedCorsConfigurationSource) accessor .getPropertyValue("corsConfigurationSource")).getCorsConfigurations(); - assertNotNull(configs); - assertEquals(2, configs.size()); + assertThat(configs).isNotNull(); + assertThat(configs.size()).isEqualTo(2); CorsConfiguration config = configs.get("/api/**"); - assertNotNull(config); - assertArrayEquals(new String[]{"https://domain1.com", "https://domain2.com"}, config.getAllowedOrigins().toArray()); - assertArrayEquals(new String[]{"GET", "PUT"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[]{"header1", "header2", "header3"}, config.getAllowedHeaders().toArray()); - assertArrayEquals(new String[]{"header1", "header2"}, config.getExposedHeaders().toArray()); - assertFalse(config.getAllowCredentials()); - assertEquals(Long.valueOf(123), config.getMaxAge()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[]{"https://domain1.com", "https://domain2.com"}); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[]{"GET", "PUT"}); + assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[]{"header1", "header2", "header3"}); + assertThat(config.getExposedHeaders().toArray()).isEqualTo(new String[]{"header1", "header2"}); + assertThat(config.getAllowCredentials()).isFalse(); + assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(123)); config = configs.get("/resources/**"); - assertArrayEquals(new String[]{"https://domain1.com"}, config.getAllowedOrigins().toArray()); - assertArrayEquals(new String[]{"GET", "HEAD", "POST"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray()); - assertNull(config.getExposedHeaders()); - assertNull(config.getAllowCredentials()); - assertEquals(Long.valueOf(1800), config.getMaxAge()); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[]{"https://domain1.com"}); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[]{"GET", "HEAD", "POST"}); + assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[]{"*"}); + assertThat(config.getExposedHeaders()).isNull(); + assertThat(config.getAllowCredentials()).isNull(); + assertThat(config.getMaxAge()).isEqualTo(1800L); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ContentNegotiationConfigurerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ContentNegotiationConfigurerTests.java index 34922d24d2b..402b873d262 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ContentNegotiationConfigurerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ContentNegotiationConfigurerTests.java @@ -30,7 +30,7 @@ import org.springframework.web.accept.FixedContentNegotiationStrategy; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link ContentNegotiationConfigurer} tests. @@ -59,20 +59,17 @@ public class ContentNegotiationConfigurerTests { this.servletRequest.setRequestURI("/flower.gif"); - assertEquals("Should be able to resolve file extensions by default", - MediaType.IMAGE_GIF, manager.resolveMediaTypes(this.webRequest).get(0)); + assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).as("Should be able to resolve file extensions by default").isEqualTo(MediaType.IMAGE_GIF); this.servletRequest.setRequestURI("/flower?format=gif"); this.servletRequest.addParameter("format", "gif"); - assertEquals("Should not resolve request parameters by default", - ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).as("Should not resolve request parameters by default").isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST); this.servletRequest.setRequestURI("/flower"); this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE); - assertEquals("Should resolve Accept header by default", - MediaType.IMAGE_GIF, manager.resolveMediaTypes(this.webRequest).get(0)); + assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).as("Should resolve Accept header by default").isEqualTo(MediaType.IMAGE_GIF); } @Test @@ -81,7 +78,7 @@ public class ContentNegotiationConfigurerTests { ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager(); this.servletRequest.setRequestURI("/flower.json"); - assertEquals(MediaType.APPLICATION_JSON, manager.resolveMediaTypes(this.webRequest).get(0)); + assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).isEqualTo(MediaType.APPLICATION_JSON); } @Test @@ -94,7 +91,7 @@ public class ContentNegotiationConfigurerTests { this.servletRequest.setRequestURI("/flower"); this.servletRequest.addParameter("f", "json"); - assertEquals(MediaType.APPLICATION_JSON, manager.resolveMediaTypes(this.webRequest).get(0)); + assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).isEqualTo(MediaType.APPLICATION_JSON); } @Test @@ -105,7 +102,7 @@ public class ContentNegotiationConfigurerTests { this.servletRequest.setRequestURI("/flower"); this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE); - assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST); } @Test @@ -113,7 +110,7 @@ public class ContentNegotiationConfigurerTests { this.configurer.defaultContentType(MediaType.APPLICATION_JSON); ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager(); - assertEquals(MediaType.APPLICATION_JSON, manager.resolveMediaTypes(this.webRequest).get(0)); + assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).isEqualTo(MediaType.APPLICATION_JSON); } @Test @@ -121,7 +118,7 @@ public class ContentNegotiationConfigurerTests { this.configurer.defaultContentType(MediaType.APPLICATION_JSON, MediaType.ALL); ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager(); - assertEquals(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.ALL), manager.resolveMediaTypes(this.webRequest)); + assertThat(manager.resolveMediaTypes(this.webRequest)).isEqualTo(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.ALL)); } @Test @@ -129,7 +126,7 @@ public class ContentNegotiationConfigurerTests { this.configurer.defaultContentTypeStrategy(new FixedContentNegotiationStrategy(MediaType.APPLICATION_JSON)); ContentNegotiationManager manager = this.configurer.buildContentNegotiationManager(); - assertEquals(MediaType.APPLICATION_JSON, manager.resolveMediaTypes(this.webRequest).get(0)); + assertThat(manager.resolveMediaTypes(this.webRequest).get(0)).isEqualTo(MediaType.APPLICATION_JSON); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/CorsRegistryTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/CorsRegistryTests.java index 3328301086a..67f8691125c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/CorsRegistryTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/CorsRegistryTests.java @@ -24,8 +24,7 @@ import org.junit.Test; import org.springframework.web.cors.CorsConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with a {@link CorsRegistry}. @@ -43,14 +42,14 @@ public class CorsRegistryTests { @Test public void noMapping() { - assertTrue(this.registry.getCorsConfigurations().isEmpty()); + assertThat(this.registry.getCorsConfigurations().isEmpty()).isTrue(); } @Test public void multipleMappings() { this.registry.addMapping("/foo"); this.registry.addMapping("/bar"); - assertEquals(2, this.registry.getCorsConfigurations().size()); + assertThat(this.registry.getCorsConfigurations().size()).isEqualTo(2); } @Test @@ -59,14 +58,14 @@ public class CorsRegistryTests { .allowedMethods("DELETE").allowCredentials(false).allowedHeaders("header1", "header2") .exposedHeaders("header3", "header4").maxAge(3600); Map configs = this.registry.getCorsConfigurations(); - assertEquals(1, configs.size()); + assertThat(configs.size()).isEqualTo(1); CorsConfiguration config = configs.get("/foo"); - assertEquals(Arrays.asList("https://domain2.com", "https://domain2.com"), config.getAllowedOrigins()); - assertEquals(Arrays.asList("DELETE"), config.getAllowedMethods()); - assertEquals(Arrays.asList("header1", "header2"), config.getAllowedHeaders()); - assertEquals(Arrays.asList("header3", "header4"), config.getExposedHeaders()); - assertEquals(false, config.getAllowCredentials()); - assertEquals(Long.valueOf(3600), config.getMaxAge()); + assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("https://domain2.com", "https://domain2.com")); + assertThat(config.getAllowedMethods()).isEqualTo(Arrays.asList("DELETE")); + assertThat(config.getAllowedHeaders()).isEqualTo(Arrays.asList("header1", "header2")); + assertThat(config.getExposedHeaders()).isEqualTo(Arrays.asList("header3", "header4")); + assertThat(config.getAllowCredentials()).isEqualTo(false); + assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(3600)); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurerTests.java index f45b5f5a9fa..be1191ddfc4 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurerTests.java @@ -28,9 +28,7 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with a {@link DefaultServletHandlerConfigurer}. @@ -56,7 +54,7 @@ public class DefaultServletHandlerConfigurerTests { @Test public void notEnabled() { - assertNull(configurer.buildHandlerMapping()); + assertThat(configurer.buildHandlerMapping()).isNull(); } @Test @@ -65,14 +63,14 @@ public class DefaultServletHandlerConfigurerTests { SimpleUrlHandlerMapping handlerMapping = configurer.buildHandlerMapping(); DefaultServletHttpRequestHandler handler = (DefaultServletHttpRequestHandler) handlerMapping.getUrlMap().get("/**"); - assertNotNull(handler); - assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder()); + assertThat(handler).isNotNull(); + assertThat(handlerMapping.getOrder()).isEqualTo(Integer.MAX_VALUE); handler.handleRequest(new MockHttpServletRequest(), response); String expected = "default"; - assertEquals("The ServletContext was not called with the default servlet name", expected, servletContext.url); - assertEquals("The request was not forwarded", expected, response.getForwardedUrl()); + assertThat(servletContext.url).as("The ServletContext was not called with the default servlet name").isEqualTo(expected); + assertThat(response.getForwardedUrl()).as("The request was not forwarded").isEqualTo(expected); } @Test @@ -81,14 +79,14 @@ public class DefaultServletHandlerConfigurerTests { SimpleUrlHandlerMapping handlerMapping = configurer.buildHandlerMapping(); DefaultServletHttpRequestHandler handler = (DefaultServletHttpRequestHandler) handlerMapping.getUrlMap().get("/**"); - assertNotNull(handler); - assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder()); + assertThat(handler).isNotNull(); + assertThat(handlerMapping.getOrder()).isEqualTo(Integer.MAX_VALUE); handler.handleRequest(new MockHttpServletRequest(), response); String expected = "defaultServlet"; - assertEquals("The ServletContext was not called with the default servlet name", expected, servletContext.url); - assertEquals("The request was not forwarded", expected, response.getForwardedUrl()); + assertThat(servletContext.url).as("The ServletContext was not called with the default servlet name").isEqualTo(expected); + assertThat(response.getForwardedUrl()).as("The request was not forwarded").isEqualTo(expected); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfigurationTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfigurationTests.java index 28b68fe5b5b..1fa3dd92abf 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfigurationTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfigurationTests.java @@ -45,10 +45,7 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; import org.springframework.web.util.UrlPathHelper; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -111,13 +108,14 @@ public class DelegatingWebMvcConfigurationTests { verify(webMvcConfigurer).addReturnValueHandlers(handlers.capture()); verify(webMvcConfigurer).configureAsyncSupport(asyncConfigurer.capture()); - assertNotNull(initializer); - assertSame(conversionService.getValue(), initializer.getConversionService()); - assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean); - assertEquals(0, resolvers.getValue().size()); - assertEquals(0, handlers.getValue().size()); - assertEquals(converters.getValue(), adapter.getMessageConverters()); - assertNotNull(asyncConfigurer); + assertThat(initializer).isNotNull(); + assertThat(initializer.getConversionService()).isSameAs(conversionService.getValue()); + boolean condition = initializer.getValidator() instanceof LocalValidatorFactoryBean; + assertThat(condition).isTrue(); + assertThat(resolvers.getValue().size()).isEqualTo(0); + assertThat(handlers.getValue().size()).isEqualTo(0); + assertThat(adapter.getMessageConverters()).isEqualTo(converters.getValue()); + assertThat(asyncConfigurer).isNotNull(); } @Test @@ -142,9 +140,9 @@ public class DelegatingWebMvcConfigurationTests { RequestMappingHandlerAdapter adapter = delegatingConfig.requestMappingHandlerAdapter( this.delegatingConfig.mvcContentNegotiationManager(), this.delegatingConfig.mvcConversionService(), this.delegatingConfig.mvcValidator()); - assertEquals("Only one custom converter should be registered", 2, adapter.getMessageConverters().size()); - assertSame(customConverter, adapter.getMessageConverters().get(0)); - assertSame(stringConverter, adapter.getMessageConverters().get(1)); + assertThat(adapter.getMessageConverters().size()).as("Only one custom converter should be registered").isEqualTo(2); + assertThat(adapter.getMessageConverters().get(0)).isSameAs(customConverter); + assertThat(adapter.getMessageConverters().get(1)).isSameAs(stringConverter); } @Test @@ -176,11 +174,14 @@ public class DelegatingWebMvcConfigurationTests { verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture()); verify(webMvcConfigurer).configureHandlerExceptionResolvers(exceptionResolvers.capture()); - assertEquals(3, exceptionResolvers.getValue().size()); - assertTrue(exceptionResolvers.getValue().get(0) instanceof ExceptionHandlerExceptionResolver); - assertTrue(exceptionResolvers.getValue().get(1) instanceof ResponseStatusExceptionResolver); - assertTrue(exceptionResolvers.getValue().get(2) instanceof DefaultHandlerExceptionResolver); - assertTrue(converters.getValue().size() > 0); + assertThat(exceptionResolvers.getValue().size()).isEqualTo(3); + boolean condition2 = exceptionResolvers.getValue().get(0) instanceof ExceptionHandlerExceptionResolver; + assertThat(condition2).isTrue(); + boolean condition1 = exceptionResolvers.getValue().get(1) instanceof ResponseStatusExceptionResolver; + assertThat(condition1).isTrue(); + boolean condition = exceptionResolvers.getValue().get(2) instanceof DefaultHandlerExceptionResolver; + assertThat(condition).isTrue(); + assertThat(converters.getValue().size() > 0).isTrue(); } @Test @@ -197,7 +198,7 @@ public class DelegatingWebMvcConfigurationTests { HandlerExceptionResolverComposite composite = (HandlerExceptionResolverComposite) delegatingConfig .handlerExceptionResolver(delegatingConfig.mvcContentNegotiationManager()); - assertEquals("Only one custom converter is expected", 1, composite.getExceptionResolvers().size()); + assertThat(composite.getExceptionResolvers().size()).as("Only one custom converter is expected").isEqualTo(1); } @Test @@ -220,17 +221,12 @@ public class DelegatingWebMvcConfigurationTests { RequestMappingHandlerMapping handlerMapping = delegatingConfig.requestMappingHandlerMapping( delegatingConfig.mvcContentNegotiationManager(), delegatingConfig.mvcConversionService(), delegatingConfig.mvcResourceUrlProvider()); - assertNotNull(handlerMapping); - assertEquals("PathMatchConfigurer should configure RegisteredSuffixPatternMatch", - true, handlerMapping.useRegisteredSuffixPatternMatch()); - assertEquals("PathMatchConfigurer should configure SuffixPatternMatch", - true, handlerMapping.useSuffixPatternMatch()); - assertEquals("PathMatchConfigurer should configure TrailingSlashMatch", - false, handlerMapping.useTrailingSlashMatch()); - assertEquals("PathMatchConfigurer should configure UrlPathHelper", - pathHelper, handlerMapping.getUrlPathHelper()); - assertEquals("PathMatchConfigurer should configure PathMatcher", - pathMatcher, handlerMapping.getPathMatcher()); + assertThat(handlerMapping).isNotNull(); + assertThat(handlerMapping.useRegisteredSuffixPatternMatch()).as("PathMatchConfigurer should configure RegisteredSuffixPatternMatch").isEqualTo(true); + assertThat(handlerMapping.useSuffixPatternMatch()).as("PathMatchConfigurer should configure SuffixPatternMatch").isEqualTo(true); + assertThat(handlerMapping.useTrailingSlashMatch()).as("PathMatchConfigurer should configure TrailingSlashMatch").isEqualTo(false); + assertThat(handlerMapping.getUrlPathHelper()).as("PathMatchConfigurer should configure UrlPathHelper").isEqualTo(pathHelper); + assertThat(handlerMapping.getPathMatcher()).as("PathMatchConfigurer should configure PathMatcher").isEqualTo(pathMatcher); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/InterceptorRegistryTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/InterceptorRegistryTests.java index 653fe82245a..c7e6c19c5b4 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/InterceptorRegistryTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/InterceptorRegistryTests.java @@ -40,10 +40,8 @@ import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapt import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.theme.ThemeChangeInterceptor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * Test fixture with a {@link InterceptorRegistry}, two {@link HandlerInterceptor}s and two @@ -80,7 +78,7 @@ public class InterceptorRegistryTests { public void addInterceptor() { this.registry.addInterceptor(this.interceptor1); List interceptors = getInterceptorsForPath(null); - assertEquals(Arrays.asList(this.interceptor1), interceptors); + assertThat(interceptors).isEqualTo(Arrays.asList(this.interceptor1)); } @Test @@ -88,7 +86,7 @@ public class InterceptorRegistryTests { this.registry.addInterceptor(this.interceptor1); this.registry.addInterceptor(this.interceptor2); List interceptors = getInterceptorsForPath(null); - assertEquals(Arrays.asList(this.interceptor1, this.interceptor2), interceptors); + assertThat(interceptors).isEqualTo(Arrays.asList(this.interceptor1, this.interceptor2)); } @Test @@ -96,9 +94,9 @@ public class InterceptorRegistryTests { this.registry.addInterceptor(this.interceptor1).addPathPatterns("/path1/**").excludePathPatterns("/path1/secret"); this.registry.addInterceptor(this.interceptor2).addPathPatterns("/path2"); - assertEquals(Arrays.asList(this.interceptor1), getInterceptorsForPath("/path1/test")); - assertEquals(Arrays.asList(this.interceptor2), getInterceptorsForPath("/path2")); - assertEquals(Collections.emptyList(), getInterceptorsForPath("/path1/secret")); + assertThat(getInterceptorsForPath("/path1/test")).isEqualTo(Arrays.asList(this.interceptor1)); + assertThat(getInterceptorsForPath("/path2")).isEqualTo(Arrays.asList(this.interceptor2)); + assertThat(getInterceptorsForPath("/path1/secret")).isEqualTo(Collections.emptyList()); } @Test @@ -106,7 +104,7 @@ public class InterceptorRegistryTests { this.registry.addWebRequestInterceptor(this.webInterceptor1); List interceptors = getInterceptorsForPath(null); - assertEquals(1, interceptors.size()); + assertThat(interceptors.size()).isEqualTo(1); verifyWebInterceptor(interceptors.get(0), this.webInterceptor1); } @@ -116,7 +114,7 @@ public class InterceptorRegistryTests { this.registry.addWebRequestInterceptor(this.webInterceptor2); List interceptors = getInterceptorsForPath(null); - assertEquals(2, interceptors.size()); + assertThat(interceptors.size()).isEqualTo(2); verifyWebInterceptor(interceptors.get(0), this.webInterceptor1); verifyWebInterceptor(interceptors.get(1), this.webInterceptor2); } @@ -127,7 +125,7 @@ public class InterceptorRegistryTests { this.registry.addInterceptor(interceptor1).addPathPatterns("/path1/**").pathMatcher(pathMatcher); MappedInterceptor mappedInterceptor = (MappedInterceptor) this.registry.getInterceptors().get(0); - assertSame(pathMatcher, mappedInterceptor.getPathMatcher()); + assertThat(mappedInterceptor.getPathMatcher()).isSameAs(pathMatcher); } @Test @@ -136,11 +134,11 @@ public class InterceptorRegistryTests { this.registry.addWebRequestInterceptor(this.webInterceptor2).addPathPatterns("/path2"); List interceptors = getInterceptorsForPath("/path1"); - assertEquals(1, interceptors.size()); + assertThat(interceptors.size()).isEqualTo(1); verifyWebInterceptor(interceptors.get(0), this.webInterceptor1); interceptors = getInterceptorsForPath("/path2"); - assertEquals(1, interceptors.size()); + assertThat(interceptors.size()).isEqualTo(1); verifyWebInterceptor(interceptors.get(0), this.webInterceptor2); } @@ -149,9 +147,9 @@ public class InterceptorRegistryTests { this.registry.addInterceptor(this.interceptor1).excludePathPatterns("/path1/secret"); this.registry.addInterceptor(this.interceptor2).addPathPatterns("/path2"); - assertEquals(Collections.singletonList(this.interceptor1), getInterceptorsForPath("/path1")); - assertEquals(Arrays.asList(this.interceptor1, this.interceptor2), getInterceptorsForPath("/path2")); - assertEquals(Collections.emptyList(), getInterceptorsForPath("/path1/secret")); + assertThat(getInterceptorsForPath("/path1")).isEqualTo(Collections.singletonList(this.interceptor1)); + assertThat(getInterceptorsForPath("/path2")).isEqualTo(Arrays.asList(this.interceptor1, this.interceptor2)); + assertThat(getInterceptorsForPath("/path1/secret")).isEqualTo(Collections.emptyList()); } @Test @@ -160,10 +158,10 @@ public class InterceptorRegistryTests { this.registry.addInterceptor(this.interceptor2).order(Ordered.HIGHEST_PRECEDENCE); List interceptors = this.registry.getInterceptors(); - assertEquals(2, interceptors.size()); + assertThat(interceptors.size()).isEqualTo(2); - assertSame(this.interceptor2, interceptors.get(0)); - assertSame(this.interceptor1, interceptors.get(1)); + assertThat(interceptors.get(0)).isSameAs(this.interceptor2); + assertThat(interceptors.get(1)).isSameAs(this.interceptor1); } @Test @@ -172,10 +170,10 @@ public class InterceptorRegistryTests { this.registry.addInterceptor(this.interceptor2).order(0); List interceptors = this.registry.getInterceptors(); - assertEquals(2, interceptors.size()); + assertThat(interceptors.size()).isEqualTo(2); - assertSame(this.interceptor1, interceptors.get(0)); - assertSame(this.interceptor2, interceptors.get(1)); + assertThat(interceptors.get(0)).isSameAs(this.interceptor1); + assertThat(interceptors.get(1)).isSameAs(this.interceptor2); } @@ -202,9 +200,10 @@ public class InterceptorRegistryTests { private void verifyWebInterceptor(HandlerInterceptor interceptor, TestWebRequestInterceptor webInterceptor) throws Exception { - assertTrue(interceptor instanceof WebRequestHandlerInterceptorAdapter); + boolean condition = interceptor instanceof WebRequestHandlerInterceptorAdapter; + assertThat(condition).isTrue(); interceptor.preHandle(this.request, this.response, null); - assertTrue(webInterceptor.preHandleInvoked); + assertThat(webInterceptor.preHandleInvoked).isTrue(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java index c162ff8a421..6d86b961a3c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java @@ -49,11 +49,6 @@ import org.springframework.web.servlet.resource.WebJarsResourceResolver; import org.springframework.web.util.UrlPathHelper; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Unit tests for {@link ResourceHandlerRegistry}. @@ -85,7 +80,7 @@ public class ResourceHandlerRegistryTests { @Test public void noResourceHandlers() throws Exception { this.registry = new ResourceHandlerRegistry(new GenericWebApplicationContext(), new MockServletContext()); - assertNull(this.registry.getHandlerMapping()); + assertThat((Object) this.registry.getHandlerMapping()).isNull(); } @Test @@ -97,15 +92,15 @@ public class ResourceHandlerRegistryTests { ResourceHttpRequestHandler handler = getHandler("/resources/**"); handler.handleRequest(request, this.response); - assertEquals("test stylesheet content", this.response.getContentAsString()); + assertThat(this.response.getContentAsString()).isEqualTo("test stylesheet content"); } @Test public void cachePeriod() { - assertEquals(-1, getHandler("/resources/**").getCacheSeconds()); + assertThat(getHandler("/resources/**").getCacheSeconds()).isEqualTo(-1); this.registration.setCachePeriod(0); - assertEquals(0, getHandler("/resources/**").getCacheSeconds()); + assertThat(getHandler("/resources/**").getCacheSeconds()).isEqualTo(0); } @Test @@ -119,16 +114,16 @@ public class ResourceHandlerRegistryTests { @Test public void order() { - assertEquals(Integer.MAX_VALUE -1, registry.getHandlerMapping().getOrder()); + assertThat(registry.getHandlerMapping().getOrder()).isEqualTo(Integer.MAX_VALUE -1); registry.setOrder(0); - assertEquals(0, registry.getHandlerMapping().getOrder()); + assertThat(registry.getHandlerMapping().getOrder()).isEqualTo(0); } @Test public void hasMappingForPattern() { - assertTrue(this.registry.hasMappingForPattern("/resources/**")); - assertFalse(this.registry.hasMappingForPattern("/whatever")); + assertThat(this.registry.hasMappingForPattern("/resources/**")).isTrue(); + assertThat(this.registry.hasMappingForPattern("/whatever")).isFalse(); } @Test @@ -233,14 +228,14 @@ public class ResourceHandlerRegistryTests { ResourceHttpRequestHandler handler = getHandler("/resources/**"); UrlResource resource = (UrlResource) handler.getLocations().get(1); - assertEquals("file:/tmp", resource.getURL().toString()); - assertNotNull(handler.getUrlPathHelper()); + assertThat(resource.getURL().toString()).isEqualTo("file:/tmp"); + assertThat(handler.getUrlPathHelper()).isNotNull(); List resolvers = handler.getResourceResolvers(); PathResourceResolver resolver = (PathResourceResolver) resolvers.get(resolvers.size()-1); Map locationCharsets = resolver.getLocationCharsets(); - assertEquals(1, locationCharsets.size()); - assertEquals(StandardCharsets.ISO_8859_1, locationCharsets.values().iterator().next()); + assertThat(locationCharsets.size()).isEqualTo(1); + assertThat(locationCharsets.values().iterator().next()).isEqualTo(StandardCharsets.ISO_8859_1); } private ResourceHttpRequestHandler getHandler(String pathPattern) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistryTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistryTests.java index 14d964ceeed..e33ce9f16de 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistryTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistryTests.java @@ -30,11 +30,7 @@ import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import org.springframework.web.servlet.mvc.ParameterizableViewController; import org.springframework.web.servlet.view.RedirectView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with a {@link ViewControllerRegistry}. @@ -60,7 +56,7 @@ public class ViewControllerRegistryTests { @Test public void noViewControllers() { - assertNull(this.registry.buildHandlerMapping()); + assertThat(this.registry.buildHandlerMapping()).isNull(); } @Test @@ -68,10 +64,10 @@ public class ViewControllerRegistryTests { this.registry.addViewController("/path").setViewName("viewName"); ParameterizableViewController controller = getController("/path"); - assertEquals("viewName", controller.getViewName()); - assertNull(controller.getStatusCode()); - assertFalse(controller.isStatusOnly()); - assertNotNull(controller.getApplicationContext()); + assertThat(controller.getViewName()).isEqualTo("viewName"); + assertThat(controller.getStatusCode()).isNull(); + assertThat(controller.isStatusOnly()).isFalse(); + assertThat(controller.getApplicationContext()).isNotNull(); } @Test @@ -79,10 +75,10 @@ public class ViewControllerRegistryTests { this.registry.addViewController("/path"); ParameterizableViewController controller = getController("/path"); - assertNull(controller.getViewName()); - assertNull(controller.getStatusCode()); - assertFalse(controller.isStatusOnly()); - assertNotNull(controller.getApplicationContext()); + assertThat(controller.getViewName()).isNull(); + assertThat(controller.getStatusCode()).isNull(); + assertThat(controller.isStatusOnly()).isFalse(); + assertThat(controller.getApplicationContext()).isNotNull(); } @Test @@ -93,9 +89,9 @@ public class ViewControllerRegistryTests { this.request.setContextPath("/context"); redirectView.render(Collections.emptyMap(), this.request, this.response); - assertEquals(302, this.response.getStatus()); - assertEquals("/context/redirectTo", this.response.getRedirectedUrl()); - assertNotNull(redirectView.getApplicationContext()); + assertThat(this.response.getStatus()).isEqualTo(302); + assertThat(this.response.getRedirectedUrl()).isEqualTo("/context/redirectTo"); + assertThat(redirectView.getApplicationContext()).isNotNull(); } @Test @@ -110,9 +106,9 @@ public class ViewControllerRegistryTests { this.request.setContextPath("/context"); redirectView.render(Collections.emptyMap(), this.request, this.response); - assertEquals(308, this.response.getStatus()); - assertEquals("/redirectTo?a=b", response.getRedirectedUrl()); - assertNotNull(redirectView.getApplicationContext()); + assertThat(this.response.getStatus()).isEqualTo(308); + assertThat(response.getRedirectedUrl()).isEqualTo("/redirectTo?a=b"); + assertThat(redirectView.getApplicationContext()).isNotNull(); } @Test @@ -120,36 +116,36 @@ public class ViewControllerRegistryTests { this.registry.addStatusController("/path", HttpStatus.NOT_FOUND); ParameterizableViewController controller = getController("/path"); - assertNull(controller.getViewName()); - assertEquals(HttpStatus.NOT_FOUND, controller.getStatusCode()); - assertTrue(controller.isStatusOnly()); - assertNotNull(controller.getApplicationContext()); + assertThat(controller.getViewName()).isNull(); + assertThat(controller.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(controller.isStatusOnly()).isTrue(); + assertThat(controller.getApplicationContext()).isNotNull(); } @Test public void order() { this.registry.addViewController("/path"); SimpleUrlHandlerMapping handlerMapping = this.registry.buildHandlerMapping(); - assertEquals(1, handlerMapping.getOrder()); + assertThat(handlerMapping.getOrder()).isEqualTo(1); this.registry.setOrder(2); handlerMapping = this.registry.buildHandlerMapping(); - assertEquals(2, handlerMapping.getOrder()); + assertThat(handlerMapping.getOrder()).isEqualTo(2); } private ParameterizableViewController getController(String path) { Map urlMap = this.registry.buildHandlerMapping().getUrlMap(); ParameterizableViewController controller = (ParameterizableViewController) urlMap.get(path); - assertNotNull(controller); + assertThat(controller).isNotNull(); return controller; } private RedirectView getRedirectView(String path) { ParameterizableViewController controller = getController(path); - assertNull(controller.getViewName()); - assertNotNull(controller.getView()); - assertEquals(RedirectView.class, controller.getView().getClass()); + assertThat(controller.getViewName()).isNull(); + assertThat(controller.getView()).isNotNull(); + assertThat(controller.getView().getClass()).isEqualTo(RedirectView.class); return (RedirectView) controller.getView(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolutionIntegrationTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolutionIntegrationTests.java index 771585554ce..c2565447152 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolutionIntegrationTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolutionIntegrationTests.java @@ -38,8 +38,8 @@ import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer; import org.springframework.web.servlet.view.tiles3.TilesConfigurer; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; /** * Integration tests for view resolution with {@code @EnableWebMvc}. @@ -52,19 +52,19 @@ public class ViewResolutionIntegrationTests { @Test public void freemarker() throws Exception { MockHttpServletResponse response = runTest(FreeMarkerWebConfig.class); - assertEquals("Hello World!", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Hello World!"); } @Test public void tiles() throws Exception { MockHttpServletResponse response = runTest(TilesWebConfig.class); - assertEquals("/WEB-INF/index.jsp", response.getForwardedUrl()); + assertThat(response.getForwardedUrl()).isEqualTo("/WEB-INF/index.jsp"); } @Test public void groovyMarkup() throws Exception { MockHttpServletResponse response = runTest(GroovyMarkupWebConfig.class); - assertEquals("Hello World!", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Hello World!"); } @Test @@ -93,7 +93,7 @@ public class ViewResolutionIntegrationTests { @Test public void existingViewResolver() throws Exception { MockHttpServletResponse response = runTest(ExistingViewResolverConfig.class); - assertEquals("Hello World!", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Hello World!"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolverRegistryTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolverRegistryTests.java index 80c1c13eede..d8c97bf3ddc 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolverRegistryTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolverRegistryTests.java @@ -40,11 +40,7 @@ import org.springframework.web.servlet.view.tiles3.TilesConfigurer; import org.springframework.web.servlet.view.tiles3.TilesViewResolver; import org.springframework.web.servlet.view.xml.MarshallingView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with a {@link ViewResolverRegistry}. @@ -71,44 +67,44 @@ public class ViewResolverRegistryTests { @Test public void order() { - assertEquals(Ordered.LOWEST_PRECEDENCE, this.registry.getOrder()); + assertThat(this.registry.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); this.registry.enableContentNegotiation(); - assertEquals(Ordered.HIGHEST_PRECEDENCE, this.registry.getOrder()); + assertThat(this.registry.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); } @Test public void hasRegistrations() { - assertFalse(this.registry.hasRegistrations()); + assertThat(this.registry.hasRegistrations()).isFalse(); this.registry.freeMarker(); - assertTrue(this.registry.hasRegistrations()); + assertThat(this.registry.hasRegistrations()).isTrue(); } @Test public void hasRegistrationsWhenContentNegotiationEnabled() { - assertFalse(this.registry.hasRegistrations()); + assertThat(this.registry.hasRegistrations()).isFalse(); this.registry.enableContentNegotiation(); - assertTrue(this.registry.hasRegistrations()); + assertThat(this.registry.hasRegistrations()).isTrue(); } @Test public void noResolvers() { - assertNotNull(this.registry.getViewResolvers()); - assertEquals(0, this.registry.getViewResolvers().size()); - assertFalse(this.registry.hasRegistrations()); + assertThat(this.registry.getViewResolvers()).isNotNull(); + assertThat(this.registry.getViewResolvers().size()).isEqualTo(0); + assertThat(this.registry.hasRegistrations()).isFalse(); } @Test public void customViewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver("/", ".jsp"); this.registry.viewResolver(viewResolver); - assertSame(viewResolver, this.registry.getViewResolvers().get(0)); + assertThat(this.registry.getViewResolvers().get(0)).isSameAs(viewResolver); } @Test public void beanName() { this.registry.beanName(); - assertEquals(1, this.registry.getViewResolvers().size()); - assertEquals(BeanNameViewResolver.class, registry.getViewResolvers().get(0).getClass()); + assertThat(this.registry.getViewResolvers().size()).isEqualTo(1); + assertThat(registry.getViewResolvers().get(0).getClass()).isEqualTo(BeanNameViewResolver.class); } @Test @@ -129,10 +125,10 @@ public class ViewResolverRegistryTests { public void jspMultipleResolvers() { this.registry.jsp().viewNames("view1", "view2"); this.registry.jsp().viewNames("view3", "view4"); - assertNotNull(this.registry.getViewResolvers()); - assertEquals(2, this.registry.getViewResolvers().size()); - assertEquals(InternalResourceViewResolver.class, this.registry.getViewResolvers().get(0).getClass()); - assertEquals(InternalResourceViewResolver.class, this.registry.getViewResolvers().get(1).getClass()); + assertThat(this.registry.getViewResolvers()).isNotNull(); + assertThat(this.registry.getViewResolvers().size()).isEqualTo(2); + assertThat(this.registry.getViewResolvers().get(0).getClass()).isEqualTo(InternalResourceViewResolver.class); + assertThat(this.registry.getViewResolvers().get(1).getClass()).isEqualTo(InternalResourceViewResolver.class); } @Test @@ -188,8 +184,8 @@ public class ViewResolverRegistryTests { MappingJackson2JsonView view = new MappingJackson2JsonView(); this.registry.enableContentNegotiation(view); ContentNegotiatingViewResolver resolver = checkAndGetResolver(ContentNegotiatingViewResolver.class); - assertEquals(Arrays.asList(view), resolver.getDefaultViews()); - assertEquals(Ordered.HIGHEST_PRECEDENCE, this.registry.getOrder()); + assertThat(resolver.getDefaultViews()).isEqualTo(Arrays.asList(view)); + assertThat(this.registry.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); } @Test @@ -198,22 +194,22 @@ public class ViewResolverRegistryTests { this.registry.enableContentNegotiation(view1); ContentNegotiatingViewResolver resolver1 = checkAndGetResolver(ContentNegotiatingViewResolver.class); - assertEquals(Arrays.asList(view1), resolver1.getDefaultViews()); + assertThat(resolver1.getDefaultViews()).isEqualTo(Arrays.asList(view1)); MarshallingView view2 = new MarshallingView(); this.registry.enableContentNegotiation(view2); ContentNegotiatingViewResolver resolver2 = checkAndGetResolver(ContentNegotiatingViewResolver.class); - assertEquals(Arrays.asList(view1, view2), resolver2.getDefaultViews()); - assertSame(resolver1, resolver2); + assertThat(resolver2.getDefaultViews()).isEqualTo(Arrays.asList(view1, view2)); + assertThat(resolver2).isSameAs(resolver1); } @SuppressWarnings("unchecked") private T checkAndGetResolver(Class resolverType) { - assertNotNull(this.registry.getViewResolvers()); - assertEquals(1, this.registry.getViewResolvers().size()); - assertEquals(resolverType, this.registry.getViewResolvers().get(0).getClass()); + assertThat(this.registry.getViewResolvers()).isNotNull(); + assertThat(this.registry.getViewResolvers().size()).isEqualTo(1); + assertThat(this.registry.getViewResolvers().get(0).getClass()).isEqualTo(resolverType); return (T) registry.getViewResolvers().get(0); } @@ -222,7 +218,7 @@ public class ViewResolverRegistryTests { for (int i = 0; i < nameValuePairs.length ; i++, i++) { Object expected = nameValuePairs[i + 1]; Object actual = accessor.getPropertyValue((String) nameValuePairs[i]); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java index 567ace234ba..d4f9185c68d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java @@ -88,10 +88,7 @@ import org.springframework.web.util.UrlPathHelper; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; import static com.fasterxml.jackson.databind.MapperFeature.DEFAULT_VIEW_INCLUSION; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.springframework.http.MediaType.APPLICATION_ATOM_XML; import static org.springframework.http.MediaType.APPLICATION_JSON; @@ -135,70 +132,70 @@ public class WebMvcConfigurationSupportExtensionTests { this.config.mvcConversionService(), this.config.mvcResourceUrlProvider()); rmHandlerMapping.setApplicationContext(this.context); rmHandlerMapping.afterPropertiesSet(); - assertEquals(TestPathHelper.class, rmHandlerMapping.getUrlPathHelper().getClass()); - assertEquals(TestPathMatcher.class, rmHandlerMapping.getPathMatcher().getClass()); + assertThat(rmHandlerMapping.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class); + assertThat(rmHandlerMapping.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class); HandlerExecutionChain chain = rmHandlerMapping.getHandler(new MockHttpServletRequest("GET", "/")); - assertNotNull(chain); - assertNotNull(chain.getInterceptors()); - assertEquals(4, chain.getInterceptors().length); - assertEquals("CorsInterceptor", chain.getInterceptors()[0].getClass().getSimpleName()); - assertEquals(LocaleChangeInterceptor.class, chain.getInterceptors()[1].getClass()); - assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[2].getClass()); - assertEquals(ResourceUrlProviderExposingInterceptor.class, chain.getInterceptors()[3].getClass()); + assertThat(chain).isNotNull(); + assertThat(chain.getInterceptors()).isNotNull(); + assertThat(chain.getInterceptors().length).isEqualTo(4); + assertThat(chain.getInterceptors()[0].getClass().getSimpleName()).isEqualTo("CorsInterceptor"); + assertThat(chain.getInterceptors()[1].getClass()).isEqualTo(LocaleChangeInterceptor.class); + assertThat(chain.getInterceptors()[2].getClass()).isEqualTo(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptors()[3].getClass()).isEqualTo(ResourceUrlProviderExposingInterceptor.class); Map map = rmHandlerMapping.getHandlerMethods(); - assertEquals(2, map.size()); + assertThat(map.size()).isEqualTo(2); RequestMappingInfo info = map.entrySet().stream() .filter(entry -> entry.getValue().getBeanType().equals(UserController.class)) .findFirst() .orElseThrow(() -> new AssertionError("UserController bean not found")) .getKey(); - assertEquals(Collections.singleton("/api/user/{id}"), info.getPatternsCondition().getPatterns()); + assertThat(info.getPatternsCondition().getPatterns()).isEqualTo(Collections.singleton("/api/user/{id}")); AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) this.config.viewControllerHandlerMapping( this.config.mvcPathMatcher(), this.config.mvcUrlPathHelper(), this.config.mvcConversionService(), this.config.mvcResourceUrlProvider()); handlerMapping.setApplicationContext(this.context); - assertNotNull(handlerMapping); - assertEquals(1, handlerMapping.getOrder()); - assertEquals(TestPathHelper.class, handlerMapping.getUrlPathHelper().getClass()); - assertEquals(TestPathMatcher.class, handlerMapping.getPathMatcher().getClass()); + assertThat(handlerMapping).isNotNull(); + assertThat(handlerMapping.getOrder()).isEqualTo(1); + assertThat(handlerMapping.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class); + assertThat(handlerMapping.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class); chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/path")); - assertNotNull(chain); - assertNotNull(chain.getHandler()); + assertThat(chain).isNotNull(); + assertThat(chain.getHandler()).isNotNull(); chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/bad")); - assertNotNull(chain); - assertNotNull(chain.getHandler()); + assertThat(chain).isNotNull(); + assertThat(chain.getHandler()).isNotNull(); chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/old")); - assertNotNull(chain); - assertNotNull(chain.getHandler()); + assertThat(chain).isNotNull(); + assertThat(chain.getHandler()).isNotNull(); handlerMapping = (AbstractHandlerMapping) this.config.resourceHandlerMapping( this.config.mvcUrlPathHelper(), this.config.mvcPathMatcher(), this.config.mvcContentNegotiationManager(), this.config.mvcConversionService(), this.config.mvcResourceUrlProvider()); handlerMapping.setApplicationContext(this.context); - assertNotNull(handlerMapping); - assertEquals(Integer.MAX_VALUE - 1, handlerMapping.getOrder()); - assertEquals(TestPathHelper.class, handlerMapping.getUrlPathHelper().getClass()); - assertEquals(TestPathMatcher.class, handlerMapping.getPathMatcher().getClass()); + assertThat(handlerMapping).isNotNull(); + assertThat(handlerMapping.getOrder()).isEqualTo((Integer.MAX_VALUE - 1)); + assertThat(handlerMapping.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class); + assertThat(handlerMapping.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class); chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/resources/foo.gif")); - assertNotNull(chain); - assertNotNull(chain.getHandler()); - assertEquals(Arrays.toString(chain.getInterceptors()), 5, chain.getInterceptors().length); - assertEquals("CorsInterceptor", chain.getInterceptors()[0].getClass().getSimpleName()); + assertThat(chain).isNotNull(); + assertThat(chain.getHandler()).isNotNull(); + assertThat(chain.getInterceptors().length).as(Arrays.toString(chain.getInterceptors())).isEqualTo(5); + assertThat(chain.getInterceptors()[0].getClass().getSimpleName()).isEqualTo("CorsInterceptor"); // PathExposingHandlerInterceptor at chain.getInterceptors()[1] - assertEquals(LocaleChangeInterceptor.class, chain.getInterceptors()[2].getClass()); - assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[3].getClass()); - assertEquals(ResourceUrlProviderExposingInterceptor.class, chain.getInterceptors()[4].getClass()); + assertThat(chain.getInterceptors()[2].getClass()).isEqualTo(LocaleChangeInterceptor.class); + assertThat(chain.getInterceptors()[3].getClass()).isEqualTo(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptors()[4].getClass()).isEqualTo(ResourceUrlProviderExposingInterceptor.class); handlerMapping = (AbstractHandlerMapping) this.config.defaultServletHandlerMapping(); handlerMapping.setApplicationContext(this.context); - assertNotNull(handlerMapping); - assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder()); + assertThat(handlerMapping).isNotNull(); + assertThat(handlerMapping.getOrder()).isEqualTo(Integer.MAX_VALUE); chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/anyPath")); - assertNotNull(chain); - assertNotNull(chain.getHandler()); + assertThat(chain).isNotNull(); + assertThat(chain.getHandler()).isNotNull(); } @SuppressWarnings("unchecked") @@ -210,42 +207,42 @@ public class WebMvcConfigurationSupportExtensionTests { // ConversionService String actual = this.config.mvcConversionService().convert(new TestBean(), String.class); - assertEquals("converted", actual); + assertThat(actual).isEqualTo("converted"); // Message converters List> converters = adapter.getMessageConverters(); - assertEquals(2, converters.size()); - assertEquals(StringHttpMessageConverter.class, converters.get(0).getClass()); - assertEquals(MappingJackson2HttpMessageConverter.class, converters.get(1).getClass()); + assertThat(converters.size()).isEqualTo(2); + assertThat(converters.get(0).getClass()).isEqualTo(StringHttpMessageConverter.class); + assertThat(converters.get(1).getClass()).isEqualTo(MappingJackson2HttpMessageConverter.class); ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter) converters.get(1)).getObjectMapper(); - assertFalse(objectMapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION)); - assertFalse(objectMapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION)); - assertFalse(objectMapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES)); + assertThat(objectMapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(objectMapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(objectMapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter); // Custom argument resolvers and return value handlers List argResolvers = (List) fieldAccessor.getPropertyValue("customArgumentResolvers"); - assertEquals(1, argResolvers.size()); + assertThat(argResolvers.size()).isEqualTo(1); List handlers = (List) fieldAccessor.getPropertyValue("customReturnValueHandlers"); - assertEquals(1, handlers.size()); + assertThat(handlers.size()).isEqualTo(1); // Async support options - assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass()); - assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout")); + assertThat(fieldAccessor.getPropertyValue("taskExecutor").getClass()).isEqualTo(ConcurrentTaskExecutor.class); + assertThat(fieldAccessor.getPropertyValue("asyncRequestTimeout")).isEqualTo(2500L); CallableProcessingInterceptor[] callableInterceptors = (CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors"); - assertEquals(1, callableInterceptors.length); + assertThat(callableInterceptors.length).isEqualTo(1); DeferredResultProcessingInterceptor[] deferredResultInterceptors = (DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors"); - assertEquals(1, deferredResultInterceptors.length); + assertThat(deferredResultInterceptors.length).isEqualTo(1); - assertEquals(false, fieldAccessor.getPropertyValue("ignoreDefaultModelOnRedirect")); + assertThat(fieldAccessor.getPropertyValue("ignoreDefaultModelOnRedirect")).isEqualTo(false); } @Test @@ -257,14 +254,14 @@ public class WebMvcConfigurationSupportExtensionTests { ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); - assertNotNull(initializer); + assertThat(initializer).isNotNull(); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(null, ""); initializer.getValidator().validate(null, bindingResult); - assertEquals("invalid", bindingResult.getAllErrors().get(0).getCode()); + assertThat(bindingResult.getAllErrors().get(0).getCode()).isEqualTo("invalid"); String[] codes = initializer.getMessageCodesResolver().resolveMessageCodes("invalid", null); - assertEquals("custom.invalid", codes[0]); + assertThat(codes[0]).isEqualTo("custom.invalid"); } @Test @@ -276,21 +273,20 @@ public class WebMvcConfigurationSupportExtensionTests { this.config.mvcContentNegotiationManager(), this.config.mvcConversionService(), this.config.mvcResourceUrlProvider()); ContentNegotiationManager manager = mapping.getContentNegotiationManager(); - assertEquals(Collections.singletonList(APPLICATION_JSON), manager.resolveMediaTypes(webRequest)); + assertThat(manager.resolveMediaTypes(webRequest)).isEqualTo(Collections.singletonList(APPLICATION_JSON)); request.setRequestURI("/foo.xml"); - assertEquals(Collections.singletonList(APPLICATION_XML), manager.resolveMediaTypes(webRequest)); + assertThat(manager.resolveMediaTypes(webRequest)).isEqualTo(Collections.singletonList(APPLICATION_XML)); request.setRequestURI("/foo.rss"); - assertEquals(Collections.singletonList(MediaType.valueOf("application/rss+xml")), - manager.resolveMediaTypes(webRequest)); + assertThat(manager.resolveMediaTypes(webRequest)).isEqualTo(Collections.singletonList(MediaType.valueOf("application/rss+xml"))); request.setRequestURI("/foo.atom"); - assertEquals(Collections.singletonList(APPLICATION_ATOM_XML), manager.resolveMediaTypes(webRequest)); + assertThat(manager.resolveMediaTypes(webRequest)).isEqualTo(Collections.singletonList(APPLICATION_ATOM_XML)); request.setRequestURI("/foo"); request.setParameter("f", "json"); - assertEquals(Collections.singletonList(APPLICATION_JSON), manager.resolveMediaTypes(webRequest)); + assertThat(manager.resolveMediaTypes(webRequest)).isEqualTo(Collections.singletonList(APPLICATION_JSON)); request.setRequestURI("/resources/foo.gif"); SimpleUrlHandlerMapping handlerMapping = (SimpleUrlHandlerMapping) this.config.resourceHandlerMapping( @@ -299,10 +295,10 @@ public class WebMvcConfigurationSupportExtensionTests { this.config.mvcResourceUrlProvider()); handlerMapping.setApplicationContext(this.context); HandlerExecutionChain chain = handlerMapping.getHandler(request); - assertNotNull(chain); + assertThat(chain).isNotNull(); ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) chain.getHandler(); - assertNotNull(handler); - assertSame(manager, handler.getContentNegotiationManager()); + assertThat(handler).isNotNull(); + assertThat(handler.getContentNegotiationManager()).isSameAs(manager); } @Test @@ -310,9 +306,9 @@ public class WebMvcConfigurationSupportExtensionTests { List resolvers = ((HandlerExceptionResolverComposite) this.config.handlerExceptionResolver(null)).getExceptionResolvers(); - assertEquals(2, resolvers.size()); - assertEquals(ResponseStatusExceptionResolver.class, resolvers.get(0).getClass()); - assertEquals(SimpleMappingExceptionResolver.class, resolvers.get(1).getClass()); + assertThat(resolvers.size()).isEqualTo(2); + assertThat(resolvers.get(0).getClass()).isEqualTo(ResponseStatusExceptionResolver.class); + assertThat(resolvers.get(1).getClass()).isEqualTo(SimpleMappingExceptionResolver.class); } @SuppressWarnings("unchecked") @@ -320,34 +316,34 @@ public class WebMvcConfigurationSupportExtensionTests { public void viewResolvers() throws Exception { ViewResolverComposite viewResolver = (ViewResolverComposite) this.config.mvcViewResolver( this.config.mvcContentNegotiationManager()); - assertEquals(Ordered.HIGHEST_PRECEDENCE, viewResolver.getOrder()); + assertThat(viewResolver.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); List viewResolvers = viewResolver.getViewResolvers(); DirectFieldAccessor accessor = new DirectFieldAccessor(viewResolvers.get(0)); - assertEquals(1, viewResolvers.size()); - assertEquals(ContentNegotiatingViewResolver.class, viewResolvers.get(0).getClass()); - assertFalse((Boolean) accessor.getPropertyValue("useNotAcceptableStatusCode")); - assertNotNull(accessor.getPropertyValue("contentNegotiationManager")); + assertThat(viewResolvers.size()).isEqualTo(1); + assertThat(viewResolvers.get(0).getClass()).isEqualTo(ContentNegotiatingViewResolver.class); + assertThat((boolean) (Boolean) accessor.getPropertyValue("useNotAcceptableStatusCode")).isFalse(); + assertThat(accessor.getPropertyValue("contentNegotiationManager")).isNotNull(); List defaultViews = (List) accessor.getPropertyValue("defaultViews"); - assertNotNull(defaultViews); - assertEquals(1, defaultViews.size()); - assertEquals(MappingJackson2JsonView.class, defaultViews.get(0).getClass()); + assertThat(defaultViews).isNotNull(); + assertThat(defaultViews.size()).isEqualTo(1); + assertThat(defaultViews.get(0).getClass()).isEqualTo(MappingJackson2JsonView.class); viewResolvers = (List) accessor.getPropertyValue("viewResolvers"); - assertNotNull(viewResolvers); - assertEquals(1, viewResolvers.size()); - assertEquals(InternalResourceViewResolver.class, viewResolvers.get(0).getClass()); + assertThat(viewResolvers).isNotNull(); + assertThat(viewResolvers.size()).isEqualTo(1); + assertThat(viewResolvers.get(0).getClass()).isEqualTo(InternalResourceViewResolver.class); accessor = new DirectFieldAccessor(viewResolvers.get(0)); - assertEquals("/", accessor.getPropertyValue("prefix")); - assertEquals(".jsp", accessor.getPropertyValue("suffix")); + assertThat(accessor.getPropertyValue("prefix")).isEqualTo("/"); + assertThat(accessor.getPropertyValue("suffix")).isEqualTo(".jsp"); } @Test public void crossOrigin() { Map configs = this.config.getCorsConfigurations(); - assertEquals(1, configs.size()); - assertEquals("*", configs.get("/resources/**").getAllowedOrigins().get(0)); + assertThat(configs.size()).isEqualTo(1); + assertThat(configs.get("/resources/**").getAllowedOrigins().get(0)).isEqualTo("*"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportTests.java index 17ce2206775..aa1cf5334b3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportTests.java @@ -88,11 +88,7 @@ import org.springframework.web.util.UrlPathHelper; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; import static com.fasterxml.jackson.databind.MapperFeature.DEFAULT_VIEW_INCLUSION; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link WebMvcConfigurationSupport} (imported via @@ -109,18 +105,18 @@ public class WebMvcConfigurationSupportTests { public void requestMappingHandlerMapping() throws Exception { ApplicationContext context = initContext(WebConfig.class, ScopedController.class, ScopedProxyController.class); RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class); - assertEquals(0, handlerMapping.getOrder()); + assertThat(handlerMapping.getOrder()).isEqualTo(0); HandlerExecutionChain chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/")); - assertNotNull(chain); - assertNotNull(chain.getInterceptors()); - assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[0].getClass()); + assertThat(chain).isNotNull(); + assertThat(chain.getInterceptors()).isNotNull(); + assertThat(chain.getInterceptors()[0].getClass()).isEqualTo(ConversionServiceExposingInterceptor.class); chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scoped")); - assertNotNull("HandlerExecutionChain for '/scoped' mapping should not be null.", chain); + assertThat(chain).as("HandlerExecutionChain for '/scoped' mapping should not be null.").isNotNull(); chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scopedProxy")); - assertNotNull("HandlerExecutionChain for '/scopedProxy' mapping should not be null.", chain); + assertThat(chain).as("HandlerExecutionChain for '/scopedProxy' mapping should not be null.").isNotNull(); } @Test @@ -128,34 +124,34 @@ public class WebMvcConfigurationSupportTests { ApplicationContext context = initContext(WebConfig.class); Map handlerMappings = context.getBeansOfType(HandlerMapping.class); - assertFalse(handlerMappings.containsKey("viewControllerHandlerMapping")); - assertFalse(handlerMappings.containsKey("resourceHandlerMapping")); - assertFalse(handlerMappings.containsKey("defaultServletHandlerMapping")); + assertThat(handlerMappings.containsKey("viewControllerHandlerMapping")).isFalse(); + assertThat(handlerMappings.containsKey("resourceHandlerMapping")).isFalse(); + assertThat(handlerMappings.containsKey("defaultServletHandlerMapping")).isFalse(); Object nullBean = context.getBean("viewControllerHandlerMapping"); - assertTrue(nullBean.equals(null)); + assertThat(nullBean.equals(null)).isTrue(); nullBean = context.getBean("resourceHandlerMapping"); - assertTrue(nullBean.equals(null)); + assertThat(nullBean.equals(null)).isTrue(); nullBean = context.getBean("defaultServletHandlerMapping"); - assertTrue(nullBean.equals(null)); + assertThat(nullBean.equals(null)).isTrue(); } @Test public void beanNameHandlerMapping() throws Exception { ApplicationContext context = initContext(WebConfig.class); BeanNameUrlHandlerMapping handlerMapping = context.getBean(BeanNameUrlHandlerMapping.class); - assertEquals(2, handlerMapping.getOrder()); + assertThat(handlerMapping.getOrder()).isEqualTo(2); HttpServletRequest request = new MockHttpServletRequest("GET", "/testController"); HandlerExecutionChain chain = handlerMapping.getHandler(request); - assertNotNull(chain); - assertNotNull(chain.getInterceptors()); - assertEquals(3, chain.getInterceptors().length); - assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[1].getClass()); - assertEquals(ResourceUrlProviderExposingInterceptor.class, chain.getInterceptors()[2].getClass()); + assertThat(chain).isNotNull(); + assertThat(chain.getInterceptors()).isNotNull(); + assertThat(chain.getInterceptors().length).isEqualTo(3); + assertThat(chain.getInterceptors()[1].getClass()).isEqualTo(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptors()[2].getClass()).isEqualTo(ResourceUrlProviderExposingInterceptor.class); } @Test @@ -163,37 +159,39 @@ public class WebMvcConfigurationSupportTests { ApplicationContext context = initContext(WebConfig.class); RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class); List> converters = adapter.getMessageConverters(); - assertEquals(12, converters.size()); + assertThat(converters.size()).isEqualTo(12); converters.stream() .filter(converter -> converter instanceof AbstractJackson2HttpMessageConverter) .forEach(converter -> { ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper(); - assertFalse(mapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION)); - assertFalse(mapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION)); - assertFalse(mapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES)); + assertThat(mapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(mapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION)).isFalse(); + assertThat(mapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); if (converter instanceof MappingJackson2XmlHttpMessageConverter) { - assertEquals(XmlMapper.class, mapper.getClass()); + assertThat(mapper.getClass()).isEqualTo(XmlMapper.class); } }); ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); - assertNotNull(initializer); + assertThat(initializer).isNotNull(); ConversionService conversionService = initializer.getConversionService(); - assertNotNull(conversionService); - assertTrue(conversionService instanceof FormattingConversionService); + assertThat(conversionService).isNotNull(); + boolean condition1 = conversionService instanceof FormattingConversionService; + assertThat(condition1).isTrue(); Validator validator = initializer.getValidator(); - assertNotNull(validator); - assertTrue(validator instanceof LocalValidatorFactoryBean); + assertThat(validator).isNotNull(); + boolean condition = validator instanceof LocalValidatorFactoryBean; + assertThat(condition).isTrue(); DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter); @SuppressWarnings("unchecked") List bodyAdvice = (List) fieldAccessor.getPropertyValue("requestResponseBodyAdvice"); - assertEquals(2, bodyAdvice.size()); - assertEquals(JsonViewRequestBodyAdvice.class, bodyAdvice.get(0).getClass()); - assertEquals(JsonViewResponseBodyAdvice.class, bodyAdvice.get(1).getClass()); + assertThat(bodyAdvice.size()).isEqualTo(2); + assertThat(bodyAdvice.get(0).getClass()).isEqualTo(JsonViewRequestBodyAdvice.class); + assertThat(bodyAdvice.get(1).getClass()).isEqualTo(JsonViewResponseBodyAdvice.class); } @Test @@ -203,7 +201,7 @@ public class WebMvcConfigurationSupportTests { MvcUriComponentsBuilder.MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME, CompositeUriComponentsContributor.class); - assertNotNull(uriComponentsContributor); + assertThat(uriComponentsContributor).isNotNull(); } @Test @@ -213,20 +211,20 @@ public class WebMvcConfigurationSupportTests { HandlerExceptionResolverComposite compositeResolver = context.getBean("handlerExceptionResolver", HandlerExceptionResolverComposite.class); - assertEquals(0, compositeResolver.getOrder()); + assertThat(compositeResolver.getOrder()).isEqualTo(0); List expectedResolvers = compositeResolver.getExceptionResolvers(); - assertEquals(ExceptionHandlerExceptionResolver.class, expectedResolvers.get(0).getClass()); - assertEquals(ResponseStatusExceptionResolver.class, expectedResolvers.get(1).getClass()); - assertEquals(DefaultHandlerExceptionResolver.class, expectedResolvers.get(2).getClass()); + assertThat(expectedResolvers.get(0).getClass()).isEqualTo(ExceptionHandlerExceptionResolver.class); + assertThat(expectedResolvers.get(1).getClass()).isEqualTo(ResponseStatusExceptionResolver.class); + assertThat(expectedResolvers.get(2).getClass()).isEqualTo(DefaultHandlerExceptionResolver.class); ExceptionHandlerExceptionResolver eher = (ExceptionHandlerExceptionResolver) expectedResolvers.get(0); - assertNotNull(eher.getApplicationContext()); + assertThat(eher.getApplicationContext()).isNotNull(); DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(eher); List interceptors = (List) fieldAccessor.getPropertyValue("responseBodyAdvice"); - assertEquals(1, interceptors.size()); - assertEquals(JsonViewResponseBodyAdvice.class, interceptors.get(0).getClass()); + assertThat(interceptors.size()).isEqualTo(1); + assertThat(interceptors.get(0).getClass()).isEqualTo(JsonViewResponseBodyAdvice.class); LocaleContextHolder.setLocale(Locale.ENGLISH); try { @@ -234,7 +232,7 @@ public class WebMvcConfigurationSupportTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); rser.resolveException(request, response, context.getBean(TestController.class), new UserAlreadyExistsException()); - assertEquals("User already exists!", response.getErrorMessage()); + assertThat(response.getErrorMessage()).isEqualTo("User already exists!"); } finally { LocaleContextHolder.resetLocaleContext(); @@ -247,23 +245,23 @@ public class WebMvcConfigurationSupportTests { RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class); HandlerExceptionResolverComposite composite = context.getBean(HandlerExceptionResolverComposite.class); - assertNotNull(adapter); - assertEquals(1, adapter.getCustomArgumentResolvers().size()); - assertEquals(TestArgumentResolver.class, adapter.getCustomArgumentResolvers().get(0).getClass()); - assertEquals(1, adapter.getCustomReturnValueHandlers().size()); - assertEquals(TestReturnValueHandler.class, adapter.getCustomReturnValueHandlers().get(0).getClass()); + assertThat(adapter).isNotNull(); + assertThat(adapter.getCustomArgumentResolvers().size()).isEqualTo(1); + assertThat(adapter.getCustomArgumentResolvers().get(0).getClass()).isEqualTo(TestArgumentResolver.class); + assertThat(adapter.getCustomReturnValueHandlers().size()).isEqualTo(1); + assertThat(adapter.getCustomReturnValueHandlers().get(0).getClass()).isEqualTo(TestReturnValueHandler.class); - assertNotNull(composite); - assertEquals(3, composite.getExceptionResolvers().size()); - assertEquals(ExceptionHandlerExceptionResolver.class, composite.getExceptionResolvers().get(0).getClass()); + assertThat(composite).isNotNull(); + assertThat(composite.getExceptionResolvers().size()).isEqualTo(3); + assertThat(composite.getExceptionResolvers().get(0).getClass()).isEqualTo(ExceptionHandlerExceptionResolver.class); ExceptionHandlerExceptionResolver resolver = (ExceptionHandlerExceptionResolver) composite.getExceptionResolvers().get(0); - assertEquals(1, resolver.getCustomArgumentResolvers().size()); - assertEquals(TestArgumentResolver.class, resolver.getCustomArgumentResolvers().get(0).getClass()); - assertEquals(1, resolver.getCustomReturnValueHandlers().size()); - assertEquals(TestReturnValueHandler.class, resolver.getCustomReturnValueHandlers().get(0).getClass()); + assertThat(resolver.getCustomArgumentResolvers().size()).isEqualTo(1); + assertThat(resolver.getCustomArgumentResolvers().get(0).getClass()).isEqualTo(TestArgumentResolver.class); + assertThat(resolver.getCustomReturnValueHandlers().size()).isEqualTo(1); + assertThat(resolver.getCustomReturnValueHandlers().get(0).getClass()).isEqualTo(TestReturnValueHandler.class); } @@ -272,10 +270,10 @@ public class WebMvcConfigurationSupportTests { ApplicationContext context = initContext(WebConfig.class); ViewResolverComposite resolver = context.getBean("mvcViewResolver", ViewResolverComposite.class); - assertNotNull(resolver); - assertEquals(1, resolver.getViewResolvers().size()); - assertEquals(InternalResourceViewResolver.class, resolver.getViewResolvers().get(0).getClass()); - assertEquals(Ordered.LOWEST_PRECEDENCE, resolver.getOrder()); + assertThat(resolver).isNotNull(); + assertThat(resolver.getViewResolvers().size()).isEqualTo(1); + assertThat(resolver.getViewResolvers().get(0).getClass()).isEqualTo(InternalResourceViewResolver.class); + assertThat(resolver.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); } @Test @@ -283,10 +281,10 @@ public class WebMvcConfigurationSupportTests { ApplicationContext context = initContext(WebConfig.class, ViewResolverConfig.class); ViewResolverComposite resolver = context.getBean("mvcViewResolver", ViewResolverComposite.class); - assertNotNull(resolver); - assertEquals(0, resolver.getViewResolvers().size()); - assertEquals(Ordered.LOWEST_PRECEDENCE, resolver.getOrder()); - assertNull(resolver.resolveViewName("anyViewName", Locale.ENGLISH)); + assertThat(resolver).isNotNull(); + assertThat(resolver.getViewResolvers().size()).isEqualTo(0); + assertThat(resolver.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); + assertThat(resolver.resolveViewName("anyViewName", Locale.ENGLISH)).isNull(); } @Test @@ -294,10 +292,10 @@ public class WebMvcConfigurationSupportTests { ApplicationContext context = initContext(CustomViewResolverOrderConfig.class); ViewResolverComposite resolver = context.getBean("mvcViewResolver", ViewResolverComposite.class); - assertNotNull(resolver); - assertEquals(1, resolver.getViewResolvers().size()); - assertEquals(InternalResourceViewResolver.class, resolver.getViewResolvers().get(0).getClass()); - assertEquals(123, resolver.getOrder()); + assertThat(resolver).isNotNull(); + assertThat(resolver.getViewResolvers().size()).isEqualTo(1); + assertThat(resolver.getViewResolvers().get(0).getClass()).isEqualTo(InternalResourceViewResolver.class); + assertThat(resolver.getOrder()).isEqualTo(123); } @Test @@ -306,9 +304,9 @@ public class WebMvcConfigurationSupportTests { UrlPathHelper urlPathHelper = context.getBean(UrlPathHelper.class); PathMatcher pathMatcher = context.getBean(PathMatcher.class); - assertNotNull(urlPathHelper); - assertNotNull(pathMatcher); - assertEquals(AntPathMatcher.class, pathMatcher.getClass()); + assertThat(urlPathHelper).isNotNull(); + assertThat(pathMatcher).isNotNull(); + assertThat(pathMatcher.getClass()).isEqualTo(AntPathMatcher.class); } private ApplicationContext initContext(Class... configClasses) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilderTests.java index 0ff65dc4393..aa677fb1b34 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilderTests.java @@ -42,10 +42,7 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.servlet.ModelAndView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -64,7 +61,7 @@ public class DefaultEntityResponseBuilderTests { public void fromObject() { String body = "foo"; EntityResponse response = EntityResponse.fromObject(body).build(); - assertSame(body, response.entity()); + assertThat(response.entity()).isSameAs(body); } @Test @@ -74,7 +71,7 @@ public class DefaultEntityResponseBuilderTests { new ParameterizedTypeReference() {}) .build(); - assertSame(body, response.entity()); + assertThat(response.entity()).isSameAs(body); } @Test @@ -83,7 +80,7 @@ public class DefaultEntityResponseBuilderTests { EntityResponse result = EntityResponse.fromObject(body).status(HttpStatus.CREATED).build(); - assertEquals(HttpStatus.CREATED, result.statusCode()); + assertThat(result.statusCode()).isEqualTo(HttpStatus.CREATED); } @Test @@ -92,14 +89,14 @@ public class DefaultEntityResponseBuilderTests { EntityResponse result = EntityResponse.fromObject(body).allow(HttpMethod.GET).build(); Set expected = EnumSet.of(HttpMethod.GET); - assertEquals(expected, result.headers().getAllow()); + assertThat(result.headers().getAllow()).isEqualTo(expected); } @Test public void contentLength() { String body = "foo"; EntityResponse result = EntityResponse.fromObject(body).contentLength(42).build(); - assertEquals(42, result.headers().getContentLength()); + assertThat(result.headers().getContentLength()).isEqualTo(42); } @Test @@ -109,7 +106,7 @@ public class DefaultEntityResponseBuilderTests { result = EntityResponse.fromObject(body).contentType(MediaType.APPLICATION_JSON).build(); - assertEquals(MediaType.APPLICATION_JSON, result.headers().getContentType()); + assertThat(result.headers().getContentType()).isEqualTo(MediaType.APPLICATION_JSON); } @Test @@ -117,7 +114,7 @@ public class DefaultEntityResponseBuilderTests { String body = "foo"; EntityResponse result = EntityResponse.fromObject(body).eTag("foo").build(); - assertEquals("\"foo\"", result.headers().getETag()); + assertThat(result.headers().getETag()).isEqualTo("\"foo\""); } @Test @@ -126,7 +123,7 @@ public class DefaultEntityResponseBuilderTests { String body = "foo"; EntityResponse result = EntityResponse.fromObject(body).lastModified(now).build(); long expected = now.toInstant().toEpochMilli() / 1000; - assertEquals(expected, result.headers().getLastModified() / 1000); + assertThat(result.headers().getLastModified() / 1000).isEqualTo(expected); } @Test @@ -134,7 +131,7 @@ public class DefaultEntityResponseBuilderTests { String body = "foo"; EntityResponse result = EntityResponse.fromObject(body).cacheControl(CacheControl.noCache()).build(); - assertEquals("no-cache", result.headers().getCacheControl()); + assertThat(result.headers().getCacheControl()).isEqualTo("no-cache"); } @Test @@ -142,14 +139,14 @@ public class DefaultEntityResponseBuilderTests { String body = "foo"; EntityResponse result = EntityResponse.fromObject(body).varyBy("foo").build(); List expected = Collections.singletonList("foo"); - assertEquals(expected, result.headers().getVary()); + assertThat(result.headers().getVary()).isEqualTo(expected); } @Test public void header() { String body = "foo"; EntityResponse result = EntityResponse.fromObject(body).header("foo", "bar").build(); - assertEquals("bar", result.headers().getFirst("foo")); + assertThat(result.headers().getFirst("foo")).isEqualTo("bar"); } @Test @@ -160,7 +157,7 @@ public class DefaultEntityResponseBuilderTests { EntityResponse result = EntityResponse.fromObject(body) .headers(h -> h.addAll(headers)) .build(); - assertEquals(headers, result.headers()); + assertThat(result.headers()).isEqualTo(headers); } @Test @@ -169,7 +166,7 @@ public class DefaultEntityResponseBuilderTests { EntityResponse result = EntityResponse.fromObject("foo").cookie(cookie) .build(); - assertTrue(result.cookies().get("name").contains(cookie)); + assertThat(result.cookies().get("name").contains(cookie)).isTrue(); } @Test @@ -179,7 +176,7 @@ public class DefaultEntityResponseBuilderTests { EntityResponse result = EntityResponse.fromObject("foo").cookies(cookies -> cookies.addAll(newCookies)) .build(); - assertEquals(newCookies, result.cookies()); + assertThat(result.cookies()).isEqualTo(newCookies); } @Test @@ -195,9 +192,9 @@ public class DefaultEntityResponseBuilderTests { MockHttpServletResponse mockResponse = new MockHttpServletResponse(); ModelAndView mav = entityResponse.writeTo(mockRequest, mockResponse, EMPTY_CONTEXT); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals(HttpStatus.NOT_MODIFIED.value(), mockResponse.getStatus()); + assertThat(mockResponse.getStatus()).isEqualTo(HttpStatus.NOT_MODIFIED.value()); } @@ -216,9 +213,9 @@ public class DefaultEntityResponseBuilderTests { MockHttpServletResponse mockResponse = new MockHttpServletResponse(); ModelAndView mav = entityResponse.writeTo(mockRequest, mockResponse, EMPTY_CONTEXT); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals(HttpStatus.NOT_MODIFIED.value(), mockResponse.getStatus()); + assertThat(mockResponse.getStatus()).isEqualTo(HttpStatus.NOT_MODIFIED.value()); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultRenderingResponseTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultRenderingResponseTests.java index b96c3306018..b152bcad13e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultRenderingResponseTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultRenderingResponseTests.java @@ -35,9 +35,7 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.servlet.ModelAndView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -61,7 +59,7 @@ public class DefaultRenderingResponseTests { MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = result.writeTo(request, response, EMPTY_CONTEXT); - assertEquals(name, mav.getViewName()); + assertThat(mav.getViewName()).isEqualTo(name); } @Test @@ -72,8 +70,8 @@ public class DefaultRenderingResponseTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = result.writeTo(request, response, EMPTY_CONTEXT); - assertNotNull(mav); - assertEquals(status.value(), response.getStatus()); + assertThat(mav).isNotNull(); + assertThat(response.getStatus()).isEqualTo(status.value()); } @Test @@ -87,9 +85,9 @@ public class DefaultRenderingResponseTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = result.writeTo(request, response, EMPTY_CONTEXT); - assertNotNull(mav); + assertThat(mav).isNotNull(); - assertEquals("bar", response.getHeader("foo")); + assertThat(response.getHeader("foo")).isEqualTo("bar"); } @Test @@ -100,9 +98,9 @@ public class DefaultRenderingResponseTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = result.writeTo(request, response, EMPTY_CONTEXT); - assertNotNull(mav); + assertThat(mav).isNotNull(); - assertEquals("bar", mav.getModel().get("foo")); + assertThat(mav.getModel().get("foo")).isEqualTo("bar"); } @@ -113,8 +111,8 @@ public class DefaultRenderingResponseTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = result.writeTo(request, response, EMPTY_CONTEXT); - assertNotNull(mav); - assertEquals("bar", mav.getModel().get("string")); + assertThat(mav).isNotNull(); + assertThat(mav.getModel().get("string")).isEqualTo("bar"); } @Test @@ -125,8 +123,8 @@ public class DefaultRenderingResponseTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = result.writeTo(request, response, EMPTY_CONTEXT); - assertNotNull(mav); - assertEquals("bar", mav.getModel().get("foo")); + assertThat(mav).isNotNull(); + assertThat(mav.getModel().get("foo")).isEqualTo("bar"); } @Test @@ -136,8 +134,8 @@ public class DefaultRenderingResponseTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = result.writeTo(request, response, EMPTY_CONTEXT); - assertNotNull(mav); - assertEquals("bar", mav.getModel().get("string")); + assertThat(mav).isNotNull(); + assertThat(mav.getModel().get("string")).isEqualTo("bar"); } @Test @@ -149,10 +147,10 @@ public class DefaultRenderingResponseTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = result.writeTo(request, response, EMPTY_CONTEXT); - assertNotNull(mav); - assertEquals(1, response.getCookies().length); - assertEquals("name", response.getCookies()[0].getName()); - assertEquals("value", response.getCookies()[0].getValue()); + assertThat(mav).isNotNull(); + assertThat(response.getCookies().length).isEqualTo(1); + assertThat(response.getCookies()[0].getName()).isEqualTo("name"); + assertThat(response.getCookies()[0].getValue()).isEqualTo("value"); } @Test @@ -167,8 +165,8 @@ public class DefaultRenderingResponseTests { MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = result.writeTo(request, response, EMPTY_CONTEXT); - assertNull(mav); - assertEquals(HttpStatus.NOT_MODIFIED.value(), response.getStatus()); + assertThat(mav).isNull(); + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_MODIFIED.value()); } @@ -186,8 +184,8 @@ public class DefaultRenderingResponseTests { MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = result.writeTo(request, response, EMPTY_CONTEXT); - assertNull(mav); - assertEquals(HttpStatus.NOT_MODIFIED.value(), response.getStatus()); + assertThat(mav).isNull(); + assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_MODIFIED.value()); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestBuilderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestBuilderTests.java index 336e2a5906a..7fca21e4cdd 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestBuilderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestBuilderTests.java @@ -29,7 +29,7 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.mock.web.test.MockHttpServletRequest; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -57,19 +57,19 @@ public class DefaultServerRequestBuilderTests { .body("baz") .build(); - assertEquals(HttpMethod.HEAD, result.method()); - assertEquals(2, result.headers().asHttpHeaders().size()); - assertEquals("bar", result.headers().asHttpHeaders().getFirst("foo")); - assertEquals("qux", result.headers().asHttpHeaders().getFirst("baz")); - assertEquals(2, result.cookies().size()); - assertEquals("bar", result.cookies().getFirst("foo").getValue()); - assertEquals("qux", result.cookies().getFirst("baz").getValue()); - assertEquals(2, result.attributes().size()); - assertEquals("bar", result.attributes().get("foo")); - assertEquals("qux", result.attributes().get("baz")); + assertThat(result.method()).isEqualTo(HttpMethod.HEAD); + assertThat(result.headers().asHttpHeaders().size()).isEqualTo(2); + assertThat(result.headers().asHttpHeaders().getFirst("foo")).isEqualTo("bar"); + assertThat(result.headers().asHttpHeaders().getFirst("baz")).isEqualTo("qux"); + assertThat(result.cookies().size()).isEqualTo(2); + assertThat(result.cookies().getFirst("foo").getValue()).isEqualTo("bar"); + assertThat(result.cookies().getFirst("baz").getValue()).isEqualTo("qux"); + assertThat(result.attributes().size()).isEqualTo(2); + assertThat(result.attributes().get("foo")).isEqualTo("bar"); + assertThat(result.attributes().get("baz")).isEqualTo("qux"); String body = result.body(String.class); - assertEquals("baz", body); + assertThat(body).isEqualTo("baz"); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java index bd2fb48488e..46bd12fdf76 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java @@ -44,9 +44,9 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.HttpMediaTypeNotSupportedException; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; /** * @author Arjen Poutsma @@ -63,7 +63,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertEquals(HttpMethod.HEAD, request.method()); + assertThat(request.method()).isEqualTo(HttpMethod.HEAD); } @Test @@ -76,7 +76,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertEquals(URI.create("https://example.com/"), request.uri()); + assertThat(request.uri()).isEqualTo(URI.create("https://example.com/")); } @Test @@ -88,11 +88,11 @@ public class DefaultServerRequestTests { new DefaultServerRequest(servletRequest, this.messageConverters); URI result = request.uriBuilder().build(); - assertEquals("http", result.getScheme()); - assertEquals("localhost", result.getHost()); - assertEquals(-1, result.getPort()); - assertEquals("/path", result.getPath()); - assertEquals("a=1", result.getQuery()); + assertThat(result.getScheme()).isEqualTo("http"); + assertThat(result.getHost()).isEqualTo("localhost"); + assertThat(result.getPort()).isEqualTo(-1); + assertThat(result.getPath()).isEqualTo("/path"); + assertThat(result.getQuery()).isEqualTo("a=1"); } @Test @@ -103,7 +103,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertEquals(Optional.of("bar"), request.attribute("foo")); + assertThat(request.attribute("foo")).isEqualTo(Optional.of("bar")); } @Test @@ -114,7 +114,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertEquals(Optional.of("bar"), request.param("foo")); + assertThat(request.param("foo")).isEqualTo(Optional.of("bar")); } @Test @@ -125,7 +125,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertEquals(Optional.of(""), request.param("foo")); + assertThat(request.param("foo")).isEqualTo(Optional.of("")); } @Test @@ -136,7 +136,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertEquals(Optional.empty(), request.param("bar")); + assertThat(request.param("bar")).isEqualTo(Optional.empty()); } @Test @@ -149,7 +149,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertEquals("bar", request.pathVariable("foo")); + assertThat(request.pathVariable("foo")).isEqualTo("bar"); } @Test @@ -176,7 +176,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertEquals(pathVariables, request.pathVariables()); + assertThat(request.pathVariables()).isEqualTo(pathVariables); } @Test @@ -204,11 +204,11 @@ public class DefaultServerRequestTests { this.messageConverters); ServerRequest.Headers headers = request.headers(); - assertEquals(accept, headers.accept()); - assertEquals(acceptCharset, headers.acceptCharset()); - assertEquals(OptionalLong.of(contentLength), headers.contentLength()); - assertEquals(Optional.of(contentType), headers.contentType()); - assertEquals(httpHeaders, headers.asHttpHeaders()); + assertThat(headers.accept()).isEqualTo(accept); + assertThat(headers.acceptCharset()).isEqualTo(acceptCharset); + assertThat(headers.contentLength()).isEqualTo(OptionalLong.of(contentLength)); + assertThat(headers.contentType()).isEqualTo(Optional.of(contentType)); + assertThat(headers.asHttpHeaders()).isEqualTo(httpHeaders); } @Test @@ -224,7 +224,7 @@ public class DefaultServerRequestTests { MultiValueMap expected = new LinkedMultiValueMap<>(); expected.add("foo", cookie); - assertEquals(expected, request.cookies()); + assertThat(request.cookies()).isEqualTo(expected); } @@ -238,7 +238,7 @@ public class DefaultServerRequestTests { this.messageConverters); String result = request.body(String.class); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); } @Test @@ -251,9 +251,9 @@ public class DefaultServerRequestTests { Collections.singletonList(new MappingJackson2HttpMessageConverter())); List result = request.body(new ParameterizedTypeReference>() {}); - assertEquals(2, result.size()); - assertEquals("foo", result.get(0)); - assertEquals("bar", result.get(1)); + assertThat(result.size()).isEqualTo(2); + assertThat(result.get(0)).isEqualTo("foo"); + assertThat(result.get(1)).isEqualTo("bar"); } @Test @@ -278,7 +278,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertEquals(session, request.session()); + assertThat(request.session()).isEqualTo(session); } @@ -296,7 +296,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertEquals(principal, request.principal().get()); + assertThat(request.principal().get()).isEqualTo(principal); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerResponseBuilderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerResponseBuilderTests.java index eb61052ec0a..dd2614a1492 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerResponseBuilderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerResponseBuilderTests.java @@ -47,8 +47,7 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.servlet.ModelAndView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -67,7 +66,7 @@ public class DefaultServerResponseBuilderTests { @Test public void status() { ServerResponse response = ServerResponse.status(HttpStatus.CREATED).build(); - assertEquals(HttpStatus.CREATED, response.statusCode()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.CREATED); } @Test @@ -78,9 +77,9 @@ public class DefaultServerResponseBuilderTests { .cookie(cookie) .build(); ServerResponse result = ServerResponse.from(other).build(); - assertEquals(HttpStatus.OK, result.statusCode()); - assertEquals("bar", result.headers().getFirst("foo")); - assertEquals(cookie, result.cookies().getFirst("foo")); + assertThat(result.statusCode()).isEqualTo(HttpStatus.OK); + assertThat(result.headers().getFirst("foo")).isEqualTo("bar"); + assertThat(result.cookies().getFirst("foo")).isEqualTo(cookie); } @@ -88,93 +87,93 @@ public class DefaultServerResponseBuilderTests { public void ok() { ServerResponse response = ServerResponse.ok().build(); - assertEquals(HttpStatus.OK, response.statusCode()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); } @Test public void created() { URI location = URI.create("https://example.com"); ServerResponse response = ServerResponse.created(location).build(); - assertEquals(HttpStatus.CREATED, response.statusCode()); - assertEquals(location, response.headers().getLocation()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.CREATED); + assertThat(response.headers().getLocation()).isEqualTo(location); } @Test public void accepted() { ServerResponse response = ServerResponse.accepted().build(); - assertEquals(HttpStatus.ACCEPTED, response.statusCode()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.ACCEPTED); } @Test public void noContent() { ServerResponse response = ServerResponse.noContent().build(); - assertEquals(HttpStatus.NO_CONTENT, response.statusCode()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.NO_CONTENT); } @Test public void seeOther() { URI location = URI.create("https://example.com"); ServerResponse response = ServerResponse.seeOther(location).build(); - assertEquals(HttpStatus.SEE_OTHER, response.statusCode()); - assertEquals(location, response.headers().getLocation()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.SEE_OTHER); + assertThat(response.headers().getLocation()).isEqualTo(location); } @Test public void temporaryRedirect() { URI location = URI.create("https://example.com"); ServerResponse response = ServerResponse.temporaryRedirect(location).build(); - assertEquals(HttpStatus.TEMPORARY_REDIRECT, response.statusCode()); - assertEquals(location, response.headers().getLocation()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT); + assertThat(response.headers().getLocation()).isEqualTo(location); } @Test public void permanentRedirect() { URI location = URI.create("https://example.com"); ServerResponse response = ServerResponse.permanentRedirect(location).build(); - assertEquals(HttpStatus.PERMANENT_REDIRECT, response.statusCode()); - assertEquals(location, response.headers().getLocation()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.PERMANENT_REDIRECT); + assertThat(response.headers().getLocation()).isEqualTo(location); } @Test public void badRequest() { ServerResponse response = ServerResponse.badRequest().build(); - assertEquals(HttpStatus.BAD_REQUEST, response.statusCode()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test public void notFound() { ServerResponse response = ServerResponse.notFound().build(); - assertEquals(HttpStatus.NOT_FOUND, response.statusCode()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test public void unprocessableEntity() { ServerResponse response = ServerResponse.unprocessableEntity().build(); - assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, response.statusCode()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY); } @Test public void allow() { ServerResponse response = ServerResponse.ok().allow(HttpMethod.GET).build(); - assertEquals(EnumSet.of(HttpMethod.GET), response.headers().getAllow()); + assertThat(response.headers().getAllow()).isEqualTo(EnumSet.of(HttpMethod.GET)); } @Test public void contentLength() { ServerResponse response = ServerResponse.ok().contentLength(42).build(); - assertEquals(42L, response.headers().getContentLength()); + assertThat(response.headers().getContentLength()).isEqualTo(42L); } @Test public void contentType() { ServerResponse response = ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).build(); - assertEquals(MediaType.APPLICATION_JSON, response.headers().getContentType()); + assertThat(response.headers().getContentType()).isEqualTo(MediaType.APPLICATION_JSON); } @Test public void eTag() { ServerResponse response = ServerResponse.ok().eTag("foo").build(); - assertEquals("\"foo\"", response.headers().getETag()); + assertThat(response.headers().getETag()).isEqualTo("\"foo\""); } @Test @@ -182,20 +181,20 @@ public class DefaultServerResponseBuilderTests { ZonedDateTime now = ZonedDateTime.now(); ServerResponse response = ServerResponse.ok().lastModified(now).build(); long expected = now.toInstant().toEpochMilli() / 1000; - assertEquals(expected, response.headers().getLastModified() / 1000); + assertThat(response.headers().getLastModified() / 1000).isEqualTo(expected); } @Test public void cacheControlTag() { ServerResponse response = ServerResponse.ok().cacheControl(CacheControl.noCache()).build(); - assertEquals("no-cache", response.headers().getCacheControl()); + assertThat(response.headers().getCacheControl()).isEqualTo("no-cache"); } @Test public void varyBy() { ServerResponse response = ServerResponse.ok().varyBy("foo").build(); List expected = Collections.singletonList("foo"); - assertEquals(expected, response.headers().getVary()); + assertThat(response.headers().getVary()).isEqualTo(expected); } @@ -203,7 +202,7 @@ public class DefaultServerResponseBuilderTests { public void statusCode() { HttpStatus statusCode = HttpStatus.ACCEPTED; ServerResponse response = ServerResponse.status(statusCode).build(); - assertEquals(statusCode, response.statusCode()); + assertThat(response.statusCode()).isEqualTo(statusCode); } @Test @@ -213,7 +212,7 @@ public class DefaultServerResponseBuilderTests { ServerResponse response = ServerResponse.ok() .headers(headers -> headers.addAll(newHeaders)) .build(); - assertEquals(newHeaders, response.headers()); + assertThat(response.headers()).isEqualTo(newHeaders); } @Test @@ -223,7 +222,7 @@ public class DefaultServerResponseBuilderTests { ServerResponse response = ServerResponse.ok() .cookies(cookies -> cookies.addAll(newCookies)) .build(); - assertEquals(newCookies, response.cookies()); + assertThat(response.cookies()).isEqualTo(newCookies); } @Test @@ -238,11 +237,11 @@ public class DefaultServerResponseBuilderTests { MockHttpServletResponse mockResponse = new MockHttpServletResponse(); ModelAndView mav = response.writeTo(mockRequest, mockResponse, EMPTY_CONTEXT); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals(HttpStatus.CREATED.value(), mockResponse.getStatus()); - assertEquals("MyValue", mockResponse.getHeader("MyKey")); - assertEquals("value", mockResponse.getCookie("name").getValue()); + assertThat(mockResponse.getStatus()).isEqualTo(HttpStatus.CREATED.value()); + assertThat(mockResponse.getHeader("MyKey")).isEqualTo("MyValue"); + assertThat(mockResponse.getCookie("name").getValue()).isEqualTo("value"); } @Test @@ -257,9 +256,9 @@ public class DefaultServerResponseBuilderTests { MockHttpServletResponse mockResponse = new MockHttpServletResponse(); ModelAndView mav = response.writeTo(mockRequest, mockResponse, EMPTY_CONTEXT); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals(HttpStatus.NOT_MODIFIED.value(), mockResponse.getStatus()); + assertThat(mockResponse.getStatus()).isEqualTo(HttpStatus.NOT_MODIFIED.value()); } @Test @@ -276,9 +275,9 @@ public class DefaultServerResponseBuilderTests { MockHttpServletResponse mockResponse = new MockHttpServletResponse(); ModelAndView mav = response.writeTo(mockRequest, mockResponse, EMPTY_CONTEXT); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals(HttpStatus.NOT_MODIFIED.value(), mockResponse.getStatus()); + assertThat(mockResponse.getStatus()).isEqualTo(HttpStatus.NOT_MODIFIED.value()); } @Test @@ -291,9 +290,9 @@ public class DefaultServerResponseBuilderTests { ServerResponse.Context context = () -> Collections.singletonList(new StringHttpMessageConverter()); ModelAndView mav = response.writeTo(mockRequest, mockResponse, context); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals(body, mockResponse.getContentAsString()); + assertThat(mockResponse.getContentAsString()).isEqualTo(body); } @Test @@ -308,9 +307,9 @@ public class DefaultServerResponseBuilderTests { ServerResponse.Context context = () -> Collections.singletonList(new MappingJackson2HttpMessageConverter()); ModelAndView mav = response.writeTo(mockRequest, mockResponse, context); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals("[\"foo\",\"bar\"]", mockResponse.getContentAsString()); + assertThat(mockResponse.getContentAsString()).isEqualTo("[\"foo\",\"bar\"]"); } @Test @@ -326,10 +325,10 @@ public class DefaultServerResponseBuilderTests { ServerResponse.Context context = () -> Collections.singletonList(new StringHttpMessageConverter()); ModelAndView mav = response.writeTo(mockRequest, mockResponse, context); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals(body, mockResponse.getContentAsString()); + assertThat(mockResponse.getContentAsString()).isEqualTo(body); } @Test @@ -345,9 +344,9 @@ public class DefaultServerResponseBuilderTests { ServerResponse.Context context = () -> Collections.singletonList(new StringHttpMessageConverter()); ModelAndView mav = response.writeTo(mockRequest, mockResponse, context); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals(body, mockResponse.getContentAsString()); + assertThat(mockResponse.getContentAsString()).isEqualTo(body); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/PathResourceLookupFunctionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/PathResourceLookupFunctionTests.java index 93c628840c3..f3c7a169a15 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/PathResourceLookupFunctionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/PathResourceLookupFunctionTests.java @@ -27,9 +27,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.mock.web.test.MockHttpServletRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -49,10 +47,10 @@ public class PathResourceLookupFunctionTests { ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList()); Optional result = function.apply(request); - assertTrue(result.isPresent()); + assertThat(result.isPresent()).isTrue(); File expected = new ClassPathResource("response.txt", getClass()).getFile(); - assertEquals(expected, result.get().getFile()); + assertThat(result.get().getFile()).isEqualTo(expected); } @Test @@ -68,12 +66,12 @@ public class PathResourceLookupFunctionTests { ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList()); Optional result = function.apply(request); - assertTrue(result.isPresent()); + assertThat(result.isPresent()).isTrue(); File expected = new ClassPathResource("org/springframework/web/servlet/function/child/response.txt") .getFile(); - assertEquals(expected, result.get().getFile()); + assertThat(result.get().getFile()).isEqualTo(expected); } @Test @@ -89,7 +87,7 @@ public class PathResourceLookupFunctionTests { ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList()); Optional result = function.apply(request); - assertFalse(result.isPresent()); + assertThat(result.isPresent()).isFalse(); } @Test @@ -114,9 +112,9 @@ public class PathResourceLookupFunctionTests { ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList()); Optional result = customLookupFunction.apply(request); - assertTrue(result.isPresent()); + assertThat(result.isPresent()).isTrue(); - assertEquals(defaultResource.getFile(), result.get().getFile()); + assertThat(result.get().getFile()).isEqualTo(defaultResource.getFile()); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RequestPredicateTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RequestPredicateTests.java index 30860c342c9..73bea78c246 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RequestPredicateTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RequestPredicateTests.java @@ -23,8 +23,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -45,9 +44,9 @@ public class RequestPredicateTests { RequestPredicate predicate2 = request -> true; RequestPredicate predicate3 = request -> false; - assertTrue(predicate1.and(predicate2).test(request)); - assertTrue(predicate2.and(predicate1).test(request)); - assertFalse(predicate1.and(predicate3).test(request)); + assertThat(predicate1.and(predicate2).test(request)).isTrue(); + assertThat(predicate2.and(predicate1).test(request)).isTrue(); + assertThat(predicate1.and(predicate3).test(request)).isFalse(); } @Test @@ -55,12 +54,12 @@ public class RequestPredicateTests { RequestPredicate predicate = request -> false; RequestPredicate negated = predicate.negate(); - assertTrue(negated.test(request)); + assertThat(negated.test(request)).isTrue(); predicate = request -> true; negated = predicate.negate(); - assertFalse(negated.test(request)); + assertThat(negated.test(request)).isFalse(); } @Test @@ -69,9 +68,9 @@ public class RequestPredicateTests { RequestPredicate predicate2 = request -> false; RequestPredicate predicate3 = request -> false; - assertTrue(predicate1.or(predicate2).test(request)); - assertTrue(predicate2.or(predicate1).test(request)); - assertFalse(predicate2.or(predicate3).test(request)); + assertThat(predicate1.or(predicate2).test(request)).isTrue(); + assertThat(predicate2.or(predicate1).test(request)).isTrue(); + assertThat(predicate2.or(predicate3).test(request)).isFalse(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RequestPredicatesTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RequestPredicatesTests.java index f1fa58fe5a0..382acfadf1b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RequestPredicatesTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RequestPredicatesTests.java @@ -27,8 +27,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.util.pattern.PathPatternParser; import static java.util.Collections.emptyList; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.http.MediaType.TEXT_XML_VALUE; /** @@ -41,7 +40,7 @@ public class RequestPredicatesTests { RequestPredicate predicate = RequestPredicates.all(); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); } @@ -52,10 +51,10 @@ public class RequestPredicatesTests { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "https://example.com"); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); servletRequest.setMethod("POST"); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -63,13 +62,13 @@ public class RequestPredicatesTests { RequestPredicate predicate = RequestPredicates.methods(HttpMethod.GET, HttpMethod.HEAD); MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "https://example.com"); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); servletRequest.setMethod("HEAD"); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); servletRequest.setMethod("POST"); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -78,31 +77,31 @@ public class RequestPredicatesTests { ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); RequestPredicate predicate = RequestPredicates.GET("/p*"); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.HEAD("/p*"); servletRequest.setMethod("HEAD"); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.POST("/p*"); servletRequest.setMethod("POST"); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.PUT("/p*"); servletRequest.setMethod("PUT"); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.PATCH("/p*"); servletRequest.setMethod("PATCH"); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.DELETE("/p*"); servletRequest.setMethod("DELETE"); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.OPTIONS("/p*"); servletRequest.setMethod("OPTIONS"); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); } @Test @@ -110,11 +109,11 @@ public class RequestPredicatesTests { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/path"); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); RequestPredicate predicate = RequestPredicates.path("/p*"); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); servletRequest = new MockHttpServletRequest("GET", "/foo"); request = new DefaultServerRequest(servletRequest, emptyList()); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -122,7 +121,7 @@ public class RequestPredicatesTests { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/path"); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); RequestPredicate predicate = RequestPredicates.path("p*"); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); } @Test @@ -131,11 +130,11 @@ public class RequestPredicatesTests { ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); RequestPredicate predicate = RequestPredicates.path("/foo bar"); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); servletRequest = new MockHttpServletRequest(); request = new DefaultServerRequest(servletRequest, emptyList()); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -147,7 +146,7 @@ public class RequestPredicatesTests { RequestPredicate predicate = pathPredicates.apply("/P*"); MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/path"); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); } @@ -161,11 +160,11 @@ public class RequestPredicatesTests { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/path"); servletRequest.addHeader(name, value); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); servletRequest = new MockHttpServletRequest(); request = new DefaultServerRequest(servletRequest, emptyList()); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -176,11 +175,11 @@ public class RequestPredicatesTests { servletRequest.setContentType(json.toString()); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); servletRequest = new MockHttpServletRequest(); request = new DefaultServerRequest(servletRequest, emptyList()); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -190,12 +189,12 @@ public class RequestPredicatesTests { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/path"); servletRequest.addHeader("Accept", json.toString()); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); servletRequest = new MockHttpServletRequest(); servletRequest.addHeader("Accept", TEXT_XML_VALUE); request = new DefaultServerRequest(servletRequest, emptyList()); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -204,18 +203,18 @@ public class RequestPredicatesTests { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/file.txt"); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); servletRequest = new MockHttpServletRequest("GET", "/FILE.TXT"); request = new DefaultServerRequest(servletRequest, emptyList()); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.pathExtension("bar"); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); servletRequest = new MockHttpServletRequest("GET", "/file.foo"); request = new DefaultServerRequest(servletRequest, emptyList()); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } @Test @@ -224,16 +223,16 @@ public class RequestPredicatesTests { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/path"); servletRequest.addParameter("foo", "bar"); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.param("foo", s -> s.equals("bar")); - assertTrue(predicate.test(request)); + assertThat(predicate.test(request)).isTrue(); predicate = RequestPredicates.param("foo", "baz"); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); predicate = RequestPredicates.param("foo", s -> s.equals("baz")); - assertFalse(predicate.test(request)); + assertThat(predicate.test(request)).isFalse(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/ResourceHandlerFunctionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/ResourceHandlerFunctionTests.java index a809e3d6e4b..5516e53d43e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/ResourceHandlerFunctionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/ResourceHandlerFunctionTests.java @@ -37,10 +37,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.servlet.ModelAndView; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -74,22 +71,23 @@ public class ResourceHandlerFunctionTests { ServerRequest request = new DefaultServerRequest(servletRequest, Collections.singletonList(messageConverter)); ServerResponse response = this.handlerFunction.handle(request); - assertEquals(HttpStatus.OK, response.statusCode()); - assertTrue(response instanceof EntityResponse); + assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); + boolean condition = response instanceof EntityResponse; + assertThat(condition).isTrue(); @SuppressWarnings("unchecked") EntityResponse entityResponse = (EntityResponse) response; - assertEquals(this.resource, entityResponse.entity()); + assertThat(entityResponse.entity()).isEqualTo(this.resource); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); ModelAndView mav = response.writeTo(servletRequest, servletResponse, this.context); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals(200, servletResponse.getStatus()); + assertThat(servletResponse.getStatus()).isEqualTo(200); byte[] expectedBytes = Files.readAllBytes(this.resource.getFile().toPath()); byte[] actualBytes = servletResponse.getContentAsByteArray(); - assertArrayEquals(expectedBytes, actualBytes); - assertEquals(MediaType.TEXT_PLAIN_VALUE, servletResponse.getContentType()); - assertEquals(this.resource.contentLength(),servletResponse.getContentLength()); + assertThat(actualBytes).isEqualTo(expectedBytes); + assertThat(servletResponse.getContentType()).isEqualTo(MediaType.TEXT_PLAIN_VALUE); + assertThat(servletResponse.getContentLength()).isEqualTo(this.resource.contentLength()); } @Test @@ -98,22 +96,23 @@ public class ResourceHandlerFunctionTests { ServerRequest request = new DefaultServerRequest(servletRequest, Collections.singletonList(messageConverter)); ServerResponse response = this.handlerFunction.handle(request); - assertEquals(HttpStatus.OK, response.statusCode()); - assertTrue(response instanceof EntityResponse); + assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); + boolean condition = response instanceof EntityResponse; + assertThat(condition).isTrue(); @SuppressWarnings("unchecked") EntityResponse entityResponse = (EntityResponse) response; - assertEquals(this.resource.getFilename(), entityResponse.entity().getFilename()); + assertThat(entityResponse.entity().getFilename()).isEqualTo(this.resource.getFilename()); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); ModelAndView mav = response.writeTo(servletRequest, servletResponse, this.context); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals(200, servletResponse.getStatus()); + assertThat(servletResponse.getStatus()).isEqualTo(200); byte[] actualBytes = servletResponse.getContentAsByteArray(); - assertEquals(0, actualBytes.length); - assertEquals(MediaType.TEXT_PLAIN_VALUE, servletResponse.getContentType()); - assertEquals(this.resource.contentLength(),servletResponse.getContentLength()); + assertThat(actualBytes.length).isEqualTo(0); + assertThat(servletResponse.getContentType()).isEqualTo(MediaType.TEXT_PLAIN_VALUE); + assertThat(servletResponse.getContentLength()).isEqualTo(this.resource.contentLength()); } @@ -123,17 +122,17 @@ public class ResourceHandlerFunctionTests { ServerRequest request = new DefaultServerRequest(servletRequest, Collections.singletonList(messageConverter)); ServerResponse response = this.handlerFunction.handle(request); - assertEquals(HttpStatus.OK, response.statusCode()); - assertEquals(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS), response.headers().getAllow()); + assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.headers().getAllow()).isEqualTo(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS)); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); ModelAndView mav = response.writeTo(servletRequest, servletResponse, this.context); - assertNull(mav); + assertThat(mav).isNull(); - assertEquals(200, servletResponse.getStatus()); - assertEquals("GET,HEAD,OPTIONS", servletResponse.getHeader("Allow")); + assertThat(servletResponse.getStatus()).isEqualTo(200); + assertThat(servletResponse.getHeader("Allow")).isEqualTo("GET,HEAD,OPTIONS"); byte[] actualBytes = servletResponse.getContentAsByteArray(); - assertEquals(0, actualBytes.length); + assertThat(actualBytes.length).isEqualTo(0); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionBuilderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionBuilderTests.java index d70dc0170f3..5c8df3bed1a 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionBuilderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionBuilderTests.java @@ -28,9 +28,7 @@ import org.springframework.http.MediaType; import org.springframework.mock.web.test.MockHttpServletRequest; import static java.util.Collections.emptyList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.servlet.function.RequestPredicates.HEAD; /** @@ -56,7 +54,7 @@ public class RouterFunctionBuilderTests { .map(handlerFunction -> handle(handlerFunction, getFooRequest)) .map(ServerResponse::statusCode) .map(HttpStatus::value); - assertEquals(200, responseStatus.get().intValue()); + assertThat(responseStatus.get().intValue()).isEqualTo(200); servletRequest = new MockHttpServletRequest("HEAD", "/foo"); ServerRequest headFooRequest = new DefaultServerRequest(servletRequest, emptyList()); @@ -65,7 +63,7 @@ public class RouterFunctionBuilderTests { .map(handlerFunction -> handle(handlerFunction, getFooRequest)) .map(ServerResponse::statusCode) .map(HttpStatus::value); - assertEquals(202, responseStatus.get().intValue()); + assertThat(responseStatus.get().intValue()).isEqualTo(202); servletRequest = new MockHttpServletRequest("POST", "/"); servletRequest.setContentType("text/plain"); @@ -75,7 +73,7 @@ public class RouterFunctionBuilderTests { .map(handlerFunction -> handle(handlerFunction, barRequest)) .map(ServerResponse::statusCode) .map(HttpStatus::value); - assertEquals(204, responseStatus.get().intValue()); + assertThat(responseStatus.get().intValue()).isEqualTo(204); servletRequest = new MockHttpServletRequest("POST", "/"); ServerRequest invalidRequest = new DefaultServerRequest(servletRequest, emptyList()); @@ -85,7 +83,7 @@ public class RouterFunctionBuilderTests { .map(ServerResponse::statusCode) .map(HttpStatus::value); - assertFalse(responseStatus.isPresent()); + assertThat(responseStatus.isPresent()).isFalse(); } @@ -102,7 +100,7 @@ public class RouterFunctionBuilderTests { @Test public void resources() { Resource resource = new ClassPathResource("/org/springframework/web/servlet/function/"); - assertTrue(resource.exists()); + assertThat(resource.exists()).isTrue(); RouterFunction route = RouterFunctions.route() .resources("/resources/**", resource) @@ -116,7 +114,7 @@ public class RouterFunctionBuilderTests { .map(handlerFunction -> handle(handlerFunction, resourceRequest)) .map(ServerResponse::statusCode) .map(HttpStatus::value); - assertEquals(200, responseStatus.get().intValue()); + assertThat(responseStatus.get().intValue()).isEqualTo(200); servletRequest = new MockHttpServletRequest("POST", "/resources/foo.txt"); ServerRequest invalidRequest = new DefaultServerRequest(servletRequest, emptyList()); @@ -125,7 +123,7 @@ public class RouterFunctionBuilderTests { .map(handlerFunction -> handle(handlerFunction, invalidRequest)) .map(ServerResponse::statusCode) .map(HttpStatus::value); - assertFalse(responseStatus.isPresent()); + assertThat(responseStatus.isPresent()).isFalse(); } @Test @@ -145,7 +143,7 @@ public class RouterFunctionBuilderTests { .map(handlerFunction -> handle(handlerFunction, fooRequest)) .map(ServerResponse::statusCode) .map(HttpStatus::value); - assertEquals(200, responseStatus.get().intValue()); + assertThat(responseStatus.get().intValue()).isEqualTo(200); } @Test @@ -159,20 +157,20 @@ public class RouterFunctionBuilderTests { }) .before(request -> { int count = filterCount.getAndIncrement(); - assertEquals(0, count); + assertThat(count).isEqualTo(0); return request; }) .after((request, response) -> { int count = filterCount.getAndIncrement(); - assertEquals(3, count); + assertThat(count).isEqualTo(3); return response; }) .filter((request, next) -> { int count = filterCount.getAndIncrement(); - assertEquals(1, count); + assertThat(count).isEqualTo(1); ServerResponse responseMono = next.handle(request); count = filterCount.getAndIncrement(); - assertEquals(2, count); + assertThat(count).isEqualTo(2); return responseMono; }) .onError(IllegalStateException.class, @@ -185,7 +183,7 @@ public class RouterFunctionBuilderTests { route.route(fooRequest) .map(handlerFunction -> handle(handlerFunction, fooRequest)); - assertEquals(4, filterCount.get()); + assertThat(filterCount.get()).isEqualTo(4); filterCount.set(0); @@ -196,7 +194,7 @@ public class RouterFunctionBuilderTests { .map(handlerFunction -> handle(handlerFunction, barRequest)) .map(ServerResponse::statusCode) .map(HttpStatus::value); - assertEquals(500, responseStatus.get().intValue()); + assertThat(responseStatus.get().intValue()).isEqualTo(500); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionTests.java index 5d94ec1812f..5976678416a 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionTests.java @@ -23,14 +23,11 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import static java.util.Collections.emptyList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma */ -@SuppressWarnings("unchecked") public class RouterFunctionTests { @Test @@ -40,14 +37,14 @@ public class RouterFunctionTests { RouterFunction routerFunction2 = request -> Optional.of(handlerFunction); RouterFunction result = routerFunction1.and(routerFunction2); - assertNotNull(result); + assertThat(result).isNotNull(); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); Optional> resultHandlerFunction = result.route(request); - assertTrue(resultHandlerFunction.isPresent()); - assertEquals(handlerFunction, resultHandlerFunction.get()); + assertThat(resultHandlerFunction.isPresent()).isTrue(); + assertThat(resultHandlerFunction.get()).isEqualTo(handlerFunction); } @@ -58,14 +55,14 @@ public class RouterFunctionTests { RouterFunction routerFunction2 = request -> Optional.of(handlerFunction); RouterFunction result = routerFunction1.andOther(routerFunction2); - assertNotNull(result); + assertThat(result).isNotNull(); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); Optional> resultHandlerFunction = result.route(request); - assertTrue(resultHandlerFunction.isPresent()); - assertEquals(handlerFunction, resultHandlerFunction.get()); + assertThat(resultHandlerFunction.isPresent()).isTrue(); + assertThat(resultHandlerFunction.get()).isEqualTo(handlerFunction); } @@ -75,13 +72,13 @@ public class RouterFunctionTests { RequestPredicate requestPredicate = request -> true; RouterFunction result = routerFunction1.andRoute(requestPredicate, this::handlerMethod); - assertNotNull(result); + assertThat(result).isNotNull(); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); Optional> resultHandlerFunction = result.route(request); - assertTrue(resultHandlerFunction.isPresent()); + assertThat(resultHandlerFunction.isPresent()).isTrue(); } @@ -101,7 +98,7 @@ public class RouterFunctionTests { }; RouterFunction> result = routerFunction.filter(filterFunction); - assertNotNull(result); + assertThat(result).isNotNull(); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); ServerRequest request = new DefaultServerRequest(servletRequest, emptyList()); @@ -115,8 +112,8 @@ public class RouterFunctionTests { throw new AssertionError(ex.getMessage(), ex); } }); - assertTrue(resultHandlerFunction.isPresent()); - assertEquals(42, (int)resultHandlerFunction.get().entity()); + assertThat(resultHandlerFunction.isPresent()).isTrue(); + assertThat((int) resultHandlerFunction.get().entity()).isEqualTo(42); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionsTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionsTests.java index 498a708d50f..1a46f3c6c6e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionsTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionsTests.java @@ -23,17 +23,13 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author Arjen Poutsma */ -@SuppressWarnings("unchecked") public class RouterFunctionsTests { @Test @@ -47,11 +43,11 @@ public class RouterFunctionsTests { RouterFunction result = RouterFunctions.route(requestPredicate, handlerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); Optional> resultHandlerFunction = result.route(request); - assertTrue(resultHandlerFunction.isPresent()); - assertEquals(handlerFunction, resultHandlerFunction.get()); + assertThat(resultHandlerFunction.isPresent()).isTrue(); + assertThat(resultHandlerFunction.get()).isEqualTo(handlerFunction); } @Test @@ -64,10 +60,10 @@ public class RouterFunctionsTests { given(requestPredicate.test(request)).willReturn(false); RouterFunction result = RouterFunctions.route(requestPredicate, handlerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); Optional> resultHandlerFunction = result.route(request); - assertFalse(resultHandlerFunction.isPresent()); + assertThat(resultHandlerFunction.isPresent()).isFalse(); } @Test @@ -81,11 +77,11 @@ public class RouterFunctionsTests { given(requestPredicate.nest(request)).willReturn(Optional.of(request)); RouterFunction result = RouterFunctions.nest(requestPredicate, routerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); Optional> resultHandlerFunction = result.route(request); - assertTrue(resultHandlerFunction.isPresent()); - assertEquals(handlerFunction, resultHandlerFunction.get()); + assertThat(resultHandlerFunction.isPresent()).isTrue(); + assertThat(resultHandlerFunction.get()).isEqualTo(handlerFunction); } @Test @@ -99,10 +95,10 @@ public class RouterFunctionsTests { given(requestPredicate.nest(request)).willReturn(Optional.empty()); RouterFunction result = RouterFunctions.nest(requestPredicate, routerFunction); - assertNotNull(result); + assertThat(result).isNotNull(); Optional> resultHandlerFunction = result.route(request); - assertFalse(resultHandlerFunction.isPresent()); + assertThat(resultHandlerFunction.isPresent()).isFalse(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/ToStringVisitorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/ToStringVisitorTests.java index c9901bce49f..1aa19cf4b46 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/function/ToStringVisitorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/function/ToStringVisitorTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.servlet.function.RequestPredicates.GET; import static org.springframework.web.servlet.function.RequestPredicates.accept; import static org.springframework.web.servlet.function.RequestPredicates.contentType; @@ -57,7 +57,7 @@ public class ToStringVisitorTests { " (GET && /baz) -> \n" + " }\n" + "}"; - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); } @Test @@ -93,7 +93,7 @@ public class ToStringVisitorTests { predicate.accept(visitor); String result = visitor.toString(); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java index a5d2db4ff74..7fc56258ee6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java @@ -29,8 +29,8 @@ import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.HandlerMapping; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertTrue; /** * @author Rod Johnson @@ -59,11 +59,11 @@ public class BeanNameUrlHandlerMappingTests { MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/nonsense.html"); req.setContextPath("/myapp"); Object h = hm.getHandler(req); - assertTrue("Handler is null", h == null); + assertThat(h == null).as("Handler is null").isTrue(); req = new MockHttpServletRequest("GET", "/foo/bar/baz.html"); h = hm.getHandler(req); - assertTrue("Handler is null", h == null); + assertThat(h == null).as("Handler is null").isTrue(); } @Test @@ -85,38 +85,38 @@ public class BeanNameUrlHandlerMappingTests { MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/welcome.html"); HandlerExecutionChain hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/myapp/mypath/welcome.html"); req.setContextPath("/myapp"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/myapp/mypath/welcome.html"); req.setContextPath("/myapp"); req.setServletPath("/mypath/welcome.html"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/myapp/myservlet/mypath/welcome.html"); req.setContextPath("/myapp"); req.setServletPath("/myservlet"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/myapp/myapp/mypath/welcome.html"); req.setContextPath("/myapp"); req.setServletPath("/myapp"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/mypath/show.html"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/mypath/bookseats.html"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); } @Test @@ -128,28 +128,28 @@ public class BeanNameUrlHandlerMappingTests { MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/welcome.html"); HandlerExecutionChain hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/myapp/mypath/welcome.html"); req.setContextPath("/myapp"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/mypath/welcome.html"); req.setContextPath(""); req.setServletPath("/mypath"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/Myapp/mypath/welcome.html"); req.setContextPath("/myapp"); req.setServletPath("/mypath"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); } @Test @@ -159,15 +159,15 @@ public class BeanNameUrlHandlerMappingTests { MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/test.html"); HandlerExecutionChain hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/mypath/testarossa"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/mypath/tes"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec == null); + assertThat(hec == null).as("Handler is correct bean").isTrue(); } @Test @@ -179,15 +179,15 @@ public class BeanNameUrlHandlerMappingTests { MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/test.html"); HandlerExecutionChain hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/mypath/testarossa"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == anotherHandler); + assertThat(hec != null && hec.getHandler() == anotherHandler).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/mypath/tes"); hec = hm.getHandler(req); - assertTrue("Handler is correct bean", hec == null); + assertThat(hec == null).as("Handler is correct bean").isTrue(); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/CorsAbstractHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/CorsAbstractHandlerMappingTests.java index 35e248ced92..b41a9e2e345 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/CorsAbstractHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/CorsAbstractHandlerMappingTests.java @@ -39,9 +39,7 @@ import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.support.WebContentGenerator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -74,8 +72,9 @@ public class CorsAbstractHandlerMappingTests { this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); HandlerExecutionChain chain = handlerMapping.getHandler(this.request); - assertNotNull(chain); - assertTrue(chain.getHandler() instanceof SimpleHandler); + assertThat(chain).isNotNull(); + boolean condition = chain.getHandler() instanceof SimpleHandler; + assertThat(condition).isTrue(); } @Test @@ -86,8 +85,9 @@ public class CorsAbstractHandlerMappingTests { this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); HandlerExecutionChain chain = handlerMapping.getHandler(this.request); - assertNotNull(chain); - assertTrue(chain.getHandler() instanceof SimpleHandler); + assertThat(chain).isNotNull(); + boolean condition = chain.getHandler() instanceof SimpleHandler; + assertThat(condition).isTrue(); } @Test @@ -98,9 +98,10 @@ public class CorsAbstractHandlerMappingTests { this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); HandlerExecutionChain chain = handlerMapping.getHandler(this.request); - assertNotNull(chain); - assertTrue(chain.getHandler() instanceof CorsAwareHandler); - assertEquals(Collections.singletonList("*"), getRequiredCorsConfiguration(chain, false).getAllowedOrigins()); + assertThat(chain).isNotNull(); + boolean condition = chain.getHandler() instanceof CorsAwareHandler; + assertThat(condition).isTrue(); + assertThat(getRequiredCorsConfiguration(chain, false).getAllowedOrigins()).isEqualTo(Collections.singletonList("*")); } @Test @@ -111,10 +112,10 @@ public class CorsAbstractHandlerMappingTests { this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); HandlerExecutionChain chain = handlerMapping.getHandler(this.request); - assertNotNull(chain); - assertNotNull(chain.getHandler()); - assertEquals("PreFlightHandler", chain.getHandler().getClass().getSimpleName()); - assertEquals(Collections.singletonList("*"), getRequiredCorsConfiguration(chain, true).getAllowedOrigins()); + assertThat(chain).isNotNull(); + assertThat(chain.getHandler()).isNotNull(); + assertThat(chain.getHandler().getClass().getSimpleName()).isEqualTo("PreFlightHandler"); + assertThat(getRequiredCorsConfiguration(chain, true).getAllowedOrigins()).isEqualTo(Collections.singletonList("*")); } @Test @@ -128,9 +129,10 @@ public class CorsAbstractHandlerMappingTests { this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); HandlerExecutionChain chain = handlerMapping.getHandler(this.request); - assertNotNull(chain); - assertTrue(chain.getHandler() instanceof SimpleHandler); - assertEquals(Collections.singletonList("*"), getRequiredCorsConfiguration(chain, false).getAllowedOrigins()); + assertThat(chain).isNotNull(); + boolean condition = chain.getHandler() instanceof SimpleHandler; + assertThat(condition).isTrue(); + assertThat(getRequiredCorsConfiguration(chain, false).getAllowedOrigins()).isEqualTo(Collections.singletonList("*")); } @Test @@ -144,10 +146,10 @@ public class CorsAbstractHandlerMappingTests { this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); HandlerExecutionChain chain = handlerMapping.getHandler(this.request); - assertNotNull(chain); - assertNotNull(chain.getHandler()); - assertEquals("PreFlightHandler", chain.getHandler().getClass().getSimpleName()); - assertEquals(Collections.singletonList("*"), getRequiredCorsConfiguration(chain, true).getAllowedOrigins()); + assertThat(chain).isNotNull(); + assertThat(chain.getHandler()).isNotNull(); + assertThat(chain.getHandler().getClass().getSimpleName()).isEqualTo("PreFlightHandler"); + assertThat(getRequiredCorsConfiguration(chain, true).getAllowedOrigins()).isEqualTo(Collections.singletonList("*")); } @Test @@ -159,12 +161,13 @@ public class CorsAbstractHandlerMappingTests { this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); HandlerExecutionChain chain = handlerMapping.getHandler(this.request); - assertNotNull(chain); - assertTrue(chain.getHandler() instanceof SimpleHandler); + assertThat(chain).isNotNull(); + boolean condition = chain.getHandler() instanceof SimpleHandler; + assertThat(condition).isTrue(); CorsConfiguration config = getRequiredCorsConfiguration(chain, false); - assertNotNull(config); - assertEquals(Collections.singletonList("*"), config.getAllowedOrigins()); - assertEquals(true, config.getAllowCredentials()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedOrigins()).isEqualTo(Collections.singletonList("*")); + assertThat(config.getAllowCredentials()).isEqualTo(true); } @Test @@ -176,13 +179,13 @@ public class CorsAbstractHandlerMappingTests { this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); HandlerExecutionChain chain = handlerMapping.getHandler(this.request); - assertNotNull(chain); - assertNotNull(chain.getHandler()); - assertEquals("PreFlightHandler", chain.getHandler().getClass().getSimpleName()); + assertThat(chain).isNotNull(); + assertThat(chain.getHandler()).isNotNull(); + assertThat(chain.getHandler().getClass().getSimpleName()).isEqualTo("PreFlightHandler"); CorsConfiguration config = getRequiredCorsConfiguration(chain, true); - assertNotNull(config); - assertEquals(Collections.singletonList("*"), config.getAllowedOrigins()); - assertEquals(true, config.getAllowCredentials()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedOrigins()).isEqualTo(Collections.singletonList("*")); + assertThat(config.getAllowCredentials()).isEqualTo(true); } @@ -191,7 +194,7 @@ public class CorsAbstractHandlerMappingTests { CorsConfiguration corsConfig = null; if (isPreFlightRequest) { Object handler = chain.getHandler(); - assertEquals("PreFlightHandler", handler.getClass().getSimpleName()); + assertThat(handler.getClass().getSimpleName()).isEqualTo("PreFlightHandler"); DirectFieldAccessor accessor = new DirectFieldAccessor(handler); corsConfig = (CorsConfiguration) accessor.getPropertyValue("config"); } @@ -202,7 +205,7 @@ public class CorsAbstractHandlerMappingTests { corsConfig = (CorsConfiguration) accessor.getPropertyValue("config"); } } - assertNotNull(corsConfig); + assertThat(corsConfig).isNotNull(); return corsConfig; } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java index 187fbbc8b99..5ab6723c56d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java @@ -39,10 +39,8 @@ import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.springframework.web.servlet.HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE; /** @@ -64,7 +62,7 @@ public class HandlerMappingIntrospectorTests { List expected = Arrays.asList(cxt.getBean("hmA"), cxt.getBean("hmB"), cxt.getBean("hmC")); List actual = getIntrospector(cxt).getHandlerMappings(); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -81,7 +79,7 @@ public class HandlerMappingIntrospectorTests { List expected = Arrays.asList(cxt.getBean("hmC"), cxt.getBean("hmB"), cxt.getBean("hmA")); List actual = getIntrospector(cxt).getHandlerMappings(); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } public void defaultHandlerMappings() throws Exception { @@ -89,9 +87,9 @@ public class HandlerMappingIntrospectorTests { cxt.refresh(); List actual = getIntrospector(cxt).getHandlerMappings(); - assertEquals(2, actual.size()); - assertEquals(BeanNameUrlHandlerMapping.class, actual.get(0).getClass()); - assertEquals(RequestMappingHandlerMapping.class, actual.get(1).getClass()); + assertThat(actual.size()).isEqualTo(2); + assertThat(actual.get(0).getClass()).isEqualTo(BeanNameUrlHandlerMapping.class); + assertThat(actual.get(1).getClass()).isEqualTo(RequestMappingHandlerMapping.class); } @Test @@ -106,8 +104,8 @@ public class HandlerMappingIntrospectorTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/path"); MatchableHandlerMapping hm = getIntrospector(cxt).getMatchableHandlerMapping(request); - assertEquals(cxt.getBean("hm"), hm); - assertNull("Attributes changes not ignored", request.getAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE)); + assertThat(hm).isEqualTo(cxt.getBean("hm")); + assertThat(request.getAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE)).as("Attributes changes not ignored").isNull(); } @Test @@ -134,9 +132,9 @@ public class HandlerMappingIntrospectorTests { request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"); CorsConfiguration corsConfig = getIntrospector(cxt).getCorsConfiguration(request); - assertNotNull(corsConfig); - assertEquals(Collections.singletonList("http://localhost:9000"), corsConfig.getAllowedOrigins()); - assertEquals(Collections.singletonList("POST"), corsConfig.getAllowedMethods()); + assertThat(corsConfig).isNotNull(); + assertThat(corsConfig.getAllowedOrigins()).isEqualTo(Collections.singletonList("http://localhost:9000")); + assertThat(corsConfig.getAllowedMethods()).isEqualTo(Collections.singletonList("POST")); } @Test @@ -149,9 +147,9 @@ public class HandlerMappingIntrospectorTests { request.addHeader("Origin", "http://localhost:9000"); CorsConfiguration corsConfig = getIntrospector(cxt).getCorsConfiguration(request); - assertNotNull(corsConfig); - assertEquals(Collections.singletonList("http://localhost:9000"), corsConfig.getAllowedOrigins()); - assertEquals(Collections.singletonList("POST"), corsConfig.getAllowedMethods()); + assertThat(corsConfig).isNotNull(); + assertThat(corsConfig.getAllowedOrigins()).isEqualTo(Collections.singletonList("http://localhost:9000")); + assertThat(corsConfig.getAllowedMethods()).isEqualTo(Collections.singletonList("POST")); } private HandlerMappingIntrospector getIntrospector(WebApplicationContext cxt) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMethodMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMethodMappingTests.java index da989b72c54..3d6e2c86430 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMethodMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMethodMappingTests.java @@ -38,10 +38,8 @@ import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.util.UrlPathHelper; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; /** @@ -85,8 +83,8 @@ public class HandlerMethodMappingTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", key); HandlerMethod result = this.mapping.getHandlerInternal(request); - assertEquals(method1, result.getMethod()); - assertEquals(result, request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)); + assertThat(result.getMethod()).isEqualTo(method1); + assertThat(request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)).isEqualTo(result); } @Test @@ -96,8 +94,8 @@ public class HandlerMethodMappingTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); HandlerMethod result = this.mapping.getHandlerInternal(request); - assertEquals(method1, result.getMethod()); - assertEquals(result, request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)); + assertThat(result.getMethod()).isEqualTo(method1); + assertThat(request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)).isEqualTo(result); } @Test @@ -118,14 +116,14 @@ public class HandlerMethodMappingTests { mapping1.setApplicationContext(new StaticApplicationContext(cxt)); mapping1.afterPropertiesSet(); - assertEquals(0, mapping1.getHandlerMethods().size()); + assertThat(mapping1.getHandlerMethods().size()).isEqualTo(0); AbstractHandlerMethodMapping mapping2 = new MyHandlerMethodMapping(); mapping2.setDetectHandlerMethodsInAncestorContexts(true); mapping2.setApplicationContext(new StaticApplicationContext(cxt)); mapping2.afterPropertiesSet(); - assertEquals(2, mapping2.getHandlerMethods().size()); + assertThat(mapping2.getHandlerMethods().size()).isEqualTo(2); } @Test @@ -139,9 +137,9 @@ public class HandlerMethodMappingTests { // Direct URL lookup List directUrlMatches = this.mapping.getMappingRegistry().getMappingsByUrl(key1); - assertNotNull(directUrlMatches); - assertEquals(1, directUrlMatches.size()); - assertEquals(key1, directUrlMatches.get(0)); + assertThat(directUrlMatches).isNotNull(); + assertThat(directUrlMatches.size()).isEqualTo(1); + assertThat(directUrlMatches.get(0)).isEqualTo(key1); // Mapping name lookup @@ -150,25 +148,25 @@ public class HandlerMethodMappingTests { String name1 = this.method1.getName(); List handlerMethods = this.mapping.getMappingRegistry().getHandlerMethodsByMappingName(name1); - assertNotNull(handlerMethods); - assertEquals(1, handlerMethods.size()); - assertEquals(handlerMethod1, handlerMethods.get(0)); + assertThat(handlerMethods).isNotNull(); + assertThat(handlerMethods.size()).isEqualTo(1); + assertThat(handlerMethods.get(0)).isEqualTo(handlerMethod1); String name2 = this.method2.getName(); handlerMethods = this.mapping.getMappingRegistry().getHandlerMethodsByMappingName(name2); - assertNotNull(handlerMethods); - assertEquals(1, handlerMethods.size()); - assertEquals(handlerMethod2, handlerMethods.get(0)); + assertThat(handlerMethods).isNotNull(); + assertThat(handlerMethods.size()).isEqualTo(1); + assertThat(handlerMethods.get(0)).isEqualTo(handlerMethod2); // CORS lookup CorsConfiguration config = this.mapping.getMappingRegistry().getCorsConfiguration(handlerMethod1); - assertNotNull(config); - assertEquals("http://" + handler.hashCode() + name1, config.getAllowedOrigins().get(0)); + assertThat(config).isNotNull(); + assertThat(config.getAllowedOrigins().get(0)).isEqualTo(("http://" + handler.hashCode() + name1)); config = this.mapping.getMappingRegistry().getCorsConfiguration(handlerMethod2); - assertNotNull(config); - assertEquals("http://" + handler.hashCode() + name2, config.getAllowedOrigins().get(0)); + assertThat(config).isNotNull(); + assertThat(config.getAllowedOrigins().get(0)).isEqualTo(("http://" + handler.hashCode() + name2)); } @Test @@ -189,28 +187,28 @@ public class HandlerMethodMappingTests { // Direct URL lookup List directUrlMatches = this.mapping.getMappingRegistry().getMappingsByUrl(key1); - assertNotNull(directUrlMatches); - assertEquals(1, directUrlMatches.size()); - assertEquals(key1, directUrlMatches.get(0)); + assertThat(directUrlMatches).isNotNull(); + assertThat(directUrlMatches.size()).isEqualTo(1); + assertThat(directUrlMatches.get(0)).isEqualTo(key1); // Mapping name lookup String name = this.method1.getName(); List handlerMethods = this.mapping.getMappingRegistry().getHandlerMethodsByMappingName(name); - assertNotNull(handlerMethods); - assertEquals(2, handlerMethods.size()); - assertEquals(handlerMethod1, handlerMethods.get(0)); - assertEquals(handlerMethod2, handlerMethods.get(1)); + assertThat(handlerMethods).isNotNull(); + assertThat(handlerMethods.size()).isEqualTo(2); + assertThat(handlerMethods.get(0)).isEqualTo(handlerMethod1); + assertThat(handlerMethods.get(1)).isEqualTo(handlerMethod2); // CORS lookup CorsConfiguration config = this.mapping.getMappingRegistry().getCorsConfiguration(handlerMethod1); - assertNotNull(config); - assertEquals("http://" + handler1.hashCode() + name, config.getAllowedOrigins().get(0)); + assertThat(config).isNotNull(); + assertThat(config.getAllowedOrigins().get(0)).isEqualTo(("http://" + handler1.hashCode() + name)); config = this.mapping.getMappingRegistry().getCorsConfiguration(handlerMethod2); - assertNotNull(config); - assertEquals("http://" + handler2.hashCode() + name, config.getAllowedOrigins().get(0)); + assertThat(config).isNotNull(); + assertThat(config.getAllowedOrigins().get(0)).isEqualTo(("http://" + handler2.hashCode() + name)); } @Test @@ -220,13 +218,13 @@ public class HandlerMethodMappingTests { HandlerMethod handlerMethod = new HandlerMethod(this.handler, this.method1); this.mapping.registerMapping(key, this.handler, this.method1); - assertNotNull(this.mapping.getHandlerInternal(new MockHttpServletRequest("GET", key))); + assertThat(this.mapping.getHandlerInternal(new MockHttpServletRequest("GET", key))).isNotNull(); this.mapping.unregisterMapping(key); - assertNull(mapping.getHandlerInternal(new MockHttpServletRequest("GET", key))); - assertNull(this.mapping.getMappingRegistry().getMappingsByUrl(key)); - assertNull(this.mapping.getMappingRegistry().getHandlerMethodsByMappingName(this.method1.getName())); - assertNull(this.mapping.getMappingRegistry().getCorsConfiguration(handlerMethod)); + assertThat(mapping.getHandlerInternal(new MockHttpServletRequest("GET", key))).isNull(); + assertThat(this.mapping.getMappingRegistry().getMappingsByUrl(key)).isNull(); + assertThat(this.mapping.getMappingRegistry().getHandlerMethodsByMappingName(this.method1.getName())).isNull(); + assertThat(this.mapping.getMappingRegistry().getCorsConfiguration(handlerMethod)).isNull(); } @Test @@ -243,8 +241,8 @@ public class HandlerMethodMappingTests { HandlerMethod handlerMethod = this.mapping.getHandlerInternal(new MockHttpServletRequest("GET", key)); CorsConfiguration config = this.mapping.getMappingRegistry().getCorsConfiguration(handlerMethod); - assertNotNull(config); - assertEquals("http://" + beanName.hashCode() + this.method1.getName(), config.getAllowedOrigins().get(0)); + assertThat(config).isNotNull(); + assertThat(config.getAllowedOrigins().get(0)).isEqualTo(("http://" + beanName.hashCode() + this.method1.getName())); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/MappedInterceptorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/MappedInterceptorTests.java index 86b93a957a3..d0e3b0f3535 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/MappedInterceptorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/MappedInterceptorTests.java @@ -29,8 +29,7 @@ import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.then; import static org.mockito.Mockito.mock; @@ -54,29 +53,29 @@ public class MappedInterceptorTests { @Test public void noPatterns() { MappedInterceptor mappedInterceptor = new MappedInterceptor(null, null, this.interceptor); - assertTrue(mappedInterceptor.matches("/foo", pathMatcher)); + assertThat(mappedInterceptor.matches("/foo", pathMatcher)).isTrue(); } @Test public void includePattern() { MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/foo/*" }, this.interceptor); - assertTrue(mappedInterceptor.matches("/foo/bar", pathMatcher)); - assertFalse(mappedInterceptor.matches("/bar/foo", pathMatcher)); + assertThat(mappedInterceptor.matches("/foo/bar", pathMatcher)).isTrue(); + assertThat(mappedInterceptor.matches("/bar/foo", pathMatcher)).isFalse(); } @Test public void includePatternWithMatrixVariables() { MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/foo*/*" }, this.interceptor); - assertTrue(mappedInterceptor.matches("/foo;q=1/bar;s=2", pathMatcher)); + assertThat(mappedInterceptor.matches("/foo;q=1/bar;s=2", pathMatcher)).isTrue(); } @Test public void excludePattern() { MappedInterceptor mappedInterceptor = new MappedInterceptor(null, new String[] { "/admin/**" }, this.interceptor); - assertTrue(mappedInterceptor.matches("/foo", pathMatcher)); - assertFalse(mappedInterceptor.matches("/admin/foo", pathMatcher)); + assertThat(mappedInterceptor.matches("/foo", pathMatcher)).isTrue(); + assertThat(mappedInterceptor.matches("/admin/foo", pathMatcher)).isFalse(); } @Test @@ -84,8 +83,8 @@ public class MappedInterceptorTests { MappedInterceptor mappedInterceptor = new MappedInterceptor( new String[] { "/**" }, new String[] { "/admin/**" }, this.interceptor); - assertTrue(mappedInterceptor.matches("/foo", pathMatcher)); - assertFalse(mappedInterceptor.matches("/admin/foo", pathMatcher)); + assertThat(mappedInterceptor.matches("/foo", pathMatcher)).isTrue(); + assertThat(mappedInterceptor.matches("/admin/foo", pathMatcher)).isFalse(); } @Test @@ -93,8 +92,8 @@ public class MappedInterceptorTests { MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/foo/[0-9]*" }, this.interceptor); mappedInterceptor.setPathMatcher(new TestPathMatcher()); - assertTrue(mappedInterceptor.matches("/foo/123", pathMatcher)); - assertFalse(mappedInterceptor.matches("/foo/bar", pathMatcher)); + assertThat(mappedInterceptor.matches("/foo/123", pathMatcher)).isTrue(); + assertThat(mappedInterceptor.matches("/foo/bar", pathMatcher)).isFalse(); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/PathMatchingUrlHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/PathMatchingUrlHandlerMappingTests.java index abfba413a64..1587a1b5375 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/PathMatchingUrlHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/PathMatchingUrlHandlerMappingTests.java @@ -27,8 +27,7 @@ import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.HandlerMapping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Alef Arendsen @@ -58,15 +57,15 @@ public class PathMatchingUrlHandlerMappingTests { MockHttpServletRequest req = new MockHttpServletRequest("GET", "/welcome.html"); HandlerExecutionChain hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/show.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/bookseats.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); } @Test @@ -80,148 +79,148 @@ public class PathMatchingUrlHandlerMappingTests { // testing some normal behavior MockHttpServletRequest req = new MockHttpServletRequest("GET", "/pathmatchingTest.html"); HandlerExecutionChain hec = getHandler(req); - assertTrue("Handler is null", hec != null); - assertTrue("Handler is correct bean", hec.getHandler() == bean); - assertEquals("/pathmatchingTest.html", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)); + assertThat(hec != null).as("Handler is null").isTrue(); + assertThat(hec.getHandler() == bean).as("Handler is correct bean").isTrue(); + assertThat(req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("/pathmatchingTest.html"); // no match, no forward slash included req = new MockHttpServletRequest("GET", "welcome.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); - assertEquals("welcome.html", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); + assertThat(req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("welcome.html"); // testing some ????? behavior req = new MockHttpServletRequest("GET", "/pathmatchingAA.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); - assertEquals("pathmatchingAA.html", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); + assertThat(req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("pathmatchingAA.html"); // testing some ????? behavior req = new MockHttpServletRequest("GET", "/pathmatchingA.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); - assertEquals("/pathmatchingA.html", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); + assertThat(req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("/pathmatchingA.html"); // testing some ????? behavior req = new MockHttpServletRequest("GET", "/administrator/pathmatching.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); // testing simple /**/behavior req = new MockHttpServletRequest("GET", "/administrator/test/pathmatching.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); // this should not match because of the administratorT req = new MockHttpServletRequest("GET", "/administratort/pathmatching.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); // this should match because of *.jsp req = new MockHttpServletRequest("GET", "/bla.jsp"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); // should match because exact pattern is there req = new MockHttpServletRequest("GET", "/administrator/another/bla.xml"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); // should not match, because there's not .gif extension in there req = new MockHttpServletRequest("GET", "/administrator/another/bla.gif"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); // should match because there testlast* in there req = new MockHttpServletRequest("GET", "/administrator/test/testlastbit"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); // but this not, because it's testlast and not testla req = new MockHttpServletRequest("GET", "/administrator/test/testla"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/administrator/testing/longer/bla"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/administrator/testing/longer/test.jsp"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/administrator/testing/longer2/notmatching/notmatching"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/shortpattern/testing/toolong"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/XXpathXXmatching.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/pathXXmatching.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/XpathXXmatching.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/XXpathmatching.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/show12.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/show123.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/show1.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/reallyGood-test-is-this.jpeg"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/reallyGood-tst-is-this.jpeg"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/testing/test.jpeg"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/testing/test.jpg"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/anotherTest"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/stillAnotherTest"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); // there outofpattern*yeah in the pattern, so this should fail req = new MockHttpServletRequest("GET", "/outofpattern*ye"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/test't est/path'm atching.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/test%26t%20est/path%26m%20atching.html"); hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); } @Test @@ -229,7 +228,7 @@ public class PathMatchingUrlHandlerMappingTests { Object bean = wac.getBean("starController"); MockHttpServletRequest req = new MockHttpServletRequest("GET", "/goggog.html"); HandlerExecutionChain hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); } @Test @@ -237,9 +236,8 @@ public class PathMatchingUrlHandlerMappingTests { Object bean = wac.getBean("mainController"); MockHttpServletRequest req = new MockHttpServletRequest("GET", "/show.html"); HandlerExecutionChain hec = getHandler(req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); - assertEquals("Mapping not exposed", "show.html", - req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); + assertThat(req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).as("Mapping not exposed").isEqualTo("show.html"); } private HandlerExecutionChain getHandler(MockHttpServletRequest req) throws Exception { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolverTests.java index 2cfda13cb78..689cbcd8cdf 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolverTests.java @@ -28,8 +28,7 @@ import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.util.WebUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Seth Ladd @@ -59,15 +58,15 @@ public class SimpleMappingExceptionResolverTests { @Test public void setOrder() { exceptionResolver.setOrder(2); - assertEquals(2, exceptionResolver.getOrder()); + assertThat(exceptionResolver.getOrder()).isEqualTo(2); } @Test public void defaultErrorView() { exceptionResolver.setDefaultErrorView("default-view"); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("default-view", mav.getViewName()); - assertEquals(genericException, mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)); + assertThat(mav.getViewName()).isEqualTo("default-view"); + assertThat(mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)).isEqualTo(genericException); } @Test @@ -75,7 +74,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setDefaultErrorView("default-view"); exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException); - assertNull(mav); + assertThat(mav).isNull(); } @Test @@ -83,7 +82,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setDefaultErrorView("default-view"); exceptionResolver.setMappedHandlerClasses(String.class); ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException); - assertNull(mav); + assertThat(mav).isNull(); } @Test @@ -91,8 +90,8 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setDefaultErrorView("default-view"); exceptionResolver.setExceptionAttribute(null); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("default-view", mav.getViewName()); - assertNull(mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)); + assertThat(mav.getViewName()).isEqualTo("default-view"); + assertThat(mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)).isNull(); } @Test @@ -100,14 +99,14 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setExceptionMappings(null); exceptionResolver.setDefaultErrorView("default-view"); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("default-view", mav.getViewName()); + assertThat(mav.getViewName()).isEqualTo("default-view"); } @Test public void noDefaultStatusCode() { exceptionResolver.setDefaultErrorView("default-view"); exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals(HttpServletResponse.SC_OK, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -115,7 +114,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setDefaultErrorView("default-view"); exceptionResolver.setDefaultStatusCode(HttpServletResponse.SC_BAD_REQUEST); exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_BAD_REQUEST); } @Test @@ -124,7 +123,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setDefaultStatusCode(HttpServletResponse.SC_BAD_REQUEST); request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "some path"); exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals(HttpServletResponse.SC_OK, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -135,7 +134,7 @@ public class SimpleMappingExceptionResolverTests { statusCodes.setProperty("default-view", "406"); exceptionResolver.setStatusCodes(statusCodes); exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals(HttpServletResponse.SC_NOT_ACCEPTABLE, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_NOT_ACCEPTABLE); } @Test @@ -145,7 +144,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setWarnLogCategory("HANDLER_EXCEPTION"); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); + assertThat(mav.getViewName()).isEqualTo("error"); } @Test @@ -155,7 +154,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); + assertThat(mav.getViewName()).isEqualTo("error"); } @Test @@ -165,7 +164,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setMappedHandlerClasses(String.class); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); + assertThat(mav.getViewName()).isEqualTo("error"); } @Test @@ -175,7 +174,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setMappedHandlerClasses(Comparable.class); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); + assertThat(mav.getViewName()).isEqualTo("error"); } @Test @@ -185,7 +184,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException); - assertNull(mav); + assertThat(mav).isNull(); } @Test @@ -195,7 +194,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setMappedHandlerClasses(String.class); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException); - assertNull(mav); + assertThat(mav).isNull(); } @Test @@ -205,7 +204,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setExceptionMappings(props); exceptionResolver.setExcludedExceptions(IllegalArgumentException.class); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, new IllegalArgumentException()); - assertNull(mav); + assertThat(mav).isNull(); } @Test @@ -215,7 +214,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setWarnLogCategory("HANDLER_EXCEPTION"); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertNull(mav); + assertThat(mav).isNull(); } @Test @@ -226,7 +225,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); + assertThat(mav.getViewName()).isEqualTo("error"); } @Test @@ -237,7 +236,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); + assertThat(mav.getViewName()).isEqualTo("error"); } @Test @@ -249,7 +248,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException); - assertEquals("another-error", mav.getViewName()); + assertThat(mav.getViewName()).isEqualTo("another-error"); } @Test @@ -261,7 +260,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException); - assertEquals("another-error", mav.getViewName()); + assertThat(mav.getViewName()).isEqualTo("another-error"); } @Test @@ -274,7 +273,7 @@ public class SimpleMappingExceptionResolverTests { exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); exceptionResolver.setExceptionMappings(props); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException); - assertEquals("another-some-error", mav.getViewName()); + assertThat(mav.getViewName()).isEqualTo("another-some-error"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMappingTests.java index b987f84b6d5..a5c25777640 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMappingTests.java @@ -34,10 +34,6 @@ import org.springframework.web.util.WebUtils; import static org.assertj.core.api.Assertions.assertThat; 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; /** * @author Rod Johnson @@ -87,8 +83,8 @@ public class SimpleUrlHandlerMappingTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo%0a%0dbar/baz"); HandlerExecutionChain hec = handlerMapping.getHandler(request); - assertNotNull(hec); - assertSame(controller, hec.getHandler()); + assertThat(hec).isNotNull(); + assertThat(hec.getHandler()).isSameAs(controller); } @SuppressWarnings("resource") @@ -105,63 +101,63 @@ public class SimpleUrlHandlerMappingTests { MockHttpServletRequest req = new MockHttpServletRequest("GET", "/welcome.html"); HandlerExecutionChain hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); - assertEquals("/welcome.html", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)); - assertEquals(bean, req.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); + assertThat(req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("/welcome.html"); + assertThat(req.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)).isEqualTo(bean); req = new MockHttpServletRequest("GET", "/welcome.x"); hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == otherBean); - assertEquals("welcome.x", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)); - assertEquals(otherBean, req.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)); + assertThat(hec != null && hec.getHandler() == otherBean).as("Handler is correct bean").isTrue(); + assertThat(req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("welcome.x"); + assertThat(req.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)).isEqualTo(otherBean); req = new MockHttpServletRequest("GET", "/welcome/"); hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == otherBean); - assertEquals("welcome", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)); + assertThat(hec != null && hec.getHandler() == otherBean).as("Handler is correct bean").isTrue(); + assertThat(req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("welcome"); req = new MockHttpServletRequest("GET", "/"); req.setServletPath("/welcome.html"); hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/welcome.html"); req.setContextPath("/app"); hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/show.html"); hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/bookseats.html"); hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/original-welcome.html"); req.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/welcome.html"); hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/original-show.html"); req.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/show.html"); hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/original-bookseats.html"); req.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/bookseats.html"); hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); req = new MockHttpServletRequest("GET", "/"); hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean); - assertEquals("/", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)); + assertThat(hec != null && hec.getHandler() == bean).as("Handler is correct bean").isTrue(); + assertThat(req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("/"); req = new MockHttpServletRequest("GET", "/somePath"); hec = getHandler(hm, req); - assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean); - assertEquals("/somePath", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)); + assertThat(hec != null && hec.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); + assertThat(req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("/somePath"); } private HandlerExecutionChain getHandler(HandlerMapping hm, MockHttpServletRequest req) throws Exception { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/AcceptHeaderLocaleResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/AcceptHeaderLocaleResolverTests.java index 8ba3c5608d1..50597a8324d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/AcceptHeaderLocaleResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/AcceptHeaderLocaleResolverTests.java @@ -34,7 +34,7 @@ import static java.util.Locale.JAPANESE; import static java.util.Locale.KOREA; import static java.util.Locale.UK; import static java.util.Locale.US; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link AcceptHeaderLocaleResolver}. @@ -49,38 +49,38 @@ public class AcceptHeaderLocaleResolverTests { @Test public void resolve() { - assertEquals(CANADA, this.resolver.resolveLocale(request(CANADA))); - assertEquals(US, this.resolver.resolveLocale(request(US, CANADA))); + assertThat(this.resolver.resolveLocale(request(CANADA))).isEqualTo(CANADA); + assertThat(this.resolver.resolveLocale(request(US, CANADA))).isEqualTo(US); } @Test public void resolvePreferredSupported() { this.resolver.setSupportedLocales(Collections.singletonList(CANADA)); - assertEquals(CANADA, this.resolver.resolveLocale(request(US, CANADA))); + assertThat(this.resolver.resolveLocale(request(US, CANADA))).isEqualTo(CANADA); } @Test public void resolvePreferredNotSupported() { this.resolver.setSupportedLocales(Collections.singletonList(CANADA)); - assertEquals(US, this.resolver.resolveLocale(request(US, UK))); + assertThat(this.resolver.resolveLocale(request(US, UK))).isEqualTo(US); } @Test public void resolvePreferredAgainstLanguageOnly() { this.resolver.setSupportedLocales(Collections.singletonList(ENGLISH)); - assertEquals(ENGLISH, this.resolver.resolveLocale(request(GERMANY, US, UK))); + assertThat(this.resolver.resolveLocale(request(GERMANY, US, UK))).isEqualTo(ENGLISH); } @Test public void resolvePreferredAgainstCountryIfPossible() { this.resolver.setSupportedLocales(Arrays.asList(ENGLISH, UK)); - assertEquals(UK, this.resolver.resolveLocale(request(GERMANY, US, UK))); + assertThat(this.resolver.resolveLocale(request(GERMANY, US, UK))).isEqualTo(UK); } @Test public void resolvePreferredAgainstLanguageWithMultipleSupportedLocales() { this.resolver.setSupportedLocales(Arrays.asList(GERMAN, US)); - assertEquals(GERMAN, this.resolver.resolveLocale(request(GERMANY, US, UK))); + assertThat(this.resolver.resolveLocale(request(GERMANY, US, UK))).isEqualTo(GERMAN); } @Test @@ -91,18 +91,18 @@ public class AcceptHeaderLocaleResolverTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Accept-Language", KOREA.toLanguageTag()); request.setPreferredLocales(Collections.singletonList(KOREA)); - assertEquals(Locale.JAPAN, this.resolver.resolveLocale(request)); + assertThat(this.resolver.resolveLocale(request)).isEqualTo(Locale.JAPAN); } @Test public void defaultLocale() { this.resolver.setDefaultLocale(JAPANESE); MockHttpServletRequest request = new MockHttpServletRequest(); - assertEquals(JAPANESE, this.resolver.resolveLocale(request)); + assertThat(this.resolver.resolveLocale(request)).isEqualTo(JAPANESE); request.addHeader("Accept-Language", US.toLanguageTag()); request.setPreferredLocales(Collections.singletonList(US)); - assertEquals(US, this.resolver.resolveLocale(request)); + assertThat(this.resolver.resolveLocale(request)).isEqualTo(US); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/CookieLocaleResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/CookieLocaleResolverTests.java index fe52f1a50d3..05c24283ded 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/CookieLocaleResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/CookieLocaleResolverTests.java @@ -31,12 +31,8 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.util.WebUtils; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Alef Arendsen @@ -54,7 +50,7 @@ public class CookieLocaleResolverTests { CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setCookieName("LanguageKoekje"); Locale loc = resolver.resolveLocale(request); - assertEquals("nl", loc.getLanguage()); + assertThat(loc.getLanguage()).isEqualTo("nl"); } @Test @@ -66,9 +62,10 @@ public class CookieLocaleResolverTests { CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setCookieName("LanguageKoekje"); LocaleContext loc = resolver.resolveLocaleContext(request); - assertEquals("nl", loc.getLocale().getLanguage()); - assertTrue(loc instanceof TimeZoneAwareLocaleContext); - assertNull(((TimeZoneAwareLocaleContext) loc).getTimeZone()); + assertThat(loc.getLocale().getLanguage()).isEqualTo("nl"); + boolean condition = loc instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isNull(); } @Test @@ -80,9 +77,10 @@ public class CookieLocaleResolverTests { CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setCookieName("LanguageKoekje"); LocaleContext loc = resolver.resolveLocaleContext(request); - assertEquals("nl", loc.getLocale().getLanguage()); - assertTrue(loc instanceof TimeZoneAwareLocaleContext); - assertEquals(TimeZone.getTimeZone("GMT+1"), ((TimeZoneAwareLocaleContext) loc).getTimeZone()); + assertThat(loc.getLocale().getLanguage()).isEqualTo("nl"); + boolean condition = loc instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); } @Test @@ -111,9 +109,10 @@ public class CookieLocaleResolverTests { resolver.setDefaultTimeZone(TimeZone.getTimeZone("GMT+2")); resolver.setCookieName("LanguageKoekje"); LocaleContext loc = resolver.resolveLocaleContext(request); - assertEquals(Locale.GERMAN, loc.getLocale()); - assertTrue(loc instanceof TimeZoneAwareLocaleContext); - assertEquals(TimeZone.getTimeZone("GMT+2"), ((TimeZoneAwareLocaleContext) loc).getTimeZone()); + assertThat(loc.getLocale()).isEqualTo(Locale.GERMAN); + boolean condition = loc instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2")); } @Test @@ -141,9 +140,10 @@ public class CookieLocaleResolverTests { resolver.setDefaultTimeZone(TimeZone.getTimeZone("GMT+2")); resolver.setCookieName("LanguageKoekje"); LocaleContext loc = resolver.resolveLocaleContext(request); - assertEquals("nl", loc.getLocale().getLanguage()); - assertTrue(loc instanceof TimeZoneAwareLocaleContext); - assertEquals(TimeZone.getTimeZone("GMT+2"), ((TimeZoneAwareLocaleContext) loc).getTimeZone()); + assertThat(loc.getLocale().getLanguage()).isEqualTo("nl"); + boolean condition = loc instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+2")); } @Test @@ -155,18 +155,18 @@ public class CookieLocaleResolverTests { resolver.setLocale(request, response, new Locale("nl", "")); Cookie cookie = response.getCookie(CookieLocaleResolver.DEFAULT_COOKIE_NAME); - assertNotNull(cookie); - assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_NAME, cookie.getName()); - assertEquals(null, cookie.getDomain()); - assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_PATH, cookie.getPath()); - assertFalse(cookie.getSecure()); + assertThat(cookie).isNotNull(); + assertThat(cookie.getName()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_NAME); + assertThat(cookie.getDomain()).isEqualTo(null); + assertThat(cookie.getPath()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_PATH); + assertThat(cookie.getSecure()).isFalse(); request = new MockHttpServletRequest(); request.setCookies(cookie); resolver = new CookieLocaleResolver(); Locale loc = resolver.resolveLocale(request); - assertEquals("nl", loc.getLanguage()); + assertThat(loc.getLanguage()).isEqualTo("nl"); } @Test @@ -183,9 +183,10 @@ public class CookieLocaleResolverTests { resolver = new CookieLocaleResolver(); LocaleContext loc = resolver.resolveLocaleContext(request); - assertEquals("nl", loc.getLocale().getLanguage()); - assertTrue(loc instanceof TimeZoneAwareLocaleContext); - assertNull(((TimeZoneAwareLocaleContext) loc).getTimeZone()); + assertThat(loc.getLocale().getLanguage()).isEqualTo("nl"); + boolean condition = loc instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isNull(); } @Test @@ -203,9 +204,10 @@ public class CookieLocaleResolverTests { resolver = new CookieLocaleResolver(); LocaleContext loc = resolver.resolveLocaleContext(request); - assertEquals("nl", loc.getLocale().getLanguage()); - assertTrue(loc instanceof TimeZoneAwareLocaleContext); - assertEquals(TimeZone.getTimeZone("GMT+1"), ((TimeZoneAwareLocaleContext) loc).getTimeZone()); + assertThat(loc.getLocale().getLanguage()).isEqualTo("nl"); + boolean condition = loc instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); } @Test @@ -224,9 +226,10 @@ public class CookieLocaleResolverTests { resolver = new CookieLocaleResolver(); LocaleContext loc = resolver.resolveLocaleContext(request); - assertEquals(Locale.GERMANY, loc.getLocale()); - assertTrue(loc instanceof TimeZoneAwareLocaleContext); - assertEquals(TimeZone.getTimeZone("GMT+1"), ((TimeZoneAwareLocaleContext) loc).getTimeZone()); + assertThat(loc.getLocale()).isEqualTo(Locale.GERMANY); + boolean condition = loc instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); } @Test @@ -238,20 +241,20 @@ public class CookieLocaleResolverTests { resolver.setLocale(request, response, new Locale("de", "AT")); Cookie cookie = response.getCookie(CookieLocaleResolver.DEFAULT_COOKIE_NAME); - assertNotNull(cookie); - assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_NAME, cookie.getName()); - assertEquals(null, cookie.getDomain()); - assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_PATH, cookie.getPath()); - assertFalse(cookie.getSecure()); - assertEquals("de-AT", cookie.getValue()); + assertThat(cookie).isNotNull(); + assertThat(cookie.getName()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_NAME); + assertThat(cookie.getDomain()).isEqualTo(null); + assertThat(cookie.getPath()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_PATH); + assertThat(cookie.getSecure()).isFalse(); + assertThat(cookie.getValue()).isEqualTo("de-AT"); request = new MockHttpServletRequest(); request.setCookies(cookie); resolver = new CookieLocaleResolver(); Locale loc = resolver.resolveLocale(request); - assertEquals("de", loc.getLanguage()); - assertEquals("AT", loc.getCountry()); + assertThat(loc.getLanguage()).isEqualTo("de"); + assertThat(loc.getCountry()).isEqualTo("AT"); } @Test @@ -264,20 +267,20 @@ public class CookieLocaleResolverTests { resolver.setLocale(request, response, new Locale("de", "AT")); Cookie cookie = response.getCookie(CookieLocaleResolver.DEFAULT_COOKIE_NAME); - assertNotNull(cookie); - assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_NAME, cookie.getName()); - assertEquals(null, cookie.getDomain()); - assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_PATH, cookie.getPath()); - assertFalse(cookie.getSecure()); - assertEquals("de_AT", cookie.getValue()); + assertThat(cookie).isNotNull(); + assertThat(cookie.getName()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_NAME); + assertThat(cookie.getDomain()).isEqualTo(null); + assertThat(cookie.getPath()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_PATH); + assertThat(cookie.getSecure()).isFalse(); + assertThat(cookie.getValue()).isEqualTo("de_AT"); request = new MockHttpServletRequest(); request.setCookies(cookie); resolver = new CookieLocaleResolver(); Locale loc = resolver.resolveLocale(request); - assertEquals("de", loc.getLanguage()); - assertEquals("AT", loc.getCountry()); + assertThat(loc.getLanguage()).isEqualTo("de"); + assertThat(loc.getCountry()).isEqualTo("AT"); } @Test @@ -294,12 +297,12 @@ public class CookieLocaleResolverTests { resolver.setLocale(request, response, new Locale("nl", "")); Cookie cookie = response.getCookie("LanguageKoek"); - assertNotNull(cookie); - assertEquals("LanguageKoek", cookie.getName()); - assertEquals(".springframework.org", cookie.getDomain()); - assertEquals("/mypath", cookie.getPath()); - assertEquals(10000, cookie.getMaxAge()); - assertTrue(cookie.getSecure()); + assertThat(cookie).isNotNull(); + assertThat(cookie.getName()).isEqualTo("LanguageKoek"); + assertThat(cookie.getDomain()).isEqualTo(".springframework.org"); + assertThat(cookie.getPath()).isEqualTo("/mypath"); + assertThat(cookie.getMaxAge()).isEqualTo(10000); + assertThat(cookie.getSecure()).isTrue(); request = new MockHttpServletRequest(); request.setCookies(cookie); @@ -307,7 +310,7 @@ public class CookieLocaleResolverTests { resolver = new CookieLocaleResolver(); resolver.setCookieName("LanguageKoek"); Locale loc = resolver.resolveLocale(request); - assertEquals("nl", loc.getLanguage()); + assertThat(loc.getLanguage()).isEqualTo("nl"); } @Test @@ -318,7 +321,7 @@ public class CookieLocaleResolverTests { CookieLocaleResolver resolver = new CookieLocaleResolver(); Locale loc = resolver.resolveLocale(request); - assertEquals(request.getLocale(), loc); + assertThat(loc).isEqualTo(request.getLocale()); } @Test @@ -329,9 +332,10 @@ public class CookieLocaleResolverTests { CookieLocaleResolver resolver = new CookieLocaleResolver(); LocaleContext loc = resolver.resolveLocaleContext(request); - assertEquals(request.getLocale(), loc.getLocale()); - assertTrue(loc instanceof TimeZoneAwareLocaleContext); - assertNull(((TimeZoneAwareLocaleContext) loc).getTimeZone()); + assertThat(loc.getLocale()).isEqualTo(request.getLocale()); + boolean condition = loc instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isNull(); } @Test @@ -343,7 +347,7 @@ public class CookieLocaleResolverTests { resolver.setDefaultLocale(Locale.GERMAN); Locale loc = resolver.resolveLocale(request); - assertEquals(Locale.GERMAN, loc); + assertThat(loc).isEqualTo(Locale.GERMAN); } @Test @@ -356,9 +360,10 @@ public class CookieLocaleResolverTests { resolver.setDefaultTimeZone(TimeZone.getTimeZone("GMT+1")); LocaleContext loc = resolver.resolveLocaleContext(request); - assertEquals(Locale.GERMAN, loc.getLocale()); - assertTrue(loc instanceof TimeZoneAwareLocaleContext); - assertEquals(TimeZone.getTimeZone("GMT+1"), ((TimeZoneAwareLocaleContext) loc).getTimeZone()); + assertThat(loc.getLocale()).isEqualTo(Locale.GERMAN); + boolean condition = loc instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isEqualTo(TimeZone.getTimeZone("GMT+1")); } @Test @@ -371,7 +376,7 @@ public class CookieLocaleResolverTests { CookieLocaleResolver resolver = new CookieLocaleResolver(); Locale loc = resolver.resolveLocale(request); - assertEquals(request.getLocale(), loc); + assertThat(loc).isEqualTo(request.getLocale()); } @Test @@ -384,9 +389,10 @@ public class CookieLocaleResolverTests { CookieLocaleResolver resolver = new CookieLocaleResolver(); LocaleContext loc = resolver.resolveLocaleContext(request); - assertEquals(request.getLocale(), loc.getLocale()); - assertTrue(loc instanceof TimeZoneAwareLocaleContext); - assertNull(((TimeZoneAwareLocaleContext) loc).getTimeZone()); + assertThat(loc.getLocale()).isEqualTo(request.getLocale()); + boolean condition = loc instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(((TimeZoneAwareLocaleContext) loc).getTimeZone()).isNull(); } @Test @@ -400,13 +406,13 @@ public class CookieLocaleResolverTests { CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setLocale(request, response, null); Locale locale = (Locale) request.getAttribute(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME); - assertEquals(Locale.TAIWAN, locale); + assertThat(locale).isEqualTo(Locale.TAIWAN); Cookie[] cookies = response.getCookies(); - assertEquals(1, cookies.length); + assertThat(cookies.length).isEqualTo(1); Cookie localeCookie = cookies[0]; - assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_NAME, localeCookie.getName()); - assertEquals("", localeCookie.getValue()); + assertThat(localeCookie.getName()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_NAME); + assertThat(localeCookie.getValue()).isEqualTo(""); } @Test @@ -420,15 +426,15 @@ public class CookieLocaleResolverTests { CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setLocaleContext(request, response, null); Locale locale = (Locale) request.getAttribute(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME); - assertEquals(Locale.TAIWAN, locale); + assertThat(locale).isEqualTo(Locale.TAIWAN); TimeZone timeZone = (TimeZone) request.getAttribute(CookieLocaleResolver.TIME_ZONE_REQUEST_ATTRIBUTE_NAME); - assertNull(timeZone); + assertThat(timeZone).isNull(); Cookie[] cookies = response.getCookies(); - assertEquals(1, cookies.length); + assertThat(cookies.length).isEqualTo(1); Cookie localeCookie = cookies[0]; - assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_NAME, localeCookie.getName()); - assertEquals("", localeCookie.getValue()); + assertThat(localeCookie.getName()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_NAME); + assertThat(localeCookie.getValue()).isEqualTo(""); } @Test @@ -443,13 +449,13 @@ public class CookieLocaleResolverTests { resolver.setDefaultLocale(Locale.CANADA_FRENCH); resolver.setLocale(request, response, null); Locale locale = (Locale) request.getAttribute(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME); - assertEquals(Locale.CANADA_FRENCH, locale); + assertThat(locale).isEqualTo(Locale.CANADA_FRENCH); Cookie[] cookies = response.getCookies(); - assertEquals(1, cookies.length); + assertThat(cookies.length).isEqualTo(1); Cookie localeCookie = cookies[0]; - assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_NAME, localeCookie.getName()); - assertEquals("", localeCookie.getValue()); + assertThat(localeCookie.getName()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_NAME); + assertThat(localeCookie.getValue()).isEqualTo(""); } @Test @@ -465,15 +471,15 @@ public class CookieLocaleResolverTests { resolver.setDefaultTimeZone(TimeZone.getTimeZone("GMT+1")); resolver.setLocaleContext(request, response, null); Locale locale = (Locale) request.getAttribute(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME); - assertEquals(Locale.CANADA_FRENCH, locale); + assertThat(locale).isEqualTo(Locale.CANADA_FRENCH); TimeZone timeZone = (TimeZone) request.getAttribute(CookieLocaleResolver.TIME_ZONE_REQUEST_ATTRIBUTE_NAME); - assertEquals(TimeZone.getTimeZone("GMT+1"), timeZone); + assertThat(timeZone).isEqualTo(TimeZone.getTimeZone("GMT+1")); Cookie[] cookies = response.getCookies(); - assertEquals(1, cookies.length); + assertThat(cookies.length).isEqualTo(1); Cookie localeCookie = cookies[0]; - assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_NAME, localeCookie.getName()); - assertEquals("", localeCookie.getValue()); + assertThat(localeCookie.getName()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_NAME); + assertThat(localeCookie.getValue()).isEqualTo(""); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/LocaleResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/LocaleResolverTests.java index b11da726934..76b5b3e5d71 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/LocaleResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/LocaleResolverTests.java @@ -32,10 +32,7 @@ import org.springframework.web.servlet.LocaleContextResolver; import org.springframework.web.servlet.LocaleResolver; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; /** * @author Juergen Hoeller @@ -72,14 +69,14 @@ public class LocaleResolverTests { // check original locale Locale locale = localeResolver.resolveLocale(request); - assertEquals(Locale.UK, locale); + assertThat(locale).isEqualTo(Locale.UK); // set new locale try { localeResolver.setLocale(request, response, Locale.GERMANY); assertThat(shouldSet).as("should not be able to set Locale").isTrue(); // check new locale locale = localeResolver.resolveLocale(request); - assertEquals(Locale.GERMANY, locale); + assertThat(locale).isEqualTo(Locale.GERMANY); } catch (UnsupportedOperationException ex) { assertThat(shouldSet).as("should be able to set Locale").isFalse(); @@ -90,17 +87,18 @@ public class LocaleResolverTests { LocaleContextResolver localeContextResolver = (LocaleContextResolver) localeResolver; LocaleContext localeContext = localeContextResolver.resolveLocaleContext(request); if (shouldSet) { - assertEquals(Locale.GERMANY, localeContext.getLocale()); + assertThat(localeContext.getLocale()).isEqualTo(Locale.GERMANY); } else { - assertEquals(Locale.UK, localeContext.getLocale()); + assertThat(localeContext.getLocale()).isEqualTo(Locale.UK); } - assertTrue(localeContext instanceof TimeZoneAwareLocaleContext); - assertNull(((TimeZoneAwareLocaleContext) localeContext).getTimeZone()); + boolean condition2 = localeContext instanceof TimeZoneAwareLocaleContext; + assertThat(condition2).isTrue(); + assertThat(((TimeZoneAwareLocaleContext) localeContext).getTimeZone()).isNull(); if (localeContextResolver instanceof AbstractLocaleContextResolver) { ((AbstractLocaleContextResolver) localeContextResolver).setDefaultTimeZone(TimeZone.getTimeZone("GMT+1")); - assertEquals(((TimeZoneAwareLocaleContext) localeContext).getTimeZone(), TimeZone.getTimeZone("GMT+1")); + assertThat(TimeZone.getTimeZone("GMT+1")).isEqualTo(((TimeZoneAwareLocaleContext) localeContext).getTimeZone()); } try { @@ -109,31 +107,33 @@ public class LocaleResolverTests { fail("should not be able to set Locale"); } localeContext = localeContextResolver.resolveLocaleContext(request); - assertEquals(Locale.US, localeContext.getLocale()); + assertThat(localeContext.getLocale()).isEqualTo(Locale.US); if (localeContextResolver instanceof AbstractLocaleContextResolver) { - assertEquals(((TimeZoneAwareLocaleContext) localeContext).getTimeZone(), TimeZone.getTimeZone("GMT+1")); + assertThat(TimeZone.getTimeZone("GMT+1")).isEqualTo(((TimeZoneAwareLocaleContext) localeContext).getTimeZone()); } else { - assertNull(((TimeZoneAwareLocaleContext) localeContext).getTimeZone()); + assertThat(((TimeZoneAwareLocaleContext) localeContext).getTimeZone()).isNull(); } localeContextResolver.setLocaleContext(request, response, new SimpleTimeZoneAwareLocaleContext(Locale.GERMANY, TimeZone.getTimeZone("GMT+2"))); localeContext = localeContextResolver.resolveLocaleContext(request); - assertEquals(Locale.GERMANY, localeContext.getLocale()); - assertTrue(localeContext instanceof TimeZoneAwareLocaleContext); - assertEquals(((TimeZoneAwareLocaleContext) localeContext).getTimeZone(), TimeZone.getTimeZone("GMT+2")); + assertThat(localeContext.getLocale()).isEqualTo(Locale.GERMANY); + boolean condition1 = localeContext instanceof TimeZoneAwareLocaleContext; + assertThat(condition1).isTrue(); + assertThat(TimeZone.getTimeZone("GMT+2")).isEqualTo(((TimeZoneAwareLocaleContext) localeContext).getTimeZone()); localeContextResolver.setLocaleContext(request, response, new SimpleTimeZoneAwareLocaleContext(null, TimeZone.getTimeZone("GMT+3"))); localeContext = localeContextResolver.resolveLocaleContext(request); - assertEquals(Locale.UK, localeContext.getLocale()); - assertTrue(localeContext instanceof TimeZoneAwareLocaleContext); - assertEquals(((TimeZoneAwareLocaleContext) localeContext).getTimeZone(), TimeZone.getTimeZone("GMT+3")); + assertThat(localeContext.getLocale()).isEqualTo(Locale.UK); + boolean condition = localeContext instanceof TimeZoneAwareLocaleContext; + assertThat(condition).isTrue(); + assertThat(TimeZone.getTimeZone("GMT+3")).isEqualTo(((TimeZoneAwareLocaleContext) localeContext).getTimeZone()); if (localeContextResolver instanceof AbstractLocaleContextResolver) { ((AbstractLocaleContextResolver) localeContextResolver).setDefaultLocale(Locale.GERMANY); - assertEquals(Locale.GERMANY, localeContext.getLocale()); + assertThat(localeContext.getLocale()).isEqualTo(Locale.GERMANY); } } catch (UnsupportedOperationException ex) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/SessionLocaleResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/SessionLocaleResolverTests.java index d488f65ecee..5ba4f812b0d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/SessionLocaleResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/SessionLocaleResolverTests.java @@ -24,8 +24,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -38,7 +37,7 @@ public class SessionLocaleResolverTests { request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, Locale.GERMAN); SessionLocaleResolver resolver = new SessionLocaleResolver(); - assertEquals(Locale.GERMAN, resolver.resolveLocale(request)); + assertThat(resolver.resolveLocale(request)).isEqualTo(Locale.GERMAN); } @Test @@ -48,14 +47,14 @@ public class SessionLocaleResolverTests { SessionLocaleResolver resolver = new SessionLocaleResolver(); resolver.setLocale(request, response, Locale.GERMAN); - assertEquals(Locale.GERMAN, resolver.resolveLocale(request)); + assertThat(resolver.resolveLocale(request)).isEqualTo(Locale.GERMAN); HttpSession session = request.getSession(); request = new MockHttpServletRequest(); request.setSession(session); resolver = new SessionLocaleResolver(); - assertEquals(Locale.GERMAN, resolver.resolveLocale(request)); + assertThat(resolver.resolveLocale(request)).isEqualTo(Locale.GERMAN); } @Test @@ -65,7 +64,7 @@ public class SessionLocaleResolverTests { SessionLocaleResolver resolver = new SessionLocaleResolver(); - assertEquals(request.getLocale(), resolver.resolveLocale(request)); + assertThat(resolver.resolveLocale(request)).isEqualTo(request.getLocale()); } @Test @@ -76,7 +75,7 @@ public class SessionLocaleResolverTests { SessionLocaleResolver resolver = new SessionLocaleResolver(); resolver.setDefaultLocale(Locale.GERMAN); - assertEquals(Locale.GERMAN, resolver.resolveLocale(request)); + assertThat(resolver.resolveLocale(request)).isEqualTo(Locale.GERMAN); } @Test @@ -89,14 +88,14 @@ public class SessionLocaleResolverTests { SessionLocaleResolver resolver = new SessionLocaleResolver(); resolver.setLocale(request, response, null); Locale locale = (Locale) request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME); - assertNull(locale); + assertThat(locale).isNull(); HttpSession session = request.getSession(); request = new MockHttpServletRequest(); request.addPreferredLocale(Locale.TAIWAN); request.setSession(session); resolver = new SessionLocaleResolver(); - assertEquals(Locale.TAIWAN, resolver.resolveLocale(request)); + assertThat(resolver.resolveLocale(request)).isEqualTo(Locale.TAIWAN); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java index a6f3408657b..3bbe45e16bc 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java @@ -34,11 +34,7 @@ import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.util.WebUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -56,9 +52,9 @@ public class ControllerTests { pvc.setViewName(viewName); // We don't care about the params. ModelAndView mv = pvc.handleRequest(new MockHttpServletRequest("GET", "foo.html"), new MockHttpServletResponse()); - assertTrue("model has no data", mv.getModel().size() == 0); - assertTrue("model has correct viewname", mv.getViewName().equals(viewName)); - assertTrue("getViewName matches", pvc.getViewName().equals(viewName)); + assertThat(mv.getModel().size() == 0).as("model has no data").isTrue(); + assertThat(mv.getViewName().equals(viewName)).as("model has correct viewname").isTrue(); + assertThat(pvc.getViewName().equals(viewName)).as("getViewName matches").isTrue(); } @Test @@ -102,7 +98,7 @@ public class ControllerTests { StaticWebApplicationContext sac = new StaticWebApplicationContext(); sac.setServletContext(context); sfc.setApplicationContext(sac); - assertNull(sfc.handleRequest(request, response)); + assertThat(sfc.handleRequest(request, response)).isNull(); if (include) { verify(dispatcher).include(request, response); @@ -125,19 +121,19 @@ public class ControllerTests { swc.setInitParameters(props); swc.afterPropertiesSet(); - assertNotNull(TestServlet.config); - assertEquals("action", TestServlet.config.getServletName()); - assertEquals("myValue", TestServlet.config.getInitParameter("config")); - assertNull(TestServlet.request); - assertFalse(TestServlet.destroyed); + assertThat(TestServlet.config).isNotNull(); + assertThat(TestServlet.config.getServletName()).isEqualTo("action"); + assertThat(TestServlet.config.getInitParameter("config")).isEqualTo("myValue"); + assertThat(TestServlet.request).isNull(); + assertThat(TestServlet.destroyed).isFalse(); - assertNull(swc.handleRequest(request, response)); - assertEquals(request, TestServlet.request); - assertEquals(response, TestServlet.response); - assertFalse(TestServlet.destroyed); + assertThat(swc.handleRequest(request, response)).isNull(); + assertThat(TestServlet.request).isEqualTo(request); + assertThat(TestServlet.response).isEqualTo(response); + assertThat(TestServlet.destroyed).isFalse(); swc.destroy(); - assertTrue(TestServlet.destroyed); + assertThat(TestServlet.destroyed).isTrue(); } @Test @@ -150,18 +146,18 @@ public class ControllerTests { swc.setBeanName("action"); swc.afterPropertiesSet(); - assertNotNull(TestServlet.config); - assertEquals("action", TestServlet.config.getServletName()); - assertNull(TestServlet.request); - assertFalse(TestServlet.destroyed); + assertThat(TestServlet.config).isNotNull(); + assertThat(TestServlet.config.getServletName()).isEqualTo("action"); + assertThat(TestServlet.request).isNull(); + assertThat(TestServlet.destroyed).isFalse(); - assertNull(swc.handleRequest(request, response)); - assertEquals(request, TestServlet.request); - assertEquals(response, TestServlet.response); - assertFalse(TestServlet.destroyed); + assertThat(swc.handleRequest(request, response)).isNull(); + assertThat(TestServlet.request).isEqualTo(request); + assertThat(TestServlet.response).isEqualTo(response); + assertThat(TestServlet.destroyed).isFalse(); swc.destroy(); - assertTrue(TestServlet.destroyed); + assertThat(TestServlet.destroyed).isTrue(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ParameterizableViewControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ParameterizableViewControllerTests.java index 1cd992c035a..ed9a984fed7 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ParameterizableViewControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ParameterizableViewControllerTests.java @@ -26,9 +26,7 @@ import org.springframework.ui.ModelMap; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.ModelAndView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with a ParameterizableViewController. @@ -53,23 +51,23 @@ public class ParameterizableViewControllerTests { String viewName = "testView"; this.controller.setViewName(viewName); ModelAndView mav = this.controller.handleRequest(this.request, new MockHttpServletResponse()); - assertEquals(viewName, mav.getViewName()); - assertTrue(mav.getModel().isEmpty()); + assertThat(mav.getViewName()).isEqualTo(viewName); + assertThat(mav.getModel().isEmpty()).isTrue(); } @Test public void handleRequestWithoutViewName() throws Exception { ModelAndView mav = this.controller.handleRequest(this.request, new MockHttpServletResponse()); - assertNull(mav.getViewName()); - assertTrue(mav.getModel().isEmpty()); + assertThat(mav.getViewName()).isNull(); + assertThat(mav.getModel().isEmpty()).isTrue(); } @Test public void handleRequestWithFlashAttributes() throws Exception { this.request.setAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE, new ModelMap("name", "value")); ModelAndView mav = this.controller.handleRequest(this.request, new MockHttpServletResponse()); - assertEquals(1, mav.getModel().size()); - assertEquals("value", mav.getModel().get("name")); + assertThat(mav.getModel().size()).isEqualTo(1); + assertThat(mav.getModel().get("name")).isEqualTo("value"); } @Test @@ -78,8 +76,8 @@ public class ParameterizableViewControllerTests { MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = this.controller.handleRequest(this.request, response); - assertNull(mav); - assertEquals("GET,HEAD,OPTIONS", response.getHeader("Allow")); + assertThat(mav).isNull(); + assertThat(response.getHeader("Allow")).isEqualTo("GET,HEAD,OPTIONS"); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/UrlFilenameViewControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/UrlFilenameViewControllerTests.java index 8787557fd9c..4fa13467517 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/UrlFilenameViewControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/UrlFilenameViewControllerTests.java @@ -27,9 +27,7 @@ import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.ModelAndView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -47,8 +45,8 @@ public class UrlFilenameViewControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("index", mv.getViewName()); - assertTrue(mv.getModel().isEmpty()); + assertThat(mv.getViewName()).isEqualTo("index"); + assertThat(mv.getModel().isEmpty()).isTrue(); } @Test @@ -57,8 +55,8 @@ public class UrlFilenameViewControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("index", mv.getViewName()); - assertTrue(mv.getModel().isEmpty()); + assertThat(mv.getViewName()).isEqualTo("index"); + assertThat(mv.getModel().isEmpty()).isTrue(); } @Test @@ -67,8 +65,8 @@ public class UrlFilenameViewControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index;a=A;b=B"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("index", mv.getViewName()); - assertTrue(mv.getModel().isEmpty()); + assertThat(mv.getViewName()).isEqualTo("index"); + assertThat(mv.getModel().isEmpty()).isTrue(); } @Test @@ -79,8 +77,8 @@ public class UrlFilenameViewControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("mypre_index_mysuf", mv.getViewName()); - assertTrue(mv.getModel().isEmpty()); + assertThat(mv.getViewName()).isEqualTo("mypre_index_mysuf"); + assertThat(mv.getModel().isEmpty()).isTrue(); } @Test @@ -90,8 +88,8 @@ public class UrlFilenameViewControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("mypre_index", mv.getViewName()); - assertTrue(mv.getModel().isEmpty()); + assertThat(mv.getViewName()).isEqualTo("mypre_index"); + assertThat(mv.getModel().isEmpty()).isTrue(); } @Test @@ -101,8 +99,8 @@ public class UrlFilenameViewControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("index_mysuf", mv.getViewName()); - assertTrue(mv.getModel().isEmpty()); + assertThat(mv.getViewName()).isEqualTo("index_mysuf"); + assertThat(mv.getModel().isEmpty()).isTrue(); } @Test @@ -111,8 +109,8 @@ public class UrlFilenameViewControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/docs/cvs/commit.html"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("docs/cvs/commit", mv.getViewName()); - assertTrue(mv.getModel().isEmpty()); + assertThat(mv.getViewName()).isEqualTo("docs/cvs/commit"); + assertThat(mv.getModel().isEmpty()).isTrue(); } @Test @@ -122,8 +120,8 @@ public class UrlFilenameViewControllerTests { exposePathInMapping(request, "/docs/**"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("cvs/commit", mv.getViewName()); - assertTrue(mv.getModel().isEmpty()); + assertThat(mv.getViewName()).isEqualTo("cvs/commit"); + assertThat(mv.getModel().isEmpty()).isTrue(); } @Test @@ -133,8 +131,8 @@ public class UrlFilenameViewControllerTests { exposePathInMapping(request, "/docs/cvs/commit.html"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("docs/cvs/commit", mv.getViewName()); - assertTrue(mv.getModel().isEmpty()); + assertThat(mv.getViewName()).isEqualTo("docs/cvs/commit"); + assertThat(mv.getModel().isEmpty()).isTrue(); } @Test @@ -144,24 +142,24 @@ public class UrlFilenameViewControllerTests { request.setContextPath("/myapp"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("docs/cvs/commit", mv.getViewName()); - assertTrue(mv.getModel().isEmpty()); + assertThat(mv.getViewName()).isEqualTo("docs/cvs/commit"); + assertThat(mv.getModel().isEmpty()).isTrue(); } @Test public void settingPrefixToNullCausesEmptyStringToBeUsed() throws Exception { UrlFilenameViewController ctrl = new UrlFilenameViewController(); ctrl.setPrefix(null); - assertNotNull("For setPrefix(..) with null, the empty string must be used instead.", ctrl.getPrefix()); - assertEquals("For setPrefix(..) with null, the empty string must be used instead.", "", ctrl.getPrefix()); + assertThat(ctrl.getPrefix()).as("For setPrefix(..) with null, the empty string must be used instead.").isNotNull(); + assertThat(ctrl.getPrefix()).as("For setPrefix(..) with null, the empty string must be used instead.").isEqualTo(""); } @Test public void settingSuffixToNullCausesEmptyStringToBeUsed() throws Exception { UrlFilenameViewController ctrl = new UrlFilenameViewController(); ctrl.setSuffix(null); - assertNotNull("For setPrefix(..) with null, the empty string must be used instead.", ctrl.getSuffix()); - assertEquals("For setPrefix(..) with null, the empty string must be used instead.", "", ctrl.getSuffix()); + assertThat(ctrl.getSuffix()).as("For setPrefix(..) with null, the empty string must be used instead.").isNotNull(); + assertThat(ctrl.getSuffix()).as("For setPrefix(..) with null, the empty string must be used instead.").isEqualTo(""); } /** @@ -174,8 +172,8 @@ public class UrlFilenameViewControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/products/view.html"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("products/view", mv.getViewName()); - assertTrue(mv.getModel().isEmpty()); + assertThat(mv.getViewName()).isEqualTo("products/view"); + assertThat(mv.getModel().isEmpty()).isTrue(); } @Test @@ -185,9 +183,9 @@ public class UrlFilenameViewControllerTests { request.setAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE, new ModelMap("name", "value")); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = ctrl.handleRequest(request, response); - assertEquals("index", mv.getViewName()); - assertEquals(1, mv.getModel().size()); - assertEquals("value", mv.getModel().get("name")); + assertThat(mv.getViewName()).isEqualTo("index"); + assertThat(mv.getModel().size()).isEqualTo(1); + assertThat(mv.getModel().get("name")).isEqualTo("value"); } private void exposePathInMapping(MockHttpServletRequest request, String mapping) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/CglibProxyControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/CglibProxyControllerTests.java index 0ad2f78b062..3ed572eece1 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/CglibProxyControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/CglibProxyControllerTests.java @@ -38,7 +38,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -56,7 +56,7 @@ public class CglibProxyControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); - assertEquals("doIt", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("doIt"); } @Test @@ -66,7 +66,7 @@ public class CglibProxyControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); - assertEquals("doIt", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("doIt"); } @Test @@ -76,7 +76,7 @@ public class CglibProxyControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/bookings"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); - assertEquals("doIt", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("doIt"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/JdkProxyControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/JdkProxyControllerTests.java index e95bd4f39b4..3e07e3d5837 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/JdkProxyControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/JdkProxyControllerTests.java @@ -36,7 +36,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -54,7 +54,7 @@ public class JdkProxyControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); - assertEquals("doIt", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("doIt"); } @Test @@ -64,7 +64,7 @@ public class JdkProxyControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); - assertEquals("doIt", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("doIt"); } @Test @@ -74,7 +74,7 @@ public class JdkProxyControllerTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/bookings"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); - assertEquals("doIt", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("doIt"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java index 1ee541d5826..a43edafde3b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java @@ -35,9 +35,7 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.servlet.ModelAndView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link ResponseStatusExceptionResolver}. @@ -93,7 +91,7 @@ public class ResponseStatusExceptionResolverTests { StatusCodeAndReasonMessageException ex = new StatusCodeAndReasonMessageException(); exceptionResolver.resolveException(request, response, null, ex); - assertEquals("Invalid status reason", "Gone reason message", response.getErrorMessage()); + assertThat(response.getErrorMessage()).as("Invalid status reason").isEqualTo("Gone reason message"); } finally { LocaleContextHolder.resetLocaleContext(); @@ -105,7 +103,7 @@ public class ResponseStatusExceptionResolverTests { Exception ex = new Exception(); exceptionResolver.resolveException(request, response, null, ex); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNull("ModelAndView returned", mav); + assertThat(mav).as("ModelAndView returned").isNull(); } @Test // SPR-12903 @@ -132,10 +130,10 @@ public class ResponseStatusExceptionResolverTests { private void assertResolved(ModelAndView mav, int status, String reason) { - assertTrue("No Empty ModelAndView returned", mav != null && mav.isEmpty()); - assertEquals(status, response.getStatus()); - assertEquals(reason, response.getErrorMessage()); - assertTrue(response.isCommitted()); + assertThat(mav != null && mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).isEqualTo(status); + assertThat(response.getErrorMessage()).isEqualTo(reason); + assertThat(response.isCommitted()).isTrue(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/CompositeRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/CompositeRequestConditionTests.java index 2dcb44940f9..75ba5843fd8 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/CompositeRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/CompositeRequestConditionTests.java @@ -24,10 +24,8 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.bind.annotation.RequestMethod; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * A test fixture for {@link CompositeRequestCondition} tests. @@ -61,7 +59,7 @@ public class CompositeRequestConditionTests { CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param2, this.header2); CompositeRequestCondition cond3 = new CompositeRequestCondition(this.param3, this.header3); - assertEquals(cond3, cond1.combine(cond2)); + assertThat(cond1.combine(cond2)).isEqualTo(cond3); } @Test @@ -69,9 +67,9 @@ public class CompositeRequestConditionTests { CompositeRequestCondition empty = new CompositeRequestCondition(); CompositeRequestCondition notEmpty = new CompositeRequestCondition(this.param1); - assertSame(empty, empty.combine(empty)); - assertSame(notEmpty, notEmpty.combine(empty)); - assertSame(notEmpty, empty.combine(notEmpty)); + assertThat(empty.combine(empty)).isSameAs(empty); + assertThat(notEmpty.combine(empty)).isSameAs(notEmpty); + assertThat(empty.combine(notEmpty)).isSameAs(notEmpty); } @Test @@ -94,7 +92,7 @@ public class CompositeRequestConditionTests { CompositeRequestCondition condition = new CompositeRequestCondition(this.param1, getPostCond); CompositeRequestCondition matchingCondition = new CompositeRequestCondition(this.param1, getCond); - assertEquals(matchingCondition, condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isEqualTo(matchingCondition); } @Test @@ -102,13 +100,13 @@ public class CompositeRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); CompositeRequestCondition cond = new CompositeRequestCondition(this.param1); - assertNull(cond.getMatchingCondition(request)); + assertThat(cond.getMatchingCondition(request)).isNull(); } @Test public void matchEmpty() { CompositeRequestCondition empty = new CompositeRequestCondition(); - assertSame(empty, empty.getMatchingCondition(new MockHttpServletRequest())); + assertThat(empty.getMatchingCondition(new MockHttpServletRequest())).isSameAs(empty); } @Test @@ -118,8 +116,8 @@ public class CompositeRequestConditionTests { CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1); CompositeRequestCondition cond3 = new CompositeRequestCondition(this.param3); - assertEquals(1, cond1.compareTo(cond3, request)); - assertEquals(-1, cond3.compareTo(cond1, request)); + assertThat(cond1.compareTo(cond3, request)).isEqualTo(1); + assertThat(cond3.compareTo(cond1, request)).isEqualTo(-1); } @Test @@ -129,9 +127,9 @@ public class CompositeRequestConditionTests { CompositeRequestCondition empty = new CompositeRequestCondition(); CompositeRequestCondition notEmpty = new CompositeRequestCondition(this.param1); - assertEquals(0, empty.compareTo(empty, request)); - assertEquals(-1, notEmpty.compareTo(empty, request)); - assertEquals(1, empty.compareTo(notEmpty, request)); + assertThat(empty.compareTo(empty, request)).isEqualTo(0); + assertThat(notEmpty.compareTo(empty, request)).isEqualTo(-1); + assertThat(empty.compareTo(notEmpty, request)).isEqualTo(1); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ConsumesRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ConsumesRequestConditionTests.java index f0fb3445b1c..cc95b380d58 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ConsumesRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ConsumesRequestConditionTests.java @@ -26,10 +26,6 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.servlet.mvc.condition.ConsumesRequestCondition.ConsumeMediaTypeExpression; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Arjen Poutsma @@ -43,7 +39,7 @@ public class ConsumesRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.setContentType("text/plain"); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test @@ -53,13 +49,13 @@ public class ConsumesRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.setContentType("text/plain"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test public void getConsumableMediaTypesNegatedExpression() { ConsumesRequestCondition condition = new ConsumesRequestCondition("!application/xml"); - assertEquals(Collections.emptySet(), condition.getConsumableMediaTypes()); + assertThat(condition.getConsumableMediaTypes()).isEqualTo(Collections.emptySet()); } @Test @@ -69,7 +65,7 @@ public class ConsumesRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.setContentType("text/plain"); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test @@ -79,7 +75,7 @@ public class ConsumesRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.setContentType("text/plain"); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test @@ -89,7 +85,7 @@ public class ConsumesRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.setContentType("application/xml"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test @@ -99,7 +95,7 @@ public class ConsumesRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.setContentType("01"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test @@ -109,7 +105,7 @@ public class ConsumesRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.setContentType("01"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test // gh-22010 @@ -118,19 +114,19 @@ public class ConsumesRequestConditionTests { condition.setBodyRequired(false); MockHttpServletRequest request = new MockHttpServletRequest(); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.CONTENT_LENGTH, "0"); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.CONTENT_LENGTH, "21"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.TRANSFER_ENCODING, "chunked"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test @@ -141,10 +137,10 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition("text/*"); int result = condition1.compareTo(condition2, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, request); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @Test @@ -155,10 +151,10 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition("text/*", "text/plain;q=0.7"); int result = condition1.compareTo(condition2, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, request); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @@ -168,7 +164,7 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition("application/xml"); ConsumesRequestCondition result = condition1.combine(condition2); - assertEquals(condition2, result); + assertThat(result).isEqualTo(condition2); } @Test @@ -177,7 +173,7 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition(); ConsumesRequestCondition result = condition1.combine(condition2); - assertEquals(condition1, result); + assertThat(result).isEqualTo(condition1); } @Test @@ -202,7 +198,7 @@ public class ConsumesRequestConditionTests { condition = new ConsumesRequestCondition("application/xml"); result = condition.getMatchingCondition(request); - assertNull(result); + assertThat(result).isNull(); } private void assertConditions(ConsumesRequestCondition condition, String... expected) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/HeadersRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/HeadersRequestConditionTests.java index 0ef04f94d71..a95e95adc52 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/HeadersRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/HeadersRequestConditionTests.java @@ -23,11 +23,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.servlet.mvc.condition.HeadersRequestCondition.HeaderExpression; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -36,11 +32,11 @@ public class HeadersRequestConditionTests { @Test public void headerEquals() { - assertEquals(new HeadersRequestCondition("foo"), new HeadersRequestCondition("foo")); - assertEquals(new HeadersRequestCondition("foo"), new HeadersRequestCondition("FOO")); - assertNotEquals(new HeadersRequestCondition("foo"), new HeadersRequestCondition("bar")); - assertEquals(new HeadersRequestCondition("foo=bar"), new HeadersRequestCondition("foo=bar")); - assertEquals(new HeadersRequestCondition("foo=bar"), new HeadersRequestCondition("FOO=bar")); + assertThat(new HeadersRequestCondition("foo")).isEqualTo(new HeadersRequestCondition("foo")); + assertThat(new HeadersRequestCondition("FOO")).isEqualTo(new HeadersRequestCondition("foo")); + assertThat(new HeadersRequestCondition("bar")).isNotEqualTo(new HeadersRequestCondition("foo")); + assertThat(new HeadersRequestCondition("foo=bar")).isEqualTo(new HeadersRequestCondition("foo=bar")); + assertThat(new HeadersRequestCondition("FOO=bar")).isEqualTo(new HeadersRequestCondition("foo=bar")); } @Test @@ -50,7 +46,7 @@ public class HeadersRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Accept", ""); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test @@ -60,7 +56,7 @@ public class HeadersRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("bar", ""); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test @@ -69,7 +65,7 @@ public class HeadersRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test @@ -79,7 +75,7 @@ public class HeadersRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("foo", "bar"); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test @@ -89,7 +85,7 @@ public class HeadersRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("foo", "bazz"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test @@ -99,7 +95,7 @@ public class HeadersRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("foo", "bar"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test @@ -108,7 +104,7 @@ public class HeadersRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("foo", "baz"); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test @@ -117,7 +113,7 @@ public class HeadersRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("foo", "bar"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test @@ -128,10 +124,10 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition2 = new HeadersRequestCondition("foo=a", "bar"); int result = condition1.compareTo(condition2, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, request); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @Test // SPR-16674 @@ -142,10 +138,10 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition2 = new HeadersRequestCondition("foo"); int result = condition1.compareTo(condition2, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, request); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @Test @@ -155,8 +151,7 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition1 = new HeadersRequestCondition("foo!=a"); HeadersRequestCondition condition2 = new HeadersRequestCondition("foo"); - assertEquals("Negated match should not count as more specific", - 0, condition1.compareTo(condition2, request)); + assertThat(condition1.compareTo(condition2, request)).as("Negated match should not count as more specific").isEqualTo(0); } @Test @@ -166,7 +161,7 @@ public class HeadersRequestConditionTests { HeadersRequestCondition result = condition1.combine(condition2); Collection conditions = result.getContent(); - assertEquals(2, conditions.size()); + assertThat(conditions.size()).isEqualTo(2); } @Test @@ -177,12 +172,12 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition = new HeadersRequestCondition("foo"); HeadersRequestCondition result = condition.getMatchingCondition(request); - assertEquals(condition, result); + assertThat(result).isEqualTo(condition); condition = new HeadersRequestCondition("bar"); result = condition.getMatchingCondition(request); - assertNull(result); + assertThat(result).isNull(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ParamsRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ParamsRequestConditionTests.java index 9588d935928..9a3aa980aaf 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ParamsRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ParamsRequestConditionTests.java @@ -23,11 +23,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.servlet.mvc.condition.ParamsRequestCondition.ParamExpression; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ParamsRequestCondition}. @@ -37,11 +33,11 @@ public class ParamsRequestConditionTests { @Test public void paramEquals() { - assertEquals(new ParamsRequestCondition("foo"), new ParamsRequestCondition("foo")); - assertFalse(new ParamsRequestCondition("foo").equals(new ParamsRequestCondition("bar"))); - assertFalse(new ParamsRequestCondition("foo").equals(new ParamsRequestCondition("FOO"))); - assertEquals(new ParamsRequestCondition("foo=bar"), new ParamsRequestCondition("foo=bar")); - assertFalse(new ParamsRequestCondition("foo=bar").equals(new ParamsRequestCondition("FOO=bar"))); + assertThat(new ParamsRequestCondition("foo")).isEqualTo(new ParamsRequestCondition("foo")); + assertThat(new ParamsRequestCondition("foo").equals(new ParamsRequestCondition("bar"))).isFalse(); + assertThat(new ParamsRequestCondition("foo").equals(new ParamsRequestCondition("FOO"))).isFalse(); + assertThat(new ParamsRequestCondition("foo=bar")).isEqualTo(new ParamsRequestCondition("foo=bar")); + assertThat(new ParamsRequestCondition("foo=bar").equals(new ParamsRequestCondition("FOO=bar"))).isFalse(); } @Test @@ -49,7 +45,7 @@ public class ParamsRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("foo", ""); - assertNotNull(new ParamsRequestCondition("foo").getMatchingCondition(request)); + assertThat(new ParamsRequestCondition("foo").getMatchingCondition(request)).isNotNull(); } @Test // SPR-15831 @@ -57,7 +53,7 @@ public class ParamsRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("foo", (String) null); - assertNotNull(new ParamsRequestCondition("foo").getMatchingCondition(request)); + assertThat(new ParamsRequestCondition("foo").getMatchingCondition(request)).isNotNull(); } @Test @@ -65,7 +61,7 @@ public class ParamsRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("bar", ""); - assertNull(new ParamsRequestCondition("foo").getMatchingCondition(request)); + assertThat(new ParamsRequestCondition("foo").getMatchingCondition(request)).isNull(); } @Test @@ -73,7 +69,7 @@ public class ParamsRequestConditionTests { ParamsRequestCondition condition = new ParamsRequestCondition("!foo"); MockHttpServletRequest request = new MockHttpServletRequest(); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test @@ -81,7 +77,7 @@ public class ParamsRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("foo", "bar"); - assertNotNull(new ParamsRequestCondition("foo=bar").getMatchingCondition(request)); + assertThat(new ParamsRequestCondition("foo=bar").getMatchingCondition(request)).isNotNull(); } @Test @@ -89,7 +85,7 @@ public class ParamsRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("foo", "bazz"); - assertNull(new ParamsRequestCondition("foo=bar").getMatchingCondition(request)); + assertThat(new ParamsRequestCondition("foo=bar").getMatchingCondition(request)).isNull(); } @Test @@ -100,10 +96,10 @@ public class ParamsRequestConditionTests { ParamsRequestCondition condition2 = new ParamsRequestCondition("foo=a", "bar"); int result = condition1.compareTo(condition2, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, request); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @Test // SPR-16674 @@ -114,7 +110,7 @@ public class ParamsRequestConditionTests { ParamsRequestCondition condition2 = new ParamsRequestCondition("response_type"); int result = condition1.compareTo(condition2, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); } @Test @@ -124,8 +120,7 @@ public class ParamsRequestConditionTests { ParamsRequestCondition condition1 = new ParamsRequestCondition("response_type!=code"); ParamsRequestCondition condition2 = new ParamsRequestCondition("response_type"); - assertEquals("Negated match should not count as more specific", - 0, condition1.compareTo(condition2, request)); + assertThat(condition1.compareTo(condition2, request)).as("Negated match should not count as more specific").isEqualTo(0); } @Test @@ -135,7 +130,7 @@ public class ParamsRequestConditionTests { ParamsRequestCondition result = condition1.combine(condition2); Collection conditions = result.getContent(); - assertEquals(2, conditions.size()); + assertThat(conditions.size()).isEqualTo(2); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PatternsRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PatternsRequestConditionTests.java index 7567173f8d8..b8b0937b08b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PatternsRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PatternsRequestConditionTests.java @@ -24,9 +24,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rossen Stoyanchev @@ -36,13 +34,13 @@ public class PatternsRequestConditionTests { @Test public void prependSlash() { PatternsRequestCondition c = new PatternsRequestCondition("foo"); - assertEquals("/foo", c.getPatterns().iterator().next()); + assertThat(c.getPatterns().iterator().next()).isEqualTo("/foo"); } @Test public void prependNonEmptyPatternsOnly() { PatternsRequestCondition c = new PatternsRequestCondition(""); - assertEquals("Do not prepend empty patterns (SPR-8255)", "", c.getPatterns().iterator().next()); + assertThat(c.getPatterns().iterator().next()).as("Do not prepend empty patterns (SPR-8255)").isEqualTo(""); } @Test @@ -50,7 +48,7 @@ public class PatternsRequestConditionTests { PatternsRequestCondition c1 = new PatternsRequestCondition(); PatternsRequestCondition c2 = new PatternsRequestCondition(); - assertEquals(new PatternsRequestCondition(""), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(new PatternsRequestCondition("")); } @Test @@ -58,12 +56,12 @@ public class PatternsRequestConditionTests { PatternsRequestCondition c1 = new PatternsRequestCondition("/type1", "/type2"); PatternsRequestCondition c2 = new PatternsRequestCondition(); - assertEquals(new PatternsRequestCondition("/type1", "/type2"), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(new PatternsRequestCondition("/type1", "/type2")); c1 = new PatternsRequestCondition(); c2 = new PatternsRequestCondition("/method1", "/method2"); - assertEquals(new PatternsRequestCondition("/method1", "/method2"), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(new PatternsRequestCondition("/method1", "/method2")); } @Test @@ -71,7 +69,7 @@ public class PatternsRequestConditionTests { PatternsRequestCondition c1 = new PatternsRequestCondition("/t1", "/t2"); PatternsRequestCondition c2 = new PatternsRequestCondition("/m1", "/m2"); - assertEquals(new PatternsRequestCondition("/t1/m1", "/t1/m2", "/t2/m1", "/t2/m2"), c1.combine(c2)); + assertThat(c1.combine(c2)).isEqualTo(new PatternsRequestCondition("/t1/m1", "/t1/m2", "/t2/m1", "/t2/m2")); } @Test @@ -79,7 +77,7 @@ public class PatternsRequestConditionTests { PatternsRequestCondition condition = new PatternsRequestCondition("/foo"); PatternsRequestCondition match = condition.getMatchingCondition(new MockHttpServletRequest("GET", "/foo")); - assertNotNull(match); + assertThat(match).isNotNull(); } @Test @@ -87,7 +85,7 @@ public class PatternsRequestConditionTests { PatternsRequestCondition condition = new PatternsRequestCondition("/foo/*"); PatternsRequestCondition match = condition.getMatchingCondition(new MockHttpServletRequest("GET", "/foo/bar")); - assertNotNull(match); + assertThat(match).isNotNull(); } @Test @@ -96,7 +94,7 @@ public class PatternsRequestConditionTests { PatternsRequestCondition match = condition.getMatchingCondition(new MockHttpServletRequest("GET", "/foo/bar")); PatternsRequestCondition expected = new PatternsRequestCondition("/foo/bar", "/foo/*", "/**"); - assertEquals(expected, match); + assertThat(match).isEqualTo(expected); } @Test @@ -106,15 +104,15 @@ public class PatternsRequestConditionTests { PatternsRequestCondition condition = new PatternsRequestCondition("/{foo}"); PatternsRequestCondition match = condition.getMatchingCondition(request); - assertNotNull(match); - assertEquals("/{foo}.*", match.getPatterns().iterator().next()); + assertThat(match).isNotNull(); + assertThat(match.getPatterns().iterator().next()).isEqualTo("/{foo}.*"); boolean useSuffixPatternMatch = false; condition = new PatternsRequestCondition(new String[] {"/{foo}"}, null, null, useSuffixPatternMatch, false); match = condition.getMatchingCondition(request); - assertNotNull(match); - assertEquals("/{foo}", match.getPatterns().iterator().next()); + assertThat(match).isNotNull(); + assertThat(match.getPatterns().iterator().next()).isEqualTo("/{foo}"); } @Test // SPR-8410 @@ -126,14 +124,14 @@ public class PatternsRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/jobs/my.job"); PatternsRequestCondition match = condition.getMatchingCondition(request); - assertNotNull(match); - assertEquals("/jobs/{jobName}", match.getPatterns().iterator().next()); + assertThat(match).isNotNull(); + assertThat(match.getPatterns().iterator().next()).isEqualTo("/jobs/{jobName}"); request = new MockHttpServletRequest("GET", "/jobs/my.job.json"); match = condition.getMatchingCondition(request); - assertNotNull(match); - assertEquals("/jobs/{jobName}.json", match.getPatterns().iterator().next()); + assertThat(match).isNotNull(); + assertThat(match.getPatterns().iterator().next()).isEqualTo("/jobs/{jobName}.json"); } @Test @@ -149,7 +147,7 @@ public class PatternsRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/prefix/suffix.json"); PatternsRequestCondition match = combined.getMatchingCondition(request); - assertNotNull(match); + assertThat(match).isNotNull(); } @Test @@ -159,20 +157,19 @@ public class PatternsRequestConditionTests { PatternsRequestCondition condition = new PatternsRequestCondition("/foo"); PatternsRequestCondition match = condition.getMatchingCondition(request); - assertNotNull(match); - assertEquals("Should match by default", "/foo/", match.getPatterns().iterator().next()); + assertThat(match).isNotNull(); + assertThat(match.getPatterns().iterator().next()).as("Should match by default").isEqualTo("/foo/"); condition = new PatternsRequestCondition(new String[] {"/foo"}, null, null, false, true); match = condition.getMatchingCondition(request); - assertNotNull(match); - assertEquals("Trailing slash should be insensitive to useSuffixPatternMatch settings (SPR-6164, SPR-5636)", - "/foo/", match.getPatterns().iterator().next()); + assertThat(match).isNotNull(); + assertThat(match.getPatterns().iterator().next()).as("Trailing slash should be insensitive to useSuffixPatternMatch settings (SPR-6164, SPR-5636)").isEqualTo("/foo/"); condition = new PatternsRequestCondition(new String[] {"/foo"}, null, null, false, false); match = condition.getMatchingCondition(request); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -180,20 +177,20 @@ public class PatternsRequestConditionTests { PatternsRequestCondition condition = new PatternsRequestCondition("/foo.jpg"); PatternsRequestCondition match = condition.getMatchingCondition(new MockHttpServletRequest("GET", "/foo.html")); - assertNull(match); + assertThat(match).isNull(); } @Test // gh-22543 public void matchWithEmptyPatterns() { PatternsRequestCondition condition = new PatternsRequestCondition(); - assertEquals(new PatternsRequestCondition(""), condition); - assertNotNull(condition.getMatchingCondition(new MockHttpServletRequest("GET", ""))); - assertNull(condition.getMatchingCondition(new MockHttpServletRequest("GET", "/anything"))); + assertThat(condition).isEqualTo(new PatternsRequestCondition("")); + assertThat(condition.getMatchingCondition(new MockHttpServletRequest("GET", ""))).isNotNull(); + assertThat(condition.getMatchingCondition(new MockHttpServletRequest("GET", "/anything"))).isNull(); condition = condition.combine(new PatternsRequestCondition()); - assertEquals(new PatternsRequestCondition(""), condition); - assertNotNull(condition.getMatchingCondition(new MockHttpServletRequest("GET", ""))); - assertNull(condition.getMatchingCondition(new MockHttpServletRequest("GET", "/anything"))); + assertThat(condition).isEqualTo(new PatternsRequestCondition("")); + assertThat(condition.getMatchingCondition(new MockHttpServletRequest("GET", ""))).isNotNull(); + assertThat(condition.getMatchingCondition(new MockHttpServletRequest("GET", "/anything"))).isNull(); } @Test @@ -201,7 +198,7 @@ public class PatternsRequestConditionTests { PatternsRequestCondition c1 = new PatternsRequestCondition("/foo*"); PatternsRequestCondition c2 = new PatternsRequestCondition("/foo*"); - assertEquals(0, c1.compareTo(c2, new MockHttpServletRequest("GET", "/foo"))); + assertThat(c1.compareTo(c2, new MockHttpServletRequest("GET", "/foo"))).isEqualTo(0); } @Test @@ -209,7 +206,7 @@ public class PatternsRequestConditionTests { PatternsRequestCondition c1 = new PatternsRequestCondition("/fo*"); PatternsRequestCondition c2 = new PatternsRequestCondition("/foo"); - assertEquals(1, c1.compareTo(c2, new MockHttpServletRequest("GET", "/foo"))); + assertThat(c1.compareTo(c2, new MockHttpServletRequest("GET", "/foo"))).isEqualTo(1); } @Test @@ -222,7 +219,7 @@ public class PatternsRequestConditionTests { PatternsRequestCondition match1 = c1.getMatchingCondition(request); PatternsRequestCondition match2 = c2.getMatchingCondition(request); - assertEquals(1, match1.compareTo(match2, request)); + assertThat(match1.compareTo(match2, request)).isEqualTo(1); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ProducesRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ProducesRequestConditionTests.java index 805e46cfdc3..2d9e12e78d0 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ProducesRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ProducesRequestConditionTests.java @@ -31,10 +31,6 @@ import org.springframework.web.accept.HeaderContentNegotiationStrategy; import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition.ProduceMediaTypeExpression; import static org.assertj.core.api.Assertions.assertThat; -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 ProducesRequestCondition}. @@ -49,7 +45,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition = new ProducesRequestCondition("text/plain"); HttpServletRequest request = createRequest("text/plain"); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test @@ -57,21 +53,21 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition = new ProducesRequestCondition("!text/plain"); HttpServletRequest request = createRequest("text/plain"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test public void matchNegatedWithoutAcceptHeader() { ProducesRequestCondition condition = new ProducesRequestCondition("!text/plain"); - assertNotNull(condition.getMatchingCondition(new MockHttpServletRequest())); - assertEquals(Collections.emptySet(), condition.getProducibleMediaTypes()); + assertThat(condition.getMatchingCondition(new MockHttpServletRequest())).isNotNull(); + assertThat(condition.getProducibleMediaTypes()).isEqualTo(Collections.emptySet()); } @Test public void getProducibleMediaTypes() { ProducesRequestCondition condition = new ProducesRequestCondition("!application/xml"); - assertEquals(Collections.emptySet(), condition.getProducibleMediaTypes()); + assertThat(condition.getProducibleMediaTypes()).isEqualTo(Collections.emptySet()); } @Test @@ -79,7 +75,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition = new ProducesRequestCondition("text/*"); HttpServletRequest request = createRequest("text/plain"); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test @@ -87,7 +83,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition = new ProducesRequestCondition("text/plain", "application/xml"); HttpServletRequest request = createRequest("text/plain"); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test @@ -95,7 +91,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition = new ProducesRequestCondition("text/plain"); HttpServletRequest request = createRequest("application/xml"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test // gh-21670 @@ -103,23 +99,19 @@ public class ProducesRequestConditionTests { String base = "application/atom+xml"; ProducesRequestCondition condition = new ProducesRequestCondition(base + ";type=feed"); HttpServletRequest request = createRequest(base + ";type=entry"); - assertNull("Declared parameter value must match if present in request", - condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).as("Declared parameter value must match if present in request").isNull(); condition = new ProducesRequestCondition(base + ";type=feed"); request = createRequest(base + ";type=feed"); - assertNotNull("Declared parameter value must match if present in request", - condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).as("Declared parameter value must match if present in request").isNotNull(); condition = new ProducesRequestCondition(base + ";type=feed"); request = createRequest(base); - assertNotNull("Declared parameter has no impact if not present in request", - condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).as("Declared parameter has no impact if not present in request").isNotNull(); condition = new ProducesRequestCondition(base); request = createRequest(base + ";type=feed"); - assertNotNull("No impact from other parameters in request", - condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).as("No impact from other parameters in request").isNotNull(); } @Test @@ -127,7 +119,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition = new ProducesRequestCondition("text/plain"); HttpServletRequest request = createRequest("bogus"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test @@ -135,7 +127,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition = new ProducesRequestCondition("!text/plain"); HttpServletRequest request = createRequest("bogus"); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } @Test @@ -145,7 +137,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition = new ProducesRequestCondition(produces, headers); HttpServletRequest request = new MockHttpServletRequest("GET", "/foo.txt"); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test // SPR-17550 @@ -154,7 +146,7 @@ public class ProducesRequestConditionTests { HttpServletRequest request = createRequest( "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } @Test // gh-22853 @@ -172,7 +164,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition noneMatch = none.getMatchingCondition(request); ProducesRequestCondition htmlMatch = html.getMatchingCondition(request); - assertEquals(1, noneMatch.compareTo(htmlMatch, request)); + assertThat(noneMatch.compareTo(htmlMatch, request)).isEqualTo(1); } @Test @@ -183,28 +175,28 @@ public class ProducesRequestConditionTests { HttpServletRequest request = createRequest("application/xml, text/html"); - assertTrue(html.compareTo(xml, request) > 0); - assertTrue(xml.compareTo(html, request) < 0); - assertTrue(xml.compareTo(none, request) < 0); - assertTrue(none.compareTo(xml, request) > 0); - assertTrue(html.compareTo(none, request) < 0); - assertTrue(none.compareTo(html, request) > 0); + assertThat(html.compareTo(xml, request) > 0).isTrue(); + assertThat(xml.compareTo(html, request) < 0).isTrue(); + assertThat(xml.compareTo(none, request) < 0).isTrue(); + assertThat(none.compareTo(xml, request) > 0).isTrue(); + assertThat(html.compareTo(none, request) < 0).isTrue(); + assertThat(none.compareTo(html, request) > 0).isTrue(); request = createRequest("application/xml, text/*"); - assertTrue(html.compareTo(xml, request) > 0); - assertTrue(xml.compareTo(html, request) < 0); + assertThat(html.compareTo(xml, request) > 0).isTrue(); + assertThat(xml.compareTo(html, request) < 0).isTrue(); request = createRequest("application/pdf"); - assertEquals(0, html.compareTo(xml, request)); - assertEquals(0, xml.compareTo(html, request)); + assertThat(html.compareTo(xml, request)).isEqualTo(0); + assertThat(xml.compareTo(html, request)).isEqualTo(0); // See SPR-7000 request = createRequest("text/html;q=0.9,application/xml"); - assertTrue(html.compareTo(xml, request) > 0); - assertTrue(xml.compareTo(html, request) < 0); + assertThat(html.compareTo(xml, request) > 0).isTrue(); + assertThat(xml.compareTo(html, request) < 0).isTrue(); } @Test @@ -215,10 +207,10 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition("text/*"); int result = condition1.compareTo(condition2, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, request); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @Test @@ -229,10 +221,10 @@ public class ProducesRequestConditionTests { HttpServletRequest request = createRequest("text/plain"); int result = condition1.compareTo(condition2, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, request); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); } @Test @@ -243,18 +235,18 @@ public class ProducesRequestConditionTests { HttpServletRequest request = createRequest("text/plain", "application/xml"); int result = condition1.compareTo(condition2, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, request); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); request = createRequest("application/xml", "text/plain"); result = condition1.compareTo(condition2, request); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); result = condition2.compareTo(condition1, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); } // SPR-8536 @@ -266,30 +258,28 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition1 = new ProducesRequestCondition(); ProducesRequestCondition condition2 = new ProducesRequestCondition("application/json"); - assertTrue("Should have picked '*/*' condition as an exact match", - condition1.compareTo(condition2, request) < 0); - assertTrue("Should have picked '*/*' condition as an exact match", - condition2.compareTo(condition1, request) > 0); + assertThat(condition1.compareTo(condition2, request) < 0).as("Should have picked '*/*' condition as an exact match").isTrue(); + assertThat(condition2.compareTo(condition1, request) > 0).as("Should have picked '*/*' condition as an exact match").isTrue(); condition1 = new ProducesRequestCondition("*/*"); condition2 = new ProducesRequestCondition("application/json"); - assertTrue(condition1.compareTo(condition2, request) < 0); - assertTrue(condition2.compareTo(condition1, request) > 0); + assertThat(condition1.compareTo(condition2, request) < 0).isTrue(); + assertThat(condition2.compareTo(condition1, request) > 0).isTrue(); request.addHeader("Accept", "*/*"); condition1 = new ProducesRequestCondition(); condition2 = new ProducesRequestCondition("application/json"); - assertTrue(condition1.compareTo(condition2, request) < 0); - assertTrue(condition2.compareTo(condition1, request) > 0); + assertThat(condition1.compareTo(condition2, request) < 0).isTrue(); + assertThat(condition2.compareTo(condition1, request) > 0).isTrue(); condition1 = new ProducesRequestCondition("*/*"); condition2 = new ProducesRequestCondition("application/json"); - assertTrue(condition1.compareTo(condition2, request) < 0); - assertTrue(condition2.compareTo(condition1, request) > 0); + assertThat(condition1.compareTo(condition2, request) < 0).isTrue(); + assertThat(condition2.compareTo(condition1, request) > 0).isTrue(); } // SPR-9021 @@ -301,8 +291,8 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition1 = new ProducesRequestCondition(); ProducesRequestCondition condition2 = new ProducesRequestCondition("application/json"); - assertTrue(condition1.compareTo(condition2, request) < 0); - assertTrue(condition2.compareTo(condition1, request) > 0); + assertThat(condition1.compareTo(condition2, request) < 0).isTrue(); + assertThat(condition2.compareTo(condition1, request) > 0).isTrue(); } @Test @@ -313,10 +303,10 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition("text/xhtml"); int result = condition1.compareTo(condition2, request); - assertTrue("Should have used MediaType.equals(Object) to break the match", result < 0); + assertThat(result < 0).as("Should have used MediaType.equals(Object) to break the match").isTrue(); result = condition2.compareTo(condition1, request); - assertTrue("Should have used MediaType.equals(Object) to break the match", result > 0); + assertThat(result > 0).as("Should have used MediaType.equals(Object) to break the match").isTrue(); } @Test @@ -325,7 +315,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition("application/xml"); ProducesRequestCondition result = condition1.combine(condition2); - assertEquals(condition2, result); + assertThat(result).isEqualTo(condition2); } @Test @@ -334,7 +324,7 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition(); ProducesRequestCondition result = condition1.combine(condition2); - assertEquals(condition1, result); + assertThat(result).isEqualTo(condition1); } @Test @@ -358,7 +348,7 @@ public class ProducesRequestConditionTests { condition = new ProducesRequestCondition("application/xml"); result = condition.getMatchingCondition(request); - assertNull(result); + assertThat(result).isNull(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestConditionHolderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestConditionHolderTests.java index 567d3c95ed1..2604a216c86 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestConditionHolderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestConditionHolderTests.java @@ -23,10 +23,8 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.bind.annotation.RequestMethod; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; /** * A test fixture for {@link RequestConditionHolder} tests. @@ -41,7 +39,7 @@ public class RequestConditionHolderTests { RequestConditionHolder params2 = new RequestConditionHolder(new ParamsRequestCondition("name2")); RequestConditionHolder expected = new RequestConditionHolder(new ParamsRequestCondition("name1", "name2")); - assertEquals(expected, params1.combine(params2)); + assertThat(params1.combine(params2)).isEqualTo(expected); } @Test @@ -49,9 +47,9 @@ public class RequestConditionHolderTests { RequestConditionHolder empty = new RequestConditionHolder(null); RequestConditionHolder notEmpty = new RequestConditionHolder(new ParamsRequestCondition("name")); - assertSame(empty, empty.combine(empty)); - assertSame(notEmpty, notEmpty.combine(empty)); - assertSame(notEmpty, empty.combine(notEmpty)); + assertThat(empty.combine(empty)).isSameAs(empty); + assertThat(notEmpty.combine(empty)).isSameAs(notEmpty); + assertThat(empty.combine(notEmpty)).isSameAs(notEmpty); } @Test @@ -71,7 +69,7 @@ public class RequestConditionHolderTests { RequestConditionHolder custom = new RequestConditionHolder(rm); RequestMethodsRequestCondition expected = new RequestMethodsRequestCondition(RequestMethod.GET); - assertEquals(expected, custom.getMatchingCondition(request).getCondition()); + assertThat(custom.getMatchingCondition(request).getCondition()).isEqualTo(expected); } @Test @@ -81,13 +79,13 @@ public class RequestConditionHolderTests { RequestMethodsRequestCondition rm = new RequestMethodsRequestCondition(RequestMethod.POST); RequestConditionHolder custom = new RequestConditionHolder(rm); - assertNull(custom.getMatchingCondition(request)); + assertThat(custom.getMatchingCondition(request)).isNull(); } @Test public void matchEmpty() { RequestConditionHolder empty = new RequestConditionHolder(null); - assertSame(empty, empty.getMatchingCondition(new MockHttpServletRequest())); + assertThat(empty.getMatchingCondition(new MockHttpServletRequest())).isSameAs(empty); } @Test @@ -97,8 +95,8 @@ public class RequestConditionHolderTests { RequestConditionHolder params11 = new RequestConditionHolder(new ParamsRequestCondition("1")); RequestConditionHolder params12 = new RequestConditionHolder(new ParamsRequestCondition("1", "2")); - assertEquals(1, params11.compareTo(params12, request)); - assertEquals(-1, params12.compareTo(params11, request)); + assertThat(params11.compareTo(params12, request)).isEqualTo(1); + assertThat(params12.compareTo(params11, request)).isEqualTo(-1); } @Test @@ -109,9 +107,9 @@ public class RequestConditionHolderTests { RequestConditionHolder empty2 = new RequestConditionHolder(null); RequestConditionHolder notEmpty = new RequestConditionHolder(new ParamsRequestCondition("name")); - assertEquals(0, empty.compareTo(empty2, request)); - assertEquals(-1, notEmpty.compareTo(empty, request)); - assertEquals(1, empty.compareTo(notEmpty, request)); + assertThat(empty.compareTo(empty2, request)).isEqualTo(0); + assertThat(notEmpty.compareTo(empty, request)).isEqualTo(-1); + assertThat(empty.compareTo(notEmpty, request)).isEqualTo(1); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestMethodsRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestMethodsRequestConditionTests.java index f21928a2a9c..1e431e7a6cf 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestMethodsRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/RequestMethodsRequestConditionTests.java @@ -26,11 +26,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.bind.annotation.RequestMethod; -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.assertj.core.api.Assertions.assertThat; import static org.springframework.web.bind.annotation.RequestMethod.DELETE; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.HEAD; @@ -64,7 +60,7 @@ public class RequestMethodsRequestConditionTests { for (RequestMethod method : RequestMethod.values()) { if (method != OPTIONS) { HttpServletRequest request = new MockHttpServletRequest(method.name(), ""); - assertNotNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNotNull(); } } testNoMatch(condition, OPTIONS); @@ -73,8 +69,8 @@ public class RequestMethodsRequestConditionTests { @Test public void getMatchingConditionWithCustomMethod() { HttpServletRequest request = new MockHttpServletRequest("PROPFIND", ""); - assertNotNull(new RequestMethodsRequestCondition().getMatchingCondition(request)); - assertNull(new RequestMethodsRequestCondition(GET, POST).getMatchingCondition(request)); + assertThat(new RequestMethodsRequestCondition().getMatchingCondition(request)).isNotNull(); + assertThat(new RequestMethodsRequestCondition(GET, POST).getMatchingCondition(request)).isNull(); } @Test @@ -83,9 +79,9 @@ public class RequestMethodsRequestConditionTests { request.addHeader("Origin", "https://example.com"); request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PUT"); - assertNotNull(new RequestMethodsRequestCondition().getMatchingCondition(request)); - assertNotNull(new RequestMethodsRequestCondition(PUT).getMatchingCondition(request)); - assertNull(new RequestMethodsRequestCondition(DELETE).getMatchingCondition(request)); + assertThat(new RequestMethodsRequestCondition().getMatchingCondition(request)).isNotNull(); + assertThat(new RequestMethodsRequestCondition(PUT).getMatchingCondition(request)).isNotNull(); + assertThat(new RequestMethodsRequestCondition(DELETE).getMatchingCondition(request)).isNull(); } @Test // SPR-14410 @@ -96,8 +92,8 @@ public class RequestMethodsRequestConditionTests { RequestMethodsRequestCondition condition = new RequestMethodsRequestCondition(); RequestMethodsRequestCondition result = condition.getMatchingCondition(request); - assertNotNull(result); - assertSame(condition, result); + assertThat(result).isNotNull(); + assertThat(result).isSameAs(condition); } @Test @@ -109,16 +105,16 @@ public class RequestMethodsRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); int result = c1.compareTo(c2, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = c2.compareTo(c1, request); - assertTrue("Invalid comparison result: " + result, result > 0); + assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); result = c2.compareTo(c3, request); - assertTrue("Invalid comparison result: " + result, result < 0); + assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); result = c1.compareTo(c1, request); - assertEquals("Invalid comparison result ", 0, result); + assertThat(result).as("Invalid comparison result ").isEqualTo(0); } @Test @@ -127,20 +123,20 @@ public class RequestMethodsRequestConditionTests { RequestMethodsRequestCondition condition2 = new RequestMethodsRequestCondition(POST); RequestMethodsRequestCondition result = condition1.combine(condition2); - assertEquals(2, result.getContent().size()); + assertThat(result.getContent().size()).isEqualTo(2); } private void testMatch(RequestMethodsRequestCondition condition, RequestMethod method) { MockHttpServletRequest request = new MockHttpServletRequest(method.name(), ""); RequestMethodsRequestCondition actual = condition.getMatchingCondition(request); - assertNotNull(actual); - assertEquals(Collections.singleton(method), actual.getContent()); + assertThat(actual).isNotNull(); + assertThat(actual.getContent()).isEqualTo(Collections.singleton(method)); } private void testNoMatch(RequestMethodsRequestCondition condition, RequestMethod method) { MockHttpServletRequest request = new MockHttpServletRequest(method.name(), ""); - assertNull(condition.getMatchingCondition(request)); + assertThat(condition.getMatchingCondition(request)).isNull(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java index a7a3ec892b7..ef0c30feefd 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java @@ -60,10 +60,6 @@ import org.springframework.web.util.UrlPathHelper; import static org.assertj.core.api.Assertions.assertThat; 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; /** * Test fixture with {@link RequestMappingInfoHandlerMapping}. @@ -105,7 +101,7 @@ public class RequestMappingInfoHandlerMappingTests { RequestMappingInfo info = RequestMappingInfo.paths(patterns).build(); Set actual = this.handlerMapping.getMappingPathPatterns(info); - assertEquals(new HashSet<>(Arrays.asList(patterns)), actual); + assertThat(actual).isEqualTo(new HashSet<>(Arrays.asList(patterns))); } @Test @@ -113,14 +109,14 @@ public class RequestMappingInfoHandlerMappingTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); HandlerMethod handlerMethod = getHandler(request); - assertEquals(this.fooMethod.getMethod(), handlerMethod.getMethod()); + assertThat(handlerMethod.getMethod()).isEqualTo(this.fooMethod.getMethod()); } @Test public void getHandlerGlobMatch() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bar"); HandlerMethod handlerMethod = getHandler(request); - assertEquals(this.barMethod.getMethod(), handlerMethod.getMethod()); + assertThat(handlerMethod.getMethod()).isEqualTo(this.barMethod.getMethod()); } @Test @@ -128,12 +124,12 @@ public class RequestMappingInfoHandlerMappingTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); HandlerMethod handlerMethod = getHandler(request); - assertEquals(this.emptyMethod.getMethod(), handlerMethod.getMethod()); + assertThat(handlerMethod.getMethod()).isEqualTo(this.emptyMethod.getMethod()); request = new MockHttpServletRequest("GET", "/"); handlerMethod = getHandler(request); - assertEquals(this.emptyMethod.getMethod(), handlerMethod.getMethod()); + assertThat(handlerMethod.getMethod()).isEqualTo(this.emptyMethod.getMethod()); } @Test @@ -142,7 +138,7 @@ public class RequestMappingInfoHandlerMappingTests { request.setParameter("p", "anything"); HandlerMethod handlerMethod = getHandler(request); - assertEquals(this.fooParamMethod.getMethod(), handlerMethod.getMethod()); + assertThat(handlerMethod.getMethod()).isEqualTo(this.fooParamMethod.getMethod()); } @Test @@ -209,13 +205,13 @@ public class RequestMappingInfoHandlerMappingTests { this.handlerMapping.getHandler(request); String name = HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE; - assertEquals(Collections.singleton(MediaType.APPLICATION_XML), request.getAttribute(name)); + assertThat(request.getAttribute(name)).isEqualTo(Collections.singleton(MediaType.APPLICATION_XML)); request = new MockHttpServletRequest("GET", "/content"); request.addHeader("Accept", "application/json"); this.handlerMapping.getHandler(request); - assertNull("Negated expression shouldn't be listed as producible type", request.getAttribute(name)); + assertThat(request.getAttribute(name)).as("Negated expression shouldn't be listed as producible type").isNull(); } @Test @@ -230,12 +226,12 @@ public class RequestMappingInfoHandlerMappingTests { mapping.setApplicationContext(new StaticWebApplicationContext()); HandlerExecutionChain chain = mapping.getHandler(new MockHttpServletRequest("GET", path)); - assertNotNull(chain); - assertNotNull(chain.getInterceptors()); - assertSame(interceptor, chain.getInterceptors()[0]); + assertThat(chain).isNotNull(); + assertThat(chain.getInterceptors()).isNotNull(); + assertThat(chain.getInterceptors()[0]).isSameAs(interceptor); chain = mapping.getHandler(new MockHttpServletRequest("GET", "/invalid")); - assertNull(chain); + assertThat(chain).isNull(); } @SuppressWarnings("unchecked") @@ -249,9 +245,9 @@ public class RequestMappingInfoHandlerMappingTests { String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE; Map uriVariables = (Map) request.getAttribute(name); - assertNotNull(uriVariables); - assertEquals("1", uriVariables.get("path1")); - assertEquals("2", uriVariables.get("path2")); + assertThat(uriVariables).isNotNull(); + assertThat(uriVariables.get("path1")).isEqualTo("1"); + assertThat(uriVariables.get("path2")).isEqualTo("2"); } @SuppressWarnings("unchecked") @@ -270,9 +266,9 @@ public class RequestMappingInfoHandlerMappingTests { String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE; Map uriVariables = (Map) request.getAttribute(name); - assertNotNull(uriVariables); - assertEquals("group", uriVariables.get("group")); - assertEquals("a/b", uriVariables.get("identifier")); + assertThat(uriVariables).isNotNull(); + assertThat(uriVariables.get("group")).isEqualTo("group"); + assertThat(uriVariables.get("identifier")).isEqualTo("a/b"); } @Test @@ -281,7 +277,7 @@ public class RequestMappingInfoHandlerMappingTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/1/2"); this.handlerMapping.handleMatch(key, "/1/2", request); - assertEquals("/{path1}/2", request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)); + assertThat(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)).isEqualTo("/{path1}/2"); } @Test // gh-22543 @@ -289,7 +285,7 @@ public class RequestMappingInfoHandlerMappingTests { String path = ""; MockHttpServletRequest request = new MockHttpServletRequest("GET", path); this.handlerMapping.handleMatch(RequestMappingInfo.paths().build(), path, request); - assertEquals(path, request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)); + assertThat(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)).isEqualTo(path); } @Test @@ -305,10 +301,10 @@ public class RequestMappingInfoHandlerMappingTests { matrixVariables = getMatrixVariables(request, "cars"); uriVariables = getUriTemplateVariables(request); - assertNotNull(matrixVariables); - assertEquals(Arrays.asList("red", "blue", "green"), matrixVariables.get("colors")); - assertEquals("2012", matrixVariables.getFirst("year")); - assertEquals("cars", uriVariables.get("cars")); + assertThat(matrixVariables).isNotNull(); + assertThat(matrixVariables.get("colors")).isEqualTo(Arrays.asList("red", "blue", "green")); + assertThat(matrixVariables.getFirst("year")).isEqualTo("2012"); + assertThat(uriVariables.get("cars")).isEqualTo("cars"); // URI var with regex for path variable, and URI var for matrix params.. request = new MockHttpServletRequest(); @@ -317,11 +313,11 @@ public class RequestMappingInfoHandlerMappingTests { matrixVariables = getMatrixVariables(request, "params"); uriVariables = getUriTemplateVariables(request); - assertNotNull(matrixVariables); - assertEquals(Arrays.asList("red", "blue", "green"), matrixVariables.get("colors")); - assertEquals("2012", matrixVariables.getFirst("year")); - assertEquals("cars", uriVariables.get("cars")); - assertEquals(";colors=red,blue,green;year=2012", uriVariables.get("params")); + assertThat(matrixVariables).isNotNull(); + assertThat(matrixVariables.get("colors")).isEqualTo(Arrays.asList("red", "blue", "green")); + assertThat(matrixVariables.getFirst("year")).isEqualTo("2012"); + assertThat(uriVariables.get("cars")).isEqualTo("cars"); + assertThat(uriVariables.get("params")).isEqualTo(";colors=red,blue,green;year=2012"); // URI var with regex for path variable, and (empty) URI var for matrix params.. request = new MockHttpServletRequest(); @@ -330,9 +326,9 @@ public class RequestMappingInfoHandlerMappingTests { matrixVariables = getMatrixVariables(request, "params"); uriVariables = getUriTemplateVariables(request); - assertNull(matrixVariables); - assertEquals("cars", uriVariables.get("cars")); - assertEquals("", uriVariables.get("params")); + assertThat(matrixVariables).isNull(); + assertThat(uriVariables.get("cars")).isEqualTo("cars"); + assertThat(uriVariables.get("params")).isEqualTo(""); // SPR-11897 request = new MockHttpServletRequest(); @@ -341,11 +337,11 @@ public class RequestMappingInfoHandlerMappingTests { matrixVariables = getMatrixVariables(request, "foo"); uriVariables = getUriTemplateVariables(request); - assertNotNull(matrixVariables); - assertEquals(2, matrixVariables.size()); - assertEquals("42", matrixVariables.getFirst("a")); - assertEquals("c", matrixVariables.getFirst("b")); - assertEquals("a=42", uriVariables.get("foo")); + assertThat(matrixVariables).isNotNull(); + assertThat(matrixVariables.size()).isEqualTo(2); + assertThat(matrixVariables.getFirst("a")).isEqualTo("42"); + assertThat(matrixVariables.getFirst("b")).isEqualTo("c"); + assertThat(uriVariables.get("foo")).isEqualTo("a=42"); } @Test // SPR-10140, SPR-16867 @@ -365,15 +361,15 @@ public class RequestMappingInfoHandlerMappingTests { MultiValueMap matrixVariables = getMatrixVariables(request, "cars"); Map uriVariables = getUriTemplateVariables(request); - assertNotNull(matrixVariables); - assertEquals(Collections.singletonList("a/b"), matrixVariables.get("mvar")); - assertEquals("cars", uriVariables.get("cars")); + assertThat(matrixVariables).isNotNull(); + assertThat(matrixVariables.get("mvar")).isEqualTo(Collections.singletonList("a/b")); + assertThat(uriVariables.get("cars")).isEqualTo("cars"); } private HandlerMethod getHandler(MockHttpServletRequest request) throws Exception { HandlerExecutionChain chain = this.handlerMapping.getHandler(request); - assertNotNull(chain); + assertThat(chain).isNotNull(); return (HandlerMethod) chain.getHandler(); } @@ -393,9 +389,9 @@ public class RequestMappingInfoHandlerMappingTests { ModelAndViewContainer mavContainer = new ModelAndViewContainer(); Object result = new InvocableHandlerMethod(handlerMethod).invokeForRequest(webRequest, mavContainer); - assertNotNull(result); - assertEquals(HttpHeaders.class, result.getClass()); - assertEquals(allowHeader, ((HttpHeaders) result).getFirst("Allow")); + assertThat(result).isNotNull(); + assertThat(result.getClass()).isEqualTo(HttpHeaders.class); + assertThat(((HttpHeaders) result).getFirst("Allow")).isEqualTo(allowHeader); } private void testHttpMediaTypeNotAcceptableException(String url) throws Exception { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMethodMappingNamingStrategyTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMethodMappingNamingStrategyTests.java index 8ef8288e125..8d361bd5edf 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMethodMappingNamingStrategyTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMethodMappingNamingStrategyTests.java @@ -25,7 +25,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for @@ -45,7 +45,7 @@ public class RequestMappingInfoHandlerMethodMappingNamingStrategyTests { HandlerMethodMappingNamingStrategy strategy = new RequestMappingInfoHandlerMethodMappingNamingStrategy(); - assertEquals("foo", strategy.getName(handlerMethod, rmi)); + assertThat(strategy.getName(handlerMethod, rmi)).isEqualTo("foo"); } @Test @@ -58,7 +58,7 @@ public class RequestMappingInfoHandlerMethodMappingNamingStrategyTests { HandlerMethodMappingNamingStrategy strategy = new RequestMappingInfoHandlerMethodMappingNamingStrategy(); - assertEquals("TC#handle", strategy.getName(handlerMethod, rmi)); + assertThat(strategy.getName(handlerMethod, rmi)).isEqualTo("TC#handle"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoTests.java index 79dfc83c34c..1777ebc2b2b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoTests.java @@ -28,11 +28,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.bind.annotation.RequestMethod; import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.HEAD; import static org.springframework.web.servlet.mvc.method.RequestMappingInfo.paths; @@ -49,13 +45,14 @@ public class RequestMappingInfoTests { public void createEmpty() { RequestMappingInfo info = paths().build(); - assertEquals(Collections.singleton(""), info.getPatternsCondition().getPatterns()); // gh-22543 - assertEquals(0, info.getMethodsCondition().getMethods().size()); - assertEquals(true, info.getConsumesCondition().isEmpty()); - assertEquals(true, info.getProducesCondition().isEmpty()); - assertNotNull(info.getParamsCondition()); - assertNotNull(info.getHeadersCondition()); - assertNull(info.getCustomCondition()); + // gh-22543 + assertThat(info.getPatternsCondition().getPatterns()).isEqualTo(Collections.singleton("")); + assertThat(info.getMethodsCondition().getMethods().size()).isEqualTo(0); + assertThat(info.getConsumesCondition().isEmpty()).isEqualTo(true); + assertThat(info.getProducesCondition().isEmpty()).isEqualTo(true); + assertThat(info.getParamsCondition()).isNotNull(); + assertThat(info.getHeadersCondition()).isNotNull(); + assertThat(info.getCustomCondition()).isNull(); } @Test @@ -65,12 +62,12 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo*", "/bar").build(); RequestMappingInfo expected = paths("/foo*").build(); - assertEquals(expected, info.getMatchingCondition(request)); + assertThat(info.getMatchingCondition(request)).isEqualTo(expected); info = paths("/**", "/foo*", "/foo").build(); expected = paths("/foo", "/foo*", "/**").build(); - assertEquals(expected, info.getMatchingCondition(request)); + assertThat(info.getMatchingCondition(request)).isEqualTo(expected); } @Test @@ -81,12 +78,12 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").params("foo=bar").build(); RequestMappingInfo match = info.getMatchingCondition(request); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").params("foo!=bar").build(); match = info.getMatchingCondition(request); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -97,12 +94,12 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").headers("foo=bar").build(); RequestMappingInfo match = info.getMatchingCondition(request); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").headers("foo!=bar").build(); match = info.getMatchingCondition(request); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -113,12 +110,12 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").consumes("text/plain").build(); RequestMappingInfo match = info.getMatchingCondition(request); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").consumes("application/xml").build(); match = info.getMatchingCondition(request); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -129,12 +126,12 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").produces("text/plain").build(); RequestMappingInfo match = info.getMatchingCondition(request); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").produces("application/xml").build(); match = info.getMatchingCondition(request); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -145,12 +142,12 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").params("foo=bar").build(); RequestMappingInfo match = info.getMatchingCondition(request); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").params("foo!=bar").params("foo!=bar").build(); match = info.getMatchingCondition(request); - assertNull(match); + assertThat(match).isNull(); } @Test @@ -166,9 +163,9 @@ public class RequestMappingInfoTests { Collections.shuffle(list); Collections.sort(list, comparator); - assertEquals(oneMethodOneParam, list.get(0)); - assertEquals(oneMethod, list.get(1)); - assertEquals(noMethods, list.get(2)); + assertThat(list.get(0)).isEqualTo(oneMethodOneParam); + assertThat(list.get(1)).isEqualTo(oneMethod); + assertThat(list.get(2)).isEqualTo(noMethods); } @Test // SPR-14383 @@ -187,9 +184,9 @@ public class RequestMappingInfoTests { Collections.shuffle(list); Collections.sort(list, comparator); - assertEquals(headMethod, list.get(0)); - assertEquals(getMethod, list.get(1)); - assertEquals(noMethods, list.get(2)); + assertThat(list.get(0)).isEqualTo(headMethod); + assertThat(list.get(1)).isEqualTo(getMethod); + assertThat(list.get(2)).isEqualTo(noMethods); } @Test @@ -204,64 +201,64 @@ public class RequestMappingInfoTests { .consumes("text/plain").produces("text/plain") .build(); - assertEquals(info1, info2); - assertEquals(info1.hashCode(), info2.hashCode()); + assertThat(info2).isEqualTo(info1); + assertThat(info2.hashCode()).isEqualTo(info1.hashCode()); info2 = paths("/foo", "/NOOOOOO").methods(GET) .params("foo=bar", "customFoo=customBar").headers("foo=bar") .consumes("text/plain").produces("text/plain") .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(GET, RequestMethod.POST) .params("foo=bar", "customFoo=customBar").headers("foo=bar") .consumes("text/plain").produces("text/plain") .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(GET) .params("/NOOOOOO", "customFoo=customBar").headers("foo=bar") .consumes("text/plain").produces("text/plain") .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(GET) .params("foo=bar", "customFoo=customBar").headers("/NOOOOOO") .consumes("text/plain").produces("text/plain") .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(GET) .params("foo=bar", "customFoo=customBar").headers("foo=bar") .consumes("text/NOOOOOO").produces("text/plain") .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(GET) .params("foo=bar", "customFoo=customBar").headers("foo=bar") .consumes("text/plain").produces("text/NOOOOOO") .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); info2 = paths("/foo").methods(GET) .params("foo=bar", "customFoo=NOOOOOO").headers("foo=bar") .consumes("text/plain").produces("text/plain") .build(); - assertFalse(info1.equals(info2)); - assertNotEquals(info1.hashCode(), info2.hashCode()); + assertThat(info1.equals(info2)).isFalse(); + assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode()); } @Test @@ -272,11 +269,11 @@ public class RequestMappingInfoTests { RequestMappingInfo info = paths("/foo").methods(RequestMethod.POST).build(); RequestMappingInfo match = info.getMatchingCondition(request); - assertNotNull(match); + assertThat(match).isNotNull(); info = paths("/foo").methods(RequestMethod.OPTIONS).build(); match = info.getMatchingCondition(request); - assertNull("Pre-flight should match the ACCESS_CONTROL_REQUEST_METHOD", match); + assertThat(match).as("Pre-flight should match the ACCESS_CONTROL_REQUEST_METHOD").isNull(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractRequestAttributesArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractRequestAttributesArgumentResolverTests.java index 6ab478484ae..e74fb5a2b45 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractRequestAttributesArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractRequestAttributesArgumentResolverTests.java @@ -41,13 +41,8 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -89,8 +84,8 @@ public abstract class AbstractRequestAttributesArgumentResolverTests { @Test public void supportsParameter() throws Exception { - assertTrue(this.resolver.supportsParameter(new MethodParameter(this.handleMethod, 0))); - assertFalse(this.resolver.supportsParameter(new MethodParameter(this.handleMethod, -1))); + assertThat(this.resolver.supportsParameter(new MethodParameter(this.handleMethod, 0))).isTrue(); + assertThat(this.resolver.supportsParameter(new MethodParameter(this.handleMethod, -1))).isFalse(); } @Test @@ -102,7 +97,7 @@ public abstract class AbstractRequestAttributesArgumentResolverTests { Foo foo = new Foo(); this.webRequest.setAttribute("foo", foo, getScope()); - assertSame(foo, testResolveArgument(param)); + assertThat(testResolveArgument(param)).isSameAs(foo); } @Test @@ -110,17 +105,17 @@ public abstract class AbstractRequestAttributesArgumentResolverTests { MethodParameter param = initMethodParameter(1); Foo foo = new Foo(); this.webRequest.setAttribute("specialFoo", foo, getScope()); - assertSame(foo, testResolveArgument(param)); + assertThat(testResolveArgument(param)).isSameAs(foo); } @Test public void resolveNotRequired() throws Exception { MethodParameter param = initMethodParameter(2); - assertNull(testResolveArgument(param)); + assertThat(testResolveArgument(param)).isNull(); Foo foo = new Foo(); this.webRequest.setAttribute("foo", foo, getScope()); - assertSame(foo, testResolveArgument(param)); + assertThat(testResolveArgument(param)).isSameAs(foo); } @Test @@ -132,18 +127,18 @@ public abstract class AbstractRequestAttributesArgumentResolverTests { MethodParameter param = initMethodParameter(3); Object actual = testResolveArgument(param, factory); - assertNotNull(actual); - assertEquals(Optional.class, actual.getClass()); - assertFalse(((Optional) actual).isPresent()); + assertThat(actual).isNotNull(); + assertThat(actual.getClass()).isEqualTo(Optional.class); + assertThat(((Optional) actual).isPresent()).isFalse(); Foo foo = new Foo(); this.webRequest.setAttribute("foo", foo, getScope()); actual = testResolveArgument(param, factory); - assertNotNull(actual); - assertEquals(Optional.class, actual.getClass()); - assertTrue(((Optional) actual).isPresent()); - assertSame(foo, ((Optional) actual).get()); + assertThat(actual).isNotNull(); + assertThat(actual.getClass()).isEqualTo(Optional.class); + assertThat(((Optional) actual).isPresent()).isTrue(); + assertThat(((Optional) actual).get()).isSameAs(foo); } private Object testResolveArgument(MethodParameter param) throws Exception { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractServletHandlerMethodTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractServletHandlerMethodTests.java index e6f6f1aee55..296bed50127 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractServletHandlerMethodTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/AbstractServletHandlerMethodTests.java @@ -30,7 +30,7 @@ import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver; import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Base class for tests using on the DispatcherServlet and HandlerMethod infrastructure classes: @@ -48,7 +48,7 @@ public abstract class AbstractServletHandlerMethodTests { protected DispatcherServlet getServlet() { - assertNotNull("DispatcherServlet not initialized", servlet); + assertThat(servlet).as("DispatcherServlet not initialized").isNotNull(); return servlet; } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/CrossOriginTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/CrossOriginTests.java index 3858199dccf..3a49cefe99d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/CrossOriginTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/CrossOriginTests.java @@ -53,13 +53,8 @@ import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition; import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * Test fixture for {@link CrossOrigin @CrossOrigin} annotated methods. @@ -98,7 +93,7 @@ public class CrossOriginTests { this.handlerMapping.registerHandler(new MethodLevelController()); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/no"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); - assertNull(getCorsConfiguration(chain, false)); + assertThat(getCorsConfiguration(chain, false)).isNull(); } @Test // SPR-12931 @@ -106,7 +101,7 @@ public class CrossOriginTests { this.handlerMapping.registerHandler(new MethodLevelController()); this.request.setRequestURI("/no"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); - assertNull(getCorsConfiguration(chain, false)); + assertThat(getCorsConfiguration(chain, false)).isNull(); } @Test // SPR-12931 @@ -115,7 +110,7 @@ public class CrossOriginTests { this.request.setMethod("POST"); this.request.setRequestURI("/no"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); - assertNull(getCorsConfiguration(chain, false)); + assertThat(getCorsConfiguration(chain, false)).isNull(); } @Test @@ -124,13 +119,13 @@ public class CrossOriginTests { this.request.setRequestURI("/default"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, false); - assertNotNull(config); - assertArrayEquals(new String[] {"GET"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray()); - assertNull(config.getAllowCredentials()); - assertArrayEquals(new String[] {"*"}, config.getAllowedHeaders().toArray()); - assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders())); - assertEquals(new Long(1800), config.getMaxAge()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] {"GET"}); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] {"*"}); + assertThat(config.getAllowCredentials()).isNull(); + assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[] {"*"}); + assertThat(CollectionUtils.isEmpty(config.getExposedHeaders())).isTrue(); + assertThat(config.getMaxAge()).isEqualTo(new Long(1800)); } @Test @@ -139,13 +134,13 @@ public class CrossOriginTests { this.request.setRequestURI("/customized"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, false); - assertNotNull(config); - assertArrayEquals(new String[] {"DELETE"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[] {"https://site1.com", "https://site2.com"}, config.getAllowedOrigins().toArray()); - assertArrayEquals(new String[] {"header1", "header2"}, config.getAllowedHeaders().toArray()); - assertArrayEquals(new String[] {"header3", "header4"}, config.getExposedHeaders().toArray()); - assertEquals(new Long(123), config.getMaxAge()); - assertFalse(config.getAllowCredentials()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] {"DELETE"}); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] {"https://site1.com", "https://site2.com"}); + assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[] {"header1", "header2"}); + assertThat(config.getExposedHeaders().toArray()).isEqualTo(new String[] {"header3", "header4"}); + assertThat(config.getMaxAge()).isEqualTo(new Long(123)); + assertThat((boolean) config.getAllowCredentials()).isFalse(); } @Test @@ -154,9 +149,9 @@ public class CrossOriginTests { this.request.setRequestURI("/customOrigin"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, false); - assertNotNull(config); - assertEquals(Arrays.asList("https://example.com"), config.getAllowedOrigins()); - assertNull(config.getAllowCredentials()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("https://example.com")); + assertThat(config.getAllowCredentials()).isNull(); } @Test @@ -165,9 +160,9 @@ public class CrossOriginTests { this.request.setRequestURI("/someOrigin"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, false); - assertNotNull(config); - assertEquals(Arrays.asList("https://example.com"), config.getAllowedOrigins()); - assertNull(config.getAllowCredentials()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("https://example.com")); + assertThat(config.getAllowCredentials()).isNull(); } @Test @@ -185,26 +180,26 @@ public class CrossOriginTests { this.request.setRequestURI("/foo"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, false); - assertNotNull(config); - assertArrayEquals(new String[] {"GET"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray()); - assertFalse(config.getAllowCredentials()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] {"GET"}); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] {"*"}); + assertThat((boolean) config.getAllowCredentials()).isFalse(); this.request.setRequestURI("/bar"); chain = this.handlerMapping.getHandler(request); config = getCorsConfiguration(chain, false); - assertNotNull(config); - assertArrayEquals(new String[] {"GET"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray()); - assertFalse(config.getAllowCredentials()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] {"GET"}); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] {"*"}); + assertThat((boolean) config.getAllowCredentials()).isFalse(); this.request.setRequestURI("/baz"); chain = this.handlerMapping.getHandler(request); config = getCorsConfiguration(chain, false); - assertNotNull(config); - assertArrayEquals(new String[] {"GET"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray()); - assertTrue(config.getAllowCredentials()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] {"GET"}); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] {"*"}); + assertThat((boolean) config.getAllowCredentials()).isTrue(); } @Test // SPR-13468 @@ -214,10 +209,10 @@ public class CrossOriginTests { this.request.setRequestURI("/foo"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, false); - assertNotNull(config); - assertArrayEquals(new String[] {"GET"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[] {"http://www.foo.com/"}, config.getAllowedOrigins().toArray()); - assertTrue(config.getAllowCredentials()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] {"GET"}); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] {"http://www.foo.com/"}); + assertThat((boolean) config.getAllowCredentials()).isTrue(); } @Test // SPR-13468 @@ -227,10 +222,10 @@ public class CrossOriginTests { this.request.setRequestURI("/foo"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, false); - assertNotNull(config); - assertArrayEquals(new String[] {"GET"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[] {"http://www.foo.com/"}, config.getAllowedOrigins().toArray()); - assertTrue(config.getAllowCredentials()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] {"GET"}); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] {"http://www.foo.com/"}); + assertThat((boolean) config.getAllowCredentials()).isTrue(); } @Test @@ -241,13 +236,13 @@ public class CrossOriginTests { this.request.setRequestURI("/default"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, true); - assertNotNull(config); - assertArrayEquals(new String[] {"GET"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray()); - assertNull(config.getAllowCredentials()); - assertArrayEquals(new String[] {"*"}, config.getAllowedHeaders().toArray()); - assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders())); - assertEquals(new Long(1800), config.getMaxAge()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] {"GET"}); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] {"*"}); + assertThat(config.getAllowCredentials()).isNull(); + assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[] {"*"}); + assertThat(CollectionUtils.isEmpty(config.getExposedHeaders())).isTrue(); + assertThat(config.getMaxAge()).isEqualTo(new Long(1800)); } @Test @@ -259,13 +254,13 @@ public class CrossOriginTests { this.request.setRequestURI("/ambiguous-header"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, true); - assertNotNull(config); - assertArrayEquals(new String[] {"*"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray()); - assertArrayEquals(new String[] {"*"}, config.getAllowedHeaders().toArray()); - assertTrue(config.getAllowCredentials()); - assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders())); - assertNull(config.getMaxAge()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] {"*"}); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] {"*"}); + assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[] {"*"}); + assertThat((boolean) config.getAllowCredentials()).isTrue(); + assertThat(CollectionUtils.isEmpty(config.getExposedHeaders())).isTrue(); + assertThat(config.getMaxAge()).isNull(); } @Test @@ -276,27 +271,27 @@ public class CrossOriginTests { this.request.setRequestURI("/ambiguous-produces"); HandlerExecutionChain chain = this.handlerMapping.getHandler(request); CorsConfiguration config = getCorsConfiguration(chain, true); - assertNotNull(config); - assertArrayEquals(new String[] {"*"}, config.getAllowedMethods().toArray()); - assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray()); - assertArrayEquals(new String[] {"*"}, config.getAllowedHeaders().toArray()); - assertTrue(config.getAllowCredentials()); - assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders())); - assertNull(config.getMaxAge()); + assertThat(config).isNotNull(); + assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] {"*"}); + assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] {"*"}); + assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[] {"*"}); + assertThat((boolean) config.getAllowCredentials()).isTrue(); + assertThat(CollectionUtils.isEmpty(config.getExposedHeaders())).isTrue(); + assertThat(config.getMaxAge()).isNull(); } @Test public void preFlightRequestWithoutRequestMethodHeader() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/default"); request.addHeader(HttpHeaders.ORIGIN, "https://domain2.com"); - assertNull(this.handlerMapping.getHandler(request)); + assertThat(this.handlerMapping.getHandler(request)).isNull(); } private CorsConfiguration getCorsConfiguration(HandlerExecutionChain chain, boolean isPreFlightRequest) { if (isPreFlightRequest) { Object handler = chain.getHandler(); - assertTrue(handler.getClass().getSimpleName().equals("PreFlightHandler")); + assertThat(handler.getClass().getSimpleName().equals("PreFlightHandler")).isTrue(); DirectFieldAccessor accessor = new DirectFieldAccessor(handler); return (CorsConfiguration)accessor.getPropertyValue("config"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/DeferredResultReturnValueHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/DeferredResultReturnValueHandlerTests.java index e48f4912f2b..3284ab52eec 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/DeferredResultReturnValueHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/DeferredResultReturnValueHandlerTests.java @@ -34,9 +34,7 @@ import org.springframework.web.context.request.async.StandardServletAsyncWebRequ import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.method.support.ModelAndViewContainer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.method.ResolvableMethod.on; /** @@ -68,19 +66,19 @@ public class DeferredResultReturnValueHandlerTests { @Test public void supportsReturnType() throws Exception { - assertTrue(this.handler.supportsReturnType( - on(TestController.class).resolveReturnType(DeferredResult.class, String.class))); + assertThat(this.handler.supportsReturnType( + on(TestController.class).resolveReturnType(DeferredResult.class, String.class))).isTrue(); - assertTrue(this.handler.supportsReturnType( - on(TestController.class).resolveReturnType(ListenableFuture.class, String.class))); + assertThat(this.handler.supportsReturnType( + on(TestController.class).resolveReturnType(ListenableFuture.class, String.class))).isTrue(); - assertTrue(this.handler.supportsReturnType( - on(TestController.class).resolveReturnType(CompletableFuture.class, String.class))); + assertThat(this.handler.supportsReturnType( + on(TestController.class).resolveReturnType(CompletableFuture.class, String.class))).isTrue(); } @Test public void doesNotSupportReturnType() throws Exception { - assertFalse(this.handler.supportsReturnType(on(TestController.class).resolveReturnType(String.class))); + assertThat(this.handler.supportsReturnType(on(TestController.class).resolveReturnType(String.class))).isFalse(); } @Test @@ -130,13 +128,13 @@ public class DeferredResultReturnValueHandlerTests { MethodParameter returnType = on(TestController.class).resolveReturnType(asyncType, String.class); this.handler.handleReturnValue(returnValue, returnType, mavContainer, this.webRequest); - assertTrue(this.request.isAsyncStarted()); - assertFalse(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult()); + assertThat(this.request.isAsyncStarted()).isTrue(); + assertThat(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult()).isFalse(); setResultTask.run(); - assertTrue(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult()); - assertEquals(expectedValue, WebAsyncUtils.getAsyncManager(this.webRequest).getConcurrentResult()); + assertThat(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult()).isTrue(); + assertThat(WebAsyncUtils.getAsyncManager(this.webRequest).getConcurrentResult()).isEqualTo(expectedValue); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolverTests.java index bf175fb5e12..62f9abcb1f4 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolverTests.java @@ -50,11 +50,7 @@ import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.util.NestedServletException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link ExceptionHandlerExceptionResolver}. @@ -102,7 +98,7 @@ public class ExceptionHandlerExceptionResolverTests { Object handler = null; this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handler, null); - assertNull("Exception can be resolved only if there is a HandlerMethod", mav); + assertThat(mav).as("Exception can be resolved only if there is a HandlerMethod").isNull(); } @Test @@ -111,7 +107,7 @@ public class ExceptionHandlerExceptionResolverTests { this.resolver.setCustomArgumentResolvers(Collections.singletonList(resolver)); this.resolver.afterPropertiesSet(); - assertTrue(this.resolver.getArgumentResolvers().getResolvers().contains(resolver)); + assertThat(this.resolver.getArgumentResolvers().getResolvers().contains(resolver)).isTrue(); assertMethodProcessorCount(RESOLVER_COUNT + 1, HANDLER_COUNT); } @@ -130,7 +126,7 @@ public class ExceptionHandlerExceptionResolverTests { this.resolver.setCustomReturnValueHandlers(Collections.singletonList(handler)); this.resolver.afterPropertiesSet(); - assertTrue(this.resolver.getReturnValueHandlers().getHandlers().contains(handler)); + assertThat(this.resolver.getReturnValueHandlers().getHandlers().contains(handler)).isTrue(); assertMethodProcessorCount(RESOLVER_COUNT, HANDLER_COUNT + 1); } @@ -150,7 +146,7 @@ public class ExceptionHandlerExceptionResolverTests { this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, npe); - assertNull("NPE should not have been handled", mav); + assertThat(mav).as("NPE should not have been handled").isNull(); } @Test @@ -160,10 +156,10 @@ public class ExceptionHandlerExceptionResolverTests { this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); - assertNotNull(mav); - assertFalse(mav.isEmpty()); - assertEquals("errorView", mav.getViewName()); - assertEquals("Bad argument", mav.getModel().get("detail")); + assertThat(mav).isNotNull(); + assertThat(mav.isEmpty()).isFalse(); + assertThat(mav.getViewName()).isEqualTo("errorView"); + assertThat(mav.getModel().get("detail")).isEqualTo("Bad argument"); } @Test @@ -173,9 +169,9 @@ public class ExceptionHandlerExceptionResolverTests { this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); - assertNotNull(mav); - assertTrue(mav.isEmpty()); - assertEquals("IllegalArgumentException", this.response.getContentAsString()); + assertThat(mav).isNotNull(); + assertThat(mav.isEmpty()).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo("IllegalArgumentException"); } @Test @@ -185,9 +181,9 @@ public class ExceptionHandlerExceptionResolverTests { this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); - assertNotNull(mav); - assertTrue(mav.isEmpty()); - assertEquals("IllegalArgumentException", this.response.getContentAsString()); + assertThat(mav).isNotNull(); + assertThat(mav.isEmpty()).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo("IllegalArgumentException"); } @Test // SPR-13546 @@ -197,9 +193,9 @@ public class ExceptionHandlerExceptionResolverTests { this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); - assertNotNull(mav); - assertEquals(1, mav.getModelMap().size()); - assertEquals("IllegalArgumentException", mav.getModelMap().get("exceptionClassName")); + assertThat(mav).isNotNull(); + assertThat(mav.getModelMap().size()).isEqualTo(1); + assertThat(mav.getModelMap().get("exceptionClassName")).isEqualTo("IllegalArgumentException"); } @Test // SPR-14651 @@ -209,11 +205,11 @@ public class ExceptionHandlerExceptionResolverTests { this.resolver.afterPropertiesSet(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); - assertNotNull(mav); - assertEquals("redirect:/", mav.getViewName()); + assertThat(mav).isNotNull(); + assertThat(mav.getViewName()).isEqualTo("redirect:/"); FlashMap flashMap = (FlashMap) this.request.getAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE); - assertNotNull("output FlashMap should exist", flashMap); - assertEquals("IllegalArgumentException", flashMap.get("exceptionClassName")); + assertThat((Object) flashMap).as("output FlashMap should exist").isNotNull(); + assertThat(flashMap.get("exceptionClassName")).isEqualTo("IllegalArgumentException"); } @Test @@ -226,9 +222,9 @@ public class ExceptionHandlerExceptionResolverTests { HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); - assertNotNull("Exception was not handled", mav); - assertTrue(mav.isEmpty()); - assertEquals("AnotherTestExceptionResolver: IllegalAccessException", this.response.getContentAsString()); + assertThat(mav).as("Exception was not handled").isNotNull(); + assertThat(mav.isEmpty()).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo("AnotherTestExceptionResolver: IllegalAccessException"); } @Test @@ -241,9 +237,9 @@ public class ExceptionHandlerExceptionResolverTests { HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); - assertNotNull("Exception was not handled", mav); - assertTrue(mav.isEmpty()); - assertEquals("TestExceptionResolver: IllegalStateException", this.response.getContentAsString()); + assertThat(mav).as("Exception was not handled").isNotNull(); + assertThat(mav.isEmpty()).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo("TestExceptionResolver: IllegalStateException"); } @Test // SPR-12605 @@ -256,9 +252,9 @@ public class ExceptionHandlerExceptionResolverTests { HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); - assertNotNull("Exception was not handled", mav); - assertTrue(mav.isEmpty()); - assertEquals("HandlerMethod: handle", this.response.getContentAsString()); + assertThat(mav).as("Exception was not handled").isNotNull(); + assertThat(mav.isEmpty()).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo("HandlerMethod: handle"); } @Test @@ -272,9 +268,9 @@ public class ExceptionHandlerExceptionResolverTests { ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, new NestedServletException("Handler dispatch failed", err)); - assertNotNull("Exception was not handled", mav); - assertTrue(mav.isEmpty()); - assertEquals(err.toString(), this.response.getContentAsString()); + assertThat(mav).as("Exception was not handled").isNotNull(); + assertThat(mav.isEmpty()).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo(err.toString()); } @Test @@ -288,9 +284,9 @@ public class ExceptionHandlerExceptionResolverTests { HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); - assertNotNull("Exception was not handled", mav); - assertTrue(mav.isEmpty()); - assertEquals(err.toString(), this.response.getContentAsString()); + assertThat(mav).as("Exception was not handled").isNotNull(); + assertThat(mav.isEmpty()).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo(err.toString()); } @Test @@ -303,9 +299,9 @@ public class ExceptionHandlerExceptionResolverTests { HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); - assertNotNull("Exception was not handled", mav); - assertTrue(mav.isEmpty()); - assertEquals("BasePackageTestExceptionResolver: IllegalStateException", this.response.getContentAsString()); + assertThat(mav).as("Exception was not handled").isNotNull(); + assertThat(mav.isEmpty()).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo("BasePackageTestExceptionResolver: IllegalStateException"); } @Test @@ -317,9 +313,9 @@ public class ExceptionHandlerExceptionResolverTests { IllegalStateException ex = new IllegalStateException(); ModelAndView mav = this.resolver.resolveException(this.request, this.response, null, ex); - assertNotNull("Exception was not handled", mav); - assertTrue(mav.isEmpty()); - assertEquals("DefaultTestExceptionResolver: IllegalStateException", this.response.getContentAsString()); + assertThat(mav).as("Exception was not handled").isNotNull(); + assertThat(mav.isEmpty()).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo("DefaultTestExceptionResolver: IllegalStateException"); } @Test // SPR-16496 @@ -332,15 +328,15 @@ public class ExceptionHandlerExceptionResolverTests { HandlerMethod handlerMethod = new HandlerMethod(new ProxyFactory(new ResponseBodyController()).getProxy(), "handle"); ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); - assertNotNull("Exception was not handled", mav); - assertTrue(mav.isEmpty()); - assertEquals("BasePackageTestExceptionResolver: IllegalStateException", this.response.getContentAsString()); + assertThat(mav).as("Exception was not handled").isNotNull(); + assertThat(mav.isEmpty()).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo("BasePackageTestExceptionResolver: IllegalStateException"); } private void assertMethodProcessorCount(int resolverCount, int handlerCount) { - assertEquals(resolverCount, this.resolver.getArgumentResolvers().getResolvers().size()); - assertEquals(handlerCount, this.resolver.getReturnValueHandlers().getHandlers().size()); + assertThat(this.resolver.getArgumentResolvers().getResolvers().size()).isEqualTo(resolverCount); + assertThat(this.resolver.getReturnValueHandlers().getHandlers().size()).isEqualTo(handlerCount); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExtendedServletRequestDataBinderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExtendedServletRequestDataBinderTests.java index cece8b4124f..b3de3698a45 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExtendedServletRequestDataBinderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExtendedServletRequestDataBinderTests.java @@ -28,7 +28,7 @@ import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.servlet.HandlerMapping; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link ExtendedServletRequestDataBinder}. @@ -55,8 +55,8 @@ public class ExtendedServletRequestDataBinderTests { WebDataBinder binder = new ExtendedServletRequestDataBinder(target, ""); ((ServletRequestDataBinder) binder).bind(request); - assertEquals("nameValue", target.getName()); - assertEquals(25, target.getAge()); + assertThat(target.getName()).isEqualTo("nameValue"); + assertThat(target.getAge()).isEqualTo(25); } @Test @@ -72,8 +72,8 @@ public class ExtendedServletRequestDataBinderTests { WebDataBinder binder = new ExtendedServletRequestDataBinder(target, ""); ((ServletRequestDataBinder) binder).bind(request); - assertEquals("nameValue", target.getName()); - assertEquals(35, target.getAge()); + assertThat(target.getName()).isEqualTo("nameValue"); + assertThat(target.getAge()).isEqualTo(35); } @Test @@ -82,8 +82,8 @@ public class ExtendedServletRequestDataBinderTests { WebDataBinder binder = new ExtendedServletRequestDataBinder(target, ""); ((ServletRequestDataBinder) binder).bind(request); - assertEquals(null, target.getName()); - assertEquals(0, target.getAge()); + assertThat(target.getName()).isEqualTo(null); + assertThat(target.getAge()).isEqualTo(0); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HandlerMethodAnnotationDetectionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HandlerMethodAnnotationDetectionTests.java index 06b46514a99..c3da6d7b118 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HandlerMethodAnnotationDetectionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HandlerMethodAnnotationDetectionTests.java @@ -50,8 +50,7 @@ import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.ModelAndView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Test various scenarios for detecting method-level and method parameter annotations depending @@ -134,17 +133,17 @@ public class HandlerMethodAnnotationDetectionTests { request.addHeader("header2", dateB); HandlerExecutionChain chain = handlerMapping.getHandler(request); - assertNotNull(chain); + assertThat(chain).isNotNull(); ModelAndView mav = handlerAdapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); - assertEquals("model attr1:", dateFormat.parse(dateA), mav.getModel().get("attr1")); - assertEquals("model attr2:", dateFormat.parse(dateB), mav.getModel().get("attr2")); + assertThat(mav.getModel().get("attr1")).as("model attr1:").isEqualTo(dateFormat.parse(dateA)); + assertThat(mav.getModel().get("attr2")).as("model attr2:").isEqualTo(dateFormat.parse(dateB)); MockHttpServletResponse response = new MockHttpServletResponse(); exceptionResolver.resolveException(request, response, chain.getHandler(), new Exception("failure")); - assertEquals("text/plain;charset=ISO-8859-1", response.getHeader("Content-Type")); - assertEquals("failure", response.getContentAsString()); + assertThat(response.getHeader("Content-Type")).isEqualTo("text/plain;charset=ISO-8859-1"); + assertThat(response.getContentAsString()).isEqualTo("failure"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java index 155b06b8649..3da29b184b6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java @@ -59,9 +59,6 @@ import static java.time.Instant.ofEpochMilli; import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME; import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.argThat; @@ -172,20 +169,19 @@ public class HttpEntityMethodProcessorMockTests { @Test public void supportsParameter() { - assertTrue("HttpEntity parameter not supported", processor.supportsParameter(paramHttpEntity)); - assertTrue("RequestEntity parameter not supported", processor.supportsParameter(paramRequestEntity)); - assertFalse("ResponseEntity parameter supported", processor.supportsParameter(paramResponseEntity)); - assertFalse("non-entity parameter supported", processor.supportsParameter(paramInt)); + assertThat(processor.supportsParameter(paramHttpEntity)).as("HttpEntity parameter not supported").isTrue(); + assertThat(processor.supportsParameter(paramRequestEntity)).as("RequestEntity parameter not supported").isTrue(); + assertThat(processor.supportsParameter(paramResponseEntity)).as("ResponseEntity parameter supported").isFalse(); + assertThat(processor.supportsParameter(paramInt)).as("non-entity parameter supported").isFalse(); } @Test public void supportsReturnType() { - assertTrue("ResponseEntity return type not supported", processor.supportsReturnType(returnTypeResponseEntity)); - assertTrue("HttpEntity return type not supported", processor.supportsReturnType(returnTypeHttpEntity)); - assertTrue("Custom HttpEntity subclass not supported", processor.supportsReturnType(returnTypeHttpEntitySubclass)); - assertFalse("RequestEntity parameter supported", - processor.supportsReturnType(paramRequestEntity)); - assertFalse("non-ResponseBody return type supported", processor.supportsReturnType(returnTypeInt)); + assertThat(processor.supportsReturnType(returnTypeResponseEntity)).as("ResponseEntity return type not supported").isTrue(); + assertThat(processor.supportsReturnType(returnTypeHttpEntity)).as("HttpEntity return type not supported").isTrue(); + assertThat(processor.supportsReturnType(returnTypeHttpEntitySubclass)).as("Custom HttpEntity subclass not supported").isTrue(); + assertThat(processor.supportsReturnType(paramRequestEntity)).as("RequestEntity parameter supported").isFalse(); + assertThat(processor.supportsReturnType(returnTypeInt)).as("non-ResponseBody return type supported").isFalse(); } @Test @@ -201,9 +197,9 @@ public class HttpEntityMethodProcessorMockTests { Object result = processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null); - assertTrue(result instanceof HttpEntity); - assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); - assertEquals("Invalid argument", body, ((HttpEntity) result).getBody()); + assertThat(result instanceof HttpEntity).isTrue(); + assertThat(mavContainer.isRequestHandled()).as("The requestHandled flag shouldn't change").isFalse(); + assertThat(((HttpEntity) result).getBody()).as("Invalid argument").isEqualTo(body); } @Test @@ -223,14 +219,14 @@ public class HttpEntityMethodProcessorMockTests { Object result = processor.resolveArgument(paramRequestEntity, mavContainer, webRequest, null); - assertTrue(result instanceof RequestEntity); - assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); + assertThat(result instanceof RequestEntity).isTrue(); + assertThat(mavContainer.isRequestHandled()).as("The requestHandled flag shouldn't change").isFalse(); RequestEntity requestEntity = (RequestEntity) result; - assertEquals("Invalid method", HttpMethod.GET, requestEntity.getMethod()); + assertThat(requestEntity.getMethod()).as("Invalid method").isEqualTo(HttpMethod.GET); // using default port (which is 80), so do not need to append the port (-1 means ignore) URI uri = new URI("http", null, "www.example.com", -1, "/path", null, null); - assertEquals("Invalid url", uri, requestEntity.getUrl()); - assertEquals("Invalid argument", body, requestEntity.getBody()); + assertThat(requestEntity.getUrl()).as("Invalid url").isEqualTo(uri); + assertThat(requestEntity.getBody()).as("Invalid argument").isEqualTo(body); } @Test @@ -264,7 +260,7 @@ public class HttpEntityMethodProcessorMockTests { processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); - assertTrue(mavContainer.isRequestHandled()); + assertThat(mavContainer.isRequestHandled()).isTrue(); verify(stringHttpMessageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); } @@ -278,7 +274,7 @@ public class HttpEntityMethodProcessorMockTests { processor.handleReturnValue(returnValue, returnTypeResponseEntityProduces, mavContainer, webRequest); - assertTrue(mavContainer.isRequestHandled()); + assertThat(mavContainer.isRequestHandled()).isTrue(); verify(stringHttpMessageConverter).write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); } @@ -300,7 +296,7 @@ public class HttpEntityMethodProcessorMockTests { processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); - assertTrue(mavContainer.isRequestHandled()); + assertThat(mavContainer.isRequestHandled()).isTrue(); verify(stringHttpMessageConverter).write(eq("Foo"), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); } @@ -352,8 +348,8 @@ public class HttpEntityMethodProcessorMockTests { processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); - assertTrue(mavContainer.isRequestHandled()); - assertEquals("headerValue", servletResponse.getHeader("headerName")); + assertThat(mavContainer.isRequestHandled()).isTrue(); + assertThat(servletResponse.getHeader("headerName")).isEqualTo("headerValue"); } @Test @@ -367,8 +363,8 @@ public class HttpEntityMethodProcessorMockTests { ArgumentCaptor outputMessage = ArgumentCaptor.forClass(HttpOutputMessage.class); verify(stringHttpMessageConverter).write(eq("body"), eq(TEXT_PLAIN), outputMessage.capture()); - assertTrue(mavContainer.isRequestHandled()); - assertEquals("headerValue", outputMessage.getValue().getHeaders().get("header").get(0)); + assertThat(mavContainer.isRequestHandled()).isTrue(); + assertThat(outputMessage.getValue().getHeaders().get("header").get(0)).isEqualTo("headerValue"); } @Test @@ -525,7 +521,7 @@ public class HttpEntityMethodProcessorMockTests { then(resourceMessageConverter).should(times(1)).write( any(ByteArrayResource.class), eq(APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class)); - assertEquals(200, servletResponse.getStatus()); + assertThat(servletResponse.getStatus()).isEqualTo(200); } @Test @@ -542,7 +538,7 @@ public class HttpEntityMethodProcessorMockTests { then(resourceRegionMessageConverter).should(times(1)).write( anyCollection(), eq(APPLICATION_OCTET_STREAM), argThat(outputMessage -> "bytes".equals(outputMessage.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES)))); - assertEquals(206, servletResponse.getStatus()); + assertThat(servletResponse.getStatus()).isEqualTo(206); } @Test @@ -558,7 +554,7 @@ public class HttpEntityMethodProcessorMockTests { then(resourceRegionMessageConverter).should(never()).write( anyCollection(), eq(APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class)); - assertEquals(416, servletResponse.getStatus()); + assertThat(servletResponse.getStatus()).isEqualTo(416); } @Test //SPR-16754 @@ -574,7 +570,7 @@ public class HttpEntityMethodProcessorMockTests { processor.handleReturnValue(returnValue, returnTypeResponseEntityResource, mavContainer, webRequest); then(resourceMessageConverter).should(times(1)).write( any(InputStreamResource.class), eq(APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class)); - assertEquals(200, servletResponse.getStatus()); + assertThat(servletResponse.getStatus()).isEqualTo(200); assertThat(servletResponse.getHeader(HttpHeaders.ACCEPT_RANGES)).isNull(); } @@ -591,7 +587,7 @@ public class HttpEntityMethodProcessorMockTests { processor.handleReturnValue(returnValue, returnTypeResponseEntityResource, mavContainer, webRequest); then(resourceRegionMessageConverter).should(never()).write(anyCollection(), any(), any()); - assertEquals(206, servletResponse.getStatus()); + assertThat(servletResponse.getStatus()).isEqualTo(206); } @Test //SPR-14767 @@ -670,8 +666,8 @@ public class HttpEntityMethodProcessorMockTests { initStringMessageConversion(TEXT_PLAIN); processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); - assertTrue(mavContainer.isRequestHandled()); - assertEquals(Arrays.asList(expected), servletResponse.getHeaders("Vary")); + assertThat(mavContainer.isRequestHandled()).isTrue(); + assertThat(servletResponse.getHeaders("Vary")).isEqualTo(Arrays.asList(expected)); verify(stringHttpMessageConverter).write(eq("Foo"), eq(TEXT_PLAIN), isA(HttpOutputMessage.class)); } @@ -689,21 +685,21 @@ public class HttpEntityMethodProcessorMockTests { private void assertConditionalResponse(HttpStatus status, String body, String etag, long lastModified) throws IOException { - assertEquals(status.value(), servletResponse.getStatus()); - assertTrue(mavContainer.isRequestHandled()); + assertThat(servletResponse.getStatus()).isEqualTo(status.value()); + assertThat(mavContainer.isRequestHandled()).isTrue(); if (body != null) { assertResponseBody(body); } else { - assertEquals(0, servletResponse.getContentAsByteArray().length); + assertThat(servletResponse.getContentAsByteArray().length).isEqualTo(0); } if (etag != null) { - assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.ETAG).size()); - assertEquals(etag, servletResponse.getHeader(HttpHeaders.ETAG)); + assertThat(servletResponse.getHeaderValues(HttpHeaders.ETAG).size()).isEqualTo(1); + assertThat(servletResponse.getHeader(HttpHeaders.ETAG)).isEqualTo(etag); } if (lastModified != -1) { - assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.LAST_MODIFIED).size()); - assertEquals(lastModified / 1000, servletResponse.getDateHeader(HttpHeaders.LAST_MODIFIED) / 1000); + assertThat(servletResponse.getHeaderValues(HttpHeaders.LAST_MODIFIED).size()).isEqualTo(1); + assertThat((servletResponse.getDateHeader(HttpHeaders.LAST_MODIFIED) / 1000)).isEqualTo((lastModified / 1000)); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorTests.java index 46fa730615f..d60d7f974cb 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorTests.java @@ -47,10 +47,7 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.support.ModelAndViewContainer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link HttpEntityMethodProcessor} delegating to @@ -107,8 +104,8 @@ public class HttpEntityMethodProcessorTests { HttpEntity result = (HttpEntity) processor.resolveArgument( paramSimpleBean, mavContainer, webRequest, binderFactory); - assertNotNull(result); - assertEquals("Jad", result.getBody().getName()); + assertThat(result).isNotNull(); + assertThat(result.getBody().getName()).isEqualTo("Jad"); } @Test // SPR-12861 @@ -123,8 +120,8 @@ public class HttpEntityMethodProcessorTests { HttpEntity result = (HttpEntity) processor.resolveArgument(this.paramSimpleBean, this.mavContainer, this.webRequest, this.binderFactory); - assertNotNull(result); - assertNull(result.getBody()); + assertThat(result).isNotNull(); + assertThat(result.getBody()).isNull(); } @Test @@ -141,9 +138,9 @@ public class HttpEntityMethodProcessorTests { HttpEntity> result = (HttpEntity>) processor.resolveArgument( paramList, mavContainer, webRequest, binderFactory); - assertNotNull(result); - assertEquals("Jad", result.getBody().get(0).getName()); - assertEquals("Robert", result.getBody().get(1).getName()); + assertThat(result).isNotNull(); + assertThat(result.getBody().get(0).getName()).isEqualTo("Jad"); + assertThat(result.getBody().get(1).getName()).isEqualTo("Robert"); } @Test @@ -164,8 +161,8 @@ public class HttpEntityMethodProcessorTests { HttpEntity result = (HttpEntity) processor.resolveArgument(methodParam, mavContainer, webRequest, binderFactory); - assertNotNull(result); - assertEquals("Jad", result.getBody().getName()); + assertThat(result).isNotNull(); + assertThat(result.getBody().getName()).isEqualTo("Jad"); } @Test // SPR-12811 @@ -182,8 +179,8 @@ public class HttpEntityMethodProcessorTests { processor.handleReturnValue(returnValue, methodReturnType, this.mavContainer, this.webRequest); String content = this.servletResponse.getContentAsString(); - assertTrue(content.contains("\"type\":\"foo\"")); - assertTrue(content.contains("\"type\":\"bar\"")); + assertThat(content.contains("\"type\":\"foo\"")).isTrue(); + assertThat(content.contains("\"type\":\"bar\"")).isTrue(); } @Test // SPR-13423 @@ -199,8 +196,8 @@ public class HttpEntityMethodProcessorTests { HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters); processor.handleReturnValue(returnValue, returnType, mavContainer, webRequest); - assertEquals("text/plain;charset=ISO-8859-1", servletResponse.getHeader("Content-Type")); - assertEquals("Foo", servletResponse.getContentAsString()); + assertThat(servletResponse.getHeader("Content-Type")).isEqualTo("text/plain;charset=ISO-8859-1"); + assertThat(servletResponse.getContentAsString()).isEqualTo("Foo"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMapMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMapMethodArgumentResolverTests.java index 5fb4eb03443..c36848dad9c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMapMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMapMethodArgumentResolverTests.java @@ -35,9 +35,7 @@ import org.springframework.web.method.ResolvableMethod; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.HandlerMapping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.method.MvcAnnotationPredicates.matrixAttribute; /** @@ -73,19 +71,19 @@ public class MatrixVariablesMapMethodArgumentResolverTests { @Test public void supportsParameter() { - assertFalse(this.resolver.supportsParameter(this.testMethod.arg(String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(String.class))).isFalse(); - assertTrue(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().noName()) - .arg(Map.class, String.class, String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().noName()) + .arg(Map.class, String.class, String.class))).isTrue(); - assertTrue(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().noPathVar()) - .arg(MultiValueMap.class, String.class, String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().noPathVar()) + .arg(MultiValueMap.class, String.class, String.class))).isTrue(); - assertTrue(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().pathVar("cars")) - .arg(MultiValueMap.class, String.class, String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().pathVar("cars")) + .arg(MultiValueMap.class, String.class, String.class))).isTrue(); - assertFalse(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().name("name")) - .arg(Map.class, String.class, String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.annot(matrixAttribute().name("name")) + .arg(Map.class, String.class, String.class))).isFalse(); } @Test @@ -103,7 +101,7 @@ public class MatrixVariablesMapMethodArgumentResolverTests { Map map = (Map) this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null); - assertEquals("red", map.get("colors")); + assertThat(map.get("colors")).isEqualTo("red"); param = this.testMethod .annot(matrixAttribute().noPathVar()) @@ -113,7 +111,7 @@ public class MatrixVariablesMapMethodArgumentResolverTests { MultiValueMap multivalueMap = (MultiValueMap) this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null); - assertEquals(Arrays.asList("red", "green", "blue"), multivalueMap.get("colors")); + assertThat(multivalueMap.get("colors")).isEqualTo(Arrays.asList("red", "green", "blue")); } @Test @@ -130,10 +128,10 @@ public class MatrixVariablesMapMethodArgumentResolverTests { .arg(MultiValueMap.class, String.class, String.class); @SuppressWarnings("unchecked") - Map mapForPathVar = (Map) this.resolver.resolveArgument( + Map mapForPathVar = (Map) this.resolver.resolveArgument( param, this.mavContainer, this.webRequest, null); - assertEquals(Arrays.asList("red", "purple"), mapForPathVar.get("colors")); + assertThat(mapForPathVar.get("colors")).isEqualTo(Arrays.asList("red", "purple")); param = this.testMethod.annot(matrixAttribute().noName()).arg(Map.class, String.class, String.class); @@ -141,7 +139,7 @@ public class MatrixVariablesMapMethodArgumentResolverTests { Map mapAll = (Map) this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null); - assertEquals("red", mapAll.get("colors")); + assertThat(mapAll.get("colors")).isEqualTo("red"); } @Test @@ -154,7 +152,7 @@ public class MatrixVariablesMapMethodArgumentResolverTests { Map map = (Map) this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null); - assertEquals(Collections.emptyMap(), map); + assertThat(map).isEqualTo(Collections.emptyMap()); } @Test @@ -170,7 +168,7 @@ public class MatrixVariablesMapMethodArgumentResolverTests { Map map = (Map) this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null); - assertEquals(Collections.emptyMap(), map); + assertThat(map).isEqualTo(Collections.emptyMap()); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMethodArgumentResolverTests.java index 5d42eed7324..a460c9051fd 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MatrixVariablesMethodArgumentResolverTests.java @@ -36,10 +36,8 @@ import org.springframework.web.method.ResolvableMethod; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.HandlerMapping; +import static org.assertj.core.api.Assertions.assertThat; 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; import static org.springframework.web.method.MvcAnnotationPredicates.matrixAttribute; /** @@ -74,13 +72,13 @@ public class MatrixVariablesMethodArgumentResolverTests { @Test public void supportsParameter() { - assertFalse(this.resolver.supportsParameter(this.testMethod.arg(String.class))); + assertThat(this.resolver.supportsParameter(this.testMethod.arg(String.class))).isFalse(); - assertTrue(this.resolver.supportsParameter( - this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class))); + assertThat(this.resolver.supportsParameter( + this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class))).isTrue(); - assertTrue(this.resolver.supportsParameter( - this.testMethod.annot(matrixAttribute().name("year")).arg(int.class))); + assertThat(this.resolver.supportsParameter( + this.testMethod.annot(matrixAttribute().name("year")).arg(int.class))).isTrue(); } @Test @@ -91,8 +89,7 @@ public class MatrixVariablesMethodArgumentResolverTests { params.add("colors", "blue"); MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class); - assertEquals(Arrays.asList("red", "green", "blue"), - this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null)); + assertThat(this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null)).isEqualTo(Arrays.asList("red", "green", "blue")); } @Test @@ -101,13 +98,13 @@ public class MatrixVariablesMethodArgumentResolverTests { getVariablesFor("bikes").add("year", "2005"); MethodParameter param = this.testMethod.annot(matrixAttribute().name("year")).arg(int.class); - assertEquals("2006", this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null)); + assertThat(this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null)).isEqualTo("2006"); } @Test public void resolveArgumentDefaultValue() throws Exception { MethodParameter param = this.testMethod.annot(matrixAttribute().name("year")).arg(int.class); - assertEquals("2013", resolver.resolveArgument(param, this.mavContainer, this.webRequest, null)); + assertThat(resolver.resolveArgument(param, this.mavContainer, this.webRequest, null)).isEqualTo("2013"); } @Test @@ -133,7 +130,7 @@ public class MatrixVariablesMethodArgumentResolverTests { params.add("anotherYear", "2012"); MethodParameter param = this.testMethod.annot(matrixAttribute().name("year")).arg(int.class); - assertEquals("2013", this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null)); + assertThat(this.resolver.resolveArgument(param, this.mavContainer, this.webRequest, null)).isEqualTo("2013"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandlerTests.java index 433638b452f..aacb618577c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandlerTests.java @@ -30,11 +30,7 @@ import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap; import org.springframework.web.servlet.view.RedirectView; -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; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link ModelAndViewMethodReturnValueHandler}. @@ -63,8 +59,8 @@ public class ModelAndViewMethodReturnValueHandlerTests { @Test public void supportsReturnType() throws Exception { - assertTrue(handler.supportsReturnType(returnParamModelAndView)); - assertFalse(handler.supportsReturnType(getReturnValueParam("viewName"))); + assertThat(handler.supportsReturnType(returnParamModelAndView)).isTrue(); + assertThat(handler.supportsReturnType(getReturnValueParam("viewName"))).isFalse(); } @Test @@ -72,8 +68,8 @@ public class ModelAndViewMethodReturnValueHandlerTests { ModelAndView mav = new ModelAndView("viewName", "attrName", "attrValue"); handler.handleReturnValue(mav, returnParamModelAndView, mavContainer, webRequest); - assertEquals("viewName", mavContainer.getView()); - assertEquals("attrValue", mavContainer.getModel().get("attrName")); + assertThat(mavContainer.getView()).isEqualTo("viewName"); + assertThat(mavContainer.getModel().get("attrName")).isEqualTo("attrValue"); } @Test @@ -81,15 +77,15 @@ public class ModelAndViewMethodReturnValueHandlerTests { ModelAndView mav = new ModelAndView(new RedirectView(), "attrName", "attrValue"); handler.handleReturnValue(mav, returnParamModelAndView, mavContainer, webRequest); - assertEquals(RedirectView.class, mavContainer.getView().getClass()); - assertEquals("attrValue", mavContainer.getModel().get("attrName")); + assertThat(mavContainer.getView().getClass()).isEqualTo(RedirectView.class); + assertThat(mavContainer.getModel().get("attrName")).isEqualTo("attrValue"); } @Test public void handleNull() throws Exception { handler.handleReturnValue(null, returnParamModelAndView, mavContainer, webRequest); - assertTrue(mavContainer.isRequestHandled()); + assertThat(mavContainer.isRequestHandled()).isTrue(); } @Test @@ -100,10 +96,9 @@ public class ModelAndViewMethodReturnValueHandlerTests { ModelAndView mav = new ModelAndView(new RedirectView(), "attrName", "attrValue"); handler.handleReturnValue(mav, returnParamModelAndView, mavContainer, webRequest); - assertEquals(RedirectView.class, mavContainer.getView().getClass()); - assertEquals("attrValue", mavContainer.getModel().get("attrName")); - assertSame("RedirectAttributes should be used if controller redirects", redirectAttributes, - mavContainer.getModel()); + assertThat(mavContainer.getView().getClass()).isEqualTo(RedirectView.class); + assertThat(mavContainer.getModel().get("attrName")).isEqualTo("attrValue"); + assertThat(mavContainer.getModel()).as("RedirectAttributes should be used if controller redirects").isSameAs(redirectAttributes); } @Test @@ -115,9 +110,9 @@ public class ModelAndViewMethodReturnValueHandlerTests { handler.handleReturnValue(mav, returnParamModelAndView, mavContainer, webRequest); ModelMap model = mavContainer.getModel(); - assertEquals("redirect:viewName", mavContainer.getViewName()); - assertEquals("attrValue", model.get("attrName")); - assertSame(redirectAttributes, model); + assertThat(mavContainer.getViewName()).isEqualTo("redirect:viewName"); + assertThat(model.get("attrName")).isEqualTo("attrValue"); + assertThat(model).isSameAs(redirectAttributes); } @Test @@ -130,9 +125,9 @@ public class ModelAndViewMethodReturnValueHandlerTests { handler.handleReturnValue(mav, returnParamModelAndView, mavContainer, webRequest); ModelMap model = mavContainer.getModel(); - assertEquals("myRedirect:viewName", mavContainer.getViewName()); - assertEquals("attrValue", model.get("attrName")); - assertSame(redirectAttributes, model); + assertThat(mavContainer.getViewName()).isEqualTo("myRedirect:viewName"); + assertThat(model.get("attrName")).isEqualTo("attrValue"); + assertThat(model).isSameAs(redirectAttributes); } @Test @@ -144,9 +139,9 @@ public class ModelAndViewMethodReturnValueHandlerTests { handler.handleReturnValue(mav, returnParamModelAndView, mavContainer, webRequest); ModelMap model = mavContainer.getModel(); - assertEquals(null, mavContainer.getView()); - assertTrue(mavContainer.getModel().isEmpty()); - assertNotSame("RedirectAttributes should not be used if controller doesn't redirect", redirectAttributes, model); + assertThat(mavContainer.getView()).isEqualTo(null); + assertThat(mavContainer.getModel().isEmpty()).isTrue(); + assertThat(model).as("RedirectAttributes should not be used if controller doesn't redirect").isNotSameAs(redirectAttributes); } @Test // SPR-14045 @@ -158,9 +153,9 @@ public class ModelAndViewMethodReturnValueHandlerTests { handler.handleReturnValue(mav, returnParamModelAndView, mavContainer, webRequest); ModelMap model = mavContainer.getModel(); - assertSame(redirectView, mavContainer.getView()); - assertEquals(1, model.size()); - assertEquals("value", model.get("name")); + assertThat(mavContainer.getView()).isSameAs(redirectView); + assertThat(model.size()).isEqualTo(1); + assertThat(model.get("name")).isEqualTo("value"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java index 63785903e94..b45f8913869 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java @@ -33,12 +33,8 @@ import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * Test fixture with {@link ModelAndViewResolverMethodReturnValueHandler}. @@ -73,9 +69,9 @@ public class ModelAndViewResolverMethodReturnValueHandlerTests { handler.handleReturnValue(testBean, returnType, mavContainer, request); - assertEquals("viewName", mavContainer.getViewName()); - assertSame(testBean, mavContainer.getModel().get("modelAttrName")); - assertFalse(mavContainer.isRequestHandled()); + assertThat(mavContainer.getViewName()).isEqualTo("viewName"); + assertThat(mavContainer.getModel().get("modelAttrName")).isSameAs(testBean); + assertThat(mavContainer.isRequestHandled()).isFalse(); } @Test @@ -91,9 +87,9 @@ public class ModelAndViewResolverMethodReturnValueHandlerTests { MethodParameter returnType = new MethodParameter(getClass().getDeclaredMethod("testBeanReturnValue"), -1); handler.handleReturnValue(null, returnType, mavContainer, request); - assertNull(mavContainer.getView()); - assertNull(mavContainer.getViewName()); - assertTrue(mavContainer.getModel().isEmpty()); + assertThat(mavContainer.getView()).isNull(); + assertThat(mavContainer.getViewName()).isNull(); + assertThat(mavContainer.getModel().isEmpty()).isTrue(); } @Test @@ -108,7 +104,7 @@ public class ModelAndViewResolverMethodReturnValueHandlerTests { MethodParameter returnType = new MethodParameter(getClass().getDeclaredMethod("testBeanReturnValue"), -1); handler.handleReturnValue(new TestBean(), returnType, mavContainer, request); - assertTrue(mavContainer.containsAttribute("testBean")); + assertThat(mavContainer.containsAttribute("testBean")).isTrue(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java index 95d2efebf84..a42254be3ab 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java @@ -63,7 +63,6 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.fromController; import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.fromMappingName; import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.fromMethodCall; @@ -131,8 +130,8 @@ public class MvcUriComponentsBuilderTests { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("https://example.org:9090/base"); UriComponents uriComponents = fromController(builder, PersonControllerImpl.class).build(); - assertEquals("https://example.org:9090/base/people", uriComponents.toString()); - assertEquals("https://example.org:9090/base", builder.toUriString()); + assertThat(uriComponents.toString()).isEqualTo("https://example.org:9090/base/people"); + assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base"); } @Test @@ -141,8 +140,8 @@ public class MvcUriComponentsBuilderTests { MvcUriComponentsBuilder mvcBuilder = relativeTo(builder); UriComponents uriComponents = mvcBuilder.withController(PersonControllerImpl.class).build(); - assertEquals("https://example.org:9090/base/people", uriComponents.toString()); - assertEquals("https://example.org:9090/base", builder.toUriString()); + assertThat(uriComponents.toString()).isEqualTo("https://example.org:9090/base/people"); + assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base"); } @Test @@ -247,8 +246,8 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodName(builder, ControllerWithMethods.class, "methodWithPathVariable", "1").build(); - assertEquals("https://example.org:9090/base/something/1/foo", uriComponents.toString()); - assertEquals("https://example.org:9090/base", builder.toUriString()); + assertThat(uriComponents.toString()).isEqualTo("https://example.org:9090/base/something/1/foo"); + assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base"); } @Test @@ -258,8 +257,8 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = mvcBuilder.withMethodName(ControllerWithMethods.class, "methodWithPathVariable", "1").build(); - assertEquals("https://example.org:9090/base/something/1/foo", uriComponents.toString()); - assertEquals("https://example.org:9090/base", builder.toUriString()); + assertThat(uriComponents.toString()).isEqualTo("https://example.org:9090/base/something/1/foo"); + assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base"); } @Test // SPR-14405 @@ -348,8 +347,8 @@ public class MvcUriComponentsBuilderTests { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("https://example.org:9090/base"); UriComponents uriComponents = fromMethodCall(builder, on(ControllerWithMethods.class).myMethod(null)).build(); - assertEquals("https://example.org:9090/base/something/else", uriComponents.toString()); - assertEquals("https://example.org:9090/base", builder.toUriString()); + assertThat(uriComponents.toString()).isEqualTo("https://example.org:9090/base/something/else"); + assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base"); } @Test @@ -358,8 +357,8 @@ public class MvcUriComponentsBuilderTests { MvcUriComponentsBuilder mvcBuilder = relativeTo(builder); UriComponents result = mvcBuilder.withMethodCall(on(ControllerWithMethods.class).myMethod(null)).build(); - assertEquals("https://example.org:9090/base/something/else", result.toString()); - assertEquals("https://example.org:9090/base", builder.toUriString()); + assertThat(result.toString()).isEqualTo("https://example.org:9090/base/something/else"); + assertThat(builder.toUriString()).isEqualTo("https://example.org:9090/base"); } @Test // SPR-16710 @@ -367,7 +366,7 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodCall( on(BookingControllerWithModelAndView.class).getBooking(21L)).buildAndExpand(42); - assertEquals("http://localhost/hotels/42/bookings/21", uriComponents.encode().toUri().toString()); + assertThat(uriComponents.encode().toUri().toString()).isEqualTo("http://localhost/hotels/42/bookings/21"); } @Test // SPR-16710 @@ -375,7 +374,7 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodCall( on(BookingControllerWithObject.class).getBooking(21L)).buildAndExpand(42); - assertEquals("http://localhost/hotels/42/bookings/21", uriComponents.encode().toUri().toString()); + assertThat(uriComponents.encode().toUri().toString()).isEqualTo("http://localhost/hotels/42/bookings/21"); } @Test // SPR-16710 @@ -392,7 +391,7 @@ public class MvcUriComponentsBuilderTests { UriComponents uriComponents = fromMethodName( BookingControllerWithString.class, "getBooking", 21L).buildAndExpand(42); - assertEquals("http://localhost/hotels/42/bookings/21", uriComponents.encode().toUri().toString()); + assertThat(uriComponents.encode().toUri().toString()).isEqualTo("http://localhost/hotels/42/bookings/21"); } @Test @@ -406,7 +405,7 @@ public class MvcUriComponentsBuilderTests { String mappingName = "PAC#getAddressesForCountry"; String url = fromMappingName(mappingName).arg(0, "DE").buildAndExpand(123); - assertEquals("/base/people/123/addresses/DE", url); + assertThat(url).isEqualTo("/base/people/123/addresses/DE"); } @Test @@ -417,7 +416,7 @@ public class MvcUriComponentsBuilderTests { UriComponentsBuilder baseUrl = UriComponentsBuilder.fromUriString("https://example.org:9999/base"); MvcUriComponentsBuilder mvcBuilder = relativeTo(baseUrl); String url = mvcBuilder.withMappingName("PAC#getAddressesForCountry").arg(0, "DE").buildAndExpand(123); - assertEquals("https://example.org:9999/base/people/123/addresses/DE", url); + assertThat(url).isEqualTo("https://example.org:9999/base/people/123/addresses/DE"); } @Test // SPR-17027 @@ -431,7 +430,7 @@ public class MvcUriComponentsBuilderTests { String mappingName = "PAC#getAddressesForCountry"; String url = fromMappingName(mappingName).arg(0, "DE;FR").encode().buildAndExpand("_+_"); - assertEquals("/base/people/_%2B_/addresses/DE%3BFR", url); + assertThat(url).isEqualTo("/base/people/_%2B_/addresses/DE%3BFR"); } @Test @@ -444,8 +443,7 @@ public class MvcUriComponentsBuilderTests { this.request.setServerPort(9999); this.request.setContextPath("/base"); - assertEquals("https://example.org:9999/base/api/people/123/addresses", - fromController(PersonsAddressesController.class).buildAndExpand("123").toString()); + assertThat(fromController(PersonsAddressesController.class).buildAndExpand("123").toString()).isEqualTo("https://example.org:9999/base/api/people/123/addresses"); } @Test @@ -458,9 +456,8 @@ public class MvcUriComponentsBuilderTests { this.request.setServerPort(9999); this.request.setContextPath("/base"); - assertEquals("https://example.org:9999/base/api/people/123/addresses/DE", - fromMethodCall(on(PersonsAddressesController.class).getAddressesForCountry("DE")) - .buildAndExpand("123").toString()); + assertThat(fromMethodCall(on(PersonsAddressesController.class).getAddressesForCountry("DE")) + .buildAndExpand("123").toString()).isEqualTo("https://example.org:9999/base/api/people/123/addresses/DE"); } private void initWebApplicationContext(Class configClass) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMapMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMapMethodArgumentResolverTests.java index 214f97bb68c..9034505e883 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMapMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMapMethodArgumentResolverTests.java @@ -32,9 +32,7 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.HandlerMapping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link PathVariableMapMethodArgumentResolver}. @@ -72,9 +70,9 @@ public class PathVariableMapMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(resolver.supportsParameter(paramMap)); - assertFalse(resolver.supportsParameter(paramNamedMap)); - assertFalse(resolver.supportsParameter(paramMapNoAnnot)); + assertThat(resolver.supportsParameter(paramMap)).isTrue(); + assertThat(resolver.supportsParameter(paramNamedMap)).isFalse(); + assertThat(resolver.supportsParameter(paramMapNoAnnot)).isFalse(); } @Test @@ -86,7 +84,7 @@ public class PathVariableMapMethodArgumentResolverTests { Object result = resolver.resolveArgument(paramMap, mavContainer, webRequest, null); - assertEquals(uriTemplateVars, result); + assertThat(result).isEqualTo(uriTemplateVars); } @Test @@ -94,7 +92,7 @@ public class PathVariableMapMethodArgumentResolverTests { public void resolveArgumentNoUriVars() throws Exception { Map map = (Map) resolver.resolveArgument(paramMap, mavContainer, webRequest, null); - assertEquals(Collections.emptyMap(), map); + assertThat(map).isEqualTo(Collections.emptyMap()); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolverTests.java index 00f1ccde423..0836b040b5a 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolverTests.java @@ -40,12 +40,8 @@ import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.View; +import static org.assertj.core.api.Assertions.assertThat; 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.assertNull; -import static org.junit.Assert.assertTrue; /** * Test fixture with {@link PathVariableMethodArgumentResolver}. @@ -86,8 +82,8 @@ public class PathVariableMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue("Parameter with @PathVariable annotation", resolver.supportsParameter(paramNamedString)); - assertFalse("Parameter without @PathVariable annotation", resolver.supportsParameter(paramString)); + assertThat(resolver.supportsParameter(paramNamedString)).as("Parameter with @PathVariable annotation").isTrue(); + assertThat(resolver.supportsParameter(paramString)).as("Parameter without @PathVariable annotation").isFalse(); } @Test @@ -97,13 +93,13 @@ public class PathVariableMethodArgumentResolverTests { request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); String result = (String) resolver.resolveArgument(paramNamedString, mavContainer, webRequest, null); - assertEquals("PathVariable not resolved correctly", "value", result); + assertThat(result).as("PathVariable not resolved correctly").isEqualTo("value"); @SuppressWarnings("unchecked") Map pathVars = (Map) request.getAttribute(View.PATH_VARIABLES); - assertNotNull(pathVars); - assertEquals(1, pathVars.size()); - assertEquals("value", pathVars.get("name")); + assertThat(pathVars).isNotNull(); + assertThat(pathVars.size()).isEqualTo(1); + assertThat(pathVars.get("name")).isEqualTo("value"); } @Test @@ -113,13 +109,13 @@ public class PathVariableMethodArgumentResolverTests { request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); String result = (String) resolver.resolveArgument(paramNotRequired, mavContainer, webRequest, null); - assertEquals("PathVariable not resolved correctly", "value", result); + assertThat(result).as("PathVariable not resolved correctly").isEqualTo("value"); @SuppressWarnings("unchecked") Map pathVars = (Map) request.getAttribute(View.PATH_VARIABLES); - assertNotNull(pathVars); - assertEquals(1, pathVars.size()); - assertEquals("value", pathVars.get("name")); + assertThat(pathVars).isNotNull(); + assertThat(pathVars.size()).isEqualTo(1); + assertThat(pathVars.get("name")).isEqualTo("value"); } @Test @@ -135,13 +131,13 @@ public class PathVariableMethodArgumentResolverTests { @SuppressWarnings("unchecked") Optional result = (Optional) resolver.resolveArgument(paramOptional, mavContainer, webRequest, binderFactory); - assertEquals("PathVariable not resolved correctly", "value", result.get()); + assertThat(result.get()).as("PathVariable not resolved correctly").isEqualTo("value"); @SuppressWarnings("unchecked") Map pathVars = (Map) request.getAttribute(View.PATH_VARIABLES); - assertNotNull(pathVars); - assertEquals(1, pathVars.size()); - assertEquals(Optional.of("value"), pathVars.get("name")); + assertThat(pathVars).isNotNull(); + assertThat(pathVars.size()).isEqualTo(1); + assertThat(pathVars.get("name")).isEqualTo(Optional.of("value")); } @Test @@ -154,14 +150,14 @@ public class PathVariableMethodArgumentResolverTests { request.setAttribute(View.PATH_VARIABLES, uriTemplateVars); String result = (String) resolver.resolveArgument(paramNamedString, mavContainer, webRequest, null); - assertEquals("PathVariable not resolved correctly", "value", result); + assertThat(result).as("PathVariable not resolved correctly").isEqualTo("value"); @SuppressWarnings("unchecked") Map pathVars = (Map) request.getAttribute(View.PATH_VARIABLES); - assertNotNull(pathVars); - assertEquals(2, pathVars.size()); - assertEquals("value", pathVars.get("name")); - assertEquals("oldValue", pathVars.get("oldName")); + assertThat(pathVars).isNotNull(); + assertThat(pathVars.size()).isEqualTo(2); + assertThat(pathVars.get("name")).isEqualTo("value"); + assertThat(pathVars.get("oldName")).isEqualTo("oldValue"); } @Test @@ -172,7 +168,7 @@ public class PathVariableMethodArgumentResolverTests { @Test public void nullIfNotRequired() throws Exception { - assertNull(resolver.resolveArgument(paramNotRequired, mavContainer, webRequest, null)); + assertThat(resolver.resolveArgument(paramNotRequired, mavContainer, webRequest, null)).isNull(); } @Test @@ -181,7 +177,7 @@ public class PathVariableMethodArgumentResolverTests { initializer.setConversionService(new DefaultConversionService()); WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer); - assertEquals(Optional.empty(), resolver.resolveArgument(paramOptional, mavContainer, webRequest, binderFactory)); + assertThat(resolver.resolveArgument(paramOptional, mavContainer, webRequest, binderFactory)).isEqualTo(Optional.empty()); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ReactiveTypeHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ReactiveTypeHandlerTests.java index fe439748479..9257213b6f7 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ReactiveTypeHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ReactiveTypeHandlerTests.java @@ -54,10 +54,7 @@ import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.HandlerMapping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.ResolvableType.forClass; import static org.springframework.web.method.ResolvableMethod.on; @@ -99,14 +96,14 @@ public class ReactiveTypeHandlerTests { @Test public void supportsType() throws Exception { - assertTrue(this.handler.isReactiveType(Mono.class)); - assertTrue(this.handler.isReactiveType(Single.class)); - assertTrue(this.handler.isReactiveType(io.reactivex.Single.class)); + assertThat(this.handler.isReactiveType(Mono.class)).isTrue(); + assertThat(this.handler.isReactiveType(Single.class)).isTrue(); + assertThat(this.handler.isReactiveType(io.reactivex.Single.class)).isTrue(); } @Test public void doesNotSupportType() throws Exception { - assertFalse(this.handler.isReactiveType(String.class)); + assertThat(this.handler.isReactiveType(String.class)).isFalse(); } @Test @@ -195,7 +192,8 @@ public class ReactiveTypeHandlerTests { private void testSseResponse(boolean expectSseEmitter) throws Exception { ResponseBodyEmitter emitter = handleValue(Flux.empty(), Flux.class, forClass(String.class)); - assertEquals(expectSseEmitter, emitter instanceof SseEmitter); + Object actual = emitter instanceof SseEmitter; + assertThat(actual).isEqualTo(expectSseEmitter); resetRequest(); } @@ -214,7 +212,7 @@ public class ReactiveTypeHandlerTests { processor.onNext("baz"); processor.onComplete(); - assertEquals("data:foo\n\ndata:bar\n\ndata:baz\n\n", emitterHandler.getValuesAsText()); + assertThat(emitterHandler.getValuesAsText()).isEqualTo("data:foo\n\ndata:bar\n\ndata:baz\n\n"); } @Test @@ -233,8 +231,7 @@ public class ReactiveTypeHandlerTests { processor.onNext(ServerSentEvent.builder("baz").id("3").build()); processor.onComplete(); - assertEquals("id:1\ndata:foo\n\nid:2\ndata:bar\n\nid:3\ndata:baz\n\n", - emitterHandler.getValuesAsText()); + assertThat(emitterHandler.getValuesAsText()).isEqualTo("id:1\ndata:foo\n\nid:2\ndata:bar\n\nid:3\ndata:baz\n\n"); } @Test @@ -258,8 +255,8 @@ public class ReactiveTypeHandlerTests { processor.onNext(bar2); processor.onComplete(); - assertEquals("application/stream+json", message.getHeaders().getContentType().toString()); - assertEquals(Arrays.asList(bar1, "\n", bar2, "\n"), emitterHandler.getValues()); + assertThat(message.getHeaders().getContentType().toString()).isEqualTo("application/stream+json"); + assertThat(emitterHandler.getValues()).isEqualTo(Arrays.asList(bar1, "\n", bar2, "\n")); } @Test @@ -276,7 +273,7 @@ public class ReactiveTypeHandlerTests { processor.onNext("the lazy dog"); processor.onComplete(); - assertEquals("The quick brown fox jumps over the lazy dog", emitterHandler.getValuesAsText()); + assertThat(emitterHandler.getValuesAsText()).isEqualTo("The quick brown fox jumps over the lazy dog"); } @Test @@ -306,7 +303,7 @@ public class ReactiveTypeHandlerTests { ServletServerHttpResponse message = new ServletServerHttpResponse(this.servletResponse); ResponseBodyEmitter emitter = handleValue(Flux.empty(), Flux.class, forClass(String.class)); emitter.extendResponse(message); - assertEquals(expected, message.getHeaders().getContentType().toString()); + assertThat(message.getHeaders().getContentType().toString()).isEqualTo(expected); resetRequest(); } @@ -315,15 +312,15 @@ public class ReactiveTypeHandlerTests { ResolvableType elementType, Runnable produceTask, Object expected) throws Exception { ResponseBodyEmitter emitter = handleValue(returnValue, asyncType, elementType); - assertNull(emitter); + assertThat(emitter).isNull(); - assertTrue(this.servletRequest.isAsyncStarted()); - assertFalse(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult()); + assertThat(this.servletRequest.isAsyncStarted()).isTrue(); + assertThat(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult()).isFalse(); produceTask.run(); - assertTrue(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult()); - assertEquals(expected, WebAsyncUtils.getAsyncManager(this.webRequest).getConcurrentResult()); + assertThat(WebAsyncUtils.getAsyncManager(this.webRequest).hasConcurrentResult()).isTrue(); + assertThat(WebAsyncUtils.getAsyncManager(this.webRequest).getConcurrentResult()).isEqualTo(expected); resetRequest(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterIntegrationTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterIntegrationTests.java index c1892eb8992..f9bf698d2d6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterIntegrationTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterIntegrationTests.java @@ -85,12 +85,6 @@ import org.springframework.web.servlet.ModelAndView; import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * A test fixture with a controller with all supported method signature styles @@ -181,49 +175,49 @@ public class RequestMappingHandlerAdapterIntegrationTests { ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod); ModelMap model = mav.getModelMap(); - assertEquals("viewName", mav.getViewName()); - assertEquals(99, model.get("cookie")); - assertEquals("pathvarValue", model.get("pathvar")); - assertEquals("headerValue", model.get("header")); - assertEquals(date, model.get("dateParam")); + assertThat(mav.getViewName()).isEqualTo("viewName"); + assertThat(model.get("cookie")).isEqualTo(99); + assertThat(model.get("pathvar")).isEqualTo("pathvarValue"); + assertThat(model.get("header")).isEqualTo("headerValue"); + assertThat(model.get("dateParam")).isEqualTo(date); Map map = (Map) model.get("headerMap"); - assertEquals("headerValue", map.get("header")); - assertEquals("anotherHeaderValue", map.get("anotherHeader")); - assertEquals("systemHeaderValue", model.get("systemHeader")); + assertThat(map.get("header")).isEqualTo("headerValue"); + assertThat(map.get("anotherHeader")).isEqualTo("anotherHeaderValue"); + assertThat(model.get("systemHeader")).isEqualTo("systemHeaderValue"); map = (Map) model.get("paramMap"); - assertEquals(formattedDate, map.get("dateParam")); - assertEquals("paramByConventionValue", map.get("paramByConvention")); + assertThat(map.get("dateParam")).isEqualTo(formattedDate); + assertThat(map.get("paramByConvention")).isEqualTo("paramByConventionValue"); - assertEquals("/contextPath", model.get("value")); + assertThat(model.get("value")).isEqualTo("/contextPath"); TestBean modelAttr = (TestBean) model.get("modelAttr"); - assertEquals(25, modelAttr.getAge()); - assertEquals("Set by model method [modelAttr]", modelAttr.getName()); - assertSame(modelAttr, request.getSession().getAttribute("modelAttr")); + assertThat(modelAttr.getAge()).isEqualTo(25); + assertThat(modelAttr.getName()).isEqualTo("Set by model method [modelAttr]"); + assertThat(request.getSession().getAttribute("modelAttr")).isSameAs(modelAttr); BindingResult bindingResult = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + "modelAttr"); - assertSame(modelAttr, bindingResult.getTarget()); - assertEquals(1, bindingResult.getErrorCount()); + assertThat(bindingResult.getTarget()).isSameAs(modelAttr); + assertThat(bindingResult.getErrorCount()).isEqualTo(1); String conventionAttrName = "testBean"; TestBean modelAttrByConvention = (TestBean) model.get(conventionAttrName); - assertEquals(25, modelAttrByConvention.getAge()); - assertEquals("Set by model method [modelAttrByConvention]", modelAttrByConvention.getName()); - assertSame(modelAttrByConvention, request.getSession().getAttribute(conventionAttrName)); + assertThat(modelAttrByConvention.getAge()).isEqualTo(25); + assertThat(modelAttrByConvention.getName()).isEqualTo("Set by model method [modelAttrByConvention]"); + assertThat(request.getSession().getAttribute(conventionAttrName)).isSameAs(modelAttrByConvention); bindingResult = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + conventionAttrName); - assertSame(modelAttrByConvention, bindingResult.getTarget()); + assertThat(bindingResult.getTarget()).isSameAs(modelAttrByConvention); - assertTrue(model.get("customArg") instanceof Color); - assertEquals(User.class, model.get("user").getClass()); - assertEquals(OtherUser.class, model.get("otherUser").getClass()); + assertThat(model.get("customArg") instanceof Color).isTrue(); + assertThat(model.get("user").getClass()).isEqualTo(User.class); + assertThat(model.get("otherUser").getClass()).isEqualTo(OtherUser.class); - assertSame(sessionAttribute, model.get("sessionAttribute")); - assertSame(requestAttribute, model.get("requestAttribute")); + assertThat(model.get("sessionAttribute")).isSameAs(sessionAttribute); + assertThat(model.get("requestAttribute")).isSameAs(requestAttribute); - assertEquals(new URI("http://localhost/contextPath/main/path"), model.get("url")); + assertThat(model.get("url")).isEqualTo(new URI("http://localhost/contextPath/main/path")); } @Test @@ -262,49 +256,49 @@ public class RequestMappingHandlerAdapterIntegrationTests { ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod); ModelMap model = mav.getModelMap(); - assertEquals("viewName", mav.getViewName()); - assertEquals(99, model.get("cookie")); - assertEquals("pathvarValue", model.get("pathvar")); - assertEquals("headerValue", model.get("header")); - assertEquals(date, model.get("dateParam")); + assertThat(mav.getViewName()).isEqualTo("viewName"); + assertThat(model.get("cookie")).isEqualTo(99); + assertThat(model.get("pathvar")).isEqualTo("pathvarValue"); + assertThat(model.get("header")).isEqualTo("headerValue"); + assertThat(model.get("dateParam")).isEqualTo(date); Map map = (Map) model.get("headerMap"); - assertEquals("headerValue", map.get("header")); - assertEquals("anotherHeaderValue", map.get("anotherHeader")); - assertEquals("systemHeaderValue", model.get("systemHeader")); + assertThat(map.get("header")).isEqualTo("headerValue"); + assertThat(map.get("anotherHeader")).isEqualTo("anotherHeaderValue"); + assertThat(model.get("systemHeader")).isEqualTo("systemHeaderValue"); map = (Map) model.get("paramMap"); - assertEquals(formattedDate, map.get("dateParam")); - assertEquals("paramByConventionValue", map.get("paramByConvention")); + assertThat(map.get("dateParam")).isEqualTo(formattedDate); + assertThat(map.get("paramByConvention")).isEqualTo("paramByConventionValue"); - assertEquals("/contextPath", model.get("value")); + assertThat(model.get("value")).isEqualTo("/contextPath"); TestBean modelAttr = (TestBean) model.get("modelAttr"); - assertEquals(25, modelAttr.getAge()); - assertEquals("Set by model method [modelAttr]", modelAttr.getName()); - assertSame(modelAttr, request.getSession().getAttribute("modelAttr")); + assertThat(modelAttr.getAge()).isEqualTo(25); + assertThat(modelAttr.getName()).isEqualTo("Set by model method [modelAttr]"); + assertThat(request.getSession().getAttribute("modelAttr")).isSameAs(modelAttr); BindingResult bindingResult = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + "modelAttr"); - assertSame(modelAttr, bindingResult.getTarget()); - assertEquals(1, bindingResult.getErrorCount()); + assertThat(bindingResult.getTarget()).isSameAs(modelAttr); + assertThat(bindingResult.getErrorCount()).isEqualTo(1); String conventionAttrName = "testBean"; TestBean modelAttrByConvention = (TestBean) model.get(conventionAttrName); - assertEquals(25, modelAttrByConvention.getAge()); - assertEquals("Set by model method [modelAttrByConvention]", modelAttrByConvention.getName()); - assertSame(modelAttrByConvention, request.getSession().getAttribute(conventionAttrName)); + assertThat(modelAttrByConvention.getAge()).isEqualTo(25); + assertThat(modelAttrByConvention.getName()).isEqualTo("Set by model method [modelAttrByConvention]"); + assertThat(request.getSession().getAttribute(conventionAttrName)).isSameAs(modelAttrByConvention); bindingResult = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + conventionAttrName); - assertSame(modelAttrByConvention, bindingResult.getTarget()); + assertThat(bindingResult.getTarget()).isSameAs(modelAttrByConvention); - assertTrue(model.get("customArg") instanceof Color); - assertEquals(User.class, model.get("user").getClass()); - assertEquals(OtherUser.class, model.get("otherUser").getClass()); + assertThat(model.get("customArg") instanceof Color).isTrue(); + assertThat(model.get("user").getClass()).isEqualTo(User.class); + assertThat(model.get("otherUser").getClass()).isEqualTo(OtherUser.class); - assertSame(sessionAttribute, model.get("sessionAttribute")); - assertSame(requestAttribute, model.get("requestAttribute")); + assertThat(model.get("sessionAttribute")).isSameAs(sessionAttribute); + assertThat(model.get("requestAttribute")).isSameAs(requestAttribute); - assertEquals(new URI("http://localhost/contextPath/main/path"), model.get("url")); + assertThat(model.get("url")).isEqualTo(new URI("http://localhost/contextPath/main/path")); } @Test @@ -319,9 +313,9 @@ public class RequestMappingHandlerAdapterIntegrationTests { ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod); - assertNull(mav); - assertEquals("Handled requestBody=[Hello Server]", new String(response.getContentAsByteArray(), "UTF-8")); - assertEquals(HttpStatus.ACCEPTED.value(), response.getStatus()); + assertThat(mav).isNull(); + assertThat(new String(response.getContentAsByteArray(), "UTF-8")).isEqualTo("Handled requestBody=[Hello Server]"); + assertThat(response.getStatus()).isEqualTo(HttpStatus.ACCEPTED.value()); } @Test @@ -335,9 +329,9 @@ public class RequestMappingHandlerAdapterIntegrationTests { ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod); - assertNull(mav); - assertEquals("Error count [1]", new String(response.getContentAsByteArray(), "UTF-8")); - assertEquals(HttpStatus.ACCEPTED.value(), response.getStatus()); + assertThat(mav).isNull(); + assertThat(new String(response.getContentAsByteArray(), "UTF-8")).isEqualTo("Error count [1]"); + assertThat(response.getStatus()).isEqualTo(HttpStatus.ACCEPTED.value()); } @Test @@ -351,12 +345,12 @@ public class RequestMappingHandlerAdapterIntegrationTests { ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod); - assertNull(mav); - assertEquals(HttpStatus.ACCEPTED.value(), response.getStatus()); - assertEquals("Handled requestBody=[Hello Server]", new String(response.getContentAsByteArray(), "UTF-8")); - assertEquals("headerValue", response.getHeader("header")); + assertThat(mav).isNull(); + assertThat(response.getStatus()).isEqualTo(HttpStatus.ACCEPTED.value()); + assertThat(new String(response.getContentAsByteArray(), "UTF-8")).isEqualTo("Handled requestBody=[Hello Server]"); + assertThat(response.getHeader("header")).isEqualTo("headerValue"); // set because of @SesstionAttributes - assertEquals("no-store", response.getHeader("Cache-Control")); + assertThat(response.getHeader("Cache-Control")).isEqualTo("no-store"); } // SPR-13867 @@ -369,9 +363,9 @@ public class RequestMappingHandlerAdapterIntegrationTests { HandlerMethod handlerMethod = handlerMethod("handleHttpEntityWithCacheControl", parameterTypes); ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod); - assertNull(mav); - assertEquals(HttpStatus.OK.value(), response.getStatus()); - assertEquals("Handled requestBody=[Hello Server]", new String(response.getContentAsByteArray(), "UTF-8")); + assertThat(mav).isNull(); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); + assertThat(new String(response.getContentAsByteArray(), "UTF-8")).isEqualTo("Handled requestBody=[Hello Server]"); assertThat(response.getHeaderValues("Cache-Control")).containsExactly("max-age=3600"); } @@ -383,8 +377,8 @@ public class RequestMappingHandlerAdapterIntegrationTests { HandlerMethod handlerMethod = handlerMethod("handleRequestPart", String.class, Model.class); ModelAndView mav = handlerAdapter.handle(multipartRequest, response, handlerMethod); - assertNotNull(mav); - assertEquals("content", mav.getModelMap().get("requestPart")); + assertThat(mav).isNotNull(); + assertThat(mav.getModelMap().get("requestPart")).isEqualTo("content"); } @Test @@ -395,8 +389,8 @@ public class RequestMappingHandlerAdapterIntegrationTests { HandlerMethod handlerMethod = handlerMethod("handleAndValidateRequestPart", String.class, Errors.class, Model.class); ModelAndView mav = handlerAdapter.handle(multipartRequest, response, handlerMethod); - assertNotNull(mav); - assertEquals(1, mav.getModelMap().get("error count")); + assertThat(mav).isNotNull(); + assertThat(mav.getModelMap().get("error count")).isEqualTo(1); } @Test @@ -404,7 +398,7 @@ public class RequestMappingHandlerAdapterIntegrationTests { HandlerMethod handlerMethod = handlerMethod("handleAndCompleteSession", SessionStatus.class); handlerAdapter.handle(request, response, handlerMethod); - assertFalse(request.getSession().getAttributeNames().hasMoreElements()); + assertThat(request.getSession().getAttributeNames().hasMoreElements()).isFalse(); } private HandlerMethod handlerMethod(String methodName, Class... paramTypes) throws Exception { @@ -495,8 +489,8 @@ public class RequestMappingHandlerAdapterIntegrationTests { .addAttribute("requestAttribute", requestAttribute) .addAttribute("url", builder.path("/path").build().toUri()); - assertNotNull(request); - assertNotNull(response); + assertThat(request).isNotNull(); + assertThat(response).isNotNull(); return "viewName"; } @@ -534,8 +528,8 @@ public class RequestMappingHandlerAdapterIntegrationTests { .addAttribute("requestAttribute", requestAttribute) .addAttribute("url", builder.path("/path").build().toUri()); - assertNotNull(request); - assertNotNull(response); + assertThat(request).isNotNull(); + assertThat(response).isNotNull(); return "viewName"; } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterTests.java index 949887c93d2..d4e0cc65481 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterTests.java @@ -58,8 +58,7 @@ import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.FlashMap; import org.springframework.web.servlet.ModelAndView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link RequestMappingHandlerAdapter}. @@ -115,7 +114,7 @@ public class RequestMappingHandlerAdapterTests { this.handlerAdapter.afterPropertiesSet(); this.handlerAdapter.handle(this.request, this.response, handlerMethod); - assertTrue(response.getHeader("Cache-Control").contains("max-age")); + assertThat(response.getHeader("Cache-Control").contains("max-age")).isTrue(); } @Test @@ -125,7 +124,7 @@ public class RequestMappingHandlerAdapterTests { this.handlerAdapter.afterPropertiesSet(); this.handlerAdapter.handle(this.request, this.response, handlerMethod(handler, "handle")); - assertEquals("no-store", this.response.getHeader("Cache-Control")); + assertThat(this.response.getHeader("Cache-Control")).isEqualTo("no-store"); } @Test @@ -144,7 +143,7 @@ public class RequestMappingHandlerAdapterTests { HandlerMethod handlerMethod = handlerMethod(new RedirectAttributeController(), "handle", Model.class); ModelAndView mav = this.handlerAdapter.handle(request, response, handlerMethod); - assertTrue("Without RedirectAttributes arg, model should be empty", mav.getModel().isEmpty()); + assertThat(mav.getModel().isEmpty()).as("Without RedirectAttributes arg, model should be empty").isTrue(); } @Test @@ -153,7 +152,7 @@ public class RequestMappingHandlerAdapterTests { this.handlerAdapter.setCustomArgumentResolvers(Collections.singletonList(resolver)); this.handlerAdapter.afterPropertiesSet(); - assertTrue(this.handlerAdapter.getArgumentResolvers().contains(resolver)); + assertThat(this.handlerAdapter.getArgumentResolvers().contains(resolver)).isTrue(); assertMethodProcessorCount(RESOLVER_COUNT + 1, INIT_BINDER_RESOLVER_COUNT + 1, HANDLER_COUNT); } @@ -181,7 +180,7 @@ public class RequestMappingHandlerAdapterTests { this.handlerAdapter.setCustomReturnValueHandlers(Collections.singletonList(handler)); this.handlerAdapter.afterPropertiesSet(); - assertTrue(this.handlerAdapter.getReturnValueHandlers().contains(handler)); + assertThat(this.handlerAdapter.getReturnValueHandlers().contains(handler)).isTrue(); assertMethodProcessorCount(RESOLVER_COUNT, INIT_BINDER_RESOLVER_COUNT, HANDLER_COUNT + 1); } @@ -203,8 +202,8 @@ public class RequestMappingHandlerAdapterTests { this.handlerAdapter.afterPropertiesSet(); ModelAndView mav = this.handlerAdapter.handle(this.request, this.response, handlerMethod); - assertEquals("lAttr1", mav.getModel().get("attr1")); - assertEquals("gAttr2", mav.getModel().get("attr2")); + assertThat(mav.getModel().get("attr1")).isEqualTo("lAttr1"); + assertThat(mav.getModel().get("attr2")).isEqualTo("gAttr2"); } @Test @@ -219,8 +218,8 @@ public class RequestMappingHandlerAdapterTests { this.handlerAdapter.afterPropertiesSet(); ModelAndView mav = this.handlerAdapter.handle(this.request, this.response, handlerMethod); - assertEquals("lAttr1", mav.getModel().get("attr1")); - assertEquals("gAttr2", mav.getModel().get("attr2")); + assertThat(mav.getModel().get("attr1")).isEqualTo("lAttr1"); + assertThat(mav.getModel().get("attr2")).isEqualTo("gAttr2"); } @Test @@ -233,9 +232,9 @@ public class RequestMappingHandlerAdapterTests { this.handlerAdapter.afterPropertiesSet(); ModelAndView mav = this.handlerAdapter.handle(this.request, this.response, handlerMethod); - assertEquals("lAttr1", mav.getModel().get("attr1")); - assertEquals("gAttr2", mav.getModel().get("attr2")); - assertEquals(null,mav.getModel().get("attr3")); + assertThat(mav.getModel().get("attr1")).isEqualTo("lAttr1"); + assertThat(mav.getModel().get("attr2")).isEqualTo("gAttr2"); + assertThat(mav.getModel().get("attr3")).isEqualTo(null); } // SPR-10859 @@ -256,8 +255,8 @@ public class RequestMappingHandlerAdapterTests { this.handlerAdapter.afterPropertiesSet(); this.handlerAdapter.handle(this.request, this.response, handlerMethod); - assertEquals(200, this.response.getStatus()); - assertEquals("{\"status\":400,\"message\":\"body\"}", this.response.getContentAsString()); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getContentAsString()).isEqualTo("{\"status\":400,\"message\":\"body\"}"); } private HandlerMethod handlerMethod(Object handler, String methodName, Class... paramTypes) throws Exception { @@ -266,9 +265,9 @@ public class RequestMappingHandlerAdapterTests { } private void assertMethodProcessorCount(int resolverCount, int initBinderResolverCount, int handlerCount) { - assertEquals(resolverCount, this.handlerAdapter.getArgumentResolvers().size()); - assertEquals(initBinderResolverCount, this.handlerAdapter.getInitBinderArgumentResolvers().size()); - assertEquals(handlerCount, this.handlerAdapter.getReturnValueHandlers().size()); + assertThat(this.handlerAdapter.getArgumentResolvers().size()).isEqualTo(resolverCount); + assertThat(this.handlerAdapter.getInitBinderArgumentResolvers().size()).isEqualTo(initBinderResolverCount); + assertThat(this.handlerAdapter.getReturnValueHandlers().size()).isEqualTo(handlerCount); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java index caaec7e44a6..771a9fa73e1 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java @@ -50,11 +50,7 @@ import org.springframework.web.method.HandlerTypePredicate; import org.springframework.web.servlet.mvc.condition.ConsumesRequestCondition; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -75,8 +71,8 @@ public class RequestMappingHandlerMappingTests { @Test public void useRegisteredSuffixPatternMatch() { - assertTrue(this.handlerMapping.useSuffixPatternMatch()); - assertFalse(this.handlerMapping.useRegisteredSuffixPatternMatch()); + assertThat(this.handlerMapping.useSuffixPatternMatch()).isTrue(); + assertThat(this.handlerMapping.useRegisteredSuffixPatternMatch()).isFalse(); Map fileExtensions = Collections.singletonMap("json", MediaType.APPLICATION_JSON); PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(fileExtensions); @@ -86,9 +82,9 @@ public class RequestMappingHandlerMappingTests { this.handlerMapping.setUseRegisteredSuffixPatternMatch(true); this.handlerMapping.afterPropertiesSet(); - assertTrue(this.handlerMapping.useSuffixPatternMatch()); - assertTrue(this.handlerMapping.useRegisteredSuffixPatternMatch()); - assertEquals(Arrays.asList("json"), this.handlerMapping.getFileExtensions()); + assertThat(this.handlerMapping.useSuffixPatternMatch()).isTrue(); + assertThat(this.handlerMapping.useRegisteredSuffixPatternMatch()).isTrue(); + assertThat(this.handlerMapping.getFileExtensions()).isEqualTo(Arrays.asList("json")); } @Test @@ -115,23 +111,21 @@ public class RequestMappingHandlerMappingTests { hm.setApplicationContext(wac); hm.afterPropertiesSet(); - assertEquals(Collections.singleton("json"), extensions); + assertThat(extensions).isEqualTo(Collections.singleton("json")); } @Test public void useSuffixPatternMatch() { - assertTrue(this.handlerMapping.useSuffixPatternMatch()); + assertThat(this.handlerMapping.useSuffixPatternMatch()).isTrue(); this.handlerMapping.setUseSuffixPatternMatch(false); - assertFalse(this.handlerMapping.useSuffixPatternMatch()); + assertThat(this.handlerMapping.useSuffixPatternMatch()).isFalse(); this.handlerMapping.setUseRegisteredSuffixPatternMatch(false); - assertFalse("'false' registeredSuffixPatternMatch shouldn't impact suffixPatternMatch", - this.handlerMapping.useSuffixPatternMatch()); + assertThat(this.handlerMapping.useSuffixPatternMatch()).as("'false' registeredSuffixPatternMatch shouldn't impact suffixPatternMatch").isFalse(); this.handlerMapping.setUseRegisteredSuffixPatternMatch(true); - assertTrue("'true' registeredSuffixPatternMatch should enable suffixPatternMatch", - this.handlerMapping.useSuffixPatternMatch()); + assertThat(this.handlerMapping.useSuffixPatternMatch()).as("'true' registeredSuffixPatternMatch should enable suffixPatternMatch").isTrue(); } @Test @@ -143,7 +137,7 @@ public class RequestMappingHandlerMappingTests { String[] patterns = new String[] { "/foo", "/${pattern}/bar" }; String[] result = this.handlerMapping.resolveEmbeddedValuesInPatterns(patterns); - assertArrayEquals(new String[] { "/foo", "/foo/bar" }, result); + assertThat(result).isEqualTo(new String[] { "/foo", "/foo/bar" }); } @Test @@ -155,18 +149,16 @@ public class RequestMappingHandlerMappingTests { Method method = UserController.class.getMethod("getUser"); RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, UserController.class); - assertNotNull(info); - assertEquals(Collections.singleton("/api/user/{id}"), info.getPatternsCondition().getPatterns()); + assertThat(info).isNotNull(); + assertThat(info.getPatternsCondition().getPatterns()).isEqualTo(Collections.singleton("/api/user/{id}")); } @Test public void resolveRequestMappingViaComposedAnnotation() throws Exception { RequestMappingInfo info = assertComposedAnnotationMapping("postJson", "/postJson", RequestMethod.POST); - assertEquals(MediaType.APPLICATION_JSON_VALUE, - info.getConsumesCondition().getConsumableMediaTypes().iterator().next().toString()); - assertEquals(MediaType.APPLICATION_JSON_VALUE, - info.getProducesCondition().getProducibleMediaTypes().iterator().next().toString()); + assertThat(info.getConsumesCondition().getConsumableMediaTypes().iterator().next().toString()).isEqualTo(MediaType.APPLICATION_JSON_VALUE); + assertThat(info.getProducesCondition().getProducibleMediaTypes().iterator().next().toString()).isEqualTo(MediaType.APPLICATION_JSON_VALUE); } @Test // SPR-14988 @@ -174,7 +166,7 @@ public class RequestMappingHandlerMappingTests { RequestMappingInfo requestMappingInfo = assertComposedAnnotationMapping(RequestMethod.POST); ConsumesRequestCondition condition = requestMappingInfo.getConsumesCondition(); - assertEquals(Collections.singleton(MediaType.APPLICATION_XML), condition.getConsumableMediaTypes()); + assertThat(condition.getConsumableMediaTypes()).isEqualTo(Collections.singleton(MediaType.APPLICATION_XML)); } @Test // gh-22010 @@ -187,7 +179,7 @@ public class RequestMappingHandlerMappingTests { .findFirst() .orElseThrow(() -> new AssertionError("No /post")); - assertFalse(info.getConsumesCondition().isBodyRequired()); + assertThat(info.getConsumesCondition().isBodyRequired()).isFalse(); } @Test @@ -229,15 +221,15 @@ public class RequestMappingHandlerMappingTests { Method method = ClassUtils.getMethod(clazz, methodName, (Class[]) null); RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, clazz); - assertNotNull(info); + assertThat(info).isNotNull(); Set paths = info.getPatternsCondition().getPatterns(); - assertEquals(1, paths.size()); - assertEquals(path, paths.iterator().next()); + assertThat(paths.size()).isEqualTo(1); + assertThat(paths.iterator().next()).isEqualTo(path); Set methods = info.getMethodsCondition().getMethods(); - assertEquals(1, methods.size()); - assertEquals(requestMethod, methods.iterator().next()); + assertThat(methods.size()).isEqualTo(1); + assertThat(methods.iterator().next()).isEqualTo(requestMethod); return info; } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java index e38df85ff5a..8605a14ccd3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java @@ -66,8 +66,7 @@ import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.bind.annotation.RequestMethod.POST; /** @@ -178,7 +177,7 @@ public class RequestPartIntegrationTests { this.restTemplate.setMessageConverters(Collections.singletonList(converter)); ResponseEntity responseEntity = restTemplate.exchange(requestEntity, Void.class); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); } private void testCreate(String url, String basename) { @@ -192,7 +191,7 @@ public class RequestPartIntegrationTests { parts.add("iso-8859-1-data", new HttpEntity<>(new byte[] {(byte) 0xC4}, headers)); // SPR-13096 URI location = restTemplate.postForLocation(url, parts); - assertEquals("http://localhost:8080/test/" + basename + "/logo.jpg", location.toString()); + assertThat(location.toString()).isEqualTo(("http://localhost:8080/test/" + basename + "/logo.jpg")); } @@ -239,7 +238,7 @@ public class RequestPartIntegrationTests { @RequestPart(name = "empty-data", required = false) TestData emptyData, @RequestPart(name = "iso-8859-1-data") byte[] iso88591Data) { - assertArrayEquals(new byte[]{(byte) 0xC4}, iso88591Data); + assertThat(iso88591Data).isEqualTo(new byte[]{(byte) 0xC4}); String url = "http://localhost:8080/test/" + testData.getName() + "/" + file.get().getOriginalFilename(); HttpHeaders headers = new HttpHeaders(); @@ -249,7 +248,7 @@ public class RequestPartIntegrationTests { @RequestMapping(value = "/spr13319", method = POST, consumes = "multipart/form-data") public ResponseEntity create(@RequestPart("file") MultipartFile multipartFile) { - assertEquals("élève.txt", multipartFile.getOriginalFilename()); + assertThat(multipartFile.getOriginalFilename()).isEqualTo("élève.txt"); return ResponseEntity.ok().build(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java index 5551e750819..c53f49bd7c6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java @@ -58,11 +58,6 @@ import org.springframework.web.multipart.support.MissingServletRequestPartExcept import static org.assertj.core.api.Assertions.assertThat; 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.assertSame; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; @@ -156,47 +151,49 @@ public class RequestPartMethodArgumentResolverTests { @Test public void supportsParameter() { - assertTrue(resolver.supportsParameter(paramRequestPart)); - assertTrue(resolver.supportsParameter(paramNamedRequestPart)); - assertTrue(resolver.supportsParameter(paramValidRequestPart)); - assertTrue(resolver.supportsParameter(paramMultipartFile)); - assertTrue(resolver.supportsParameter(paramMultipartFileList)); - assertTrue(resolver.supportsParameter(paramMultipartFileArray)); - assertFalse(resolver.supportsParameter(paramInt)); - assertTrue(resolver.supportsParameter(paramMultipartFileNotAnnot)); - assertTrue(resolver.supportsParameter(paramPart)); - assertTrue(resolver.supportsParameter(paramPartList)); - assertTrue(resolver.supportsParameter(paramPartArray)); - assertFalse(resolver.supportsParameter(paramRequestParamAnnot)); - assertTrue(resolver.supportsParameter(optionalMultipartFile)); - assertTrue(resolver.supportsParameter(optionalMultipartFileList)); - assertTrue(resolver.supportsParameter(optionalPart)); - assertTrue(resolver.supportsParameter(optionalPartList)); - assertTrue(resolver.supportsParameter(optionalRequestPart)); + assertThat(resolver.supportsParameter(paramRequestPart)).isTrue(); + assertThat(resolver.supportsParameter(paramNamedRequestPart)).isTrue(); + assertThat(resolver.supportsParameter(paramValidRequestPart)).isTrue(); + assertThat(resolver.supportsParameter(paramMultipartFile)).isTrue(); + assertThat(resolver.supportsParameter(paramMultipartFileList)).isTrue(); + assertThat(resolver.supportsParameter(paramMultipartFileArray)).isTrue(); + assertThat(resolver.supportsParameter(paramInt)).isFalse(); + assertThat(resolver.supportsParameter(paramMultipartFileNotAnnot)).isTrue(); + assertThat(resolver.supportsParameter(paramPart)).isTrue(); + assertThat(resolver.supportsParameter(paramPartList)).isTrue(); + assertThat(resolver.supportsParameter(paramPartArray)).isTrue(); + assertThat(resolver.supportsParameter(paramRequestParamAnnot)).isFalse(); + assertThat(resolver.supportsParameter(optionalMultipartFile)).isTrue(); + assertThat(resolver.supportsParameter(optionalMultipartFileList)).isTrue(); + assertThat(resolver.supportsParameter(optionalPart)).isTrue(); + assertThat(resolver.supportsParameter(optionalPartList)).isTrue(); + assertThat(resolver.supportsParameter(optionalRequestPart)).isTrue(); } @Test public void resolveMultipartFile() throws Exception { Object actual = resolver.resolveArgument(paramMultipartFile, null, webRequest, null); - assertSame(multipartFile1, actual); + assertThat(actual).isSameAs(multipartFile1); } @Test public void resolveMultipartFileList() throws Exception { Object actual = resolver.resolveArgument(paramMultipartFileList, null, webRequest, null); - assertTrue(actual instanceof List); - assertEquals(Arrays.asList(multipartFile1, multipartFile2), actual); + boolean condition = actual instanceof List; + assertThat(condition).isTrue(); + assertThat(actual).isEqualTo(Arrays.asList(multipartFile1, multipartFile2)); } @Test public void resolveMultipartFileArray() throws Exception { Object actual = resolver.resolveArgument(paramMultipartFileArray, null, webRequest, null); - assertNotNull(actual); - assertTrue(actual instanceof MultipartFile[]); + assertThat(actual).isNotNull(); + boolean condition = actual instanceof MultipartFile[]; + assertThat(condition).isTrue(); MultipartFile[] parts = (MultipartFile[]) actual; - assertEquals(2, parts.length); - assertEquals(parts[0], multipartFile1); - assertEquals(parts[1], multipartFile2); + assertThat(parts.length).isEqualTo(2); + assertThat(multipartFile1).isEqualTo(parts[0]); + assertThat(multipartFile2).isEqualTo(parts[1]); } @Test @@ -209,8 +206,9 @@ public class RequestPartMethodArgumentResolverTests { Object result = resolver.resolveArgument(paramMultipartFileNotAnnot, null, webRequest, null); - assertTrue(result instanceof MultipartFile); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof MultipartFile; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test @@ -224,8 +222,9 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object result = resolver.resolveArgument(paramPart, null, webRequest, null); - assertTrue(result instanceof Part); - assertEquals("Invalid result", expected, result); + boolean condition = result instanceof Part; + assertThat(condition).isTrue(); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test @@ -241,8 +240,9 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object result = resolver.resolveArgument(paramPartList, null, webRequest, null); - assertTrue(result instanceof List); - assertEquals(Arrays.asList(part1, part2), result); + boolean condition = result instanceof List; + assertThat(condition).isTrue(); + assertThat(result).isEqualTo(Arrays.asList(part1, part2)); } @Test @@ -258,11 +258,12 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object result = resolver.resolveArgument(paramPartArray, null, webRequest, null); - assertTrue(result instanceof Part[]); + boolean condition = result instanceof Part[]; + assertThat(condition).isTrue(); Part[] parts = (Part[]) result; - assertEquals(2, parts.length); - assertEquals(parts[0], part1); - assertEquals(parts[1], part2); + assertThat(parts.length).isEqualTo(2); + assertThat(part1).isEqualTo(parts[0]); + assertThat(part2).isEqualTo(parts[1]); } @Test @@ -320,7 +321,7 @@ public class RequestPartMethodArgumentResolverTests { public void isMultipartRequestPut() throws Exception { this.multipartRequest.setMethod("PUT"); Object actualValue = resolver.resolveArgument(paramMultipartFile, null, webRequest, null); - assertSame(multipartFile1, actualValue); + assertThat(actualValue).isSameAs(multipartFile1); } @Test @@ -332,12 +333,14 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object actualValue = resolver.resolveArgument(optionalMultipartFile, null, webRequest, null); - assertTrue(actualValue instanceof Optional); - assertEquals("Invalid result", expected, ((Optional) actualValue).get()); + boolean condition1 = actualValue instanceof Optional; + assertThat(condition1).isTrue(); + assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(expected); actualValue = resolver.resolveArgument(optionalMultipartFile, null, webRequest, null); - assertTrue(actualValue instanceof Optional); - assertEquals("Invalid result", expected, ((Optional) actualValue).get()); + boolean condition = actualValue instanceof Optional; + assertThat(condition).isTrue(); + assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(expected); } @Test @@ -346,10 +349,10 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object actualValue = resolver.resolveArgument(optionalMultipartFile, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); actualValue = resolver.resolveArgument(optionalMultipartFile, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); } @Test @@ -357,10 +360,10 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(new MockHttpServletRequest()); Object actualValue = resolver.resolveArgument(optionalMultipartFile, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); actualValue = resolver.resolveArgument(optionalMultipartFile, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); } @Test @@ -372,12 +375,14 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object actualValue = resolver.resolveArgument(optionalMultipartFileList, null, webRequest, null); - assertTrue(actualValue instanceof Optional); - assertEquals("Invalid result", Collections.singletonList(expected), ((Optional) actualValue).get()); + boolean condition1 = actualValue instanceof Optional; + assertThat(condition1).isTrue(); + assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(Collections.singletonList(expected)); actualValue = resolver.resolveArgument(optionalMultipartFileList, null, webRequest, null); - assertTrue(actualValue instanceof Optional); - assertEquals("Invalid result", Collections.singletonList(expected), ((Optional) actualValue).get()); + boolean condition = actualValue instanceof Optional; + assertThat(condition).isTrue(); + assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(Collections.singletonList(expected)); } @Test @@ -386,10 +391,10 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object actualValue = resolver.resolveArgument(optionalMultipartFileList, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); actualValue = resolver.resolveArgument(optionalMultipartFileList, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); } @Test @@ -397,10 +402,10 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(new MockHttpServletRequest()); Object actualValue = resolver.resolveArgument(optionalMultipartFileList, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); actualValue = resolver.resolveArgument(optionalMultipartFileList, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); } @Test @@ -414,12 +419,14 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object actualValue = resolver.resolveArgument(optionalPart, null, webRequest, null); - assertTrue(actualValue instanceof Optional); - assertEquals("Invalid result", expected, ((Optional) actualValue).get()); + boolean condition1 = actualValue instanceof Optional; + assertThat(condition1).isTrue(); + assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(expected); actualValue = resolver.resolveArgument(optionalPart, null, webRequest, null); - assertTrue(actualValue instanceof Optional); - assertEquals("Invalid result", expected, ((Optional) actualValue).get()); + boolean condition = actualValue instanceof Optional; + assertThat(condition).isTrue(); + assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(expected); } @Test @@ -430,10 +437,10 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object actualValue = resolver.resolveArgument(optionalPart, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); actualValue = resolver.resolveArgument(optionalPart, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); } @Test @@ -441,10 +448,10 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(new MockHttpServletRequest()); Object actualValue = resolver.resolveArgument(optionalPart, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); actualValue = resolver.resolveArgument(optionalPart, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); } @Test @@ -458,12 +465,14 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object actualValue = resolver.resolveArgument(optionalPartList, null, webRequest, null); - assertTrue(actualValue instanceof Optional); - assertEquals("Invalid result", Collections.singletonList(expected), ((Optional) actualValue).get()); + boolean condition1 = actualValue instanceof Optional; + assertThat(condition1).isTrue(); + assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(Collections.singletonList(expected)); actualValue = resolver.resolveArgument(optionalPartList, null, webRequest, null); - assertTrue(actualValue instanceof Optional); - assertEquals("Invalid result", Collections.singletonList(expected), ((Optional) actualValue).get()); + boolean condition = actualValue instanceof Optional; + assertThat(condition).isTrue(); + assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(Collections.singletonList(expected)); } @Test @@ -474,10 +483,10 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object actualValue = resolver.resolveArgument(optionalPartList, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); actualValue = resolver.resolveArgument(optionalPartList, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); } @Test @@ -485,10 +494,10 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(new MockHttpServletRequest()); Object actualValue = resolver.resolveArgument(optionalPartList, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); actualValue = resolver.resolveArgument(optionalPartList, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); } @Test @@ -501,12 +510,12 @@ public class RequestPartMethodArgumentResolverTests { Object actualValue = resolver.resolveArgument( optionalRequestPart, mavContainer, webRequest, new ValidatingBinderFactory()); - assertEquals("Invalid argument value", Optional.of(simpleBean), actualValue); - assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.of(simpleBean)); + assertThat(mavContainer.isRequestHandled()).as("The requestHandled flag shouldn't change").isFalse(); actualValue = resolver.resolveArgument(optionalRequestPart, mavContainer, webRequest, new ValidatingBinderFactory()); - assertEquals("Invalid argument value", Optional.of(simpleBean), actualValue); - assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.of(simpleBean)); + assertThat(mavContainer.isRequestHandled()).as("The requestHandled flag shouldn't change").isFalse(); } @Test @@ -517,10 +526,10 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object actualValue = resolver.resolveArgument(optionalRequestPart, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); actualValue = resolver.resolveArgument(optionalRequestPart, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); } @Test @@ -528,10 +537,10 @@ public class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(new MockHttpServletRequest()); Object actualValue = resolver.resolveArgument(optionalRequestPart, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); actualValue = resolver.resolveArgument(optionalRequestPart, null, webRequest, null); - assertEquals("Invalid argument value", Optional.empty(), actualValue); + assertThat(actualValue).as("Invalid argument value").isEqualTo(Optional.empty()); } @@ -542,8 +551,8 @@ public class RequestPartMethodArgumentResolverTests { ModelAndViewContainer mavContainer = new ModelAndViewContainer(); Object actualValue = resolver.resolveArgument(parameter, mavContainer, webRequest, new ValidatingBinderFactory()); - assertEquals("Invalid argument value", argValue, actualValue); - assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); + assertThat(actualValue).as("Invalid argument value").isEqualTo(argValue); + assertThat(mavContainer.isRequestHandled()).as("The requestHandled flag shouldn't change").isFalse(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyAdviceChainTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyAdviceChainTests.java index 6a959fd1b29..89b5627dbf5 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyAdviceChainTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyAdviceChainTests.java @@ -42,8 +42,7 @@ import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.method.ControllerAdviceBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.same; import static org.mockito.BDDMockito.given; @@ -94,14 +93,14 @@ public class RequestResponseBodyAdviceChainTests { given(requestAdvice.beforeBodyRead(eq(this.request), eq(this.paramType), eq(String.class), eq(this.converterType))).willReturn(wrapped); - assertSame(wrapped, chain.beforeBodyRead(this.request, this.paramType, String.class, this.converterType)); + assertThat(chain.beforeBodyRead(this.request, this.paramType, String.class, this.converterType)).isSameAs(wrapped); String modified = "body++"; given(requestAdvice.afterBodyRead(eq(this.body), eq(this.request), eq(this.paramType), eq(String.class), eq(this.converterType))).willReturn(modified); - assertEquals(modified, chain.afterBodyRead(this.body, this.request, this.paramType, - String.class, this.converterType)); + assertThat(chain.afterBodyRead(this.body, this.request, this.paramType, + String.class, this.converterType)).isEqualTo(modified); } @SuppressWarnings("unchecked") @@ -120,7 +119,7 @@ public class RequestResponseBodyAdviceChainTests { String actual = (String) chain.beforeBodyWrite(this.body, this.returnType, this.contentType, this.converterType, this.request, this.response); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -131,7 +130,7 @@ public class RequestResponseBodyAdviceChainTests { String actual = (String) chain.beforeBodyWrite(this.body, this.returnType, this.contentType, this.converterType, this.request, this.response); - assertEquals("body-MyControllerAdvice", actual); + assertThat(actual).isEqualTo("body-MyControllerAdvice"); } @Test @@ -142,7 +141,7 @@ public class RequestResponseBodyAdviceChainTests { String actual = (String) chain.beforeBodyWrite(this.body, this.returnType, this.contentType, this.converterType, this.request, this.response); - assertEquals(this.body, actual); + assertThat(actual).isEqualTo(this.body); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java index f21cc73584d..e30c7e56eb4 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java @@ -56,10 +56,6 @@ import org.springframework.web.servlet.HandlerMapping; import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.argThat; @@ -144,14 +140,14 @@ public class RequestResponseBodyMethodProcessorMockTests { @Test public void supportsParameter() { - assertTrue("RequestBody parameter not supported", processor.supportsParameter(paramRequestBodyString)); - assertFalse("non-RequestBody parameter supported", processor.supportsParameter(paramInt)); + assertThat(processor.supportsParameter(paramRequestBodyString)).as("RequestBody parameter not supported").isTrue(); + assertThat(processor.supportsParameter(paramInt)).as("non-RequestBody parameter supported").isFalse(); } @Test public void supportsReturnType() { - assertTrue("ResponseBody return type not supported", processor.supportsReturnType(returnTypeString)); - assertFalse("non-ResponseBody return type supported", processor.supportsReturnType(returnTypeInt)); + assertThat(processor.supportsReturnType(returnTypeString)).as("ResponseBody return type not supported").isTrue(); + assertThat(processor.supportsReturnType(returnTypeInt)).as("non-ResponseBody return type supported").isFalse(); } @Test @@ -168,8 +164,8 @@ public class RequestResponseBodyMethodProcessorMockTests { Object result = processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, new ValidatingBinderFactory()); - assertEquals("Invalid argument", body, result); - assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); + assertThat(result).as("Invalid argument").isEqualTo(body); + assertThat(mavContainer.isRequestHandled()).as("The requestHandled flag shouldn't change").isFalse(); } @Test @@ -248,8 +244,8 @@ public class RequestResponseBodyMethodProcessorMockTests { servletRequest.setMethod("GET"); servletRequest.setContent(new byte[0]); given(stringMessageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false); - assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, - webRequest, new ValidatingBinderFactory())); + assertThat(processor.resolveArgument(paramStringNotRequired, mavContainer, + webRequest, new ValidatingBinderFactory())).isNull(); } @Test @@ -258,8 +254,8 @@ public class RequestResponseBodyMethodProcessorMockTests { servletRequest.setContent("body".getBytes()); given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true); given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn("body"); - assertEquals("body", processor.resolveArgument(paramStringNotRequired, mavContainer, - webRequest, new ValidatingBinderFactory())); + assertThat(processor.resolveArgument(paramStringNotRequired, mavContainer, + webRequest, new ValidatingBinderFactory())).isEqualTo("body"); } @Test @@ -267,8 +263,8 @@ public class RequestResponseBodyMethodProcessorMockTests { servletRequest.setContentType("text/plain"); servletRequest.setContent(new byte[0]); given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true); - assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, - webRequest, new ValidatingBinderFactory())); + assertThat(processor.resolveArgument(paramStringNotRequired, mavContainer, + webRequest, new ValidatingBinderFactory())).isNull(); } @Test // SPR-13417 @@ -276,8 +272,8 @@ public class RequestResponseBodyMethodProcessorMockTests { servletRequest.setContent(new byte[0]); given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true); given(stringMessageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false); - assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, - webRequest, new ValidatingBinderFactory())); + assertThat(processor.resolveArgument(paramStringNotRequired, mavContainer, + webRequest, new ValidatingBinderFactory())).isNull(); } @Test @@ -286,8 +282,8 @@ public class RequestResponseBodyMethodProcessorMockTests { servletRequest.setContent("body".getBytes()); given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true); given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn("body"); - assertEquals(Optional.of("body"), processor.resolveArgument(paramOptionalString, mavContainer, - webRequest, new ValidatingBinderFactory())); + assertThat(processor.resolveArgument(paramOptionalString, mavContainer, + webRequest, new ValidatingBinderFactory())).isEqualTo(Optional.of("body")); } @Test @@ -295,7 +291,7 @@ public class RequestResponseBodyMethodProcessorMockTests { servletRequest.setContentType("text/plain"); servletRequest.setContent(new byte[0]); given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true); - assertEquals(Optional.empty(), processor.resolveArgument(paramOptionalString, mavContainer, webRequest, new ValidatingBinderFactory())); + assertThat(processor.resolveArgument(paramOptionalString, mavContainer, webRequest, new ValidatingBinderFactory())).isEqualTo(Optional.empty()); } @Test @@ -303,8 +299,8 @@ public class RequestResponseBodyMethodProcessorMockTests { servletRequest.setContent(new byte[0]); given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true); given(stringMessageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false); - assertEquals(Optional.empty(), processor.resolveArgument(paramOptionalString, mavContainer, - webRequest, new ValidatingBinderFactory())); + assertThat(processor.resolveArgument(paramOptionalString, mavContainer, + webRequest, new ValidatingBinderFactory())).isEqualTo(Optional.empty()); } @Test @@ -319,7 +315,7 @@ public class RequestResponseBodyMethodProcessorMockTests { processor.handleReturnValue(body, returnTypeString, mavContainer, webRequest); - assertTrue("The requestHandled flag wasn't set", mavContainer.isRequestHandled()); + assertThat(mavContainer.isRequestHandled()).as("The requestHandled flag wasn't set").isTrue(); verify(stringMessageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); } @@ -335,7 +331,7 @@ public class RequestResponseBodyMethodProcessorMockTests { processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest); - assertTrue(mavContainer.isRequestHandled()); + assertThat(mavContainer.isRequestHandled()).isTrue(); verify(stringMessageConverter).write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); } @@ -379,7 +375,7 @@ public class RequestResponseBodyMethodProcessorMockTests { then(resourceMessageConverter).should(times(1)).write(any(ByteArrayResource.class), eq(MediaType.APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class)); - assertEquals(200, servletResponse.getStatus()); + assertThat(servletResponse.getStatus()).isEqualTo(200); } @Test // SPR-9841 @@ -396,7 +392,7 @@ public class RequestResponseBodyMethodProcessorMockTests { processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest); - assertTrue(mavContainer.isRequestHandled()); + assertThat(mavContainer.isRequestHandled()).isTrue(); verify(stringMessageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); } @@ -413,7 +409,7 @@ public class RequestResponseBodyMethodProcessorMockTests { then(resourceRegionMessageConverter).should(times(1)).write( anyCollection(), eq(MediaType.APPLICATION_OCTET_STREAM), argThat(outputMessage -> "bytes".equals(outputMessage.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES)))); - assertEquals(206, servletResponse.getStatus()); + assertThat(servletResponse.getStatus()).isEqualTo(206); } @Test @@ -428,7 +424,7 @@ public class RequestResponseBodyMethodProcessorMockTests { then(resourceRegionMessageConverter).should(never()).write( anyCollection(), eq(MediaType.APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class)); - assertEquals(416, servletResponse.getStatus()); + assertThat(servletResponse.getStatus()).isEqualTo(416); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java index a8ded42cbca..1d1c8da62d3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java @@ -70,13 +70,9 @@ import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import org.springframework.web.util.WebUtils; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; 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; -import static org.junit.Assert.assertTrue; /** * Test fixture for a {@link RequestResponseBodyMethodProcessor} with @@ -139,9 +135,9 @@ public class RequestResponseBodyMethodProcessorTests { List result = (List) processor.resolveArgument( paramGenericList, container, request, factory); - assertNotNull(result); - assertEquals("Jad", result.get(0).getName()); - assertEquals("Robert", result.get(1).getName()); + assertThat(result).isNotNull(); + assertThat(result.get(0).getName()).isEqualTo("Jad"); + assertThat(result.get(1).getName()).isEqualTo("Robert"); } @Test @@ -159,9 +155,9 @@ public class RequestResponseBodyMethodProcessorTests { MultiValueMap result = (MultiValueMap) processor.resolveArgument( paramMultiValueMap, container, request, factory); - assertNotNull(result); - assertEquals("apple", result.getFirst("fruit")); - assertEquals("kale", result.getFirst("vegetable")); + assertThat(result).isNotNull(); + assertThat(result.getFirst("fruit")).isEqualTo("apple"); + assertThat(result.getFirst("vegetable")).isEqualTo("kale"); } @Test @@ -177,8 +173,8 @@ public class RequestResponseBodyMethodProcessorTests { SimpleBean result = (SimpleBean) processor.resolveArgument( paramSimpleBean, container, request, factory); - assertNotNull(result); - assertEquals("Jad", result.getName()); + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo("Jad"); } @Test @@ -194,8 +190,8 @@ public class RequestResponseBodyMethodProcessorTests { String result = (String) processor.resolveArgument( paramString, container, request, factory); - assertNotNull(result); - assertEquals("foobarbaz", result); + assertThat(result).isNotNull(); + assertThat(result).isEqualTo("foobarbaz"); } @Test // SPR-9942 @@ -217,8 +213,8 @@ public class RequestResponseBodyMethodProcessorTests { List advice = Collections.singletonList(new EmptyRequestBodyAdvice()); RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters, advice); String arg = (String) processor.resolveArgument(paramString, container, request, factory); - assertNotNull(arg); - assertEquals("default value for empty body", arg); + assertThat(arg).isNotNull(); + assertThat(arg).isEqualTo("default value for empty body"); } @Test // SPR-9964 @@ -237,8 +233,8 @@ public class RequestResponseBodyMethodProcessorTests { SimpleBean result = (SimpleBean) processor.resolveArgument(methodParam, container, request, factory); - assertNotNull(result); - assertEquals("Jad", result.getName()); + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo("Jad"); } @Test // SPR-14470 @@ -259,9 +255,9 @@ public class RequestResponseBodyMethodProcessorTests { List result = (List) processor.resolveArgument( methodParam, container, request, factory); - assertNotNull(result); - assertEquals("Jad", result.get(0).getName()); - assertEquals("Robert", result.get(1).getName()); + assertThat(result).isNotNull(); + assertThat(result.get(0).getName()).isEqualTo("Jad"); + assertThat(result.get(1).getName()).isEqualTo("Robert"); } @Test // SPR-11225 @@ -282,8 +278,8 @@ public class RequestResponseBodyMethodProcessorTests { SimpleBean result = (SimpleBean) processor.resolveArgument(methodParam, container, request, factory); - assertNotNull(result); - assertEquals("Jad", result.getName()); + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo("Jad"); } @Test // SPR-9160 @@ -297,7 +293,7 @@ public class RequestResponseBodyMethodProcessorTests { processor.writeWithMessageConverters("Foo", returnTypeString, request); - assertEquals("application/json;charset=UTF-8", servletResponse.getHeader("Content-Type")); + assertThat(servletResponse.getHeader("Content-Type")).isEqualTo("application/json;charset=UTF-8"); } @Test @@ -309,8 +305,8 @@ public class RequestResponseBodyMethodProcessorTests { RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters); processor.handleReturnValue("Foo", returnTypeString, container, request); - assertEquals("text/plain;charset=ISO-8859-1", servletResponse.getHeader("Content-Type")); - assertEquals("Foo", servletResponse.getContentAsString()); + assertThat(servletResponse.getHeader("Content-Type")).isEqualTo("text/plain;charset=ISO-8859-1"); + assertThat(servletResponse.getContentAsString()).isEqualTo("Foo"); } @Test // SPR-13423 @@ -325,8 +321,8 @@ public class RequestResponseBodyMethodProcessorTests { RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters); processor.handleReturnValue(new StringBuilder("Foo"), returnType, container, request); - assertEquals("text/plain;charset=ISO-8859-1", servletResponse.getHeader("Content-Type")); - assertEquals("Foo", servletResponse.getContentAsString()); + assertThat(servletResponse.getHeader("Content-Type")).isEqualTo("text/plain;charset=ISO-8859-1"); + assertThat(servletResponse.getContentAsString()).isEqualTo("Foo"); } @Test @@ -340,7 +336,7 @@ public class RequestResponseBodyMethodProcessorTests { processor.writeWithMessageConverters("Foo", returnTypeString, request); - assertEquals("text/plain;charset=UTF-8", servletResponse.getHeader("Content-Type")); + assertThat(servletResponse.getHeader("Content-Type")).isEqualTo("text/plain;charset=UTF-8"); } // SPR-12894 @@ -359,7 +355,7 @@ public class RequestResponseBodyMethodProcessorTests { ClassPathResource resource = new ClassPathResource("logo.jpg", getClass()); processor.writeWithMessageConverters(resource, returnType, this.request); - assertEquals("image/jpeg", this.servletResponse.getHeader("Content-Type")); + assertThat(this.servletResponse.getHeader("Content-Type")).isEqualTo("image/jpeg"); } // SPR-13135 @@ -414,7 +410,7 @@ public class RequestResponseBodyMethodProcessorTests { RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters); - assertTrue("Failed to recognize type-level @ResponseBody", processor.supportsReturnType(returnType)); + assertThat(processor.supportsReturnType(returnType)).as("Failed to recognize type-level @ResponseBody").isTrue(); } @Test @@ -427,7 +423,7 @@ public class RequestResponseBodyMethodProcessorTests { RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters); - assertTrue("Failed to recognize type-level @RestController", processor.supportsReturnType(returnType)); + assertThat(processor.supportsReturnType(returnType)).as("Failed to recognize type-level @RestController").isTrue(); } @Test @@ -446,9 +442,9 @@ public class RequestResponseBodyMethodProcessorTests { processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request); String content = this.servletResponse.getContentAsString(); - assertFalse(content.contains("\"withView1\":\"with\"")); - assertTrue(content.contains("\"withView2\":\"with\"")); - assertFalse(content.contains("\"withoutView\":\"without\"")); + assertThat(content.contains("\"withView1\":\"with\"")).isFalse(); + assertThat(content.contains("\"withView2\":\"with\"")).isTrue(); + assertThat(content.contains("\"withoutView\":\"without\"")).isFalse(); } @Test @@ -467,9 +463,9 @@ public class RequestResponseBodyMethodProcessorTests { processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request); String content = this.servletResponse.getContentAsString(); - assertFalse(content.contains("\"withView1\":\"with\"")); - assertTrue(content.contains("\"withView2\":\"with\"")); - assertFalse(content.contains("\"withoutView\":\"without\"")); + assertThat(content.contains("\"withView1\":\"with\"")).isFalse(); + assertThat(content.contains("\"withView2\":\"with\"")).isTrue(); + assertThat(content.contains("\"withoutView\":\"without\"")).isFalse(); } @Test // SPR-12149 @@ -488,9 +484,9 @@ public class RequestResponseBodyMethodProcessorTests { processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request); String content = this.servletResponse.getContentAsString(); - assertFalse(content.contains("with")); - assertTrue(content.contains("with")); - assertFalse(content.contains("without")); + assertThat(content.contains("with")).isFalse(); + assertThat(content.contains("with")).isTrue(); + assertThat(content.contains("without")).isFalse(); } @Test // SPR-12149 @@ -509,9 +505,9 @@ public class RequestResponseBodyMethodProcessorTests { processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request); String content = this.servletResponse.getContentAsString(); - assertFalse(content.contains("with")); - assertTrue(content.contains("with")); - assertFalse(content.contains("without")); + assertThat(content.contains("with")).isFalse(); + assertThat(content.contains("with")).isTrue(); + assertThat(content.contains("without")).isFalse(); } @Test // SPR-12501 @@ -530,14 +526,13 @@ public class RequestResponseBodyMethodProcessorTests { RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor( converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice())); - @SuppressWarnings("unchecked") JacksonViewBean result = (JacksonViewBean) processor.resolveArgument(methodParameter, this.container, this.request, this.factory); - assertNotNull(result); - assertEquals("with", result.getWithView1()); - assertNull(result.getWithView2()); - assertNull(result.getWithoutView()); + assertThat(result).isNotNull(); + assertThat(result.getWithView1()).isEqualTo("with"); + assertThat(result.getWithView2()).isNull(); + assertThat(result.getWithoutView()).isNull(); } @Test // SPR-12501 @@ -560,11 +555,11 @@ public class RequestResponseBodyMethodProcessorTests { HttpEntity result = (HttpEntity) processor.resolveArgument( methodParameter, this.container, this.request, this.factory); - assertNotNull(result); - assertNotNull(result.getBody()); - assertEquals("with", result.getBody().getWithView1()); - assertNull(result.getBody().getWithView2()); - assertNull(result.getBody().getWithoutView()); + assertThat(result).isNotNull(); + assertThat(result.getBody()).isNotNull(); + assertThat(result.getBody().getWithView1()).isEqualTo("with"); + assertThat(result.getBody().getWithView2()).isNull(); + assertThat(result.getBody().getWithoutView()).isNull(); } @Test // SPR-12501 @@ -586,14 +581,13 @@ public class RequestResponseBodyMethodProcessorTests { RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor( converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice())); - @SuppressWarnings("unchecked") JacksonViewBean result = (JacksonViewBean) processor.resolveArgument(methodParameter, this.container, this.request, this.factory); - assertNotNull(result); - assertEquals("with", result.getWithView1()); - assertNull(result.getWithView2()); - assertNull(result.getWithoutView()); + assertThat(result).isNotNull(); + assertThat(result.getWithView1()).isEqualTo("with"); + assertThat(result.getWithView2()).isNull(); + assertThat(result.getWithoutView()).isNull(); } @Test // SPR-12501 @@ -619,11 +613,11 @@ public class RequestResponseBodyMethodProcessorTests { HttpEntity result = (HttpEntity) processor.resolveArgument(methodParameter, this.container, this.request, this.factory); - assertNotNull(result); - assertNotNull(result.getBody()); - assertEquals("with", result.getBody().getWithView1()); - assertNull(result.getBody().getWithView2()); - assertNull(result.getBody().getWithoutView()); + assertThat(result).isNotNull(); + assertThat(result.getBody()).isNotNull(); + assertThat(result.getBody().getWithView1()).isEqualTo("with"); + assertThat(result.getBody().getWithView2()).isNull(); + assertThat(result.getBody().getWithoutView()).isNull(); } @Test // SPR-12811 @@ -640,8 +634,8 @@ public class RequestResponseBodyMethodProcessorTests { processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request); String content = this.servletResponse.getContentAsString(); - assertTrue(content.contains("\"type\":\"foo\"")); - assertTrue(content.contains("\"type\":\"bar\"")); + assertThat(content.contains("\"type\":\"foo\"")).isTrue(); + assertThat(content.contains("\"type\":\"bar\"")).isTrue(); } @Test // SPR-13318 @@ -658,8 +652,8 @@ public class RequestResponseBodyMethodProcessorTests { processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request); String content = this.servletResponse.getContentAsString(); - assertTrue(content.contains("\"id\":123")); - assertTrue(content.contains("\"name\":\"foo\"")); + assertThat(content.contains("\"id\":123")).isTrue(); + assertThat(content.contains("\"name\":\"foo\"")).isTrue(); } @Test // SPR-13318 @@ -676,10 +670,10 @@ public class RequestResponseBodyMethodProcessorTests { processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request); String content = this.servletResponse.getContentAsString(); - assertTrue(content.contains("\"id\":123")); - assertTrue(content.contains("\"name\":\"foo\"")); - assertTrue(content.contains("\"id\":456")); - assertTrue(content.contains("\"name\":\"bar\"")); + assertThat(content.contains("\"id\":123")).isTrue(); + assertThat(content.contains("\"name\":\"foo\"")).isTrue(); + assertThat(content.contains("\"id\":456")).isTrue(); + assertThat(content.contains("\"name\":\"bar\"")).isTrue(); } @Test // SPR-13631 @@ -695,7 +689,7 @@ public class RequestResponseBodyMethodProcessorTests { Object returnValue = new JacksonController().defaultCharset(); processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request); - assertEquals("UTF-8", this.servletResponse.getCharacterEncoding()); + assertThat(this.servletResponse.getCharacterEncoding()).isEqualTo("UTF-8"); } @Test // SPR-14520 @@ -714,7 +708,7 @@ public class RequestResponseBodyMethodProcessorTests { String value = (String) processor.readWithMessageConverters( this.request, methodParameter, methodParameter.getGenericParameterType()); - assertEquals("foo", value); + assertThat(value).isEqualTo("foo"); } private void assertContentDisposition(RequestResponseBodyMethodProcessor processor, @@ -725,11 +719,10 @@ public class RequestResponseBodyMethodProcessorTests { String header = servletResponse.getHeader("Content-Disposition"); if (expectContentDisposition) { - assertEquals("Expected 'Content-Disposition' header. Use case: '" + comment + "'", - "inline;filename=f.txt", header); + assertThat(header).as("Expected 'Content-Disposition' header. Use case: '" + comment + "'").isEqualTo("inline;filename=f.txt"); } else { - assertNull("Did not expect 'Content-Disposition' header. Use case: '" + comment + "'", header); + assertThat(header).as("Did not expect 'Content-Disposition' header. Use case: '" + comment + "'").isNull(); } this.servletRequest = new MockHttpServletRequest(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandlerTests.java index b4cd27c9ffd..20d0b884906 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandlerTests.java @@ -44,12 +44,7 @@ import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.method.support.ModelAndViewContainer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -94,35 +89,35 @@ public class ResponseBodyEmitterReturnValueHandlerTests { @Test public void supportsReturnTypes() throws Exception { - assertTrue(this.handler.supportsReturnType( - on(TestController.class).resolveReturnType(ResponseBodyEmitter.class))); + assertThat(this.handler.supportsReturnType( + on(TestController.class).resolveReturnType(ResponseBodyEmitter.class))).isTrue(); - assertTrue(this.handler.supportsReturnType( - on(TestController.class).resolveReturnType(SseEmitter.class))); + assertThat(this.handler.supportsReturnType( + on(TestController.class).resolveReturnType(SseEmitter.class))).isTrue(); - assertTrue(this.handler.supportsReturnType( - on(TestController.class).resolveReturnType(ResponseEntity.class, ResponseBodyEmitter.class))); + assertThat(this.handler.supportsReturnType( + on(TestController.class).resolveReturnType(ResponseEntity.class, ResponseBodyEmitter.class))).isTrue(); - assertTrue(this.handler.supportsReturnType( - on(TestController.class).resolveReturnType(Flux.class, String.class))); + assertThat(this.handler.supportsReturnType( + on(TestController.class).resolveReturnType(Flux.class, String.class))).isTrue(); - assertTrue(this.handler.supportsReturnType( + assertThat(this.handler.supportsReturnType( on(TestController.class).resolveReturnType(forClassWithGenerics(ResponseEntity.class, - forClassWithGenerics(Flux.class, String.class))))); + forClassWithGenerics(Flux.class, String.class))))).isTrue(); } @Test public void doesNotSupportReturnTypes() throws Exception { - assertFalse(this.handler.supportsReturnType( - on(TestController.class).resolveReturnType(ResponseEntity.class, String.class))); + assertThat(this.handler.supportsReturnType( + on(TestController.class).resolveReturnType(ResponseEntity.class, String.class))).isFalse(); - assertFalse(this.handler.supportsReturnType( + assertThat(this.handler.supportsReturnType( on(TestController.class).resolveReturnType(forClassWithGenerics(ResponseEntity.class, - forClassWithGenerics(AtomicReference.class, String.class))))); + forClassWithGenerics(AtomicReference.class, String.class))))).isFalse(); - assertFalse(this.handler.supportsReturnType( - on(TestController.class).resolveReturnType(ResponseEntity.class))); + assertThat(this.handler.supportsReturnType( + on(TestController.class).resolveReturnType(ResponseEntity.class))).isFalse(); } @Test @@ -131,8 +126,8 @@ public class ResponseBodyEmitterReturnValueHandlerTests { ResponseBodyEmitter emitter = new ResponseBodyEmitter(); this.handler.handleReturnValue(emitter, type, this.mavContainer, this.webRequest); - assertTrue(this.request.isAsyncStarted()); - assertEquals("", this.response.getContentAsString()); + assertThat(this.request.isAsyncStarted()).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo(""); SimpleBean bean = new SimpleBean(); bean.setId(1L); @@ -149,15 +144,15 @@ public class ResponseBodyEmitterReturnValueHandlerTests { bean.setName("Jason"); emitter.send(bean); - assertEquals("{\"id\":1,\"name\":\"Joe\"}\n" + + assertThat(this.response.getContentAsString()).isEqualTo(("{\"id\":1,\"name\":\"Joe\"}\n" + "{\"id\":2,\"name\":\"John\"}\n" + - "{\"id\":3,\"name\":\"Jason\"}", this.response.getContentAsString()); + "{\"id\":3,\"name\":\"Jason\"}")); MockAsyncContext asyncContext = (MockAsyncContext) this.request.getAsyncContext(); - assertNull(asyncContext.getDispatchedPath()); + assertThat(asyncContext.getDispatchedPath()).isNull(); emitter.complete(); - assertNotNull(asyncContext.getDispatchedPath()); + assertThat(asyncContext.getDispatchedPath()).isNotNull(); } @Test @@ -204,8 +199,8 @@ public class ResponseBodyEmitterReturnValueHandlerTests { SseEmitter emitter = new SseEmitter(); this.handler.handleReturnValue(emitter, type, this.mavContainer, this.webRequest); - assertTrue(this.request.isAsyncStarted()); - assertEquals(200, this.response.getStatus()); + assertThat(this.request.isAsyncStarted()).isTrue(); + assertThat(this.response.getStatus()).isEqualTo(200); SimpleBean bean1 = new SimpleBean(); bean1.setId(1L); @@ -218,14 +213,14 @@ public class ResponseBodyEmitterReturnValueHandlerTests { emitter.send(SseEmitter.event(). comment("a test").name("update").id("1").reconnectTime(5000L).data(bean1).data(bean2)); - assertEquals("text/event-stream;charset=UTF-8", this.response.getContentType()); - assertEquals(":a test\n" + + assertThat(this.response.getContentType()).isEqualTo("text/event-stream;charset=UTF-8"); + assertThat(this.response.getContentAsString()).isEqualTo((":a test\n" + "event:update\n" + "id:1\n" + "retry:5000\n" + "data:{\"id\":1,\"name\":\"Joe\"}\n" + "data:{\"id\":2,\"name\":\"John\"}\n" + - "\n", this.response.getContentAsString()); + "\n")); } @Test @@ -237,16 +232,16 @@ public class ResponseBodyEmitterReturnValueHandlerTests { EmitterProcessor processor = EmitterProcessor.create(); this.handler.handleReturnValue(processor, type, this.mavContainer, this.webRequest); - assertTrue(this.request.isAsyncStarted()); - assertEquals(200, this.response.getStatus()); + assertThat(this.request.isAsyncStarted()).isTrue(); + assertThat(this.response.getStatus()).isEqualTo(200); processor.onNext("foo"); processor.onNext("bar"); processor.onNext("baz"); processor.onComplete(); - assertEquals("text/event-stream;charset=UTF-8", this.response.getContentType()); - assertEquals("data:foo\n\ndata:bar\n\ndata:baz\n\n", this.response.getContentAsString()); + assertThat(this.response.getContentType()).isEqualTo("text/event-stream;charset=UTF-8"); + assertThat(this.response.getContentAsString()).isEqualTo("data:foo\n\ndata:bar\n\ndata:baz\n\n"); } @Test // gh-21972 @@ -258,15 +253,15 @@ public class ResponseBodyEmitterReturnValueHandlerTests { EmitterProcessor processor = EmitterProcessor.create(); this.handler.handleReturnValue(processor, type, this.mavContainer, this.webRequest); - assertTrue(this.request.isAsyncStarted()); + assertThat(this.request.isAsyncStarted()).isTrue(); IllegalStateException ex = new IllegalStateException("wah wah"); processor.onError(ex); processor.onComplete(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.webRequest); - assertSame(ex, asyncManager.getConcurrentResult()); - assertNull(this.response.getContentType()); + assertThat(asyncManager.getConcurrentResult()).isSameAs(ex); + assertThat(this.response.getContentType()).isNull(); } @Test @@ -277,10 +272,10 @@ public class ResponseBodyEmitterReturnValueHandlerTests { this.handler.handleReturnValue(entity, type, this.mavContainer, this.webRequest); emitter.complete(); - assertTrue(this.request.isAsyncStarted()); - assertEquals(200, this.response.getStatus()); - assertEquals("text/event-stream;charset=UTF-8", this.response.getContentType()); - assertEquals("bar", this.response.getHeader("foo")); + assertThat(this.request.isAsyncStarted()).isTrue(); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getContentType()).isEqualTo("text/event-stream;charset=UTF-8"); + assertThat(this.response.getHeader("foo")).isEqualTo("bar"); } @Test @@ -289,9 +284,9 @@ public class ResponseBodyEmitterReturnValueHandlerTests { ResponseEntity entity = ResponseEntity.noContent().header("foo", "bar").build(); this.handler.handleReturnValue(entity, type, this.mavContainer, this.webRequest); - assertFalse(this.request.isAsyncStarted()); - assertEquals(204, this.response.getStatus()); - assertEquals(Collections.singletonList("bar"), this.response.getHeaders("foo")); + assertThat(this.request.isAsyncStarted()).isFalse(); + assertThat(this.response.getStatus()).isEqualTo(204); + assertThat(this.response.getHeaders("foo")).isEqualTo(Collections.singletonList("bar")); } @Test @@ -303,16 +298,16 @@ public class ResponseBodyEmitterReturnValueHandlerTests { MethodParameter type = on(TestController.class).resolveReturnType(ResponseEntity.class, bodyType); this.handler.handleReturnValue(entity, type, this.mavContainer, this.webRequest); - assertTrue(this.request.isAsyncStarted()); - assertEquals(200, this.response.getStatus()); + assertThat(this.request.isAsyncStarted()).isTrue(); + assertThat(this.response.getStatus()).isEqualTo(200); processor.onNext("foo"); processor.onNext("bar"); processor.onNext("baz"); processor.onComplete(); - assertEquals("text/plain", this.response.getContentType()); - assertEquals("foobarbaz", this.response.getContentAsString()); + assertThat(this.response.getContentType()).isEqualTo("text/plain"); + assertThat(this.response.getContentAsString()).isEqualTo("foobarbaz"); } @Test // SPR-17076 @@ -324,10 +319,10 @@ public class ResponseBodyEmitterReturnValueHandlerTests { MethodParameter type = on(TestController.class).resolveReturnType(ResponseEntity.class, bodyType); this.handler.handleReturnValue(entity, type, this.mavContainer, this.webRequest); - assertTrue(this.request.isAsyncStarted()); - assertEquals(200, this.response.getStatus()); - assertEquals("bar", this.response.getHeader("x-foo")); - assertFalse(this.response.isCommitted()); + assertThat(this.request.isAsyncStarted()).isTrue(); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getHeader("x-foo")).isEqualTo("bar"); + assertThat(this.response.isCommitted()).isFalse(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java index 7c348b3437d..95c231299d6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java @@ -26,9 +26,9 @@ import org.mockito.MockitoAnnotations; import org.springframework.http.MediaType; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIOException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -169,7 +169,7 @@ public class ResponseBodyEmitterTests { verify(this.handler).onTimeout(captor.capture()); verify(this.handler).onCompletion(any()); - assertNotNull(captor.getValue()); + assertThat(captor.getValue()).isNotNull(); captor.getValue().run(); verify(runnable).run(); } @@ -185,7 +185,7 @@ public class ResponseBodyEmitterTests { Runnable runnable = mock(Runnable.class); this.emitter.onTimeout(runnable); - assertNotNull(captor.getValue()); + assertThat(captor.getValue()).isNotNull(); captor.getValue().run(); verify(runnable).run(); } @@ -200,7 +200,7 @@ public class ResponseBodyEmitterTests { verify(this.handler).onTimeout(any()); verify(this.handler).onCompletion(captor.capture()); - assertNotNull(captor.getValue()); + assertThat(captor.getValue()).isNotNull(); captor.getValue().run(); verify(runnable).run(); } @@ -216,7 +216,7 @@ public class ResponseBodyEmitterTests { Runnable runnable = mock(Runnable.class); this.emitter.onCompletion(runnable); - assertNotNull(captor.getValue()); + assertThat(captor.getValue()).isNotNull(); captor.getValue().run(); verify(runnable).run(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandlerTests.java index 52da8edb621..5eb22b84ada 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandlerTests.java @@ -61,11 +61,7 @@ import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.NoHandlerFoundException; import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; -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.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link ResponseEntityExceptionHandler}. @@ -107,7 +103,7 @@ public class ResponseEntityExceptionHandlerTests { Class[] paramTypes = method.getParameterTypes(); if (method.getName().startsWith("handle") && (paramTypes.length == 4)) { String name = paramTypes[0].getSimpleName(); - assertTrue("@ExceptionHandler is missing " + name, exceptionTypes.contains(paramTypes[0])); + assertThat(exceptionTypes.contains(paramTypes[0])).as("@ExceptionHandler is missing " + name).isTrue(); } } } @@ -118,7 +114,7 @@ public class ResponseEntityExceptionHandlerTests { Exception ex = new HttpRequestMethodNotSupportedException("GET", supported); ResponseEntity responseEntity = testException(ex); - assertEquals(EnumSet.of(HttpMethod.POST, HttpMethod.DELETE), responseEntity.getHeaders().getAllow()); + assertThat(responseEntity.getHeaders().getAllow()).isEqualTo(EnumSet.of(HttpMethod.POST, HttpMethod.DELETE)); } @Test @@ -127,7 +123,7 @@ public class ResponseEntityExceptionHandlerTests { Exception ex = new HttpMediaTypeNotSupportedException(MediaType.APPLICATION_JSON, acceptable); ResponseEntity responseEntity = testException(ex); - assertEquals(acceptable, responseEntity.getHeaders().getAccept()); + assertThat(responseEntity.getHeaders().getAccept()).isEqualTo(acceptable); } @Test @@ -224,11 +220,11 @@ public class ResponseEntityExceptionHandlerTests { resolver.afterPropertiesSet(); ServletRequestBindingException ex = new ServletRequestBindingException("message"); - assertNotNull(resolver.resolveException(this.servletRequest, this.servletResponse, null, ex)); + assertThat(resolver.resolveException(this.servletRequest, this.servletResponse, null, ex)).isNotNull(); - assertEquals(400, this.servletResponse.getStatus()); - assertEquals("error content", this.servletResponse.getContentAsString()); - assertEquals("someHeaderValue", this.servletResponse.getHeader("someHeader")); + assertThat(this.servletResponse.getStatus()).isEqualTo(400); + assertThat(this.servletResponse.getContentAsString()).isEqualTo("error content"); + assertThat(this.servletResponse.getHeader("someHeader")).isEqualTo("someHeaderValue"); } @Test @@ -242,7 +238,7 @@ public class ResponseEntityExceptionHandlerTests { resolver.afterPropertiesSet(); IllegalStateException ex = new IllegalStateException(new ServletRequestBindingException("message")); - assertNull(resolver.resolveException(this.servletRequest, this.servletResponse, null, ex)); + assertThat(resolver.resolveException(this.servletRequest, this.servletResponse, null, ex)).isNull(); } @Test @@ -256,9 +252,9 @@ public class ResponseEntityExceptionHandlerTests { servlet.init(new MockServletConfig()); servlet.service(this.servletRequest, this.servletResponse); - assertEquals(400, this.servletResponse.getStatus()); - assertEquals("error content", this.servletResponse.getContentAsString()); - assertEquals("someHeaderValue", this.servletResponse.getHeader("someHeader")); + assertThat(this.servletResponse.getStatus()).isEqualTo(400); + assertThat(this.servletResponse.getContentAsString()).isEqualTo("error content"); + assertThat(this.servletResponse.getHeader("someHeader")).isEqualTo("someHeaderValue"); } @Test @@ -274,8 +270,10 @@ public class ResponseEntityExceptionHandlerTests { servlet.service(this.servletRequest, this.servletResponse); } catch (ServletException ex) { - assertTrue(ex.getCause() instanceof IllegalStateException); - assertTrue(ex.getCause().getCause() instanceof ServletRequestBindingException); + boolean condition1 = ex.getCause() instanceof IllegalStateException; + assertThat(condition1).isTrue(); + boolean condition = ex.getCause().getCause() instanceof ServletRequestBindingException; + assertThat(condition).isTrue(); } } @@ -286,12 +284,12 @@ public class ResponseEntityExceptionHandlerTests { // SPR-9653 if (HttpStatus.INTERNAL_SERVER_ERROR.equals(responseEntity.getStatusCode())) { - assertSame(ex, this.servletRequest.getAttribute("javax.servlet.error.exception")); + assertThat(this.servletRequest.getAttribute("javax.servlet.error.exception")).isSameAs(ex); } this.defaultExceptionResolver.resolveException(this.servletRequest, this.servletResponse, null, ex); - assertEquals(this.servletResponse.getStatus(), responseEntity.getStatusCode().value()); + assertThat(responseEntity.getStatusCode().value()).isEqualTo(this.servletResponse.getStatus()); return responseEntity; } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java index 8ecfbe687ef..0c40c709c82 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java @@ -151,14 +151,8 @@ import org.springframework.web.servlet.support.RequestContextUtils; import org.springframework.web.servlet.view.AbstractView; import org.springframework.web.servlet.view.InternalResourceViewResolver; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; /** * @author Rossen Stoyanchev @@ -176,7 +170,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.setServletPath(""); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test"); } @Test @@ -188,7 +182,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.setServletPath(""); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test"); } @Test @@ -198,7 +192,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Invalid response status code", HttpServletResponse.SC_OK, response.getStatus()); + assertThat(response.getStatus()).as("Invalid response status code").isEqualTo(HttpServletResponse.SC_OK); } @Test @@ -208,8 +202,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); - assertTrue(webAppContext.isSingleton(RequiredParamController.class.getSimpleName())); + assertThat(response.getStatus()).as("Invalid response status code").isEqualTo(HttpServletResponse.SC_BAD_REQUEST); + assertThat(webAppContext.isSingleton(RequiredParamController.class.getSimpleName())).isTrue(); } @Test @@ -220,7 +214,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("id", "foo"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); + assertThat(response.getStatus()).as("Invalid response status code").isEqualTo(HttpServletResponse.SC_BAD_REQUEST); } @Test @@ -233,7 +227,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("header", "otherVal"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("val-true-otherVal", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("val-true-otherVal"); } @Test @@ -243,7 +237,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("null-false-null", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("null-false-null"); } @Test @@ -253,7 +247,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("foo--bar", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("foo--bar"); } @Test @@ -274,7 +268,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl finally { System.clearProperty("myHeader"); } - assertEquals("foo-bar-/myApp", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("foo-bar-/myApp"); } @Test @@ -293,7 +287,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("testBeanSet", "1", "2"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("[1, 2]-org.springframework.tests.sample.beans.TestBean", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("[1, 2]-org.springframework.tests.sample.beans.TestBean"); } @Test // SPR-12903 @@ -311,7 +305,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath/1"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(404, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(404); } @Test @@ -321,18 +315,18 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Invalid response status", HttpServletResponse.SC_METHOD_NOT_ALLOWED, response.getStatus()); + assertThat(response.getStatus()).as("Invalid response status").isEqualTo(HttpServletResponse.SC_METHOD_NOT_ALLOWED); String allowHeader = response.getHeader("Allow"); - assertNotNull("No Allow header", allowHeader); + assertThat(allowHeader).as("No Allow header").isNotNull(); Set allowedMethods = new HashSet<>(); allowedMethods.addAll(Arrays.asList(StringUtils.delimitedListToStringArray(allowHeader, ", "))); - assertEquals("Invalid amount of supported methods", 6, allowedMethods.size()); - assertTrue("PUT not allowed", allowedMethods.contains("PUT")); - assertTrue("DELETE not allowed", allowedMethods.contains("DELETE")); - assertTrue("HEAD not allowed", allowedMethods.contains("HEAD")); - assertTrue("TRACE not allowed", allowedMethods.contains("TRACE")); - assertTrue("OPTIONS not allowed", allowedMethods.contains("OPTIONS")); - assertTrue("POST not allowed", allowedMethods.contains("POST")); + assertThat(allowedMethods.size()).as("Invalid amount of supported methods").isEqualTo(6); + assertThat(allowedMethods.contains("PUT")).as("PUT not allowed").isTrue(); + assertThat(allowedMethods.contains("DELETE")).as("DELETE not allowed").isTrue(); + assertThat(allowedMethods.contains("HEAD")).as("HEAD not allowed").isTrue(); + assertThat(allowedMethods.contains("TRACE")).as("TRACE not allowed").isTrue(); + assertThat(allowedMethods.contains("OPTIONS")).as("OPTIONS not allowed").isTrue(); + assertThat(allowedMethods.contains("POST")).as("POST not allowed").isTrue(); } @Test @@ -348,8 +342,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl EmptyParameterListHandlerMethodController.called = false; getServlet().service(request, response); - assertTrue(EmptyParameterListHandlerMethodController.called); - assertEquals("", response.getContentAsString()); + assertThat(EmptyParameterListHandlerMethodController.called).isTrue(); + assertThat(response.getContentAsString()).isEqualTo(""); } @SuppressWarnings("rawtypes") @@ -362,22 +356,22 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPage"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("page1", request.getAttribute("viewName")); + assertThat(request.getAttribute("viewName")).isEqualTo("page1"); HttpSession session = request.getSession(); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); + assertThat(session.getAttribute("object1") != null).isTrue(); + assertThat(session.getAttribute("object2") != null).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object1")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object2")).isTrue(); request = new MockHttpServletRequest("POST", "/myPage"); request.setSession(session); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("page2", request.getAttribute("viewName")); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); + assertThat(request.getAttribute("viewName")).isEqualTo("page2"); + assertThat(session.getAttribute("object1") != null).isTrue(); + assertThat(session.getAttribute("object2") != null).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object1")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object2")).isTrue(); } @SuppressWarnings("rawtypes") @@ -394,22 +388,22 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPage"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("page1", request.getAttribute("viewName")); + assertThat(request.getAttribute("viewName")).isEqualTo("page1"); HttpSession session = request.getSession(); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); + assertThat(session.getAttribute("object1") != null).isTrue(); + assertThat(session.getAttribute("object2") != null).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object1")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object2")).isTrue(); request = new MockHttpServletRequest("POST", "/myPage"); request.setSession(session); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("page2", request.getAttribute("viewName")); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); + assertThat(request.getAttribute("viewName")).isEqualTo("page2"); + assertThat(session.getAttribute("object1") != null).isTrue(); + assertThat(session.getAttribute("object2") != null).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object1")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object2")).isTrue(); } @SuppressWarnings("rawtypes") @@ -422,24 +416,24 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPage"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("page1", request.getAttribute("viewName")); + assertThat(request.getAttribute("viewName")).isEqualTo("page1"); HttpSession session = request.getSession(); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - assertTrue(((Map) session.getAttribute("model")).containsKey("testBeanList")); + assertThat(session.getAttribute("object1") != null).isTrue(); + assertThat(session.getAttribute("object2") != null).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object1")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object2")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("testBeanList")).isTrue(); request = new MockHttpServletRequest("POST", "/myPage"); request.setSession(session); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("page2", request.getAttribute("viewName")); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - assertTrue(((Map) session.getAttribute("model")).containsKey("testBeanList")); + assertThat(request.getAttribute("viewName")).isEqualTo("page2"); + assertThat(session.getAttribute("object1") != null).isTrue(); + assertThat(session.getAttribute("object2") != null).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object1")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object2")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("testBeanList")).isTrue(); } @SuppressWarnings("rawtypes") @@ -452,24 +446,24 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPage"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("page1", request.getAttribute("viewName")); + assertThat(request.getAttribute("viewName")).isEqualTo("page1"); HttpSession session = request.getSession(); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - assertTrue(((Map) session.getAttribute("model")).containsKey("testBeanList")); + assertThat(session.getAttribute("object1") != null).isTrue(); + assertThat(session.getAttribute("object2") != null).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object1")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object2")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("testBeanList")).isTrue(); request = new MockHttpServletRequest("POST", "/myPage"); request.setSession(session); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("page2", request.getAttribute("viewName")); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - assertTrue(((Map) session.getAttribute("model")).containsKey("testBeanList")); + assertThat(request.getAttribute("viewName")).isEqualTo("page2"); + assertThat(session.getAttribute("object1") != null).isTrue(); + assertThat(session.getAttribute("object2") != null).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object1")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("object2")).isTrue(); + assertThat(((Map) session.getAttribute("model")).containsKey("testBeanList")).isTrue(); } @Test @@ -495,7 +489,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("param1", "value1"); request.addParameter("param2", "2"); getServlet().service(request, response); - assertEquals("test", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test"); request = new MockHttpServletRequest("GET", "/myPath2.do"); request.addParameter("param1", "value1"); @@ -504,7 +498,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.setCookies(new Cookie("cookie1", "3")); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-value1-2-10-3", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test-value1-2-10-3"); request = new MockHttpServletRequest("GET", "/myPath3.do"); request.addParameter("param1", "value1"); @@ -513,7 +507,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("age", "2"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-name1-2", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test-name1-2"); request = new MockHttpServletRequest("GET", "/myPath4.do"); request.addParameter("param1", "value1"); @@ -522,7 +516,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("age", "value2"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-name1-typeMismatch", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test-name1-typeMismatch"); } @Test @@ -536,7 +530,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("age", "value2"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView-name1-typeMismatch-tb1-myValue"); } @Test @@ -550,7 +544,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("age", "value2"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myPath-name1-typeMismatch-tb1-myValue-yourValue", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myPath-name1-typeMismatch-tb1-myValue-yourValue"); } @Test @@ -564,7 +558,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("age", "value2"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView-name1-typeMismatch-tb1-myValue"); } @Test @@ -583,7 +577,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("age", "value2"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView-name1-typeMismatch-tb1-myValue"); } @Test @@ -601,7 +595,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("date", "2007-10-02"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue"); } @Test @@ -622,7 +616,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("date", "2007-10-02"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView-Integer:10-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView-Integer:10-typeMismatch-tb1-myOriginalValue"); request = new MockHttpServletRequest("GET", "/myOtherPath.do"); request.addParameter("defaultName", "10"); @@ -630,7 +624,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("date", "2007-10-02"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView-myName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView-myName-typeMismatch-tb1-myOriginalValue"); request = new MockHttpServletRequest("GET", "/myThirdPath.do"); request.addParameter("defaultName", "10"); @@ -638,7 +632,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("date", "2007-10-02"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView-special-99-special-99", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView-special-99-special-99"); } @Test @@ -653,7 +647,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("date", "2007-10-02"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue"); } @Test @@ -668,7 +662,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("date", "2007-10-02"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue"); } @Test @@ -687,47 +681,47 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); HttpSession session = request.getSession(); getServlet().service(request, response); - assertEquals("myView", response.getContentAsString()); - assertSame(servletContext, request.getAttribute("servletContext")); - assertSame(servletConfig, request.getAttribute("servletConfig")); - assertSame(session.getId(), request.getAttribute("sessionId")); - assertSame(request.getRequestURI(), request.getAttribute("requestUri")); - assertSame(request.getLocale(), request.getAttribute("locale")); + assertThat(response.getContentAsString()).isEqualTo("myView"); + assertThat(request.getAttribute("servletContext")).isSameAs(servletContext); + assertThat(request.getAttribute("servletConfig")).isSameAs(servletConfig); + assertThat(request.getAttribute("sessionId")).isSameAs(session.getId()); + assertThat(request.getAttribute("requestUri")).isSameAs(request.getRequestURI()); + assertThat(request.getAttribute("locale")).isSameAs(request.getLocale()); request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); response = new MockHttpServletResponse(); session = request.getSession(); getServlet().service(request, response); - assertEquals("myView", response.getContentAsString()); - assertSame(servletContext, request.getAttribute("servletContext")); - assertSame(servletConfig, request.getAttribute("servletConfig")); - assertSame(session.getId(), request.getAttribute("sessionId")); - assertSame(request.getRequestURI(), request.getAttribute("requestUri")); + assertThat(response.getContentAsString()).isEqualTo("myView"); + assertThat(request.getAttribute("servletContext")).isSameAs(servletContext); + assertThat(request.getAttribute("servletConfig")).isSameAs(servletConfig); + assertThat(request.getAttribute("sessionId")).isSameAs(session.getId()); + assertThat(request.getAttribute("requestUri")).isSameAs(request.getRequestURI()); request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); request.addParameter("view", "other"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myOtherView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myOtherView"); request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); request.addParameter("view", "my"); request.addParameter("lang", "de"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myLangView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myLangView"); request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); request.addParameter("surprise", "!"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("mySurpriseView"); MyParameterDispatchingController deserialized = (MyParameterDispatchingController) SerializationTestUtils.serializeAndDeserialize( webAppContext.getBean(MyParameterDispatchingController.class.getSimpleName())); - assertNotNull(deserialized.request); - assertNotNull(deserialized.session); + assertThat(deserialized.request).isNotNull(); + assertThat(deserialized.session).isNotNull(); } @Test @@ -738,22 +732,22 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myApp/myHandle"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView"); request = new MockHttpServletRequest("GET", "/myApp/myOther"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myOtherView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myOtherView"); request = new MockHttpServletRequest("GET", "/myApp/myLang"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myLangView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myLangView"); request = new MockHttpServletRequest("GET", "/myApp/surprise.do"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("mySurpriseView"); } @Test @@ -764,22 +758,22 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myApp/myHandle"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView"); request = new MockHttpServletRequest("GET", "/yourApp/myOther"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myOtherView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myOtherView"); request = new MockHttpServletRequest("GET", "/hisApp/myLang"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myLangView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myLangView"); request = new MockHttpServletRequest("GET", "/herApp/surprise.do"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("mySurpriseView"); } @Test @@ -791,7 +785,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.setUserPrincipal(new OtherPrincipal()); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myView", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myView"); } @Test @@ -809,13 +803,13 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bogus-unmapped"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(404, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(404); request = new MockHttpServletRequest("GET", ""); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("get", response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentAsString()).isEqualTo("get"); } @Test @@ -825,12 +819,12 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("get", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("get"); request = new MockHttpServletRequest("GET", ""); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("get", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("get"); } @Test @@ -840,7 +834,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/dir/myPath1.do"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("method1", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("method1"); } @Test @@ -854,8 +848,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Accept", "text/*, */*"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals(requestBody, response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentAsString()).isEqualTo(requestBody); } @Test @@ -869,8 +863,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Accept", "text/*, */*"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals(requestBody, response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentAsString()).isEqualTo(requestBody); } @Test @@ -889,7 +883,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Accept", "application/pdf, application/msword"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(406, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(406); } @Test @@ -903,7 +897,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Accept", "*/*"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(requestBody, response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo(requestBody); } @Test @@ -920,8 +914,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Content-Type", "application/pdf"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(415, response.getStatus()); - assertNotNull("No Accept response header set", response.getHeader("Accept")); + assertThat(response.getStatus()).isEqualTo(415); + assertThat(response.getHeader("Accept")).as("No Accept response header set").isNotNull(); } @Test @@ -934,8 +928,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Content-Type", "text/plain; charset=utf-8"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals(requestBody, response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentAsString()).isEqualTo(requestBody); } @Test @@ -952,7 +946,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Content-Type", "application/pdf"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); + assertThat(response.getStatus()).as("Invalid response status code").isEqualTo(HttpServletResponse.SC_BAD_REQUEST); } @Test @@ -967,15 +961,15 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("MyRequestHeader", "MyValue"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(201, response.getStatus()); - assertEquals(requestBody, response.getContentAsString()); - assertEquals("MyValue", response.getHeader("MyResponseHeader")); + assertThat(response.getStatus()).isEqualTo(201); + assertThat(response.getContentAsString()).isEqualTo(requestBody); + assertThat(response.getHeader("MyResponseHeader")).isEqualTo("MyValue"); request = new MockHttpServletRequest("GET", "/bar"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("MyValue", response.getHeader("MyResponseHeader")); - assertEquals(404, response.getStatus()); + assertThat(response.getHeader("MyResponseHeader")).isEqualTo("MyValue"); + assertThat(response.getStatus()).isEqualTo(404); } @Test // SPR-16172 @@ -992,10 +986,10 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test-entity"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("application/xml", response.getHeader("Content-Type")); - assertEquals("" + - "Foo Bar", response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getHeader("Content-Type")).isEqualTo("application/xml"); + assertThat(response.getContentAsString()).isEqualTo(("" + + "Foo Bar")); } @Test // SPR-6877 @@ -1016,7 +1010,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Accept", "application/json, text/javascript, */*"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Invalid content-type", "application/json;charset=ISO-8859-1", response.getHeader("Content-Type")); + assertThat(response.getHeader("Content-Type")).as("Invalid content-type").isEqualTo("application/json;charset=ISO-8859-1"); } @Test @@ -1027,7 +1021,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Accept", "text/*, */*"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(200); } @Test @@ -1054,7 +1048,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Content-Type", "application/xml; charset=utf-8"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(400, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(400); } @@ -1066,19 +1060,19 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.setContentType("application/pdf"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("pdf", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("pdf"); request = new MockHttpServletRequest("POST", "/something"); request.setContentType("text/html"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("text", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("text"); request = new MockHttpServletRequest("POST", "/something"); request.setContentType("application/xml"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(415, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(415); } @Test @@ -1089,19 +1083,19 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.setContentType("application/pdf"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("pdf", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("pdf"); request = new MockHttpServletRequest("POST", "/something"); request.setContentType("text/html"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("text", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("text"); request = new MockHttpServletRequest("POST", "/something"); request.setContentType("application/xml"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(415, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(415); } @Test @@ -1112,13 +1106,13 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.setContentType("application/pdf"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("pdf", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("pdf"); request = new MockHttpServletRequest("POST", "/something"); request.setContentType("text/html"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("non-pdf", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("non-pdf"); } @Test @@ -1129,31 +1123,31 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Accept", "text/html"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("html", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("html"); request = new MockHttpServletRequest("GET", "/something"); request.addHeader("Accept", "application/xml"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("xml", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("xml"); request = new MockHttpServletRequest("GET", "/something"); request.addHeader("Accept", "application/xml, text/html"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("xml", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("xml"); request = new MockHttpServletRequest("GET", "/something"); request.addHeader("Accept", "text/html;q=0.9, application/xml"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("xml", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("xml"); request = new MockHttpServletRequest("GET", "/something"); request.addHeader("Accept", "application/msword"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(406, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(406); } @Test @@ -1179,40 +1173,40 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addHeader("Accept", "text/html"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("html", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("html"); request = new MockHttpServletRequest("GET", "/something"); request.addHeader("Accept", "application/xml"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("xml", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("xml"); request = new MockHttpServletRequest("GET", "/something"); request.addHeader("Accept", "application/xml, text/html"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("xml", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("xml"); request = new MockHttpServletRequest("GET", "/something"); request.addHeader("Accept", "text/html;q=0.9, application/xml"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("xml", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("xml"); request = new MockHttpServletRequest("GET", "/something"); request.addHeader("Accept", "application/msword"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(406, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(406); // SPR-16318 request = new MockHttpServletRequest("GET", "/something"); request.addHeader("Accept", "text/csv,application/problem+json"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(500, response.getStatus()); - assertEquals("application/problem+json", response.getContentType()); - assertEquals("{\"reason\":\"error\"}", response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(500); + assertThat(response.getContentType()).isEqualTo("application/problem+json"); + assertThat(response.getContentAsString()).isEqualTo("{\"reason\":\"error\"}"); } @Test @@ -1222,9 +1216,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/something"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("something", response.getContentAsString()); - assertEquals(201, response.getStatus()); - assertEquals("It's alive!", response.getErrorMessage()); + assertThat(response.getContentAsString()).isEqualTo("something"); + assertThat(response.getStatus()).isEqualTo(201); + assertThat(response.getErrorMessage()).isEqualTo("It's alive!"); } @Test @@ -1239,7 +1233,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myValue", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myValue"); } @@ -1251,7 +1245,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.setCookies(new Cookie("date", "2008-11-18")); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-2008", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test-2008"); } @Test @@ -1261,13 +1255,13 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("noParams", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("noParams"); request = new MockHttpServletRequest("GET", "/test"); request.addParameter("myParam", "42"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("myParam-42", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("myParam-42"); } @Test // SPR-9062 @@ -1277,8 +1271,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bug/EXISTING"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("Pattern", response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentAsString()).isEqualTo("Pattern"); } @Test @@ -1309,13 +1303,13 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("key1=value1,key2=value21", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("key1=value1,key2=value21"); request.setRequestURI("/multiValueMap"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("key1=[value1],key2=[value21,value22]", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("key1=[value1],key2=[value21,value22]"); } @Test @@ -1328,19 +1322,19 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Content-Type=text/html,Custom-Header=value21", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Content-Type=text/html,Custom-Header=value21"); request.setRequestURI("/multiValueMap"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Content-Type=[text/html],Custom-Header=[value21,value22]", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Content-Type=[text/html],Custom-Header=[value21,value22]"); request.setRequestURI("/httpHeaders"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Content-Type=[text/html],Custom-Header=[value21,value22]", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Content-Type=[text/html],Custom-Header=[value21,value22]"); } @@ -1351,13 +1345,13 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/handle"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("handle null", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("handle null"); request = new MockHttpServletRequest("GET", "/handle"); request.addParameter("p", "value"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("handle value", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("handle value"); } @Test @@ -1372,13 +1366,13 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/handle"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("handle null", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("handle null"); request = new MockHttpServletRequest("GET", "/handle"); request.addParameter("p", "value"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("handle value", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("handle value"); } @Test @@ -1388,7 +1382,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/handle"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("handle", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("handle"); } @@ -1399,7 +1393,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo/"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("templatePath", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("templatePath"); } /* @@ -1415,7 +1409,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl getServlet().service(request, response); - assertEquals("test-{foo=bar}", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test-{foo=bar}"); } @Test @@ -1427,7 +1421,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addFile(new MockMultipartFile("content", "Juergen".getBytes())); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Juergen", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Juergen"); } @Test @@ -1440,7 +1434,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("content", "Juergen"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Juergen", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Juergen"); } @Test @@ -1452,7 +1446,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addFile(new MockMultipartFile("content", "Juergen".getBytes())); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Juergen", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Juergen"); } @Test @@ -1465,7 +1459,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("content", "Juergen"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Juergen", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Juergen"); } @Test @@ -1478,7 +1472,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addFile(new MockMultipartFile("content", "Eva".getBytes())); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Juergen-Eva", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Juergen-Eva"); } @Test @@ -1492,7 +1486,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("content", "Eva"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Juergen-Eva", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Juergen-Eva"); } @Test @@ -1512,7 +1506,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("content", "1,2"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("1-2", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("1-2"); } @Test @@ -1522,7 +1516,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/t1/m2"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(405, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(405); } @Test // SPR-8536 @@ -1534,8 +1528,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("home", response.getForwardedUrl()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getForwardedUrl()).isEqualTo("home"); // Accept "*/*" request = new MockHttpServletRequest("GET", "/"); @@ -1543,8 +1537,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("home", response.getForwardedUrl()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getForwardedUrl()).isEqualTo("home"); // Accept "application/json" request = new MockHttpServletRequest("GET", "/"); @@ -1552,9 +1546,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("application/json;charset=ISO-8859-1", response.getHeader("Content-Type")); - assertEquals("homeJson", response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getHeader("Content-Type")).isEqualTo("application/json;charset=ISO-8859-1"); + assertThat(response.getContentAsString()).isEqualTo("homeJson"); } @Test @@ -1569,9 +1563,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl // POST -> bind error getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("messages/new", response.getForwardedUrl()); - assertTrue(RequestContextUtils.getOutputFlashMap(request).isEmpty()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getForwardedUrl()).isEqualTo("messages/new"); + assertThat(RequestContextUtils.getOutputFlashMap(request).isEmpty()).isTrue(); // POST -> success request = new MockHttpServletRequest("POST", "/messages"); @@ -1580,9 +1574,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(302, response.getStatus()); - assertEquals("/messages/1?name=value", response.getRedirectedUrl()); - assertEquals("yay!", RequestContextUtils.getOutputFlashMap(request).get("successMessage")); + assertThat(response.getStatus()).isEqualTo(302); + assertThat(response.getRedirectedUrl()).isEqualTo("/messages/1?name=value"); + assertThat(RequestContextUtils.getOutputFlashMap(request).get("successMessage")).isEqualTo("yay!"); // GET after POST request = new MockHttpServletRequest("GET", "/messages/1"); @@ -1591,9 +1585,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("Got: yay!", response.getContentAsString()); - assertTrue(RequestContextUtils.getOutputFlashMap(request).isEmpty()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentAsString()).isEqualTo("Got: yay!"); + assertThat(RequestContextUtils.getOutputFlashMap(request).isEmpty()).isTrue(); } @Test // SPR-15176 @@ -1606,9 +1600,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl getServlet().service(request, response); - assertEquals(302, response.getStatus()); - assertEquals("/messages/1?name=value", response.getRedirectedUrl()); - assertEquals("yay!", RequestContextUtils.getOutputFlashMap(request).get("successMessage")); + assertThat(response.getStatus()).isEqualTo(302); + assertThat(response.getRedirectedUrl()).isEqualTo("/messages/1?name=value"); + assertThat(RequestContextUtils.getOutputFlashMap(request).get("successMessage")).isEqualTo("yay!"); // GET after POST request = new MockHttpServletRequest("GET", "/messages/1"); @@ -1617,9 +1611,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("Got: yay!", response.getContentAsString()); - assertTrue(RequestContextUtils.getOutputFlashMap(request).isEmpty()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentAsString()).isEqualTo("Got: yay!"); + assertThat(RequestContextUtils.getOutputFlashMap(request).isEmpty()).isTrue(); } @Test @@ -1635,12 +1629,12 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("count:3", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("count:3"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("count:3", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("count:3"); } @Test @@ -1650,7 +1644,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Hello World!", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("Hello World!"); } @Test @@ -1659,10 +1653,10 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(new MockHttpServletRequest("POST", "/"), response); - assertEquals("Wrong status code", MockHttpServletResponse.SC_CREATED, response.getStatus()); - assertEquals("Wrong number of headers", 1, response.getHeaderNames().size()); - assertEquals("Wrong value for 'location' header", "/test/items/123", response.getHeader("location")); - assertEquals("Expected an empty content", 0, response.getContentLength()); + assertThat(response.getStatus()).as("Wrong status code").isEqualTo(MockHttpServletResponse.SC_CREATED); + assertThat(response.getHeaderNames().size()).as("Wrong number of headers").isEqualTo(1); + assertThat(response.getHeader("location")).as("Wrong value for 'location' header").isEqualTo("/test/items/123"); + assertThat(response.getContentLength()).as("Expected an empty content").isEqualTo(0); } @Test @@ -1671,9 +1665,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(new MockHttpServletRequest("POST", "/empty"), response); - assertEquals("Wrong status code", MockHttpServletResponse.SC_CREATED, response.getStatus()); - assertEquals("Wrong number of headers", 0, response.getHeaderNames().size()); - assertEquals("Expected an empty content", 0, response.getContentLength()); + assertThat(response.getStatus()).as("Wrong status code").isEqualTo(MockHttpServletResponse.SC_CREATED); + assertThat(response.getHeaderNames().size()).as("Wrong number of headers").isEqualTo(0); + assertThat(response.getContentLength()).as("Expected an empty content").isEqualTo(0); } @Test @@ -1693,10 +1687,10 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("text/html;charset=ISO-8859-1", response.getContentType()); - assertEquals("inline;filename=f.txt", response.getHeader("Content-Disposition")); - assertArrayEquals(content, response.getContentAsByteArray()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentType()).isEqualTo("text/html;charset=ISO-8859-1"); + assertThat(response.getHeader("Content-Disposition")).isEqualTo("inline;filename=f.txt"); + assertThat(response.getContentAsByteArray()).isEqualTo(content); } @Test @@ -1716,10 +1710,10 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("text/html;charset=ISO-8859-1", response.getContentType()); - assertNull(response.getHeader("Content-Disposition")); - assertArrayEquals(content, response.getContentAsByteArray()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentType()).isEqualTo("text/html;charset=ISO-8859-1"); + assertThat(response.getHeader("Content-Disposition")).isNull(); + assertThat(response.getContentAsByteArray()).isEqualTo(content); } @Test @@ -1739,10 +1733,10 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("text/html;charset=ISO-8859-1", response.getContentType()); - assertNull(response.getHeader("Content-Disposition")); - assertArrayEquals(content, response.getContentAsByteArray()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentType()).isEqualTo("text/html;charset=ISO-8859-1"); + assertThat(response.getHeader("Content-Disposition")).isNull(); + assertThat(response.getContentAsByteArray()).isEqualTo(content); } @Test @@ -1762,10 +1756,10 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("text/css;charset=ISO-8859-1", response.getContentType()); - assertNull(response.getHeader("Content-Disposition")); - assertArrayEquals(content, response.getContentAsByteArray()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentType()).isEqualTo("text/css;charset=ISO-8859-1"); + assertThat(response.getHeader("Content-Disposition")).isNull(); + assertThat(response.getContentAsByteArray()).isEqualTo(content); } @Test @@ -1776,8 +1770,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(422, response.getStatus()); - assertEquals("view", response.getForwardedUrl()); + assertThat(response.getStatus()).isEqualTo(422); + assertThat(response.getForwardedUrl()).isEqualTo("view"); } @Test // SPR-14796 @@ -1788,8 +1782,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(422, response.getStatus()); - assertEquals("view", response.getForwardedUrl()); + assertThat(response.getStatus()).isEqualTo(422); + assertThat(response.getForwardedUrl()).isEqualTo("view"); } @Test @@ -1800,20 +1794,20 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("MyValue", response.getHeader("MyResponseHeader")); - assertEquals(4, response.getContentLength()); - assertTrue(response.getContentAsByteArray().length == 0); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getHeader("MyResponseHeader")).isEqualTo("MyValue"); + assertThat(response.getContentLength()).isEqualTo(4); + assertThat(response.getContentAsByteArray().length == 0).isTrue(); // Now repeat with GET request = new MockHttpServletRequest("GET", "/baz"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("MyValue", response.getHeader("MyResponseHeader")); - assertEquals(4, response.getContentLength()); - assertEquals("body", response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getHeader("MyResponseHeader")).isEqualTo("MyValue"); + assertThat(response.getContentLength()).isEqualTo(4); + assertThat(response.getContentAsString()).isEqualTo("body"); } @Test @@ -1824,8 +1818,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("v1", response.getHeader("h1")); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getHeader("h1")).isEqualTo("v1"); } @Test @@ -1836,9 +1830,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("GET,HEAD,OPTIONS", response.getHeader("Allow")); - assertTrue(response.getContentAsByteArray().length == 0); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getHeader("Allow")).isEqualTo("GET,HEAD,OPTIONS"); + assertThat(response.getContentAsByteArray().length == 0).isTrue(); } @Test @@ -1850,7 +1844,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("param2", "true"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("value1-true-0", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("value1-true-0"); } @Test @@ -1863,7 +1857,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("param3", "3"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("value1-true-3", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("value1-true-3"); } @Test @@ -1876,7 +1870,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("param3", "3"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("value1-true-3", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("value1-true-3"); } @Test @@ -1889,7 +1883,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("optionalParam", "8"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("value1-true-8", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("value1-true-8"); } @Test @@ -1900,7 +1894,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("param1", "value1"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("1:value1-null-null", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("1:value1-null-null"); } @Test @@ -1912,7 +1906,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("param2", "x"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("1:value1-x-null", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("1:value1-x-null"); } @Test @@ -1924,7 +1918,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("param3", "0"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("1:null-true-0", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("1:null-true-0"); } @Test @@ -1935,7 +1929,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("param2", "x"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("2:null-x-null", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("2:null-x-null"); } @Test @@ -1948,7 +1942,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("param3", "3"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("value1-true-3", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("value1-true-3"); } @Test @@ -1960,7 +1954,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("param2", "x"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("value1-x-null", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("value1-x-null"); } @Test @@ -1973,7 +1967,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("_param2", "on"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("value1-true-0", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("value1-true-0"); } @Test @@ -1985,7 +1979,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("_param2", "on"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("value1-false-0", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("value1-false-0"); } @Test @@ -1998,7 +1992,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("!param2", "false"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("value1-true-0", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("value1-true-0"); } @Test @@ -2010,7 +2004,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("!param2", "false"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("value1-false-0", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("value1-false-0"); } @Test @@ -2021,7 +2015,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("date", "2010-01-01"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("2010-01-01", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("2010-01-01"); } @@ -2128,14 +2122,14 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl public void initBinder(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) { - assertNull(px); + assertThat(px).isNull(); } @ModelAttribute public void modelAttribute(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) { - assertNull(px); + assertThat(px).isNull(); } } @@ -2168,7 +2162,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl public void initBinder(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) { - assertNull(px); + assertThat(px).isNull(); } @Override @@ -2176,7 +2170,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl public void modelAttribute(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) { - assertNull(px); + assertThat(px).isNull(); } } @@ -2329,8 +2323,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @RequestMapping("/myPath.do") public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) { FieldError error = errors.getFieldError("age"); - assertNotNull("Must have field error for age property", error); - assertEquals("value2", error.getRejectedValue()); + assertThat(error).as("Must have field error for age property").isNotNull(); + assertThat(error.getRejectedValue()).isEqualTo("value2"); if (!model.containsKey("myKey")) { model.addAttribute("myKey", "myValue"); } @@ -2389,8 +2383,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl BindingResult errors, ModelMap model) { FieldError error = errors.getFieldError("age"); - assertNotNull("Must have field error for age property", error); - assertEquals("value2", error.getRejectedValue()); + assertThat(error).as("Must have field error for age property").isNotNull(); + assertThat(error.getRejectedValue()).isEqualTo("value2"); if (!model.containsKey("myKey")) { model.addAttribute("myKey", "myValue"); } @@ -2424,8 +2418,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl public String myOtherHandle(TB tb, BindingResult errors, ExtendedModelMap model, MySpecialArg arg) { TestBean tbReal = (TestBean) tb; tbReal.setName("myName"); - assertTrue(model.get("ITestBean") instanceof DerivedTestBean); - assertNotNull(arg); + boolean condition = model.get("ITestBean") instanceof DerivedTestBean; + assertThat(condition).isTrue(); + assertThat(arg).isNotNull(); return super.myHandle(tbReal, errors, model); } @@ -2489,9 +2484,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl LocalValidatorFactoryBean vf = new LocalValidatorFactoryBean(); vf.afterPropertiesSet(); binder.setValidator(vf); - assertEquals("2007-10-02", date); - assertEquals(1, date2.length); - assertEquals("2007-10-02", date2[0]); + assertThat(date).isEqualTo("2007-10-02"); + assertThat(date2.length).isEqualTo(1); + assertThat(date2[0]).isEqualTo("2007-10-02"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); @@ -2656,10 +2651,10 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @ModelAttribute TestPrincipal modelPrinc, OtherPrincipal requestPrinc, Writer writer) throws IOException { - assertNull(testBean); - assertNotNull(modelPrinc); - assertNotNull(requestPrinc); - assertFalse(errors.hasErrors()); + assertThat(testBean).isNull(); + assertThat(modelPrinc).isNotNull(); + assertThat(requestPrinc).isNotNull(); + assertThat(errors.hasErrors()).isFalse(); errors.reject("myCode"); writer.write("myView"); } @@ -2699,7 +2694,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl tb = (TestBean) model.get("myCommand"); } if (tb.getName() != null && tb.getName().endsWith("myDefaultName")) { - assertEquals(107, tb.getDate().getYear()); + assertThat(tb.getDate().getYear()).isEqualTo(107); } Errors errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "testBean"); if (errors == null) { @@ -2709,7 +2704,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl throw new IllegalStateException(); } if (model.containsKey("ITestBean")) { - assertTrue(model.get(BindingResult.MODEL_KEY_PREFIX + "ITestBean") instanceof Errors); + boolean condition = model.get(BindingResult.MODEL_KEY_PREFIX + "ITestBean") instanceof Errors; + assertThat(condition).isTrue(); } List testBeans = (List) model.get("testBeanList"); if (errors.hasFieldErrors("age")) { @@ -3207,7 +3203,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @RequestMapping(method = RequestMethod.GET) public void handle(@CookieValue("date") Date date, Writer writer) throws IOException { - assertEquals("Invalid path variable value", new GregorianCalendar(2008, 10, 18).getTime(), date); + assertThat(date).as("Invalid path variable value").isEqualTo(new GregorianCalendar(2008, 10, 18).getTime()); writer.write("test-" + new SimpleDateFormat("yyyy").format(date)); } } @@ -3374,7 +3370,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @RequestMapping("/httpHeaders") public void httpHeaders(@RequestHeader HttpHeaders headers, Writer writer) throws IOException { - assertEquals("Invalid Content-Type", new MediaType("text", "html"), headers.getContentType()); + assertThat(headers.getContentType()).as("Invalid Content-Type").isEqualTo(new MediaType("text", "html")); multiValueMap(headers, writer); } @@ -3430,11 +3426,11 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @PostMapping("/foo") public ResponseEntity foo(HttpEntity requestEntity) throws Exception { - assertNotNull(requestEntity); - assertEquals("MyValue", requestEntity.getHeaders().getFirst("MyRequestHeader")); + assertThat(requestEntity).isNotNull(); + assertThat(requestEntity.getHeaders().getFirst("MyRequestHeader")).isEqualTo("MyValue"); String body = new String(requestEntity.getBody(), "UTF-8"); - assertEquals("Hello World", body); + assertThat(body).isEqualTo("Hello World"); URI location = new URI("/foo"); return ResponseEntity.created(location).header("MyResponseHeader", "MyValue").body(body); @@ -3782,8 +3778,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl @RequestMapping("/bind") public String handle(Optional optionalData, BindingResult result) { if (result.hasErrors()) { - assertNotNull(optionalData); - assertFalse(optionalData.isPresent()); + assertThat(optionalData).isNotNull(); + assertThat(optionalData.isPresent()).isFalse(); return result.getFieldValue("param1") + "-" + result.getFieldValue("param2") + "-" + result.getFieldValue("param3"); } @@ -3815,11 +3811,11 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl if (result.hasErrors()) { return result.getFieldError().toString(); } - assertNotNull(data); - assertNotNull(data.date); - assertEquals(2010, data.date.getYear()); - assertEquals(1, data.date.getMonthValue()); - assertEquals(1, data.date.getDayOfMonth()); + assertThat(data).isNotNull(); + assertThat(data.date).isNotNull(); + assertThat(data.date.getYear()).isEqualTo(2010); + assertThat(data.date.getMonthValue()).isEqualTo(1); + assertThat(data.date.getDayOfMonth()).isEqualTo(1); return result.getFieldValue("date").toString(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletCookieValueMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletCookieValueMethodArgumentResolverTests.java index 21ba9f8c212..8ec9e8ab0e2 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletCookieValueMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletCookieValueMethodArgumentResolverTests.java @@ -29,7 +29,7 @@ import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.context.request.ServletWebRequest; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link ServletCookieValueMethodArgumentResolver}. @@ -67,7 +67,7 @@ public class ServletCookieValueMethodArgumentResolverTests { request.setCookies(expected); Cookie result = (Cookie) resolver.resolveArgument(cookieParameter, null, webRequest, null); - assertEquals("Invalid result", expected, result); + assertThat(result).as("Invalid result").isEqualTo(expected); } @Test @@ -76,7 +76,7 @@ public class ServletCookieValueMethodArgumentResolverTests { request.setCookies(cookie); String result = (String) resolver.resolveArgument(cookieStringParameter, null, webRequest, null); - assertEquals("Invalid result", cookie.getValue(), result); + assertThat(result).as("Invalid result").isEqualTo(cookie.getValue()); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java index 6d1f199a200..9d566248966 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java @@ -52,10 +52,8 @@ import org.springframework.web.method.support.HandlerMethodReturnValueHandlerCom import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.view.RedirectView; +import static org.assertj.core.api.Assertions.assertThat; 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.assertTrue; /** * Test fixture with {@link ServletInvocableHandlerMethod}. @@ -89,9 +87,8 @@ public class ServletInvocableHandlerMethodTests { ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "responseStatus"); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertTrue("Null return value + @ResponseStatus should result in 'request handled'", - this.mavContainer.isRequestHandled()); - assertEquals(HttpStatus.BAD_REQUEST.value(), this.response.getStatus()); + assertThat(this.mavContainer.isRequestHandled()).as("Null return value + @ResponseStatus should result in 'request handled'").isTrue(); + assertThat(this.response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); } @Test @@ -99,9 +96,8 @@ public class ServletInvocableHandlerMethodTests { ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "composedResponseStatus"); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertTrue("Null return value + @ComposedResponseStatus should result in 'request handled'", - this.mavContainer.isRequestHandled()); - assertEquals(HttpStatus.BAD_REQUEST.value(), this.response.getStatus()); + assertThat(this.mavContainer.isRequestHandled()).as("Null return value + @ComposedResponseStatus should result in 'request handled'").isTrue(); + assertThat(this.response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); } @Test @@ -109,8 +105,8 @@ public class ServletInvocableHandlerMethodTests { ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseStatusHandler(), "handle"); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertTrue(this.mavContainer.isRequestHandled()); - assertEquals(HttpStatus.BAD_REQUEST.value(), this.response.getStatus()); + assertThat(this.mavContainer.isRequestHandled()).isTrue(); + assertThat(this.response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); } @Test @@ -121,8 +117,7 @@ public class ServletInvocableHandlerMethodTests { getHandlerMethod(new Handler(), "httpServletResponse", HttpServletResponse.class); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertTrue("Null return value + HttpServletResponse arg should result in 'request handled'", - this.mavContainer.isRequestHandled()); + assertThat(this.mavContainer.isRequestHandled()).as("Null return value + HttpServletResponse arg should result in 'request handled'").isTrue(); } @Test @@ -134,8 +129,7 @@ public class ServletInvocableHandlerMethodTests { ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "notModified"); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertTrue("Null return value + 'not modified' request should result in 'request handled'", - this.mavContainer.isRequestHandled()); + assertThat(this.mavContainer.isRequestHandled()).as("Null return value + 'not modified' request should result in 'request handled'").isTrue(); } @Test // SPR-9159 @@ -143,9 +137,9 @@ public class ServletInvocableHandlerMethodTests { ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "responseStatusWithReason"); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertTrue("When a status reason w/ used, the request is handled", this.mavContainer.isRequestHandled()); - assertEquals(HttpStatus.BAD_REQUEST.value(), this.response.getStatus()); - assertEquals("400 Bad Request", this.response.getErrorMessage()); + assertThat(this.mavContainer.isRequestHandled()).as("When a status reason w/ used, the request is handled").isTrue(); + assertThat(this.response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); + assertThat(this.response.getErrorMessage()).isEqualTo("400 Bad Request"); } @Test @@ -167,14 +161,14 @@ public class ServletInvocableHandlerMethodTests { ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "dynamicReturnValue", String.class); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertNotNull(this.mavContainer.getView()); - assertEquals(RedirectView.class, this.mavContainer.getView().getClass()); + assertThat(this.mavContainer.getView()).isNotNull(); + assertThat(this.mavContainer.getView().getClass()).isEqualTo(RedirectView.class); // Invoke with a request parameter (RedirectView return value) this.request.setParameter("param", "value"); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertEquals("view", this.mavContainer.getViewName()); + assertThat(this.mavContainer.getViewName()).isEqualTo("view"); } @Test @@ -216,8 +210,9 @@ public class ServletInvocableHandlerMethodTests { handlerMethod = handlerMethod.wrapConcurrentResult(result); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertEquals((result != null ? result.toString() : ""), this.response.getContentAsString()); - assertEquals(expectedReturnType, handlerMethod.getReturnValueType(result).getParameterType()); + Object expected = (result != null ? result.toString() : ""); + assertThat(this.response.getContentAsString()).isEqualTo(expected); + assertThat(handlerMethod.getReturnValueType(result).getParameterType()).isEqualTo(expectedReturnType); } @Test @@ -227,7 +222,7 @@ public class ServletInvocableHandlerMethodTests { handlerMethod = handlerMethod.wrapConcurrentResult(new ResponseEntity<>("bar", HttpStatus.OK)); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertEquals("bar", this.response.getContentAsString()); + assertThat(this.response.getContentAsString()).isEqualTo("bar"); } @Test // SPR-12287 @@ -237,8 +232,8 @@ public class ServletInvocableHandlerMethodTests { handlerMethod = handlerMethod.wrapConcurrentResult(new ResponseEntity<>(HttpStatus.OK)); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertEquals(200, this.response.getStatus()); - assertEquals("", this.response.getContentAsString()); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getContentAsString()).isEqualTo(""); } @Test @@ -248,8 +243,8 @@ public class ServletInvocableHandlerMethodTests { handlerMethod = handlerMethod.wrapConcurrentResult(null); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertEquals(200, this.response.getStatus()); - assertEquals("", this.response.getContentAsString()); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getContentAsString()).isEqualTo(""); } @Test @@ -261,8 +256,8 @@ public class ServletInvocableHandlerMethodTests { handlerMethod = handlerMethod.wrapConcurrentResult(null); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertEquals(200, this.response.getStatus()); - assertEquals("", this.response.getContentAsString()); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getContentAsString()).isEqualTo(""); } @Test @@ -272,8 +267,8 @@ public class ServletInvocableHandlerMethodTests { handlerMethod = handlerMethod.wrapConcurrentResult(null); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertEquals(200, this.response.getStatus()); - assertEquals("", this.response.getContentAsString()); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getContentAsString()).isEqualTo(""); } @Test @@ -290,8 +285,8 @@ public class ServletInvocableHandlerMethodTests { hm = hm.wrapConcurrentResult(result); hm.invokeAndHandle(this.webRequest, this.mavContainer); - assertEquals(200, this.response.getStatus()); - assertEquals("[[\"foo1\",\"bar1\"],[\"foo2\",\"bar2\"]]", this.response.getContentAsString()); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getContentAsString()).isEqualTo("[[\"foo1\",\"bar1\"],[\"foo2\",\"bar2\"]]"); } @Test // SPR-15478 @@ -308,8 +303,8 @@ public class ServletInvocableHandlerMethodTests { hm = hm.wrapConcurrentResult(result); hm.invokeAndHandle(this.webRequest, this.mavContainer); - assertEquals(200, this.response.getStatus()); - assertEquals("[{\"value\":\"foo\"},{\"value\":\"bar\"}]", this.response.getContentAsString()); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getContentAsString()).isEqualTo("[{\"value\":\"foo\"},{\"value\":\"bar\"}]"); } @Test // SPR-12287 (16/Oct/14 comments) @@ -318,8 +313,8 @@ public class ServletInvocableHandlerMethodTests { ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handleRawType"); handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); - assertEquals(200, this.response.getStatus()); - assertEquals("", this.response.getContentAsString()); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getContentAsString()).isEqualTo(""); } private ServletInvocableHandlerMethod getHandlerMethod(Object controller, diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletModelAttributeMethodProcessorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletModelAttributeMethodProcessorTests.java index 2dd898f4b0c..b093f0ab5ae 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletModelAttributeMethodProcessorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletModelAttributeMethodProcessorTests.java @@ -36,10 +36,7 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.HandlerMapping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link ServletModelAttributeMethodProcessor} specific tests. @@ -94,7 +91,7 @@ public class ServletModelAttributeMethodProcessorTests { TestBean testBean = (TestBean) processor.resolveArgument( testBeanModelAttr, mavContainer, webRequest, binderFactory); - assertEquals("Patty", testBean.getName()); + assertThat(testBean.getName()).isEqualTo("Patty"); } @Test @@ -106,7 +103,7 @@ public class ServletModelAttributeMethodProcessorTests { TestBeanWithoutStringConstructor testBean = (TestBeanWithoutStringConstructor) processor.resolveArgument( testBeanWithoutStringConstructorModelAttr, mavContainer, webRequest, binderFactory); - assertNotNull(testBean); + assertThat(testBean).isNotNull(); } @Test @@ -120,7 +117,7 @@ public class ServletModelAttributeMethodProcessorTests { Optional testBean = (Optional) processor.resolveArgument( testBeanWithOptionalModelAttr, mavContainer, webRequest, binderFactory); - assertEquals("Patty", testBean.get().getName()); + assertThat(testBean.get().getName()).isEqualTo("Patty"); } @Test @@ -131,7 +128,7 @@ public class ServletModelAttributeMethodProcessorTests { TestBean testBean = (TestBean) processor.resolveArgument( testBeanModelAttr, mavContainer, webRequest, binderFactory); - assertEquals("Patty", testBean.getName()); + assertThat(testBean.getName()).isEqualTo("Patty"); } @Test @@ -141,7 +138,7 @@ public class ServletModelAttributeMethodProcessorTests { TestBeanWithoutStringConstructor testBean = (TestBeanWithoutStringConstructor) processor.resolveArgument( testBeanWithoutStringConstructorModelAttr, mavContainer, webRequest, binderFactory); - assertNotNull(testBean); + assertThat(testBean).isNotNull(); } @Test @@ -152,7 +149,7 @@ public class ServletModelAttributeMethodProcessorTests { Optional testBean = (Optional) processor.resolveArgument( testBeanWithOptionalModelAttr, mavContainer, webRequest, binderFactory); - assertEquals("Patty", testBean.get().getName()); + assertThat(testBean.get().getName()).isEqualTo("Patty"); } @Test @@ -164,15 +161,15 @@ public class ServletModelAttributeMethodProcessorTests { mavContainer.getModel().put("testBean2", null); mavContainer.getModel().put("testBean3", null); - assertNull(processor.resolveArgument( - testBeanModelAttr, mavContainer, webRequest, binderFactory)); + assertThat(processor.resolveArgument( + testBeanModelAttr, mavContainer, webRequest, binderFactory)).isNull(); - assertNull(processor.resolveArgument( - testBeanWithoutStringConstructorModelAttr, mavContainer, webRequest, binderFactory)); + assertThat(processor.resolveArgument( + testBeanWithoutStringConstructorModelAttr, mavContainer, webRequest, binderFactory)).isNull(); Optional testBean = (Optional) processor.resolveArgument( testBeanWithOptionalModelAttr, mavContainer, webRequest, binderFactory); - assertFalse(testBean.isPresent()); + assertThat(testBean.isPresent()).isFalse(); } @Test @@ -184,15 +181,15 @@ public class ServletModelAttributeMethodProcessorTests { mavContainer.getModel().put("testBean2", Optional.empty()); mavContainer.getModel().put("testBean3", Optional.empty()); - assertNull(processor.resolveArgument( - testBeanModelAttr, mavContainer, webRequest, binderFactory)); + assertThat(processor.resolveArgument( + testBeanModelAttr, mavContainer, webRequest, binderFactory)).isNull(); - assertNull(processor.resolveArgument( - testBeanWithoutStringConstructorModelAttr, mavContainer, webRequest, binderFactory)); + assertThat(processor.resolveArgument( + testBeanWithoutStringConstructorModelAttr, mavContainer, webRequest, binderFactory)).isNull(); Optional testBean =(Optional) processor.resolveArgument( testBeanWithOptionalModelAttr, mavContainer, webRequest, binderFactory); - assertFalse(testBean.isPresent()); + assertThat(testBean.isPresent()).isFalse(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletRequestMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletRequestMethodArgumentResolverTests.java index 88bdade908d..457b1bc98b6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletRequestMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletRequestMethodArgumentResolverTests.java @@ -43,11 +43,7 @@ import org.springframework.web.multipart.MultipartRequest; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.i18n.FixedLocaleResolver; -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; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -84,11 +80,11 @@ public class ServletRequestMethodArgumentResolverTests { @Test public void servletRequest() throws Exception { MethodParameter servletRequestParameter = new MethodParameter(method, 0); - assertTrue("ServletRequest not supported", resolver.supportsParameter(servletRequestParameter)); + assertThat(resolver.supportsParameter(servletRequestParameter)).as("ServletRequest not supported").isTrue(); Object result = resolver.resolveArgument(servletRequestParameter, mavContainer, webRequest, null); - assertSame("Invalid result", servletRequest, result); - assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); + assertThat(result).as("Invalid result").isSameAs(servletRequest); + assertThat(mavContainer.isRequestHandled()).as("The requestHandled flag shouldn't change").isFalse(); } @Test @@ -97,11 +93,11 @@ public class ServletRequestMethodArgumentResolverTests { servletRequest.setSession(session); MethodParameter sessionParameter = new MethodParameter(method, 2); - assertTrue("Session not supported", resolver.supportsParameter(sessionParameter)); + assertThat(resolver.supportsParameter(sessionParameter)).as("Session not supported").isTrue(); Object result = resolver.resolveArgument(sessionParameter, mavContainer, webRequest, null); - assertSame("Invalid result", session, result); - assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); + assertThat(result).as("Invalid result").isSameAs(session); + assertThat(mavContainer.isRequestHandled()).as("The requestHandled flag shouldn't change").isFalse(); } @Test @@ -110,19 +106,19 @@ public class ServletRequestMethodArgumentResolverTests { servletRequest.setUserPrincipal(principal); MethodParameter principalParameter = new MethodParameter(method, 3); - assertTrue("Principal not supported", resolver.supportsParameter(principalParameter)); + assertThat(resolver.supportsParameter(principalParameter)).as("Principal not supported").isTrue(); Object result = resolver.resolveArgument(principalParameter, null, webRequest, null); - assertSame("Invalid result", principal, result); + assertThat(result).as("Invalid result").isSameAs(principal); } @Test public void principalAsNull() throws Exception { MethodParameter principalParameter = new MethodParameter(method, 3); - assertTrue("Principal not supported", resolver.supportsParameter(principalParameter)); + assertThat(resolver.supportsParameter(principalParameter)).as("Principal not supported").isTrue(); Object result = resolver.resolveArgument(principalParameter, null, webRequest, null); - assertNull("Invalid result", result); + assertThat(result).as("Invalid result").isNull(); } @Test @@ -131,10 +127,10 @@ public class ServletRequestMethodArgumentResolverTests { servletRequest.addPreferredLocale(locale); MethodParameter localeParameter = new MethodParameter(method, 4); - assertTrue("Locale not supported", resolver.supportsParameter(localeParameter)); + assertThat(resolver.supportsParameter(localeParameter)).as("Locale not supported").isTrue(); Object result = resolver.resolveArgument(localeParameter, null, webRequest, null); - assertSame("Invalid result", locale, result); + assertThat(result).as("Invalid result").isSameAs(locale); } @Test @@ -144,19 +140,19 @@ public class ServletRequestMethodArgumentResolverTests { new FixedLocaleResolver(locale)); MethodParameter localeParameter = new MethodParameter(method, 4); - assertTrue("Locale not supported", resolver.supportsParameter(localeParameter)); + assertThat(resolver.supportsParameter(localeParameter)).as("Locale not supported").isTrue(); Object result = resolver.resolveArgument(localeParameter, null, webRequest, null); - assertSame("Invalid result", locale, result); + assertThat(result).as("Invalid result").isSameAs(locale); } @Test public void timeZone() throws Exception { MethodParameter timeZoneParameter = new MethodParameter(method, 8); - assertTrue("TimeZone not supported", resolver.supportsParameter(timeZoneParameter)); + assertThat(resolver.supportsParameter(timeZoneParameter)).as("TimeZone not supported").isTrue(); Object result = resolver.resolveArgument(timeZoneParameter, null, webRequest, null); - assertEquals("Invalid result", TimeZone.getDefault(), result); + assertThat(result).as("Invalid result").isEqualTo(TimeZone.getDefault()); } @Test @@ -166,19 +162,19 @@ public class ServletRequestMethodArgumentResolverTests { new FixedLocaleResolver(Locale.US, timeZone)); MethodParameter timeZoneParameter = new MethodParameter(method, 8); - assertTrue("TimeZone not supported", resolver.supportsParameter(timeZoneParameter)); + assertThat(resolver.supportsParameter(timeZoneParameter)).as("TimeZone not supported").isTrue(); Object result = resolver.resolveArgument(timeZoneParameter, null, webRequest, null); - assertEquals("Invalid result", timeZone, result); + assertThat(result).as("Invalid result").isEqualTo(timeZone); } @Test public void zoneId() throws Exception { MethodParameter zoneIdParameter = new MethodParameter(method, 9); - assertTrue("ZoneId not supported", resolver.supportsParameter(zoneIdParameter)); + assertThat(resolver.supportsParameter(zoneIdParameter)).as("ZoneId not supported").isTrue(); Object result = resolver.resolveArgument(zoneIdParameter, null, webRequest, null); - assertEquals("Invalid result", ZoneId.systemDefault(), result); + assertThat(result).as("Invalid result").isEqualTo(ZoneId.systemDefault()); } @Test @@ -188,46 +184,46 @@ public class ServletRequestMethodArgumentResolverTests { new FixedLocaleResolver(Locale.US, timeZone)); MethodParameter zoneIdParameter = new MethodParameter(method, 9); - assertTrue("ZoneId not supported", resolver.supportsParameter(zoneIdParameter)); + assertThat(resolver.supportsParameter(zoneIdParameter)).as("ZoneId not supported").isTrue(); Object result = resolver.resolveArgument(zoneIdParameter, null, webRequest, null); - assertEquals("Invalid result", timeZone.toZoneId(), result); + assertThat(result).as("Invalid result").isEqualTo(timeZone.toZoneId()); } @Test public void inputStream() throws Exception { MethodParameter inputStreamParameter = new MethodParameter(method, 5); - assertTrue("InputStream not supported", resolver.supportsParameter(inputStreamParameter)); + assertThat(resolver.supportsParameter(inputStreamParameter)).as("InputStream not supported").isTrue(); Object result = resolver.resolveArgument(inputStreamParameter, null, webRequest, null); - assertSame("Invalid result", webRequest.getRequest().getInputStream(), result); + assertThat(result).as("Invalid result").isSameAs(webRequest.getRequest().getInputStream()); } @Test public void reader() throws Exception { MethodParameter readerParameter = new MethodParameter(method, 6); - assertTrue("Reader not supported", resolver.supportsParameter(readerParameter)); + assertThat(resolver.supportsParameter(readerParameter)).as("Reader not supported").isTrue(); Object result = resolver.resolveArgument(readerParameter, null, webRequest, null); - assertSame("Invalid result", webRequest.getRequest().getReader(), result); + assertThat(result).as("Invalid result").isSameAs(webRequest.getRequest().getReader()); } @Test public void webRequest() throws Exception { MethodParameter webRequestParameter = new MethodParameter(method, 7); - assertTrue("WebRequest not supported", resolver.supportsParameter(webRequestParameter)); + assertThat(resolver.supportsParameter(webRequestParameter)).as("WebRequest not supported").isTrue(); Object result = resolver.resolveArgument(webRequestParameter, null, webRequest, null); - assertSame("Invalid result", webRequest, result); + assertThat(result).as("Invalid result").isSameAs(webRequest); } @Test public void httpMethod() throws Exception { MethodParameter httpMethodParameter = new MethodParameter(method, 10); - assertTrue("HttpMethod not supported", resolver.supportsParameter(httpMethodParameter)); + assertThat(resolver.supportsParameter(httpMethodParameter)).as("HttpMethod not supported").isTrue(); Object result = resolver.resolveArgument(httpMethodParameter, null, webRequest, null); - assertSame("Invalid result", HttpMethod.valueOf(webRequest.getRequest().getMethod()), result); + assertThat(result).as("Invalid result").isSameAs(HttpMethod.valueOf(webRequest.getRequest().getMethod())); } @Test @@ -242,10 +238,10 @@ public class ServletRequestMethodArgumentResolverTests { ServletWebRequest webRequest = new ServletWebRequest(servletRequest, new MockHttpServletResponse()); MethodParameter pushBuilderParameter = new MethodParameter(method, 11); - assertTrue("PushBuilder not supported", resolver.supportsParameter(pushBuilderParameter)); + assertThat(resolver.supportsParameter(pushBuilderParameter)).as("PushBuilder not supported").isTrue(); Object result = resolver.resolveArgument(pushBuilderParameter, null, webRequest, null); - assertSame("Invalid result", pushBuilder, result); + assertThat(result).as("Invalid result").isSameAs(pushBuilder); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletResponseMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletResponseMethodArgumentResolverTests.java index 71494c3e6dd..573d1c538ff 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletResponseMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletResponseMethodArgumentResolverTests.java @@ -30,8 +30,7 @@ import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link ServletResponseMethodArgumentResolver}. @@ -65,40 +64,40 @@ public class ServletResponseMethodArgumentResolverTests { @Test public void servletResponse() throws Exception { MethodParameter servletResponseParameter = new MethodParameter(method, 0); - assertTrue("ServletResponse not supported", resolver.supportsParameter(servletResponseParameter)); + assertThat(resolver.supportsParameter(servletResponseParameter)).as("ServletResponse not supported").isTrue(); Object result = resolver.resolveArgument(servletResponseParameter, mavContainer, webRequest, null); - assertSame("Invalid result", servletResponse, result); - assertTrue(mavContainer.isRequestHandled()); + assertThat(result).as("Invalid result").isSameAs(servletResponse); + assertThat(mavContainer.isRequestHandled()).isTrue(); } @Test // SPR-8983 public void servletResponseNoMavContainer() throws Exception { MethodParameter servletResponseParameter = new MethodParameter(method, 0); - assertTrue("ServletResponse not supported", resolver.supportsParameter(servletResponseParameter)); + assertThat(resolver.supportsParameter(servletResponseParameter)).as("ServletResponse not supported").isTrue(); Object result = resolver.resolveArgument(servletResponseParameter, null, webRequest, null); - assertSame("Invalid result", servletResponse, result); + assertThat(result).as("Invalid result").isSameAs(servletResponse); } @Test public void outputStream() throws Exception { MethodParameter outputStreamParameter = new MethodParameter(method, 1); - assertTrue("OutputStream not supported", resolver.supportsParameter(outputStreamParameter)); + assertThat(resolver.supportsParameter(outputStreamParameter)).as("OutputStream not supported").isTrue(); Object result = resolver.resolveArgument(outputStreamParameter, mavContainer, webRequest, null); - assertSame("Invalid result", servletResponse.getOutputStream(), result); - assertTrue(mavContainer.isRequestHandled()); + assertThat(result).as("Invalid result").isSameAs(servletResponse.getOutputStream()); + assertThat(mavContainer.isRequestHandled()).isTrue(); } @Test public void writer() throws Exception { MethodParameter writerParameter = new MethodParameter(method, 2); - assertTrue("Writer not supported", resolver.supportsParameter(writerParameter)); + assertThat(resolver.supportsParameter(writerParameter)).as("Writer not supported").isTrue(); Object result = resolver.resolveArgument(writerParameter, mavContainer, webRequest, null); - assertSame("Invalid result", servletResponse.getWriter(), result); - assertTrue(mavContainer.isRequestHandled()); + assertThat(result).as("Invalid result").isSameAs(servletResponse.getWriter()); + assertThat(mavContainer.isRequestHandled()).isTrue(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitterTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitterTests.java index 0386e2f12fa..77fe8e77049 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitterTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitterTests.java @@ -25,8 +25,7 @@ import org.junit.Test; import org.springframework.http.MediaType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event; @@ -122,7 +121,7 @@ public class SseEmitterTests { public void assertSentObjectCount(int size) { - assertEquals(size, this.objects.size()); + assertThat(this.objects.size()).isEqualTo(size); } public void assertObject(int index, Object object) { @@ -130,9 +129,9 @@ public class SseEmitterTests { } public void assertObject(int index, Object object, MediaType mediaType) { - assertTrue(index <= this.objects.size()); - assertEquals(object, this.objects.get(index)); - assertEquals(mediaType, this.mediaTypes.get(index)); + assertThat(index <= this.objects.size()).isTrue(); + assertThat(this.objects.get(index)).isEqualTo(object); + assertThat(this.mediaTypes.get(index)).isEqualTo(mediaType); } @Override diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/StreamingResponseBodyReturnValueHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/StreamingResponseBodyReturnValueHandlerTests.java index 0c4e2b9db0c..547b014cfc9 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/StreamingResponseBodyReturnValueHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/StreamingResponseBodyReturnValueHandlerTests.java @@ -37,9 +37,7 @@ import org.springframework.web.context.request.async.StandardServletAsyncWebRequ import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.method.support.ModelAndViewContainer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** @@ -78,10 +76,10 @@ public class StreamingResponseBodyReturnValueHandlerTests { @Test public void supportsReturnType() throws Exception { - assertTrue(this.handler.supportsReturnType(returnType(TestController.class, "handle"))); - assertTrue(this.handler.supportsReturnType(returnType(TestController.class, "handleResponseEntity"))); - assertFalse(this.handler.supportsReturnType(returnType(TestController.class, "handleResponseEntityString"))); - assertFalse(this.handler.supportsReturnType(returnType(TestController.class, "handleResponseEntityParameterized"))); + assertThat(this.handler.supportsReturnType(returnType(TestController.class, "handle"))).isTrue(); + assertThat(this.handler.supportsReturnType(returnType(TestController.class, "handleResponseEntity"))).isTrue(); + assertThat(this.handler.supportsReturnType(returnType(TestController.class, "handleResponseEntityString"))).isFalse(); + assertThat(this.handler.supportsReturnType(returnType(TestController.class, "handleResponseEntityParameterized"))).isFalse(); } @Test @@ -95,9 +93,9 @@ public class StreamingResponseBodyReturnValueHandlerTests { }; this.handler.handleReturnValue(streamingBody, returnType, this.mavContainer, this.webRequest); - assertTrue(this.request.isAsyncStarted()); - assertTrue(latch.await(5, TimeUnit.SECONDS)); - assertEquals("foo", this.response.getContentAsString()); + assertThat(this.request.isAsyncStarted()).isTrue(); + assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo("foo"); } @@ -113,12 +111,12 @@ public class StreamingResponseBodyReturnValueHandlerTests { }); this.handler.handleReturnValue(emitter, returnType, this.mavContainer, this.webRequest); - assertTrue(this.request.isAsyncStarted()); - assertEquals(200, this.response.getStatus()); - assertEquals("bar", this.response.getHeader("foo")); + assertThat(this.request.isAsyncStarted()).isTrue(); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getHeader("foo")).isEqualTo("bar"); - assertTrue(latch.await(5, TimeUnit.SECONDS)); - assertEquals("foo", this.response.getContentAsString()); + assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(this.response.getContentAsString()).isEqualTo("foo"); } @@ -128,8 +126,8 @@ public class StreamingResponseBodyReturnValueHandlerTests { ResponseEntity emitter = ResponseEntity.noContent().build(); this.handler.handleReturnValue(emitter, returnType, this.mavContainer, this.webRequest); - assertFalse(this.request.isAsyncStarted()); - assertEquals(204, this.response.getStatus()); + assertThat(this.request.isAsyncStarted()).isFalse(); + assertThat(this.response.getStatus()).isEqualTo(204); } @Test @@ -138,7 +136,7 @@ public class StreamingResponseBodyReturnValueHandlerTests { MethodParameter returnType = returnType(TestController.class, "handleResponseEntity"); this.handler.handleReturnValue(emitter, returnType, this.mavContainer, this.webRequest); - assertEquals(Collections.singletonList("bar"), this.response.getHeaders("foo")); + assertThat(this.response.getHeaders("foo")).isEqualTo(Collections.singletonList("bar")); } private MethodParameter returnType(Class clazz, String methodName) throws NoSuchMethodException { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriComponentsBuilderMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriComponentsBuilderMethodArgumentResolverTests.java index 8603b7e303b..5d652a71311 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriComponentsBuilderMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriComponentsBuilderMethodArgumentResolverTests.java @@ -28,10 +28,7 @@ import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link UriComponentsBuilderMethodArgumentResolver}. @@ -67,9 +64,9 @@ public class UriComponentsBuilderMethodArgumentResolverTests { @Test public void supportsParameter() throws Exception { - assertTrue(this.resolver.supportsParameter(this.builderParam)); - assertTrue(this.resolver.supportsParameter(this.servletBuilderParam)); - assertFalse(this.resolver.supportsParameter(this.intParam)); + assertThat(this.resolver.supportsParameter(this.builderParam)).isTrue(); + assertThat(this.resolver.supportsParameter(this.servletBuilderParam)).isTrue(); + assertThat(this.resolver.supportsParameter(this.intParam)).isFalse(); } @Test @@ -80,9 +77,9 @@ public class UriComponentsBuilderMethodArgumentResolverTests { Object actual = this.resolver.resolveArgument(this.builderParam, new ModelAndViewContainer(), this.webRequest, null); - assertNotNull(actual); - assertEquals(ServletUriComponentsBuilder.class, actual.getClass()); - assertEquals("http://localhost/myapp/main", ((ServletUriComponentsBuilder) actual).build().toUriString()); + assertThat(actual).isNotNull(); + assertThat(actual.getClass()).isEqualTo(ServletUriComponentsBuilder.class); + assertThat(((ServletUriComponentsBuilder) actual).build().toUriString()).isEqualTo("http://localhost/myapp/main"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java index 8d63057a15e..6c6f586f9e4 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java @@ -50,8 +50,7 @@ import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.view.AbstractView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rossen Stoyanchev @@ -66,7 +65,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-42-7", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test-42-7"); } @Test @@ -76,8 +75,8 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42;q=24/bookings/21-other;q=12"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("test-42-q24-21-other-q12", response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentAsString()).isEqualTo("test-42-q24-21-other-q12"); } @Test @@ -101,7 +100,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab getServlet().service(request, new MockHttpServletResponse()); ModelValidatingViewResolver resolver = wac.getBean(ModelValidatingViewResolver.class); - assertEquals(3, resolver.validatedAttrCount); + assertThat(resolver.validatedAttrCount).isEqualTo(3); } @Test @@ -111,18 +110,18 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/dates/2008-11-18"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(200); request = new MockHttpServletRequest("GET", "/hotels/42/dates/2008-foo-bar"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(400, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(400); initServletWithControllers(NonBindingUriTemplateController.class); request = new MockHttpServletRequest("GET", "/hotels/42/dates/2008-foo-bar"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(500, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(500); } @Test @@ -132,7 +131,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/new"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("specific", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("specific"); } @Test @@ -142,12 +141,12 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-42-21", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test-42-21"); request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21.html"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-42-21", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test-42-21"); } @Test @@ -157,7 +156,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42;jsessionid=c0o7fszeb1;q=24.xml"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-42-24", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test-42-24"); } @@ -168,7 +167,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.xml"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); + assertThat(response.getStatus()).as("Invalid response status code").isEqualTo(HttpServletResponse.SC_BAD_REQUEST); } @Test @@ -178,7 +177,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-42", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test-42"); } @Test @@ -188,7 +187,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("test-42", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("test-42"); } @Test @@ -198,37 +197,37 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("list", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("list"); request = new MockHttpServletRequest("GET", "/hotels/"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("list", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("list"); request = new MockHttpServletRequest("POST", "/hotels"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("create", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("create"); request = new MockHttpServletRequest("GET", "/hotels/42"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("show-42", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("show-42"); request = new MockHttpServletRequest("GET", "/hotels/42/"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("show-42", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("show-42"); request = new MockHttpServletRequest("PUT", "/hotels/42"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("createOrUpdate-42", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("createOrUpdate-42"); request = new MockHttpServletRequest("DELETE", "/hotels/42"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("remove-42", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("remove-42"); } @Test @@ -238,22 +237,22 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/1"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(200); request = new MockHttpServletRequest("POST", "/hotels/1"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(405, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(405); request = new MockHttpServletRequest("GET", "/hotels"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(200); request = new MockHttpServletRequest("POST", "/hotels"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(405, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(405); } @Test @@ -263,12 +262,12 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/category/page/5"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("handle4-page-5", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("handle4-page-5"); request = new MockHttpServletRequest("GET", "/category/page/5.html"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("handle4-page-5", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("handle4-page-5"); } @Test @@ -278,8 +277,8 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42;q=1;q=2"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals(200, response.getStatus()); - assertEquals("test-42-;q=1;q=2-[1, 2]", response.getContentAsString()); + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContentAsString()).isEqualTo("test-42-;q=1;q=2-[1, 2]"); } /* @@ -292,7 +291,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/book/menu/type/M5"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("M5", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("M5"); } /* @@ -305,12 +304,12 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/foo"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("foo-foo", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("foo-foo"); request = new MockHttpServletRequest("DELETE", "/test/bar"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("bar-bar", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("bar-bar"); } /* @@ -323,7 +322,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/foo.json"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("foo-foo", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("foo-foo"); } /* @@ -336,22 +335,22 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo/100"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("loadEntity:foo:100", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("loadEntity:foo:100"); request = new MockHttpServletRequest("POST", "/foo/100"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("publish:foo:100", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("publish:foo:100"); request = new MockHttpServletRequest("GET", "/module/100"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("loadModule:100", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("loadModule:100"); request = new MockHttpServletRequest("POST", "/module/100"); response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("publish:module:100", response.getContentAsString()); + assertThat(response.getContentAsString()).isEqualTo("publish:module:100"); } @@ -367,7 +366,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab public void handle(@PathVariable("root") int root, @MatrixVariable(required=false, defaultValue="7") int q, Writer writer) throws IOException { - assertEquals("Invalid path variable value", 42, root); + assertThat(root).as("Invalid path variable value").isEqualTo(42); writer.write("test-" + root + "-" + q); } @@ -383,8 +382,8 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab @MatrixVariable(name = "q", pathVar = "hotel") int qHotel, @MatrixVariable(name = "q", pathVar = "other") int qOther, Writer writer) throws IOException { - assertEquals("Invalid path variable value", "42", hotel); - assertEquals("Invalid path variable value", 21, booking); + assertThat(hotel).as("Invalid path variable value").isEqualTo("42"); + assertThat(booking).as("Invalid path variable value").isEqualTo(21); writer.write("test-" + hotel + "-q" + qHotel + "-" + booking + "-" + other + "-q" + qOther); } @@ -397,10 +396,10 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab public void handle(@PathVariable("hotel") String hotel, @PathVariable int booking, @PathVariable String other, @MatrixVariable MultiValueMap params) { - assertEquals("Invalid path variable value", "42", hotel); - assertEquals("Invalid path variable value", 21, booking); - assertEquals(Arrays.asList("1", "2", "3"), params.get("q")); - assertEquals("R", params.getFirst("r")); + assertThat(hotel).as("Invalid path variable value").isEqualTo("42"); + assertThat(booking).as("Invalid path variable value").isEqualTo(21); + assertThat(params.get("q")).isEqualTo(Arrays.asList("1", "2", "3")); + assertThat(params.getFirst("r")).isEqualTo("R"); } } @@ -410,7 +409,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab @InitBinder public void initBinder(WebDataBinder binder, @PathVariable("hotel") String hotel) { - assertEquals("Invalid path variable value", "42", hotel); + assertThat(hotel).as("Invalid path variable value").isEqualTo("42"); binder.initBeanPropertyAccess(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); @@ -420,8 +419,8 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab @RequestMapping("/hotels/{hotel}/dates/{date}") public void handle(@PathVariable("hotel") String hotel, @PathVariable Date date, Writer writer) throws IOException { - assertEquals("Invalid path variable value", "42", hotel); - assertEquals("Invalid path variable value", new GregorianCalendar(2008, 10, 18).getTime(), date); + assertThat(hotel).as("Invalid path variable value").isEqualTo("42"); + assertThat(date).as("Invalid path variable value").isEqualTo(new GregorianCalendar(2008, 10, 18).getTime()); writer.write("test-" + hotel); } } @@ -443,8 +442,8 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab @RequestMapping("bookings/{booking}") public void handle(@PathVariable("hotel") String hotel, @PathVariable int booking, Writer writer) throws IOException { - assertEquals("Invalid path variable value", "42", hotel); - assertEquals("Invalid path variable value", 21, booking); + assertThat(hotel).as("Invalid path variable value").isEqualTo("42"); + assertThat(booking).as("Invalid path variable value").isEqualTo(21); writer.write("test-" + hotel + "-" + booking); } @@ -456,7 +455,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab @RequestMapping("/{hotel}") public void handleVars(@PathVariable("hotel") String hotel, Writer writer) throws IOException { - assertEquals("Invalid path variable value", "42", hotel); + assertThat(hotel).as("Invalid path variable value").isEqualTo("42"); writer.write("variables"); } @@ -500,7 +499,7 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab public void handle(@PathVariable("root") int root, @PathVariable("params") String paramString, @MatrixVariable List q, Writer writer) throws IOException { - assertEquals("Invalid path variable value", 42, root); + assertThat(root).as("Invalid path variable value").isEqualTo(42); writer.write("test-" + root + "-" + paramString + "-" + q); } } @@ -665,8 +664,8 @@ public class UriTemplateServletAnnotationControllerHandlerMethodTests extends Ab protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { for (String key : attrsToValidate.keySet()) { - assertTrue("Model should contain attribute named " + key, model.containsKey(key)); - assertEquals(attrsToValidate.get(key), model.get(key)); + assertThat(model.containsKey(key)).as("Model should contain attribute named " + key).isTrue(); + assertThat(model.get(key)).isEqualTo(attrsToValidate.get(key)); validatedAttrCount++; } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandlerTests.java index 5e4dc74b596..0c909154a1b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandlerTests.java @@ -31,8 +31,7 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap; import org.springframework.web.servlet.view.InternalResourceView; import org.springframework.web.servlet.view.RedirectView; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link ViewMethodReturnValueHandler}. @@ -58,7 +57,7 @@ public class ViewMethodReturnValueHandlerTests { @Test public void supportsReturnType() throws Exception { - assertTrue(this.handler.supportsReturnType(createReturnValueParam("view"))); + assertThat(this.handler.supportsReturnType(createReturnValueParam("view"))).isTrue(); } @Test @@ -66,7 +65,7 @@ public class ViewMethodReturnValueHandlerTests { InternalResourceView view = new InternalResourceView("testView"); this.handler.handleReturnValue(view, createReturnValueParam("view"), this.mavContainer, this.webRequest); - assertSame(view, this.mavContainer.getView()); + assertThat(this.mavContainer.getView()).isSameAs(view); } @Test @@ -77,8 +76,8 @@ public class ViewMethodReturnValueHandlerTests { MethodParameter param = createReturnValueParam("view"); this.handler.handleReturnValue(redirectView, param, this.mavContainer, this.webRequest); - assertSame(redirectView, this.mavContainer.getView()); - assertSame("Should have switched to the RedirectModel", redirectModel, this.mavContainer.getModel()); + assertThat(this.mavContainer.getView()).isSameAs(redirectView); + assertThat(this.mavContainer.getModel()).as("Should have switched to the RedirectModel").isSameAs(redirectModel); } private MethodParameter createReturnValueParam(String methodName) throws Exception { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ViewNameMethodReturnValueHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ViewNameMethodReturnValueHandlerTests.java index 7e48374890f..ac1d5923418 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ViewNameMethodReturnValueHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ViewNameMethodReturnValueHandlerTests.java @@ -26,9 +26,7 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture with {@link ViewNameMethodReturnValueHandler}. @@ -58,13 +56,13 @@ public class ViewNameMethodReturnValueHandlerTests { @Test public void supportsReturnType() throws Exception { - assertTrue(this.handler.supportsReturnType(this.param)); + assertThat(this.handler.supportsReturnType(this.param)).isTrue(); } @Test public void returnViewName() throws Exception { this.handler.handleReturnValue("testView", this.param, this.mavContainer, this.webRequest); - assertEquals("testView", this.mavContainer.getViewName()); + assertThat(this.mavContainer.getViewName()).isEqualTo("testView"); } @Test @@ -72,8 +70,8 @@ public class ViewNameMethodReturnValueHandlerTests { ModelMap redirectModel = new RedirectAttributesModelMap(); this.mavContainer.setRedirectModel(redirectModel); this.handler.handleReturnValue("redirect:testView", this.param, this.mavContainer, this.webRequest); - assertEquals("redirect:testView", this.mavContainer.getViewName()); - assertSame(redirectModel, this.mavContainer.getModel()); + assertThat(this.mavContainer.getViewName()).isEqualTo("redirect:testView"); + assertThat(this.mavContainer.getModel()).isSameAs(redirectModel); } @Test @@ -82,8 +80,8 @@ public class ViewNameMethodReturnValueHandlerTests { this.mavContainer.setRedirectModel(redirectModel); this.handler.setRedirectPatterns("myRedirect:*"); this.handler.handleReturnValue("myRedirect:testView", this.param, this.mavContainer, this.webRequest); - assertEquals("myRedirect:testView", this.mavContainer.getViewName()); - assertSame(redirectModel, this.mavContainer.getModel()); + assertThat(this.mavContainer.getViewName()).isEqualTo("myRedirect:testView"); + assertThat(this.mavContainer.getModel()).isSameAs(redirectModel); } @Test @@ -92,8 +90,8 @@ public class ViewNameMethodReturnValueHandlerTests { this.mavContainer.setRedirectModel(redirectModel); this.handler.setRedirectPatterns("myRedirect:*"); this.handler.handleReturnValue("redirect:testView", this.param, this.mavContainer, this.webRequest); - assertEquals("redirect:testView", this.mavContainer.getViewName()); - assertSame(redirectModel, this.mavContainer.getModel()); + assertThat(this.mavContainer.getViewName()).isEqualTo("redirect:testView"); + assertThat(this.mavContainer.getModel()).isSameAs(redirectModel); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolverTests.java index 1cd45969dc0..eb9448e31b8 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolverTests.java @@ -45,10 +45,7 @@ import org.springframework.web.multipart.support.MissingServletRequestPartExcept import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.NoHandlerFoundException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma @@ -73,10 +70,10 @@ public class DefaultHandlerExceptionResolverTests { HttpRequestMethodNotSupportedException ex = new HttpRequestMethodNotSupportedException("GET", new String[]{"POST", "PUT"}); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 405, response.getStatus()); - assertEquals("Invalid Allow header", "POST, PUT", response.getHeader("Allow")); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(405); + assertThat(response.getHeader("Allow")).as("Invalid Allow header").isEqualTo("POST, PUT"); } @Test @@ -84,10 +81,10 @@ public class DefaultHandlerExceptionResolverTests { HttpMediaTypeNotSupportedException ex = new HttpMediaTypeNotSupportedException(new MediaType("text", "plain"), Collections.singletonList(new MediaType("application", "pdf"))); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 415, response.getStatus()); - assertEquals("Invalid Accept header", "application/pdf", response.getHeader("Accept")); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(415); + assertThat(response.getHeader("Accept")).as("Invalid Accept header").isEqualTo("application/pdf"); } @Test @@ -96,21 +93,20 @@ public class DefaultHandlerExceptionResolverTests { MethodParameter parameter = new MethodParameter(method, 0); MissingPathVariableException ex = new MissingPathVariableException("foo", parameter); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 500, response.getStatus()); - assertEquals("Missing URI template variable 'foo' for method parameter of type String", - response.getErrorMessage()); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(500); + assertThat(response.getErrorMessage()).isEqualTo("Missing URI template variable 'foo' for method parameter of type String"); } @Test public void handleMissingServletRequestParameter() { MissingServletRequestParameterException ex = new MissingServletRequestParameterException("foo", "bar"); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 400, response.getStatus()); - assertEquals("Required bar parameter 'foo' is not present", response.getErrorMessage()); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400); + assertThat(response.getErrorMessage()).isEqualTo("Required bar parameter 'foo' is not present"); } @Test @@ -118,18 +114,18 @@ public class DefaultHandlerExceptionResolverTests { String message = "Missing required value - header, cookie, or pathvar"; ServletRequestBindingException ex = new ServletRequestBindingException(message); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 400, response.getStatus()); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400); } @Test public void handleTypeMismatch() { TypeMismatchException ex = new TypeMismatchException("foo", String.class); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 400, response.getStatus()); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400); } @Test @@ -137,18 +133,18 @@ public class DefaultHandlerExceptionResolverTests { public void handleHttpMessageNotReadable() { HttpMessageNotReadableException ex = new HttpMessageNotReadableException("foo"); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 400, response.getStatus()); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400); } @Test public void handleHttpMessageNotWritable() { HttpMessageNotWritableException ex = new HttpMessageNotWritableException("foo"); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 500, response.getStatus()); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(500); } @Test @@ -158,30 +154,30 @@ public class DefaultHandlerExceptionResolverTests { MethodParameter parameter = new MethodParameter(this.getClass().getMethod("handle", String.class), 0); MethodArgumentNotValidException ex = new MethodArgumentNotValidException(parameter, errors); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 400, response.getStatus()); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400); } @Test public void handleMissingServletRequestPartException() throws Exception { MissingServletRequestPartException ex = new MissingServletRequestPartException("name"); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 400, response.getStatus()); - assertTrue(response.getErrorMessage().contains("request part")); - assertTrue(response.getErrorMessage().contains("name")); - assertTrue(response.getErrorMessage().contains("not present")); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400); + assertThat(response.getErrorMessage().contains("request part")).isTrue(); + assertThat(response.getErrorMessage().contains("name")).isTrue(); + assertThat(response.getErrorMessage().contains("not present")).isTrue(); } @Test public void handleBindException() throws Exception { BindException ex = new BindException(new Object(), "name"); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 400, response.getStatus()); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400); } @Test @@ -191,9 +187,9 @@ public class DefaultHandlerExceptionResolverTests { NoHandlerFoundException ex = new NoHandlerFoundException(req.getMethod().name(), req.getServletRequest().getRequestURI(),req.getHeaders()); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 404, response.getStatus()); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(404); } @Test @@ -201,21 +197,21 @@ public class DefaultHandlerExceptionResolverTests { ConversionNotSupportedException ex = new ConversionNotSupportedException(new Object(), String.class, new Exception()); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 500, response.getStatus()); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(500); // SPR-9653 - assertSame(ex, request.getAttribute("javax.servlet.error.exception")); + assertThat(request.getAttribute("javax.servlet.error.exception")).isSameAs(ex); } @Test // SPR-14669 public void handleAsyncRequestTimeoutException() throws Exception { Exception ex = new AsyncRequestTimeoutException(); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("No Empty ModelAndView returned", mav.isEmpty()); - assertEquals("Invalid status code", 503, response.getStatus()); + assertThat(mav).as("No ModelAndView returned").isNotNull(); + assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue(); + assertThat(response.getStatus()).as("Invalid status code").isEqualTo(503); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/ParameterizableViewControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/ParameterizableViewControllerTests.java index 7f03b0d7229..d0a11298602 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/ParameterizableViewControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/ParameterizableViewControllerTests.java @@ -26,9 +26,7 @@ import org.springframework.web.servlet.View; import org.springframework.web.servlet.mvc.ParameterizableViewController; import org.springframework.web.servlet.view.RedirectView; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for @@ -49,14 +47,14 @@ public class ParameterizableViewControllerTests { @Test public void defaultViewName() throws Exception { ModelAndView modelAndView = this.controller.handleRequest(this.request, this.response); - assertNull(modelAndView.getViewName()); + assertThat(modelAndView.getViewName()).isNull(); } @Test public void viewName() throws Exception { this.controller.setViewName("view"); ModelAndView modelAndView = this.controller.handleRequest(this.request, this.response); - assertEquals("view", modelAndView.getViewName()); + assertThat(modelAndView.getViewName()).isEqualTo("view"); } @Test @@ -64,16 +62,16 @@ public class ParameterizableViewControllerTests { this.controller.setViewName("view"); this.controller.setStatusCode(HttpStatus.NOT_FOUND); ModelAndView modelAndView = this.controller.handleRequest(this.request, this.response); - assertEquals("view", modelAndView.getViewName()); - assertEquals(404, this.response.getStatus()); + assertThat(modelAndView.getViewName()).isEqualTo("view"); + assertThat(this.response.getStatus()).isEqualTo(404); } @Test public void viewNameAndStatus204() throws Exception { this.controller.setStatusCode(HttpStatus.NO_CONTENT); ModelAndView modelAndView = this.controller.handleRequest(this.request, this.response); - assertNull(modelAndView); - assertEquals(204, this.response.getStatus()); + assertThat(modelAndView).isNull(); + assertThat(this.response.getStatus()).isEqualTo(204); } @Test @@ -82,9 +80,9 @@ public class ParameterizableViewControllerTests { this.controller.setViewName("/foo"); ModelAndView modelAndView = this.controller.handleRequest(this.request, this.response); - assertEquals("redirect:/foo", modelAndView.getViewName()); - assertEquals("3xx status should be left to RedirectView to set", 200, this.response.getStatus()); - assertEquals(HttpStatus.PERMANENT_REDIRECT, this.request.getAttribute(View.RESPONSE_STATUS_ATTRIBUTE)); + assertThat(modelAndView.getViewName()).isEqualTo("redirect:/foo"); + assertThat(this.response.getStatus()).as("3xx status should be left to RedirectView to set").isEqualTo(200); + assertThat(this.request.getAttribute(View.RESPONSE_STATUS_ATTRIBUTE)).isEqualTo(HttpStatus.PERMANENT_REDIRECT); } @Test @@ -93,9 +91,9 @@ public class ParameterizableViewControllerTests { this.controller.setViewName("redirect:/foo"); ModelAndView modelAndView = this.controller.handleRequest(this.request, this.response); - assertEquals("redirect:/foo", modelAndView.getViewName()); - assertEquals("3xx status should be left to RedirectView to set", 200, this.response.getStatus()); - assertEquals(HttpStatus.PERMANENT_REDIRECT, this.request.getAttribute(View.RESPONSE_STATUS_ATTRIBUTE)); + assertThat(modelAndView.getViewName()).isEqualTo("redirect:/foo"); + assertThat(this.response.getStatus()).as("3xx status should be left to RedirectView to set").isEqualTo(200); + assertThat(this.request.getAttribute(View.RESPONSE_STATUS_ATTRIBUTE)).isEqualTo(HttpStatus.PERMANENT_REDIRECT); } @Test @@ -103,7 +101,7 @@ public class ParameterizableViewControllerTests { RedirectView view = new RedirectView("/foo"); this.controller.setView(view); ModelAndView modelAndView = this.controller.handleRequest(this.request, this.response); - assertSame(view, modelAndView.getView()); + assertThat(modelAndView.getView()).isSameAs(view); } @Test @@ -111,8 +109,8 @@ public class ParameterizableViewControllerTests { this.controller.setStatusCode(HttpStatus.NOT_FOUND); this.controller.setStatusOnly(true); ModelAndView modelAndView = this.controller.handleRequest(this.request, this.response); - assertNull(modelAndView); - assertEquals(404, this.response.getStatus()); + assertThat(modelAndView).isNull(); + assertThat(this.response.getStatus()).isEqualTo(404); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java index 4b95f0520a1..dbde2fb141a 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java @@ -29,7 +29,7 @@ import org.springframework.format.support.FormattingConversionService; import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.DataBinder; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @@ -56,7 +56,7 @@ public class RedirectAttributesModelMapTests { @Test public void addAttributePrimitiveType() { this.redirectAttributes.addAttribute("speed", 65); - assertEquals("65", this.redirectAttributes.get("speed")); + assertThat(this.redirectAttributes.get("speed")).isEqualTo("65"); } @Test @@ -64,12 +64,12 @@ public class RedirectAttributesModelMapTests { String attrName = "person"; this.redirectAttributes.addAttribute(attrName, new TestBean("Fred")); - assertEquals("ConversionService should have invoked toString()", "Fred", this.redirectAttributes.get(attrName)); + assertThat(this.redirectAttributes.get(attrName)).as("ConversionService should have invoked toString()").isEqualTo("Fred"); this.conversionService.addConverter(new TestBeanConverter()); this.redirectAttributes.addAttribute(attrName, new TestBean("Fred")); - assertEquals("Type converter should have been used", "[Fred]", this.redirectAttributes.get(attrName)); + assertThat(this.redirectAttributes.get(attrName)).as("Type converter should have been used").isEqualTo("[Fred]"); } @Test @@ -78,22 +78,22 @@ public class RedirectAttributesModelMapTests { RedirectAttributesModelMap model = new RedirectAttributesModelMap(); model.addAttribute(attrName, new TestBean("Fred")); - assertEquals("toString() should have been used", "Fred", model.get(attrName)); + assertThat(model.get(attrName)).as("toString() should have been used").isEqualTo("Fred"); } @Test public void addAttributeValue() { this.redirectAttributes.addAttribute(new TestBean("Fred")); - assertEquals("Fred", this.redirectAttributes.get("testBean")); + assertThat(this.redirectAttributes.get("testBean")).isEqualTo("Fred"); } @Test public void addAllAttributesList() { this.redirectAttributes.addAllAttributes(Arrays.asList(new TestBean("Fred"), new Integer(5))); - assertEquals("Fred", this.redirectAttributes.get("testBean")); - assertEquals("5", this.redirectAttributes.get("integer")); + assertThat(this.redirectAttributes.get("testBean")).isEqualTo("Fred"); + assertThat(this.redirectAttributes.get("integer")).isEqualTo("5"); } @Test @@ -103,8 +103,8 @@ public class RedirectAttributesModelMapTests { map.put("age", 33); this.redirectAttributes.addAllAttributes(map); - assertEquals("Fred", this.redirectAttributes.get("person")); - assertEquals("33", this.redirectAttributes.get("age")); + assertThat(this.redirectAttributes.get("person")).isEqualTo("Fred"); + assertThat(this.redirectAttributes.get("age")).isEqualTo("33"); } @Test @@ -116,15 +116,15 @@ public class RedirectAttributesModelMapTests { this.redirectAttributes.addAttribute("person", new TestBean("Ralph")); this.redirectAttributes.mergeAttributes(map); - assertEquals("Ralph", this.redirectAttributes.get("person")); - assertEquals("33", this.redirectAttributes.get("age")); + assertThat(this.redirectAttributes.get("person")).isEqualTo("Ralph"); + assertThat(this.redirectAttributes.get("age")).isEqualTo("33"); } @Test public void put() { this.redirectAttributes.put("testBean", new TestBean("Fred")); - assertEquals("Fred", this.redirectAttributes.get("testBean")); + assertThat(this.redirectAttributes.get("testBean")).isEqualTo("Fred"); } @Test @@ -134,8 +134,8 @@ public class RedirectAttributesModelMapTests { map.put("age", 33); this.redirectAttributes.putAll(map); - assertEquals("Fred", this.redirectAttributes.get("person")); - assertEquals("33", this.redirectAttributes.get("age")); + assertThat(this.redirectAttributes.get("person")).isEqualTo("Fred"); + assertThat(this.redirectAttributes.get("age")).isEqualTo("33"); } public static class TestBeanConverter implements Converter { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/AppCacheManifestTransformerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/AppCacheManifestTransformerTests.java index 000b29a63e8..189033ab8e0 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/AppCacheManifestTransformerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/AppCacheManifestTransformerTests.java @@ -30,7 +30,6 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; /** * Unit tests for {@link AppCacheManifestTransformer}. @@ -82,7 +81,7 @@ public class AppCacheManifestTransformerTests { Resource resource = getResource("foo.css"); Resource result = this.transformer.transform(this.request, resource, this.chain); - assertEquals(resource, result); + assertThat(result).isEqualTo(resource); } @Test @@ -91,7 +90,7 @@ public class AppCacheManifestTransformerTests { Resource resource = getResource("error.appcache"); Resource result = this.transformer.transform(this.request, resource, this.chain); - assertEquals(resource, result); + assertThat(result).isEqualTo(resource); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/CachingResourceResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/CachingResourceResolverTests.java index eea9b5a42c3..73524182a47 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/CachingResourceResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/CachingResourceResolverTests.java @@ -30,10 +30,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.mock.web.test.MockHttpServletRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for @@ -70,8 +67,8 @@ public class CachingResourceResolverTests { Resource expected = new ClassPathResource("test/bar.css", getClass()); Resource actual = this.chain.resolveResource(null, "bar.css", this.locations); - assertNotSame(expected, actual); - assertEquals(expected, actual); + assertThat(actual).isNotSameAs(expected); + assertThat(actual).isEqualTo(expected); } @Test @@ -80,12 +77,12 @@ public class CachingResourceResolverTests { this.cache.put(resourceKey("bar.css"), expected); Resource actual = this.chain.resolveResource(null, "bar.css", this.locations); - assertSame(expected, actual); + assertThat(actual).isSameAs(expected); } @Test public void resolveResourceInternalNoMatch() { - assertNull(this.chain.resolveResource(null, "invalid.css", this.locations)); + assertThat(this.chain.resolveResource(null, "invalid.css", this.locations)).isNull(); } @Test @@ -93,7 +90,7 @@ public class CachingResourceResolverTests { String expected = "/foo.css"; String actual = this.chain.resolveUrlPath(expected, this.locations); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -102,12 +99,12 @@ public class CachingResourceResolverTests { this.cache.put(CachingResourceResolver.RESOLVED_URL_PATH_CACHE_KEY_PREFIX + "imaginary.css", expected); String actual = this.chain.resolveUrlPath("imaginary.css", this.locations); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void resolverUrlPathNoMatch() { - assertNull(this.chain.resolveUrlPath("invalid.css", this.locations)); + assertThat(this.chain.resolveUrlPath("invalid.css", this.locations)).isNull(); } @Test @@ -122,7 +119,7 @@ public class CachingResourceResolverTests { Resource expected = this.chain.resolveResource(request, file, this.locations); String cacheKey = resourceKey(file); - assertSame(expected, this.cache.get(cacheKey).get()); + assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); // 2. Resolve with Accept-Encoding @@ -131,7 +128,7 @@ public class CachingResourceResolverTests { expected = this.chain.resolveResource(request, file, this.locations); cacheKey = resourceKey(file + "+encoding=br,gzip"); - assertSame(expected, this.cache.get(cacheKey).get()); + assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); // 3. Resolve with Accept-Encoding but no matching codings @@ -140,7 +137,7 @@ public class CachingResourceResolverTests { expected = this.chain.resolveResource(request, file, this.locations); cacheKey = resourceKey(file); - assertSame(expected, this.cache.get(cacheKey).get()); + assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); } @Test @@ -152,7 +149,7 @@ public class CachingResourceResolverTests { String cacheKey = resourceKey(file); Object actual = this.cache.get(cacheKey).get(); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -163,11 +160,11 @@ public class CachingResourceResolverTests { this.cache.put(resourceKey("bar.css+encoding=gzip"), gzipped); MockHttpServletRequest request = new MockHttpServletRequest("GET", "bar.css"); - assertSame(resource, this.chain.resolveResource(request,"bar.css", this.locations)); + assertThat(this.chain.resolveResource(request, "bar.css", this.locations)).isSameAs(resource); request = new MockHttpServletRequest("GET", "bar.css"); request.addHeader("Accept-Encoding", "gzip"); - assertSame(gzipped, this.chain.resolveResource(request, "bar.css", this.locations)); + assertThat(this.chain.resolveResource(request, "bar.css", this.locations)).isSameAs(gzipped); } private static String resourceKey(String key) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ContentBasedVersionStrategyTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ContentBasedVersionStrategyTests.java index 30723bfa5ef..b90a7cc5d30 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ContentBasedVersionStrategyTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ContentBasedVersionStrategyTests.java @@ -27,8 +27,7 @@ import org.springframework.core.io.Resource; import org.springframework.util.DigestUtils; import org.springframework.util.FileCopyUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ContentVersionStrategy}. @@ -52,8 +51,8 @@ public class ContentBasedVersionStrategyTests { String hash = "7fbe76cdac6093784895bb4989203e5a"; String path = "font-awesome/css/font-awesome.min-" + hash + ".css"; - assertEquals(hash, this.versionStrategy.extractVersion(path)); - assertNull(this.versionStrategy.extractVersion("foo/bar.css")); + assertThat(this.versionStrategy.extractVersion(path)).isEqualTo(hash); + assertThat(this.versionStrategy.extractVersion("foo/bar.css")).isNull(); } @Test @@ -61,8 +60,7 @@ public class ContentBasedVersionStrategyTests { String hash = "7fbe76cdac6093784895bb4989203e5a"; String file = "font-awesome/css/font-awesome.min%s%s.css"; - assertEquals(String.format(file, "", ""), - this.versionStrategy.removeVersion(String.format(file, "-", hash), hash)); + assertThat(this.versionStrategy.removeVersion(String.format(file, "-", hash), hash)).isEqualTo(String.format(file, "", "")); } @Test @@ -70,12 +68,12 @@ public class ContentBasedVersionStrategyTests { Resource expected = new ClassPathResource("test/bar.css", getClass()); String hash = DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(expected.getInputStream())); - assertEquals(hash, this.versionStrategy.getResourceVersion(expected)); + assertThat(this.versionStrategy.getResourceVersion(expected)).isEqualTo(hash); } @Test public void addVersionToUrl() { - assertEquals("test/bar-123.css", this.versionStrategy.addVersion("test/bar.css", "123")); + assertThat(this.versionStrategy.addVersion("test/bar.css", "123")).isEqualTo("test/bar-123.css"); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/CssLinkResourceTransformerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/CssLinkResourceTransformerTests.java index 1f374c74b91..30f1e1080c6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/CssLinkResourceTransformerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/CssLinkResourceTransformerTests.java @@ -31,8 +31,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.util.StringUtils; import org.springframework.web.servlet.resource.EncodedResourceResolver.EncodedResource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link CssLinkResourceTransformer}. @@ -93,7 +92,7 @@ public class CssLinkResourceTransformerTests { TransformedResource actual = (TransformedResource) this.transformerChain.transform(this.request, css); String result = new String(actual.getByteArray(), StandardCharsets.UTF_8); result = StringUtils.deleteAny(result, "\r"); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); } @Test @@ -101,7 +100,7 @@ public class CssLinkResourceTransformerTests { this.request = new MockHttpServletRequest("GET", "/static/foo.css"); Resource expected = getResource("foo.css"); Resource actual = this.transformerChain.transform(this.request, expected); - assertSame(expected, actual); + assertThat(actual).isSameAs(expected); } @Test @@ -120,7 +119,7 @@ public class CssLinkResourceTransformerTests { TransformedResource transformedResource = (TransformedResource) chain.transform(this.request, resource); String result = new String(transformedResource.getByteArray(), StandardCharsets.UTF_8); result = StringUtils.deleteAny(result, "\r"); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); List locations = Collections.singletonList(resource); Mockito.verify(mockChain, Mockito.never()).resolveUrlPath("https://example.org/fonts/css", locations); @@ -134,7 +133,7 @@ public class CssLinkResourceTransformerTests { Resource expected = getResource("images/image.png"); Resource actual = this.transformerChain.transform(this.request, expected); - assertSame(expected, actual); + assertThat(actual).isSameAs(expected); } @Test @@ -147,7 +146,7 @@ public class CssLinkResourceTransformerTests { EncodedResource gzipped = new EncodedResource(original, "gzip", ".gz"); Resource actual = this.transformerChain.transform(this.request, gzipped); - assertSame(gzipped, actual); + assertThat(actual).isSameAs(gzipped); } @Test // https://github.com/spring-projects/spring-framework/issues/22602 @@ -162,7 +161,7 @@ public class CssLinkResourceTransformerTests { TransformedResource actual = (TransformedResource) this.transformerChain.transform(this.request, css); String result = new String(actual.getByteArray(), StandardCharsets.UTF_8); result = StringUtils.deleteAny(result, "\r"); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); } private Resource getResource(String filePath) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/EncodedResourceResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/EncodedResourceResolverTests.java index c89611ccf10..6cf7a33770e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/EncodedResourceResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/EncodedResourceResolverTests.java @@ -40,9 +40,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.util.FileCopyUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link EncodedResourceResolver}. @@ -106,13 +104,14 @@ public class EncodedResourceResolverTests { request.addHeader("Accept-Encoding", "gzip"); Resource actual = this.resolver.resolveResource(request, file, this.locations); - assertEquals(getResource(file + ".gz").getDescription(), actual.getDescription()); - assertEquals(getResource(file).getFilename(), actual.getFilename()); + assertThat(actual.getDescription()).isEqualTo(getResource(file + ".gz").getDescription()); + assertThat(actual.getFilename()).isEqualTo(getResource(file).getFilename()); - assertTrue(actual instanceof HttpResource); + boolean condition = actual instanceof HttpResource; + assertThat(condition).isTrue(); HttpHeaders headers = ((HttpResource) actual).getResponseHeaders(); - assertEquals("gzip", headers.getFirst(HttpHeaders.CONTENT_ENCODING)); - assertEquals("Accept-Encoding", headers.getFirst(HttpHeaders.VARY)); + assertThat(headers.getFirst(HttpHeaders.CONTENT_ENCODING)).isEqualTo("gzip"); + assertThat(headers.getFirst(HttpHeaders.VARY)).isEqualTo("Accept-Encoding"); } @Test @@ -122,9 +121,10 @@ public class EncodedResourceResolverTests { request.addHeader("Accept-Encoding", "gzip"); Resource resolved = this.resolver.resolveResource(request, file, this.locations); - assertEquals(getResource("foo.css.gz").getDescription(), resolved.getDescription()); - assertEquals(getResource("foo.css").getFilename(), resolved.getFilename()); - assertTrue(resolved instanceof HttpResource); + assertThat(resolved.getDescription()).isEqualTo(getResource("foo.css.gz").getDescription()); + assertThat(resolved.getFilename()).isEqualTo(getResource("foo.css").getFilename()); + boolean condition = resolved instanceof HttpResource; + assertThat(condition).isTrue(); } @Test @@ -135,17 +135,19 @@ public class EncodedResourceResolverTests { request.addHeader("Accept-Encoding", "gzip"); Resource resolved = this.resolver.resolveResource(request, file, this.locations); - assertEquals(getResource(file + ".gz").getDescription(), resolved.getDescription()); - assertEquals(getResource(file).getFilename(), resolved.getFilename()); - assertTrue(resolved instanceof HttpResource); + assertThat(resolved.getDescription()).isEqualTo(getResource(file + ".gz").getDescription()); + assertThat(resolved.getFilename()).isEqualTo(getResource(file).getFilename()); + boolean condition = resolved instanceof HttpResource; + assertThat(condition).isTrue(); // 2. Resolve unencoded resource request = new MockHttpServletRequest("GET", "/js/foo.js"); resolved = this.resolver.resolveResource(request, file, this.locations); - assertEquals(getResource(file).getDescription(), resolved.getDescription()); - assertEquals(getResource(file).getFilename(), resolved.getFilename()); - assertFalse(resolved instanceof HttpResource); + assertThat(resolved.getDescription()).isEqualTo(getResource(file).getDescription()); + assertThat(resolved.getFilename()).isEqualTo(getResource(file).getFilename()); + boolean condition1 = resolved instanceof HttpResource; + assertThat(condition1).isFalse(); } @Test // SPR-13149 @@ -153,8 +155,8 @@ public class EncodedResourceResolverTests { String file = "js/foo.js"; Resource resolved = this.resolver.resolveResource(null, file, this.locations); - assertEquals(getResource(file).getDescription(), resolved.getDescription()); - assertEquals(getResource(file).getFilename(), resolved.getFilename()); + assertThat(resolved.getDescription()).isEqualTo(getResource(file).getDescription()); + assertThat(resolved.getFilename()).isEqualTo(getResource(file).getFilename()); } private Resource getResource(String filePath) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/FixedVersionStrategyTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/FixedVersionStrategyTests.java index 4e780f4b9bb..62f9da972e3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/FixedVersionStrategyTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/FixedVersionStrategyTests.java @@ -19,9 +19,8 @@ package org.springframework.web.servlet.resource; import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * Unit tests for {@link FixedVersionStrategy}. @@ -53,24 +52,24 @@ public class FixedVersionStrategyTests { @Test public void extractVersion() { - assertEquals(VERSION, this.strategy.extractVersion(VERSION + "/" + PATH)); - assertNull(this.strategy.extractVersion(PATH)); + assertThat(this.strategy.extractVersion(VERSION + "/" + PATH)).isEqualTo(VERSION); + assertThat(this.strategy.extractVersion(PATH)).isNull(); } @Test public void removeVersion() { - assertEquals("/" + PATH, this.strategy.removeVersion(VERSION + "/" + PATH, VERSION)); + assertThat(this.strategy.removeVersion(VERSION + "/" + PATH, VERSION)).isEqualTo(("/" + PATH)); } @Test public void addVersion() { - assertEquals(VERSION + "/" + PATH, this.strategy.addVersion("/" + PATH, VERSION)); + assertThat(this.strategy.addVersion("/" + PATH, VERSION)).isEqualTo((VERSION + "/" + PATH)); } @Test // SPR-13727 public void addVersionRelativePath() { String relativePath = "../" + PATH; - assertEquals(relativePath, this.strategy.addVersion(relativePath, VERSION)); + assertThat(this.strategy.addVersion(relativePath, VERSION)).isEqualTo(relativePath); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/PathResourceResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/PathResourceResolverTests.java index 424eadf93d3..58aa5080266 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/PathResourceResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/PathResourceResolverTests.java @@ -31,12 +31,8 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.context.support.ServletContextResource; import org.springframework.web.util.UrlPathHelper; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * Unit tests for {@link PathResourceResolver}. @@ -55,7 +51,7 @@ public class PathResourceResolverTests { String requestPath = "bar.css"; Resource actual = this.resolver.resolveResource(null, requestPath, Collections.singletonList(location), null); - assertEquals(location.createRelative(requestPath), actual); + assertThat(actual).isEqualTo(location.createRelative(requestPath)); } @Test @@ -64,7 +60,7 @@ public class PathResourceResolverTests { String requestPath = "org/springframework/web/servlet/resource/test/bar.css"; Resource actual = this.resolver.resolveResource(null, requestPath, Collections.singletonList(location), null); - assertNotNull(actual); + assertThat(actual).isNotNull(); } @Test @@ -92,7 +88,7 @@ public class PathResourceResolverTests { if (!location.createRelative(requestPath).exists() && !requestPath.contains(":")) { fail(requestPath + " doesn't actually exist as a relative path"); } - assertNull(actual); + assertThat(actual).isNull(); } @Test @@ -105,7 +101,7 @@ public class PathResourceResolverTests { Resource location = getResource("main.css"); List locations = Collections.singletonList(location); String actual = this.resolver.resolveUrlPath("../testalternatepath/bar.css", locations, null); - assertEquals("../testalternatepath/bar.css", actual); + assertThat(actual).isEqualTo("../testalternatepath/bar.css"); } // SPR-12432 @@ -117,8 +113,8 @@ public class PathResourceResolverTests { ServletContextResource servletContextLocation = new ServletContextResource(context, "/webjars/"); ServletContextResource resource = new ServletContextResource(context, "/webjars/webjar-foo/1.0/foo.js"); - assertFalse(this.resolver.checkResource(resource, classpathLocation)); - assertTrue(this.resolver.checkResource(resource, servletContextLocation)); + assertThat(this.resolver.checkResource(resource, classpathLocation)).isFalse(); + assertThat(this.resolver.checkResource(resource, servletContextLocation)).isTrue(); } // SPR-12624 @@ -127,14 +123,14 @@ public class PathResourceResolverTests { String locationUrl= new UrlResource(getClass().getResource("./test/")).getURL().toExternalForm(); Resource location = new UrlResource(locationUrl.replace("/springframework","/../org/springframework")); - assertNotNull(this.resolver.resolveResource(null, "main.css", Collections.singletonList(location), null)); + assertThat(this.resolver.resolveResource(null, "main.css", Collections.singletonList(location), null)).isNotNull(); } // SPR-12747 @Test public void checkFileLocation() throws Exception { Resource resource = getResource("main.css"); - assertTrue(this.resolver.checkResource(resource, resource)); + assertThat(this.resolver.checkResource(resource, resource)).isTrue(); } // SPR-13241 @@ -143,7 +139,7 @@ public class PathResourceResolverTests { Resource webjarsLocation = new ClassPathResource("/META-INF/resources/webjars/", PathResourceResolver.class); String path = this.resolver.resolveUrlPathInternal("", Collections.singletonList(webjarsLocation), null); - assertNull(path); + assertThat(path).isNull(); } @Test @@ -156,19 +152,19 @@ public class PathResourceResolverTests { this.resolver.setLocationCharsets(Collections.singletonMap(location, StandardCharsets.ISO_8859_1)); this.resolver.resolveResource(new MockHttpServletRequest(), "/Ä ;ä.txt", locations, null); - assertEquals("%C4%20%3B%E4.txt", location.getSavedRelativePath()); + assertThat(location.getSavedRelativePath()).isEqualTo("%C4%20%3B%E4.txt"); // UTF-8 this.resolver.setLocationCharsets(Collections.singletonMap(location, StandardCharsets.UTF_8)); this.resolver.resolveResource(new MockHttpServletRequest(), "/Ä ;ä.txt", locations, null); - assertEquals("%C3%84%20%3B%C3%A4.txt", location.getSavedRelativePath()); + assertThat(location.getSavedRelativePath()).isEqualTo("%C3%84%20%3B%C3%A4.txt"); // UTF-8 by default this.resolver.setLocationCharsets(Collections.emptyMap()); this.resolver.resolveResource(new MockHttpServletRequest(), "/Ä ;ä.txt", locations, null); - assertEquals("%C3%84%20%3B%C3%A4.txt", location.getSavedRelativePath()); + assertThat(location.getSavedRelativePath()).isEqualTo("%C3%84%20%3B%C3%A4.txt"); } private Resource getResource(String filePath) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java index 2d5c35469c5..c9358ad35d7 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java @@ -44,10 +44,7 @@ import org.springframework.web.servlet.HandlerMapping; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -92,14 +89,14 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.handler.handleRequest(this.request, this.response); - assertEquals("text/css", this.response.getContentType()); - assertEquals(17, this.response.getContentLength()); - assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); - assertTrue(this.response.containsHeader("Last-Modified")); - assertEquals(resourceLastModified("test/foo.css") / 1000, this.response.getDateHeader("Last-Modified") / 1000); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); - assertEquals("h1 { color:red; }", this.response.getContentAsString()); + assertThat(this.response.getContentType()).isEqualTo("text/css"); + assertThat(this.response.getContentLength()).isEqualTo(17); + assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600"); + assertThat(this.response.containsHeader("Last-Modified")).isTrue(); + assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.css") / 1000); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); + assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }"); } @Test @@ -108,15 +105,15 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.handler.handleRequest(this.request, this.response); - assertEquals(200, this.response.getStatus()); - assertEquals("text/css", this.response.getContentType()); - assertEquals(17, this.response.getContentLength()); - assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); - assertTrue(this.response.containsHeader("Last-Modified")); - assertEquals(resourceLastModified("test/foo.css") / 1000, this.response.getDateHeader("Last-Modified") / 1000); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); - assertEquals(0, this.response.getContentAsByteArray().length); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getContentType()).isEqualTo("text/css"); + assertThat(this.response.getContentLength()).isEqualTo(17); + assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600"); + assertThat(this.response.containsHeader("Last-Modified")).isTrue(); + assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.css") / 1000); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); + assertThat(this.response.getContentAsByteArray().length).isEqualTo(0); } @Test @@ -125,8 +122,8 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.handler.handleRequest(this.request, this.response); - assertEquals(200, this.response.getStatus()); - assertEquals("GET,HEAD,OPTIONS", this.response.getHeader("Allow")); + assertThat(this.response.getStatus()).isEqualTo(200); + assertThat(this.response.getHeader("Allow")).isEqualTo("GET,HEAD,OPTIONS"); } @Test @@ -135,11 +132,11 @@ public class ResourceHttpRequestHandlerTests { this.handler.setCacheSeconds(0); this.handler.handleRequest(this.request, this.response); - assertEquals("no-store", this.response.getHeader("Cache-Control")); - assertTrue(this.response.containsHeader("Last-Modified")); - assertEquals(resourceLastModified("test/foo.css") / 1000, this.response.getDateHeader("Last-Modified") / 1000); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); + assertThat(this.response.getHeader("Cache-Control")).isEqualTo("no-store"); + assertThat(this.response.containsHeader("Last-Modified")).isTrue(); + assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.css") / 1000); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -152,9 +149,9 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "versionString/foo.css"); this.handler.handleRequest(this.request, this.response); - assertEquals("\"versionString\"", this.response.getHeader("ETag")); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); + assertThat(this.response.getHeader("ETag")).isEqualTo("\"versionString\""); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -167,12 +164,12 @@ public class ResourceHttpRequestHandlerTests { this.handler.setAlwaysMustRevalidate(true); this.handler.handleRequest(this.request, this.response); - assertEquals("max-age=3600, must-revalidate", this.response.getHeader("Cache-Control")); - assertTrue(this.response.getDateHeader("Expires") >= System.currentTimeMillis() - 1000 + (3600 * 1000)); - assertTrue(this.response.containsHeader("Last-Modified")); - assertEquals(resourceLastModified("test/foo.css") / 1000, this.response.getDateHeader("Last-Modified") / 1000); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); + assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600, must-revalidate"); + assertThat(this.response.getDateHeader("Expires") >= System.currentTimeMillis() - 1000 + (3600 * 1000)).isTrue(); + assertThat(this.response.containsHeader("Last-Modified")).isTrue(); + assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.css") / 1000); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -185,14 +182,14 @@ public class ResourceHttpRequestHandlerTests { this.handler.setUseCacheControlHeader(true); this.handler.handleRequest(this.request, this.response); - assertEquals("no-cache", this.response.getHeader("Pragma")); + assertThat(this.response.getHeader("Pragma")).isEqualTo("no-cache"); assertThat(this.response.getHeaderValues("Cache-Control")).hasSize(1); - assertEquals("no-cache", this.response.getHeader("Cache-Control")); - assertTrue(this.response.getDateHeader("Expires") <= System.currentTimeMillis()); - assertTrue(this.response.containsHeader("Last-Modified")); - assertEquals(resourceLastModified("test/foo.css") / 1000, this.response.getDateHeader("Last-Modified") / 1000); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); + assertThat(this.response.getHeader("Cache-Control")).isEqualTo("no-cache"); + assertThat(this.response.getDateHeader("Expires") <= System.currentTimeMillis()).isTrue(); + assertThat(this.response.containsHeader("Last-Modified")).isTrue(); + assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.css") / 1000); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -200,12 +197,12 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.html"); this.handler.handleRequest(this.request, this.response); - assertEquals("text/html", this.response.getContentType()); - assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); - assertTrue(this.response.containsHeader("Last-Modified")); - assertEquals(resourceLastModified("test/foo.html") / 1000, this.response.getDateHeader("Last-Modified") / 1000); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); + assertThat(this.response.getContentType()).isEqualTo("text/html"); + assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600"); + assertThat(this.response.containsHeader("Last-Modified")).isTrue(); + assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("test/foo.html") / 1000); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -213,15 +210,14 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "baz.css"); this.handler.handleRequest(this.request, this.response); - assertEquals("text/css", this.response.getContentType()); - assertEquals(17, this.response.getContentLength()); - assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); - assertTrue(this.response.containsHeader("Last-Modified")); - assertEquals(resourceLastModified("testalternatepath/baz.css") / 1000, - this.response.getDateHeader("Last-Modified") / 1000); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); - assertEquals("h1 { color:red; }", this.response.getContentAsString()); + assertThat(this.response.getContentType()).isEqualTo("text/css"); + assertThat(this.response.getContentLength()).isEqualTo(17); + assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600"); + assertThat(this.response.containsHeader("Last-Modified")).isTrue(); + assertThat(this.response.getDateHeader("Last-Modified") / 1000).isEqualTo(resourceLastModified("testalternatepath/baz.css") / 1000); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); + assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }"); } @Test @@ -229,8 +225,8 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "js/foo.js"); this.handler.handleRequest(this.request, this.response); - assertEquals("text/javascript", this.response.getContentType()); - assertEquals("function foo() { console.log(\"hello world\"); }", this.response.getContentAsString()); + assertThat(this.response.getContentType()).isEqualTo("text/javascript"); + assertThat(this.response.getContentAsString()).isEqualTo("function foo() { console.log(\"hello world\"); }"); } @Test @@ -238,8 +234,8 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "js/baz.js"); this.handler.handleRequest(this.request, this.response); - assertEquals("text/javascript", this.response.getContentType()); - assertEquals("function foo() { console.log(\"hello world\"); }", this.response.getContentAsString()); + assertThat(this.response.getContentType()).isEqualTo("text/javascript"); + assertThat(this.response.getContentAsString()).isEqualTo("function foo() { console.log(\"hello world\"); }"); } @Test // SPR-13658 @@ -259,8 +255,8 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.bar"); handler.handleRequest(this.request, this.response); - assertEquals("foo/bar", this.response.getContentType()); - assertEquals("h1 { color:red; }", this.response.getContentAsString()); + assertThat(this.response.getContentType()).isEqualTo("foo/bar"); + assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }"); } @Test // SPR-14577 @@ -281,7 +277,7 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.html"); handler.handleRequest(this.request, this.response); - assertEquals("text/html", this.response.getContentType()); + assertThat(this.response.getContentType()).isEqualTo("text/html"); } @Test // SPR-14368 @@ -306,8 +302,8 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); handler.handleRequest(this.request, this.response); - assertEquals("foo/bar", this.response.getContentType()); - assertEquals("h1 { color:red; }", this.response.getContentAsString()); + assertThat(this.response.getContentType()).isEqualTo("foo/bar"); + assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }"); } @Test @@ -350,7 +346,7 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, requestPath); this.response = new MockHttpServletResponse(); handler.handleRequest(this.request, this.response); - assertEquals(HttpStatus.NOT_FOUND.value(), this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @Test @@ -395,7 +391,7 @@ public class ResourceHttpRequestHandlerTests { if (!location.createRelative(requestPath).exists() && !requestPath.contains(":")) { fail(requestPath + " doesn't actually exist as a relative path"); } - assertEquals(HttpStatus.NOT_FOUND.value(), this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @Test @@ -403,43 +399,43 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/%foo%/bar.txt"); this.response = new MockHttpServletResponse(); this.handler.handleRequest(this.request, this.response); - assertEquals(404, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(404); } @Test public void processPath() { // Unchanged - assertSame("/foo/bar", this.handler.processPath("/foo/bar")); - assertSame("foo/bar", this.handler.processPath("foo/bar")); + assertThat(this.handler.processPath("/foo/bar")).isSameAs("/foo/bar"); + assertThat(this.handler.processPath("foo/bar")).isSameAs("foo/bar"); // leading whitespace control characters (00-1F) - assertEquals("/foo/bar", this.handler.processPath(" /foo/bar")); - assertEquals("/foo/bar", this.handler.processPath((char) 1 + "/foo/bar")); - assertEquals("/foo/bar", this.handler.processPath((char) 31 + "/foo/bar")); - assertEquals("foo/bar", this.handler.processPath(" foo/bar")); - assertEquals("foo/bar", this.handler.processPath((char) 31 + "foo/bar")); + assertThat(this.handler.processPath(" /foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath((char) 1 + "/foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath((char) 31 + "/foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath(" foo/bar")).isEqualTo("foo/bar"); + assertThat(this.handler.processPath((char) 31 + "foo/bar")).isEqualTo("foo/bar"); // leading control character 0x7F (DEL) - assertEquals("/foo/bar", this.handler.processPath((char) 127 + "/foo/bar")); - assertEquals("/foo/bar", this.handler.processPath((char) 127 + "/foo/bar")); + assertThat(this.handler.processPath((char) 127 + "/foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath((char) 127 + "/foo/bar")).isEqualTo("/foo/bar"); // leading control and '/' characters - assertEquals("/foo/bar", this.handler.processPath(" / foo/bar")); - assertEquals("/foo/bar", this.handler.processPath(" / / foo/bar")); - assertEquals("/foo/bar", this.handler.processPath(" // /// //// foo/bar")); - assertEquals("/foo/bar", this.handler.processPath((char) 1 + " / " + (char) 127 + " // foo/bar")); + assertThat(this.handler.processPath(" / foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath(" / / foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath(" // /// //// foo/bar")).isEqualTo("/foo/bar"); + assertThat(this.handler.processPath((char) 1 + " / " + (char) 127 + " // foo/bar")).isEqualTo("/foo/bar"); // root or empty path - assertEquals("", this.handler.processPath(" ")); - assertEquals("/", this.handler.processPath("/")); - assertEquals("/", this.handler.processPath("///")); - assertEquals("/", this.handler.processPath("/ / / ")); - assertEquals("/", this.handler.processPath("\\/ \\/ \\/ ")); + assertThat(this.handler.processPath(" ")).isEqualTo(""); + assertThat(this.handler.processPath("/")).isEqualTo("/"); + assertThat(this.handler.processPath("///")).isEqualTo("/"); + assertThat(this.handler.processPath("/ / / ")).isEqualTo("/"); + assertThat(this.handler.processPath("\\/ \\/ \\/ ")).isEqualTo("/"); // duplicate slash or backslash - assertEquals("/foo/ /bar/baz/", this.handler.processPath("//foo/ /bar//baz//")); - assertEquals("/foo/ /bar/baz/", this.handler.processPath("\\\\foo\\ \\bar\\\\baz\\\\")); - assertEquals("foo/bar", this.handler.processPath("foo\\\\/\\////bar")); + assertThat(this.handler.processPath("//foo/ /bar//baz//")).isEqualTo("/foo/ /bar/baz/"); + assertThat(this.handler.processPath("\\\\foo\\ \\bar\\\\baz\\\\")).isEqualTo("/foo/ /bar/baz/"); + assertThat(this.handler.processPath("foo\\\\/\\////bar")).isEqualTo("foo/bar"); } @@ -448,10 +444,10 @@ public class ResourceHttpRequestHandlerTests { PathResourceResolver resolver = (PathResourceResolver) this.handler.getResourceResolvers().get(0); Resource[] locations = resolver.getAllowedLocations(); - assertEquals(3, locations.length); - assertEquals("test/", ((ClassPathResource) locations[0]).getPath()); - assertEquals("testalternatepath/", ((ClassPathResource) locations[1]).getPath()); - assertEquals("META-INF/resources/webjars/", ((ClassPathResource) locations[2]).getPath()); + assertThat(locations.length).isEqualTo(3); + assertThat(((ClassPathResource) locations[0]).getPath()).isEqualTo("test/"); + assertThat(((ClassPathResource) locations[1]).getPath()).isEqualTo("testalternatepath/"); + assertThat(((ClassPathResource) locations[2]).getPath()).isEqualTo("META-INF/resources/webjars/"); } @Test @@ -469,8 +465,8 @@ public class ResourceHttpRequestHandlerTests { handler.afterPropertiesSet(); Resource[] locations = pathResolver.getAllowedLocations(); - assertEquals(1, locations.length); - assertEquals("test/", ((ClassPathResource) locations[0]).getPath()); + assertThat(locations.length).isEqualTo(1); + assertThat(((ClassPathResource) locations[0]).getPath()).isEqualTo("test/"); } @Test @@ -478,7 +474,7 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.request.addHeader("If-Modified-Since", resourceLastModified("test/foo.css")); this.handler.handleRequest(this.request, this.response); - assertEquals(HttpServletResponse.SC_NOT_MODIFIED, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_NOT_MODIFIED); } @Test @@ -486,29 +482,29 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.request.addHeader("If-Modified-Since", resourceLastModified("test/foo.css") / 1000 * 1000 - 1); this.handler.handleRequest(this.request, this.response); - assertEquals(HttpServletResponse.SC_OK, this.response.getStatus()); - assertEquals("h1 { color:red; }", this.response.getContentAsString()); + assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }"); } @Test public void directory() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "js/"); this.handler.handleRequest(this.request, this.response); - assertEquals(404, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(404); } @Test public void directoryInJarFile() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "underscorejs/"); this.handler.handleRequest(this.request, this.response); - assertEquals(404, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(404); } @Test public void missingResourcePath() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, ""); this.handler.handleRequest(this.request, this.response); - assertEquals(404, this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(404); } @Test @@ -538,7 +534,7 @@ public class ResourceHttpRequestHandlerTests { this.request.setMethod(httpMethod.name()); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "not-there.css"); this.handler.handleRequest(this.request, this.response); - assertEquals(HttpStatus.NOT_FOUND.value(), this.response.getStatus()); + assertThat(this.response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @Test @@ -547,13 +543,13 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); - assertEquals(206, this.response.getStatus()); - assertEquals("text/plain", this.response.getContentType()); - assertEquals(2, this.response.getContentLength()); - assertEquals("bytes 0-1/10", this.response.getHeader("Content-Range")); - assertEquals("So", this.response.getContentAsString()); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); + assertThat(this.response.getStatus()).isEqualTo(206); + assertThat(this.response.getContentType()).isEqualTo("text/plain"); + assertThat(this.response.getContentLength()).isEqualTo(2); + assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 0-1/10"); + assertThat(this.response.getContentAsString()).isEqualTo("So"); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -562,13 +558,13 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); - assertEquals(206, this.response.getStatus()); - assertEquals("text/plain", this.response.getContentType()); - assertEquals(1, this.response.getContentLength()); - assertEquals("bytes 9-9/10", this.response.getHeader("Content-Range")); - assertEquals(".", this.response.getContentAsString()); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); + assertThat(this.response.getStatus()).isEqualTo(206); + assertThat(this.response.getContentType()).isEqualTo("text/plain"); + assertThat(this.response.getContentLength()).isEqualTo(1); + assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 9-9/10"); + assertThat(this.response.getContentAsString()).isEqualTo("."); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -577,13 +573,13 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); - assertEquals(206, this.response.getStatus()); - assertEquals("text/plain", this.response.getContentType()); - assertEquals(1, this.response.getContentLength()); - assertEquals("bytes 9-9/10", this.response.getHeader("Content-Range")); - assertEquals(".", this.response.getContentAsString()); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); + assertThat(this.response.getStatus()).isEqualTo(206); + assertThat(this.response.getContentType()).isEqualTo("text/plain"); + assertThat(this.response.getContentLength()).isEqualTo(1); + assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 9-9/10"); + assertThat(this.response.getContentAsString()).isEqualTo("."); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -592,13 +588,13 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); - assertEquals(206, this.response.getStatus()); - assertEquals("text/plain", this.response.getContentType()); - assertEquals(1, this.response.getContentLength()); - assertEquals("bytes 9-9/10", this.response.getHeader("Content-Range")); - assertEquals(".", this.response.getContentAsString()); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); + assertThat(this.response.getStatus()).isEqualTo(206); + assertThat(this.response.getContentType()).isEqualTo("text/plain"); + assertThat(this.response.getContentLength()).isEqualTo(1); + assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 9-9/10"); + assertThat(this.response.getContentAsString()).isEqualTo("."); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -607,13 +603,13 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); - assertEquals(206, this.response.getStatus()); - assertEquals("text/plain", this.response.getContentType()); - assertEquals(10, this.response.getContentLength()); - assertEquals("bytes 0-9/10", this.response.getHeader("Content-Range")); - assertEquals("Some text.", this.response.getContentAsString()); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); + assertThat(this.response.getStatus()).isEqualTo(206); + assertThat(this.response.getContentType()).isEqualTo("text/plain"); + assertThat(this.response.getContentLength()).isEqualTo(10); + assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 0-9/10"); + assertThat(this.response.getContentAsString()).isEqualTo("Some text."); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -622,10 +618,10 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); - assertEquals(416, this.response.getStatus()); - assertEquals("bytes */10", this.response.getHeader("Content-Range")); - assertEquals("bytes", this.response.getHeader("Accept-Ranges")); - assertEquals(1, this.response.getHeaders("Accept-Ranges").size()); + assertThat(this.response.getStatus()).isEqualTo(416); + assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes */10"); + assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); + assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @@ -634,28 +630,28 @@ public class ResourceHttpRequestHandlerTests { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); - assertEquals(206, this.response.getStatus()); - assertTrue(this.response.getContentType().startsWith("multipart/byteranges; boundary=")); + assertThat(this.response.getStatus()).isEqualTo(206); + assertThat(this.response.getContentType().startsWith("multipart/byteranges; boundary=")).isTrue(); String boundary = "--" + this.response.getContentType().substring(31); String content = this.response.getContentAsString(); String[] ranges = StringUtils.tokenizeToStringArray(content, "\r\n", false, true); - assertEquals(boundary, ranges[0]); - assertEquals("Content-Type: text/plain", ranges[1]); - assertEquals("Content-Range: bytes 0-1/10", ranges[2]); - assertEquals("So", ranges[3]); + assertThat(ranges[0]).isEqualTo(boundary); + assertThat(ranges[1]).isEqualTo("Content-Type: text/plain"); + assertThat(ranges[2]).isEqualTo("Content-Range: bytes 0-1/10"); + assertThat(ranges[3]).isEqualTo("So"); - assertEquals(boundary, ranges[4]); - assertEquals("Content-Type: text/plain", ranges[5]); - assertEquals("Content-Range: bytes 4-5/10", ranges[6]); - assertEquals(" t", ranges[7]); + assertThat(ranges[4]).isEqualTo(boundary); + assertThat(ranges[5]).isEqualTo("Content-Type: text/plain"); + assertThat(ranges[6]).isEqualTo("Content-Range: bytes 4-5/10"); + assertThat(ranges[7]).isEqualTo(" t"); - assertEquals(boundary, ranges[8]); - assertEquals("Content-Type: text/plain", ranges[9]); - assertEquals("Content-Range: bytes 8-9/10", ranges[10]); - assertEquals("t.", ranges[11]); + assertThat(ranges[8]).isEqualTo(boundary); + assertThat(ranges[9]).isEqualTo("Content-Type: text/plain"); + assertThat(ranges[10]).isEqualTo("Content-Range: bytes 8-9/10"); + assertThat(ranges[11]).isEqualTo("t."); } @Test // SPR-14005 @@ -665,7 +661,7 @@ public class ResourceHttpRequestHandlerTests { this.handler.handleRequest(this.request, this.response); - assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); + assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceTransformerSupportTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceTransformerSupportTests.java index f259d859f87..78a2f01a6b8 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceTransformerSupportTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceTransformerSupportTests.java @@ -27,7 +27,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.mock.web.test.MockHttpServletRequest; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@code ResourceTransformerSupport}. @@ -79,7 +79,7 @@ public class ResourceTransformerSupportTests { Resource resource = getResource("main.css"); String actual = this.transformer.resolveUrlPath(resourcePath, this.request, resource, this.transformerChain); - assertEquals("/context/servlet/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", actual); + assertThat(actual).isEqualTo("/context/servlet/resources/bar-11e16cf79faee7ac698c805cf28248d2.css"); } @Test @@ -87,7 +87,7 @@ public class ResourceTransformerSupportTests { Resource resource = getResource("main.css"); String actual = this.transformer.resolveUrlPath("bar.css", this.request, resource, this.transformerChain); - assertEquals("bar-11e16cf79faee7ac698c805cf28248d2.css", actual); + assertThat(actual).isEqualTo("bar-11e16cf79faee7ac698c805cf28248d2.css"); } @Test @@ -95,18 +95,18 @@ public class ResourceTransformerSupportTests { Resource resource = getResource("images/image.png"); String actual = this.transformer.resolveUrlPath("../bar.css", this.request, resource, this.transformerChain); - assertEquals("../bar-11e16cf79faee7ac698c805cf28248d2.css", actual); + assertThat(actual).isEqualTo("../bar-11e16cf79faee7ac698c805cf28248d2.css"); } @Test public void toAbsolutePath() { String absolute = this.transformer.toAbsolutePath("img/image.png", new MockHttpServletRequest("GET", "/resources/style.css")); - assertEquals("/resources/img/image.png", absolute); + assertThat(absolute).isEqualTo("/resources/img/image.png"); absolute = this.transformer.toAbsolutePath("/img/image.png", new MockHttpServletRequest("GET", "/resources/style.css")); - assertEquals("/img/image.png", absolute); + assertThat(absolute).isEqualTo("/img/image.png"); } private Resource getResource(String filePath) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilterTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilterTests.java index 7fa60a9284d..37d74bb1f98 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilterTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilterTests.java @@ -29,7 +29,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@code ResourceUrlEncodingFilter}. @@ -94,7 +94,7 @@ public class ResourceUrlEncodingFilterTests { request.setRequestURI("/forwarded"); request.setContextPath("/"); String result = ((HttpServletResponse) res).encodeURL("/context/resources/bar.css"); - assertEquals("/context/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", result); + assertThat(result).isEqualTo("/context/resources/bar-11e16cf79faee7ac698c805cf28248d2.css"); }); } @@ -161,7 +161,7 @@ public class ResourceUrlEncodingFilterTests { this.filter.doFilter(request, new MockHttpServletResponse(), (req, res) -> { req.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); String result = ((HttpServletResponse) res).encodeURL(url); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); }); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderJavaConfigTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderJavaConfigTests.java index f2bd4ab9913..e5f0c6a0fd7 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderJavaConfigTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderJavaConfigTests.java @@ -32,7 +32,7 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** @@ -79,8 +79,7 @@ public class ResourceUrlProviderJavaConfigTests { this.request.setServletPath("/index"); this.filterChain.doFilter(this.request, this.response); - assertEquals("/myapp/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css", - resolvePublicResourceUrlPath("/myapp/resources/foo.css")); + assertThat(resolvePublicResourceUrlPath("/myapp/resources/foo.css")).isEqualTo("/myapp/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css"); } @Test @@ -89,8 +88,7 @@ public class ResourceUrlProviderJavaConfigTests { this.request.setServletPath("/myservlet"); this.filterChain.doFilter(this.request, this.response); - assertEquals("/myapp/myservlet/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css", - resolvePublicResourceUrlPath("/myapp/myservlet/resources/foo.css")); + assertThat(resolvePublicResourceUrlPath("/myapp/myservlet/resources/foo.css")).isEqualTo("/myapp/myservlet/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css"); } @Test @@ -99,7 +97,7 @@ public class ResourceUrlProviderJavaConfigTests { this.request.setServletPath("/myservlet"); this.filterChain.doFilter(this.request, this.response); - assertEquals("/myapp/myservlet/index", resolvePublicResourceUrlPath("/myapp/myservlet/index")); + assertThat(resolvePublicResourceUrlPath("/myapp/myservlet/index")).isEqualTo("/myapp/myservlet/index"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderTests.java index 901cd2c8a60..ef240d17de2 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderTests.java @@ -34,9 +34,6 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -73,7 +70,7 @@ public class ResourceUrlProviderTests { @Test public void getStaticResourceUrl() { String url = this.urlProvider.getForLookupPath("/resources/foo.css"); - assertEquals("/resources/foo.css", url); + assertThat(url).isEqualTo("/resources/foo.css"); } @Test // SPR-13374 @@ -84,11 +81,11 @@ public class ResourceUrlProviderTests { String url = "/resources/foo.css?foo=bar&url=https://example.org"; String resolvedUrl = this.urlProvider.getForRequestUrl(request, url); - assertEquals("/resources/foo.css?foo=bar&url=https://example.org", resolvedUrl); + assertThat(resolvedUrl).isEqualTo("/resources/foo.css?foo=bar&url=https://example.org"); url = "/resources/foo.css#hash"; resolvedUrl = this.urlProvider.getForRequestUrl(request, url); - assertEquals("/resources/foo.css#hash", resolvedUrl); + assertThat(resolvedUrl).isEqualTo("/resources/foo.css#hash"); } @Test // SPR-16526 @@ -98,7 +95,7 @@ public class ResourceUrlProviderTests { request.setRequestURI("/contextpath-longer-than-request-path/style.css"); String url = "/resources/foo.css"; String resolvedUrl = this.urlProvider.getForRequestUrl(request, url); - assertNull(resolvedUrl); + assertThat((Object) resolvedUrl).isNull(); } @Test @@ -114,7 +111,7 @@ public class ResourceUrlProviderTests { this.handler.setResourceResolvers(resolvers); String url = this.urlProvider.getForLookupPath("/resources/foo.css"); - assertEquals("/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css", url); + assertThat(url).isEqualTo("/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css"); } @Test // SPR-12647 @@ -135,7 +132,7 @@ public class ResourceUrlProviderTests { this.urlProvider.setHandlerMap(this.handlerMap); String url = this.urlProvider.getForLookupPath("/resources/foo.css"); - assertEquals("/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css", url); + assertThat(url).isEqualTo("/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css"); } @Test // SPR-12592 @@ -148,7 +145,7 @@ public class ResourceUrlProviderTests { ResourceUrlProvider urlProviderBean = context.getBean(ResourceUrlProvider.class); assertThat(urlProviderBean.getHandlerMap()).containsKey("/resources/**"); - assertFalse(urlProviderBean.isAutodetect()); + assertThat(urlProviderBean.isAutodetect()).isFalse(); } @Test // SPR-16296 @@ -167,7 +164,7 @@ public class ResourceUrlProviderTests { String lookupForPath = provider.getForLookupPath("/some-pattern/some-lib//some-resource"); // then - assertEquals("/some-pattern/some-path", lookupForPath); + assertThat(lookupForPath).isEqualTo("/some-pattern/some-path"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/VersionResourceResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/VersionResourceResolverTests.java index a8e69442a4d..069513d2b91 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/VersionResourceResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/VersionResourceResolverTests.java @@ -29,8 +29,6 @@ import org.springframework.core.io.Resource; import org.springframework.mock.web.test.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -73,7 +71,7 @@ public class VersionResourceResolverTests { this.resolver.setStrategyMap(Collections.singletonMap("/**", this.versionStrategy)); Resource actual = this.resolver.resolveResourceInternal(null, file, this.locations, this.chain); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); verify(this.chain, times(1)).resolveResource(null, file, this.locations); verify(this.versionStrategy, never()).extractVersion(file); } @@ -85,7 +83,7 @@ public class VersionResourceResolverTests { this.resolver.setStrategyMap(Collections.emptyMap()); Resource actual = this.resolver.resolveResourceInternal(null, file, this.locations, this.chain); - assertNull(actual); + assertThat((Object) actual).isNull(); verify(this.chain, times(1)).resolveResource(null, file, this.locations); } @@ -97,7 +95,7 @@ public class VersionResourceResolverTests { this.resolver.setStrategyMap(Collections.singletonMap("/**", this.versionStrategy)); Resource actual = this.resolver.resolveResourceInternal(null, file, this.locations, this.chain); - assertNull(actual); + assertThat((Object) actual).isNull(); verify(this.chain, times(1)).resolveResource(null, file, this.locations); verify(this.versionStrategy, times(1)).extractVersion(file); } @@ -114,7 +112,7 @@ public class VersionResourceResolverTests { this.resolver.setStrategyMap(Collections.singletonMap("/**", this.versionStrategy)); Resource actual = this.resolver.resolveResourceInternal(null, versionFile, this.locations, this.chain); - assertNull(actual); + assertThat((Object) actual).isNull(); verify(this.versionStrategy, times(1)).removeVersion(versionFile, version); } @@ -132,7 +130,7 @@ public class VersionResourceResolverTests { this.resolver.setStrategyMap(Collections.singletonMap("/**", this.versionStrategy)); Resource actual = this.resolver.resolveResourceInternal(null, versionFile, this.locations, this.chain); - assertNull(actual); + assertThat((Object) actual).isNull(); verify(this.versionStrategy, times(1)).getResourceVersion(expected); } @@ -152,10 +150,10 @@ public class VersionResourceResolverTests { this.resolver .setStrategyMap(Collections.singletonMap("/**", this.versionStrategy)); Resource actual = this.resolver.resolveResourceInternal(request, versionFile, this.locations, this.chain); - assertEquals(expected.getFilename(), actual.getFilename()); + assertThat(actual.getFilename()).isEqualTo(expected.getFilename()); verify(this.versionStrategy, times(1)).getResourceVersion(expected); assertThat(actual).isInstanceOf(HttpResource.class); - assertEquals("\"" + version + "\"", ((HttpResource)actual).getResponseHeaders().getETag()); + assertThat(((HttpResource)actual).getResponseHeaders().getETag()).isEqualTo("\"" + version + "\""); } @Test @@ -167,10 +165,10 @@ public class VersionResourceResolverTests { strategies.put("/**/*.js", jsStrategy); this.resolver.setStrategyMap(strategies); - assertEquals(catchAllStrategy, this.resolver.getStrategyForPath("foo.css")); - assertEquals(catchAllStrategy, this.resolver.getStrategyForPath("foo-js.css")); - assertEquals(jsStrategy, this.resolver.getStrategyForPath("foo.js")); - assertEquals(jsStrategy, this.resolver.getStrategyForPath("bar/foo.js")); + assertThat(this.resolver.getStrategyForPath("foo.css")).isEqualTo(catchAllStrategy); + assertThat(this.resolver.getStrategyForPath("foo-js.css")).isEqualTo(catchAllStrategy); + assertThat(this.resolver.getStrategyForPath("foo.js")).isEqualTo(jsStrategy); + assertThat(this.resolver.getStrategyForPath("bar/foo.js")).isEqualTo(jsStrategy); } // SPR-13883 diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/WebJarsResourceResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/WebJarsResourceResolverTests.java index 78350e7d70b..d5dbef01fa1 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/WebJarsResourceResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/WebJarsResourceResolverTests.java @@ -27,8 +27,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.mock.web.test.MockHttpServletRequest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -69,7 +68,7 @@ public class WebJarsResourceResolverTests { String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); - assertEquals(file, actual); + assertThat(actual).isEqualTo(file); verify(this.chain, times(1)).resolveUrlPath(file, this.locations); } @@ -81,7 +80,7 @@ public class WebJarsResourceResolverTests { String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); - assertNull(actual); + assertThat(actual).isNull(); verify(this.chain, times(1)).resolveUrlPath(file, this.locations); verify(this.chain, never()).resolveUrlPath("foo/2.3/foo.txt", this.locations); } @@ -95,7 +94,7 @@ public class WebJarsResourceResolverTests { String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); verify(this.chain, times(1)).resolveUrlPath(file, this.locations); verify(this.chain, times(1)).resolveUrlPath(expected, this.locations); } @@ -107,7 +106,7 @@ public class WebJarsResourceResolverTests { String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); - assertNull(actual); + assertThat(actual).isNull(); verify(this.chain, times(1)).resolveUrlPath(file, this.locations); verify(this.chain, never()).resolveUrlPath(null, this.locations); } @@ -121,7 +120,7 @@ public class WebJarsResourceResolverTests { Resource actual = this.resolver.resolveResource(this.request, file, this.locations, this.chain); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); verify(this.chain, times(1)).resolveResource(this.request, file, this.locations); } @@ -132,7 +131,7 @@ public class WebJarsResourceResolverTests { Resource actual = this.resolver.resolveResource(this.request, file, this.locations, this.chain); - assertNull(actual); + assertThat(actual).isNull(); verify(this.chain, times(1)).resolveResource(this.request, file, this.locations); verify(this.chain, never()).resolveResource(this.request, null, this.locations); } @@ -147,7 +146,7 @@ public class WebJarsResourceResolverTests { Resource actual = this.resolver.resolveResource(this.request, file, this.locations, this.chain); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); verify(this.chain, times(1)).resolveResource(this.request, file, this.locations); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/AnnotationConfigDispatcherServletInitializerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/AnnotationConfigDispatcherServletInitializerTests.java index 9723f35c60c..3faf96d80ec 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/AnnotationConfigDispatcherServletInitializerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/AnnotationConfigDispatcherServletInitializerTests.java @@ -43,10 +43,7 @@ import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.filter.HiddenHttpMethodFilter; import org.springframework.web.servlet.DispatcherServlet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test case for {@link AbstractAnnotationConfigDispatcherServletInitializer}. @@ -88,37 +85,38 @@ public class AnnotationConfigDispatcherServletInitializerTests { public void register() throws ServletException { initializer.onStartup(servletContext); - assertEquals(1, servlets.size()); - assertNotNull(servlets.get(SERVLET_NAME)); + assertThat(servlets.size()).isEqualTo(1); + assertThat(servlets.get(SERVLET_NAME)).isNotNull(); DispatcherServlet servlet = (DispatcherServlet) servlets.get(SERVLET_NAME); WebApplicationContext wac = servlet.getWebApplicationContext(); ((AnnotationConfigWebApplicationContext) wac).refresh(); - assertTrue(wac.containsBean("bean")); - assertTrue(wac.getBean("bean") instanceof MyBean); + assertThat(wac.containsBean("bean")).isTrue(); + boolean condition = wac.getBean("bean") instanceof MyBean; + assertThat(condition).isTrue(); - assertEquals(1, servletRegistrations.size()); - assertNotNull(servletRegistrations.get(SERVLET_NAME)); + assertThat(servletRegistrations.size()).isEqualTo(1); + assertThat(servletRegistrations.get(SERVLET_NAME)).isNotNull(); MockServletRegistration servletRegistration = servletRegistrations.get(SERVLET_NAME); - assertEquals(Collections.singleton(SERVLET_MAPPING), servletRegistration.getMappings()); - assertEquals(1, servletRegistration.getLoadOnStartup()); - assertEquals(ROLE_NAME, servletRegistration.getRunAsRole()); - assertTrue(servletRegistration.isAsyncSupported()); + assertThat(servletRegistration.getMappings()).isEqualTo(Collections.singleton(SERVLET_MAPPING)); + assertThat(servletRegistration.getLoadOnStartup()).isEqualTo(1); + assertThat(servletRegistration.getRunAsRole()).isEqualTo(ROLE_NAME); + assertThat(servletRegistration.isAsyncSupported()).isTrue(); - assertEquals(4, filterRegistrations.size()); - assertNotNull(filterRegistrations.get("hiddenHttpMethodFilter")); - assertNotNull(filterRegistrations.get("delegatingFilterProxy")); - assertNotNull(filterRegistrations.get("delegatingFilterProxy#0")); - assertNotNull(filterRegistrations.get("delegatingFilterProxy#1")); + assertThat(filterRegistrations.size()).isEqualTo(4); + assertThat(filterRegistrations.get("hiddenHttpMethodFilter")).isNotNull(); + assertThat(filterRegistrations.get("delegatingFilterProxy")).isNotNull(); + assertThat(filterRegistrations.get("delegatingFilterProxy#0")).isNotNull(); + assertThat(filterRegistrations.get("delegatingFilterProxy#1")).isNotNull(); for (MockFilterRegistration filterRegistration : filterRegistrations.values()) { - assertTrue(filterRegistration.isAsyncSupported()); + assertThat(filterRegistration.isAsyncSupported()).isTrue(); EnumSet enumSet = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC); - assertEquals(enumSet, filterRegistration.getMappings().get(SERVLET_NAME)); + assertThat(filterRegistration.getMappings().get(SERVLET_NAME)).isEqualTo(enumSet); } } @@ -135,12 +133,11 @@ public class AnnotationConfigDispatcherServletInitializerTests { initializer.onStartup(servletContext); MockServletRegistration servletRegistration = servletRegistrations.get(SERVLET_NAME); - assertFalse(servletRegistration.isAsyncSupported()); + assertThat(servletRegistration.isAsyncSupported()).isFalse(); for (MockFilterRegistration filterRegistration : filterRegistrations.values()) { - assertFalse(filterRegistration.isAsyncSupported()); - assertEquals(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), - filterRegistration.getMappings().get(SERVLET_NAME)); + assertThat(filterRegistration.isAsyncSupported()).isFalse(); + assertThat(filterRegistration.getMappings().get(SERVLET_NAME)).isEqualTo(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE)); } } @@ -166,8 +163,9 @@ public class AnnotationConfigDispatcherServletInitializerTests { WebApplicationContext wac = servlet.getWebApplicationContext(); ((AnnotationConfigWebApplicationContext) wac).refresh(); - assertTrue(wac.containsBean("bean")); - assertTrue(wac.getBean("bean") instanceof MyBean); + assertThat(wac.containsBean("bean")).isTrue(); + boolean condition = wac.getBean("bean") instanceof MyBean; + assertThat(condition).isTrue(); } @Test @@ -181,7 +179,7 @@ public class AnnotationConfigDispatcherServletInitializerTests { initializer.onStartup(servletContext); - assertEquals(0, filterRegistrations.size()); + assertThat(filterRegistrations.size()).isEqualTo(0); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/DispatcherServletInitializerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/DispatcherServletInitializerTests.java index f16116ed447..624e0f33248 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/DispatcherServletInitializerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/DispatcherServletInitializerTests.java @@ -30,9 +30,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Test case for {@link AbstractDispatcherServletInitializer}. @@ -61,23 +59,24 @@ public class DispatcherServletInitializerTests { public void register() throws ServletException { initializer.onStartup(servletContext); - assertEquals(1, servlets.size()); - assertNotNull(servlets.get(SERVLET_NAME)); + assertThat(servlets.size()).isEqualTo(1); + assertThat(servlets.get(SERVLET_NAME)).isNotNull(); DispatcherServlet servlet = (DispatcherServlet) servlets.get(SERVLET_NAME); - assertEquals(MyDispatcherServlet.class, servlet.getClass()); + assertThat(servlet.getClass()).isEqualTo(MyDispatcherServlet.class); WebApplicationContext servletContext = servlet.getWebApplicationContext(); - assertTrue(servletContext.containsBean("bean")); - assertTrue(servletContext.getBean("bean") instanceof MyBean); + assertThat(servletContext.containsBean("bean")).isTrue(); + boolean condition = servletContext.getBean("bean") instanceof MyBean; + assertThat(condition).isTrue(); - assertEquals(1, registrations.size()); - assertNotNull(registrations.get(SERVLET_NAME)); + assertThat(registrations.size()).isEqualTo(1); + assertThat(registrations.get(SERVLET_NAME)).isNotNull(); MockServletRegistration registration = registrations.get(SERVLET_NAME); - assertEquals(Collections.singleton(SERVLET_MAPPING), registration.getMappings()); - assertEquals(1, registration.getLoadOnStartup()); - assertEquals(ROLE_NAME, registration.getRunAsRole()); + assertThat(registration.getMappings()).isEqualTo(Collections.singleton(SERVLET_MAPPING)); + assertThat(registration.getLoadOnStartup()).isEqualTo(1); + assertThat(registration.getRunAsRole()).isEqualTo(ROLE_NAME); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/FlashMapManagerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/FlashMapManagerTests.java index a78dd7e360c..b098d8f7e5f 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/FlashMapManagerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/FlashMapManagerTests.java @@ -25,6 +25,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.assertj.core.api.ObjectAssert; import org.junit.Before; import org.junit.Test; @@ -33,11 +34,7 @@ import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.servlet.FlashMap; import org.springframework.web.util.WebUtils; -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.assertj.core.api.Assertions.assertThat; /** @@ -73,7 +70,7 @@ public class FlashMapManagerTests { this.request.setRequestURI("/path"); FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertEquals(flashMap, inputFlashMap); + assertThatFlashMap(inputFlashMap).isEqualTo(flashMap); } // SPR-8779 @@ -90,8 +87,8 @@ public class FlashMapManagerTests { this.request.setRequestURI("/mvc/accounts"); FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertEquals(flashMap, inputFlashMap); - assertEquals("Input FlashMap should have been removed", 0, this.flashMapManager.getFlashMaps().size()); + assertThatFlashMap(inputFlashMap).isEqualTo(flashMap); + assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(0); } @Test @@ -105,8 +102,8 @@ public class FlashMapManagerTests { this.request.setRequestURI("/path/"); FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertEquals(flashMap, inputFlashMap); - assertEquals("Input FlashMap should have been removed", 0, this.flashMapManager.getFlashMaps().size()); + assertThatFlashMap(inputFlashMap).isEqualTo(flashMap); + assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(0); } @Test @@ -120,20 +117,20 @@ public class FlashMapManagerTests { this.request.setQueryString("number="); FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertNull(inputFlashMap); - assertEquals("FlashMap should not have been removed", 1, this.flashMapManager.getFlashMaps().size()); + assertThatFlashMap(inputFlashMap).isNull(); + assertThat(this.flashMapManager.getFlashMaps().size()).as("FlashMap should not have been removed").isEqualTo(1); this.request.setQueryString("number=two"); inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertNull(inputFlashMap); - assertEquals("FlashMap should not have been removed", 1, this.flashMapManager.getFlashMaps().size()); + assertThatFlashMap(inputFlashMap).isNull(); + assertThat(this.flashMapManager.getFlashMaps().size()).as("FlashMap should not have been removed").isEqualTo(1); this.request.setQueryString("number=one"); inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertEquals(flashMap, inputFlashMap); - assertEquals("Input FlashMap should have been removed", 0, this.flashMapManager.getFlashMaps().size()); + assertThatFlashMap(inputFlashMap).isEqualTo(flashMap); + assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(0); } // SPR-8798 @@ -150,14 +147,14 @@ public class FlashMapManagerTests { this.request.setQueryString("id=1"); FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertNull(inputFlashMap); - assertEquals("FlashMap should not have been removed", 1, this.flashMapManager.getFlashMaps().size()); + assertThatFlashMap(inputFlashMap).isNull(); + assertThat(this.flashMapManager.getFlashMaps().size()).as("FlashMap should not have been removed").isEqualTo(1); this.request.setQueryString("id=1&id=2"); inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertEquals(flashMap, inputFlashMap); - assertEquals("Input FlashMap should have been removed", 0, this.flashMapManager.getFlashMaps().size()); + assertThatFlashMap(inputFlashMap).isEqualTo(flashMap); + assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(0); } @Test @@ -178,8 +175,8 @@ public class FlashMapManagerTests { this.request.setRequestURI("/one/two"); FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertEquals(flashMapTwo, inputFlashMap); - assertEquals("Input FlashMap should have been removed", 2, this.flashMapManager.getFlashMaps().size()); + assertThatFlashMap(inputFlashMap).isEqualTo(flashMapTwo); + assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(2); } @Test @@ -193,8 +190,7 @@ public class FlashMapManagerTests { this.flashMapManager.setFlashMaps(flashMaps); this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertEquals("Expired instances should be removed even if the saved FlashMap is empty", - 0, this.flashMapManager.getFlashMaps().size()); + assertThat(this.flashMapManager.getFlashMaps().size()).as("Expired instances should be removed even if the saved FlashMap is empty").isEqualTo(0); } @Test @@ -204,7 +200,7 @@ public class FlashMapManagerTests { this.flashMapManager.saveOutputFlashMap(flashMap, this.request, this.response); List allMaps = this.flashMapManager.getFlashMaps(); - assertNull(allMaps); + assertThat(allMaps).isNull(); } @Test @@ -216,9 +212,9 @@ public class FlashMapManagerTests { this.flashMapManager.saveOutputFlashMap(flashMap, this.request, this.response); List allMaps = this.flashMapManager.getFlashMaps(); - assertNotNull(allMaps); - assertSame(flashMap, allMaps.get(0)); - assertTrue(flashMap.isExpired()); + assertThat(allMaps).isNotNull(); + assertThatFlashMap(allMaps.get(0)).isSameAs(flashMap); + assertThat(flashMap.isExpired()).isTrue(); } @Test @@ -229,7 +225,7 @@ public class FlashMapManagerTests { flashMap.setTargetRequestPath("/once%20upon%20a%20time"); this.flashMapManager.saveOutputFlashMap(flashMap, this.request, this.response); - assertEquals("/once upon a time", flashMap.getTargetRequestPath()); + assertThat(flashMap.getTargetRequestPath()).isEqualTo("/once upon a time"); } @Test @@ -241,31 +237,31 @@ public class FlashMapManagerTests { this.request.setRequestURI("/once/upon/a/time"); this.flashMapManager.saveOutputFlashMap(flashMap, this.request, this.response); - assertEquals("/once/upon/a", flashMap.getTargetRequestPath()); + assertThat(flashMap.getTargetRequestPath()).isEqualTo("/once/upon/a"); flashMap.setTargetRequestPath("./"); this.request.setRequestURI("/once/upon/a/time"); this.flashMapManager.saveOutputFlashMap(flashMap, this.request, this.response); - assertEquals("/once/upon/a/", flashMap.getTargetRequestPath()); + assertThat(flashMap.getTargetRequestPath()).isEqualTo("/once/upon/a/"); flashMap.setTargetRequestPath(".."); this.request.setRequestURI("/once/upon/a/time"); this.flashMapManager.saveOutputFlashMap(flashMap, this.request, this.response); - assertEquals("/once/upon", flashMap.getTargetRequestPath()); + assertThat(flashMap.getTargetRequestPath()).isEqualTo("/once/upon"); flashMap.setTargetRequestPath("../"); this.request.setRequestURI("/once/upon/a/time"); this.flashMapManager.saveOutputFlashMap(flashMap, this.request, this.response); - assertEquals("/once/upon/", flashMap.getTargetRequestPath()); + assertThat(flashMap.getTargetRequestPath()).isEqualTo("/once/upon/"); flashMap.setTargetRequestPath("../../only"); this.request.setRequestURI("/once/upon/a/time"); this.flashMapManager.saveOutputFlashMap(flashMap, this.request, this.response); - assertEquals("/once/only", flashMap.getTargetRequestPath()); + assertThat(flashMap.getTargetRequestPath()).isEqualTo("/once/only"); } // SPR-9657, SPR-11504 @@ -293,9 +289,9 @@ public class FlashMapManagerTests { requestAfterRedirect.addParameter(":/?#[]@", "value"); flashMap = this.flashMapManager.retrieveAndUpdate(requestAfterRedirect, new MockHttpServletResponse()); - assertNotNull(flashMap); - assertEquals(1, flashMap.size()); - assertEquals("value", flashMap.get("key")); + assertThatFlashMap(flashMap).isNotNull(); + assertThat(flashMap.size()).isEqualTo(1); + assertThat(flashMap.get("key")).isEqualTo("value"); } // SPR-12569 @@ -318,9 +314,9 @@ public class FlashMapManagerTests { requestAfterRedirect.addParameter("param", "1 2"); flashMap = this.flashMapManager.retrieveAndUpdate(requestAfterRedirect, new MockHttpServletResponse()); - assertNotNull(flashMap); - assertEquals(1, flashMap.size()); - assertEquals("value", flashMap.get("key")); + assertThatFlashMap(flashMap).isNotNull(); + assertThat(flashMap.size()).isEqualTo(1); + assertThat(flashMap.get("key")).isEqualTo("value"); } @Test // SPR-15505 @@ -338,8 +334,13 @@ public class FlashMapManagerTests { this.request.setQueryString("x=y"); FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertEquals(flashMap, inputFlashMap); - assertEquals("Input FlashMap should have been removed", 0, this.flashMapManager.getFlashMaps().size()); + assertThatFlashMap(inputFlashMap).isEqualTo(flashMap); + assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(0); + } + + + private static ObjectAssert assertThatFlashMap(FlashMap flashMap) { + return assertThat((Object) flashMap); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/RequestContextTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/RequestContextTests.java index 7f57025e65a..2ac50002233 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/RequestContextTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/RequestContextTests.java @@ -29,7 +29,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.util.WebUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Dave Syer @@ -56,7 +56,7 @@ public class RequestContextTests { public void testGetContextUrl() throws Exception { request.setContextPath("foo/"); RequestContext context = new RequestContext(request, response, servletContext, model); - assertEquals("foo/bar", context.getContextUrl("bar")); + assertThat(context.getContextUrl("bar")).isEqualTo("foo/bar"); } @Test @@ -66,7 +66,7 @@ public class RequestContextTests { Map map = new HashMap<>(); map.put("foo", "bar"); map.put("spam", "bucket"); - assertEquals("foo/bar?spam=bucket", context.getContextUrl("{foo}?spam={spam}", map)); + assertThat(context.getContextUrl("{foo}?spam={spam}", map)).isEqualTo("foo/bar?spam=bucket"); } @Test @@ -76,7 +76,7 @@ public class RequestContextTests { Map map = new HashMap<>(); map.put("foo", "bar baz"); map.put("spam", "&bucket="); - assertEquals("foo/bar%20baz?spam=%26bucket%3D", context.getContextUrl("{foo}?spam={spam}", map)); + assertThat(context.getContextUrl("{foo}?spam={spam}", map)).isEqualTo("foo/bar%20baz?spam=%26bucket%3D"); } @Test @@ -85,12 +85,12 @@ public class RequestContextTests { request.setServletPath("/servlet"); RequestContext context = new RequestContext(request, response, servletContext, model); - assertEquals("/app/servlet", context.getPathToServlet()); + assertThat(context.getPathToServlet()).isEqualTo("/app/servlet"); request.setAttribute(WebUtils.FORWARD_CONTEXT_PATH_ATTRIBUTE, "/origApp"); request.setAttribute(WebUtils.FORWARD_SERVLET_PATH_ATTRIBUTE, "/origServlet"); - assertEquals("/origApp/origServlet", context.getPathToServlet()); + assertThat(context.getPathToServlet()).isEqualTo("/origApp/origServlet"); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/ServletUriComponentsBuilderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/ServletUriComponentsBuilderTests.java index 74480c0ead8..dd8f1dceaba 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/ServletUriComponentsBuilderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/ServletUriComponentsBuilderTests.java @@ -29,8 +29,7 @@ import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.filter.ForwardedHeaderFilter; import org.springframework.web.util.UriComponents; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for @@ -59,21 +58,21 @@ public class ServletUriComponentsBuilderTests { this.request.setRequestURI("/mvc-showcase/data/param"); this.request.setQueryString("foo=123"); String result = ServletUriComponentsBuilder.fromRequest(this.request).build().toUriString(); - assertEquals("http://localhost/mvc-showcase/data/param?foo=123", result); + assertThat(result).isEqualTo("http://localhost/mvc-showcase/data/param?foo=123"); } @Test public void fromRequestEncodedPath() { this.request.setRequestURI("/mvc-showcase/data/foo%20bar"); String result = ServletUriComponentsBuilder.fromRequest(this.request).build().toUriString(); - assertEquals("http://localhost/mvc-showcase/data/foo%20bar", result); + assertThat(result).isEqualTo("http://localhost/mvc-showcase/data/foo%20bar"); } @Test public void fromRequestAtypicalHttpPort() { this.request.setServerPort(8080); String result = ServletUriComponentsBuilder.fromRequest(this.request).build().toUriString(); - assertEquals("http://localhost:8080/mvc-showcase", result); + assertThat(result).isEqualTo("http://localhost:8080/mvc-showcase"); } @Test @@ -81,7 +80,7 @@ public class ServletUriComponentsBuilderTests { this.request.setScheme("https"); this.request.setServerPort(9043); String result = ServletUriComponentsBuilder.fromRequest(this.request).build().toUriString(); - assertEquals("https://localhost:9043/mvc-showcase", result); + assertThat(result).isEqualTo("https://localhost:9043/mvc-showcase"); } // Some X-Forwarded-* tests in addition to the ones in UriComponentsBuilderTests @@ -100,7 +99,7 @@ public class ServletUriComponentsBuilderTests { HttpServletRequest requestToUse = adaptFromForwardedHeaders(request); UriComponents result = ServletUriComponentsBuilder.fromRequest(requestToUse).build(); - assertEquals("https://84.198.58.199/mvc-showcase", result.toString()); + assertThat(result.toString()).isEqualTo("https://84.198.58.199/mvc-showcase"); } @Test @@ -108,7 +107,7 @@ public class ServletUriComponentsBuilderTests { this.request.setRequestURI("/mvc-showcase/data/param"); this.request.setQueryString("foo=123"); String result = ServletUriComponentsBuilder.fromRequestUri(this.request).build().toUriString(); - assertEquals("http://localhost/mvc-showcase/data/param", result); + assertThat(result).isEqualTo("http://localhost/mvc-showcase/data/param"); } @Test // SPR-16650 @@ -120,7 +119,7 @@ public class ServletUriComponentsBuilderTests { HttpServletRequest requestToUse = adaptFromForwardedHeaders(this.request); UriComponents result = ServletUriComponentsBuilder.fromRequest(requestToUse).build(); - assertEquals("http://localhost/prefix/bar", result.toUriString()); + assertThat(result.toUriString()).isEqualTo("http://localhost/prefix/bar"); } @Test // SPR-16650 @@ -132,7 +131,7 @@ public class ServletUriComponentsBuilderTests { HttpServletRequest requestToUse = adaptFromForwardedHeaders(this.request); UriComponents result = ServletUriComponentsBuilder.fromRequest(requestToUse).build(); - assertEquals("http://localhost/foo/bar", result.toUriString()); + assertThat(result.toUriString()).isEqualTo("http://localhost/foo/bar"); } @Test // SPR-16650 @@ -144,7 +143,7 @@ public class ServletUriComponentsBuilderTests { HttpServletRequest requestToUse = adaptFromForwardedHeaders(this.request); UriComponents result = ServletUriComponentsBuilder.fromRequest(requestToUse).build(); - assertEquals("http://localhost/bar", result.toUriString()); + assertThat(result.toUriString()).isEqualTo("http://localhost/bar"); } @Test @@ -152,7 +151,7 @@ public class ServletUriComponentsBuilderTests { this.request.setRequestURI("/mvc-showcase/data/param"); this.request.setQueryString("foo=123"); String result = ServletUriComponentsBuilder.fromContextPath(this.request).build().toUriString(); - assertEquals("http://localhost/mvc-showcase", result); + assertThat(result).isEqualTo("http://localhost/mvc-showcase"); } @Test // SPR-16650 @@ -164,7 +163,7 @@ public class ServletUriComponentsBuilderTests { HttpServletRequest requestToUse = adaptFromForwardedHeaders(this.request); String result = ServletUriComponentsBuilder.fromContextPath(requestToUse).build().toUriString(); - assertEquals("http://localhost/prefix", result); + assertThat(result).isEqualTo("http://localhost/prefix"); } @Test @@ -173,7 +172,7 @@ public class ServletUriComponentsBuilderTests { this.request.setServletPath("/app"); this.request.setQueryString("foo=123"); String result = ServletUriComponentsBuilder.fromServletMapping(this.request).build().toUriString(); - assertEquals("http://localhost/mvc-showcase/app", result); + assertThat(result).isEqualTo("http://localhost/mvc-showcase/app"); } @Test // SPR-16650 @@ -186,7 +185,7 @@ public class ServletUriComponentsBuilderTests { HttpServletRequest requestToUse = adaptFromForwardedHeaders(this.request); String result = ServletUriComponentsBuilder.fromServletMapping(requestToUse).build().toUriString(); - assertEquals("http://localhost/prefix/app", result); + assertThat(result).isEqualTo("http://localhost/prefix/app"); } @Test @@ -196,7 +195,7 @@ public class ServletUriComponentsBuilderTests { RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(this.request)); try { String result = ServletUriComponentsBuilder.fromCurrentRequest().build().toUriString(); - assertEquals("http://localhost/mvc-showcase/data/param?foo=123", result); + assertThat(result).isEqualTo("http://localhost/mvc-showcase/data/param?foo=123"); } finally { RequestContextHolder.resetRequestAttributes(); @@ -209,14 +208,14 @@ public class ServletUriComponentsBuilderTests { ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromRequestUri(this.request); String extension = builder.removePathExtension(); String result = builder.path("/pages/1.{ext}").buildAndExpand(extension).toUriString(); - assertEquals("http://localhost/rest/books/6/pages/1.json", result); + assertThat(result).isEqualTo("http://localhost/rest/books/6/pages/1.json"); } @Test public void pathExtensionNone() { this.request.setRequestURI("/rest/books/6"); ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromRequestUri(this.request); - assertNull(builder.removePathExtension()); + assertThat(builder.removePathExtension()).isNull(); } // SPR-16668 diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/WebContentGeneratorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/WebContentGeneratorTests.java index fff06bb6a48..f57e5fb22de 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/WebContentGeneratorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/WebContentGeneratorTests.java @@ -21,8 +21,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletResponse; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link WebContentGenerator}. @@ -33,34 +32,33 @@ public class WebContentGeneratorTests { @Test public void getAllowHeaderWithConstructorTrue() throws Exception { WebContentGenerator generator = new TestWebContentGenerator(true); - assertEquals("GET,HEAD,POST,OPTIONS", generator.getAllowHeader()); + assertThat(generator.getAllowHeader()).isEqualTo("GET,HEAD,POST,OPTIONS"); } @Test public void getAllowHeaderWithConstructorFalse() throws Exception { WebContentGenerator generator = new TestWebContentGenerator(false); - assertEquals("GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS", generator.getAllowHeader()); + assertThat(generator.getAllowHeader()).isEqualTo("GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS"); } @Test public void getAllowHeaderWithSupportedMethodsConstructor() throws Exception { WebContentGenerator generator = new TestWebContentGenerator("POST"); - assertEquals("POST,OPTIONS", generator.getAllowHeader()); + assertThat(generator.getAllowHeader()).isEqualTo("POST,OPTIONS"); } @Test public void getAllowHeaderWithSupportedMethodsSetter() throws Exception { WebContentGenerator generator = new TestWebContentGenerator(); generator.setSupportedMethods("POST"); - assertEquals("POST,OPTIONS", generator.getAllowHeader()); + assertThat(generator.getAllowHeader()).isEqualTo("POST,OPTIONS"); } @Test public void getAllowHeaderWithSupportedMethodsSetterEmpty() throws Exception { WebContentGenerator generator = new TestWebContentGenerator(); generator.setSupportedMethods(); - assertEquals("Effectively \"no restriction\" on supported methods", - "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS", generator.getAllowHeader()); + assertThat(generator.getAllowHeader()).as("Effectively \"no restriction\" on supported methods").isEqualTo("GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS"); } @Test @@ -69,7 +67,7 @@ public class WebContentGeneratorTests { MockHttpServletResponse response = new MockHttpServletResponse(); generator.prepareResponse(response); - assertNull(response.getHeader("Vary")); + assertThat(response.getHeader("Vary")).isNull(); } @Test @@ -112,7 +110,7 @@ public class WebContentGeneratorTests { response.addHeader("Vary", value); } generator.prepareResponse(response); - assertEquals(Arrays.asList(expected), response.getHeaderValues("Vary")); + assertThat(response.getHeaderValues("Vary")).isEqualTo(Arrays.asList(expected)); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ArgumentTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ArgumentTagTests.java index d9e12aab435..77449941520 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ArgumentTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ArgumentTagTests.java @@ -27,8 +27,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockBodyContent; import org.springframework.mock.web.test.MockHttpServletResponse; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ArgumentTag} @@ -56,16 +55,16 @@ public class ArgumentTagTests extends AbstractTagTests { int action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("value1", parent.getArgument()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getArgument()).isEqualTo("value1"); } @Test public void argumentWithImplicitNullValue() throws JspException { int action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertNull(parent.getArgument()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getArgument()).isNull(); } @Test @@ -74,8 +73,8 @@ public class ArgumentTagTests extends AbstractTagTests { int action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertNull(parent.getArgument()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getArgument()).isNull(); } @Test @@ -85,8 +84,8 @@ public class ArgumentTagTests extends AbstractTagTests { int action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("value2", parent.getArgument()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getArgument()).isEqualTo("value2"); } @Test @@ -95,8 +94,8 @@ public class ArgumentTagTests extends AbstractTagTests { int action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("value3", parent.getArgument()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getArgument()).isEqualTo("value3"); tag.release(); @@ -108,8 +107,8 @@ public class ArgumentTagTests extends AbstractTagTests { action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("value4", parent.getArgument()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getArgument()).isEqualTo("value4"); } @SuppressWarnings("serial") diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java index 5dd4f270765..65f6cde3f40 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java @@ -41,12 +41,8 @@ import org.springframework.web.servlet.support.BindStatus; import org.springframework.web.servlet.tags.form.FormTag; import org.springframework.web.servlet.tags.form.TagWriter; +import static org.assertj.core.api.Assertions.assertThat; 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; /** * @author Juergen Hoeller @@ -63,18 +59,19 @@ public class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", status.getExpression() == null); - assertTrue("Correct value", status.getValue() == null); - assertTrue("Correct displayValue", "".equals(status.getDisplayValue())); - assertTrue("Correct isError", !status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 0); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 0); - assertTrue("Correct errorCode", "".equals(status.getErrorCode())); - assertTrue("Correct errorMessage", "".equals(status.getErrorMessage())); - assertTrue("Correct errorMessagesAsString", "".equals(status.getErrorMessagesAsString(","))); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat(status.getExpression() == null).as("Correct expression").isTrue(); + assertThat(status.getValue() == null).as("Correct value").isTrue(); + assertThat("".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + boolean condition = !status.isError(); + assertThat(condition).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 0).as("Correct errorCodes").isTrue(); + assertThat(status.getErrorMessages().length == 0).as("Correct errorMessages").isTrue(); + assertThat("".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); + assertThat("".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("".equals(status.getErrorMessagesAsString(","))).as("Correct errorMessagesAsString").isTrue(); } @Test @@ -87,34 +84,34 @@ public class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", status.getExpression() == null); - assertTrue("Correct value", status.getValue() == null); - assertTrue("Correct displayValue", "".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 1); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 1); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCode())); - assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessage())); - assertTrue("Correct errorMessagesAsString", "message1".equals(status.getErrorMessagesAsString(","))); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat(status.getExpression() == null).as("Correct expression").isTrue(); + assertThat(status.getValue() == null).as("Correct value").isTrue(); + assertThat("".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 1).as("Correct errorCodes").isTrue(); + assertThat(status.getErrorMessages().length == 1).as("Correct errorMessages").isTrue(); + assertThat("code1".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); + assertThat("message1".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("message1".equals(status.getErrorMessagesAsString(","))).as("Correct errorMessagesAsString").isTrue(); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "*".equals(status.getExpression())); - assertTrue("Correct value", status.getValue() == null); - assertTrue("Correct displayValue", "".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 1); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 1); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCode())); - assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessage())); - assertTrue("Correct errorMessagesAsString", "message1".equals(status.getErrorMessagesAsString(","))); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("*".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(status.getValue() == null).as("Correct value").isTrue(); + assertThat("".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 1).as("Correct errorCodes").isTrue(); + assertThat(status.getErrorMessages().length == 1).as("Correct errorMessages").isTrue(); + assertThat("code1".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); + assertThat("message1".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("message1".equals(status.getErrorMessagesAsString(","))).as("Correct errorMessagesAsString").isTrue(); } @Test @@ -127,28 +124,28 @@ public class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", status.getExpression() == null); - assertTrue("Correct value", status.getValue() == null); - assertTrue("Correct displayValue", "".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 1); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCode())); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat(status.getExpression() == null).as("Correct expression").isTrue(); + assertThat(status.getValue() == null).as("Correct value").isTrue(); + assertThat("".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 1).as("Correct errorCodes").isTrue(); + assertThat("code1".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "*".equals(status.getExpression())); - assertTrue("Correct value", status.getValue() == null); - assertTrue("Correct displayValue", "".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 1); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCode())); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("*".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(status.getValue() == null).as("Correct value").isTrue(); + assertThat("".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 1).as("Correct errorCodes").isTrue(); + assertThat("code1".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); } @Test @@ -161,30 +158,30 @@ public class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", status.getExpression() == null); - assertTrue("Correct value", status.getValue() == null); - assertTrue("Correct displayValue", "".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 1); - assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessage())); - assertTrue("Correct errorMessagesAsString", "message1".equals(status.getErrorMessagesAsString(","))); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat(status.getExpression() == null).as("Correct expression").isTrue(); + assertThat(status.getValue() == null).as("Correct value").isTrue(); + assertThat("".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorMessages().length == 1).as("Correct errorMessages").isTrue(); + assertThat("message1".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("message1".equals(status.getErrorMessagesAsString(","))).as("Correct errorMessagesAsString").isTrue(); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "*".equals(status.getExpression())); - assertTrue("Correct value", status.getValue() == null); - assertTrue("Correct displayValue", "".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 1); - assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessage())); - assertTrue("Correct errorMessagesAsString", "message1".equals(status.getErrorMessagesAsString(","))); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("*".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(status.getValue() == null).as("Correct value").isTrue(); + assertThat("".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorMessages().length == 1).as("Correct errorMessages").isTrue(); + assertThat("message1".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("message1".equals(status.getErrorMessagesAsString(","))).as("Correct errorMessagesAsString").isTrue(); } @Test @@ -199,8 +196,7 @@ public class BindTagTests extends AbstractTagTests { tag.setPath("tb"); tag.doStartTag(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertEquals("Error messages String should be 'message1'", - "message1", status.getErrorMessagesAsString(",")); + assertThat(status.getErrorMessagesAsString(",")).as("Error messages String should be 'message1'").isEqualTo("message1"); // two errors pc = createPageContext(); @@ -213,8 +209,7 @@ public class BindTagTests extends AbstractTagTests { tag.setPath("tb"); tag.doStartTag(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertEquals("Error messages String should be 'message1,message2'", - "message1,message2", status.getErrorMessagesAsString(",")); + assertThat(status.getErrorMessagesAsString(",")).as("Error messages String should be 'message1,message2'").isEqualTo("message1,message2"); // no errors pc = createPageContext(); @@ -225,7 +220,7 @@ public class BindTagTests extends AbstractTagTests { tag.setPath("tb"); tag.doStartTag(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertEquals("Error messages String should be ''", "", status.getErrorMessagesAsString(",")); + assertThat(status.getErrorMessagesAsString(",")).as("Error messages String should be ''").isEqualTo(""); } @Test @@ -243,60 +238,59 @@ public class BindTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setPath("tb.name"); tag.setHtmlEscape(true); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "name".equals(status.getExpression())); - assertTrue("Correct value", "name1".equals(status.getValue())); - assertTrue("Correct displayValue", "name1".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 2); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 2); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCode())); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0])); - assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1])); - assertTrue("Correct errorMessage", "message & 1".equals(status.getErrorMessage())); - assertTrue("Correct errorMessage", "message & 1".equals(status.getErrorMessages()[0])); - assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1])); - assertTrue("Correct errorMessagesAsString", - "message & 1 - message2".equals(status.getErrorMessagesAsString(" - "))); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("name".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat("name1".equals(status.getValue())).as("Correct value").isTrue(); + assertThat("name1".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 2).as("Correct errorCodes").isTrue(); + assertThat(status.getErrorMessages().length == 2).as("Correct errorMessages").isTrue(); + assertThat("code1".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); + assertThat("code1".equals(status.getErrorCodes()[0])).as("Correct errorCode").isTrue(); + assertThat("code2".equals(status.getErrorCodes()[1])).as("Correct errorCode").isTrue(); + assertThat("message & 1".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("message & 1".equals(status.getErrorMessages()[0])).as("Correct errorMessage").isTrue(); + assertThat("message2".equals(status.getErrorMessages()[1])).as("Correct errorMessage").isTrue(); + assertThat("message & 1 - message2".equals(status.getErrorMessagesAsString(" - "))).as("Correct errorMessagesAsString").isTrue(); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.age"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "age".equals(status.getExpression())); - assertTrue("Correct value", new Integer(0).equals(status.getValue())); - assertTrue("Correct displayValue", "0".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 1); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 1); - assertTrue("Correct errorCode", "code2".equals(status.getErrorCode())); - assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessage())); - assertTrue("Correct errorMessagesAsString", "message2".equals(status.getErrorMessagesAsString(" - "))); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("age".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(new Integer(0).equals(status.getValue())).as("Correct value").isTrue(); + assertThat("0".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 1).as("Correct errorCodes").isTrue(); + assertThat(status.getErrorMessages().length == 1).as("Correct errorMessages").isTrue(); + assertThat("code2".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); + assertThat("message2".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("message2".equals(status.getErrorMessagesAsString(" - "))).as("Correct errorMessagesAsString").isTrue(); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "*".equals(status.getExpression())); - assertTrue("Correct value", status.getValue() == null); - assertTrue("Correct displayValue", "".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 3); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 3); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCode())); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0])); - assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1])); - assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[2])); - assertTrue("Correct errorMessage", "message & 1".equals(status.getErrorMessage())); - assertTrue("Correct errorMessage", "message & 1".equals(status.getErrorMessages()[0])); - assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1])); - assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[2])); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("*".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(status.getValue() == null).as("Correct value").isTrue(); + assertThat("".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 3).as("Correct errorCodes").isTrue(); + assertThat(status.getErrorMessages().length == 3).as("Correct errorMessages").isTrue(); + assertThat("code1".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); + assertThat("code1".equals(status.getErrorCodes()[0])).as("Correct errorCode").isTrue(); + assertThat("code2".equals(status.getErrorCodes()[1])).as("Correct errorCode").isTrue(); + assertThat("code2".equals(status.getErrorCodes()[2])).as("Correct errorCode").isTrue(); + assertThat("message & 1".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("message & 1".equals(status.getErrorMessages()[0])).as("Correct errorMessage").isTrue(); + assertThat("message2".equals(status.getErrorMessages()[1])).as("Correct errorMessage").isTrue(); + assertThat("message2".equals(status.getErrorMessages()[2])).as("Correct errorMessage").isTrue(); } @Test @@ -314,46 +308,46 @@ public class BindTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setPath("tb.name"); tag.setHtmlEscape(true); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "name".equals(status.getExpression())); - assertTrue("Correct value", "name1".equals(status.getValue())); - assertTrue("Correct displayValue", "name1".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 2); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCode())); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0])); - assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1])); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("name".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat("name1".equals(status.getValue())).as("Correct value").isTrue(); + assertThat("name1".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 2).as("Correct errorCodes").isTrue(); + assertThat("code1".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); + assertThat("code1".equals(status.getErrorCodes()[0])).as("Correct errorCode").isTrue(); + assertThat("code2".equals(status.getErrorCodes()[1])).as("Correct errorCode").isTrue(); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.age"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "age".equals(status.getExpression())); - assertTrue("Correct value", new Integer(0).equals(status.getValue())); - assertTrue("Correct displayValue", "0".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 1); - assertTrue("Correct errorCode", "code2".equals(status.getErrorCode())); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("age".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(new Integer(0).equals(status.getValue())).as("Correct value").isTrue(); + assertThat("0".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 1).as("Correct errorCodes").isTrue(); + assertThat("code2".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "*".equals(status.getExpression())); - assertTrue("Correct value", status.getValue() == null); - assertTrue("Correct displayValue", "".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 3); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCode())); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0])); - assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1])); - assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[2])); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("*".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(status.getValue() == null).as("Correct value").isTrue(); + assertThat("".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 3).as("Correct errorCodes").isTrue(); + assertThat("code1".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); + assertThat("code1".equals(status.getErrorCodes()[0])).as("Correct errorCode").isTrue(); + assertThat("code2".equals(status.getErrorCodes()[1])).as("Correct errorCode").isTrue(); + assertThat("code2".equals(status.getErrorCodes()[2])).as("Correct errorCode").isTrue(); } @Test @@ -371,49 +365,48 @@ public class BindTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setPath("tb.name"); tag.setHtmlEscape(true); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "name".equals(status.getExpression())); - assertTrue("Correct value", "name1".equals(status.getValue())); - assertTrue("Correct displayValue", "name1".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 2); - assertTrue("Correct errorMessage", "message & 1".equals(status.getErrorMessage())); - assertTrue("Correct errorMessage", "message & 1".equals(status.getErrorMessages()[0])); - assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1])); - assertTrue("Correct errorMessagesAsString", - "message & 1 - message2".equals(status.getErrorMessagesAsString(" - "))); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("name".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat("name1".equals(status.getValue())).as("Correct value").isTrue(); + assertThat("name1".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorMessages().length == 2).as("Correct errorMessages").isTrue(); + assertThat("message & 1".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("message & 1".equals(status.getErrorMessages()[0])).as("Correct errorMessage").isTrue(); + assertThat("message2".equals(status.getErrorMessages()[1])).as("Correct errorMessage").isTrue(); + assertThat("message & 1 - message2".equals(status.getErrorMessagesAsString(" - "))).as("Correct errorMessagesAsString").isTrue(); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.age"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "age".equals(status.getExpression())); - assertTrue("Correct value", new Integer(0).equals(status.getValue())); - assertTrue("Correct displayValue", "0".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 1); - assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessage())); - assertTrue("Correct errorMessagesAsString", "message2".equals(status.getErrorMessagesAsString(" - "))); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("age".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(new Integer(0).equals(status.getValue())).as("Correct value").isTrue(); + assertThat("0".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorMessages().length == 1).as("Correct errorMessages").isTrue(); + assertThat("message2".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("message2".equals(status.getErrorMessagesAsString(" - "))).as("Correct errorMessagesAsString").isTrue(); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "*".equals(status.getExpression())); - assertTrue("Correct value", status.getValue() == null); - assertTrue("Correct displayValue", "".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 3); - assertTrue("Correct errorMessage", "message & 1".equals(status.getErrorMessage())); - assertTrue("Correct errorMessage", "message & 1".equals(status.getErrorMessages()[0])); - assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1])); - assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[2])); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("*".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(status.getValue() == null).as("Correct value").isTrue(); + assertThat("".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorMessages().length == 3).as("Correct errorMessages").isTrue(); + assertThat("message & 1".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("message & 1".equals(status.getErrorMessages()[0])).as("Correct errorMessage").isTrue(); + assertThat("message2".equals(status.getErrorMessages()[1])).as("Correct errorMessage").isTrue(); + assertThat("message2".equals(status.getErrorMessages()[2])).as("Correct errorMessage").isTrue(); } @Test @@ -430,18 +423,18 @@ public class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.spouse.name"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "spouse.name".equals(status.getExpression())); - assertTrue("Correct value", "name2".equals(status.getValue())); - assertTrue("Correct displayValue", "name2".equals(status.getDisplayValue())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 1); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 1); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCode())); - assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessage())); - assertTrue("Correct errorMessagesAsString", "message1".equals(status.getErrorMessagesAsString(" - "))); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("spouse.name".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat("name2".equals(status.getValue())).as("Correct value").isTrue(); + assertThat("name2".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 1).as("Correct errorCodes").isTrue(); + assertThat(status.getErrorMessages().length == 1).as("Correct errorMessages").isTrue(); + assertThat("code1".equals(status.getErrorCode())).as("Correct errorCode").isTrue(); + assertThat("message1".equals(status.getErrorMessage())).as("Correct errorMessage").isTrue(); + assertThat("message1".equals(status.getErrorMessagesAsString(" - "))).as("Correct errorMessagesAsString").isTrue(); } @Test @@ -458,15 +451,15 @@ public class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertNull(tag.getProperty()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.getProperty()).isNull(); // test property set (tb.name) tag.release(); tag.setPageContext(pc); tag.setPath("tb.name"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("name", tag.getProperty()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.getProperty()).isEqualTo("name"); } @Test @@ -481,19 +474,20 @@ public class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.array[0]"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "array[0]".equals(status.getExpression())); - assertTrue("Value is TestBean", status.getValue() instanceof TestBean); - assertTrue("Correct value", "name0".equals(((TestBean) status.getValue()).getName())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 2); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 2); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0])); - assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1])); - assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessages()[0])); - assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1])); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("array[0]".equals(status.getExpression())).as("Correct expression").isTrue(); + boolean condition = status.getValue() instanceof TestBean; + assertThat(condition).as("Value is TestBean").isTrue(); + assertThat("name0".equals(((TestBean) status.getValue()).getName())).as("Correct value").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 2).as("Correct errorCodes").isTrue(); + assertThat(status.getErrorMessages().length == 2).as("Correct errorMessages").isTrue(); + assertThat("code1".equals(status.getErrorCodes()[0])).as("Correct errorCode").isTrue(); + assertThat("code2".equals(status.getErrorCodes()[1])).as("Correct errorCode").isTrue(); + assertThat("message1".equals(status.getErrorMessages()[0])).as("Correct errorMessage").isTrue(); + assertThat("message2".equals(status.getErrorMessages()[1])).as("Correct errorMessage").isTrue(); } @Test @@ -508,19 +502,20 @@ public class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.map[key1]"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "map[key1]".equals(status.getExpression())); - assertTrue("Value is TestBean", status.getValue() instanceof TestBean); - assertTrue("Correct value", "name4".equals(((TestBean) status.getValue()).getName())); - assertTrue("Correct isError", status.isError()); - assertTrue("Correct errorCodes", status.getErrorCodes().length == 2); - assertTrue("Correct errorMessages", status.getErrorMessages().length == 2); - assertTrue("Correct errorCode", "code1".equals(status.getErrorCodes()[0])); - assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[1])); - assertTrue("Correct errorMessage", "message1".equals(status.getErrorMessages()[0])); - assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1])); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("map[key1]".equals(status.getExpression())).as("Correct expression").isTrue(); + boolean condition = status.getValue() instanceof TestBean; + assertThat(condition).as("Value is TestBean").isTrue(); + assertThat("name4".equals(((TestBean) status.getValue()).getName())).as("Correct value").isTrue(); + assertThat(status.isError()).as("Correct isError").isTrue(); + assertThat(status.getErrorCodes().length == 2).as("Correct errorCodes").isTrue(); + assertThat(status.getErrorMessages().length == 2).as("Correct errorMessages").isTrue(); + assertThat("code1".equals(status.getErrorCodes()[0])).as("Correct errorCode").isTrue(); + assertThat("code2".equals(status.getErrorCodes()[1])).as("Correct errorCode").isTrue(); + assertThat("message1".equals(status.getErrorMessages()[0])).as("Correct errorMessage").isTrue(); + assertThat("message2".equals(status.getErrorMessages()[1])).as("Correct errorMessage").isTrue(); } @Test @@ -542,13 +537,14 @@ public class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.array[0]"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertTrue("Correct expression", "array[0]".equals(status.getExpression())); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat("array[0]".equals(status.getExpression())).as("Correct expression").isTrue(); // because of the custom editor getValue() should return a String - assertTrue("Value is TestBean", status.getValue() instanceof String); - assertTrue("Correct value", "something".equals(status.getValue())); + boolean condition = status.getValue() instanceof String; + assertThat(condition).as("Value is TestBean").isTrue(); + assertThat("something".equals(status.getValue())).as("Correct value").isTrue(); } @Test @@ -564,9 +560,10 @@ public class BindTagTests extends AbstractTagTests { pc.getRequest().setAttribute("tb", tb); tag.doStartTag(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertEquals("doctor", status.getExpression()); - assertTrue(status.getValue() instanceof NestedTestBean); - assertTrue(status.getDisplayValue().contains("juergen&eva")); + assertThat(status.getExpression()).isEqualTo("doctor"); + boolean condition = status.getValue() instanceof NestedTestBean; + assertThat(condition).isTrue(); + assertThat(status.getDisplayValue().contains("juergen&eva")).isTrue(); } @Test @@ -579,8 +576,9 @@ public class BindTagTests extends AbstractTagTests { pc.getRequest().setAttribute("tb", new TestBean("juergen&eva", 99)); tag.doStartTag(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertEquals("someSet", status.getExpression()); - assertTrue(status.getValue() instanceof Set); + assertThat(status.getExpression()).isEqualTo("someSet"); + boolean condition = status.getValue() instanceof Set; + assertThat(condition).isTrue(); } @Test @@ -592,8 +590,8 @@ public class BindTagTests extends AbstractTagTests { pc.getRequest().setAttribute("tb", new TestBean("juergen&eva", 99)); tag.doStartTag(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertEquals("name", status.getExpression()); - assertEquals("juergen&eva", status.getValue()); + assertThat(status.getExpression()).isEqualTo("name"); + assertThat(status.getValue()).isEqualTo("juergen&eva"); } @Test @@ -606,8 +604,8 @@ public class BindTagTests extends AbstractTagTests { pc.getRequest().setAttribute("tb", new TestBean("juergen&eva", 99)); tag.doStartTag(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertEquals("name", status.getExpression()); - assertEquals("juergen&eva", status.getValue()); + assertThat(status.getExpression()).isEqualTo("name"); + assertThat(status.getValue()).isEqualTo("juergen&eva"); } @Test @@ -619,8 +617,8 @@ public class BindTagTests extends AbstractTagTests { pc.getRequest().setAttribute("tb", new TestBean("juergen", 99)); tag.doStartTag(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertNull(status.getExpression()); - assertNull(status.getValue()); + assertThat(status.getExpression()).isNull(); + assertThat(status.getValue()).isNull(); } @Test @@ -642,8 +640,8 @@ public class BindTagTests extends AbstractTagTests { BindErrorsTag tag = new BindErrorsTag(); tag.setPageContext(pc); tag.setName("tb"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.SKIP_BODY); - assertTrue("Doesn't have errors variable", pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME) == null); + assertThat(tag.doStartTag() == Tag.SKIP_BODY).as("Correct doStartTag return value").isTrue(); + assertThat(pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME) == null).as("Doesn't have errors variable").isTrue(); } @Test @@ -655,9 +653,8 @@ public class BindTagTests extends AbstractTagTests { BindErrorsTag tag = new BindErrorsTag(); tag.setPageContext(pc); tag.setName("tb"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertTrue("Has errors variable", - pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME, PageContext.REQUEST_SCOPE) == errors); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME, PageContext.REQUEST_SCOPE) == errors).as("Has errors variable").isTrue(); } @Test @@ -666,7 +663,7 @@ public class BindTagTests extends AbstractTagTests { BindErrorsTag tag = new BindErrorsTag(); tag.setPageContext(pc); tag.setName("tb"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.SKIP_BODY); + assertThat(tag.doStartTag() == Tag.SKIP_BODY).as("Correct doStartTag return value").isTrue(); } @@ -678,8 +675,8 @@ public class BindTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.doStartTag(); int returnValue = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, returnValue); - assertNull(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)); + assertThat(returnValue).isEqualTo(Tag.EVAL_PAGE); + assertThat(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)).isNull(); } @Test @@ -696,10 +693,10 @@ public class BindTagTests extends AbstractTagTests { anotherTag.doStartTag(); anotherTag.doEndTag(); - assertEquals("foo.", pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)); + assertThat(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)).isEqualTo("foo."); tag.doEndTag(); - assertNull(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)); + assertThat(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)).isNull(); } @Test @@ -710,8 +707,8 @@ public class BindTagTests extends AbstractTagTests { tag.setPageContext(pc); int returnValue = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, returnValue); - assertEquals("foo.", pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)); + assertThat(returnValue).isEqualTo(Tag.EVAL_BODY_INCLUDE); + assertThat(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)).isEqualTo("foo."); } @Test @@ -721,21 +718,21 @@ public class BindTagTests extends AbstractTagTests { tag.setPath("foo"); tag.setPageContext(pc); tag.doStartTag(); - assertEquals("foo.", pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)); + assertThat(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)).isEqualTo("foo."); NestedPathTag anotherTag = new NestedPathTag(); anotherTag.setPageContext(pc); anotherTag.setPath("bar"); anotherTag.doStartTag(); - assertEquals("foo.bar.", pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)); + assertThat(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)).isEqualTo("foo.bar."); NestedPathTag yetAnotherTag = new NestedPathTag(); yetAnotherTag.setPageContext(pc); yetAnotherTag.setPath("boo"); yetAnotherTag.doStartTag(); - assertEquals("foo.bar.boo.", pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)); + assertThat(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)).isEqualTo("foo.bar.boo."); yetAnotherTag.doEndTag(); @@ -744,7 +741,7 @@ public class BindTagTests extends AbstractTagTests { andAnotherTag.setPath("boo2"); andAnotherTag.doStartTag(); - assertEquals("foo.bar.boo2.", pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)); + assertThat(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE)).isEqualTo("foo.bar.boo2."); } @Test @@ -762,28 +759,28 @@ public class BindTagTests extends AbstractTagTests { bindTag.setPageContext(pc); bindTag.setPath("name"); - assertTrue("Correct doStartTag return value", bindTag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(bindTag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertEquals("tb.name", status.getPath()); - assertEquals("Correct field value", "", status.getDisplayValue()); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat(status.getPath()).isEqualTo("tb.name"); + assertThat(status.getDisplayValue()).as("Correct field value").isEqualTo(""); BindTag bindTag2 = new BindTag(); bindTag2.setPageContext(pc); bindTag2.setPath("age"); - assertTrue("Correct doStartTag return value", bindTag2.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(bindTag2.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status2 = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status2 != null); - assertEquals("tb.age", status2.getPath()); - assertEquals("Correct field value", "0", status2.getDisplayValue()); + assertThat(status2 != null).as("Has status variable").isTrue(); + assertThat(status2.getPath()).isEqualTo("tb.age"); + assertThat(status2.getDisplayValue()).as("Correct field value").isEqualTo("0"); bindTag2.doEndTag(); BindStatus status3 = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertSame("Status matches previous status", status, status3); - assertEquals("tb.name", status.getPath()); - assertEquals("Correct field value", "", status.getDisplayValue()); + assertThat(status3).as("Status matches previous status").isSameAs(status); + assertThat(status.getPath()).isEqualTo("tb.name"); + assertThat(status.getDisplayValue()).as("Correct field value").isEqualTo(""); bindTag.doEndTag(); nestedPathTag.doEndTag(); @@ -805,10 +802,10 @@ public class BindTagTests extends AbstractTagTests { bindTag.setIgnoreNestedPath(true); bindTag.setPath("tb2.name"); - assertTrue("Correct doStartTag return value", bindTag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(bindTag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertTrue("Has status variable", status != null); - assertEquals("tb2.name", status.getPath()); + assertThat(status != null).as("Has status variable").isTrue(); + assertThat(status.getPath()).isEqualTo("tb2.name"); } @Test @@ -836,8 +833,8 @@ public class BindTagTests extends AbstractTagTests { transform.setVar("theDate"); transform.doStartTag(); - assertNotNull(pc.getAttribute("theDate")); - assertEquals(pc.getAttribute("theDate"), df.format(tb.getDate())); + assertThat(pc.getAttribute("theDate")).isNotNull(); + assertThat(df.format(tb.getDate())).isEqualTo(pc.getAttribute("theDate")); // try another time, this time using Strings bind = new BindTag(); @@ -852,8 +849,8 @@ public class BindTagTests extends AbstractTagTests { transform.setVar("theString"); transform.doStartTag(); - assertNotNull(pc.getAttribute("theString")); - assertEquals("name", pc.getAttribute("theString")); + assertThat(pc.getAttribute("theString")).isNotNull(); + assertThat(pc.getAttribute("theString")).isEqualTo("name"); } @Test @@ -881,8 +878,8 @@ public class BindTagTests extends AbstractTagTests { transform.setHtmlEscape(true); transform.doStartTag(); - assertNotNull(pc.getAttribute("theString")); - assertEquals("na<me", pc.getAttribute("theString")); + assertThat(pc.getAttribute("theString")).isNotNull(); + assertThat(pc.getAttribute("theString")).isEqualTo("na<me"); } @Test @@ -940,7 +937,7 @@ public class BindTagTests extends AbstractTagTests { transform.setVar("theString2"); transform.doStartTag(); - assertNull(pc.getAttribute("theString2")); + assertThat(pc.getAttribute("theString2")).isNull(); } @Test @@ -971,8 +968,8 @@ public class BindTagTests extends AbstractTagTests { transform.release(); - assertNotNull(pc.getAttribute("theDate")); - assertEquals(df.format(tb.getDate()), pc.getAttribute("theDate")); + assertThat(pc.getAttribute("theDate")).isNotNull(); + assertThat(pc.getAttribute("theDate")).isEqualTo(df.format(tb.getDate())); // try another time, this time using Strings bind = new BindTag(); @@ -990,8 +987,8 @@ public class BindTagTests extends AbstractTagTests { transform.release(); - assertNotNull(pc.getAttribute("theString")); - assertEquals("name", pc.getAttribute("theString")); + assertThat(pc.getAttribute("theString")).isNotNull(); + assertThat(pc.getAttribute("theString")).isEqualTo("name"); } /** diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/EvalTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/EvalTagTests.java index 9e435554767..1cacd3b662d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/EvalTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/EvalTagTests.java @@ -35,7 +35,7 @@ import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.mock.web.test.MockPageContext; import org.springframework.web.servlet.DispatcherServlet; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Keith Donald @@ -63,20 +63,20 @@ public class EvalTagTests extends AbstractTagTests { public void printScopedAttributeResult() throws Exception { tag.setExpression("bean.method()"); int action = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, action); + assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("foo", ((MockHttpServletResponse) context.getResponse()).getContentAsString()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(((MockHttpServletResponse) context.getResponse()).getContentAsString()).isEqualTo("foo"); } @Test public void printNullAsEmptyString() throws Exception { tag.setExpression("bean.null"); int action = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, action); + assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("", ((MockHttpServletResponse) context.getResponse()).getContentAsString()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(((MockHttpServletResponse) context.getResponse()).getContentAsString()).isEqualTo(""); } @Test @@ -84,11 +84,10 @@ public class EvalTagTests extends AbstractTagTests { PercentStyleFormatter formatter = new PercentStyleFormatter(); tag.setExpression("bean.formattable"); int action = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, action); + assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals(formatter.print(new BigDecimal(".25"), Locale.getDefault()), - ((MockHttpServletResponse) context.getResponse()).getContentAsString()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(((MockHttpServletResponse) context.getResponse()).getContentAsString()).isEqualTo(formatter.print(new BigDecimal(".25"), Locale.getDefault())); } @Test @@ -96,10 +95,10 @@ public class EvalTagTests extends AbstractTagTests { tag.setExpression("bean.html()"); tag.setHtmlEscape(true); int action = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, action); + assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("<p>", ((MockHttpServletResponse) context.getResponse()).getContentAsString()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(((MockHttpServletResponse) context.getResponse()).getContentAsString()).isEqualTo("<p>"); } @Test @@ -107,11 +106,10 @@ public class EvalTagTests extends AbstractTagTests { tag.setExpression("bean.js()"); tag.setJavaScriptEscape(true); int action = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, action); + assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("function foo() { alert(\\\"hi\\\") }", - ((MockHttpServletResponse)context.getResponse()).getContentAsString()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(((MockHttpServletResponse) context.getResponse()).getContentAsString()).isEqualTo("function foo() { alert(\\\"hi\\\") }"); } @Test @@ -119,10 +117,10 @@ public class EvalTagTests extends AbstractTagTests { tag.setExpression("bean.formattable"); tag.setVar("foo"); int action = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, action); + assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals(new BigDecimal(".25"), context.getAttribute("foo")); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(context.getAttribute("foo")).isEqualTo(new BigDecimal(".25")); } @Test // SPR-6923 @@ -130,10 +128,10 @@ public class EvalTagTests extends AbstractTagTests { tag.setExpression("bean.bean"); tag.setVar("foo"); int action = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, action); + assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("not the bean object", context.getAttribute("foo")); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(context.getAttribute("foo")).isEqualTo("not the bean object"); } @Test @@ -144,10 +142,10 @@ public class EvalTagTests extends AbstractTagTests { tag.setExpression("@bean2.bean"); tag.setVar("foo"); int action = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, action); + assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("not the bean object", context.getAttribute("foo")); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(context.getAttribute("foo")).isEqualTo("not the bean object"); } @Test @@ -160,20 +158,20 @@ public class EvalTagTests extends AbstractTagTests { wac.getDefaultListableBeanFactory().registerSingleton("bean2", context.getRequest().getAttribute("bean")); tag.setExpression("@environment['key.foo']"); int action = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, action); + assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("value.foo", ((MockHttpServletResponse) context.getResponse()).getContentAsString()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(((MockHttpServletResponse) context.getResponse()).getContentAsString()).isEqualTo("value.foo"); } @Test public void mapAccess() throws Exception { tag.setExpression("bean.map.key"); int action = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, action); + assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("value", ((MockHttpServletResponse) context.getResponse()).getContentAsString()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(((MockHttpServletResponse) context.getResponse()).getContentAsString()).isEqualTo("value"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/HtmlEscapeTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/HtmlEscapeTagTests.java index ec02a886a35..bb4c712191a 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/HtmlEscapeTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/HtmlEscapeTagTests.java @@ -26,8 +26,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.util.WebUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -51,33 +50,41 @@ public class HtmlEscapeTagTests extends AbstractTagTests { testTag.setPageContext(pc); testTag.doStartTag(); - assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape()); - assertTrue("Correctly applied", !testTag.isHtmlEscape()); + boolean condition7 = !tag.getRequestContext().isDefaultHtmlEscape(); + assertThat(condition7).as("Correct default").isTrue(); + boolean condition6 = !testTag.isHtmlEscape(); + assertThat(condition6).as("Correctly applied").isTrue(); tag.setDefaultHtmlEscape(true); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape()); - assertTrue("Correctly applied", testTag.isHtmlEscape()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.getRequestContext().isDefaultHtmlEscape()).as("Correctly enabled").isTrue(); + assertThat(testTag.isHtmlEscape()).as("Correctly applied").isTrue(); tag.setDefaultHtmlEscape(false); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape()); - assertTrue("Correctly applied", !testTag.isHtmlEscape()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + boolean condition5 = !tag.getRequestContext().isDefaultHtmlEscape(); + assertThat(condition5).as("Correctly disabled").isTrue(); + boolean condition4 = !testTag.isHtmlEscape(); + assertThat(condition4).as("Correctly applied").isTrue(); tag.setDefaultHtmlEscape(true); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); testTag.setHtmlEscape(true); - assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape()); - assertTrue("Correctly applied", testTag.isHtmlEscape()); + assertThat(tag.getRequestContext().isDefaultHtmlEscape()).as("Correctly enabled").isTrue(); + assertThat(testTag.isHtmlEscape()).as("Correctly applied").isTrue(); testTag.setHtmlEscape(false); - assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape()); - assertTrue("Correctly applied", !testTag.isHtmlEscape()); + assertThat(tag.getRequestContext().isDefaultHtmlEscape()).as("Correctly enabled").isTrue(); + boolean condition3 = !testTag.isHtmlEscape(); + assertThat(condition3).as("Correctly applied").isTrue(); tag.setDefaultHtmlEscape(false); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); testTag.setHtmlEscape(true); - assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape()); - assertTrue("Correctly applied", testTag.isHtmlEscape()); + boolean condition2 = !tag.getRequestContext().isDefaultHtmlEscape(); + assertThat(condition2).as("Correctly disabled").isTrue(); + assertThat(testTag.isHtmlEscape()).as("Correctly applied").isTrue(); testTag.setHtmlEscape(false); - assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape()); - assertTrue("Correctly applied", !testTag.isHtmlEscape()); + boolean condition1 = !tag.getRequestContext().isDefaultHtmlEscape(); + assertThat(condition1).as("Correctly disabled").isTrue(); + boolean condition = !testTag.isHtmlEscape(); + assertThat(condition).as("Correctly applied").isTrue(); } @Test @@ -90,13 +97,15 @@ public class HtmlEscapeTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.doStartTag(); - assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape()); + boolean condition1 = !tag.getRequestContext().isDefaultHtmlEscape(); + assertThat(condition1).as("Correct default").isTrue(); tag.setDefaultHtmlEscape(true); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.getRequestContext().isDefaultHtmlEscape()).as("Correctly enabled").isTrue(); tag.setDefaultHtmlEscape(false); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + boolean condition = !tag.getRequestContext().isDefaultHtmlEscape(); + assertThat(condition).as("Correctly disabled").isTrue(); } @Test @@ -108,13 +117,15 @@ public class HtmlEscapeTagTests extends AbstractTagTests { tag.doStartTag(); sc.addInitParameter(WebUtils.HTML_ESCAPE_CONTEXT_PARAM, "false"); - assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape()); + boolean condition1 = !tag.getRequestContext().isDefaultHtmlEscape(); + assertThat(condition1).as("Correct default").isTrue(); tag.setDefaultHtmlEscape(true); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.getRequestContext().isDefaultHtmlEscape()).as("Correctly enabled").isTrue(); tag.setDefaultHtmlEscape(false); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + boolean condition = !tag.getRequestContext().isDefaultHtmlEscape(); + assertThat(condition).as("Correctly disabled").isTrue(); } @Test @@ -132,9 +143,9 @@ public class HtmlEscapeTagTests extends AbstractTagTests { } }; tag.setPageContext(pc); - assertEquals(BodyTag.EVAL_BODY_BUFFERED, tag.doStartTag()); - assertEquals(Tag.SKIP_BODY, tag.doAfterBody()); - assertEquals("test text", result.toString()); + assertThat(tag.doStartTag()).isEqualTo(BodyTag.EVAL_BODY_BUFFERED); + assertThat(tag.doAfterBody()).isEqualTo(Tag.SKIP_BODY); + assertThat(result.toString()).isEqualTo("test text"); } @Test @@ -153,9 +164,9 @@ public class HtmlEscapeTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setHtmlEscape(true); - assertEquals(BodyTag.EVAL_BODY_BUFFERED, tag.doStartTag()); - assertEquals(Tag.SKIP_BODY, tag.doAfterBody()); - assertEquals("test & text", result.toString()); + assertThat(tag.doStartTag()).isEqualTo(BodyTag.EVAL_BODY_BUFFERED); + assertThat(tag.doAfterBody()).isEqualTo(Tag.SKIP_BODY); + assertThat(result.toString()).isEqualTo("test & text"); } @Test @@ -174,9 +185,9 @@ public class HtmlEscapeTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setJavaScriptEscape(true); - assertEquals(BodyTag.EVAL_BODY_BUFFERED, tag.doStartTag()); - assertEquals(Tag.SKIP_BODY, tag.doAfterBody()); - assertEquals("Correct content", "\\' test & text \\\\", result.toString()); + assertThat(tag.doStartTag()).isEqualTo(BodyTag.EVAL_BODY_BUFFERED); + assertThat(tag.doAfterBody()).isEqualTo(Tag.SKIP_BODY); + assertThat(result.toString()).as("Correct content").isEqualTo("\\' test & text \\\\"); } @Test @@ -196,9 +207,9 @@ public class HtmlEscapeTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setHtmlEscape(true); tag.setJavaScriptEscape(true); - assertEquals(BodyTag.EVAL_BODY_BUFFERED, tag.doStartTag()); - assertEquals(Tag.SKIP_BODY, tag.doAfterBody()); - assertEquals("Correct content", "' test & text \\\\", result.toString()); + assertThat(tag.doStartTag()).isEqualTo(BodyTag.EVAL_BODY_BUFFERED); + assertThat(tag.doAfterBody()).isEqualTo(Tag.SKIP_BODY); + assertThat(result.toString()).as("Correct content").isEqualTo("' test & text \\\\"); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/MessageTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/MessageTagTests.java index 72d380d5129..380f3643adc 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/MessageTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/MessageTagTests.java @@ -33,8 +33,7 @@ import org.springframework.web.servlet.support.RequestContext; import org.springframework.web.servlet.support.RequestContextUtils; import org.springframework.web.util.WebUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MessageTag}. @@ -58,9 +57,9 @@ public class MessageTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setMessage(new DefaultMessageSourceResolvable("test")); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test message", message.toString()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("test message"); } @Test @@ -75,9 +74,9 @@ public class MessageTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setCode("test"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test message", message.toString()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("test message"); } @Test @@ -93,9 +92,9 @@ public class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setCode("testArgs"); tag.setArguments("arg1"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test arg1 message {1}", message.toString()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("test arg1 message {1}"); } @Test @@ -111,9 +110,9 @@ public class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setCode("testArgs"); tag.setArguments("arg1,arg2"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test arg1 message arg2", message.toString()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("test arg1 message arg2"); } @Test @@ -130,9 +129,9 @@ public class MessageTagTests extends AbstractTagTests { tag.setCode("testArgs"); tag.setArguments("arg1,1;arg2,2"); tag.setArgumentSeparator(";"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test arg1,1 message arg2,2", message.toString()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("test arg1,1 message arg2,2"); } @Test @@ -148,9 +147,9 @@ public class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setCode("testArgs"); tag.setArguments(new Object[] {"arg1", 5}); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test arg1 message 5", message.toString()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("test arg1 message 5"); } @Test @@ -166,9 +165,9 @@ public class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setCode("testArgs"); tag.setArguments(5); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test 5 message {1}", message.toString()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("test 5 message {1}"); } @Test @@ -183,11 +182,11 @@ public class MessageTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setCode("testArgs"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); tag.setArguments(5); tag.addArgument(7); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test 5 message 7", message.toString()); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("test 5 message 7"); } @Test @@ -202,10 +201,10 @@ public class MessageTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setCode("testArgs"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); tag.addArgument(7); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test 7 message {1}", message.toString()); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("test 7 message {1}"); } @Test @@ -220,11 +219,11 @@ public class MessageTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setCode("testArgs"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); tag.addArgument("arg1"); tag.addArgument(6); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test arg1 message 6", message.toString()); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("test arg1 message 6"); } @Test @@ -240,9 +239,9 @@ public class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setCode("test"); tag.setText("testtext"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test message", (message.toString())); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat((message.toString())).as("Correct message").isEqualTo("test message"); } @Test @@ -258,9 +257,9 @@ public class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setText("test & text é"); tag.setHtmlEscape(true); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertTrue("Correct message", message.toString().startsWith("test & text &")); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString().startsWith("test & text &")).as("Correct message").isTrue(); } @Test @@ -278,9 +277,9 @@ public class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setText("test <&> é"); tag.setHtmlEscape(true); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test <&> é", message.toString()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("test <&> é"); } @Test @@ -296,9 +295,9 @@ public class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setText("' test & text \\"); tag.setJavaScriptEscape(true); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "\\' test & text \\\\", message.toString()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("\\' test & text \\\\"); } @Test @@ -315,9 +314,9 @@ public class MessageTagTests extends AbstractTagTests { tag.setText("' test & text \\"); tag.setHtmlEscape(true); tag.setJavaScriptEscape(true); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "' test & text \\\\", message.toString()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).as("Correct message").isEqualTo("' test & text \\\\"); } @Test @@ -329,8 +328,8 @@ public class MessageTagTests extends AbstractTagTests { tag.setVar("testvar"); tag.setScope("page"); tag.doStartTag(); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("text & text", pc.getAttribute("testvar")); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(pc.getAttribute("testvar")).isEqualTo("text & text"); tag.release(); tag = new MessageTag(); @@ -338,8 +337,8 @@ public class MessageTagTests extends AbstractTagTests { tag.setCode("test"); tag.setVar("testvar2"); tag.doStartTag(); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test message", pc.getAttribute("testvar2")); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(pc.getAttribute("testvar2")).as("Correct message").isEqualTo("test message"); tag.release(); } @@ -351,8 +350,8 @@ public class MessageTagTests extends AbstractTagTests { tag.setText("text & text"); tag.setVar("testvar"); tag.doStartTag(); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("text & text", pc.getAttribute("testvar")); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(pc.getAttribute("testvar")).isEqualTo("text & text"); tag.release(); // try to reuse @@ -361,8 +360,8 @@ public class MessageTagTests extends AbstractTagTests { tag.setVar("testvar"); tag.doStartTag(); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("Correct message", "test message", pc.getAttribute("testvar")); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(pc.getAttribute("testvar")).as("Correct message").isEqualTo("test message"); } @Test @@ -377,7 +376,7 @@ public class MessageTagTests extends AbstractTagTests { tag.setCode("test"); tag.setVar("testvar2"); tag.doStartTag(); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); } @Test @@ -385,18 +384,16 @@ public class MessageTagTests extends AbstractTagTests { public void requestContext() throws ServletException { PageContext pc = createPageContext(); RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest(), pc.getServletContext()); - assertEquals("test message", rc.getMessage("test")); - assertEquals("test message", rc.getMessage("test", (Object[]) null)); - assertEquals("test message", rc.getMessage("test", "default")); - assertEquals("test message", rc.getMessage("test", (Object[]) null, "default")); - assertEquals("test arg1 message arg2", - rc.getMessage("testArgs", new String[] {"arg1", "arg2"}, "default")); - assertEquals("test arg1 message arg2", - rc.getMessage("testArgs", Arrays.asList(new String[] {"arg1", "arg2"}), "default")); - assertEquals("default", rc.getMessage("testa", "default")); - assertEquals("default", rc.getMessage("testa", (List) null, "default")); + assertThat(rc.getMessage("test")).isEqualTo("test message"); + assertThat(rc.getMessage("test", (Object[]) null)).isEqualTo("test message"); + assertThat(rc.getMessage("test", "default")).isEqualTo("test message"); + assertThat(rc.getMessage("test", (Object[]) null, "default")).isEqualTo("test message"); + assertThat(rc.getMessage("testArgs", new String[]{"arg1", "arg2"}, "default")).isEqualTo("test arg1 message arg2"); + assertThat(rc.getMessage("testArgs", Arrays.asList(new String[]{"arg1", "arg2"}), "default")).isEqualTo("test arg1 message arg2"); + assertThat(rc.getMessage("testa", "default")).isEqualTo("default"); + assertThat(rc.getMessage("testa", (List) null, "default")).isEqualTo("default"); MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"test"}); - assertEquals("test message", rc.getMessage(resolvable)); + assertThat(rc.getMessage(resolvable)).isEqualTo("test message"); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java index e0aae341ff8..40a4a7a3e1d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java @@ -27,9 +27,8 @@ import org.junit.Test; import org.springframework.mock.web.test.MockBodyContent; import org.springframework.mock.web.test.MockHttpServletResponse; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; /** * Unit tests for {@link ParamTag}. @@ -57,9 +56,9 @@ public class ParamTagTests extends AbstractTagTests { int action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("name", parent.getParam().getName()); - assertEquals("value", parent.getParam().getValue()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getParam().getName()).isEqualTo("name"); + assertThat(parent.getParam().getValue()).isEqualTo("value"); } @Test @@ -69,9 +68,9 @@ public class ParamTagTests extends AbstractTagTests { int action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("name", parent.getParam().getName()); - assertEquals("value", parent.getParam().getValue()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getParam().getName()).isEqualTo("name"); + assertThat(parent.getParam().getValue()).isEqualTo("value"); } @Test @@ -80,9 +79,9 @@ public class ParamTagTests extends AbstractTagTests { int action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("name", parent.getParam().getName()); - assertNull(parent.getParam().getValue()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getParam().getName()).isEqualTo("name"); + assertThat(parent.getParam().getValue()).isNull(); } @Test @@ -92,9 +91,9 @@ public class ParamTagTests extends AbstractTagTests { int action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("name", parent.getParam().getName()); - assertNull(parent.getParam().getValue()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getParam().getName()).isEqualTo("name"); + assertThat(parent.getParam().getValue()).isNull(); } @Test @@ -104,9 +103,9 @@ public class ParamTagTests extends AbstractTagTests { int action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("name1", parent.getParam().getName()); - assertEquals("value1", parent.getParam().getValue()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getParam().getName()).isEqualTo("name1"); + assertThat(parent.getParam().getValue()).isEqualTo("value1"); tag.release(); @@ -118,9 +117,9 @@ public class ParamTagTests extends AbstractTagTests { action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); - assertEquals("name2", parent.getParam().getName()); - assertEquals("value2", parent.getParam().getValue()); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); + assertThat(parent.getParam().getName()).isEqualTo("name2"); + assertThat(parent.getParam().getValue()).isEqualTo("value2"); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTests.java index c5a0eefbbd0..16ac3a2bf7e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTests.java @@ -18,8 +18,7 @@ package org.springframework.web.servlet.tags; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link Param}. @@ -33,19 +32,19 @@ public class ParamTests { @Test public void name() { param.setName("name"); - assertEquals("name", param.getName()); + assertThat(param.getName()).isEqualTo("name"); } @Test public void value() { param.setValue("value"); - assertEquals("value", param.getValue()); + assertThat(param.getValue()).isEqualTo("value"); } @Test public void nullDefaults() { - assertNull(param.getName()); - assertNull(param.getValue()); + assertThat(param.getName()).isNull(); + assertThat(param.getValue()).isNull(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ThemeTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ThemeTagTests.java index 19f1f26eb66..64c22f5419b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ThemeTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ThemeTagTests.java @@ -30,8 +30,7 @@ import org.springframework.context.MessageSourceResolvable; import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.web.servlet.support.RequestContext; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller @@ -52,9 +51,9 @@ public class ThemeTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setCode("themetest"); - assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); - assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag()); - assertEquals("theme test message", message.toString()); + assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); + assertThat(message.toString()).isEqualTo("theme test message"); } @Test @@ -62,18 +61,16 @@ public class ThemeTagTests extends AbstractTagTests { public void requestContext() throws ServletException { PageContext pc = createPageContext(); RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest()); - assertEquals("theme test message", rc.getThemeMessage("themetest")); - assertEquals("theme test message", rc.getThemeMessage("themetest", (String[]) null)); - assertEquals("theme test message", rc.getThemeMessage("themetest", "default")); - assertEquals("theme test message", rc.getThemeMessage("themetest", (Object[]) null, "default")); - assertEquals("theme test message arg1", - rc.getThemeMessage("themetestArgs", new String[] {"arg1"})); - assertEquals("theme test message arg1", - rc.getThemeMessage("themetestArgs", Arrays.asList(new String[] {"arg1"}))); - assertEquals("default", rc.getThemeMessage("themetesta", "default")); - assertEquals("default", rc.getThemeMessage("themetesta", (List) null, "default")); + assertThat(rc.getThemeMessage("themetest")).isEqualTo("theme test message"); + assertThat(rc.getThemeMessage("themetest", (String[]) null)).isEqualTo("theme test message"); + assertThat(rc.getThemeMessage("themetest", "default")).isEqualTo("theme test message"); + assertThat(rc.getThemeMessage("themetest", (Object[]) null, "default")).isEqualTo("theme test message"); + assertThat(rc.getThemeMessage("themetestArgs", new String[]{"arg1"})).isEqualTo("theme test message arg1"); + assertThat(rc.getThemeMessage("themetestArgs", Arrays.asList(new String[]{"arg1"}))).isEqualTo("theme test message arg1"); + assertThat(rc.getThemeMessage("themetesta", "default")).isEqualTo("default"); + assertThat(rc.getThemeMessage("themetesta", (List) null, "default")).isEqualTo("default"); MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"themetest"}); - assertEquals("theme test message", rc.getThemeMessage(resolvable)); + assertThat(rc.getThemeMessage(resolvable)).isEqualTo("theme test message"); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java index 728d66dc19d..3f182613e96 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java @@ -31,8 +31,6 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockPageContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; /** * @author Scott Andrews @@ -61,7 +59,7 @@ public class UrlTagTests extends AbstractTagTests { public void doStartTag() throws JspException { int action = tag.doStartTag(); - assertEquals(Tag.EVAL_BODY_INCLUDE, action); + assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); } @Test @@ -70,7 +68,7 @@ public class UrlTagTests extends AbstractTagTests { tag.doStartTag(); int action = tag.doEndTag(); - assertEquals(Tag.EVAL_PAGE, action); + assertThat(action).isEqualTo(Tag.EVAL_PAGE); } @Test @@ -80,7 +78,7 @@ public class UrlTagTests extends AbstractTagTests { tag.doStartTag(); tag.doEndTag(); - assertEquals("url/path", context.getAttribute("var", PageContext.PAGE_SCOPE)); + assertThat(context.getAttribute("var", PageContext.PAGE_SCOPE)).isEqualTo("url/path"); } @Test @@ -91,7 +89,7 @@ public class UrlTagTests extends AbstractTagTests { tag.doStartTag(); tag.doEndTag(); - assertEquals("url/path", context.getAttribute("var", PageContext.REQUEST_SCOPE)); + assertThat(context.getAttribute("var", PageContext.REQUEST_SCOPE)).isEqualTo("url/path"); } @Test @@ -111,7 +109,7 @@ public class UrlTagTests extends AbstractTagTests { tag.addParam(param); tag.doEndTag(); - assertEquals("url/path?n%20me=v%26l%3De&name=value2", context.getAttribute("var")); + assertThat(context.getAttribute("var")).isEqualTo("url/path?n%20me=v%26l%3De&name=value2"); } @Test @@ -133,7 +131,7 @@ public class UrlTagTests extends AbstractTagTests { tag.addParam(param); tag.doEndTag(); - assertEquals("url/path?n%20me=v%26l%3De&name=value2", context.getAttribute("var")); + assertThat(context.getAttribute("var")).isEqualTo("url/path?n%20me=v%26l%3De&name=value2"); } @Test @@ -154,7 +152,7 @@ public class UrlTagTests extends AbstractTagTests { tag.addParam(param); tag.doEndTag(); - assertEquals("url/path?n%20me=v%26l%3De&name=value2", context.getAttribute("var")); + assertThat(context.getAttribute("var")).isEqualTo("url/path?n%20me=v%26l%3De&name=value2"); } @Test @@ -175,7 +173,7 @@ public class UrlTagTests extends AbstractTagTests { tag.addParam(param); tag.doEndTag(); - assertEquals("url\\/path?n%20me=v%26l%3De&name=value2", context.getAttribute("var")); + assertThat(context.getAttribute("var")).isEqualTo("url\\/path?n%20me=v%26l%3De&name=value2"); } @Test @@ -197,7 +195,7 @@ public class UrlTagTests extends AbstractTagTests { tag.addParam(param); tag.doEndTag(); - assertEquals("url\\/path?n%20me=v%26l%3De&name=value2", context.getAttribute("var")); + assertThat(context.getAttribute("var")).isEqualTo("url\\/path?n%20me=v%26l%3De&name=value2"); } @Test @@ -206,7 +204,7 @@ public class UrlTagTests extends AbstractTagTests { Set usedParams = new HashSet<>(); String queryString = tag.createQueryString(params, usedParams, true); - assertEquals("", queryString); + assertThat(queryString).isEqualTo(""); } @Test @@ -220,7 +218,7 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String queryString = tag.createQueryString(params, usedParams, true); - assertEquals("?name=value", queryString); + assertThat(queryString).isEqualTo("?name=value"); } @Test @@ -234,7 +232,7 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String queryString = tag.createQueryString(params, usedParams, false); - assertEquals("&name=value", queryString); + assertThat(queryString).isEqualTo("&name=value"); } @Test @@ -248,7 +246,7 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String queryString = tag.createQueryString(params, usedParams, true); - assertEquals("?name=", queryString); + assertThat(queryString).isEqualTo("?name="); } @Test @@ -262,7 +260,7 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String queryString = tag.createQueryString(params, usedParams, true); - assertEquals("?name", queryString); + assertThat(queryString).isEqualTo("?name"); } @Test @@ -277,7 +275,7 @@ public class UrlTagTests extends AbstractTagTests { usedParams.add("name"); String queryString = tag.createQueryString(params, usedParams, true); - assertEquals("", queryString); + assertThat(queryString).isEqualTo(""); } @Test @@ -296,7 +294,7 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String queryString = tag.createQueryString(params, usedParams, true); - assertEquals("?name=value&name=value2", queryString); + assertThat(queryString).isEqualTo("?name=value&name=value2"); } @Test @@ -315,7 +313,7 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String queryString = tag.createQueryString(params, usedParams, true); - assertEquals("?n%20me=v%26l%3De&name=value2", queryString); + assertThat(queryString).isEqualTo("?n%20me=v%26l%3De&name=value2"); } @Test @@ -329,7 +327,7 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String queryString = tag.createQueryString(params, usedParams, true); - assertEquals("", queryString); + assertThat(queryString).isEqualTo(""); } @Test @@ -343,7 +341,7 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String queryString = tag.createQueryString(params, usedParams, true); - assertEquals("", queryString); + assertThat(queryString).isEqualTo(""); } @Test @@ -352,8 +350,8 @@ public class UrlTagTests extends AbstractTagTests { Set usedParams = new HashSet<>(); String uri = tag.replaceUriTemplateParams("url/path", params, usedParams); - assertEquals("url/path", uri); - assertEquals(0, usedParams.size()); + assertThat(uri).isEqualTo("url/path"); + assertThat(usedParams.size()).isEqualTo(0); } @Test @@ -362,8 +360,8 @@ public class UrlTagTests extends AbstractTagTests { Set usedParams = new HashSet<>(); String uri = tag.replaceUriTemplateParams("url/{path}", params, usedParams); - assertEquals("url/{path}", uri); - assertEquals(0, usedParams.size()); + assertThat(uri).isEqualTo("url/{path}"); + assertThat(usedParams.size()).isEqualTo(0); } @Test @@ -377,9 +375,9 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String uri = tag.replaceUriTemplateParams("url/{name}", params, usedParams); - assertEquals("url/value", uri); - assertEquals(1, usedParams.size()); - assertTrue(usedParams.contains("name")); + assertThat(uri).isEqualTo("url/value"); + assertThat(usedParams.size()).isEqualTo(1); + assertThat(usedParams.contains("name")).isTrue(); } @Test @@ -393,9 +391,9 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String uri = tag.replaceUriTemplateParams("url/{n me}", params, usedParams); - assertEquals("url/value", uri); - assertEquals(1, usedParams.size()); - assertTrue(usedParams.contains("n me")); + assertThat(uri).isEqualTo("url/value"); + assertThat(usedParams.size()).isEqualTo(1); + assertThat(usedParams.contains("n me")).isTrue(); } @Test @@ -411,9 +409,9 @@ public class UrlTagTests extends AbstractTagTests { String uri = tag.replaceUriTemplateParams("url/{name}", params, usedParams); - assertEquals("url/v%20lue", uri); - assertEquals(1, usedParams.size()); - assertTrue(usedParams.contains("name")); + assertThat(uri).isEqualTo("url/v%20lue"); + assertThat(usedParams.size()).isEqualTo(1); + assertThat(usedParams.contains("name")).isTrue(); } @Test // SPR-11401 @@ -428,9 +426,9 @@ public class UrlTagTests extends AbstractTagTests { String uri = tag.replaceUriTemplateParams("url/{/name}", params, usedParams); - assertEquals("url/my%2FId", uri); - assertEquals(1, usedParams.size()); - assertTrue(usedParams.contains("name")); + assertThat(uri).isEqualTo("url/my%2FId"); + assertThat(usedParams.size()).isEqualTo(1); + assertThat(usedParams.contains("name")).isTrue(); } @Test @@ -444,9 +442,9 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String uri = tag.replaceUriTemplateParams("url/{name}", params, usedParams); - assertEquals("url/my/Id", uri); - assertEquals(1, usedParams.size()); - assertTrue(usedParams.contains("name")); + assertThat(uri).isEqualTo("url/my/Id"); + assertThat(usedParams.size()).isEqualTo(1); + assertThat(usedParams.contains("name")).isTrue(); } @Test @@ -455,7 +453,7 @@ public class UrlTagTests extends AbstractTagTests { tag.doStartTag(); String uri = tag.createUrl(); - assertEquals("https://www.springframework.org/", uri); + assertThat(uri).isEqualTo("https://www.springframework.org/"); } @Test @@ -464,7 +462,7 @@ public class UrlTagTests extends AbstractTagTests { tag.doStartTag(); String uri = tag.createUrl(); - assertEquals("url/path", uri); + assertThat(uri).isEqualTo("url/path"); } @Test @@ -475,7 +473,7 @@ public class UrlTagTests extends AbstractTagTests { tag.doStartTag(); String uri = tag.createUrl(); - assertEquals("/app-context/url/path", uri); + assertThat(uri).isEqualTo("/app-context/url/path"); } @Test @@ -487,7 +485,7 @@ public class UrlTagTests extends AbstractTagTests { tag.doStartTag(); String uri = tag.createUrl(); - assertEquals("/some-other-context/url/path", uri); + assertThat(uri).isEqualTo("/some-other-context/url/path"); } @Test @@ -499,7 +497,7 @@ public class UrlTagTests extends AbstractTagTests { tag.doStartTag(); String uri = tag.createUrl(); - assertEquals("/some-other-context/url/path", uri); + assertThat(uri).isEqualTo("/some-other-context/url/path"); } @Test @@ -511,7 +509,7 @@ public class UrlTagTests extends AbstractTagTests { tag.doStartTag(); String uri = tag.createUrl(); - assertEquals("/url/path", uri); + assertThat(uri).isEqualTo("/url/path"); } @Test @@ -530,7 +528,7 @@ public class UrlTagTests extends AbstractTagTests { tag.addParam(param); String uri = tag.createUrl(); - assertEquals("url/path?name=value&n%20me=v%20lue", uri); + assertThat(uri).isEqualTo("url/path?name=value&n%20me=v%20lue"); } @Test @@ -549,7 +547,7 @@ public class UrlTagTests extends AbstractTagTests { tag.addParam(param); String uri = tag.createUrl(); - assertEquals("url/value?n%20me=v%20lue", uri); + assertThat(uri).isEqualTo("url/value?n%20me=v%20lue"); } @Test @@ -563,7 +561,7 @@ public class UrlTagTests extends AbstractTagTests { tag.addParam(param); String uri = tag.createUrl(); - assertEquals("url/path?foo=bar&name=value", uri); + assertThat(uri).isEqualTo("url/path?foo=bar&name=value"); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java index 56326d9323f..01d22accc39 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java @@ -39,7 +39,7 @@ import org.springframework.web.servlet.support.RequestDataValueProcessorWrapper; import org.springframework.web.servlet.tags.AbstractTagTests; import org.springframework.web.servlet.tags.RequestContextAwareTag; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -124,21 +124,19 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests { protected final void assertContainsAttribute(String output, String attributeName, String attributeValue) { String attributeString = attributeName + "=\"" + attributeValue + "\""; - assertTrue("Expected to find attribute '" + attributeName + + assertThat(output.contains(attributeString)).as("Expected to find attribute '" + attributeName + "' with value '" + attributeValue + - "' in output + '" + output + "'", - output.contains(attributeString)); + "' in output + '" + output + "'").isTrue(); } protected final void assertAttributeNotPresent(String output, String attributeName) { - assertTrue("Unexpected attribute '" + attributeName + "' in output '" + output + "'.", - !output.contains(attributeName + "=\"")); + boolean condition = !output.contains(attributeName + "=\""); + assertThat(condition).as("Unexpected attribute '" + attributeName + "' in output '" + output + "'.").isTrue(); } protected final void assertBlockTagContains(String output, String desiredContents) { String contents = output.substring(output.indexOf(">") + 1, output.lastIndexOf("<")); - assertTrue("Expected to find '" + desiredContents + "' in the contents of block tag '" + output + "'", - contents.contains(desiredContents)); + assertThat(contents.contains(desiredContents)).as("Expected to find '" + desiredContents + "' in the contents of block tag '" + output + "'").isTrue(); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java index c6d71aa0e43..3f10732ca91 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java @@ -23,8 +23,7 @@ import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rossen Stoyanchev @@ -45,8 +44,8 @@ public class ButtonTagTests extends AbstractFormTagTests { @Test public void buttonTag() throws Exception { - assertEquals(Tag.EVAL_BODY_INCLUDE, this.tag.doStartTag()); - assertEquals(Tag.EVAL_PAGE, this.tag.doEndTag()); + assertThat(this.tag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE); + assertThat(this.tag.doEndTag()).isEqualTo(Tag.EVAL_PAGE); String output = getOutput(); assertTagOpened(output); @@ -79,11 +78,11 @@ public class ButtonTagTests extends AbstractFormTagTests { } protected final void assertTagClosed(String output) { - assertTrue("Tag not closed properly", output.endsWith("")); + assertThat(output.endsWith("")).as("Tag not closed properly").isTrue(); } protected final void assertTagOpened(String output) { - assertTrue("Tag not opened properly", output.startsWith("