diff --git a/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java b/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java index 5b76d47f4c6..683a5d994a0 100644 --- a/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java +++ b/integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,7 +99,7 @@ class AopNamespaceHandlerScopeIntegrationTests { RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(oldRequest)); assertThat(requestScoped.getName()).isEqualTo(bram); - assertThat(((Advised) requestScoped).getAdvisors().length > 0).as("Should have advisors").isTrue(); + assertThat(((Advised) requestScoped).getAdvisors()).as("Should have advisors").isNotEmpty(); } @Test @@ -131,7 +131,7 @@ class AopNamespaceHandlerScopeIntegrationTests { request.setSession(oldSession); assertThat(sessionScoped.getName()).isEqualTo(bram); - assertThat(((Advised) sessionScoped).getAdvisors().length > 0).as("Should have advisors").isTrue(); + assertThat(((Advised) sessionScoped).getAdvisors()).as("Should have advisors").isNotEmpty(); } } diff --git a/integration-tests/src/test/java/org/springframework/beans/factory/xml/ComponentBeanDefinitionParserTests.java b/integration-tests/src/test/java/org/springframework/beans/factory/xml/ComponentBeanDefinitionParserTests.java index fbc3fec5b4b..31eee877ed5 100644 --- a/integration-tests/src/test/java/org/springframework/beans/factory/xml/ComponentBeanDefinitionParserTests.java +++ b/integration-tests/src/test/java/org/springframework/beans/factory/xml/ComponentBeanDefinitionParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,25 +52,25 @@ class ComponentBeanDefinitionParserTests { @Test void testBionicBasic() { Component cp = getBionicFamily(); - assertThat("Bionic-1").isEqualTo(cp.getName()); + assertThat(cp.getName()).isEqualTo("Bionic-1"); } @Test void testBionicFirstLevelChildren() { Component cp = getBionicFamily(); List components = cp.getComponents(); - assertThat(2).isEqualTo(components.size()); - assertThat("Mother-1").isEqualTo(components.get(0).getName()); - assertThat("Rock-1").isEqualTo(components.get(1).getName()); + assertThat(components).hasSize(2); + assertThat(components.get(0).getName()).isEqualTo("Mother-1"); + assertThat(components.get(1).getName()).isEqualTo("Rock-1"); } @Test void testBionicSecondLevelChildren() { Component cp = getBionicFamily(); List components = cp.getComponents().get(0).getComponents(); - assertThat(2).isEqualTo(components.size()); - assertThat("Karate-1").isEqualTo(components.get(0).getName()); - assertThat("Sport-1").isEqualTo(components.get(1).getName()); + assertThat(components).hasSize(2); + assertThat(components.get(0).getName()).isEqualTo("Karate-1"); + assertThat(components.get(1).getName()).isEqualTo("Sport-1"); } private Component getBionicFamily() { 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 4591b74624a..b465a462514 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,7 +70,7 @@ public class MethodInvocationProceedingJoinPointTests { AtomicInteger depth = new AtomicInteger(); pf.addAdvice((MethodBeforeAdvice) (method, args, target) -> { JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint(); - assertThat(jp.toString().contains(method.getName())).as("Method named in toString").isTrue(); + assertThat(jp.toString()).as("Method named in toString").contains(method.getName()); // Ensure that these don't cause problems jp.toShortString(); jp.toLongString(); 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 f990d2ab16e..074668bb8a8 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 @@ -319,10 +319,10 @@ abstract class AbstractAspectJAdvisorFactoryTests { @Test void introductionOnTargetNotImplementingInterface() { NotLockable notLockableTarget = new NotLockable(); - assertThat(notLockableTarget instanceof Lockable).isFalse(); + assertThat(notLockableTarget).isNotInstanceOf(Lockable.class); NotLockable notLockable1 = createProxy(notLockableTarget, NotLockable.class, getAdvisorFactory().getAdvisors(aspectInstanceFactory(new MakeLockable(), "someBean"))); - assertThat(notLockable1 instanceof Lockable).isTrue(); + assertThat(notLockable1).isInstanceOf(Lockable.class); Lockable lockable = (Lockable) notLockable1; assertThat(lockable.locked()).isFalse(); lockable.lock(); @@ -331,7 +331,7 @@ abstract class AbstractAspectJAdvisorFactoryTests { NotLockable notLockable2Target = new NotLockable(); NotLockable notLockable2 = createProxy(notLockable2Target, NotLockable.class, getAdvisorFactory().getAdvisors(aspectInstanceFactory(new MakeLockable(), "someBean"))); - assertThat(notLockable2 instanceof Lockable).isTrue(); + assertThat(notLockable2).isInstanceOf(Lockable.class); Lockable lockable2 = (Lockable) notLockable2; assertThat(lockable2.locked()).isFalse(); notLockable2.setIntValue(1); @@ -345,7 +345,7 @@ abstract class AbstractAspectJAdvisorFactoryTests { assertThat(AopUtils.findAdvisorsThatCanApply( getAdvisorFactory().getAdvisors( aspectInstanceFactory(new MakeLockable(), "someBean")), - CannotBeUnlocked.class).isEmpty()).isTrue(); + CannotBeUnlocked.class)).isEmpty(); assertThat(AopUtils.findAdvisorsThatCanApply(getAdvisorFactory().getAdvisors( aspectInstanceFactory(new MakeLockable(),"someBean")), NotLockable.class)).hasSize(2); } @@ -373,7 +373,7 @@ abstract class AbstractAspectJAdvisorFactoryTests { AopUtils.findAdvisorsThatCanApply( getAdvisorFactory().getAdvisors(aspectInstanceFactory(new MakeLockable(), "someBean")), List.class)); - assertThat(proxy instanceof Lockable).as("Type pattern must have excluded mixin").isFalse(); + assertThat(proxy).as("Type pattern must have excluded mixin").isNotInstanceOf(Lockable.class); } @Test @@ -430,7 +430,7 @@ abstract class AbstractAspectJAdvisorFactoryTests { UnsupportedOperationException expectedException = new UnsupportedOperationException(); List advisors = getAdvisorFactory().getAdvisors( aspectInstanceFactory(new ExceptionThrowingAspect(expectedException), "someBean")); - assertThat(advisors.size()).as("One advice method was found").isEqualTo(1); + assertThat(advisors).as("One advice method was found").hasSize(1); ITestBean itb = createProxy(target, ITestBean.class, advisors); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(itb::getAge); } @@ -443,7 +443,7 @@ abstract class AbstractAspectJAdvisorFactoryTests { RemoteException expectedException = new RemoteException(); List advisors = getAdvisorFactory().getAdvisors( aspectInstanceFactory(new ExceptionThrowingAspect(expectedException), "someBean")); - assertThat(advisors.size()).as("One advice method was found").isEqualTo(1); + assertThat(advisors).as("One advice method was found").hasSize(1); ITestBean itb = createProxy(target, ITestBean.class, advisors); assertThatExceptionOfType(UndeclaredThrowableException.class) .isThrownBy(itb::getAge) @@ -456,7 +456,7 @@ abstract class AbstractAspectJAdvisorFactoryTests { TwoAdviceAspect twoAdviceAspect = new TwoAdviceAspect(); List advisors = getAdvisorFactory().getAdvisors( aspectInstanceFactory(twoAdviceAspect, "someBean")); - assertThat(advisors.size()).as("Two advice methods found").isEqualTo(2); + assertThat(advisors).as("Two advice methods found").hasSize(2); ITestBean itb = createProxy(target, ITestBean.class, advisors); itb.setName(""); assertThat(itb.getAge()).isEqualTo(0); 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 a7aa735995b..effbed9f8d9 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 @@ -197,11 +197,11 @@ public class ProxyFactoryTests { TestBeanSubclass raw = new TestBeanSubclass(); ProxyFactory factory = new ProxyFactory(raw); //System.out.println("Proxied interfaces are " + StringUtils.arrayToDelimitedString(factory.getProxiedInterfaces(), ",")); - assertThat(factory.getProxiedInterfaces().length).as("Found correct number of interfaces").isEqualTo(5); + assertThat(factory.getProxiedInterfaces()).as("Found correct number of interfaces").hasSize(5); ITestBean tb = (ITestBean) factory.getProxy(); assertThat(tb).as("Picked up secondary interface").isInstanceOf(IOther.class); raw.setAge(25); - assertThat(tb.getAge() == raw.getAge()).isTrue(); + assertThat(tb.getAge()).isEqualTo(raw.getAge()); long t = 555555L; TimestampIntroductionInterceptor ti = new TimestampIntroductionInterceptor(t); @@ -211,10 +211,10 @@ public class ProxyFactoryTests { factory.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class)); Class[] newProxiedInterfaces = factory.getProxiedInterfaces(); - assertThat(newProxiedInterfaces.length).as("Advisor proxies one more interface after introduction").isEqualTo(oldProxiedInterfaces.length + 1); + assertThat(newProxiedInterfaces).as("Advisor proxies one more interface after introduction").hasSize(oldProxiedInterfaces.length + 1); TimeStamped ts = (TimeStamped) factory.getProxy(); - assertThat(ts.getTimeStamp() == t).isTrue(); + assertThat(ts.getTimeStamp()).isEqualTo(t); // Shouldn't fail; ((IOther) ts).absquatulate(); } @@ -234,13 +234,13 @@ public class ProxyFactoryTests { factory.addAdvice(0, di); assertThat(factory.getProxy()).isInstanceOf(ITestBean.class); assertThat(factory.adviceIncluded(di)).isTrue(); - assertThat(!factory.adviceIncluded(diUnused)).isTrue(); - assertThat(factory.countAdvicesOfType(NopInterceptor.class) == 1).isTrue(); - assertThat(factory.countAdvicesOfType(MyInterceptor.class) == 0).isTrue(); + assertThat(factory.adviceIncluded(diUnused)).isFalse(); + assertThat(factory.countAdvicesOfType(NopInterceptor.class)).isEqualTo(1); + assertThat(factory.countAdvicesOfType(MyInterceptor.class)).isEqualTo(0); factory.addAdvice(0, diUnused); assertThat(factory.adviceIncluded(diUnused)).isTrue(); - assertThat(factory.countAdvicesOfType(NopInterceptor.class) == 2).isTrue(); + assertThat(factory.countAdvicesOfType(NopInterceptor.class)).isEqualTo(2); } @Test @@ -260,7 +260,8 @@ public class ProxyFactoryTests { public void testCanAddAndRemoveAspectInterfacesOnSingleton() { ProxyFactory config = new ProxyFactory(new TestBean()); - assertThat(config.getProxy() instanceof TimeStamped).as("Shouldn't implement TimeStamped before manipulation").isFalse(); + assertThat(config.getProxy()).as("Shouldn't implement TimeStamped before manipulation") + .isNotInstanceOf(TimeStamped.class); long time = 666L; TimestampIntroductionInterceptor ti = new TimestampIntroductionInterceptor(); @@ -270,26 +271,26 @@ public class ProxyFactoryTests { int oldCount = config.getAdvisors().length; config.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class)); - assertThat(config.getAdvisors().length == oldCount + 1).isTrue(); + assertThat(config.getAdvisors()).hasSize(oldCount + 1); TimeStamped ts = (TimeStamped) config.getProxy(); - assertThat(ts.getTimeStamp() == time).isTrue(); + assertThat(ts.getTimeStamp()).isEqualTo(time); // Can remove config.removeAdvice(ti); - assertThat(config.getAdvisors().length == oldCount).isTrue(); + assertThat(config.getAdvisors()).hasSize(oldCount); assertThatRuntimeException() .as("Existing object won't implement this interface any more") .isThrownBy(ts::getTimeStamp); // Existing reference will fail - assertThat(config.getProxy() instanceof TimeStamped).as("Should no longer implement TimeStamped").isFalse(); + assertThat(config.getProxy()).as("Should no longer implement TimeStamped").isNotInstanceOf(TimeStamped.class); // Now check non-effect of removing interceptor that isn't there config.removeAdvice(new DebugInterceptor()); - assertThat(config.getAdvisors().length == oldCount).isTrue(); + assertThat(config.getAdvisors()).hasSize(oldCount); ITestBean it = (ITestBean) ts; DebugInterceptor debugInterceptor = new DebugInterceptor(); @@ -299,7 +300,7 @@ public class ProxyFactoryTests { config.removeAdvice(debugInterceptor); it.getSpouse(); // not invoked again - assertThat(debugInterceptor.getCount() == 1).isTrue(); + assertThat(debugInterceptor.getCount()).isEqualTo(1); } @Test @@ -308,13 +309,13 @@ public class ProxyFactoryTests { pf.setTargetClass(ITestBean.class); Object proxy = pf.getProxy(); assertThat(AopUtils.isJdkDynamicProxy(proxy)).as("Proxy is a JDK proxy").isTrue(); - assertThat(proxy instanceof ITestBean).isTrue(); + assertThat(proxy).isInstanceOf(ITestBean.class); assertThat(AopProxyUtils.ultimateTargetClass(proxy)).isEqualTo(ITestBean.class); ProxyFactory pf2 = new ProxyFactory(proxy); Object proxy2 = pf2.getProxy(); assertThat(AopUtils.isJdkDynamicProxy(proxy2)).as("Proxy is a JDK proxy").isTrue(); - assertThat(proxy2 instanceof ITestBean).isTrue(); + assertThat(proxy2).isInstanceOf(ITestBean.class); assertThat(AopProxyUtils.ultimateTargetClass(proxy2)).isEqualTo(ITestBean.class); } @@ -324,14 +325,14 @@ public class ProxyFactoryTests { pf.setTargetClass(TestBean.class); Object proxy = pf.getProxy(); assertThat(AopUtils.isCglibProxy(proxy)).as("Proxy is a CGLIB proxy").isTrue(); - assertThat(proxy instanceof TestBean).isTrue(); + assertThat(proxy).isInstanceOf(TestBean.class); assertThat(AopProxyUtils.ultimateTargetClass(proxy)).isEqualTo(TestBean.class); ProxyFactory pf2 = new ProxyFactory(proxy); pf2.setProxyTargetClass(true); Object proxy2 = pf2.getProxy(); assertThat(AopUtils.isCglibProxy(proxy2)).as("Proxy is a CGLIB proxy").isTrue(); - assertThat(proxy2 instanceof TestBean).isTrue(); + assertThat(proxy2).isInstanceOf(TestBean.class); assertThat(AopProxyUtils.ultimateTargetClass(proxy2)).isEqualTo(TestBean.class); } @@ -341,8 +342,8 @@ public class ProxyFactoryTests { JFrame frame = new JFrame(); ProxyFactory proxyFactory = new ProxyFactory(frame); Object proxy = proxyFactory.getProxy(); - assertThat(proxy instanceof RootPaneContainer).isTrue(); - assertThat(proxy instanceof Accessible).isTrue(); + assertThat(proxy).isInstanceOf(RootPaneContainer.class); + assertThat(proxy).isInstanceOf(Accessible.class); } @Test diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/InvocationCheckExposedInvocationTestBean.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/InvocationCheckExposedInvocationTestBean.java index 05fdd00bf1f..28125273217 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/InvocationCheckExposedInvocationTestBean.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/InvocationCheckExposedInvocationTestBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ class InvocationCheckExposedInvocationTestBean extends ExposedInvocationTestBean @Override protected void assertions(MethodInvocation invocation) { - assertThat(invocation.getThis() == this).isTrue(); + 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-aop/src/test/java/org/springframework/aop/scope/ScopedProxyBeanRegistrationAotProcessorTests.java b/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyBeanRegistrationAotProcessorTests.java index 6760391892f..778ac1dd7b0 100644 --- a/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyBeanRegistrationAotProcessorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyBeanRegistrationAotProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -128,7 +128,7 @@ class ScopedProxyBeanRegistrationAotProcessorTests { this.beanFactory.registerBeanDefinition("test", scopedBean); compile((freshBeanFactory, compiled) -> { Object bean = freshBeanFactory.getBean("test"); - assertThat(bean).isNotNull().isInstanceOf(NumberHolder.class).isInstanceOf(AopInfrastructureBean.class); + assertThat(bean).isInstanceOf(NumberHolder.class).isInstanceOf(AopInfrastructureBean.class); }); } 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 87b408222c2..1306d6f6755 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -142,7 +142,7 @@ public class ComposablePointcutTests { pc1.intersection(GETTER_METHOD_MATCHER); assertThat(pc1.equals(pc2)).isFalse(); - assertThat(pc1.hashCode() == pc2.hashCode()).isFalse(); + assertThat(pc1.hashCode()).isNotEqualTo(pc2.hashCode()); pc2.intersection(GETTER_METHOD_MATCHER); 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 f86c6e7ca9f..3f4bd17c790 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,7 +97,7 @@ public class ControlFlowPointcutTests { 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(); + assertThat(new ControlFlowPointcut(One.class, "getAge").hashCode()).isNotEqualTo(new ControlFlowPointcut(One.class).hashCode()); } @Test 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 490eed0a382..86128dd4ca6 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 @@ -56,7 +56,7 @@ class DelegatingIntroductionInterceptorTests { @Test void testIntroductionInterceptorWithDelegation() throws Exception { TestBean raw = new TestBean(); - assertThat(! (raw instanceof TimeStamped)).isTrue(); + assertThat(raw).isNotInstanceOf(TimeStamped.class); ProxyFactory factory = new ProxyFactory(raw); TimeStamped ts = mock(); @@ -66,13 +66,13 @@ class DelegatingIntroductionInterceptorTests { factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts))); TimeStamped tsp = (TimeStamped) factory.getProxy(); - assertThat(tsp.getTimeStamp() == timestamp).isTrue(); + assertThat(tsp.getTimeStamp()).isEqualTo(timestamp); } @Test void testIntroductionInterceptorWithInterfaceHierarchy() throws Exception { TestBean raw = new TestBean(); - assertThat(! (raw instanceof SubTimeStamped)).isTrue(); + assertThat(raw).isNotInstanceOf(SubTimeStamped.class); ProxyFactory factory = new ProxyFactory(raw); SubTimeStamped ts = mock(); @@ -82,13 +82,13 @@ class DelegatingIntroductionInterceptorTests { factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), SubTimeStamped.class)); SubTimeStamped tsp = (SubTimeStamped) factory.getProxy(); - assertThat(tsp.getTimeStamp() == timestamp).isTrue(); + assertThat(tsp.getTimeStamp()).isEqualTo(timestamp); } @Test void testIntroductionInterceptorWithSuperInterface() throws Exception { TestBean raw = new TestBean(); - assertThat(! (raw instanceof TimeStamped)).isTrue(); + assertThat(raw).isNotInstanceOf(TimeStamped.class); ProxyFactory factory = new ProxyFactory(raw); SubTimeStamped ts = mock(); @@ -98,8 +98,8 @@ class DelegatingIntroductionInterceptorTests { factory.addAdvisor(0, new DefaultIntroductionAdvisor(new DelegatingIntroductionInterceptor(ts), TimeStamped.class)); TimeStamped tsp = (TimeStamped) factory.getProxy(); - assertThat(!(tsp instanceof SubTimeStamped)).isTrue(); - assertThat(tsp.getTimeStamp() == timestamp).isTrue(); + assertThat(tsp).isNotInstanceOf(SubTimeStamped.class); + assertThat(tsp.getTimeStamp()).isEqualTo(timestamp); } @Test @@ -125,7 +125,7 @@ class DelegatingIntroductionInterceptorTests { //assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1); TimeStamped ts = (TimeStamped) pf.getProxy(); - assertThat(ts.getTimeStamp() == t).isTrue(); + assertThat(ts.getTimeStamp()).isEqualTo(t); ((ITester) ts).foo(); ((ITestBean) ts).getAge(); @@ -160,10 +160,10 @@ class DelegatingIntroductionInterceptorTests { assertThat(ts).isInstanceOf(TimeStamped.class); // Shouldn't proxy framework interfaces - assertThat(!(ts instanceof MethodInterceptor)).isTrue(); - assertThat(!(ts instanceof IntroductionInterceptor)).isTrue(); + assertThat(ts).isNotInstanceOf(MethodInterceptor.class); + assertThat(ts).isNotInstanceOf(IntroductionInterceptor.class); - assertThat(ts.getTimeStamp() == t).isTrue(); + assertThat(ts.getTimeStamp()).isEqualTo(t); ((ITester) ts).foo(); ((ITestBean) ts).getAge(); @@ -174,14 +174,14 @@ class DelegatingIntroductionInterceptorTests { pf = new ProxyFactory(target); pf.addAdvisor(0, new DefaultIntroductionAdvisor(ii)); Object o = pf.getProxy(); - assertThat(!(o instanceof TimeStamped)).isTrue(); + assertThat(o).isNotInstanceOf(TimeStamped.class); } @SuppressWarnings("serial") @Test void testIntroductionInterceptorDoesntReplaceToString() throws Exception { TestBean raw = new TestBean(); - assertThat(! (raw instanceof TimeStamped)).isTrue(); + assertThat(raw).isNotInstanceOf(TimeStamped.class); ProxyFactory factory = new ProxyFactory(raw); TimeStamped ts = new SerializableTimeStamped(0); @@ -266,7 +266,7 @@ class DelegatingIntroductionInterceptorTests { TimeStamped ts = (TimeStamped) pf.getProxy(); // From introduction interceptor, not target - assertThat(ts.getTimeStamp() == t).isTrue(); + assertThat(ts.getTimeStamp()).isEqualTo(t); } 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 6c7928a83e6..3000734f113 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -129,7 +129,7 @@ public class NameMatchMethodPointcutTests { pc1.setMappedName(foo); assertThat(pc1.equals(pc2)).isFalse(); - assertThat(pc1.hashCode() != pc2.hashCode()).isTrue(); + assertThat(pc1.hashCode()).isNotEqualTo(pc2.hashCode()); pc2.setMappedName(foo); assertThat(pc2).isEqualTo(pc1); diff --git a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AbstractCacheAnnotationTests.java b/spring-aspects/src/test/java/org/springframework/cache/aspectj/AbstractCacheAnnotationTests.java index 81dcf6b1e22..b272e70e307 100644 --- a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AbstractCacheAnnotationTests.java +++ b/spring-aspects/src/test/java/org/springframework/cache/aspectj/AbstractCacheAnnotationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -543,7 +543,7 @@ public abstract class AbstractCacheAnnotationTests { Object r1 = service.multiConditionalCacheAndEvict(key); Object r3 = service.multiConditionalCacheAndEvict(key); - assertThat(!r1.equals(r3)).isTrue(); + assertThat(r1.equals(r3)).isFalse(); assertThat(primary.get(key)).isNull(); Object key2 = 3; 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 6c16c26364a..7d73e484b4c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -92,7 +92,7 @@ public class AspectJEnableCachingIsolatedTests { load(MultiCacheManagerConfig.class); } catch (IllegalStateException ex) { - assertThat(ex.getMessage().contains("bean of type CacheManager")).isTrue(); + assertThat(ex.getMessage()).contains("bean of type CacheManager"); } } @@ -107,7 +107,7 @@ public class AspectJEnableCachingIsolatedTests { load(MultiCacheManagerConfigurer.class, EnableCachingConfig.class); } catch (IllegalStateException ex) { - assertThat(ex.getMessage().contains("implementations of CachingConfigurer")).isTrue(); + assertThat(ex.getMessage()).contains("implementations of CachingConfigurer"); } } @@ -117,7 +117,7 @@ public class AspectJEnableCachingIsolatedTests { load(EmptyConfig.class); } catch (IllegalStateException ex) { - assertThat(ex.getMessage().contains("no bean of type CacheManager")).isTrue(); + assertThat(ex.getMessage()).contains("no bean of type CacheManager"); } } 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 43ccef4fd29..a629ce1fee4 100644 --- a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -205,11 +205,11 @@ abstract class AbstractPropertyAccessorTests { kerry.setSpouse(target); AbstractPropertyAccessor accessor = createAccessor(target); Integer KA = (Integer) accessor.getPropertyValue("spouse.age"); - assertThat(KA == 35).as("kerry is 35").isTrue(); + assertThat(KA).as("kerry is 35").isEqualTo(35); Integer RA = (Integer) accessor.getPropertyValue("spouse.spouse.age"); - assertThat(RA == 31).as("rod is 31, not" + RA).isTrue(); + assertThat(RA).as("rod is 31, not" + RA).isEqualTo(31); ITestBean spousesSpouse = (ITestBean) accessor.getPropertyValue("spouse.spouse"); - assertThat(target == spousesSpouse).as("spousesSpouse = initial point").isTrue(); + assertThat(target).as("spousesSpouse = initial point").isSameAs(spousesSpouse); } @Test @@ -242,7 +242,7 @@ abstract class AbstractPropertyAccessorTests { accessor.setConversionService(new DefaultConversionService()); accessor.setAutoGrowNestedPaths(true); accessor.setPropertyValue("listOfMaps[0]['luckyNumber']", "9"); - assertThat(target.listOfMaps.get(0).get("luckyNumber")).isEqualTo("9"); + assertThat(target.listOfMaps.get(0)).containsEntry("luckyNumber", "9"); } @Test @@ -298,13 +298,14 @@ abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("spouse.company", "Lewisham"); assertThat(kerry.getName()).as("kerry name is Kerry").isEqualTo("Kerry"); - assertThat(target.getSpouse() == kerry).as("nested set worked").isTrue(); + assertThat(target.getSpouse()).as("nested set worked").isSameAs(kerry); assertThat(kerry.getSpouse()).as("no back relation").isNull(); accessor.setPropertyValue(new PropertyValue("spouse.spouse", target)); - assertThat(kerry.getSpouse() == target).as("nested set worked").isTrue(); + assertThat(kerry.getSpouse()).as("nested set worked").isSameAs(target); AbstractPropertyAccessor kerryAccessor = createAccessor(kerry); - assertThat("Lewisham".equals(kerryAccessor.getPropertyValue("spouse.spouse.spouse.spouse.company"))).as("spouse.spouse.spouse.spouse.company=Lewisham").isTrue(); + assertThat(kerryAccessor.getPropertyValue("spouse.spouse.spouse.spouse.company")).as("spouse.spouse.spouse.spouse.company=Lewisham") + .isEqualTo("Lewisham"); } @Test @@ -315,13 +316,13 @@ abstract class AbstractPropertyAccessorTests { AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValue("spouse", kerry); - assertThat(target.getSpouse() == kerry).as("nested set worked").isTrue(); + assertThat(target.getSpouse()).as("nested set worked").isSameAs(kerry); assertThat(kerry.getSpouse()).as("no back relation").isNull(); accessor.setPropertyValue(new PropertyValue("spouse.spouse", target)); - assertThat(kerry.getSpouse() == target).as("nested set worked").isTrue(); - assertThat(kerry.getAge() == 0).as("kerry age not set").isTrue(); + assertThat(kerry.getSpouse()).as("nested set worked").isSameAs(target); + assertThat(kerry.getAge()).as("kerry age not set").isEqualTo(0); accessor.setPropertyValue(new PropertyValue("spouse.age", 35)); - assertThat(kerry.getAge() == 35).as("Set primitive on spouse").isTrue(); + assertThat(kerry.getAge()).as("Set primitive on spouse").isEqualTo(35); assertThat(accessor.getPropertyValue("spouse")).isEqualTo(kerry); assertThat(accessor.getPropertyValue("spouse.spouse")).isEqualTo(target); @@ -359,7 +360,7 @@ abstract class AbstractPropertyAccessorTests { accessor.getPropertyValue("spouse.bla"); } catch (NotReadablePropertyException ex) { - assertThat(ex.getMessage().contains(TestBean.class.getName())).isTrue(); + assertThat(ex.getMessage()).contains(TestBean.class.getName()); } } @@ -442,12 +443,12 @@ abstract class AbstractPropertyAccessorTests { target.setAge(age); target.setName(name); AbstractPropertyAccessor accessor = createAccessor(target); - assertThat(target.getAge() == age).as("age is OK").isTrue(); - assertThat(name.equals(target.getName())).as("name is OK").isTrue(); + assertThat(target.getAge()).as("age is OK").isEqualTo(age); + assertThat(name).as("name is OK").isEqualTo(target.getName()); accessor.setPropertyValues(new MutablePropertyValues()); // Check its unchanged - assertThat(target.getAge() == age).as("age is OK").isTrue(); - assertThat(name.equals(target.getName())).as("name is OK").isTrue(); + assertThat(target.getAge()).as("age is OK").isEqualTo(age); + assertThat(name).as("name is OK").isEqualTo(target.getName()); } @@ -463,9 +464,9 @@ abstract class AbstractPropertyAccessorTests { pvs.addPropertyValue(new PropertyValue("name", newName)); pvs.addPropertyValue(new PropertyValue("touchy", newTouchy)); accessor.setPropertyValues(pvs); - 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(); + assertThat(target.getName()).as("Name property should have changed").isEqualTo(newName); + assertThat(target.getTouchy()).as("Touchy property should have changed").isEqualTo(newTouchy); + assertThat(target.getAge()).as("Age property should have changed").isEqualTo(newAge); } @Test @@ -480,7 +481,7 @@ abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue(new PropertyValue("touchy", newTouchy)); assertThat(target.getName()).as("Name property should have changed").isEqualTo(newName); assertThat(target.getTouchy()).as("Touchy property should have changed").isEqualTo(newTouchy); - assertThat(target.getAge() == newAge).as("Age property should have changed").isTrue(); + assertThat(target.getAge()).as("Age property should have changed").isEqualTo(newAge); } @Test @@ -559,11 +560,11 @@ abstract class AbstractPropertyAccessorTests { } }); accessor.setPropertyValue("name", new String[] {}); - assertThat(target.getName()).isEqualTo(""); + assertThat(target.getName()).isEmpty(); accessor.setPropertyValue("name", new String[] {"a1", "b2"}); assertThat(target.getName()).isEqualTo("a1-b2"); accessor.setPropertyValue("name", null); - assertThat(target.getName()).isEqualTo(""); + assertThat(target.getName()).isEmpty(); } @Test @@ -577,7 +578,7 @@ abstract class AbstractPropertyAccessorTests { accessor.setPropertyValue("bool2", "false"); assertThat(Boolean.FALSE.equals(accessor.getPropertyValue("bool2"))).as("Correct bool2 value").isTrue(); - assertThat(!target.getBool2()).as("Correct bool2 value").isTrue(); + assertThat(target.getBool2()).as("Correct bool2 value").isFalse(); } @Test @@ -729,7 +730,7 @@ abstract class AbstractPropertyAccessorTests { String freedomVal = target.properties.getProperty("freedom"); String peaceVal = target.properties.getProperty("peace"); assertThat(peaceVal).as("peace==war").isEqualTo("war"); - assertThat(freedomVal.equals("slavery")).as("Freedom==slavery").isTrue(); + assertThat(freedomVal).as("Freedom==slavery").isEqualTo("slavery"); } @Test @@ -1344,7 +1345,7 @@ abstract class AbstractPropertyAccessorTests { pvs.addPropertyValue(new PropertyValue("more.garbage", new Object())); AbstractPropertyAccessor accessor = createAccessor(target); accessor.setPropertyValues(pvs, true); - assertThat(target.getName().equals("rod")).as("Set valid and ignored invalid").isTrue(); + assertThat(target.getName()).as("Set valid and ignored invalid").isEqualTo("rod"); assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() -> accessor.setPropertyValues(pvs, false)); // Don't ignore: should fail } 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 7569be3d881..43140febc59 100644 --- a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyValuesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyValuesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ public abstract class AbstractPropertyValuesTests { * Must contain: forname=Tony surname=Blair age=50 */ protected void doTestTony(PropertyValues pvs) { - assertThat(pvs.getPropertyValues().length == 3).as("Contains 3").isTrue(); + assertThat(pvs.getPropertyValues()).as("Contains 3").hasSize(3); assertThat(pvs.contains("forname")).as("Contains forname").isTrue(); assertThat(pvs.contains("surname")).as("Contains surname").isTrue(); assertThat(pvs.contains("age")).as("Contains age").isTrue(); @@ -45,13 +45,13 @@ public abstract class AbstractPropertyValuesTests { m.put("age", "50"); for (PropertyValue element : ps) { Object val = m.get(element.getName()); - assertThat(val != null).as("Can't have unexpected value").isTrue(); + assertThat(val).as("Can't have unexpected value").isNotNull(); boolean condition = val instanceof String; assertThat(condition).as("Val i string").isTrue(); assertThat(val.equals(element.getValue())).as("val matches expected").isTrue(); m.remove(element.getName()); } - assertThat(m.size() == 0).as("Map size is 0").isTrue(); + assertThat(m).as("Map size is 0").isEmpty(); } } 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 6be56ed7ecf..0d75f7c3718 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -135,7 +135,7 @@ class BeanUtilsTests { PropertyDescriptor[] actual = Introspector.getBeanInfo(TestBean.class).getPropertyDescriptors(); PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(TestBean.class); assertThat(descriptors).as("Descriptors should not be null").isNotNull(); - assertThat(descriptors.length).as("Invalid number of descriptors returned").isEqualTo(actual.length); + assertThat(descriptors).as("Invalid number of descriptors returned").hasSameSizeAs(actual); } @Test @@ -161,13 +161,13 @@ class BeanUtilsTests { tb.setAge(32); tb.setTouchy("touchy"); TestBean tb2 = new TestBean(); - assertThat(tb2.getName() == null).as("Name empty").isTrue(); - assertThat(tb2.getAge() == 0).as("Age empty").isTrue(); - assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue(); + assertThat(tb2.getName()).as("Name empty").isNull(); + assertThat(tb2.getAge()).as("Age empty").isEqualTo(0); + assertThat(tb2.getTouchy()).as("Touchy empty").isNull(); BeanUtils.copyProperties(tb, tb2); - 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(); + assertThat(tb2.getName()).as("Name copied").isEqualTo(tb.getName()); + assertThat(tb2.getAge()).as("Age copied").isEqualTo(tb.getAge()); + assertThat(tb2.getTouchy()).as("Touchy copied").isEqualTo(tb.getTouchy()); } @Test @@ -177,13 +177,13 @@ class BeanUtilsTests { tb.setAge(32); tb.setTouchy("touchy"); TestBean tb2 = new TestBean(); - assertThat(tb2.getName() == null).as("Name empty").isTrue(); - assertThat(tb2.getAge() == 0).as("Age empty").isTrue(); - assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue(); + assertThat(tb2.getName()).as("Name empty").isNull(); + assertThat(tb2.getAge()).as("Age empty").isEqualTo(0); + assertThat(tb2.getTouchy()).as("Touchy empty").isNull(); BeanUtils.copyProperties(tb, tb2); - 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(); + assertThat(tb2.getName()).as("Name copied").isEqualTo(tb.getName()); + assertThat(tb2.getAge()).as("Age copied").isEqualTo(tb.getAge()); + assertThat(tb2.getTouchy()).as("Touchy copied").isEqualTo(tb.getTouchy()); } @Test @@ -193,13 +193,13 @@ class BeanUtilsTests { tb.setAge(32); tb.setTouchy("touchy"); DerivedTestBean tb2 = new DerivedTestBean(); - assertThat(tb2.getName() == null).as("Name empty").isTrue(); - assertThat(tb2.getAge() == 0).as("Age empty").isTrue(); - assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue(); + assertThat(tb2.getName()).as("Name empty").isNull(); + assertThat(tb2.getAge()).as("Age empty").isEqualTo(0); + assertThat(tb2.getTouchy()).as("Touchy empty").isNull(); BeanUtils.copyProperties(tb, tb2); - 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(); + assertThat(tb2.getName()).as("Name copied").isEqualTo(tb.getName()); + assertThat(tb2.getAge()).as("Age copied").isEqualTo(tb.getAge()); + assertThat(tb2.getTouchy()).as("Touchy copied").isEqualTo(tb.getTouchy()); } /** @@ -342,37 +342,37 @@ class BeanUtilsTests { @Test void copyPropertiesWithEditable() throws Exception { TestBean tb = new TestBean(); - assertThat(tb.getName() == null).as("Name empty").isTrue(); + assertThat(tb.getName()).as("Name empty").isNull(); tb.setAge(32); tb.setTouchy("bla"); TestBean tb2 = new TestBean(); tb2.setName("rod"); - assertThat(tb2.getAge() == 0).as("Age empty").isTrue(); - assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue(); + assertThat(tb2.getAge()).as("Age empty").isEqualTo(0); + assertThat(tb2.getTouchy()).as("Touchy empty").isNull(); // "touchy" should not be copied: it's not defined in ITestBean BeanUtils.copyProperties(tb, tb2, ITestBean.class); - 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(); + assertThat(tb2.getName()).as("Name copied").isNull(); + assertThat(tb2.getAge()).as("Age copied").isEqualTo(32); + assertThat(tb2.getTouchy()).as("Touchy still empty").isNull(); } @Test void copyPropertiesWithIgnore() throws Exception { TestBean tb = new TestBean(); - assertThat(tb.getName() == null).as("Name empty").isTrue(); + assertThat(tb.getName()).as("Name empty").isNull(); tb.setAge(32); tb.setTouchy("bla"); TestBean tb2 = new TestBean(); tb2.setName("rod"); - assertThat(tb2.getAge() == 0).as("Age empty").isTrue(); - assertThat(tb2.getTouchy() == null).as("Touchy empty").isTrue(); + assertThat(tb2.getAge()).as("Age empty").isEqualTo(0); + assertThat(tb2.getTouchy()).as("Touchy empty").isNull(); // "spouse", "touchy", "age" should not be copied BeanUtils.copyProperties(tb, tb2, "spouse", "touchy", "age"); - 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(); + assertThat(tb2.getName()).as("Name copied").isNull(); + assertThat(tb2.getAge()).as("Age still empty").isEqualTo(0); + assertThat(tb2.getTouchy()).as("Touchy still empty").isNull(); } @Test @@ -381,7 +381,7 @@ class BeanUtilsTests { source.setName("name"); TestBean target = new TestBean(); BeanUtils.copyProperties(source, target, "specialProperty"); - assertThat("name").isEqualTo(target.getName()); + assertThat(target.getName()).isEqualTo("name"); } @Test 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 a24a9bc88a3..57820c1e8fd 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,15 +90,15 @@ public class BeanWrapperAutoGrowingTests { @Test public void getPropertyValueAutoGrow2dArray() { - assertNotNull(wrapper.getPropertyValue("multiArray[0][0]")); + assertThat(wrapper.getPropertyValue("multiArray[0][0]")).isNotNull(); assertThat(bean.getMultiArray()[0]).hasSize(1); assertThat(bean.getMultiArray()[0][0]).isInstanceOf(Bean.class); } @Test public void getPropertyValueAutoGrow3dArray() { - assertNotNull(wrapper.getPropertyValue("threeDimensionalArray[1][2][3]")); - assertThat(bean.getThreeDimensionalArray()[1].length).isEqualTo(3); + assertThat(wrapper.getPropertyValue("threeDimensionalArray[1][2][3]")).isNotNull(); + assertThat(bean.getThreeDimensionalArray()[1]).hasNumberOfRows(3); assertThat(bean.getThreeDimensionalArray()[1][2][3]).isInstanceOf(Bean.class); } 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 16bc4de0e2a..d143fed51c9 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -161,8 +161,8 @@ class BeanWrapperGenericsTests { value2.add(Boolean.TRUE); input.put("2", value2); bw.setPropertyValue("collectionMap", input); - assertThat(gb.getCollectionMap().get(1) instanceof HashSet).isTrue(); - assertThat(gb.getCollectionMap().get(2) instanceof ArrayList).isTrue(); + assertThat(gb.getCollectionMap().get(1)).isInstanceOf(HashSet.class); + assertThat(gb.getCollectionMap().get(2)).isInstanceOf(ArrayList.class); } @Test @@ -174,7 +174,7 @@ class BeanWrapperGenericsTests { HashSet value1 = new HashSet<>(); value1.add(1); bw.setPropertyValue("collectionMap[1]", value1); - assertThat(gb.getCollectionMap().get(1) instanceof HashSet).isTrue(); + assertThat(gb.getCollectionMap().get(1)).isInstanceOf(HashSet.class); } @Test @@ -320,7 +320,7 @@ class BeanWrapperGenericsTests { bw.setPropertyValue("mapOfInteger", map); Object obj = gb.getMapOfInteger().get("testKey"); - assertThat(obj instanceof Integer).isTrue(); + assertThat(obj).isInstanceOf(Integer.class); } @Test @@ -334,7 +334,7 @@ class BeanWrapperGenericsTests { bw.setPropertyValue("mapOfListOfInteger", map); Object obj = gb.getMapOfListOfInteger().get("testKey").get(0); - assertThat(obj instanceof Integer).isTrue(); + assertThat(obj).isInstanceOf(Integer.class); assertThat(((Integer) obj).intValue()).isEqualTo(1); } @@ -350,7 +350,7 @@ class BeanWrapperGenericsTests { bw.setPropertyValue("listOfMapOfInteger", list); Object obj = gb.getListOfMapOfInteger().get(0).get("testKey"); - assertThat(obj instanceof Integer).isTrue(); + assertThat(obj).isInstanceOf(Integer.class); assertThat(((Integer) obj).intValue()).isEqualTo(5); } @@ -365,7 +365,7 @@ class BeanWrapperGenericsTests { bw.setPropertyValue("mapOfListOfListOfInteger", map); Object obj = gb.getMapOfListOfListOfInteger().get("testKey").get(0).get(0); - assertThat(obj instanceof Integer).isTrue(); + assertThat(obj).isInstanceOf(Integer.class); assertThat(((Integer) obj).intValue()).isEqualTo(1); } 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 c933699da38..ccaf690a051 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -246,16 +246,16 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests { accessor.setPropertyValue("object", tb); assertThat(target.value).isSameAs(tb); - assertThat(target.getObject().get()).isSameAs(tb); - assertThat(((Optional) accessor.getPropertyValue("object")).get()).isSameAs(tb); + assertThat(target.getObject()).containsSame(tb); + assertThat(((Optional) accessor.getPropertyValue("object"))).containsSame(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"); assertThat(target.value).isSameAs(tb); - assertThat(target.getObject().get()).isSameAs(tb); - assertThat(((Optional) accessor.getPropertyValue("object")).get()).isSameAs(tb); + assertThat(target.getObject()).containsSame(tb); + assertThat(((Optional) accessor.getPropertyValue("object"))).containsSame(tb); assertThat(target.value.getName()).isEqualTo("y"); assertThat(target.getObject().get().getName()).isEqualTo("y"); assertThat(accessor.getPropertyValue("object.name")).isEqualTo("y"); 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 a8ea5fae9ea..72b585bcafd 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -585,7 +585,7 @@ class ExtendedBeanInfoTests { assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); - assertThat(ebi.getPropertyDescriptors()).hasSize(bi.getPropertyDescriptors().length); + assertThat(ebi.getPropertyDescriptors()).hasSameSizeAs(bi.getPropertyDescriptors()); } @Test @@ -711,7 +711,7 @@ class ExtendedBeanInfoTests { BeanInfo bi = Introspector.getBeanInfo(TestBean.class); BeanInfo ebi = new ExtendedBeanInfo(bi); - assertThat(ebi.getPropertyDescriptors()).hasSize(bi.getPropertyDescriptors().length); + assertThat(ebi.getPropertyDescriptors()).hasSameSizeAs(bi.getPropertyDescriptors()); } @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 027811ed6a4..037933405de 100644 --- a/spring-beans/src/test/java/org/springframework/beans/MutablePropertyValuesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/MutablePropertyValuesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,7 +70,7 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests { pvs.addPropertyValue(new PropertyValue("age", "50")); MutablePropertyValues pvs2 = pvs; PropertyValues changes = pvs2.changesSince(pvs); - assertThat(changes.getPropertyValues().length == 0).as("changes are empty").isTrue(); + assertThat(changes.getPropertyValues().length).as("changes are empty").isEqualTo(0); } @Test @@ -82,26 +82,28 @@ public class MutablePropertyValuesTests extends AbstractPropertyValuesTests { MutablePropertyValues pvs2 = new MutablePropertyValues(pvs); PropertyValues changes = pvs2.changesSince(pvs); - assertThat(changes.getPropertyValues().length == 0).as("changes are empty, not of length " + changes.getPropertyValues().length).isTrue(); + assertThat(changes.getPropertyValues().length).as("changes are empty, not of length " + changes.getPropertyValues().length) + .isEqualTo(0); pvs2.addPropertyValue(new PropertyValue("forname", "Gordon")); changes = pvs2.changesSince(pvs); assertThat(changes.getPropertyValues().length).as("1 change").isEqualTo(1); PropertyValue fn = changes.getPropertyValue("forname"); - assertThat(fn != null).as("change is forname").isTrue(); + assertThat(fn).as("change is forname").isNotNull(); assertThat(fn.getValue().equals("Gordon")).as("new value is gordon").isTrue(); MutablePropertyValues pvs3 = new MutablePropertyValues(pvs); changes = pvs3.changesSince(pvs); - assertThat(changes.getPropertyValues().length == 0).as("changes are empty, not of length " + changes.getPropertyValues().length).isTrue(); + assertThat(changes.getPropertyValues().length).as("changes are empty, not of length " + changes.getPropertyValues().length) + .isEqualTo(0); // add new pvs3.addPropertyValue(new PropertyValue("foo", "bar")); pvs3.addPropertyValue(new PropertyValue("fi", "fum")); changes = pvs3.changesSince(pvs); - assertThat(changes.getPropertyValues().length == 2).as("2 change").isTrue(); + assertThat(changes.getPropertyValues().length).as("2 change").isEqualTo(2); fn = changes.getPropertyValue("foo"); - assertThat(fn != null).as("change in foo").isTrue(); + assertThat(fn).as("change in foo").isNotNull(); assertThat(fn.getValue().equals("bar")).as("new value is bar").isTrue(); } 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 4613f472624..2afa65d99d0 100644 --- a/spring-beans/src/test/java/org/springframework/beans/PropertyAccessorUtilsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/PropertyAccessorUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,8 @@ public class PropertyAccessorUtilsTests { @Test public void getPropertyName() { - assertThat(PropertyAccessorUtils.getPropertyName("")).isEqualTo(""); - assertThat(PropertyAccessorUtils.getPropertyName("[user]")).isEqualTo(""); + assertThat(PropertyAccessorUtils.getPropertyName("")).isEmpty(); + assertThat(PropertyAccessorUtils.getPropertyName("[user]")).isEmpty(); assertThat(PropertyAccessorUtils.getPropertyName("user")).isEqualTo("user"); } @@ -69,7 +69,7 @@ public class PropertyAccessorUtilsTests { @Test public void canonicalPropertyName() { - assertThat(PropertyAccessorUtils.canonicalPropertyName(null)).isEqualTo(""); + assertThat(PropertyAccessorUtils.canonicalPropertyName(null)).isEmpty(); assertThat(PropertyAccessorUtils.canonicalPropertyName("map")).isEqualTo("map"); assertThat(PropertyAccessorUtils.canonicalPropertyName("map[key1]")).isEqualTo("map[key1]"); assertThat(PropertyAccessorUtils.canonicalPropertyName("map['key1']")).isEqualTo("map[key1]"); 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 a19e9cda260..175065ce389 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,7 +85,7 @@ public class BeanFactoryUtilsTests { StaticListableBeanFactory lbf = new StaticListableBeanFactory(); lbf.addBean("t1", new TestBean()); lbf.addBean("t2", new TestBean()); - assertThat(BeanFactoryUtils.countBeansIncludingAncestors(lbf) == 2).isTrue(); + assertThat(BeanFactoryUtils.countBeansIncludingAncestors(lbf)).isEqualTo(2); } /** @@ -94,9 +94,10 @@ public class BeanFactoryUtilsTests { @Test public void testHierarchicalCountBeansWithOverride() { // Leaf count - assertThat(this.listableBeanFactory.getBeanDefinitionCount() == 1).isTrue(); + assertThat(this.listableBeanFactory.getBeanDefinitionCount()).isEqualTo(1); // Count minus duplicate - assertThat(BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory) == 8).as("Should count 8 beans, not " + BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory)).isTrue(); + assertThat(BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory)).as("Should count 8 beans, not " + BeanFactoryUtils.countBeansIncludingAncestors(this.listableBeanFactory)) + .isEqualTo(8); } @Test @@ -113,7 +114,7 @@ public class BeanFactoryUtilsTests { assertThat(names).hasSize(1); assertThat(names.contains("indexedBean")).isTrue(); // Distinguish from default ListableBeanFactory behavior - assertThat(listableBeanFactory.getBeanNamesForType(IndexedTestBean.class).length == 0).isTrue(); + assertThat(listableBeanFactory.getBeanNamesForType(IndexedTestBean.class)).isEmpty(); } @Test @@ -288,7 +289,7 @@ public class BeanFactoryUtilsTests { assertThat(names).hasSize(1); assertThat(names.contains("annotatedBean")).isTrue(); // Distinguish from default ListableBeanFactory behavior - assertThat(listableBeanFactory.getBeanNamesForAnnotation(TestAnnotation.class).length == 0).isTrue(); + assertThat(listableBeanFactory.getBeanNamesForAnnotation(TestAnnotation.class)).isEmpty(); } @Test 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 e33909e54e0..78f76e707aa 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 @@ -137,7 +137,7 @@ class DefaultListableBeanFactoryTests { KnowsIfInstantiated.clearInstantiationRecord(); Properties p = new Properties(); p.setProperty("x1.(class)", KnowsIfInstantiated.class.getName()); - assertThat(!KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isTrue(); + assertThat(KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isFalse(); registerBeanDefinitions(p); lbf.preInstantiateSingletons(); assertThat(KnowsIfInstantiated.wasInstantiated()).as("singleton was instantiated").isTrue(); @@ -149,12 +149,12 @@ class DefaultListableBeanFactoryTests { Properties p = new Properties(); p.setProperty("x1.(class)", KnowsIfInstantiated.class.getName()); p.setProperty("x1.(lazy-init)", "true"); - assertThat(!KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isTrue(); + assertThat(KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isFalse(); registerBeanDefinitions(p); - assertThat(!KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isTrue(); + assertThat(KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isFalse(); lbf.preInstantiateSingletons(); - assertThat(!KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isTrue(); + assertThat(KnowsIfInstantiated.wasInstantiated()).as("singleton not instantiated").isFalse(); lbf.getBean("x1"); assertThat(KnowsIfInstantiated.wasInstantiated()).as("singleton was instantiated").isTrue(); } @@ -166,13 +166,13 @@ class DefaultListableBeanFactoryTests { // Reset static state DummyFactory.reset(); p.setProperty("x1.singleton", "false"); - assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); + assertThat(DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isFalse(); registerBeanDefinitions(p); - assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); + assertThat(DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isFalse(); assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); lbf.preInstantiateSingletons(); - assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); + assertThat(DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isFalse(); lbf.getBean("x1"); assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); assertThat(lbf.containsBean("x1")).isTrue(); @@ -190,7 +190,7 @@ class DefaultListableBeanFactoryTests { p.setProperty("x1.singleton", "false"); registerBeanDefinitions(p); - assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); + assertThat(DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isFalse(); assertBeanNamesForType(TestBean.class, false, false); assertThat(lbf.getBeanNamesForAnnotation(SuppressWarnings.class)).isEmpty(); @@ -209,7 +209,7 @@ class DefaultListableBeanFactoryTests { 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(); + assertThat(DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isFalse(); } @Test @@ -222,7 +222,7 @@ class DefaultListableBeanFactoryTests { p.setProperty("x1.singleton", "true"); registerBeanDefinitions(p); - assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); + assertThat(DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isFalse(); assertBeanNamesForType(TestBean.class, false, false); assertThat(lbf.getBeanNamesForAnnotation(SuppressWarnings.class)).isEmpty(); @@ -241,7 +241,7 @@ class DefaultListableBeanFactoryTests { 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(); + assertThat(DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isFalse(); } @Test @@ -253,7 +253,7 @@ class DefaultListableBeanFactoryTests { p.setProperty("x1.singleton", "false"); registerBeanDefinitions(p); - assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); + assertThat(DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isFalse(); assertBeanNamesForType(TestBean.class, false, false); assertThat(lbf.getBeanNamesForAnnotation(SuppressWarnings.class)).isEmpty(); @@ -272,7 +272,7 @@ class DefaultListableBeanFactoryTests { 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(); + assertThat(DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isFalse(); } @Test @@ -303,7 +303,7 @@ class DefaultListableBeanFactoryTests { 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(); + assertThat(DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isFalse(); lbf.registerAlias("x1", "x2"); assertThat(lbf.containsBean("x2")).isTrue(); @@ -449,9 +449,9 @@ class DefaultListableBeanFactoryTests { @Test void empty() { - 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(); + assertThat(lbf.getBeanDefinitionNames()).as("No beans defined --> array != null").isNotNull(); + assertThat(lbf.getBeanDefinitionNames()).as("No beans defined after no arg constructor").isEmpty(); + assertThat(lbf.getBeanDefinitionCount()).as("No beans defined after no arg constructor").isEqualTo(0); } @Test @@ -459,7 +459,7 @@ class DefaultListableBeanFactoryTests { Properties p = new Properties(); registerBeanDefinitions(p); - assertThat(lbf.getBeanDefinitionCount() == 0).as("No beans defined after ignorable invalid").isTrue(); + assertThat(lbf.getBeanDefinitionCount()).as("No beans defined after ignorable invalid").isEqualTo(0); } @Test @@ -469,7 +469,7 @@ class DefaultListableBeanFactoryTests { p.setProperty("qwert", "er"); registerBeanDefinitions(p, "test"); - assertThat(lbf.getBeanDefinitionCount() == 0).as("No beans defined after harmless ignorable rubbish").isTrue(); + assertThat(lbf.getBeanDefinitionCount()).as("No beans defined after harmless ignorable rubbish").isEqualTo(0); } @Test @@ -480,7 +480,7 @@ class DefaultListableBeanFactoryTests { p.setProperty("test.age", "48"); int count = registerBeanDefinitions(p); - assertThat(count == 1).as("1 beans registered, not " + count).isTrue(); + assertThat(count).as("1 beans registered, not " + count).isEqualTo(1); testPropertiesPopulation(lbf); } @@ -493,7 +493,7 @@ class DefaultListableBeanFactoryTests { p.setProperty(PREFIX + "test.age", "0x30"); int count = registerBeanDefinitions(p, PREFIX); - assertThat(count == 1).as("1 beans registered, not " + count).isTrue(); + assertThat(count).as("1 beans registered, not " + count).isEqualTo(1); testPropertiesPopulation(lbf); } @@ -524,13 +524,13 @@ class DefaultListableBeanFactoryTests { p.setProperty(PREFIX + "kerry.spouse(ref)", "rod"); int count = registerBeanDefinitions(p, PREFIX); - assertThat(count == 2).as("2 beans registered, not " + count).isTrue(); + assertThat(count).as("2 beans registered, not " + count).isEqualTo(2); TestBean kerry = lbf.getBean("kerry", TestBean.class); - assertThat("Kerry".equals(kerry.getName())).as("Kerry name is Kerry").isTrue(); + assertThat(kerry.getName()).as("Kerry name is Kerry").isEqualTo("Kerry"); ITestBean spouse = kerry.getSpouse(); - assertThat(spouse != null).as("Kerry spouse is non null").isTrue(); - assertThat("Rod".equals(spouse.getName())).as("Kerry spouse name is Rod").isTrue(); + assertThat(spouse).as("Kerry spouse is non null").isNotNull(); + assertThat(spouse.getName()).as("Kerry spouse name is Rod").isEqualTo("Rod"); } @Test @@ -541,7 +541,7 @@ class DefaultListableBeanFactoryTests { p.setProperty("tb.someMap[my.key]", "my.value"); int count = registerBeanDefinitions(p); - assertThat(count == 1).as("1 beans registered, not " + count).isTrue(); + assertThat(count).as("1 beans registered, not " + count).isEqualTo(1); assertThat(lbf.getBeanDefinitionCount()).isEqualTo(1); TestBean tb = lbf.getBean("tb", TestBean.class); @@ -682,8 +682,8 @@ class DefaultListableBeanFactoryTests { registerBeanDefinitions(p); TestBean kerry1 = (TestBean) lbf.getBean("kerry"); TestBean kerry2 = (TestBean) lbf.getBean("kerry"); - assertThat(kerry1 != null).as("Non null").isTrue(); - assertThat(kerry1 == kerry2).as("Singletons equal").isTrue(); + assertThat(kerry1).as("Non null").isNotNull(); + assertThat(kerry1).as("Singletons equal").isSameAs(kerry2); p = new Properties(); p.setProperty("kerry.(class)", TestBean.class.getName()); @@ -692,8 +692,8 @@ class DefaultListableBeanFactoryTests { registerBeanDefinitions(p); kerry1 = (TestBean) lbf.getBean("kerry"); kerry2 = (TestBean) lbf.getBean("kerry"); - assertThat(kerry1 != null).as("Non null").isTrue(); - assertThat(kerry1 != kerry2).as("Prototypes NOT equal").isTrue(); + assertThat(kerry1).as("Non null").isNotNull(); + assertThat(kerry1).as("Prototypes NOT equal").isNotSameAs(kerry2); p = new Properties(); p.setProperty("kerry.(class)", TestBean.class.getName()); @@ -702,8 +702,8 @@ class DefaultListableBeanFactoryTests { registerBeanDefinitions(p); kerry1 = (TestBean) lbf.getBean("kerry"); kerry2 = (TestBean) lbf.getBean("kerry"); - assertThat(kerry1 != null).as("Non null").isTrue(); - assertThat(kerry1 == kerry2).as("Specified singletons equal").isTrue(); + assertThat(kerry1).as("Non null").isNotNull(); + assertThat(kerry1).as("Specified singletons equal").isSameAs(kerry2); } @Test @@ -737,7 +737,7 @@ class DefaultListableBeanFactoryTests { TestBean kerry2 = (TestBean) lbf.getBean("kerry"); assertThat(kerry1.getName()).isEqualTo("kerry"); assertThat(kerry1).as("Non null").isNotNull(); - assertThat(kerry1 == kerry2).as("Singletons equal").isTrue(); + assertThat(kerry1).as("Singletons equal").isSameAs(kerry2); p = new Properties(); p.setProperty("wife.(class)", TestBean.class.getName()); @@ -750,8 +750,8 @@ class DefaultListableBeanFactoryTests { assertThat(lbf.isSingleton("kerry")).isFalse(); kerry1 = (TestBean) lbf.getBean("kerry"); kerry2 = (TestBean) lbf.getBean("kerry"); - assertThat(kerry1 != null).as("Non null").isTrue(); - assertThat(kerry1 != kerry2).as("Prototypes NOT equal").isTrue(); + assertThat(kerry1).as("Non null").isNotNull(); + assertThat(kerry1).as("Prototypes NOT equal").isNotSameAs(kerry2); p = new Properties(); p.setProperty("kerry.(class)", TestBean.class.getName()); @@ -760,8 +760,8 @@ class DefaultListableBeanFactoryTests { registerBeanDefinitions(p); kerry1 = (TestBean) lbf.getBean("kerry"); kerry2 = (TestBean) lbf.getBean("kerry"); - assertThat(kerry1 != null).as("Non null").isTrue(); - assertThat(kerry1 == kerry2).as("Specified singletons equal").isTrue(); + assertThat(kerry1).as("Non null").isNotNull(); + assertThat(kerry1).as("Specified singletons equal").isSameAs(kerry2); } @Test @@ -972,7 +972,7 @@ class DefaultListableBeanFactoryTests { TestBean k = (TestBean) lbf.getBean("k"); TestBean r = (TestBean) lbf.getBean("r"); - assertThat(k.getSpouse() == r).isTrue(); + assertThat(k.getSpouse()).isSameAs(r); } @Test @@ -984,7 +984,7 @@ class DefaultListableBeanFactoryTests { registerBeanDefinitions(p); TestBean r = (TestBean) lbf.getBean("r"); - assertThat(r.getName().equals(name)).isTrue(); + assertThat(r.getName()).isEqualTo(name); } @Test @@ -1000,7 +1000,7 @@ class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("testBean", bd); TestBean testBean = (TestBean) lbf.getBean("testBean"); - assertThat(testBean.getMyFloat() == 1.1f).isTrue(); + assertThat(testBean.getMyFloat()).isEqualTo(1.1f); } @Test @@ -1024,7 +1024,7 @@ class DefaultListableBeanFactoryTests { lbf.registerBeanDefinition("testBean", bd); TestBean testBean = (TestBean) lbf.getBean("testBean"); - assertThat(testBean.getMyFloat() == 1.1f).isTrue(); + assertThat(testBean.getMyFloat()).isEqualTo(1.1f); } @Test @@ -1041,7 +1041,7 @@ class DefaultListableBeanFactoryTests { lbf.registerSingleton("myFloat", "1,1"); TestBean testBean = (TestBean) lbf.getBean("testBean"); - assertThat(testBean.getMyFloat() == 1.1f).isTrue(); + assertThat(testBean.getMyFloat()).isEqualTo(1.1f); } @Test @@ -1058,7 +1058,7 @@ class DefaultListableBeanFactoryTests { TestBean testBean = (TestBean) lbf.getBean("testBean"); assertThat(testBean.getName()).isEqualTo("myName"); assertThat(testBean.getAge()).isEqualTo(5); - assertThat(testBean.getMyFloat() == 1.1f).isTrue(); + assertThat(testBean.getMyFloat()).isEqualTo(1.1f); } @Test @@ -1076,7 +1076,7 @@ class DefaultListableBeanFactoryTests { TestBean testBean = (TestBean) lbf.getBean("testBean"); assertThat(testBean.getName()).isEqualTo("myName"); assertThat(testBean.getAge()).isEqualTo(5); - assertThat(testBean.getMyFloat() == 1.1f).isTrue(); + assertThat(testBean.getMyFloat()).isEqualTo(1.1f); } @Test @@ -1300,7 +1300,7 @@ class DefaultListableBeanFactoryTests { assertThat(lbf.getBeanDefinitionCount()).isEqualTo(1); Object registered = lbf.autowire(NoDependencies.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); assertThat(lbf.getBeanDefinitionCount()).isEqualTo(1); - assertThat(registered instanceof NoDependencies).isTrue(); + assertThat(registered).isInstanceOf(NoDependencies.class); } @Test @@ -1371,8 +1371,8 @@ class DefaultListableBeanFactoryTests { lbf.autowire(ConstructorDependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true); Object spouse = lbf.getBean("spouse"); - assertThat(bean.getSpouse1() == spouse).isTrue(); - assertThat(BeanFactoryUtils.beanOfType(lbf, TestBean.class) == spouse).isTrue(); + assertThat(bean.getSpouse1()).isSameAs(spouse); + assertThat(BeanFactoryUtils.beanOfType(lbf, TestBean.class)).isSameAs(spouse); } @Test @@ -1384,7 +1384,7 @@ class DefaultListableBeanFactoryTests { TestBean spouse = (TestBean) lbf.getBean("spouse"); assertThat(bean.getSpouse()).isEqualTo(spouse); - assertThat(BeanFactoryUtils.beanOfType(lbf, TestBean.class) == spouse).isTrue(); + assertThat(BeanFactoryUtils.beanOfType(lbf, TestBean.class)).isSameAs(spouse); } @Test @@ -2248,7 +2248,7 @@ 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)); - assertThat(bean.getSpouse() == otherBean).isTrue(); + assertThat(bean.getSpouse()).isSameAs(otherBean); } } @@ -2350,8 +2350,8 @@ class DefaultListableBeanFactoryTests { factory.registerBeanDefinition("tb2", bd2); factory.registerBeanDefinition("tb3", new RootBeanDefinition(TestBean.class)); - assertThat(((AbstractBeanDefinition) factory.getMergedBeanDefinition("tb1")).getLazyInit()).isEqualTo(Boolean.TRUE); - assertThat(((AbstractBeanDefinition) factory.getMergedBeanDefinition("tb2")).getLazyInit()).isEqualTo(Boolean.FALSE); + assertThat(((AbstractBeanDefinition) factory.getMergedBeanDefinition("tb1")).getLazyInit()).isTrue(); + assertThat(((AbstractBeanDefinition) factory.getMergedBeanDefinition("tb2")).getLazyInit()).isFalse(); assertThat(((AbstractBeanDefinition) factory.getMergedBeanDefinition("tb3")).getLazyInit()).isNull(); factory.preInstantiateSingletons(); @@ -2405,7 +2405,7 @@ class DefaultListableBeanFactoryTests { assertThat(tb.getBeanName()).isEqualTo("myBeanName"); DerivedTestBean tb2 = (DerivedTestBean) lbf.getBean("test"); - assertThat(tb != tb2).isTrue(); + assertThat(tb).isNotSameAs(tb2); assertThat(tb2.getName()).isEqualTo("myName"); assertThat(tb2.getBeanName()).isEqualTo("myBeanName"); } @@ -2424,7 +2424,7 @@ class DefaultListableBeanFactoryTests { assertThat(tb.getBeanName()).isEqualTo("myBeanName"); DerivedTestBean tb2 = (DerivedTestBean) lbf.getBean("test"); - assertThat(tb != tb2).isTrue(); + assertThat(tb).isNotSameAs(tb2); assertThat(tb2.getName()).isEqualTo("myName"); assertThat(tb2.getBeanName()).isEqualTo("myBeanName"); } @@ -2747,7 +2747,7 @@ class DefaultListableBeanFactoryTests { bd.setFactoryMethodName("empty"); lbf.registerBeanDefinition("optionalBean", bd); - assertThat((Optional) lbf.getBean(Optional.class)).isSameAs(Optional.empty()); + assertThat((Optional) lbf.getBean(Optional.class)).isEmpty(); } @Test 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 443ea6c5f02..de14305f70d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -494,7 +494,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); OptionalFieldInjectionBean bean = (OptionalFieldInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean()).isPresent(); assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean")); } @@ -503,7 +503,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalFieldInjectionBean.class)); OptionalFieldInjectionBean bean = (OptionalFieldInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isFalse(); + assertThat(bean.getTestBean()).isNotPresent(); } @Test @@ -512,7 +512,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); OptionalMethodInjectionBean bean = (OptionalMethodInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean()).isPresent(); assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean")); } @@ -521,7 +521,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalMethodInjectionBean.class)); OptionalMethodInjectionBean bean = (OptionalMethodInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isFalse(); + assertThat(bean.getTestBean()).isNotPresent(); } @Test @@ -530,7 +530,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); OptionalListFieldInjectionBean bean = (OptionalListFieldInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean()).isPresent(); assertThat(bean.getTestBean().get().get(0)).isSameAs(bf.getBean("testBean")); } @@ -539,7 +539,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListFieldInjectionBean.class)); OptionalListFieldInjectionBean bean = (OptionalListFieldInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isFalse(); + assertThat(bean.getTestBean()).isNotPresent(); } @Test @@ -548,7 +548,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); OptionalListMethodInjectionBean bean = (OptionalListMethodInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean()).isPresent(); assertThat(bean.getTestBean().get().get(0)).isSameAs(bf.getBean("testBean")); } @@ -557,7 +557,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(OptionalListMethodInjectionBean.class)); OptionalListMethodInjectionBean bean = (OptionalListMethodInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isFalse(); + assertThat(bean.getTestBean()).isNotPresent(); } @Test @@ -566,7 +566,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); ProviderOfOptionalFieldInjectionBean bean = (ProviderOfOptionalFieldInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean()).isPresent(); assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean")); } @@ -575,7 +575,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalFieldInjectionBean.class)); ProviderOfOptionalFieldInjectionBean bean = (ProviderOfOptionalFieldInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isFalse(); + assertThat(bean.getTestBean()).isNotPresent(); } @Test @@ -584,7 +584,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); ProviderOfOptionalMethodInjectionBean bean = (ProviderOfOptionalMethodInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isTrue(); + assertThat(bean.getTestBean()).isPresent(); assertThat(bean.getTestBean().get()).isSameAs(bf.getBean("testBean")); } @@ -593,7 +593,7 @@ public class InjectAnnotationBeanPostProcessorTests { bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ProviderOfOptionalMethodInjectionBean.class)); ProviderOfOptionalMethodInjectionBean bean = (ProviderOfOptionalMethodInjectionBean) bf.getBean("annotatedBean"); - assertThat(bean.getTestBean().isPresent()).isFalse(); + assertThat(bean.getTestBean()).isNotPresent(); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGeneratorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGeneratorTests.java index a530c81a102..fc1c3ef8586 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGeneratorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGeneratorTests.java @@ -406,7 +406,7 @@ class BeanDefinitionMethodGeneratorTests { compile(method, (actual, compiled) -> { ManagedList actualPropertyValue = (ManagedList) actual .getPropertyValues().get("someList"); - assertThat(actualPropertyValue).isNotNull().hasSize(2); + assertThat(actualPropertyValue).hasSize(2); assertThat(actualPropertyValue.get(0).getPropertyValues().get("name")).isEqualTo("one"); assertThat(actualPropertyValue.get(1).getPropertyValues().get("name")).isEqualTo("two"); assertThat(compiled.getSourceFileFromPackage(TestBean.class.getPackageName())) 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 74d9232908b..7088a51b1a1 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 @@ -67,7 +67,7 @@ public class ObjectFactoryCreatingFactoryBeanTests { Date date1 = (Date) objectFactory.getObject(); Date date2 = (Date) objectFactory.getObject(); - assertThat(date1 != date2).isTrue(); + assertThat(date1).isNotSameAs(date2); } @Test @@ -79,7 +79,7 @@ public class ObjectFactoryCreatingFactoryBeanTests { Date date1 = (Date) objectFactory.getObject(); Date date2 = (Date) objectFactory.getObject(); - assertThat(date1 != date2).isTrue(); + assertThat(date1).isNotSameAs(date2); } @Test @@ -89,7 +89,7 @@ public class ObjectFactoryCreatingFactoryBeanTests { Date date1 = (Date) provider.get(); Date date2 = (Date) provider.get(); - assertThat(date1 != date2).isTrue(); + assertThat(date1).isNotSameAs(date2); } @Test @@ -101,7 +101,7 @@ public class ObjectFactoryCreatingFactoryBeanTests { Date date1 = (Date) provider.get(); Date date2 = (Date) provider.get(); - assertThat(date1 != date2).isTrue(); + assertThat(date1).isNotSameAs(date2); } @Test 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 27a00cb5c47..a04c2d768da 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -138,7 +138,7 @@ public class PropertiesFactoryBeanTests { assertThat(props.getProperty("tb.array[0].age")).isEqualTo("99"); assertThat(props.getProperty("key2")).isEqualTo("value2"); Properties newProps = pfb.getObject(); - assertThat(props != newProps).isTrue(); + assertThat(props).isNotSameAs(newProps); 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 bc0c7cce84f..c70408a6f4a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ public class PropertyPathFactoryBeanTests { Object result2 = xbf.getBean("otb.spouse"); boolean condition = result1 instanceof TestBean; assertThat(condition).isTrue(); - assertThat(result1 == result2).isTrue(); + assertThat(result1).isSameAs(result2); assertThat(((TestBean) result1).getAge()).isEqualTo(99); } @@ -73,9 +73,9 @@ public class PropertyPathFactoryBeanTests { 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(); + assertThat(result1).isNotSameAs(result2); + assertThat(result1).isNotSameAs(result3); + assertThat(result2).isNotSameAs(result3); } @Test 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 693025cee20..ffbb92e8ba3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -276,7 +276,7 @@ public class PropertyResourceConfigurerTests { } catch (BeanInitializationException ex) { // prove that the processor chokes on the invalid key - assertThat(ex.getMessage().toLowerCase().contains("argh")).isTrue(); + assertThat(ex.getMessage().toLowerCase()).contains("argh"); } } } 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 c62e78ee092..fe074daf3ef 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 @@ -165,7 +165,7 @@ public class ServiceLocatorFactoryBeanTests { assertThat(testBean4).isNotSameAs(testBean2); assertThat(testBean4).isNotSameAs(testBean3); - assertThat(factory.toString().contains("TestServiceLocator3")).isTrue(); + assertThat(factory.toString()).contains("TestServiceLocator3"); } @Disabled @Test // worked when using an ApplicationContext (see commented), fails when using BeanFactory diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlPropertiesFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlPropertiesFactoryBeanTests.java index c484cba81e2..218b0d10ee4 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlPropertiesFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/YamlPropertiesFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -180,7 +180,7 @@ class YamlPropertiesFactoryBeanTests { factory.setResources(new ByteArrayResource("foo: bar\nspam:".getBytes())); Properties properties = factory.getObject(); assertThat(properties.getProperty("foo")).isEqualTo("bar"); - assertThat(properties.getProperty("spam")).isEqualTo(""); + assertThat(properties.getProperty("spam")).isEmpty(); } @Test @@ -189,7 +189,7 @@ class YamlPropertiesFactoryBeanTests { factory.setResources(new ByteArrayResource("a: alpha\ntest: []".getBytes())); Properties properties = factory.getObject(); assertThat(properties.getProperty("a")).isEqualTo("alpha"); - assertThat(properties.getProperty("test")).isEqualTo(""); + assertThat(properties.getProperty("test")).isEmpty(); } @Test 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 34abf223af4..82c8dd704ee 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,7 +55,7 @@ public class CustomProblemReporterTests { @Test public void testErrorsAreCollated() { this.reader.loadBeanDefinitions(qualifiedResource(CustomProblemReporterTests.class, "context.xml")); - assertThat(this.problemReporter.getErrors().length).as("Incorrect number of errors collated").isEqualTo(4); + assertThat(this.problemReporter.getErrors()).as("Incorrect number of errors collated").hasSize(4); TestBean bean = (TestBean) this.beanFactory.getBean("validBean"); assertThat(bean).isNotNull(); 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 81678a7c0c2..0499e16e350 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ public class BeanDefinitionTests { otherBd.setScope("request"); assertThat(bd.equals(otherBd)).isTrue(); assertThat(otherBd.equals(bd)).isTrue(); - assertThat(bd.hashCode() == otherBd.hashCode()).isTrue(); + assertThat(bd.hashCode()).isEqualTo(otherBd.hashCode()); } @Test @@ -66,7 +66,7 @@ public class BeanDefinitionTests { otherBd.getPropertyValues().add("age", "99"); assertThat(bd.equals(otherBd)).isTrue(); assertThat(otherBd.equals(bd)).isTrue(); - assertThat(bd.hashCode() == otherBd.hashCode()).isTrue(); + assertThat(bd.hashCode()).isEqualTo(otherBd.hashCode()); } @Test @@ -88,7 +88,7 @@ public class BeanDefinitionTests { otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, 5); assertThat(bd.equals(otherBd)).isTrue(); assertThat(otherBd.equals(bd)).isTrue(); - assertThat(bd.hashCode() == otherBd.hashCode()).isTrue(); + assertThat(bd.hashCode()).isEqualTo(otherBd.hashCode()); } @Test @@ -111,7 +111,7 @@ public class BeanDefinitionTests { otherBd.getConstructorArgumentValues().addIndexedArgumentValue(1, 5, "long"); assertThat(bd.equals(otherBd)).isTrue(); assertThat(otherBd.equals(bd)).isTrue(); - assertThat(bd.hashCode() == otherBd.hashCode()).isTrue(); + assertThat(bd.hashCode()).isEqualTo(otherBd.hashCode()); } @Test @@ -132,17 +132,17 @@ public class BeanDefinitionTests { otherBd.setParentName("parent"); assertThat(bd.equals(otherBd)).isTrue(); assertThat(otherBd.equals(bd)).isTrue(); - assertThat(bd.hashCode() == otherBd.hashCode()).isTrue(); + assertThat(bd.hashCode()).isEqualTo(otherBd.hashCode()); bd.getPropertyValues(); assertThat(bd.equals(otherBd)).isTrue(); assertThat(otherBd.equals(bd)).isTrue(); - assertThat(bd.hashCode() == otherBd.hashCode()).isTrue(); + assertThat(bd.hashCode()).isEqualTo(otherBd.hashCode()); bd.getConstructorArgumentValues(); assertThat(bd.equals(otherBd)).isTrue(); assertThat(otherBd.equals(bd)).isTrue(); - assertThat(bd.hashCode() == otherBd.hashCode()).isTrue(); + assertThat(bd.hashCode()).isEqualTo(otherBd.hashCode()); } @Test @@ -163,7 +163,7 @@ public class BeanDefinitionTests { BeanDefinitionHolder otherHolder = new BeanDefinitionHolder(bd, "bd"); assertThat(holder.equals(otherHolder)).isTrue(); assertThat(otherHolder.equals(holder)).isTrue(); - assertThat(holder.hashCode() == otherHolder.hashCode()).isTrue(); + assertThat(holder.hashCode()).isEqualTo(otherHolder.hashCode()); } @Test 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 aac2e43248c..a7929bf30d9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ public class ManagedMapTests { ManagedMap child = ManagedMap.ofEntries(Map.entry("tree", "three")); child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); - assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(3); + assertThat(mergedMap).as("merge() obviously did not work.").hasSize(3); } @Test @@ -70,7 +70,7 @@ public class ManagedMapTests { ManagedMap child = new ManagedMap(); child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); - assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(2); + assertThat(mergedMap).as("merge() obviously did not work.").hasSize(2); } @Test @@ -81,7 +81,7 @@ public class ManagedMapTests { child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); // child value for 'one' must override parent value... - assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(2); + assertThat(mergedMap).as("merge() obviously did not work.").hasSize(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 473679f3d10..c91fac8d99f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ public class ManagedPropertiesTests { child.setProperty("three", "three"); child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); - assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(3); + assertThat(mergedMap).as("merge() obviously did not work.").hasSize(3); } @Test @@ -74,7 +74,7 @@ public class ManagedPropertiesTests { ManagedProperties child = new ManagedProperties(); child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); - assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(2); + assertThat(mergedMap).as("merge() obviously did not work.").hasSize(2); } @Test @@ -87,7 +87,7 @@ public class ManagedPropertiesTests { child.setMergeEnabled(true); Map mergedMap = (Map) child.merge(parent); // child value for 'one' must override parent value... - assertThat(mergedMap.size()).as("merge() obviously did not work.").isEqualTo(2); + assertThat(mergedMap).as("merge() obviously did not work.").hasSize(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/Spr8954Tests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/Spr8954Tests.java index a1db2e31356..19dfaa5974a 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/Spr8954Tests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/Spr8954Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,8 +73,8 @@ public class Spr8954Tests { @SuppressWarnings("rawtypes") Map fbBeans = bf.getBeansOfType(FactoryBean.class); - assertThat(1).isEqualTo(fbBeans.size()); - assertThat("&foo").isEqualTo(fbBeans.keySet().iterator().next()); + assertThat(fbBeans.size()).isEqualTo(1); + assertThat(fbBeans.keySet().iterator().next()).isEqualTo("&foo"); Map aiBeans = bf.getBeansOfType(AnInterface.class); assertThat(aiBeans).hasSize(1); 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 55fef5cb34b..11d0324d76f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,13 +56,13 @@ public class BeanNameGenerationTests { GeneratedNameBean child1 = topLevel1.getChild(); assertThat(child1.getBeanName()).isNotNull(); - assertThat(child1.getBeanName().startsWith(className)).isTrue(); + assertThat(child1.getBeanName()).startsWith(className); GeneratedNameBean child2 = topLevel2.getChild(); assertThat(child2.getBeanName()).isNotNull(); - assertThat(child2.getBeanName().startsWith(className)).isTrue(); + assertThat(child2.getBeanName()).startsWith(className); - assertThat(child1.getBeanName().equals(child2.getBeanName())).isFalse(); + assertThat(child1.getBeanName()).isNotEqualTo(child2.getBeanName()); } } 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 85a78bab9f6..c50cbd5fe4f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ public class CollectionMergingTests { public void mergeList() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithList"); List list = bean.getSomeList(); - assertThat(list.size()).as("Incorrect size").isEqualTo(3); + assertThat(list).as("Incorrect size").hasSize(3); assertThat(list.get(0)).isEqualTo("Rob Harrop"); assertThat(list.get(1)).isEqualTo("Rod Johnson"); assertThat(list.get(2)).isEqualTo("Juergen Hoeller"); @@ -75,7 +75,7 @@ public class CollectionMergingTests { public void mergeSet() { TestBean bean = (TestBean) this.beanFactory.getBean("childWithSet"); Set set = bean.getSomeSet(); - assertThat(set.size()).as("Incorrect size").isEqualTo(2); + assertThat(set).as("Incorrect size").hasSize(2); assertThat(set.contains("Rob Harrop")).isTrue(); assertThat(set.contains("Sally Greenwood")).isTrue(); } @@ -99,7 +99,7 @@ public class CollectionMergingTests { public void mergeMap() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithMap"); Map map = bean.getSomeMap(); - assertThat(map.size()).as("Incorrect size").isEqualTo(3); + assertThat(map).as("Incorrect size").hasSize(3); assertThat(map.get("Rob")).isEqualTo("Sally"); assertThat(map.get("Rod")).isEqualTo("Kerry"); assertThat(map.get("Juergen")).isEqualTo("Eva"); @@ -121,7 +121,7 @@ public class CollectionMergingTests { public void mergeProperties() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithProps"); Properties props = bean.getSomeProperties(); - assertThat(props.size()).as("Incorrect size").isEqualTo(3); + assertThat(props).as("Incorrect size").hasSize(3); assertThat(props.getProperty("Rob")).isEqualTo("Sally"); assertThat(props.getProperty("Rod")).isEqualTo("Kerry"); assertThat(props.getProperty("Juergen")).isEqualTo("Eva"); @@ -131,7 +131,7 @@ public class CollectionMergingTests { public void mergeListInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithListInConstructor"); List list = bean.getSomeList(); - assertThat(list.size()).as("Incorrect size").isEqualTo(3); + assertThat(list).as("Incorrect size").hasSize(3); assertThat(list.get(0)).isEqualTo("Rob Harrop"); assertThat(list.get(1)).isEqualTo("Rod Johnson"); assertThat(list.get(2)).isEqualTo("Juergen Hoeller"); @@ -152,7 +152,7 @@ public class CollectionMergingTests { public void mergeSetInConstructor() { TestBean bean = (TestBean) this.beanFactory.getBean("childWithSetInConstructor"); Set set = bean.getSomeSet(); - assertThat(set.size()).as("Incorrect size").isEqualTo(2); + assertThat(set).as("Incorrect size").hasSize(2); assertThat(set.contains("Rob Harrop")).isTrue(); assertThat(set.contains("Sally Greenwood")).isTrue(); } @@ -176,7 +176,7 @@ public class CollectionMergingTests { public void mergeMapInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithMapInConstructor"); Map map = bean.getSomeMap(); - assertThat(map.size()).as("Incorrect size").isEqualTo(3); + assertThat(map).as("Incorrect size").hasSize(3); assertThat(map.get("Rob")).isEqualTo("Sally"); assertThat(map.get("Rod")).isEqualTo("Kerry"); assertThat(map.get("Juergen")).isEqualTo("Eva"); @@ -198,7 +198,7 @@ public class CollectionMergingTests { public void mergePropertiesInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithPropsInConstructor"); Properties props = bean.getSomeProperties(); - assertThat(props.size()).as("Incorrect size").isEqualTo(3); + assertThat(props).as("Incorrect size").hasSize(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 8a67fea2c1b..db1c1eaab9b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,15 +81,15 @@ public class CollectionsWithDefaultTypesTests { @SuppressWarnings("rawtypes") public void testBuildCollectionFromMixtureOfReferencesAndValues() throws Exception { MixedCollectionBean jumble = (MixedCollectionBean) this.beanFactory.getBean("jumble"); - assertThat(jumble.getJumble().size() == 3).as("Expected 3 elements, not " + jumble.getJumble().size()).isTrue(); + assertThat(jumble.getJumble()).as("Expected 3 elements, not " + jumble.getJumble().size()).hasSize(3); List l = (List) jumble.getJumble(); assertThat(l.get(0).equals("literal")).isTrue(); Integer[] array1 = (Integer[]) l.get(1); assertThat(array1[0].equals(2)).isTrue(); assertThat(array1[1].equals(4)).isTrue(); int[] array2 = (int[]) l.get(2); - assertThat(array2[0] == 3).isTrue(); - assertThat(array2[1] == 5).isTrue(); + assertThat(array2[0]).isEqualTo(3); + assertThat(array2[1]).isEqualTo(5); } } 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 ced4e5098d8..fd8498b878a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -282,7 +282,7 @@ public class FactoryMethodTests { FactoryMethods fm2 = (FactoryMethods) xbf.getBean("testBeanOnlyPrototype", tbArg2); assertThat(fm2.getTestBean().getName()).isEqualTo("arg2"); assertThat(fm2.getNum()).isEqualTo(fm1.getNum()); - assertThat("testBeanOnlyPrototypeDISetterString").isEqualTo(fm2.getStringValue()); + assertThat(fm2.getStringValue()).isEqualTo("testBeanOnlyPrototypeDISetterString"); assertThat(fm2.getStringValue()).isEqualTo(fm2.getStringValue()); // The TestBean reference is resolved to a prototype in the factory assertThat(fm2.getTestBean()).isSameAs(fm2.getTestBean()); 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 c431485456f..722465bb976 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,7 +91,7 @@ public class UtilNamespaceHandlerTests { void testNestedProperties() { TestBean bean = (TestBean) this.beanFactory.getBean("testBean"); Properties props = bean.getSomeProperties(); - assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); + assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); } @Test @@ -111,7 +111,7 @@ public class UtilNamespaceHandlerTests { Map map = (Map) this.beanFactory.getBean("simpleMap"); assertThat(map.get("foo")).isEqualTo("bar"); Map map2 = (Map) this.beanFactory.getBean("simpleMap"); - assertThat(map == map2).isTrue(); + assertThat(map).isSameAs(map2); } @Test @@ -120,7 +120,7 @@ public class UtilNamespaceHandlerTests { assertThat(map.get("foo")).isEqualTo("bar"); Map map2 = (Map) this.beanFactory.getBean("scopedMap"); assertThat(map2.get("foo")).isEqualTo("bar"); - assertThat(map != map2).isTrue(); + assertThat(map).isNotSameAs(map2); } @Test @@ -128,7 +128,7 @@ public class UtilNamespaceHandlerTests { List list = (List) this.beanFactory.getBean("simpleList"); assertThat(list.get(0)).isEqualTo("Rob Harrop"); List list2 = (List) this.beanFactory.getBean("simpleList"); - assertThat(list == list2).isTrue(); + assertThat(list).isSameAs(list2); } @Test @@ -137,7 +137,7 @@ public class UtilNamespaceHandlerTests { assertThat(list.get(0)).isEqualTo("Rob Harrop"); List list2 = (List) this.beanFactory.getBean("scopedList"); assertThat(list2.get(0)).isEqualTo("Rob Harrop"); - assertThat(list != list2).isTrue(); + assertThat(list).isNotSameAs(list2); } @Test @@ -145,7 +145,7 @@ public class UtilNamespaceHandlerTests { Set set = (Set) this.beanFactory.getBean("simpleSet"); assertThat(set.contains("Rob Harrop")).isTrue(); Set set2 = (Set) this.beanFactory.getBean("simpleSet"); - assertThat(set == set2).isTrue(); + assertThat(set).isSameAs(set2); } @Test @@ -154,7 +154,7 @@ public class UtilNamespaceHandlerTests { assertThat(set.contains("Rob Harrop")).isTrue(); Set set2 = (Set) this.beanFactory.getBean("scopedSet"); assertThat(set2.contains("Rob Harrop")).isTrue(); - assertThat(set != set2).isTrue(); + assertThat(set).isNotSameAs(set2); } @Test @@ -194,9 +194,9 @@ public class UtilNamespaceHandlerTests { 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(); + assertThat(list).isNotSameAs(bean2.getSomeList()); + assertThat(set).isNotSameAs(bean2.getSomeSet()); + assertThat(map).isNotSameAs(bean2.getSomeMap()); } @Test @@ -216,11 +216,11 @@ public class UtilNamespaceHandlerTests { TestBean bean2 = (TestBean) this.beanFactory.getBean("nestedShortcutCollections"); assertThat(Arrays.equals(bean.getStringArray(), bean2.getStringArray())).isTrue(); - assertThat(bean.getStringArray() == bean2.getStringArray()).isFalse(); + assertThat(bean.getStringArray()).isNotSameAs(bean2.getStringArray()); assertThat(bean2.getSomeList()).isEqualTo(list); assertThat(bean2.getSomeSet()).isEqualTo(set); - assertThat(list == bean2.getSomeList()).isFalse(); - assertThat(set == bean2.getSomeSet()).isFalse(); + assertThat(list).isNotSameAs(bean2.getSomeList()); + assertThat(set).isNotSameAs(bean2.getSomeSet()); } @Test @@ -244,9 +244,9 @@ public class UtilNamespaceHandlerTests { 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(); + assertThat(list).isNotSameAs(bean2.getSomeList()); + assertThat(set).isNotSameAs(bean2.getSomeSet()); + assertThat(map).isNotSameAs(bean2.getSomeMap()); } @Test @@ -338,56 +338,56 @@ public class UtilNamespaceHandlerTests { @Test void testLoadProperties() { Properties props = (Properties) this.beanFactory.getBean("myProperties"); - assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); - assertThat(props.get("foo2")).as("Incorrect property value").isNull(); + assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); + assertThat(props).as("Incorrect property value").doesNotContainKey("foo2"); Properties props2 = (Properties) this.beanFactory.getBean("myProperties"); - assertThat(props == props2).isTrue(); + assertThat(props).isSameAs(props2); } @Test void testScopedProperties() { Properties props = (Properties) this.beanFactory.getBean("myScopedProperties"); - assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); - assertThat(props.get("foo2")).as("Incorrect property value").isNull(); + assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); + assertThat(props).as("Incorrect property value").doesNotContainKey("foo2"); Properties props2 = (Properties) this.beanFactory.getBean("myScopedProperties"); - assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); - assertThat(props.get("foo2")).as("Incorrect property value").isNull(); - assertThat(props != props2).isTrue(); + assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); + assertThat(props).as("Incorrect property value").doesNotContainKey("foo2"); + assertThat(props).isNotSameAs(props2); } @Test void testLocalProperties() { Properties props = (Properties) this.beanFactory.getBean("myLocalProperties"); - assertThat(props.get("foo")).as("Incorrect property value").isNull(); - assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo("bar2"); + assertThat(props).as("Incorrect property value").doesNotContainKey("foo"); + assertThat(props).as("Incorrect property value").containsEntry("foo2", "bar2"); } @Test void testMergedProperties() { Properties props = (Properties) this.beanFactory.getBean("myMergedProperties"); - assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); - assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo("bar2"); + assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); + assertThat(props).as("Incorrect property value").containsEntry("foo2", "bar2"); } @Test void testLocalOverrideDefault() { Properties props = (Properties) this.beanFactory.getBean("defaultLocalOverrideProperties"); - assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); - assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo("local2"); + assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); + assertThat(props).as("Incorrect property value").containsEntry("foo2", "local2"); } @Test void testLocalOverrideFalse() { Properties props = (Properties) this.beanFactory.getBean("falseLocalOverrideProperties"); - assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("bar"); - assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo("local2"); + assertThat(props).as("Incorrect property value").containsEntry("foo", "bar"); + assertThat(props).as("Incorrect property value").containsEntry("foo2", "local2"); } @Test void testLocalOverrideTrue() { Properties props = (Properties) this.beanFactory.getBean("trueLocalOverrideProperties"); - assertThat(props.get("foo")).as("Incorrect property value").isEqualTo("local"); - assertThat(props.get("foo2")).as("Incorrect property value").isEqualTo("local2"); + assertThat(props).as("Incorrect property value").containsEntry("foo", "local"); + assertThat(props).as("Incorrect property value").containsEntry("foo2", "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 e67aa1d9729..579245f6cf3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,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"); - assertThat(jen.getSpouse() == dave).isTrue(); + assertThat(jen.getSpouse()).isSameAs(dave); } @Test public void testPropertyWithLiteralValueSubelement() throws Exception { TestBean verbose = (TestBean) this.beanFactory.getBean("verbose"); - assertThat(verbose.getName().equals("verbose")).isTrue(); + assertThat(verbose.getName()).isEqualTo("verbose"); } @Test public void testPropertyWithIdRefLocalAttrSubelement() throws Exception { TestBean verbose = (TestBean) this.beanFactory.getBean("verbose2"); - assertThat(verbose.getName().equals("verbose")).isTrue(); + assertThat(verbose.getName()).isEqualTo("verbose"); } @Test public void testPropertyWithIdRefBeanAttrSubelement() throws Exception { TestBean verbose = (TestBean) this.beanFactory.getBean("verbose3"); - assertThat(verbose.getName().equals("verbose")).isTrue(); + assertThat(verbose.getName()).isEqualTo("verbose"); } @Test @@ -122,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(); - assertThat(friends.length == 2).isTrue(); + assertThat(friends.length).isEqualTo(2); - assertThat(friends[0] == jen).as("First friend must be jen, not " + friends[0]).isTrue(); - assertThat(friends[1] == dave).isTrue(); + assertThat(friends[0]).as("First friend must be jen, not " + friends[0]).isSameAs(jen); + assertThat(friends[1]).isSameAs(dave); // Should be ordered } @@ -136,34 +136,34 @@ public class XmlBeanCollectionTests { TestBean rod = (TestBean) this.beanFactory.getBean("pRod"); Object[] friends = rod.getFriends().toArray(); - 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(friends.length).isEqualTo(2); + assertThat(friends[0].toString()).as("First friend must be jen, not " + friends[0]).isEqualTo(jen.toString()); + assertThat(friends[0]).as("Jen not same instance").isNotSameAs(jen); + assertThat(friends[1].toString()).isEqualTo(dave.toString()); + assertThat(friends[1]).as("Dave not same instance").isNotSameAs(dave); assertThat(dave.getSpouse().getName()).isEqualTo("Jen"); TestBean rod2 = (TestBean) this.beanFactory.getBean("pRod"); Object[] friends2 = rod2.getFriends().toArray(); - 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(); + assertThat(friends2.length).isEqualTo(2); + assertThat(friends2[0].toString()).as("First friend must be jen, not " + friends2[0]).isEqualTo(jen.toString()); + assertThat(friends2[0]).as("Jen not same instance").isNotSameAs(friends[0]); + assertThat(friends2[1].toString()).isEqualTo(dave.toString()); + assertThat(friends2[1]).as("Dave not same instance").isNotSameAs(friends[1]); } @Test public void testRefSubelementsBuildCollectionFromSingleElement() throws Exception { TestBean loner = (TestBean) this.beanFactory.getBean("loner"); TestBean dave = (TestBean) this.beanFactory.getBean("david"); - assertThat(loner.getFriends().size() == 1).isTrue(); + assertThat(loner.getFriends().size()).isEqualTo(1); assertThat(loner.getFriends().contains(dave)).isTrue(); } @Test public void testBuildCollectionFromMixtureOfReferencesAndValues() throws Exception { MixedCollectionBean jumble = (MixedCollectionBean) this.beanFactory.getBean("jumble"); - assertThat(jumble.getJumble().size() == 5).as("Expected 5 elements, not " + jumble.getJumble().size()).isTrue(); + assertThat(jumble.getJumble().size()).as("Expected 5 elements, not " + jumble.getJumble().size()).isEqualTo(5); List l = (List) jumble.getJumble(); assertThat(l.get(0).equals(this.beanFactory.getBean("david"))).isTrue(); assertThat(l.get(1).equals("literal")).isTrue(); @@ -185,25 +185,25 @@ public class XmlBeanCollectionTests { @Test public void testEmptyMap() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("emptyMap"); - assertThat(hasMap.getMap().size() == 0).isTrue(); + assertThat(hasMap.getMap().size()).isEqualTo(0); } @Test public void testMapWithLiteralsOnly() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("literalMap"); - assertThat(hasMap.getMap().size() == 3).isTrue(); + assertThat(hasMap.getMap().size()).isEqualTo(3); assertThat(hasMap.getMap().get("foo").equals("bar")).isTrue(); assertThat(hasMap.getMap().get("fi").equals("fum")).isTrue(); - assertThat(hasMap.getMap().get("fa") == null).isTrue(); + assertThat(hasMap.getMap().get("fa")).isNull(); } @Test public void testMapWithLiteralsAndReferences() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("mixedMap"); - assertThat(hasMap.getMap().size() == 5).isTrue(); + assertThat(hasMap.getMap().size()).isEqualTo(5); assertThat(hasMap.getMap().get("foo").equals(10)).isTrue(); TestBean jenny = (TestBean) this.beanFactory.getBean("jenny"); - assertThat(hasMap.getMap().get("jenny") == jenny).isTrue(); + assertThat(hasMap.getMap().get("jenny")).isSameAs(jenny); assertThat(hasMap.getMap().get(5).equals("david")).isTrue(); boolean condition1 = hasMap.getMap().get("bar") instanceof Long; assertThat(condition1).isTrue(); @@ -217,22 +217,22 @@ public class XmlBeanCollectionTests { public void testMapWithLiteralsAndPrototypeReferences() throws Exception { TestBean jenny = (TestBean) this.beanFactory.getBean("pJenny"); HasMap hasMap = (HasMap) this.beanFactory.getBean("pMixedMap"); - assertThat(hasMap.getMap().size() == 2).isTrue(); + assertThat(hasMap.getMap().size()).isEqualTo(2); 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(); + assertThat(hasMap.getMap().get("jenny").toString()).isEqualTo(jenny.toString()); + assertThat(hasMap.getMap().get("jenny")).as("Not same instance").isNotSameAs(jenny); HasMap hasMap2 = (HasMap) this.beanFactory.getBean("pMixedMap"); - assertThat(hasMap2.getMap().size() == 2).isTrue(); + assertThat(hasMap2.getMap().size()).isEqualTo(2); 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(); + assertThat(hasMap2.getMap().get("jenny").toString()).isEqualTo(jenny.toString()); + assertThat(hasMap2.getMap().get("jenny")).as("Not same instance").isNotSameAs(hasMap.getMap().get("jenny")); } @Test public void testMapWithLiteralsReferencesAndList() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("mixedMapWithList"); - assertThat(hasMap.getMap().size() == 4).isTrue(); + assertThat(hasMap.getMap().size()).isEqualTo(4); assertThat(hasMap.getMap().get(null).equals("bar")).isTrue(); TestBean jenny = (TestBean) this.beanFactory.getBean("jenny"); assertThat(hasMap.getMap().get("jenny").equals(jenny)).isTrue(); @@ -240,28 +240,28 @@ public class XmlBeanCollectionTests { // Check list List l = (List) hasMap.getMap().get("list"); assertThat(l).isNotNull(); - assertThat(l.size() == 4).isTrue(); + assertThat(l.size()).isEqualTo(4); assertThat(l.get(0).equals("zero")).isTrue(); - assertThat(l.get(3) == null).isTrue(); + assertThat(l.get(3)).isNull(); // Check nested map in list Map m = (Map) l.get(1); assertThat(m).isNotNull(); - assertThat(m.size() == 2).isTrue(); + assertThat(m.size()).isEqualTo(2); 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); assertThat(l).isNotNull(); - assertThat(l.size() == 2).isTrue(); + assertThat(l.size()).isEqualTo(2); assertThat(l.get(0).equals(jenny)).isTrue(); assertThat(l.get(1).equals("ba")).isTrue(); // Check nested map m = (Map) hasMap.getMap().get("map"); assertThat(m).isNotNull(); - assertThat(m.size() == 2).isTrue(); + assertThat(m.size()).isEqualTo(2); 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(); } @@ -269,13 +269,13 @@ public class XmlBeanCollectionTests { @Test public void testEmptySet() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("emptySet"); - assertThat(hasMap.getSet().size() == 0).isTrue(); + assertThat(hasMap.getSet().size()).isEqualTo(0); } @Test public void testPopulatedSet() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("set"); - assertThat(hasMap.getSet().size() == 3).isTrue(); + assertThat(hasMap.getSet().size()).isEqualTo(3); assertThat(hasMap.getSet().contains("bar")).isTrue(); TestBean jenny = (TestBean) this.beanFactory.getBean("jenny"); assertThat(hasMap.getSet().contains(jenny)).isTrue(); @@ -289,7 +289,7 @@ public class XmlBeanCollectionTests { @Test public void testPopulatedConcurrentSet() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("concurrentSet"); - assertThat(hasMap.getConcurrentSet().size() == 3).isTrue(); + assertThat(hasMap.getConcurrentSet().size()).isEqualTo(3); assertThat(hasMap.getConcurrentSet().contains("bar")).isTrue(); TestBean jenny = (TestBean) this.beanFactory.getBean("jenny"); assertThat(hasMap.getConcurrentSet().contains(jenny)).isTrue(); @@ -299,7 +299,7 @@ public class XmlBeanCollectionTests { @Test public void testPopulatedIdentityMap() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("identityMap"); - assertThat(hasMap.getIdentityMap().size() == 2).isTrue(); + assertThat(hasMap.getIdentityMap().size()).isEqualTo(2); HashSet set = new HashSet(hasMap.getIdentityMap().keySet()); assertThat(set.contains("foo")).isTrue(); assertThat(set.contains("jenny")).isTrue(); @@ -308,14 +308,14 @@ public class XmlBeanCollectionTests { @Test public void testEmptyProps() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("emptyProps"); - assertThat(hasMap.getProps().size() == 0).isTrue(); + assertThat(hasMap.getProps().size()).isEqualTo(0); assertThat(Properties.class).isEqualTo(hasMap.getProps().getClass()); } @Test public void testPopulatedProps() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("props"); - assertThat(hasMap.getProps().size() == 2).isTrue(); + assertThat(hasMap.getProps().size()).isEqualTo(2); assertThat(hasMap.getProps().get("foo").equals("bar")).isTrue(); assertThat(hasMap.getProps().get("2").equals("TWO")).isTrue(); } @@ -323,7 +323,7 @@ public class XmlBeanCollectionTests { @Test public void testObjectArray() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("objectArray"); - assertThat(hasMap.getObjectArray().length == 2).isTrue(); + assertThat(hasMap.getObjectArray().length).isEqualTo(2); assertThat(hasMap.getObjectArray()[0].equals("one")).isTrue(); assertThat(hasMap.getObjectArray()[1].equals(this.beanFactory.getBean("jenny"))).isTrue(); } @@ -331,16 +331,16 @@ public class XmlBeanCollectionTests { @Test public void testIntegerArray() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("integerArray"); - assertThat(hasMap.getIntegerArray().length == 3).isTrue(); - assertThat(hasMap.getIntegerArray()[0] == 0).isTrue(); - assertThat(hasMap.getIntegerArray()[1] == 1).isTrue(); - assertThat(hasMap.getIntegerArray()[2] == 2).isTrue(); + assertThat(hasMap.getIntegerArray().length).isEqualTo(3); + assertThat(hasMap.getIntegerArray()[0]).isEqualTo(0); + assertThat(hasMap.getIntegerArray()[1]).isEqualTo(1); + assertThat(hasMap.getIntegerArray()[2]).isEqualTo(2); } @Test public void testClassArray() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("classArray"); - assertThat(hasMap.getClassArray().length == 2).isTrue(); + assertThat(hasMap.getClassArray().length).isEqualTo(2); assertThat(hasMap.getClassArray()[0].equals(String.class)).isTrue(); assertThat(hasMap.getClassArray()[1].equals(Exception.class)).isTrue(); } @@ -348,7 +348,7 @@ public class XmlBeanCollectionTests { @Test public void testClassList() throws Exception { HasMap hasMap = (HasMap) this.beanFactory.getBean("classList"); - assertThat(hasMap.getClassList().size()== 2).isTrue(); + assertThat(hasMap.getClassList().size()).isEqualTo(2); assertThat(hasMap.getClassList().get(0).equals(String.class)).isTrue(); assertThat(hasMap.getClassList().get(1).equals(Exception.class)).isTrue(); } @@ -371,7 +371,7 @@ public class XmlBeanCollectionTests { List list = (List) this.beanFactory.getBean("listFactory"); boolean condition = list instanceof LinkedList; assertThat(condition).isTrue(); - assertThat(list.size() == 2).isTrue(); + assertThat(list.size()).isEqualTo(2); assertThat(list.get(0)).isEqualTo("bar"); assertThat(list.get(1)).isEqualTo("jenny"); } @@ -381,7 +381,7 @@ public class XmlBeanCollectionTests { List list = (List) this.beanFactory.getBean("pListFactory"); boolean condition = list instanceof LinkedList; assertThat(condition).isTrue(); - assertThat(list.size() == 2).isTrue(); + assertThat(list.size()).isEqualTo(2); assertThat(list.get(0)).isEqualTo("bar"); assertThat(list.get(1)).isEqualTo("jenny"); } @@ -391,7 +391,7 @@ public class XmlBeanCollectionTests { Set set = (Set) this.beanFactory.getBean("setFactory"); boolean condition = set instanceof TreeSet; assertThat(condition).isTrue(); - assertThat(set.size() == 2).isTrue(); + assertThat(set.size()).isEqualTo(2); assertThat(set.contains("bar")).isTrue(); assertThat(set.contains("jenny")).isTrue(); } @@ -401,7 +401,7 @@ public class XmlBeanCollectionTests { Set set = (Set) this.beanFactory.getBean("pSetFactory"); boolean condition = set instanceof TreeSet; assertThat(condition).isTrue(); - assertThat(set.size() == 2).isTrue(); + assertThat(set.size()).isEqualTo(2); assertThat(set.contains("bar")).isTrue(); assertThat(set.contains("jenny")).isTrue(); } @@ -411,7 +411,7 @@ public class XmlBeanCollectionTests { Map map = (Map) this.beanFactory.getBean("mapFactory"); boolean condition = map instanceof TreeMap; assertThat(condition).isTrue(); - assertThat(map.size() == 2).isTrue(); + assertThat(map.size()).isEqualTo(2); assertThat(map.get("foo")).isEqualTo("bar"); assertThat(map.get("jen")).isEqualTo("jenny"); } @@ -421,7 +421,7 @@ public class XmlBeanCollectionTests { Map map = (Map) this.beanFactory.getBean("pMapFactory"); boolean condition = map instanceof TreeMap; assertThat(condition).isTrue(); - assertThat(map.size() == 2).isTrue(); + assertThat(map.size()).isEqualTo(2); assertThat(map.get("foo")).isEqualTo("bar"); assertThat(map.get("jen")).isEqualTo("jenny"); } @@ -441,7 +441,7 @@ public class XmlBeanCollectionTests { @Test public void testEnumSetFactory() throws Exception { Set set = (Set) this.beanFactory.getBean("enumSetFactory"); - assertThat(set.size() == 2).isTrue(); + assertThat(set.size()).isEqualTo(2); assertThat(set.contains("ONE")).isTrue(); assertThat(set.contains("TWO")).isTrue(); } 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 791340e2ec3..c77c851a8ed 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -124,7 +124,7 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest @Test public void descriptionButNoProperties() { TestBean validEmpty = (TestBean) getBeanFactory().getBean("validEmptyWithDescription"); - assertThat(validEmpty.getAge()).isEqualTo(0); + assertThat(validEmpty.getAge()).isZero(); } /** @@ -136,71 +136,71 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest TestBean tb1 = (TestBean) getBeanFactory().getBean("aliased"); TestBean alias1 = (TestBean) getBeanFactory().getBean("myalias"); - assertThat(tb1 == alias1).isTrue(); + assertThat(tb1).isSameAs(alias1); List tb1Aliases = Arrays.asList(getBeanFactory().getAliases("aliased")); assertThat(tb1Aliases).hasSize(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(); + assertThat(tb1Aliases).contains("myalias"); + assertThat(tb1Aliases).contains("youralias"); + assertThat(beanNames).contains("aliased"); + assertThat(beanNames).doesNotContain("myalias"); + assertThat(beanNames).doesNotContain("youralias"); 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"); - assertThat(tb2 == alias2).isTrue(); - assertThat(tb2 == alias3).isTrue(); - assertThat(tb2 == alias3a).isTrue(); - assertThat(tb2 == alias3b).isTrue(); + assertThat(tb2).isSameAs(alias2); + assertThat(tb2).isSameAs(alias3); + assertThat(tb2).isSameAs(alias3a); + assertThat(tb2).isSameAs(alias3b); List tb2Aliases = Arrays.asList(getBeanFactory().getAliases("multiAliased")); assertThat(tb2Aliases).hasSize(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(); + assertThat(tb2Aliases).contains("alias1"); + assertThat(tb2Aliases).contains("alias2"); + assertThat(tb2Aliases).contains("alias3"); + assertThat(tb2Aliases).contains("alias4"); + assertThat(beanNames).contains("multiAliased"); + assertThat(beanNames).doesNotContain("alias1"); + assertThat(beanNames).doesNotContain("alias2"); + assertThat(beanNames).doesNotContain("alias3"); + assertThat(beanNames).doesNotContain("alias4"); TestBean tb3 = (TestBean) getBeanFactory().getBean("aliasWithoutId1"); TestBean alias4 = (TestBean) getBeanFactory().getBean("aliasWithoutId2"); TestBean alias5 = (TestBean) getBeanFactory().getBean("aliasWithoutId3"); - assertThat(tb3 == alias4).isTrue(); - assertThat(tb3 == alias5).isTrue(); + assertThat(tb3).isSameAs(alias4); + assertThat(tb3).isSameAs(alias5); List tb3Aliases = Arrays.asList(getBeanFactory().getAliases("aliasWithoutId1")); assertThat(tb3Aliases).hasSize(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(); + assertThat(tb3Aliases).contains("aliasWithoutId2"); + assertThat(tb3Aliases).contains("aliasWithoutId3"); + assertThat(beanNames).contains("aliasWithoutId1"); + assertThat(beanNames).doesNotContain("aliasWithoutId2"); + assertThat(beanNames).doesNotContain("aliasWithoutId3"); TestBean tb4 = (TestBean) getBeanFactory().getBean(TestBean.class.getName() + "#0"); assertThat(tb4.getName()).isNull(); Map drs = getListableBeanFactory().getBeansOfType(DummyReferencer.class, false, false); assertThat(drs).hasSize(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(); + assertThat(drs).containsKey(DummyReferencer.class.getName() + "#0"); + assertThat(drs).containsKey(DummyReferencer.class.getName() + "#1"); + assertThat(drs).containsKey(DummyReferencer.class.getName() + "#2"); } @Test public void factoryNesting() { ITestBean father = (ITestBean) getBeanFactory().getBean("father"); - assertThat(father != null).as("Bean from root context").isTrue(); + assertThat(father).as("Bean from root context").isNotNull(); TestBean rod = (TestBean) getBeanFactory().getBean("rod"); - assertThat("Rod".equals(rod.getName())).as("Bean from child context").isTrue(); - assertThat(rod.getSpouse() == father).as("Bean has external reference").isTrue(); + assertThat(rod.getName()).as("Bean from child context").isEqualTo("Rod"); + assertThat(rod.getSpouse()).as("Bean has external reference").isSameAs(father); rod = (TestBean) parent.getBean("rod"); - assertThat("Roderick".equals(rod.getName())).as("Bean from root context").isTrue(); + assertThat(rod.getName()).as("Bean from root context").isEqualTo("Roderick"); } @Test @@ -208,25 +208,25 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); DummyReferencer ref = (DummyReferencer) getBeanFactory().getBean("factoryReferencer"); - assertThat(ref.getTestBean1() == ref.getTestBean2()).isTrue(); - assertThat(ref.getDummyFactory() == factory).isTrue(); + assertThat(ref.getTestBean1()).isSameAs(ref.getTestBean2()); + assertThat(ref.getDummyFactory()).isSameAs(factory); DummyReferencer ref2 = (DummyReferencer) getBeanFactory().getBean("factoryReferencerWithConstructor"); - assertThat(ref2.getTestBean1() == ref2.getTestBean2()).isTrue(); - assertThat(ref2.getDummyFactory() == factory).isTrue(); + assertThat(ref2.getTestBean1()).isSameAs(ref2.getTestBean2()); + assertThat(ref2.getDummyFactory()).isSameAs(factory); } @Test public void prototypeReferences() { // check that not broken by circular reference resolution mechanism DummyReferencer ref1 = (DummyReferencer) getBeanFactory().getBean("prototypeReferencer"); - assertThat(ref1.getTestBean1() != ref1.getTestBean2()).as("Not referencing same bean twice").isTrue(); + assertThat(ref1.getTestBean1()).as("Not referencing same bean twice").isNotSameAs(ref1.getTestBean2()); DummyReferencer ref2 = (DummyReferencer) getBeanFactory().getBean("prototypeReferencer"); - 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(); + assertThat(ref1).as("Not the same referencer").isNotSameAs(ref2); + assertThat(ref2.getTestBean1()).as("Not referencing same bean twice").isNotSameAs(ref2.getTestBean2()); + assertThat(ref1.getTestBean1()).as("Not referencing same bean twice").isNotSameAs(ref2.getTestBean1()); + assertThat(ref1.getTestBean2()).as("Not referencing same bean twice").isNotSameAs(ref2.getTestBean2()); + assertThat(ref1.getTestBean1()).as("Not referencing same bean twice").isNotSameAs(ref2.getTestBean2()); } @Test @@ -245,8 +245,8 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest public void emptyValues() { TestBean rod = (TestBean) getBeanFactory().getBean("rod"); TestBean kerry = (TestBean) getBeanFactory().getBean("kerry"); - assertThat("".equals(rod.getTouchy())).as("Touchy is empty").isTrue(); - assertThat("".equals(kerry.getTouchy())).as("Touchy is empty").isTrue(); + assertThat(rod.getTouchy()).as("Touchy is empty").isEqualTo(""); + assertThat(kerry.getTouchy()).as("Touchy is empty").isEqualTo(""); } @Test 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 0ea1102cdae..ef5bdc87d76 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ public class ByteArrayPropertyEditorTests { byteEditor.setAsText(text); Object value = byteEditor.getValue(); - assertThat(value).isNotNull().isInstanceOf(byte[].class); + assertThat(value).isInstanceOf(byte[].class); byte[] bytes = (byte[]) value; for (int i = 0; i < text.length(); ++i) { assertThat(bytes[i]).as("cyte[] differs at index '" + i + "'").isEqualTo((byte) text.charAt(i)); @@ -47,10 +47,10 @@ public class ByteArrayPropertyEditorTests { @Test public void getAsTextReturnsEmptyStringIfValueIsNull() throws Exception { - assertThat(byteEditor.getAsText()).isEqualTo(""); + assertThat(byteEditor.getAsText()).isEmpty(); byteEditor.setAsText(null); - assertThat(byteEditor.getAsText()).isEqualTo(""); + assertThat(byteEditor.getAsText()).isEmpty(); } } 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 d01f59100e1..af09ae6c6e0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ public class CharArrayPropertyEditorTests { charEditor.setAsText(text); Object value = charEditor.getValue(); - assertThat(value).isNotNull().isInstanceOf(char[].class); + assertThat(value).isInstanceOf(char[].class); char[] chars = (char[]) value; for (int i = 0; i < text.length(); ++i) { assertThat(chars[i]).as("char[] differs at index '" + i + "'").isEqualTo(text.charAt(i)); @@ -47,10 +47,10 @@ public class CharArrayPropertyEditorTests { @Test public void getAsTextReturnsEmptyStringIfValueIsNull() throws Exception { - assertThat(charEditor.getAsText()).isEqualTo(""); + assertThat(charEditor.getAsText()).isEmpty(); charEditor.setAsText(null); - assertThat(charEditor.getAsText()).isEqualTo(""); + assertThat(charEditor.getAsText()).isEmpty(); } } 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 ad8d4c761de..267f2a42e67 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,7 @@ public class CustomCollectionEditorTests { boolean condition = value instanceof ArrayList; assertThat(condition).isTrue(); List list = (List) value; - assertThat(list.size()).as("There must be 3 elements in the converted collection").isEqualTo(3); + assertThat(list).as("There must be 3 elements in the converted collection").hasSize(3); assertThat(list.get(0)).isEqualTo(0); assertThat(list.get(1)).isEqualTo(1); assertThat(list.get(2)).isEqualTo(2); @@ -74,7 +74,7 @@ public class CustomCollectionEditorTests { editor.setValue("0, 1, 2"); Collection value = (Collection) editor.getValue(); assertThat(value).isNotNull(); - assertThat(value.size()).as("There must be 1 element in the converted collection").isEqualTo(1); + assertThat(value).as("There must be 1 element in the converted collection").hasSize(1); assertThat(value.iterator().next()).isEqualTo("0, 1, 2"); } @@ -87,7 +87,7 @@ public class CustomCollectionEditorTests { boolean condition = value instanceof ArrayList; assertThat(condition).isTrue(); List list = (List) value; - assertThat(list.size()).as("There must be 1 element in the converted collection").isEqualTo(1); + assertThat(list).as("There must be 1 element in the converted collection").hasSize(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 50062d8a824..4f377d5683c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -350,30 +350,30 @@ class CustomEditorTests { bw.setPropertyValue("double2", "6.1"); bw.setPropertyValue("bigDecimal", "4.5"); - assertThat(Short.valueOf("1").equals(bw.getPropertyValue("short1"))).as("Correct short1 value").isTrue(); - assertThat(tb.getShort1() == 1).as("Correct short1 value").isTrue(); - assertThat(Short.valueOf("2").equals(bw.getPropertyValue("short2"))).as("Correct short2 value").isTrue(); - assertThat(Short.valueOf("2").equals(tb.getShort2())).as("Correct short2 value").isTrue(); - assertThat(Integer.valueOf("7").equals(bw.getPropertyValue("int1"))).as("Correct int1 value").isTrue(); - assertThat(tb.getInt1() == 7).as("Correct int1 value").isTrue(); - assertThat(Integer.valueOf("8").equals(bw.getPropertyValue("int2"))).as("Correct int2 value").isTrue(); - assertThat(Integer.valueOf("8").equals(tb.getInt2())).as("Correct int2 value").isTrue(); - assertThat(Long.valueOf("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue(); - assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue(); - assertThat(Long.valueOf("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); - assertThat(Long.valueOf("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(Float.valueOf("7.1").equals(bw.getPropertyValue("float1"))).as("Correct float1 value").isTrue(); - assertThat(Float.valueOf("7.1").equals(tb.getFloat1())).as("Correct float1 value").isTrue(); - assertThat(Float.valueOf("8.1").equals(bw.getPropertyValue("float2"))).as("Correct float2 value").isTrue(); - assertThat(Float.valueOf("8.1").equals(tb.getFloat2())).as("Correct float2 value").isTrue(); - assertThat(Double.valueOf("5.1").equals(bw.getPropertyValue("double1"))).as("Correct double1 value").isTrue(); - assertThat(tb.getDouble1() == 5.1).as("Correct double1 value").isTrue(); - assertThat(Double.valueOf("6.1").equals(bw.getPropertyValue("double2"))).as("Correct double2 value").isTrue(); - assertThat(Double.valueOf("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(); + assertThat(Short.valueOf("1")).as("Correct short1 value").isEqualTo(bw.getPropertyValue("short1")); + assertThat(tb.getShort1()).as("Correct short1 value").isOne(); + assertThat(Short.valueOf("2")).as("Correct short2 value").isEqualTo(bw.getPropertyValue("short2")); + assertThat(Short.valueOf("2")).as("Correct short2 value").isEqualTo(tb.getShort2()); + assertThat(Integer.valueOf("7")).as("Correct int1 value").isEqualTo(bw.getPropertyValue("int1")); + assertThat(tb.getInt1()).as("Correct int1 value").isEqualTo(7); + assertThat(Integer.valueOf("8")).as("Correct int2 value").isEqualTo(bw.getPropertyValue("int2")); + assertThat(Integer.valueOf("8")).as("Correct int2 value").isEqualTo(tb.getInt2()); + assertThat(Long.valueOf("5")).as("Correct long1 value").isEqualTo(bw.getPropertyValue("long1")); + assertThat(tb.getLong1()).as("Correct long1 value").isEqualTo(5); + assertThat(Long.valueOf("6")).as("Correct long2 value").isEqualTo(bw.getPropertyValue("long2")); + assertThat(Long.valueOf("6")).as("Correct long2 value").isEqualTo(tb.getLong2()); + assertThat(new BigInteger("3")).as("Correct bigInteger value").isEqualTo(bw.getPropertyValue("bigInteger")); + assertThat(new BigInteger("3")).as("Correct bigInteger value").isEqualTo(tb.getBigInteger()); + assertThat(Float.valueOf("7.1")).as("Correct float1 value").isEqualTo(bw.getPropertyValue("float1")); + assertThat(Float.valueOf("7.1")).as("Correct float1 value").isEqualTo(tb.getFloat1()); + assertThat(Float.valueOf("8.1")).as("Correct float2 value").isEqualTo(bw.getPropertyValue("float2")); + assertThat(Float.valueOf("8.1")).as("Correct float2 value").isEqualTo(tb.getFloat2()); + assertThat(Double.valueOf("5.1")).as("Correct double1 value").isEqualTo(bw.getPropertyValue("double1")); + assertThat(tb.getDouble1()).as("Correct double1 value").isEqualTo(5.1); + assertThat(Double.valueOf("6.1")).as("Correct double2 value").isEqualTo(bw.getPropertyValue("double2")); + assertThat(Double.valueOf("6.1")).as("Correct double2 value").isEqualTo(tb.getDouble2()); + assertThat(new BigDecimal("4.5")).as("Correct bigDecimal value").isEqualTo(bw.getPropertyValue("bigDecimal")); + assertThat(new BigDecimal("4.5")).as("Correct bigDecimal value").isEqualTo(tb.getBigDecimal()); } @Test @@ -408,29 +408,29 @@ class CustomEditorTests { bw.setPropertyValue("bigDecimal", "4,5"); assertThat(bw.getPropertyValue("short1")).as("Correct short1 value").isEqualTo(Short.valueOf("1")); - assertThat(tb.getShort1() == 1).as("Correct short1 value").isTrue(); + assertThat(tb.getShort1()).as("Correct short1 value").isOne(); assertThat(bw.getPropertyValue("short2")).as("Correct short2 value").isEqualTo(Short.valueOf("2")); assertThat(tb.getShort2()).as("Correct short2 value").isEqualTo(Short.valueOf("2")); assertThat(bw.getPropertyValue("int1")).as("Correct int1 value").isEqualTo(Integer.valueOf("7")); - assertThat(tb.getInt1() == 7).as("Correct int1 value").isTrue(); + assertThat(tb.getInt1()).as("Correct int1 value").isEqualTo(7); assertThat(bw.getPropertyValue("int2")).as("Correct int2 value").isEqualTo(Integer.valueOf("8")); assertThat(tb.getInt2()).as("Correct int2 value").isEqualTo(Integer.valueOf("8")); assertThat(bw.getPropertyValue("long1")).as("Correct long1 value").isEqualTo(Long.valueOf("5")); - assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue(); + assertThat(tb.getLong1()).as("Correct long1 value").isEqualTo(5); assertThat(bw.getPropertyValue("long2")).as("Correct long2 value").isEqualTo(Long.valueOf("6")); assertThat(tb.getLong2()).as("Correct long2 value").isEqualTo(Long.valueOf("6")); - 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 BigInteger("3")).as("Correct bigInteger value").isEqualTo(bw.getPropertyValue("bigInteger")); + assertThat(new BigInteger("3")).as("Correct bigInteger value").isEqualTo(tb.getBigInteger()); assertThat(bw.getPropertyValue("float1")).as("Correct float1 value").isEqualTo(Float.valueOf("7.1")); assertThat(Float.valueOf(tb.getFloat1())).as("Correct float1 value").isEqualTo(Float.valueOf("7.1")); assertThat(bw.getPropertyValue("float2")).as("Correct float2 value").isEqualTo(Float.valueOf("8.1")); assertThat(tb.getFloat2()).as("Correct float2 value").isEqualTo(Float.valueOf("8.1")); assertThat(bw.getPropertyValue("double1")).as("Correct double1 value").isEqualTo(Double.valueOf("5.1")); - assertThat(tb.getDouble1() == 5.1).as("Correct double1 value").isTrue(); + assertThat(tb.getDouble1()).as("Correct double1 value").isEqualTo(5.1); assertThat(bw.getPropertyValue("double2")).as("Correct double2 value").isEqualTo(Double.valueOf("6.1")); assertThat(tb.getDouble2()).as("Correct double2 value").isEqualTo(Double.valueOf("6.1")); - 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(); + assertThat(new BigDecimal("4.5")).as("Correct bigDecimal value").isEqualTo(bw.getPropertyValue("bigDecimal")); + assertThat(new BigDecimal("4.5")).as("Correct bigDecimal value").isEqualTo(tb.getBigDecimal()); } @Test @@ -444,13 +444,13 @@ class CustomEditorTests { bw.setPropertyValue("long1", "5"); bw.setPropertyValue("long2", "6"); assertThat(Long.valueOf("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue(); - assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue(); + assertThat(tb.getLong1()).as("Correct long1 value").isEqualTo(5); assertThat(Long.valueOf("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); assertThat(Long.valueOf("6").equals(tb.getLong2())).as("Correct long2 value").isTrue(); bw.setPropertyValue("long2", ""); - assertThat(bw.getPropertyValue("long2") == null).as("Correct long2 value").isTrue(); - assertThat(tb.getLong2() == null).as("Correct long2 value").isTrue(); + assertThat(bw.getPropertyValue("long2")).as("Correct long2 value").isNull(); + assertThat(tb.getLong2()).as("Correct long2 value").isNull(); assertThatExceptionOfType(BeansException.class).isThrownBy(() -> bw.setPropertyValue("long1", "")); assertThat(bw.getPropertyValue("long1")).isEqualTo(5L); 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 ec5cc0f469d..83d13cdf1e9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ public class FileEditorTests { boolean condition = value instanceof File; assertThat(condition).isTrue(); File file = (File) value; - assertThat(file.exists()).isTrue(); + assertThat(file).exists(); } @Test @@ -86,9 +86,9 @@ public class FileEditorTests { boolean condition = value instanceof File; assertThat(condition).isTrue(); File file = (File) value; - assertThat(file.exists()).isTrue(); + assertThat(file).exists(); String absolutePath = file.getAbsolutePath().replace('\\', '/'); - assertThat(absolutePath.endsWith(fileName)).isTrue(); + assertThat(absolutePath).endsWith(fileName); } @Test @@ -101,9 +101,9 @@ public class FileEditorTests { boolean condition = value instanceof File; assertThat(condition).isTrue(); File file = (File) value; - assertThat(file.exists()).isFalse(); + assertThat(file).doesNotExist(); String absolutePath = file.getAbsolutePath().replace('\\', '/'); - assertThat(absolutePath.endsWith(fileName)).isTrue(); + assertThat(absolutePath).endsWith(fileName); } } 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 e0fb3aabce6..5720c353bce 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ public class InputStreamEditorTests { boolean condition = value instanceof InputStream; assertThat(condition).isTrue(); stream = (InputStream) value; - assertThat(stream.available() > 0).isTrue(); + assertThat(stream.available()).isGreaterThan(0); } finally { if (stream != null) { 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 f0c659bcbdb..d55cc18d48a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,9 +39,9 @@ public class PathEditorTests { pathEditor.setAsText("classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class"); Object value = pathEditor.getValue(); - assertThat(value instanceof Path).isTrue(); + assertThat(value).isInstanceOf(Path.class); Path path = (Path) value; - assertThat(path.toFile().exists()).isTrue(); + assertThat(path.toFile()).exists(); } @Test @@ -56,9 +56,9 @@ public class PathEditorTests { PropertyEditor pathEditor = new PathEditor(); pathEditor.setAsText("file:/no_way_this_file_is_found.doc"); Object value = pathEditor.getValue(); - assertThat(value instanceof Path).isTrue(); + assertThat(value).isInstanceOf(Path.class); Path path = (Path) value; - assertThat(!path.toFile().exists()).isTrue(); + assertThat(path.toFile()).doesNotExist(); } @Test @@ -66,9 +66,9 @@ public class PathEditorTests { PropertyEditor pathEditor = new PathEditor(); pathEditor.setAsText("/no_way_this_file_is_found.doc"); Object value = pathEditor.getValue(); - assertThat(value instanceof Path).isTrue(); + assertThat(value).isInstanceOf(Path.class); Path path = (Path) value; - assertThat(!path.toFile().exists()).isTrue(); + assertThat(path.toFile()).doesNotExist(); } @Test @@ -76,9 +76,9 @@ public class PathEditorTests { PropertyEditor pathEditor = new PathEditor(); pathEditor.setAsText("C:\\no_way_this_file_is_found.doc"); Object value = pathEditor.getValue(); - assertThat(value instanceof Path).isTrue(); + assertThat(value).isInstanceOf(Path.class); Path path = (Path) value; - assertThat(!path.toFile().exists()).isTrue(); + assertThat(path.toFile()).doesNotExist(); } @Test @@ -87,9 +87,9 @@ public class PathEditorTests { try { pathEditor.setAsText("file://C:\\no_way_this_file_is_found.doc"); Object value = pathEditor.getValue(); - assertThat(value instanceof Path).isTrue(); + assertThat(value).isInstanceOf(Path.class); Path path = (Path) value; - assertThat(!path.toFile().exists()).isTrue(); + assertThat(path.toFile()).doesNotExist(); } catch (IllegalArgumentException ex) { if (File.separatorChar == '\\') { // on Windows, otherwise silently ignore @@ -105,15 +105,15 @@ public class PathEditorTests { ClassUtils.getShortName(getClass()) + ".class"; pathEditor.setAsText(fileName); Object value = pathEditor.getValue(); - assertThat(value instanceof Path).isTrue(); + assertThat(value).isInstanceOf(Path.class); Path path = (Path) value; File file = path.toFile(); - assertThat(file.exists()).isTrue(); + assertThat(file).exists(); String absolutePath = file.getAbsolutePath(); if (File.separatorChar == '\\') { absolutePath = absolutePath.replace('\\', '/'); } - assertThat(absolutePath.endsWith(fileName)).isTrue(); + assertThat(absolutePath).endsWith(fileName); } @Test @@ -123,15 +123,15 @@ public class PathEditorTests { ClassUtils.getShortName(getClass()) + ".clazz"; pathEditor.setAsText(fileName); Object value = pathEditor.getValue(); - assertThat(value instanceof Path).isTrue(); + assertThat(value).isInstanceOf(Path.class); Path path = (Path) value; File file = path.toFile(); - assertThat(file.exists()).isFalse(); + assertThat(file).doesNotExist(); String absolutePath = file.getAbsolutePath(); if (File.separatorChar == '\\') { absolutePath = absolutePath.replace('\\', '/'); } - assertThat(absolutePath.endsWith(fileName)).isTrue(); + assertThat(absolutePath).endsWith(fileName); } } 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 772f44e1a98..a2631bf435b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertThat(p.entrySet().size() == 1).as("contains one entry").isTrue(); + assertThat(p.entrySet().size()).as("contains one entry").isEqualTo(1); assertThat(p.get("foo").equals("bar")).as("foo=bar").isTrue(); } @@ -51,7 +51,7 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertThat(p.entrySet().size() == 2).as("contains two entries").isTrue(); + assertThat(p.entrySet().size()).as("contains two entries").isEqualTo(2); assertThat(p.get("foo").equals("bar with whitespace")).as("foo=bar with whitespace").isTrue(); assertThat(p.get("me").equals("mi")).as("me=mi").isTrue(); } @@ -64,7 +64,7 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertThat(p.entrySet().size() == 3).as("contains two entries").isTrue(); + assertThat(p.entrySet().size()).as("contains two entries").isEqualTo(3); 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(); @@ -76,7 +76,7 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertThat(p.entrySet().size() == 3).as("contains two entries").isTrue(); + assertThat(p.entrySet().size()).as("contains two entries").isEqualTo(3); 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(); @@ -88,7 +88,7 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertThat(p.entrySet().size() == 3).as("contains three entries").isTrue(); + assertThat(p.entrySet().size()).as("contains three entries").isEqualTo(3); assertThat(p.get("foo").equals("")).as("foo is empty").isTrue(); assertThat(p.get("me").equals("mi")).as("me=mi").isTrue(); } @@ -107,7 +107,7 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertThat(p.entrySet().size() == 3).as("contains three entries").isTrue(); + assertThat(p.entrySet().size()).as("contains three entries").isEqualTo(3); assertThat(p.get("foo").equals("bar")).as("foo is bar").isTrue(); assertThat(p.get("me").equals("mi")).as("me=mi").isTrue(); } @@ -129,7 +129,7 @@ public class PropertiesEditorTests { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); Properties p = (Properties) pe.getValue(); - assertThat(p.size() == 3).as("contains 3 entries, not " + p.size()).isTrue(); + assertThat(p.size()).as("contains 3 entries, not " + p.size()).isEqualTo(3); assertThat(p.get("foo").equals("bar")).as("foo is bar").isTrue(); assertThat(p.get("me").equals("mi")).as("me=mi").isTrue(); } 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 e9896ed50ab..9275dde1d2d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,7 +99,7 @@ public class URIEditorTests { assertThat(condition).isTrue(); URI uri = (URI) value; assertThat(uriEditor.getAsText()).isEqualTo(uri.toString()); - assertThat(uri.getScheme().startsWith("classpath")).isTrue(); + assertThat(uri.getScheme()).startsWith("classpath"); } @Test @@ -107,13 +107,13 @@ public class URIEditorTests { PropertyEditor uriEditor = new URIEditor(); uriEditor.setAsText(null); assertThat(uriEditor.getValue()).isNull(); - assertThat(uriEditor.getAsText()).isEqualTo(""); + assertThat(uriEditor.getAsText()).isEmpty(); } @Test public void getAsTextReturnsEmptyStringIfValueNotSet() throws Exception { PropertyEditor uriEditor = new URIEditor(); - assertThat(uriEditor.getAsText()).isEqualTo(""); + assertThat(uriEditor.getAsText()).isEmpty(); } @Test 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 2d6c4b0d6a1..b65364b6622 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,13 +86,13 @@ public class URLEditorTests { PropertyEditor urlEditor = new URLEditor(); urlEditor.setAsText(null); assertThat(urlEditor.getValue()).isNull(); - assertThat(urlEditor.getAsText()).isEqualTo(""); + assertThat(urlEditor.getAsText()).isEmpty(); } @Test public void testGetAsTextReturnsEmptyStringIfValueNotSet() throws Exception { PropertyEditor urlEditor = new URLEditor(); - assertThat(urlEditor.getAsText()).isEqualTo(""); + assertThat(urlEditor.getAsText()).isEmpty(); } } 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 b62f952fdb1..535f0ed3ad8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,7 +60,7 @@ class ZoneIdEditorTests { @Test void getNullAsText() { - assertThat(editor.getAsText()).as("The returned value is not correct.").isEqualTo(""); + assertThat(editor.getAsText()).as("The returned value is not correct.").isEmpty(); } @Test 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 717e287e491..876233fb3f2 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 @@ -52,101 +52,101 @@ public class PagedListHolderTests { tbs.add(tb3); PagedListHolder holder = new PagedListHolder(tbs); - 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.getSource()).as("Correct source").isSameAs(tbs); + assertThat(holder.getNrOfElements()).as("Correct number of elements").isEqualTo(3); + assertThat(holder.getPageCount()).as("Correct number of pages").isEqualTo(1); + assertThat(holder.getPageSize()).as("Correct page size").isEqualTo(PagedListHolder.DEFAULT_PAGE_SIZE); + assertThat(holder.getPage()).as("Correct page number").isEqualTo(0); 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(); + assertThat(holder.getFirstElementOnPage()).as("Correct first element").isEqualTo(0); + assertThat(holder.getLastElementOnPage()).as("Correct first element").isEqualTo(2); + assertThat(holder.getPageList().size()).as("Correct page list size").isEqualTo(3); + assertThat(holder.getPageList().get(0)).as("Correct page list contents").isSameAs(tb1); + assertThat(holder.getPageList().get(1)).as("Correct page list contents").isSameAs(tb2); + assertThat(holder.getPageList().get(2)).as("Correct page list contents").isSameAs(tb3); holder.setPageSize(2); - 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.getPageCount()).as("Correct number of pages").isEqualTo(2); + assertThat(holder.getPageSize()).as("Correct page size").isEqualTo(2); + assertThat(holder.getPage()).as("Correct page number").isEqualTo(0); 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(); + assertThat(holder.getFirstElementOnPage()).as("Correct first element").isEqualTo(0); + assertThat(holder.getLastElementOnPage()).as("Correct last element").isEqualTo(1); + assertThat(holder.getPageList().size()).as("Correct page list size").isEqualTo(2); + assertThat(holder.getPageList().get(0)).as("Correct page list contents").isSameAs(tb1); + assertThat(holder.getPageList().get(1)).as("Correct page list contents").isSameAs(tb2); holder.setPage(1); - assertThat(holder.getPage() == 1).as("Correct page number").isTrue(); + assertThat(holder.getPage()).as("Correct page number").isEqualTo(1); 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(); + assertThat(holder.getFirstElementOnPage()).as("Correct first element").isEqualTo(2); + assertThat(holder.getLastElementOnPage()).as("Correct last element").isEqualTo(2); + assertThat(holder.getPageList().size()).as("Correct page list size").isEqualTo(1); + assertThat(holder.getPageList().get(0)).as("Correct page list contents").isSameAs(tb3); holder.setPageSize(3); - 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.getPageCount()).as("Correct number of pages").isEqualTo(1); + assertThat(holder.getPageSize()).as("Correct page size").isEqualTo(3); + assertThat(holder.getPage()).as("Correct page number").isEqualTo(0); 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(); + assertThat(holder.getFirstElementOnPage()).as("Correct first element").isEqualTo(0); + assertThat(holder.getLastElementOnPage()).as("Correct last element").isEqualTo(2); holder.setPage(1); holder.setPageSize(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.getPageCount()).as("Correct number of pages").isEqualTo(2); + assertThat(holder.getPageSize()).as("Correct page size").isEqualTo(2); + assertThat(holder.getPage()).as("Correct page number").isEqualTo(1); 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.getFirstElementOnPage()).as("Correct first element").isEqualTo(2); + assertThat(holder.getLastElementOnPage()).as("Correct last element").isEqualTo(2); holder.setPageSize(2); holder.setPage(1); ((MutableSortDefinition) holder.getSort()).setProperty("name"); ((MutableSortDefinition) holder.getSort()).setIgnoreCase(false); holder.resort(); - 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.getSource()).as("Correct source").isSameAs(tbs); + assertThat(holder.getNrOfElements()).as("Correct number of elements").isEqualTo(3); + assertThat(holder.getPageCount()).as("Correct number of pages").isEqualTo(2); + assertThat(holder.getPageSize()).as("Correct page size").isEqualTo(2); + assertThat(holder.getPage()).as("Correct page number").isEqualTo(0); 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(); + assertThat(holder.getFirstElementOnPage()).as("Correct first element").isEqualTo(0); + assertThat(holder.getLastElementOnPage()).as("Correct last element").isEqualTo(1); + assertThat(holder.getPageList().size()).as("Correct page list size").isEqualTo(2); + assertThat(holder.getPageList().get(0)).as("Correct page list contents").isSameAs(tb3); + assertThat(holder.getPageList().get(1)).as("Correct page list contents").isSameAs(tb1); ((MutableSortDefinition) holder.getSort()).setProperty("name"); holder.resort(); - assertThat(holder.getPageList().get(0) == tb2).as("Correct page list contents").isTrue(); - assertThat(holder.getPageList().get(1) == tb1).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(0)).as("Correct page list contents").isSameAs(tb2); + assertThat(holder.getPageList().get(1)).as("Correct page list contents").isSameAs(tb1); ((MutableSortDefinition) holder.getSort()).setProperty("name"); holder.resort(); - assertThat(holder.getPageList().get(0) == tb3).as("Correct page list contents").isTrue(); - assertThat(holder.getPageList().get(1) == tb1).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(0)).as("Correct page list contents").isSameAs(tb3); + assertThat(holder.getPageList().get(1)).as("Correct page list contents").isSameAs(tb1); holder.setPage(1); - assertThat(holder.getPageList().size() == 1).as("Correct page list size").isTrue(); - assertThat(holder.getPageList().get(0) == tb2).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().size()).as("Correct page list size").isEqualTo(1); + assertThat(holder.getPageList().get(0)).as("Correct page list contents").isSameAs(tb2); ((MutableSortDefinition) holder.getSort()).setProperty("age"); holder.resort(); - assertThat(holder.getPageList().get(0) == tb1).as("Correct page list contents").isTrue(); - assertThat(holder.getPageList().get(1) == tb3).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(0)).as("Correct page list contents").isSameAs(tb1); + assertThat(holder.getPageList().get(1)).as("Correct page list contents").isSameAs(tb3); ((MutableSortDefinition) holder.getSort()).setIgnoreCase(true); holder.resort(); - assertThat(holder.getPageList().get(0) == tb1).as("Correct page list contents").isTrue(); - assertThat(holder.getPageList().get(1) == tb3).as("Correct page list contents").isTrue(); + assertThat(holder.getPageList().get(0)).as("Correct page list contents").isSameAs(tb1); + assertThat(holder.getPageList().get(1)).as("Correct page list contents").isSameAs(tb3); holder.nextPage(); assertThat(holder.getPage()).isEqualTo(1); 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 3ca5a5d8504..aac0b2097b0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,9 +39,9 @@ public class PropertyComparatorTests { dog2.setNickName("biscy"); PropertyComparator c = new PropertyComparator<>("nickName", false, true); - assertThat(c.compare(dog, dog2) > 0).isTrue(); - assertThat(c.compare(dog, dog) == 0).isTrue(); - assertThat(c.compare(dog2, dog) < 0).isTrue(); + assertThat(c.compare(dog, dog2)).isGreaterThan(0); + assertThat(c.compare(dog, dog)).isEqualTo(0); + assertThat(c.compare(dog2, dog)).isLessThan(0); } @Test @@ -49,7 +49,7 @@ public class PropertyComparatorTests { Dog dog = new Dog(); Dog dog2 = new Dog(); PropertyComparator c = new PropertyComparator<>("nickName", false, true); - assertThat(c.compare(dog, dog2) == 0).isTrue(); + assertThat(c.compare(dog, dog2)).isEqualTo(0); } @Test @@ -64,13 +64,13 @@ public class PropertyComparatorTests { dog2.setFirstName("biscuit"); dog2.setLastName("grayspots"); - assertThat(c.compare(dog1, dog2) == 0).isTrue(); + assertThat(c.compare(dog1, dog2)).isEqualTo(0); c = c.thenComparing(new PropertyComparator<>("firstName", false, true)); - assertThat(c.compare(dog1, dog2) > 0).isTrue(); + assertThat(c.compare(dog1, dog2)).isGreaterThan(0); dog2.setLastName("konikk dog"); - assertThat(c.compare(dog2, dog1) > 0).isTrue(); + assertThat(c.compare(dog2, dog1)).isGreaterThan(0); } @Test @@ -86,9 +86,9 @@ public class PropertyComparatorTests { dog2.setFirstName("biscuit"); dog2.setLastName("grayspots"); - assertThat(c.compare(dog1, dog2) > 0).isTrue(); + assertThat(c.compare(dog1, dog2)).isGreaterThan(0); c = c.reversed(); - assertThat(c.compare(dog1, dog2) < 0).isTrue(); + assertThat(c.compare(dog1, dog2)).isLessThan(0); } diff --git a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/factory/xml/AbstractBeanFactoryTests.java b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/factory/xml/AbstractBeanFactoryTests.java index 3062dc62dcd..ff762788faa 100644 --- a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/factory/xml/AbstractBeanFactoryTests.java +++ b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/factory/xml/AbstractBeanFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,11 +58,11 @@ public abstract class AbstractBeanFactoryTests { assertThat(getBeanFactory().containsBean("roderick")).isTrue(); TestBean rod = (TestBean) getBeanFactory().getBean("rod"); TestBean roderick = (TestBean) getBeanFactory().getBean("roderick"); - assertThat(rod != roderick).as("not == ").isTrue(); + assertThat(rod).as("not == ").isNotSameAs(roderick); assertThat(rod.getName().equals("Rod")).as("rod.name is Rod").isTrue(); - assertThat(rod.getAge() == 31).as("rod.age is 31").isTrue(); + assertThat(rod.getAge()).as("rod.age is 31").isEqualTo(31); assertThat(roderick.getName().equals("Roderick")).as("roderick.name is Roderick").isTrue(); - assertThat(roderick.getAge() == rod.getAge()).as("roderick.age was inherited").isTrue(); + assertThat(roderick.getAge()).as("roderick.age was inherited").isEqualTo(rod.getAge()); } @Test @@ -104,7 +104,7 @@ public abstract class AbstractBeanFactoryTests { assertThat(condition).as("Rod bean is a TestBean").isTrue(); TestBean rod = (TestBean) o; assertThat(rod.getName().equals("Rod")).as("rod.name is Rod").isTrue(); - assertThat(rod.getAge() == 31).as("rod.age is 31").isTrue(); + assertThat(rod.getAge()).as("rod.age is 31").isEqualTo(31); } @Test @@ -158,19 +158,19 @@ public abstract class AbstractBeanFactoryTests { Object o1 = getBeanFactory().getBean("rod"); boolean condition = o1 instanceof TestBean; assertThat(condition).as("Rod bean2 is a TestBean").isTrue(); - assertThat(o == o1).as("Object equals applies").isTrue(); + assertThat(o).as("Object equals applies").isSameAs(o1); } @Test public void prototypeInstancesAreIndependent() { TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy"); TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy"); - assertThat(tb1 != tb2).as("ref equal DOES NOT apply").isTrue(); + assertThat(tb1).as("ref equal DOES NOT apply").isNotSameAs(tb2); assertThat(tb1.equals(tb2)).as("object equal true").isTrue(); tb1.setAge(1); tb2.setAge(2); - assertThat(tb1.getAge() == 1).as("1 age independent = 1").isTrue(); - assertThat(tb2.getAge() == 2).as("2 age independent = 2").isTrue(); + assertThat(tb1.getAge()).as("1 age independent = 1").isEqualTo(1); + assertThat(tb2.getAge()).as("2 age independent = 2").isEqualTo(2); boolean condition = !tb1.equals(tb2); assertThat(condition).as("object equal now false").isTrue(); } @@ -212,8 +212,8 @@ public abstract class AbstractBeanFactoryTests { 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"); - assertThat(tb == tb2).as("Singleton references ==").isTrue(); - assertThat(factory.getBeanFactory() != null).as("FactoryBean is BeanFactoryAware").isTrue(); + assertThat(tb).as("Singleton references ==").isSameAs(tb2); + assertThat(factory.getBeanFactory()).as("FactoryBean is BeanFactoryAware").isNotNull(); } @Test @@ -224,7 +224,7 @@ public abstract class AbstractBeanFactoryTests { boolean condition = !tb.getName().equals(DummyFactory.SINGLETON_NAME); assertThat(condition).isTrue(); TestBean tb2 = (TestBean) getBeanFactory().getBean("prototypeFactory"); - assertThat(tb != tb2).as("Prototype references !=").isTrue(); + assertThat(tb).as("Prototype references !=").isNotSameAs(tb2); } /** @@ -274,7 +274,7 @@ public abstract class AbstractBeanFactoryTests { cbf.registerAlias("rod", alias); Object rod = getBeanFactory().getBean("rod"); Object aliasRod = getBeanFactory().getBean(alias); - assertThat(rod == aliasRod).isTrue(); + assertThat(rod).isSameAs(aliasRod); } diff --git a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/factory/xml/AbstractListableBeanFactoryTests.java b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/factory/xml/AbstractListableBeanFactoryTests.java index 0717f8a4936..c9644f5a6c6 100644 --- a/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/factory/xml/AbstractListableBeanFactoryTests.java +++ b/spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/factory/xml/AbstractListableBeanFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,24 +50,25 @@ public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFacto protected final void assertCount(int count) { String[] defnames = getListableBeanFactory().getBeanDefinitionNames(); - assertThat(defnames.length == count).as("We should have " + count + " beans, not " + defnames.length).isTrue(); + assertThat(defnames.length).as("We should have " + count + " beans, not " + defnames.length).isEqualTo(count); } protected void assertTestBeanCount(int count) { String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false); - assertThat(defNames.length == count).as("We should have " + count + " beans for class org.springframework.beans.testfixture.beans.TestBean, not " + - defNames.length).isTrue(); + assertThat(defNames.length).as("We should have " + count + " beans for class org.springframework.beans.testfixture.beans.TestBean, not " + + defNames.length).isEqualTo(count); int countIncludingFactoryBeans = count + 2; String[] names = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, true); - assertThat(names.length == countIncludingFactoryBeans).as("We should have " + countIncludingFactoryBeans + - " beans for class org.springframework.beans.testfixture.beans.TestBean, not " + names.length).isTrue(); + assertThat(names.length).as("We should have " + countIncludingFactoryBeans + + " beans for class org.springframework.beans.testfixture.beans.TestBean, not " + names.length) + .isEqualTo(countIncludingFactoryBeans); } @Test public void getDefinitionsForNoSuchClass() { String[] defnames = getListableBeanFactory().getBeanNamesForType(String.class); - assertThat(defnames.length == 0).as("No string definitions").isTrue(); + assertThat(defnames.length).as("No string definitions").isEqualTo(0); } /** @@ -76,11 +77,11 @@ public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFacto */ @Test public void getCountForFactoryClass() { - assertThat(getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2).as("Should have 2 factories, not " + - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length).isTrue(); + assertThat(getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length).as("Should have 2 factories, not " + + getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length).isEqualTo(2); - assertThat(getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2).as("Should have 2 factories, not " + - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length).isTrue(); + assertThat(getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length).as("Should have 2 factories, not " + + getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length).isEqualTo(2); } @Test diff --git a/spring-context-indexer/src/test/java/org/springframework/context/index/processor/CandidateComponentsIndexerTests.java b/spring-context-indexer/src/test/java/org/springframework/context/index/processor/CandidateComponentsIndexerTests.java index 718060f579a..ca779c4ed65 100644 --- a/spring-context-indexer/src/test/java/org/springframework/context/index/processor/CandidateComponentsIndexerTests.java +++ b/spring-context-indexer/src/test/java/org/springframework/context/index/processor/CandidateComponentsIndexerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -222,7 +222,7 @@ class CandidateComponentsIndexerTests { for (Class c : classes) { assertThat(metadata).has(Metadata.of(c, Component.class)); } - assertThat(metadata.getItems()).hasSize(classes.length); + assertThat(metadata.getItems()).hasSameSizeAs(classes); } private void testSingleComponent(Class target, Class... stereotypes) { 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 6bffe93759e..fd2943c1919 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 @@ -93,11 +93,11 @@ public class CaffeineCacheManagerTests { Cache cache1x = cm.getCache("c1"); boolean condition1 = cache1x instanceof CaffeineCache; assertThat(condition1).isTrue(); - assertThat(cache1x != cache1).isTrue(); + assertThat(cache1x).isNotSameAs(cache1); Cache cache2x = cm.getCache("c2"); boolean condition = cache2x instanceof CaffeineCache; assertThat(condition).isTrue(); - assertThat(cache2x != cache2).isTrue(); + assertThat(cache2x).isNotSameAs(cache2); Cache cache3x = cm.getCache("c3"); assertThat(cache3x).isNull(); @@ -123,7 +123,7 @@ public class CaffeineCacheManagerTests { Caffeine caffeine = Caffeine.newBuilder().maximumSize(10); cm.setCaffeine(caffeine); Cache cache1x = cm.getCache("c1"); - assertThat(cache1x != cache1).isTrue(); + assertThat(cache1x).isNotSameAs(cache1); cm.setCaffeine(caffeine); // Set same instance Cache cache1xx = cm.getCache("c1"); @@ -137,7 +137,7 @@ public class CaffeineCacheManagerTests { cm.setCaffeineSpec(CaffeineSpec.parse("maximumSize=10")); Cache cache1x = cm.getCache("c1"); - assertThat(cache1x != cache1).isTrue(); + assertThat(cache1x).isNotSameAs(cache1); } @Test @@ -147,7 +147,7 @@ public class CaffeineCacheManagerTests { cm.setCacheSpecification("maximumSize=10"); Cache cache1x = cm.getCache("c1"); - assertThat(cache1x != cache1).isTrue(); + assertThat(cache1x).isNotSameAs(cache1); } @Test @@ -160,7 +160,7 @@ public class CaffeineCacheManagerTests { cm.setCacheLoader(loader); Cache cache1x = cm.getCache("c1"); - assertThat(cache1x != cache1).isTrue(); + assertThat(cache1x).isNotSameAs(cache1); cm.setCacheLoader(loader); // Set same instance Cache cache1xx = cm.getCache("c1"); @@ -201,11 +201,11 @@ public class CaffeineCacheManagerTests { Cache cache1 = cm.getCache("c1"); Cache cache2 = cm.getCache("c2"); - assertThat(nc == cache2.getNativeCache()).isTrue(); + assertThat(nc).isSameAs(cache2.getNativeCache()); cm.setCaffeine(Caffeine.newBuilder().maximumSize(10)); - assertThat(cm.getCache("c1") != cache1).isTrue(); - assertThat(cm.getCache("c2") == cache2).isTrue(); + assertThat(cm.getCache("c1")).isNotSameAs(cache1); + assertThat(cm.getCache("c2")).isSameAs(cache2); } } 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 c5eb097dc08..62f94db25fc 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,7 +72,7 @@ public class JCacheCustomInterceptorTests { @Test public void onlyOneInterceptorIsAvailable() { Map interceptors = ctx.getBeansOfType(JCacheInterceptor.class); - assertThat(interceptors.size()).as("Only one interceptor should be defined").isEqualTo(1); + assertThat(interceptors).as("Only one interceptor should be defined").hasSize(1); JCacheInterceptor interceptor = interceptors.values().iterator().next(); assertThat(interceptor.getClass()).as("Custom interceptor not defined").isEqualTo(TestCacheInterceptor.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 18ca02df38f..fff00d06f04 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,8 @@ public abstract class AbstractCacheOperationTests> public void simple() { O operation = createSimpleOperation(); 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()).as("Unexpected number of annotation on " + operation.getMethod()) + .hasSize(1); assertThat(operation.getAnnotations().iterator().next()).as("Wrong method annotation").isEqualTo(operation.getCacheAnnotation()); assertThat(operation.getCacheResolver()).as("cache resolver should be set").isNotNull(); 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 15a6fd3edb6..cb321a09ecb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,25 +37,25 @@ public class InternetAddressEditorTests { @Test public void uninitialized() { - assertThat(editor.getAsText()).as("Uninitialized editor did not return empty value string").isEqualTo(EMPTY); + assertThat(editor.getAsText()).as("Uninitialized editor did not return empty value string").isEmpty(); } @Test public void setNull() { editor.setAsText(null); - assertThat(editor.getAsText()).as("Setting null did not result in empty value string").isEqualTo(EMPTY); + assertThat(editor.getAsText()).as("Setting null did not result in empty value string").isEmpty(); } @Test public void setEmpty() { editor.setAsText(EMPTY); - assertThat(editor.getAsText()).as("Setting empty string did not result in empty value string").isEqualTo(EMPTY); + assertThat(editor.getAsText()).as("Setting empty string did not result in empty value string").isEmpty(); } @Test public void allWhitespace() { editor.setAsText(" "); - assertThat(editor.getAsText()).as("All whitespace was not recognized").isEqualTo(EMPTY); + assertThat(editor.getAsText()).as("All whitespace was not recognized").isEmpty(); } @Test 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 c38def86e2d..31426b1f6be 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ public class QuartzSchedulerLifecycleTests { sw.start("lazyScheduler"); context.close(); sw.stop(); - assertThat(sw.getTotalTimeMillis() < 500).as("Quartz Scheduler with lazy-init is hanging on destruction: " + - sw.getTotalTimeMillis()).isTrue(); + assertThat(sw.getTotalTimeMillis()).as("Quartz Scheduler with lazy-init is hanging on destruction: " + + sw.getTotalTimeMillis()).isLessThan(500); } @Test // SPR-6354 @@ -52,8 +52,8 @@ public class QuartzSchedulerLifecycleTests { sw.start("lazyScheduler"); context.close(); sw.stop(); - assertThat(sw.getTotalTimeMillis() < 500).as("Quartz Scheduler with lazy-init is hanging on destruction: " + - sw.getTotalTimeMillis()).isTrue(); + assertThat(sw.getTotalTimeMillis()).as("Quartz Scheduler with lazy-init is hanging on destruction: " + + sw.getTotalTimeMillis()).isLessThan(500); } } 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 17773898587..162fa930bc0 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 @@ -126,7 +126,7 @@ class QuartzSupportTests { bean.start(); Thread.sleep(500); - assertThat(DummyJob.count > 0).as("DummyJob should have been executed at least once.").isTrue(); + assertThat(DummyJob.count).as("DummyJob should have been executed at least once.").isGreaterThan(0); assertThat(taskExecutor.count).isEqualTo(DummyJob.count); bean.destroy(); @@ -168,7 +168,7 @@ class QuartzSupportTests { Thread.sleep(500); assertThat(DummyJobBean.param).isEqualTo(10); - assertThat(DummyJobBean.count > 0).isTrue(); + assertThat(DummyJobBean.count).isGreaterThan(0); bean.destroy(); } @@ -203,7 +203,7 @@ class QuartzSupportTests { Thread.sleep(500); assertThat(DummyJob.param).isEqualTo(10); - assertThat(DummyJob.count > 0).as("DummyJob should have been executed at least once.").isTrue(); + assertThat(DummyJob.count).as("DummyJob should have been executed at least once.").isGreaterThan(0); bean.destroy(); } @@ -239,7 +239,7 @@ class QuartzSupportTests { Thread.sleep(500); assertThat(DummyJob.param).isEqualTo(0); - assertThat(DummyJob.count == 0).isTrue(); + assertThat(DummyJob.count).isEqualTo(0); bean.destroy(); } @@ -273,7 +273,7 @@ class QuartzSupportTests { Thread.sleep(500); assertThat(DummyJobBean.param).isEqualTo(10); - assertThat(DummyJobBean.count > 0).isTrue(); + assertThat(DummyJobBean.count).isGreaterThan(0); bean.destroy(); } @@ -292,7 +292,7 @@ class QuartzSupportTests { Thread.sleep(500); assertThat(DummyJob.param).isEqualTo(10); - assertThat(DummyJob.count > 0).as("DummyJob should have been executed at least once.").isTrue(); + assertThat(DummyJob.count).as("DummyJob should have been executed at least once.").isGreaterThan(0); bean.destroy(); } 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 e2feef5047b..2a65204fa80 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,9 @@ class ProceedTests { @Test void testProceedWithArgsInSameAspect() { this.testBean.setMyFloat(1.0F); - 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(); + assertThat(this.testBean.getMyFloat()).as("value changed in around advice").isGreaterThan(1.9F); + assertThat(this.firstTestAspect.getLastBeforeFloatValue()).as("changed value visible to next advice in chain") + .isGreaterThan(1.9F); } @Test 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 dcfcd95fae2..e87949928e6 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 @@ -258,7 +258,7 @@ class AspectJAutoProxyCreatorTests { AdviceUsingThisJoinPoint aspectInstance = (AdviceUsingThisJoinPoint) bf.getBean("aspect"); //(AdviceUsingThisJoinPoint) Aspects.aspectOf(AdviceUsingThisJoinPoint.class); //assertEquals("method-execution(int TestBean.getAge())",aspectInstance.getLastMethodEntered()); - assertThat(aspectInstance.getLastMethodEntered().indexOf("TestBean.getAge())") != 0).isTrue(); + assertThat(aspectInstance.getLastMethodEntered()).doesNotStartWith("TestBean.getAge())"); } @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 27f84180819..df5d587e6a5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -129,7 +129,7 @@ class BenchmarkTests { assertThat(AopUtils.isAopProxy(adrian)).isTrue(); Advised a = (Advised) adrian; - assertThat(a.getAdvisors().length >= 3).isTrue(); + assertThat(a.getAdvisors()).hasSizeGreaterThanOrEqualTo(3); assertThat(adrian.getName()).isEqualTo("adrian"); for (int i = 0; i < howmany; i++) { @@ -151,7 +151,7 @@ class BenchmarkTests { assertThat(AopUtils.isAopProxy(adrian)).isTrue(); Advised a = (Advised) adrian; - assertThat(a.getAdvisors().length >= 3).isTrue(); + assertThat(a.getAdvisors()).hasSizeGreaterThanOrEqualTo(3); // Hits joinpoint adrian.setAge(25); @@ -174,7 +174,7 @@ class BenchmarkTests { assertThat(AopUtils.isAopProxy(adrian)).isTrue(); Advised a = (Advised) adrian; - assertThat(a.getAdvisors().length >= 3).isTrue(); + assertThat(a.getAdvisors()).hasSizeGreaterThanOrEqualTo(3); for (int i = 0; i < howmany; i++) { // Hit all 3 joinpoints 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 b3bf1ed0485..4f6faf2d26a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,7 @@ public class AopNamespaceHandlerTests { Advised advised = (Advised) bean; Advisor[] advisors = advised.getAdvisors(); - assertThat(advisors.length > 0).as("Advisors should not be empty").isTrue(); + assertThat(advisors).as("Advisors should not be empty").isNotEmpty(); } @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 698a0563126..193d58451ec 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 @@ -195,14 +195,14 @@ public abstract class AbstractAopProxyTests { Person p = (Person) createAopProxy(pf).getProxy(); p.echo(null); - assertThat(cta.getCalls()).isEqualTo(0); + assertThat(cta.getCalls()).isZero(); try { p.echo(new IOException()); } catch (IOException ex) { /* expected */ } - assertThat(cta.getCalls()).isEqualTo(1); + assertThat(cta.getCalls()).isOne(); // Will throw exception if it fails Person p2 = SerializationTestUtils.serializeAndDeserialize(p); @@ -214,7 +214,7 @@ public abstract class AbstractAopProxyTests { Advised a1 = (Advised) p; Advised a2 = (Advised) p2; // Check we can manipulate state of p2 - assertThat(a2.getAdvisors()).hasSize(a1.getAdvisors().length); + assertThat(a2.getAdvisors()).hasSameSizeAs(a1.getAdvisors()); // This should work as SerializablePerson is equal assertThat(p2).as("Proxies should be equal, even after one was serialized").isEqualTo(p); @@ -590,7 +590,7 @@ public abstract class AbstractAopProxyTests { t.setName(null); // Null replacement magic should work - assertThat(t.getName()).isEqualTo(""); + assertThat(t.getName()).isEmpty(); } @Test @@ -607,7 +607,7 @@ public abstract class AbstractAopProxyTests { assertThat(di.getCount()).isEqualTo(2); Advised advised = (Advised) t; - assertThat(advised.getAdvisors().length).as("Have 1 advisor").isEqualTo(1); + assertThat(advised.getAdvisors()).as("Have 1 advisor").hasSize(1); assertThat(advised.getAdvisors()[0].getAdvice()).isEqualTo(di); NopInterceptor di2 = new NopInterceptor(); advised.addAdvice(1, di2); @@ -814,7 +814,7 @@ public abstract class AbstractAopProxyTests { HashMap h = new HashMap<>(); Object value1 = "foo"; Object value2 = "bar"; - assertThat(h.get(proxy1)).isNull(); + assertThat(h).doesNotContainKey(proxy1); h.put(proxy1, value1); h.put(proxy2, value2); assertThat(value1).isEqualTo(h.get(proxy1)); @@ -836,8 +836,8 @@ public abstract class AbstractAopProxyTests { ITestBean proxied = (ITestBean) createProxy(pc); String proxyConfigString = ((Advised) proxied).toProxyConfigString(); - assertThat(proxyConfigString.contains(advisor.toString())).isTrue(); - assertThat(proxyConfigString.contains("1 interface")).isTrue(); + assertThat(proxyConfigString).contains(advisor.toString()); + assertThat(proxyConfigString).contains("1 interface"); } @Test @@ -914,24 +914,24 @@ public abstract class AbstractAopProxyTests { NopInterceptor nop = new NopInterceptor(); pc.addAdvice(nop); ITestBean proxy = (ITestBean) createProxy(pc); - assertThat(0).isEqualTo(nop.getCount()); + assertThat(nop.getCount()).isZero(); assertThat(proxy.getAge()).isEqualTo(tb1.getAge()); - assertThat(1).isEqualTo(nop.getCount()); + assertThat(nop.getCount()).isOne(); // Change to a new static target pc.setTarget(tb2); assertThat(proxy.getAge()).isEqualTo(tb2.getAge()); - assertThat(2).isEqualTo(nop.getCount()); + assertThat(nop.getCount()).isEqualTo(2); // Change to a new dynamic target HotSwappableTargetSource hts = new HotSwappableTargetSource(tb3); pc.setTargetSource(hts); assertThat(proxy.getAge()).isEqualTo(tb3.getAge()); - assertThat(3).isEqualTo(nop.getCount()); + assertThat(nop.getCount()).isEqualTo(3); hts.swap(tb1); assertThat(proxy.getAge()).isEqualTo(tb1.getAge()); tb1.setName("Colin"); assertThat(proxy.getName()).isEqualTo(tb1.getName()); - assertThat(5).isEqualTo(nop.getCount()); + assertThat(nop.getCount()).isEqualTo(5); // Change back, relying on casting to Advised Advised advised = (Advised) proxy; @@ -993,12 +993,12 @@ public abstract class AbstractAopProxyTests { pc.addAdvisor(sp); pc.setTarget(tb); ITestBean it = (ITestBean) createProxy(pc); - assertThat(0).isEqualTo(di.getCount()); + assertThat(di.getCount()).isEqualTo(0); it.getAge(); - assertThat(1).isEqualTo(di.getCount()); + assertThat(di.getCount()).isEqualTo(1); it.setAge(11); - assertThat(11).isEqualTo(it.getAge()); - assertThat(2).isEqualTo(di.getCount()); + assertThat(it.getAge()).isEqualTo(11); + assertThat(di.getCount()).isEqualTo(2); } /** @@ -1173,7 +1173,7 @@ public abstract class AbstractAopProxyTests { IOther proxyA = (IOther) createProxy(pfa); IOther proxyB = (IOther) createProxy(pfb); - assertThat(pfb.getAdvisors()).hasSize(pfa.getAdvisors().length); + assertThat(pfb.getAdvisors()).hasSameSizeAs(pfa.getAdvisors()); assertThat(b).isEqualTo(a); assertThat(i2).isEqualTo(i1); assertThat(proxyB).isEqualTo(proxyA); 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 c2ffd4706ca..047974b454b 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 @@ -136,8 +136,8 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab Object proxy = aop.getProxy(); assertThat(AopUtils.isCglibProxy(proxy)).isTrue(); - assertThat(proxy instanceof ITestBean).isTrue(); - assertThat(proxy instanceof TestBean).isTrue(); + assertThat(proxy).isInstanceOf(ITestBean.class); + assertThat(proxy).isInstanceOf(TestBean.class); TestBean tb = (TestBean) proxy; assertThat(tb.getAge()).isEqualTo(32); @@ -312,7 +312,7 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab cglib = new CglibAopProxy(as); ITestBean proxy2 = (ITestBean) cglib.getProxy(); - assertThat(proxy2 instanceof Serializable).isTrue(); + assertThat(proxy2).isInstanceOf(Serializable.class); } @Test @@ -331,7 +331,7 @@ public class CglibProxyTests extends AbstractAopProxyTests implements Serializab proxy.doTest(); } catch (Exception ex) { - assertThat(ex instanceof ApplicationContextException).as("Invalid exception class").isTrue(); + assertThat(ex).as("Invalid exception class").isInstanceOf(ApplicationContextException.class); } assertThat(proxy.isCatchInvoked()).as("Catch was not invoked").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 8e0159f9eb8..1ec383a4689 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -167,7 +167,7 @@ public class ProxyFactoryBeanTests { assertThat(cba.getCalls()).isEqualTo(0); ITestBean tb = (ITestBean) bf.getBean("directTarget"); - assertThat(tb.getName().equals("Adam")).isTrue(); + assertThat(tb.getName()).isEqualTo("Adam"); assertThat(cba.getCalls()).isEqualTo(1); ProxyFactoryBean pfb = (ProxyFactoryBean) bf.getBean("&directTarget"); @@ -179,7 +179,7 @@ public class ProxyFactoryBeanTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(TARGETSOURCE_CONTEXT, CLASS)); ITestBean tb = (ITestBean) bf.getBean("viaTargetSource"); - assertThat(tb.getName().equals("Adam")).isTrue(); + assertThat(tb.getName()).isEqualTo("Adam"); ProxyFactoryBean pfb = (ProxyFactoryBean) bf.getBean("&viaTargetSource"); assertThat(TestBean.class.isAssignableFrom(pfb.getObjectType())).as("Has correct object type").isTrue(); } @@ -219,10 +219,10 @@ public class ProxyFactoryBeanTests { pc1.addAdvice(1, di); assertThat(pc2.getAdvisors()).isEqualTo(pc1.getAdvisors()); assertThat(pc2.getAdvisors().length).as("Now have one more advisor").isEqualTo((oldLength + 1)); - assertThat(0).isEqualTo(di.getCount()); + assertThat(di.getCount()).isEqualTo(0); test1.setAge(5); assertThat(test1.getAge()).isEqualTo(test1_1.getAge()); - assertThat(3).isEqualTo(di.getCount()); + assertThat(di.getCount()).isEqualTo(3); } @Test @@ -230,8 +230,8 @@ public class ProxyFactoryBeanTests { 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"); - assertThat(test2 != test2_1).as("Prototype instances !=").isTrue(); - assertThat(test2.equals(test2_1)).as("Prototype instances equal").isTrue(); + assertThat(test2).as("Prototype instances !=").isNotSameAs(test2_1); + assertThat(test2).as("Prototype instances equal").isEqualTo(test2_1); assertThat(ITestBean.class.isAssignableFrom(factory.getType("prototype"))).as("Has correct object type").isTrue(); } @@ -262,7 +262,7 @@ public class ProxyFactoryBeanTests { assertThat(prototype2FirstInstance.getCount()).isEqualTo(INITIAL_COUNT + 1); SideEffectBean prototype2SecondInstance = (SideEffectBean) bf.getBean(beanName); - assertThat(prototype2FirstInstance == prototype2SecondInstance).as("Prototypes are not ==").isFalse(); + assertThat(prototype2FirstInstance).as("Prototypes are not ==").isNotSameAs(prototype2SecondInstance); assertThat(prototype2SecondInstance.getCount()).isEqualTo(INITIAL_COUNT); assertThat(prototype2FirstInstance.getCount()).isEqualTo(INITIAL_COUNT + 1); @@ -285,7 +285,7 @@ public class ProxyFactoryBeanTests { TestBean target = (TestBean) factory.getBean("test"); target.setName(name); ITestBean autoInvoker = (ITestBean) factory.getBean("autoInvoker"); - assertThat(autoInvoker.getName().equals(name)).isTrue(); + assertThat(autoInvoker.getName()).isEqualTo(name); } @Test @@ -308,7 +308,7 @@ public class ProxyFactoryBeanTests { config.addAdvice(0, (MethodInterceptor) invocation -> { throw ex; }); - assertThat(config.getAdvisors().length).as("Have correct advisor count").isEqualTo(2); + assertThat(config.getAdvisors()).as("Have correct advisor count").hasSize(2); ITestBean tb1 = (ITestBean) factory.getBean("test1"); assertThatException() @@ -348,31 +348,31 @@ public class ProxyFactoryBeanTests { // Add to head of interceptor chain int oldCount = config.getAdvisors().length; config.addAdvisor(0, new DefaultIntroductionAdvisor(ti, TimeStamped.class)); - assertThat(config.getAdvisors().length == oldCount + 1).isTrue(); + assertThat(config.getAdvisors()).hasSize(oldCount + 1); TimeStamped ts = (TimeStamped) factory.getBean("test2"); assertThat(ts.getTimeStamp()).isEqualTo(time); // Can remove config.removeAdvice(ti); - assertThat(config.getAdvisors().length == oldCount).isTrue(); + assertThat(config.getAdvisors()).hasSize(oldCount); // Check no change on existing object reference - assertThat(ts.getTimeStamp() == time).isTrue(); + assertThat(ts.getTimeStamp()).isEqualTo(time); 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()); - assertThat(config.getAdvisors().length == oldCount).isTrue(); + assertThat(config.getAdvisors()).hasSize(oldCount); ITestBean it = (ITestBean) ts; DebugInterceptor debugInterceptor = new DebugInterceptor(); config.addAdvice(0, debugInterceptor); it.getSpouse(); // Won't affect existing reference - assertThat(debugInterceptor.getCount() == 0).isTrue(); + assertThat(debugInterceptor.getCount()).isEqualTo(0); it = (ITestBean) factory.getBean("test2"); it.getSpouse(); assertThat(debugInterceptor.getCount()).isEqualTo(1); @@ -412,16 +412,16 @@ public class ProxyFactoryBeanTests { public void testMethodPointcuts() { ITestBean tb = (ITestBean) factory.getBean("pointcuts"); PointcutForVoid.reset(); - assertThat(PointcutForVoid.methodNames.isEmpty()).as("No methods intercepted").isTrue(); + assertThat(PointcutForVoid.methodNames).as("No methods intercepted").isEmpty(); tb.getAge(); - assertThat(PointcutForVoid.methodNames.isEmpty()).as("Not void: shouldn't have intercepted").isTrue(); + assertThat(PointcutForVoid.methodNames).as("Not void: shouldn't have intercepted").isEmpty(); tb.setAge(1); tb.getAge(); tb.setName("Tristan"); tb.toString(); - 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(); + assertThat(PointcutForVoid.methodNames).as("Recorded wrong number of invocations").hasSize(2); + assertThat(PointcutForVoid.methodNames.get(0)).isEqualTo("setAge"); + assertThat(PointcutForVoid.methodNames.get(1)).isEqualTo("setName"); } @Test @@ -498,17 +498,17 @@ public class ProxyFactoryBeanTests { @Test public void testGlobalsCanAddAspectInterfaces() { AddedGlobalInterface agi = (AddedGlobalInterface) factory.getBean("autoInvoker"); - assertThat(agi.globalsAdded() == -1).isTrue(); + assertThat(agi.globalsAdded()).isEqualTo(-1); ProxyFactoryBean pfb = (ProxyFactoryBean) factory.getBean("&validGlobals"); // Trigger lazy initialization. pfb.getObject(); // 2 globals + 2 explicit - assertThat(pfb.getAdvisors().length).as("Have 2 globals and 2 explicit advisors").isEqualTo(3); + assertThat(pfb.getAdvisors()).as("Have 2 globals and 2 explicit advisors").hasSize(3); ApplicationListener l = (ApplicationListener) factory.getBean("validGlobals"); agi = (AddedGlobalInterface) l; - assertThat(agi.globalsAdded() == -1).isTrue(); + assertThat(agi.globalsAdded()).isEqualTo(-1); assertThat(factory.getBean("test1")).as("Aspect interface shouldn't be implemented without globals") .isNotInstanceOf(AddedGlobalInterface.class); 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 8a111ebd452..de560cbf8ea 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -202,7 +202,7 @@ public class AdvisorAutoProxyCreatorTests { ITestBean test2 = (ITestBean) bf.getBean("!test"); - assertThat(test == test2).as("Prototypes cannot be the same object").isFalse(); + assertThat(test).as("Prototypes cannot be the same object").isNotSameAs(test2); assertThat(test2.getName()).isEqualTo("Rod"); assertThat(test2.getSpouse().getName()).isEqualTo("Kerry"); bf.close(); 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 051f9bdae57..d42775bd2ad 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -141,10 +141,10 @@ class XmlBeanFactoryTests { TestBean georgia = (TestBean) xbf.getBean("georgia"); ITestBean emmasJenks = emma.getSpouse(); ITestBean georgiasJenks = georgia.getSpouse(); - 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(georgiasJenks.getName().equals("Andrew")).as("Georgias jenks has right name").isTrue(); + assertThat(emmasJenks).as("Emma and georgia think they have a different boyfriend").isNotSameAs(georgiasJenks); + assertThat(emmasJenks.getName()).as("Emmas jenks has right name").isEqualTo("Andrew"); + assertThat(emmasJenks).as("Emmas doesn't equal new ref").isNotSameAs(xbf.getBean("jenks")); + assertThat(georgiasJenks.getName()).as("Georgias jenks has right name").isEqualTo("Andrew"); assertThat(emmasJenks.equals(georgiasJenks)).as("They are object equal").isTrue(); assertThat(emmasJenks.equals(xbf.getBean("jenks"))).as("They object equal direct ref").isTrue(); } @@ -161,8 +161,8 @@ class XmlBeanFactoryTests { TestBean jenks = (TestBean) xbf.getBean("jenks"); ITestBean davesJen = dave.getSpouse(); ITestBean jenksJen = jenks.getSpouse(); - assertThat(davesJen == jenksJen).as("1 jen instance").isTrue(); - assertThat(davesJen == jen).as("1 jen instance").isTrue(); + assertThat(davesJen).as("1 jen instance").isSameAs(jenksJen); + assertThat(davesJen).as("1 jen instance").isSameAs(jen); } @Test @@ -193,7 +193,7 @@ class XmlBeanFactoryTests { assertThat(friends).hasSize(3); DerivedTestBean inner2 = (DerivedTestBean) friends[0]; assertThat(inner2.getName()).isEqualTo("inner2"); - assertThat(inner2.getBeanName().startsWith(DerivedTestBean.class.getName())).isTrue(); + assertThat(inner2.getBeanName()).startsWith(DerivedTestBean.class.getName()); assertThat(xbf.containsBean("innerBean#1")).isFalse(); assertThat(inner2).isNotNull(); assertThat(inner2.getAge()).isEqualTo(7); @@ -235,7 +235,7 @@ class XmlBeanFactoryTests { xbf.destroySingletons(); assertThat(inner1.wasDestroyed()).isTrue(); assertThat(inner2.wasDestroyed()).isTrue(); - assertThat(innerFactory.getName() == null).isTrue(); + assertThat(innerFactory.getName()).isNull(); assertThat(inner5.wasDestroyed()).isTrue(); } @@ -255,7 +255,7 @@ class XmlBeanFactoryTests { assertThat(hasInnerBeans.getAge()).isEqualTo(5); TestBean inner1 = (TestBean) hasInnerBeans.getSpouse(); assertThat(inner1).isNotNull(); - assertThat(inner1.getBeanName().startsWith("innerBean")).isTrue(); + assertThat(inner1.getBeanName()).startsWith("innerBean"); assertThat(inner1.getName()).isEqualTo("inner1"); assertThat(inner1.getAge()).isEqualTo(6); @@ -264,13 +264,13 @@ class XmlBeanFactoryTests { assertThat(friends).hasSize(3); DerivedTestBean inner2 = (DerivedTestBean) friends[0]; assertThat(inner2.getName()).isEqualTo("inner2"); - assertThat(inner2.getBeanName().startsWith(DerivedTestBean.class.getName())).isTrue(); + assertThat(inner2.getBeanName()).startsWith(DerivedTestBean.class.getName()); assertThat(inner2).isNotNull(); assertThat(inner2.getAge()).isEqualTo(7); TestBean innerFactory = (TestBean) friends[1]; assertThat(innerFactory.getName()).isEqualTo(DummyFactory.SINGLETON_NAME); TestBean inner5 = (TestBean) friends[2]; - assertThat(inner5.getBeanName().startsWith("innerBean")).isTrue(); + assertThat(inner5.getBeanName()).startsWith("innerBean"); } @Test @@ -286,8 +286,8 @@ class XmlBeanFactoryTests { catch (BeanCreationException ex) { // Check whether message contains outer bean name. ex.printStackTrace(); - assertThat(ex.getMessage().contains("failsOnInnerBean")).isTrue(); - assertThat(ex.getMessage().contains("someMap")).isTrue(); + assertThat(ex.getMessage()).contains("failsOnInnerBean"); + assertThat(ex.getMessage()).contains("someMap"); } try { @@ -296,8 +296,8 @@ class XmlBeanFactoryTests { catch (BeanCreationException ex) { // Check whether message contains outer bean name. ex.printStackTrace(); - assertThat(ex.getMessage().contains("failsOnInnerBeanForConstructor")).isTrue(); - assertThat(ex.getMessage().contains("constructor argument")).isTrue(); + assertThat(ex.getMessage()).contains("failsOnInnerBeanForConstructor"); + assertThat(ex.getMessage()).contains("constructor argument"); } } @@ -310,11 +310,11 @@ class XmlBeanFactoryTests { assertThat(child.getType("inheritsFromParentFactory")).isEqualTo(TestBean.class); TestBean inherits = (TestBean) child.getBean("inheritsFromParentFactory"); // Name property value is overridden - assertThat(inherits.getName().equals("override")).isTrue(); + assertThat(inherits.getName()).isEqualTo("override"); // Age property is inherited from bean in parent factory - assertThat(inherits.getAge() == 1).isTrue(); + assertThat(inherits.getAge()).isEqualTo(1); TestBean inherits2 = (TestBean) child.getBean("inheritsFromParentFactory"); - assertThat(inherits2 == inherits).isFalse(); + assertThat(inherits2).isNotSameAs(inherits); } @Test @@ -326,9 +326,9 @@ class XmlBeanFactoryTests { assertThat(child.getType("inheritsWithClass")).isEqualTo(DerivedTestBean.class); DerivedTestBean inherits = (DerivedTestBean) child.getBean("inheritsWithDifferentClass"); // Name property value is overridden - assertThat(inherits.getName().equals("override")).isTrue(); + assertThat(inherits.getName()).isEqualTo("override"); // Age property is inherited from bean in parent factory - assertThat(inherits.getAge() == 1).isTrue(); + assertThat(inherits.getAge()).isEqualTo(1); assertThat(inherits.wasInitialized()).isTrue(); } @@ -341,9 +341,9 @@ class XmlBeanFactoryTests { assertThat(child.getType("inheritsWithClass")).isEqualTo(DerivedTestBean.class); DerivedTestBean inherits = (DerivedTestBean) child.getBean("inheritsWithClass"); // Name property value is overridden - assertThat(inherits.getName().equals("override")).isTrue(); + assertThat(inherits.getName()).isEqualTo("override"); // Age property is inherited from bean in parent factory - assertThat(inherits.getAge() == 1).isTrue(); + assertThat(inherits.getAge()).isEqualTo(1); assertThat(inherits.wasInitialized()).isTrue(); } @@ -356,15 +356,15 @@ class XmlBeanFactoryTests { assertThat(child.getType("prototypeInheritsFromParentFactoryPrototype")).isEqualTo(TestBean.class); TestBean inherits = (TestBean) child.getBean("prototypeInheritsFromParentFactoryPrototype"); // Name property value is overridden - assertThat(inherits.getName().equals("prototype-override")).isTrue(); + assertThat(inherits.getName()).isEqualTo("prototype-override"); // Age property is inherited from bean in parent factory - assertThat(inherits.getAge() == 2).isTrue(); + assertThat(inherits.getAge()).isEqualTo(2); TestBean inherits2 = (TestBean) child.getBean("prototypeInheritsFromParentFactoryPrototype"); - assertThat(inherits2 == inherits).isFalse(); + assertThat(inherits2).isNotSameAs(inherits); inherits2.setAge(13); - assertThat(inherits2.getAge() == 13).isTrue(); + assertThat(inherits2.getAge()).isEqualTo(13); // Shouldn't have changed first instance - assertThat(inherits.getAge() == 2).isTrue(); + assertThat(inherits.getAge()).isEqualTo(2); } @Test @@ -375,15 +375,15 @@ class XmlBeanFactoryTests { new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); TestBean inherits = (TestBean) child.getBean("protoypeInheritsFromParentFactorySingleton"); // Name property value is overridden - assertThat(inherits.getName().equals("prototypeOverridesInheritedSingleton")).isTrue(); + assertThat(inherits.getName()).isEqualTo("prototypeOverridesInheritedSingleton"); // Age property is inherited from bean in parent factory - assertThat(inherits.getAge() == 1).isTrue(); + assertThat(inherits.getAge()).isEqualTo(1); TestBean inherits2 = (TestBean) child.getBean("protoypeInheritsFromParentFactorySingleton"); - assertThat(inherits2 == inherits).isFalse(); + assertThat(inherits2).isNotSameAs(inherits); inherits2.setAge(13); - assertThat(inherits2.getAge() == 13).isTrue(); + assertThat(inherits2.getAge()).isEqualTo(13); // Shouldn't have changed first instance - assertThat(inherits.getAge() == 1).isTrue(); + assertThat(inherits.getAge()).isEqualTo(1); } @Test @@ -419,7 +419,7 @@ class XmlBeanFactoryTests { parent.getBean("inheritedTestBeanWithoutClass")); // non-abstract bean should work, even if it serves as parent - assertThat(parent.getBean("inheritedTestBeanPrototype") instanceof TestBean).isTrue(); + assertThat(parent.getBean("inheritedTestBeanPrototype")).isInstanceOf(TestBean.class); } @Test @@ -438,7 +438,7 @@ class XmlBeanFactoryTests { DummyBoImpl bos = (DummyBoImpl) xbf.getBean("boSingleton"); DummyBoImpl bop = (DummyBoImpl) xbf.getBean("boPrototype"); assertThat(bop).isNotSameAs(bos); - assertThat(bos.dao == bop.dao).isTrue(); + assertThat(bos.dao).isSameAs(bop.dao); } @Test @@ -449,11 +449,11 @@ class XmlBeanFactoryTests { new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); TestBean inherits = (TestBean) child.getBean("inheritedTestBean"); // Name property value is overridden - assertThat(inherits.getName().equals("overrideParentBean")).isTrue(); + assertThat(inherits.getName()).isEqualTo("overrideParentBean"); // Age property is inherited from bean in parent factory - assertThat(inherits.getAge() == 1).isTrue(); + assertThat(inherits.getAge()).isEqualTo(1); TestBean inherits2 = (TestBean) child.getBean("inheritedTestBean"); - assertThat(inherits2 != inherits).isTrue(); + assertThat(inherits2).isNotSameAs(inherits); } /** @@ -485,11 +485,11 @@ class XmlBeanFactoryTests { new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); TestBean inherits = (TestBean) child.getBean("singletonInheritsFromParentFactoryPrototype"); // Name property value is overridden - assertThat(inherits.getName().equals("prototype-override")).isTrue(); + assertThat(inherits.getName()).isEqualTo("prototype-override"); // Age property is inherited from bean in parent factory - assertThat(inherits.getAge() == 2).isTrue(); + assertThat(inherits.getAge()).isEqualTo(2); TestBean inherits2 = (TestBean) child.getBean("singletonInheritsFromParentFactoryPrototype"); - assertThat(inherits2 == inherits).isTrue(); + assertThat(inherits2).isSameAs(inherits); } @Test @@ -500,7 +500,7 @@ class XmlBeanFactoryTests { DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT); TestBean beanFromChild = (TestBean) child.getBean("inheritedTestBeanSingleton"); - assertThat(beanFromParent == beanFromChild).as("singleton from parent and child is the same").isTrue(); + assertThat(beanFromParent).as("singleton from parent and child is the same").isSameAs(beanFromChild); } @Test @@ -524,11 +524,11 @@ class XmlBeanFactoryTests { TestBean ego = (TestBean) xbf.getBean("ego"); TestBean complexInnerEgo = (TestBean) xbf.getBean("complexInnerEgo"); TestBean complexEgo = (TestBean) xbf.getBean("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(); + assertThat(jenny.getSpouse()).as("Correct circular reference").isSameAs(david); + assertThat(david.getSpouse()).as("Correct circular reference").isSameAs(jenny); + assertThat(ego.getSpouse()).as("Correct circular reference").isSameAs(ego); + assertThat(complexInnerEgo.getSpouse().getSpouse()).as("Correct circular reference").isSameAs(complexInnerEgo); + assertThat(complexEgo.getSpouse().getSpouse()).as("Correct circular reference").isSameAs(complexEgo); } @Test @@ -579,7 +579,7 @@ class XmlBeanFactoryTests { reader.loadBeanDefinitions(REFTYPES_CONTEXT); xbf.getBean("egoBridge"); TestBean complexEgo = (TestBean) xbf.getBean("complexEgo"); - assertThat(complexEgo.getSpouse().getSpouse() == complexEgo).as("Correct circular reference").isTrue(); + assertThat(complexEgo.getSpouse().getSpouse()).as("Correct circular reference").isSameAs(complexEgo); } @Test @@ -589,9 +589,9 @@ class XmlBeanFactoryTests { reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); reader.loadBeanDefinitions(REFTYPES_CONTEXT); TestBean ego1 = (TestBean) xbf.getBean("ego1"); - assertThat(ego1.getSpouse().getSpouse() == ego1).as("Correct circular reference").isTrue(); + assertThat(ego1.getSpouse().getSpouse()).as("Correct circular reference").isSameAs(ego1); TestBean ego3 = (TestBean) xbf.getBean("ego3"); - assertThat(ego3.getSpouse().getSpouse() == ego3).as("Correct circular reference").isTrue(); + assertThat(ego3.getSpouse().getSpouse()).as("Correct circular reference").isSameAs(ego3); } @Test @@ -636,7 +636,7 @@ class XmlBeanFactoryTests { assertThat(david.getSpouse().getName()).isEqualTo("Jenny"); assertThat(david.getSpouse().getSpouse()).isSameAs(david); assertThat(AopUtils.isAopProxy(jenny.getSpouse())).isTrue(); - assertThat(!AopUtils.isAopProxy(david.getSpouse())).isTrue(); + assertThat(AopUtils.isAopProxy(david.getSpouse())).isFalse(); } @Test @@ -645,7 +645,7 @@ class XmlBeanFactoryTests { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(FACTORY_CIRCLE_CONTEXT); TestBean tb = (TestBean) xbf.getBean("singletonFactory"); DummyFactory db = (DummyFactory) xbf.getBean("&singletonFactory"); - assertThat(tb == db.getOtherTestBean()).isTrue(); + assertThat(tb).isSameAs(db.getOtherTestBean()); } @Test @@ -765,7 +765,7 @@ class XmlBeanFactoryTests { xbf.getBean("lazy-and-bad"); } catch (BeanCreationException ex) { - assertThat(ex.getCause() instanceof IOException).isTrue(); + assertThat(ex.getCause()).isInstanceOf(IOException.class); } } @@ -857,12 +857,12 @@ class XmlBeanFactoryTests { DependenciesBean rod1 = (DependenciesBean) xbf.getBean("rod1"); // should have been autowired assertThat(rod1.getSpouse()).isNotNull(); - assertThat(rod1.getSpouse().getName().equals("Kerry")).isTrue(); + assertThat(rod1.getSpouse().getName()).isEqualTo("Kerry"); DependenciesBean rod2 = (DependenciesBean) xbf.getBean("rod2"); // should have been autowired assertThat(rod2.getSpouse()).isNotNull(); - assertThat(rod2.getSpouse().getName().equals("Kerry")).isTrue(); + assertThat(rod2.getSpouse().getName()).isEqualTo("Kerry"); } @Test @@ -922,7 +922,7 @@ class XmlBeanFactoryTests { DerivedConstructorDependenciesBean rod6 = (DerivedConstructorDependenciesBean) xbf.getBean("rod6"); // should have been autowired assertThat(rod6.initialized).isTrue(); - assertThat(!rod6.destroyed).isTrue(); + assertThat(rod6.destroyed).isFalse(); assertThat(rod6.getSpouse1()).isEqualTo(kerry2); assertThat(rod6.getSpouse2()).isEqualTo(kerry1); assertThat(rod6.getOther()).isEqualTo(other); @@ -943,7 +943,7 @@ class XmlBeanFactoryTests { } catch (BeanCreationException ex) { ex.printStackTrace(); - assertThat(ex.toString().contains("touchy")).isTrue(); + assertThat(ex.toString()).contains("touchy"); assertThat((Object) ex.getRelatedCauses()).isNull(); } } @@ -1144,7 +1144,7 @@ class XmlBeanFactoryTests { // comes from "resource.xml" ResourceTestBean resource2 = (ResourceTestBean) xbf.getBean("resource2"); - assertThat(resource1.getResource() instanceof ClassPathResource).isTrue(); + assertThat(resource1.getResource()).isInstanceOf(ClassPathResource.class); StringWriter writer = new StringWriter(); FileCopyUtils.copy(new InputStreamReader(resource1.getResource().getInputStream()), writer); assertThat(writer.toString()).isEqualTo("test"); @@ -1244,7 +1244,7 @@ class XmlBeanFactoryTests { sw.stop(); // System.out.println(sw); if (!LogFactory.getLog(DefaultListableBeanFactory.class).isDebugEnabled()) { - assertThat(sw.getTotalTimeMillis() < 2000).isTrue(); + assertThat(sw.getTotalTimeMillis()).isLessThan(2000); } // Now test distinct bean with swapped value in factory, to ensure the two are independent @@ -1305,7 +1305,7 @@ class XmlBeanFactoryTests { assertThat(jenny2).isNotSameAs(jenny1); TestBean notJenny = oom.getPrototypeDependency("someParam"); - assertThat(!"Jenny".equals(notJenny.getName())).isTrue(); + assertThat(notJenny.getName()).isNotEqualTo("Jenny"); // Now try protected method, and singleton TestBean dave1 = oom.protectedOverrideSingleton(); @@ -1391,12 +1391,12 @@ class XmlBeanFactoryTests { TestBean jenny1 = (TestBean) xbf.getBean("jennyChild"); assertThat(jenny1.getFriends()).hasSize(1); Object friend1 = jenny1.getFriends().iterator().next(); - assertThat(friend1 instanceof TestBean).isTrue(); + assertThat(friend1).isInstanceOf(TestBean.class); TestBean jenny2 = (TestBean) xbf.getBean("jennyChild"); assertThat(jenny2.getFriends()).hasSize(1); Object friend2 = jenny2.getFriends().iterator().next(); - assertThat(friend2 instanceof TestBean).isTrue(); + assertThat(friend2).isInstanceOf(TestBean.class); assertThat(jenny2).isNotSameAs(jenny1); assertThat(friend2).isNotSameAs(friend1); @@ -1433,8 +1433,8 @@ class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); DoubleBooleanConstructorBean bean = (DoubleBooleanConstructorBean) xbf.getBean("beanWithDoubleBoolean"); - assertThat(bean.boolean1).isEqualTo(Boolean.TRUE); - assertThat(bean.boolean2).isEqualTo(Boolean.FALSE); + assertThat(bean.boolean1).isTrue(); + assertThat(bean.boolean2).isFalse(); } @Test @@ -1442,8 +1442,8 @@ class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); DoubleBooleanConstructorBean bean = (DoubleBooleanConstructorBean) xbf.getBean("beanWithDoubleBooleanAndIndex"); - assertThat(bean.boolean1).isEqualTo(Boolean.FALSE); - assertThat(bean.boolean2).isEqualTo(Boolean.TRUE); + assertThat(bean.boolean1).isFalse(); + assertThat(bean.boolean2).isTrue(); } @Test @@ -1451,7 +1451,7 @@ class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); LenientDependencyTestBean bean = (LenientDependencyTestBean) xbf.getBean("lenientDependencyTestBean"); - assertThat(bean.tb instanceof DerivedTestBean).isTrue(); + assertThat(bean.tb).isInstanceOf(DerivedTestBean.class); } @Test @@ -1459,7 +1459,7 @@ class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); LenientDependencyTestBean bean = (LenientDependencyTestBean) xbf.getBean("lenientDependencyTestBeanFactoryMethod"); - assertThat(bean.tb instanceof DerivedTestBean).isTrue(); + assertThat(bean.tb).isInstanceOf(DerivedTestBean.class); } @Test @@ -1509,7 +1509,7 @@ class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); ConstructorArrayTestBean bean = (ConstructorArrayTestBean) xbf.getBean("constructorArray"); - assertThat(bean.array instanceof int[]).isTrue(); + assertThat(bean.array).isInstanceOf(int[].class); assertThat(((int[]) bean.array)).hasSize(1); assertThat(((int[]) bean.array)[0]).isEqualTo(1); } @@ -1519,7 +1519,7 @@ class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); ConstructorArrayTestBean bean = (ConstructorArrayTestBean) xbf.getBean("indexedConstructorArray"); - assertThat(bean.array instanceof int[]).isTrue(); + assertThat(bean.array).isInstanceOf(int[].class); assertThat(((int[]) bean.array)).hasSize(1); assertThat(((int[]) bean.array)[0]).isEqualTo(1); } @@ -1529,7 +1529,7 @@ class XmlBeanFactoryTests { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); ConstructorArrayTestBean bean = (ConstructorArrayTestBean) xbf.getBean("constructorArrayNoType"); - assertThat(bean.array instanceof String[]).isTrue(); + assertThat(bean.array).isInstanceOf(String[].class); assertThat(((String[]) bean.array)).isEmpty(); } @@ -1540,7 +1540,7 @@ class XmlBeanFactoryTests { AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("constructorArrayNoType"); bd.setLenientConstructorResolution(false); ConstructorArrayTestBean bean = (ConstructorArrayTestBean) xbf.getBean("constructorArrayNoType"); - assertThat(bean.array instanceof String[]).isTrue(); + assertThat(bean.array).isInstanceOf(String[].class); assertThat(((String[]) bean.array)).isEmpty(); } 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 a560c423240..f6336a5f51b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,7 +115,7 @@ public class CustomNamespaceHandlerTests { assertTestBean(bean); assertThat(AopUtils.isAopProxy(bean)).isTrue(); Advisor[] advisors = ((Advised) bean).getAdvisors(); - assertThat(advisors.length).as("Incorrect number of advisors").isEqualTo(1); + assertThat(advisors).as("Incorrect number of advisors").hasSize(1); assertThat(advisors[0].getAdvice().getClass()).as("Incorrect advice class").isEqualTo(DebugInterceptor.class); } @@ -136,7 +136,7 @@ public class CustomNamespaceHandlerTests { assertTestBean(bean); assertThat(AopUtils.isAopProxy(bean)).isTrue(); Advisor[] advisors = ((Advised) bean).getAdvisors(); - assertThat(advisors.length).as("Incorrect number of advisors").isEqualTo(2); + assertThat(advisors).as("Incorrect number of advisors").hasSize(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); } 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 7b4911a8b49..48878ef4e18 100644 --- a/spring-context/src/test/java/org/springframework/cache/CacheReproTests.java +++ b/spring-context/src/test/java/org/springframework/cache/CacheReproTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -139,7 +139,7 @@ class CacheReproTests { TestBean tb = new TestBean("tb1"); bean.insertItem(tb); - assertThat(bean.findById("tb1").get()).isSameAs(tb); + assertThat(bean.findById("tb1")).containsSame(tb); assertThat(cache.get("tb1").get()).isSameAs(tb); cache.clear(); 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 43366d5986d..6f78f96b781 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,23 +49,23 @@ public class AnnotationCacheOperationSourceTests { @Test public void singularAnnotation() { Collection ops = getOps(AnnotatedClass.class, "singular", 1); - assertThat(ops.iterator().next() instanceof CacheableOperation).isTrue(); + assertThat(ops.iterator().next()).isInstanceOf(CacheableOperation.class); } @Test public void multipleAnnotation() { Collection ops = getOps(AnnotatedClass.class, "multiple", 2); Iterator it = ops.iterator(); - assertThat(it.next() instanceof CacheableOperation).isTrue(); - assertThat(it.next() instanceof CacheEvictOperation).isTrue(); + assertThat(it.next()).isInstanceOf(CacheableOperation.class); + assertThat(it.next()).isInstanceOf(CacheEvictOperation.class); } @Test public void caching() { Collection ops = getOps(AnnotatedClass.class, "caching", 2); Iterator it = ops.iterator(); - assertThat(it.next() instanceof CacheableOperation).isTrue(); - assertThat(it.next() instanceof CacheEvictOperation).isTrue(); + assertThat(it.next()).isInstanceOf(CacheableOperation.class); + assertThat(it.next()).isInstanceOf(CacheEvictOperation.class); } @Test @@ -76,20 +76,20 @@ public class AnnotationCacheOperationSourceTests { @Test public void singularStereotype() { Collection ops = getOps(AnnotatedClass.class, "singleStereotype", 1); - assertThat(ops.iterator().next() instanceof CacheEvictOperation).isTrue(); + assertThat(ops.iterator().next()).isInstanceOf(CacheEvictOperation.class); } @Test public void multipleStereotypes() { Collection ops = getOps(AnnotatedClass.class, "multipleStereotype", 3); Iterator it = ops.iterator(); - assertThat(it.next() instanceof CacheableOperation).isTrue(); + assertThat(it.next()).isInstanceOf(CacheableOperation.class); CacheOperation next = it.next(); - assertThat(next instanceof CacheEvictOperation).isTrue(); - assertThat(next.getCacheNames().contains("foo")).isTrue(); + assertThat(next).isInstanceOf(CacheEvictOperation.class); + assertThat(next.getCacheNames()).contains("foo"); next = it.next(); - assertThat(next instanceof CacheEvictOperation).isTrue(); - assertThat(next.getCacheNames().contains("bar")).isTrue(); + assertThat(next).isInstanceOf(CacheEvictOperation.class); + assertThat(next.getCacheNames()).contains("bar"); } @Test @@ -100,7 +100,7 @@ public class AnnotationCacheOperationSourceTests { CacheOperation cacheOperation = it.next(); assertThat(cacheOperation).isInstanceOf(CacheableOperation.class); assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("directly declared")); - assertThat(cacheOperation.getKey()).isEqualTo(""); + assertThat(cacheOperation.getKey()).isEmpty(); cacheOperation = it.next(); assertThat(cacheOperation).isInstanceOf(CacheableOperation.class); @@ -116,7 +116,7 @@ public class AnnotationCacheOperationSourceTests { CacheOperation cacheOperation = it.next(); assertThat(cacheOperation).isInstanceOf(CacheableOperation.class); assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("directly declared")); - assertThat(cacheOperation.getKey()).isEqualTo(""); + assertThat(cacheOperation.getKey()).isEmpty(); cacheOperation = it.next(); assertThat(cacheOperation).isInstanceOf(CacheableOperation.class); @@ -126,7 +126,7 @@ public class AnnotationCacheOperationSourceTests { cacheOperation = it.next(); assertThat(cacheOperation).isInstanceOf(CacheableOperation.class); assertThat(cacheOperation.getCacheNames()).isEqualTo(Collections.singleton("foo")); - assertThat(cacheOperation.getKey()).isEqualTo(""); + assertThat(cacheOperation.getKey()).isEmpty(); cacheOperation = it.next(); assertThat(cacheOperation).isInstanceOf(CacheEvictOperation.class); @@ -222,7 +222,7 @@ public class AnnotationCacheOperationSourceTests { Collection ops = getOps(AnnotatedClass.class, "noCacheNameSpecified"); CacheOperation cacheOperation = ops.iterator().next(); assertThat(cacheOperation.getCacheNames()).as("cache names set must not be null").isNotNull(); - assertThat(cacheOperation.getCacheNames().size()).as("no cache names specified").isEqualTo(0); + assertThat(cacheOperation.getCacheNames()).as("no cache names specified").isEmpty(); } @Test @@ -251,7 +251,7 @@ public class AnnotationCacheOperationSourceTests { Collection ops = getOps(InterfaceCacheConfig.class, "interfaceCacheableOverride"); assertThat(ops.size()).isSameAs(1); CacheOperation cacheOperation = ops.iterator().next(); - assertThat(cacheOperation instanceof CacheableOperation).isTrue(); + assertThat(cacheOperation).isInstanceOf(CacheableOperation.class); } @Test @@ -278,7 +278,7 @@ public class AnnotationCacheOperationSourceTests { private Collection getOps(Class target, String name, int expectedNumberOfOperations) { Collection result = getOps(target, name); - assertThat(result.size()).as("Wrong number of operation(s) for '" + name + "'").isEqualTo(expectedNumberOfOperations); + assertThat(result).as("Wrong number of operation(s) for '" + name + "'").hasSize(expectedNumberOfOperations); return result; } @@ -298,7 +298,7 @@ public class AnnotationCacheOperationSourceTests { 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); + assertThat(actual.getCacheNames()).as("Wrong number of cache names").hasSameSizeAs(cacheNames); 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 811b55bb8f5..70d9254dcc3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,15 +33,15 @@ public class ConcurrentMapCacheManagerTests { public void testDynamicMode() { CacheManager cm = new ConcurrentMapCacheManager(); Cache cache1 = cm.getCache("c1"); - assertThat(cache1 instanceof ConcurrentMapCache).isTrue(); + assertThat(cache1).isInstanceOf(ConcurrentMapCache.class); Cache cache1again = cm.getCache("c1"); assertThat(cache1).isSameAs(cache1again); Cache cache2 = cm.getCache("c2"); - assertThat(cache2 instanceof ConcurrentMapCache).isTrue(); + assertThat(cache2).isInstanceOf(ConcurrentMapCache.class); Cache cache2again = cm.getCache("c2"); assertThat(cache2).isSameAs(cache2again); Cache cache3 = cm.getCache("c3"); - assertThat(cache3 instanceof ConcurrentMapCache).isTrue(); + assertThat(cache3).isInstanceOf(ConcurrentMapCache.class); Cache cache3again = cm.getCache("c3"); assertThat(cache3).isSameAs(cache3again); @@ -71,11 +71,11 @@ public class ConcurrentMapCacheManagerTests { public void testStaticMode() { ConcurrentMapCacheManager cm = new ConcurrentMapCacheManager("c1", "c2"); Cache cache1 = cm.getCache("c1"); - assertThat(cache1 instanceof ConcurrentMapCache).isTrue(); + assertThat(cache1).isInstanceOf(ConcurrentMapCache.class); Cache cache1again = cm.getCache("c1"); assertThat(cache1).isSameAs(cache1again); Cache cache2 = cm.getCache("c2"); - assertThat(cache2 instanceof ConcurrentMapCache).isTrue(); + assertThat(cache2).isInstanceOf(ConcurrentMapCache.class); Cache cache2again = cm.getCache("c2"); assertThat(cache2).isSameAs(cache2again); Cache cache3 = cm.getCache("c3"); @@ -92,11 +92,11 @@ public class ConcurrentMapCacheManagerTests { cm.setAllowNullValues(false); Cache cache1x = cm.getCache("c1"); - assertThat(cache1x instanceof ConcurrentMapCache).isTrue(); - assertThat(cache1x != cache1).isTrue(); + assertThat(cache1x).isInstanceOf(ConcurrentMapCache.class); + assertThat(cache1x).isNotSameAs(cache1); Cache cache2x = cm.getCache("c2"); - assertThat(cache2x instanceof ConcurrentMapCache).isTrue(); - assertThat(cache2x != cache2).isTrue(); + assertThat(cache2x).isInstanceOf(ConcurrentMapCache.class); + assertThat(cache2x).isNotSameAs(cache2); Cache cache3x = cm.getCache("c3"); assertThat(cache3x).isNull(); @@ -119,15 +119,15 @@ public class ConcurrentMapCacheManagerTests { ConcurrentMapCacheManager cm = new ConcurrentMapCacheManager("c1", "c2"); assertThat(cm.isStoreByValue()).isFalse(); Cache cache1 = cm.getCache("c1"); - assertThat(cache1 instanceof ConcurrentMapCache).isTrue(); + assertThat(cache1).isInstanceOf(ConcurrentMapCache.class); assertThat(((ConcurrentMapCache) cache1).isStoreByValue()).isFalse(); cache1.put("key", "value"); cm.setStoreByValue(true); assertThat(cm.isStoreByValue()).isTrue(); Cache cache1x = cm.getCache("c1"); - assertThat(cache1x instanceof ConcurrentMapCache).isTrue(); - assertThat(cache1x != cache1).isTrue(); + assertThat(cache1x).isInstanceOf(ConcurrentMapCache.class); + assertThat(cache1x).isNotSameAs(cache1); assertThat(cache1x.get("key")).isNull(); } 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 3be1c03a02c..c6be614ff46 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,11 +64,11 @@ public class ExpressionEvaluatorTests { assertThat(ops).hasSize(2); Iterator it = ops.iterator(); CacheOperation next = it.next(); - assertThat(next instanceof CacheableOperation).isTrue(); + assertThat(next).isInstanceOf(CacheableOperation.class); assertThat(next.getCacheNames().contains("test")).isTrue(); assertThat(next.getKey()).isEqualTo("#a"); next = it.next(); - assertThat(next instanceof CacheableOperation).isTrue(); + assertThat(next).isInstanceOf(CacheableOperation.class); assertThat(next.getCacheNames().contains("test")).isTrue(); assertThat(next.getKey()).isEqualTo("#b"); } 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 28808939e39..cdc746be3fb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,9 +43,9 @@ public abstract class AbstractCircularImportDetectionTests { newParser().parse(loadAsConfigurationSource(A.class), "A"); } catch (BeanDefinitionParsingException ex) { - assertThat(ex.getMessage().contains( - "Illegal attempt by @Configuration class 'AbstractCircularImportDetectionTests.B' " + - "to import class 'AbstractCircularImportDetectionTests.A'")).as("Wrong message. Got: " + ex.getMessage()).isTrue(); + assertThat(ex.getMessage()).as("Wrong message. Got: " + ex.getMessage()) + .contains("Illegal attempt by @Configuration class 'AbstractCircularImportDetectionTests.B' " + + "to import class 'AbstractCircularImportDetectionTests.A'"); threw = true; } assertThat(threw).isTrue(); @@ -58,9 +58,9 @@ public abstract class AbstractCircularImportDetectionTests { newParser().parse(loadAsConfigurationSource(X.class), "X"); } catch (BeanDefinitionParsingException ex) { - assertThat(ex.getMessage().contains( - "Illegal attempt by @Configuration class 'AbstractCircularImportDetectionTests.Z2' " + - "to import class 'AbstractCircularImportDetectionTests.Z'")).as("Wrong message. Got: " + ex.getMessage()).isTrue(); + assertThat(ex.getMessage()).as("Wrong message. Got: " + ex.getMessage()) + .contains("Illegal attempt by @Configuration class 'AbstractCircularImportDetectionTests.Z2' " + + "to import class 'AbstractCircularImportDetectionTests.Z'"); threw = true; } assertThat(threw).isTrue(); diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AggressiveFactoryBeanInstantiationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AggressiveFactoryBeanInstantiationTests.java index 07edad06f9d..1acfc113d1d 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AggressiveFactoryBeanInstantiationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AggressiveFactoryBeanInstantiationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,8 +71,8 @@ public class AggressiveFactoryBeanInstantiationTests { ex.printStackTrace(pw); pw.flush(); String stackTrace = baos.toString(); - assertThat(stackTrace.contains(".")).isTrue(); - assertThat(stackTrace.contains("java.lang.NoClassDefFoundError")).isFalse(); + assertThat(stackTrace).contains("."); + assertThat(stackTrace).doesNotContain("java.lang.NoClassDefFoundError"); } } 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 09498371ab7..5e79ff768b1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ public class ClassPathFactoryBeanDefinitionScannerTests { context.refresh(); FactoryMethodComponent fmc = context.getBean("factoryMethodComponent", FactoryMethodComponent.class); - assertThat(fmc.getClass().getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)).isFalse(); + assertThat(fmc.getClass().getName()).doesNotContain(ClassUtils.CGLIB_CLASS_SEPARATOR); TestBean tb = (TestBean) context.getBean("publicInstance"); //2 assertThat(tb.getName()).isEqualTo("publicInstance"); 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 bb533667f0b..21b4f53a073 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -105,9 +105,9 @@ class NestedConfigurationClassTests { ctx.refresh(); S1Config config = ctx.getBean(S1Config.class); - assertThat(config != ctx.getBean(S1Config.class)).isTrue(); + assertThat(config).isNotSameAs(ctx.getBean(S1Config.class)); TestBean tb = ctx.getBean("l0Bean", TestBean.class); - assertThat(tb == ctx.getBean("l0Bean", TestBean.class)).isTrue(); + assertThat(tb).isSameAs(ctx.getBean("l0Bean", TestBean.class)); ctx.getBean(L0Config.L1Config.class); ctx.getBean("l1Bean"); @@ -118,12 +118,12 @@ 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"); - assertThat(ob == ctx.getBean("overrideBean", TestBean.class)).isTrue(); + assertThat(ob).isSameAs(ctx.getBean("overrideBean", TestBean.class)); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); TestBean pb2 = ctx.getBean("prototypeBean", TestBean.class); - assertThat(pb1 != pb2).isTrue(); - assertThat(pb1.getFriends().iterator().next() != pb2.getFriends().iterator().next()).isTrue(); + assertThat(pb1).isNotSameAs(pb2); + assertThat(pb1.getFriends().iterator().next()).isNotSameAs(pb2.getFriends().iterator().next()); ctx.close(); } @@ -134,9 +134,9 @@ class NestedConfigurationClassTests { ctx.refresh(); S1Config config = ctx.getBean(S1Config.class); - assertThat(config != ctx.getBean(S1Config.class)).isTrue(); + assertThat(config).isNotSameAs(ctx.getBean(S1Config.class)); TestBean tb = ctx.getBean("l0Bean", TestBean.class); - assertThat(tb == ctx.getBean("l0Bean", TestBean.class)).isTrue(); + assertThat(tb).isSameAs(ctx.getBean("l0Bean", TestBean.class)); ctx.getBean(L0Config.L1Config.class); ctx.getBean("l1Bean"); @@ -147,12 +147,12 @@ 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"); - assertThat(ob == ctx.getBean("overrideBean", TestBean.class)).isTrue(); + assertThat(ob).isSameAs(ctx.getBean("overrideBean", TestBean.class)); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); TestBean pb2 = ctx.getBean("prototypeBean", TestBean.class); - assertThat(pb1 != pb2).isTrue(); - assertThat(pb1.getFriends().iterator().next() != pb2.getFriends().iterator().next()).isTrue(); + assertThat(pb1).isNotSameAs(pb2); + assertThat(pb1.getFriends().iterator().next()).isNotSameAs(pb2.getFriends().iterator().next()); ctx.close(); } @@ -163,9 +163,9 @@ class NestedConfigurationClassTests { ctx.refresh(); S1ConfigWithProxy config = ctx.getBean(S1ConfigWithProxy.class); - assertThat(config == ctx.getBean(S1ConfigWithProxy.class)).isTrue(); + assertThat(config).isSameAs(ctx.getBean(S1ConfigWithProxy.class)); TestBean tb = ctx.getBean("l0Bean", TestBean.class); - assertThat(tb == ctx.getBean("l0Bean", TestBean.class)).isTrue(); + assertThat(tb).isSameAs(ctx.getBean("l0Bean", TestBean.class)); ctx.getBean(L0Config.L1Config.class); ctx.getBean("l1Bean"); @@ -176,12 +176,12 @@ 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"); - assertThat(ob == ctx.getBean("overrideBean", TestBean.class)).isTrue(); + assertThat(ob).isSameAs(ctx.getBean("overrideBean", TestBean.class)); TestBean pb1 = ctx.getBean("prototypeBean", TestBean.class); TestBean pb2 = ctx.getBean("prototypeBean", TestBean.class); - assertThat(pb1 != pb2).isTrue(); - assertThat(pb1.getFriends().iterator().next() != pb2.getFriends().iterator().next()).isTrue(); + assertThat(pb1).isNotSameAs(pb2); + assertThat(pb1.getFriends().iterator().next()).isNotSameAs(pb2.getFriends().iterator().next()); ctx.close(); } @@ -194,15 +194,15 @@ class NestedConfigurationClassTests { assertThat(ctx.getBeanFactory().containsSingleton("l0ConfigEmpty")).isFalse(); Object l0i1 = ctx.getBean(L0ConfigEmpty.class); Object l0i2 = ctx.getBean(L0ConfigEmpty.class); - assertThat(l0i1 == l0i2).isTrue(); + assertThat(l0i1).isSameAs(l0i2); Object l1i1 = ctx.getBean(L0ConfigEmpty.L1ConfigEmpty.class); Object l1i2 = ctx.getBean(L0ConfigEmpty.L1ConfigEmpty.class); - assertThat(l1i1 != l1i2).isTrue(); + assertThat(l1i1).isNotSameAs(l1i2); Object l2i1 = ctx.getBean(L0ConfigEmpty.L1ConfigEmpty.L2ConfigEmpty.class); Object l2i2 = ctx.getBean(L0ConfigEmpty.L1ConfigEmpty.L2ConfigEmpty.class); - assertThat(l2i1 == l2i2).isTrue(); + assertThat(l2i1).isSameAs(l2i2); assertThat(l2i2.toString()).isNotEqualTo(l2i1.toString()); ctx.close(); } @@ -216,15 +216,15 @@ class NestedConfigurationClassTests { assertThat(ctx.getBeanFactory().containsSingleton("l0ConfigConcrete")).isFalse(); Object l0i1 = ctx.getBean(L0ConfigConcrete.class); Object l0i2 = ctx.getBean(L0ConfigConcrete.class); - assertThat(l0i1 == l0i2).isTrue(); + assertThat(l0i1).isSameAs(l0i2); Object l1i1 = ctx.getBean(L0ConfigConcrete.L1ConfigEmpty.class); Object l1i2 = ctx.getBean(L0ConfigConcrete.L1ConfigEmpty.class); - assertThat(l1i1 != l1i2).isTrue(); + assertThat(l1i1).isNotSameAs(l1i2); Object l2i1 = ctx.getBean(L0ConfigConcrete.L1ConfigEmpty.L2ConfigEmpty.class); Object l2i2 = ctx.getBean(L0ConfigConcrete.L1ConfigEmpty.L2ConfigEmpty.class); - assertThat(l2i1 == l2i2).isTrue(); + assertThat(l2i1).isSameAs(l2i2); assertThat(l2i2.toString()).isNotEqualTo(l2i1.toString()); ctx.close(); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/Spr8954Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/Spr8954Tests.java index 9a2cb00dfa7..475ff6d0052 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/Spr8954Tests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/Spr8954Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,12 +57,12 @@ public class Spr8954Tests { @SuppressWarnings("rawtypes") Map fbBeans = bf.getBeansOfType(FactoryBean.class); - assertThat(1).isEqualTo(fbBeans.size()); - assertThat("&foo").isEqualTo(fbBeans.keySet().iterator().next()); + assertThat(fbBeans.size()).isEqualTo(1); + assertThat(fbBeans.keySet().iterator().next()).isEqualTo("&foo"); Map aiBeans = bf.getBeansOfType(AnInterface.class); - assertThat(1).isEqualTo(aiBeans.size()); - assertThat("&foo").isEqualTo(aiBeans.keySet().iterator().next()); + assertThat(aiBeans.size()).isEqualTo(1); + assertThat(aiBeans.keySet().iterator().next()).isEqualTo("&foo"); } @Test @@ -76,12 +76,12 @@ public class Spr8954Tests { @SuppressWarnings("rawtypes") Map fbBeans = bf.getBeansOfType(FactoryBean.class); - assertThat(1).isEqualTo(fbBeans.size()); - assertThat("&foo").isEqualTo(fbBeans.keySet().iterator().next()); + assertThat(fbBeans.size()).isEqualTo(1); + assertThat(fbBeans.keySet().iterator().next()).isEqualTo("&foo"); Map aiBeans = bf.getBeansOfType(AnInterface.class); - assertThat(1).isEqualTo(aiBeans.size()); - assertThat("&foo").isEqualTo(aiBeans.keySet().iterator().next()); + assertThat(aiBeans.size()).isEqualTo(1); + assertThat(aiBeans.keySet().iterator().next()).isEqualTo("&foo"); } 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 1c61c9840ef..9a979547657 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 @@ -92,7 +92,7 @@ class AutowiredConfigurationTests { OptionalAutowiredMethodConfig.class); assertThat(context.getBeansOfType(Colour.class).isEmpty()).isTrue(); - assertThat(context.getBean(TestBean.class).getName()).isEqualTo(""); + assertThat(context.getBean(TestBean.class).getName()).isEmpty(); context.close(); } 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 5a0ab50a8fb..1ec92c65882 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 @@ -162,12 +162,12 @@ class AnnotationDrivenEventListenerTests { ContextEventListener listener = this.context.getBean(ContextEventListener.class); List events = this.eventCollector.getEvents(listener); - assertThat(events.size()).as("Wrong number of initial context events").isEqualTo(1); + assertThat(events).as("Wrong number of initial context events").hasSize(1); assertThat(events.get(0).getClass()).isEqualTo(ContextRefreshedEvent.class); this.context.stop(); List eventsAfterStop = this.eventCollector.getEvents(listener); - assertThat(eventsAfterStop.size()).as("Wrong number of context events on shutdown").isEqualTo(2); + assertThat(eventsAfterStop).as("Wrong number of context events on shutdown").hasSize(2); assertThat(eventsAfterStop.get(1).getClass()).isEqualTo(ContextStoppedEvent.class); this.eventCollector.assertTotalEventsCount(2); } @@ -334,7 +334,7 @@ class AnnotationDrivenEventListenerTests { load(ScopedProxyTestBean.class); SimpleService proxy = this.context.getBean(SimpleService.class); - assertThat(proxy instanceof Advised).as("bean should be a proxy").isTrue(); + assertThat(proxy).as("bean should be a proxy").isInstanceOf(Advised.class); this.eventCollector.assertNoEventReceived(proxy.getId()); this.context.publishEvent(new ContextRefreshedEvent(this.context)); @@ -351,7 +351,7 @@ class AnnotationDrivenEventListenerTests { load(AnnotatedProxyTestBean.class); AnnotatedSimpleService proxy = this.context.getBean(AnnotatedSimpleService.class); - assertThat(proxy instanceof Advised).as("bean should be a proxy").isTrue(); + assertThat(proxy).as("bean should be a proxy").isInstanceOf(Advised.class); this.eventCollector.assertNoEventReceived(proxy.getId()); this.context.publishEvent(new ContextRefreshedEvent(this.context)); 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 66c25561668..0c58f29a97f 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 @@ -112,9 +112,9 @@ class EventPublicationInterceptorTests { testBean.getAge(); // two events: ContextRefreshedEvent and TestEvent - assertThat(listener.getEventCount() == 2).as("Interceptor must have published 2 events").isTrue(); + assertThat(listener.getEventCount()).as("Interceptor must have published 2 events").isEqualTo(2); TestApplicationListener otherListener = (TestApplicationListener) ctx.getBean("&otherListener"); - assertThat(otherListener.getEventCount() == 2).as("Interceptor must have published 2 events").isTrue(); + assertThat(otherListener.getEventCount()).as("Interceptor must have published 2 events").isEqualTo(2); ctx.close(); } 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 fdd8fa81f95..4e7da9e2c53 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ public class EventCollector { */ public void assertNoEventReceived(String listenerId) { List events = this.content.getOrDefault(listenerId, Collections.emptyList()); - assertThat(events.size()).as("Expected no events but got " + events).isEqualTo(0); + assertThat(events).as("Expected no events but got " + events).isEmpty(); } /** @@ -74,7 +74,7 @@ public class EventCollector { */ public void assertEvent(String listenerId, Object... events) { List actual = this.content.getOrDefault(listenerId, Collections.emptyList()); - assertThat(actual.size()).as("Wrong number of events").isEqualTo(events.length); + assertThat(actual).as("Wrong number of events").hasSameSizeAs(events); for (int i = 0; i < events.length; i++) { assertThat(actual.get(i)).as("Wrong event at index " + i).isEqualTo(events[i]); } 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 e4bd7a4726c..fcbe92ac9c6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -169,9 +169,9 @@ class ApplicationContextExpressionTests { System.getProperties().put("country", "UK"); 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.optionalValue1).contains("123"); + assertThat(tb3.optionalValue2).contains("123"); + assertThat(tb3.optionalValue3).isNotPresent(); assertThat(tb3.tb).isSameAs(tb0); tb3 = SerializationTestUtils.serializeAndDeserialize(tb3); @@ -246,7 +246,7 @@ class ApplicationContextExpressionTests { ac.refresh(); String str = ac.getBean("str", String.class); - assertThat(str.startsWith("test-")).isTrue(); + assertThat(str).startsWith("test-"); ac.close(); } 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 4069558efb0..ceb8da3c98a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ public class CachedExpressionEvaluatorTests { Expression expression = expressionEvaluator.getTestExpression("true", method, getClass()); hasParsedExpression("true"); assertThat(expression.getValue()).asInstanceOf(BOOLEAN).isTrue(); - assertThat(expressionEvaluator.testCache.size()).as("Expression should be in cache").isEqualTo(1); + assertThat(expressionEvaluator.testCache).as("Expression should be in cache").hasSize(1); } @Test @@ -56,7 +56,7 @@ public class CachedExpressionEvaluatorTests { expressionEvaluator.getTestExpression("true", method, getClass()); expressionEvaluator.getTestExpression("true", method, getClass()); hasParsedExpression("true"); - assertThat(expressionEvaluator.testCache.size()).as("Only one expression should be in cache").isEqualTo(1); + assertThat(expressionEvaluator.testCache).as("Only one expression should be in cache").hasSize(1); } @Test @@ -64,7 +64,7 @@ public class CachedExpressionEvaluatorTests { Method method = ReflectionUtils.findMethod(getClass(), "toString"); expressionEvaluator.getTestExpression("true", method, getClass()); expressionEvaluator.getTestExpression("true", method, Object.class); - assertThat(expressionEvaluator.testCache.size()).as("Cached expression should be based on type").isEqualTo(2); + assertThat(expressionEvaluator.testCache).as("Cached expression should be based on type").hasSize(2); } private void hasParsedExpression(String expression) { 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 b3aac00846d..9d1d5af5ee8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,14 +73,14 @@ class ApplicationContextLifecycleTests { LifecycleTestBean bean3 = (LifecycleTestBean) context.getBean("bean3"); LifecycleTestBean bean4 = (LifecycleTestBean) context.getBean("bean4"); String notStartedError = "bean was not started"; - 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(); + assertThat(bean1.getStartOrder()).as(notStartedError).isGreaterThan(0); + assertThat(bean2.getStartOrder()).as(notStartedError).isGreaterThan(0); + assertThat(bean3.getStartOrder()).as(notStartedError).isGreaterThan(0); + assertThat(bean4.getStartOrder()).as(notStartedError).isGreaterThan(0); String orderError = "dependent bean must start after the bean it depends on"; - assertThat(bean2.getStartOrder() > bean1.getStartOrder()).as(orderError).isTrue(); - assertThat(bean3.getStartOrder() > bean2.getStartOrder()).as(orderError).isTrue(); - assertThat(bean4.getStartOrder() > bean2.getStartOrder()).as(orderError).isTrue(); + assertThat(bean2.getStartOrder()).as(orderError).isGreaterThan(bean1.getStartOrder()); + assertThat(bean3.getStartOrder()).as(orderError).isGreaterThan(bean2.getStartOrder()); + assertThat(bean4.getStartOrder()).as(orderError).isGreaterThan(bean2.getStartOrder()); context.close(); } @@ -94,14 +94,14 @@ class ApplicationContextLifecycleTests { LifecycleTestBean bean3 = (LifecycleTestBean) context.getBean("bean3"); LifecycleTestBean bean4 = (LifecycleTestBean) context.getBean("bean4"); String notStoppedError = "bean was not stopped"; - 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(); + assertThat(bean1.getStopOrder()).as(notStoppedError).isGreaterThan(0); + assertThat(bean2.getStopOrder()).as(notStoppedError).isGreaterThan(0); + assertThat(bean3.getStopOrder()).as(notStoppedError).isGreaterThan(0); + assertThat(bean4.getStopOrder()).as(notStoppedError).isGreaterThan(0); String orderError = "dependent bean must stop before the bean it depends on"; - assertThat(bean2.getStopOrder() < bean1.getStopOrder()).as(orderError).isTrue(); - assertThat(bean3.getStopOrder() < bean2.getStopOrder()).as(orderError).isTrue(); - assertThat(bean4.getStopOrder() < bean2.getStopOrder()).as(orderError).isTrue(); + assertThat(bean2.getStopOrder()).as(orderError).isLessThan(bean1.getStopOrder()); + assertThat(bean3.getStopOrder()).as(orderError).isLessThan(bean2.getStopOrder()); + assertThat(bean4.getStopOrder()).as(orderError).isLessThan(bean2.getStopOrder()); context.close(); } 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 ec0c01d2788..b91dd9b6050 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -154,8 +154,8 @@ public class ClassPathXmlApplicationContextTests { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ex.printStackTrace(new PrintStream(baos)); String dump = FileCopyUtils.copyToString(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()))); - assertThat(dump.contains("someMessageSource")).isTrue(); - assertThat(dump.contains("useCodeAsDefaultMessage")).isTrue(); + assertThat(dump).contains("someMessageSource"); + assertThat(dump).contains("useCodeAsDefaultMessage"); } catch (IOException ioex) { throw new IllegalStateException(ioex); 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 231b47b75bb..233ecc98ceb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -118,12 +118,12 @@ class ConversionServiceFactoryBeanTests { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(fileName, getClass()); ResourceTestBean tb = ctx.getBean("resourceTestBean", ResourceTestBean.class); assertThat(resourceClass.isInstance(tb.getResource())).isTrue(); - assertThat(tb.getResourceArray().length > 0).isTrue(); + assertThat(tb.getResourceArray()).isNotEmpty(); assertThat(resourceClass.isInstance(tb.getResourceArray()[0])).isTrue(); - assertThat(tb.getResourceMap().size() == 1).isTrue(); + assertThat(tb.getResourceMap()).hasSize(1); assertThat(resourceClass.isInstance(tb.getResourceMap().get("key1"))).isTrue(); - assertThat(tb.getResourceArrayMap().size() == 1).isTrue(); - assertThat(tb.getResourceArrayMap().get("key1").length > 0).isTrue(); + assertThat(tb.getResourceArrayMap()).hasSize(1); + assertThat(tb.getResourceArrayMap().get("key1")).isNotEmpty(); assertThat(resourceClass.isInstance(tb.getResourceArrayMap().get("key1")[0])).isTrue(); ctx.close(); } @@ -141,7 +141,7 @@ class ConversionServiceFactoryBeanTests { static class ComplexConstructorArgument { ComplexConstructorArgument(Map> map) { - assertThat(!map.isEmpty()).isTrue(); + assertThat(map.isEmpty()).isFalse(); 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/PropertySourcesPlaceholderConfigurerTests.java b/spring-context/src/test/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurerTests.java index 839044820ba..05e00092558 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -407,7 +407,7 @@ public class PropertySourcesPlaceholderConfigurerTests { ppc.setEnvironment(env); ppc.setIgnoreUnresolvablePlaceholders(true); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(OptionalTestBean.class).getName()).isEqualTo(Optional.of("myValue")); + assertThat(bf.getBean(OptionalTestBean.class).getName()).contains("myValue"); } @Test @@ -427,7 +427,7 @@ public class PropertySourcesPlaceholderConfigurerTests { ppc.setIgnoreUnresolvablePlaceholders(true); ppc.setNullValue(""); ppc.postProcessBeanFactory(bf); - assertThat(bf.getBean(OptionalTestBean.class).getName()).isEqualTo(Optional.empty()); + assertThat(bf.getBean(OptionalTestBean.class).getName()).isNotPresent(); } 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 d24f13a13c8..8596f602be7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,15 +70,15 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { @Test public void getMessageWithDefaultPassedInAndFoundInMsgCatalog() { // Try with Locale.US - 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(); + assertThat(sac.getMessage("message.format.example2", null, "This is a default msg if not found in MessageSource.", Locale.US)).as("valid msg from staticMsgSource with default msg passed in returned msg from msg catalog for Locale.US") + .isEqualTo("This is a test message in the message catalog with no args."); } @Test public void getMessageWithDefaultPassedInAndNotFoundInMsgCatalog() { // Try with Locale.US - 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(); + assertThat(sac.getMessage("bogus.message", null, "This is a default msg if not found in MessageSource.", Locale.US)).as("bogus msg from staticMsgSource with default msg passed in returned default msg for Locale.US") + .isEqualTo("This is a default msg if not found in MessageSource."); } /** @@ -100,8 +100,8 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { sac.getMessage("message.format.example1", arguments, Locale.US); // Now msg better be as expected - 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(); + assertThat(sac.getMessage("message.format.example1", arguments, Locale.US)).as("2nd search within MsgFormat cache returned expected message for Locale.US") + .contains("there was \"a disturbance in the Force\" on planet 7."); Object[] newArguments = { 8, new Date(System.currentTimeMillis()), @@ -109,8 +109,8 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { }; // Now msg better be as expected even with different args - 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(); + assertThat(sac.getMessage("message.format.example1", newArguments, Locale.US)).as("2nd search within MsgFormat cache with different args returned expected message for Locale.US") + .contains("there was \"a disturbance in the Force\" on planet 8."); } /** @@ -131,16 +131,16 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { and the time the ResourceBundleMessageSource resolves the msg the minutes of the time might not be the same. */ - 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(); + assertThat(sac.getMessage("message.format.example1", arguments, Locale.US)).as("msg from staticMsgSource for Locale.US substituting args for placeholders is as expected") + .contains("there was \"a disturbance in the Force\" on planet 7."); // Try with Locale.UK - 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(); + assertThat(sac.getMessage("message.format.example1", arguments, Locale.UK)).as("msg from staticMsgSource for Locale.UK substituting args for placeholders is as expected") + .contains("there was \"a disturbance in the Force\" on station number 7."); // Try with Locale.US - Use a different test msg that requires 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(); + assertThat(sac.getMessage("message.format.example2", null, Locale.US)).as("msg from staticMsgSource for Locale.US that requires no args is as expected") + .isEqualTo("This is a test message in the message catalog with no args."); } @Test @@ -155,17 +155,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"); - assertThat(MSG_TXT3_US.equals(sac.getMessage(resolvable1, Locale.US))).as("correct message retrieved").isTrue(); + assertThat(sac.getMessage(resolvable1, Locale.US)).as("correct message retrieved").isEqualTo(MSG_TXT3_US); // only second code valid String[] codes2 = new String[] {"message.format.example99", "message.format.example2"}; MessageSourceResolvable resolvable2 = new DefaultMessageSourceResolvable(codes2, null, "default"); - assertThat(MSG_TXT2_US.equals(sac.getMessage(resolvable2, Locale.US))).as("correct message retrieved").isTrue(); + assertThat(sac.getMessage(resolvable2, Locale.US)).as("correct message retrieved").isEqualTo(MSG_TXT2_US); // no code valid, but default given String[] codes3 = new String[] {"message.format.example99", "message.format.example98"}; MessageSourceResolvable resolvable3 = new DefaultMessageSourceResolvable(codes3, null, "default"); - assertThat("default".equals(sac.getMessage(resolvable3, Locale.US))).as("correct message retrieved").isTrue(); + assertThat(sac.getMessage(resolvable3, Locale.US)).as("correct message retrieved").isEqualTo("default"); // no code valid, no default String[] codes4 = new String[] {"message.format.example99", "message.format.example98"}; 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 3ae83030ae1..081aa02dff1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,8 +78,8 @@ public class DateTimeFormatterFactoryTests { public void createDateTimeFormatterInOrderOfPropertyPriority() { factory.setStylePattern("SS"); String value = applyLocale(factory.createDateTimeFormatter()).format(dateTime); - assertThat(value.startsWith("10/21/09")).isTrue(); - assertThat(value.endsWith("12:10 PM")).isTrue(); + assertThat(value).startsWith("10/21/09"); + assertThat(value).endsWith("12:10 PM"); 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 03da5996314..cefeeeef944 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 @@ -463,7 +463,7 @@ class DateTimeFormattingTests { propertyValues.add("period", "P6Y3M1D"); binder.bind(propertyValues); assertThat(binder.getBindingResult().getErrorCount()).isZero(); - assertThat(binder.getBindingResult().getFieldValue("period").toString().equals("P6Y3M1D")).isTrue(); + assertThat(binder.getBindingResult().getFieldValue("period").toString()).isEqualTo("P6Y3M1D"); } @Test @@ -472,7 +472,7 @@ class DateTimeFormattingTests { propertyValues.add("duration", "PT8H6M12.345S"); binder.bind(propertyValues); assertThat(binder.getBindingResult().getErrorCount()).isZero(); - assertThat(binder.getBindingResult().getFieldValue("duration").toString().equals("PT8H6M12.345S")).isTrue(); + assertThat(binder.getBindingResult().getFieldValue("duration").toString()).isEqualTo("PT8H6M12.345S"); } @Test @@ -481,7 +481,7 @@ class DateTimeFormattingTests { propertyValues.add("year", "2007"); binder.bind(propertyValues); assertThat(binder.getBindingResult().getErrorCount()).isZero(); - assertThat(binder.getBindingResult().getFieldValue("year").toString().equals("2007")).isTrue(); + assertThat(binder.getBindingResult().getFieldValue("year").toString()).isEqualTo("2007"); } @Test @@ -490,7 +490,7 @@ class DateTimeFormattingTests { propertyValues.add("month", "JULY"); binder.bind(propertyValues); assertThat(binder.getBindingResult().getErrorCount()).isZero(); - assertThat(binder.getBindingResult().getFieldValue("month").toString().equals("JULY")).isTrue(); + assertThat(binder.getBindingResult().getFieldValue("month").toString()).isEqualTo("JULY"); } @Test @@ -499,7 +499,7 @@ class DateTimeFormattingTests { propertyValues.add("month", "July"); binder.bind(propertyValues); assertThat(binder.getBindingResult().getErrorCount()).isZero(); - assertThat(binder.getBindingResult().getFieldValue("month").toString().equals("JULY")).isTrue(); + assertThat(binder.getBindingResult().getFieldValue("month").toString()).isEqualTo("JULY"); } @Test @@ -508,7 +508,7 @@ class DateTimeFormattingTests { propertyValues.add("yearMonth", "2007-12"); binder.bind(propertyValues); assertThat(binder.getBindingResult().getErrorCount()).isZero(); - assertThat(binder.getBindingResult().getFieldValue("yearMonth").toString().equals("2007-12")).isTrue(); + assertThat(binder.getBindingResult().getFieldValue("yearMonth").toString()).isEqualTo("2007-12"); } @Test @@ -527,7 +527,7 @@ class DateTimeFormattingTests { propertyValues.add("monthDay", "--12-03"); binder.bind(propertyValues); assertThat(binder.getBindingResult().getErrorCount()).isZero(); - assertThat(binder.getBindingResult().getFieldValue("monthDay").toString().equals("--12-03")).isTrue(); + assertThat(binder.getBindingResult().getFieldValue("monthDay").toString()).isEqualTo("--12-03"); } @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 40f250ffc56..c18a9f04df6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,7 +67,7 @@ public class MoneyFormattingTests { 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().getNumber().doubleValue()).isEqualTo(10.5d); assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); LocaleContextHolder.setLocale(Locale.CANADA); @@ -76,7 +76,7 @@ public class MoneyFormattingTests { 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().getNumber().doubleValue()).isEqualTo(10.5d); assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); } @@ -91,7 +91,7 @@ public class MoneyFormattingTests { binder.bind(propertyValues); 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().getNumber().doubleValue()).isEqualTo(10.5d); assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); LocaleContextHolder.setLocale(Locale.CANADA); @@ -99,7 +99,7 @@ public class MoneyFormattingTests { LocaleContextHolder.setLocale(Locale.US); 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().getNumber().doubleValue()).isEqualTo(10.5d); assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("CAD"); } @@ -114,7 +114,7 @@ public class MoneyFormattingTests { binder.bind(propertyValues); 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().getNumber().doubleValue()).isEqualTo(10.5d); assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); } @@ -129,7 +129,7 @@ public class MoneyFormattingTests { binder.bind(propertyValues); assertThat(binder.getBindingResult().getErrorCount()).isEqualTo(0); assertThat(binder.getBindingResult().getFieldValue("amount")).isEqualTo("10%"); - assertThat(bean.getAmount().getNumber().doubleValue() == 0.1d).isTrue(); + assertThat(bean.getAmount().getNumber().doubleValue()).isEqualTo(0.1d); assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); } @@ -144,7 +144,7 @@ public class MoneyFormattingTests { binder.bind(propertyValues); 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().getNumber().doubleValue()).isEqualTo(10.5d); assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); } @@ -159,7 +159,7 @@ public class MoneyFormattingTests { binder.bind(propertyValues); 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().getNumber().doubleValue()).isEqualTo(10.5d); assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); LocaleContextHolder.setLocale(Locale.CANADA); @@ -167,7 +167,7 @@ public class MoneyFormattingTests { LocaleContextHolder.setLocale(Locale.US); 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().getNumber().doubleValue()).isEqualTo(10.5d); assertThat(bean.getAmount().getCurrency().getCurrencyCode()).isEqualTo("USD"); } 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 b07e9370fce..578c8295408 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -522,7 +522,8 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { this.server.unregisterMBean(new ObjectName(OBJECT_NAME)); exporter.destroy(); - assertThat(listener.getUnregistered().size()).as("Listener should not have been invoked (MBean previously unregistered by external agent)").isEqualTo(0); + assertThat(listener.getUnregistered()).as("Listener should not have been invoked (MBean previously unregistered by external agent)") + .isEmpty(); } @Test // SPR-3302 @@ -664,8 +665,8 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { private void assertListener(MockMBeanExporterListener listener) throws MalformedObjectNameException { ObjectName desired = ObjectNameManager.getInstance(OBJECT_NAME); - 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()).as("Incorrect number of registrations").hasSize(1); + assertThat(listener.getUnregistered()).as("Incorrect number of unregistrations").hasSize(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/assembler/AbstractMetadataAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java index f851ae7fb63..7afe8e29546 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,7 +146,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble ModelMBeanOperationInfo oper = info.getOperation("add"); MBeanParameterInfo[] params = oper.getSignature(); - assertThat(params.length).as("Invalid number of params").isEqualTo(2); + assertThat(params).as("Invalid number of params").hasSize(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()); @@ -176,8 +176,8 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble start(exporter); MBeanInfo inf = getServer().getMBeanInfo(ObjectNameManager.getInstance(objectName)); - assertThat(inf.getOperations().length).as("Incorrect number of operations").isEqualTo(getExpectedOperationCount()); - assertThat(inf.getAttributes().length).as("Incorrect number of attributes").isEqualTo(getExpectedAttributeCount()); + assertThat(inf.getOperations()).as("Incorrect number of operations").hasSize(getExpectedOperationCount()); + assertThat(inf.getAttributes()).as("Incorrect number of attributes").hasSize(getExpectedAttributeCount()); assertThat(assembler.includeBean(proxy.getClass(), "some bean name")).as("Not included in autodetection").isTrue(); } 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 77f9df24a4d..4b9c4f7af23 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java @@ -57,7 +57,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("java:comp/env/foo"); jof.setResourceRef(true); jof.afterPropertiesSet(); - assertThat(jof.getObject() == o).isTrue(); + assertThat(jof.getObject()).isSameAs(o); } @Test @@ -68,7 +68,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("java:comp/env/foo"); jof.setResourceRef(false); jof.afterPropertiesSet(); - assertThat(jof.getObject() == o).isTrue(); + assertThat(jof.getObject()).isSameAs(o); } @Test @@ -79,7 +79,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("java:foo"); jof.setResourceRef(true); jof.afterPropertiesSet(); - assertThat(jof.getObject() == o).isTrue(); + assertThat(jof.getObject()).isSameAs(o); } @Test @@ -90,7 +90,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("java:foo"); jof.setResourceRef(false); jof.afterPropertiesSet(); - assertThat(jof.getObject() == o).isTrue(); + assertThat(jof.getObject()).isSameAs(o); } @Test @@ -101,7 +101,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("foo"); jof.setResourceRef(true); jof.afterPropertiesSet(); - assertThat(jof.getObject() == o).isTrue(); + assertThat(jof.getObject()).isSameAs(o); } @Test @@ -122,7 +122,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("foo"); jof.setResourceRef(false); jof.afterPropertiesSet(); - assertThat(jof.getObject() == o).isTrue(); + assertThat(jof.getObject()).isSameAs(o); } @Test @@ -133,7 +133,7 @@ public class JndiObjectFactoryBeanTests { jof.setJndiName("foo"); jof.setExpectedType(String.class); jof.afterPropertiesSet(); - assertThat(jof.getObject() == s).isTrue(); + assertThat(jof.getObject()).isSameAs(s); } @Test 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 ab6980725d4..eaeb25836b1 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiTemplateEditorTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiTemplateEditorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ public class JndiTemplateEditorTests { JndiTemplateEditor je = new JndiTemplateEditor(); je.setAsText(""); JndiTemplate jt = (JndiTemplate) je.getValue(); - assertThat(jt.getEnvironment() == null).isTrue(); + assertThat(jt.getEnvironment()).isNull(); } @Test @@ -49,9 +49,10 @@ public class JndiTemplateEditorTests { // to look anything up je.setAsText("jndiInitialSomethingOrOther=org.springframework.myjndi.CompleteRubbish\nfoo=bar"); JndiTemplate jt = (JndiTemplate) je.getValue(); - 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(); + assertThat(jt.getEnvironment()).hasSize(2); + assertThat(jt.getEnvironment().getProperty("jndiInitialSomethingOrOther")).isEqualTo( + "org.springframework.myjndi.CompleteRubbish"); + assertThat(jt.getEnvironment().getProperty("foo")).isEqualTo("bar"); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/AnnotationAsyncExecutionInterceptorTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/AnnotationAsyncExecutionInterceptorTests.java index 51566b02293..a7f335afa39 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/AnnotationAsyncExecutionInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/AnnotationAsyncExecutionInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ public class AnnotationAsyncExecutionInterceptorTests { } { // method and class level -> method value, even if empty, overrides @Async("qClass") class C { @Async void m() { } } - assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEqualTo(""); + assertThat(i.getExecutorQualifier(C.class.getDeclaredMethod("m"))).isEmpty(); } { // meta annotation with qualifier @MyAsync class C { void m() { } } 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 aae702ac305..3d342f0e478 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -106,7 +106,7 @@ public class AsyncAnnotationBeanPostProcessorTests { testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); - assertThat(asyncThread.getName().startsWith("testExecutor")).isTrue(); + assertThat(asyncThread.getName()).startsWith("testExecutor"); context.close(); } @@ -131,7 +131,7 @@ public class AsyncAnnotationBeanPostProcessorTests { testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); - assertThat(asyncThread.getName().startsWith("testExecutor")).isTrue(); + assertThat(asyncThread.getName()).startsWith("testExecutor"); context.close(); } @@ -160,7 +160,7 @@ public class AsyncAnnotationBeanPostProcessorTests { testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); - assertThat(asyncThread.getName().startsWith("testExecutor2")).isTrue(); + assertThat(asyncThread.getName()).startsWith("testExecutor2"); context.close(); } @@ -173,7 +173,7 @@ public class AsyncAnnotationBeanPostProcessorTests { testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); - assertThat(asyncThread.getName().startsWith("testExecutor")).isTrue(); + assertThat(asyncThread.getName()).startsWith("testExecutor"); TestableAsyncUncaughtExceptionHandler exceptionHandler = context.getBean("exceptionHandler", TestableAsyncUncaughtExceptionHandler.class); 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 fe473e56b45..533861d2587 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 @@ -183,7 +183,9 @@ class ScheduledExecutorFactoryBeanTests { ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() { @Override protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) { - assertThat("Bah; the setThreadFactory(..) method must use a default ThreadFactory if a null arg is passed in.").isNotNull(); + assertThat(threadFactory) + .withFailMessage("Bah; the setThreadFactory(..) method must use a default ThreadFactory if a null arg is passed in.") + .isNotNull(); return super.createExecutor(poolSize, threadFactory, rejectedExecutionHandler); } }; @@ -199,7 +201,6 @@ class ScheduledExecutorFactoryBeanTests { ScheduledExecutorFactoryBean factory = new ScheduledExecutorFactoryBean() { @Override protected ScheduledExecutorService createExecutor(int poolSize, ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) { - assertThat("Bah; the setRejectedExecutionHandler(..) method must use a default RejectedExecutionHandler if a null arg is passed in.").isNotNull(); return super.createExecutor(poolSize, threadFactory, rejectedExecutionHandler); } }; 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 2daefd28839..d06d41775fb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -218,8 +218,8 @@ class PeriodicTriggerTests { private static void assertApproximateDifference(Instant lesser, Instant greater, long expected) { long diff = greater.toEpochMilli() - lesser.toEpochMilli(); long variance = Math.abs(expected - diff); - assertThat(variance < 100).as("expected approximate difference of " + expected + - ", but actual difference was " + diff).isTrue(); + assertThat(variance).as("expected approximate difference of " + expected + + ", but actual difference was " + diff).isLessThan(100); } private static TriggerContext context(@Nullable Object scheduled, @Nullable Object actual, 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 53c9ce6c169..e265610c69d 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 @@ -69,7 +69,7 @@ class BshScriptFactoryTests { assertThat(messenger).isEqualTo(messenger); boolean condition1 = !messenger.equals(calc); assertThat(condition1).isTrue(); - assertThat(messenger.hashCode() != calc.hashCode()).isTrue(); + assertThat(messenger.hashCode()).isNotEqualTo(calc.hashCode()); boolean condition = !messenger.toString().equals(calc.toString()); assertThat(condition).isTrue(); 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 8150bc3d5e2..ffe5a19f2a0 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 @@ -87,7 +87,7 @@ public class GroovyScriptFactoryTests { assertThat(messenger).isEqualTo(messenger); boolean condition1 = !messenger.equals(calc); assertThat(condition1).isTrue(); - assertThat(messenger.hashCode() != calc.hashCode()).isTrue(); + assertThat(messenger.hashCode()).isNotEqualTo(calc.hashCode()); boolean condition = !messenger.toString().equals(calc.toString()); assertThat(condition).isTrue(); @@ -120,7 +120,7 @@ public class GroovyScriptFactoryTests { assertThat(messenger).isEqualTo(messenger); boolean condition1 = !messenger.equals(calc); assertThat(condition1).isTrue(); - assertThat(messenger.hashCode() != calc.hashCode()).isTrue(); + assertThat(messenger.hashCode()).isNotEqualTo(calc.hashCode()); boolean condition = !messenger.toString().equals(calc.toString()); assertThat(condition).isTrue(); @@ -455,7 +455,7 @@ public class GroovyScriptFactoryTests { new ClassPathXmlApplicationContext("groovy-with-xsd-proxy-target-class.xml", getClass()); } catch (BeanCreationException ex) { - assertThat(ex.getMessage().contains("Cannot use proxyTargetClass=true")).isTrue(); + assertThat(ex.getMessage()).contains("Cannot use proxyTargetClass=true"); } } 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 f8ffc26ab8a..d1eea63691e 100644 --- a/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,11 +52,11 @@ class DataBinderFieldAccessTests { binder.bind(pvs); binder.close(); - assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue(); - assertThat(rod.getAge() == 32).as("changed age correctly").isTrue(); + assertThat(rod.getName()).as("changed name correctly").isEqualTo("Rod"); + assertThat(rod.getAge()).as("changed age correctly").isEqualTo(32); Map m = binder.getBindingResult().getModel(); - assertThat(m.size() == 2).as("There is one element in map").isTrue(); + assertThat(m).as("There is one element in map").hasSize(2); FieldAccessBean tb = (FieldAccessBean) m.get("person"); assertThat(tb.equals(rod)).as("Same object").isTrue(); } 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 05dd886da82..a990612917e 100644 --- a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,11 +95,11 @@ class DataBinderTests { binder.bind(pvs); binder.close(); - assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue(); - assertThat(rod.getAge() == 32).as("changed age correctly").isTrue(); + assertThat(rod.getName()).as("changed name correctly").isEqualTo("Rod"); + assertThat(rod.getAge()).as("changed age correctly").isEqualTo(32); Map map = binder.getBindingResult().getModel(); - assertThat(map.size() == 2).as("There is one element in map").isTrue(); + assertThat(map).as("There is one element in map").hasSize(2); TestBean tb = (TestBean) map.get("person"); assertThat(tb.equals(rod)).as("Same object").isTrue(); @@ -576,7 +576,7 @@ class DataBinderTests { editor = binder.getBindingResult().findEditor("myFloat", null); assertThat(editor).isNotNull(); editor.setAsText("1,6"); - assertThat(((Number) editor.getValue()).floatValue() == 1.6f).isTrue(); + assertThat(((Number) editor.getValue()).floatValue()).isEqualTo(1.6f); } finally { LocaleContextHolder.resetLocaleContext(); @@ -752,15 +752,15 @@ class DataBinderTests { binder.bind(pvs); binder.close(); - 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(); + assertThat(rod.getName()).as("changed name correctly").isEqualTo("Rod"); + assertThat(rod.getTouchy()).as("changed touchy correctly").isEqualTo("Rod"); + assertThat(rod.getAge()).as("did not change age").isEqualTo(0); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); assertThat(disallowedFields).hasSize(1); assertThat(disallowedFields[0]).isEqualTo("age"); Map m = binder.getBindingResult().getModel(); - assertThat(m.size() == 2).as("There is one element in map").isTrue(); + assertThat(m).as("There is one element in map").hasSize(2); TestBean tb = (TestBean) m.get("person"); assertThat(tb.equals(rod)).as("Same object").isTrue(); } @@ -914,7 +914,7 @@ class DataBinderTests { binder.getBindingResult().rejectValue("touchy", "someCode", "someMessage"); binder.getBindingResult().rejectValue("spouse.name", "someCode", "someMessage"); - assertThat(binder.getBindingResult().getNestedPath()).isEqualTo(""); + assertThat(binder.getBindingResult().getNestedPath()).isEmpty(); assertThat(binder.getBindingResult().getFieldValue("name")).isEqualTo("value"); assertThat(binder.getBindingResult().getFieldError("name").getRejectedValue()).isEqualTo("prefixvalue"); assertThat(tb.getName()).isEqualTo("prefixvalue"); @@ -1010,7 +1010,7 @@ class DataBinderTests { binder.getBindingResult().rejectValue("touchy", "someCode", "someMessage"); binder.getBindingResult().rejectValue("spouse.name", "someCode", "someMessage"); - assertThat(binder.getBindingResult().getNestedPath()).isEqualTo(""); + assertThat(binder.getBindingResult().getNestedPath()).isEmpty(); assertThat(binder.getBindingResult().getFieldValue("name")).isEqualTo("value"); assertThat(binder.getBindingResult().getFieldError("name").getRejectedValue()).isEqualTo("prefixvalue"); assertThat(tb.getName()).isEqualTo("prefixvalue"); @@ -1148,7 +1148,7 @@ class DataBinderTests { spouseValidator.validate(tb.getSpouse(), errors); errors.setNestedPath(""); - assertThat(errors.getNestedPath()).isEqualTo(""); + assertThat(errors.getNestedPath()).isEmpty(); errors.pushNestedPath("spouse"); assertThat(errors.getNestedPath()).isEqualTo("spouse."); errors.pushNestedPath("spouse"); @@ -1156,7 +1156,7 @@ class DataBinderTests { errors.popNestedPath(); assertThat(errors.getNestedPath()).isEqualTo("spouse."); errors.popNestedPath(); - assertThat(errors.getNestedPath()).isEqualTo(""); + assertThat(errors.getNestedPath()).isEmpty(); try { errors.popNestedPath(); } @@ -1166,7 +1166,7 @@ class DataBinderTests { errors.pushNestedPath("spouse"); assertThat(errors.getNestedPath()).isEqualTo("spouse."); errors.setNestedPath(""); - assertThat(errors.getNestedPath()).isEqualTo(""); + assertThat(errors.getNestedPath()).isEmpty(); try { errors.popNestedPath(); } 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 83138f4344f..060869a17f0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -200,7 +200,7 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(parent, "parent"); validatorAdapter.validate(parent, errors); - assertThat(errors.getErrorCount() > 0).isTrue(); + assertThat(errors.getErrorCount()).isGreaterThan(0); } @Test // SPR-16177 @@ -212,7 +212,7 @@ public class SpringValidatorAdapterTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(parent, "parent"); validatorAdapter.validate(parent, errors); - assertThat(errors.getErrorCount() > 0).isTrue(); + assertThat(errors.getErrorCount()).isGreaterThan(0); } 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 bcbeda94f7c..37b867ca2fd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,7 +76,7 @@ class ValidatorFactoryTests { } Validator nativeValidator = validator.unwrap(Validator.class); - assertThat(nativeValidator.getClass().getName().startsWith("org.hibernate")).isTrue(); + assertThat(nativeValidator.getClass().getName()).startsWith("org.hibernate"); assertThat(validator.unwrap(ValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); assertThat(validator.unwrap(HibernateValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); @@ -100,7 +100,7 @@ class ValidatorFactoryTests { } Validator nativeValidator = validator.unwrap(Validator.class); - assertThat(nativeValidator.getClass().getName().startsWith("org.hibernate")).isTrue(); + assertThat(nativeValidator.getClass().getName()).startsWith("org.hibernate"); assertThat(validator.unwrap(ValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); assertThat(validator.unwrap(HibernateValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); @@ -120,8 +120,8 @@ class ValidatorFactoryTests { assertThat(result).hasSize(1); Iterator> iterator = result.iterator(); ConstraintViolation cv = iterator.next(); - assertThat(cv.getPropertyPath().toString()).isEqualTo(""); - assertThat(cv.getConstraintDescriptor().getAnnotation() instanceof NameAddressValid).isTrue(); + assertThat(cv.getPropertyPath().toString()).isEmpty(); + assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NameAddressValid.class); validator.destroy(); } diff --git a/spring-context/src/testFixtures/java/org/springframework/context/testfixture/AbstractApplicationContextTests.java b/spring-context/src/testFixtures/java/org/springframework/context/testfixture/AbstractApplicationContextTests.java index e3ba64f369f..f10034d916a 100644 --- a/spring-context/src/testFixtures/java/org/springframework/context/testfixture/AbstractApplicationContextTests.java +++ b/spring-context/src/testFixtures/java/org/springframework/context/testfixture/AbstractApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,30 +82,30 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe @Test public void contextAwareSingletonWasCalledBack() throws Exception { ACATester aca = (ACATester) applicationContext.getBean("aca"); - assertThat(aca.getApplicationContext() == applicationContext).as("has had context set").isTrue(); + assertThat(aca.getApplicationContext()).as("has had context set").isSameAs(applicationContext); Object aca2 = applicationContext.getBean("aca"); - assertThat(aca == aca2).as("Same instance").isTrue(); + assertThat(aca).as("Same instance").isSameAs(aca2); assertThat(applicationContext.isSingleton("aca")).as("Says is singleton").isTrue(); } @Test public void contextAwarePrototypeWasCalledBack() throws Exception { ACATester aca = (ACATester) applicationContext.getBean("aca-prototype"); - assertThat(aca.getApplicationContext() == applicationContext).as("has had context set").isTrue(); + assertThat(aca.getApplicationContext()).as("has had context set").isSameAs(applicationContext); Object aca2 = applicationContext.getBean("aca-prototype"); - assertThat(aca != aca2).as("NOT Same instance").isTrue(); + assertThat(aca).as("NOT Same instance").isNotSameAs(aca2); boolean condition = !applicationContext.isSingleton("aca-prototype"); assertThat(condition).as("Says is prototype").isTrue(); } @Test public void parentNonNull() { - assertThat(applicationContext.getParent() != null).as("parent isn't null").isTrue(); + assertThat(applicationContext.getParent()).as("parent isn't null").isNotNull(); } @Test public void grandparentNull() { - assertThat(applicationContext.getParent().getParent() == null).as("grandparent is null").isTrue(); + assertThat(applicationContext.getParent().getParent()).as("grandparent is null").isNull(); } @Test @@ -173,11 +173,12 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe MyEvent event) { listener.zeroCounter(); parentListener.zeroCounter(); - assertThat(listener.getEventCount() == 0).as("0 events before publication").isTrue(); - assertThat(parentListener.getEventCount() == 0).as("0 parent events before publication").isTrue(); + assertThat(listener.getEventCount()).as("0 events before publication").isEqualTo(0); + assertThat(parentListener.getEventCount()).as("0 parent events before publication").isEqualTo(0); this.applicationContext.publishEvent(event); - assertThat(listener.getEventCount() == 1).as("1 events after publication, not " + listener.getEventCount()).isTrue(); - assertThat(parentListener.getEventCount() == 1).as("1 parent events after publication").isTrue(); + assertThat(listener.getEventCount()).as("1 events after publication, not " + listener.getEventCount()) + .isEqualTo(1); + assertThat(parentListener.getEventCount()).as("1 parent events after publication").isEqualTo(1); } @Test @@ -186,9 +187,9 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe //assertTrue("listeners include beanThatListens", Arrays.asList(listenerNames).contains("beanThatListens")); BeanThatListens b = (BeanThatListens) applicationContext.getBean("beanThatListens"); b.zero(); - assertThat(b.getEventCount() == 0).as("0 events before publication").isTrue(); + assertThat(b.getEventCount()).as("0 events before publication").isEqualTo(0); this.applicationContext.publishEvent(new MyEvent(this)); - assertThat(b.getEventCount() == 1).as("1 events after publication, not " + b.getEventCount()).isTrue(); + assertThat(b.getEventCount()).as("1 events after publication, not " + b.getEventCount()).isEqualTo(1); } diff --git a/spring-core/src/test/java/org/springframework/aot/hint/SimpleTypeReferenceTests.java b/spring-core/src/test/java/org/springframework/aot/hint/SimpleTypeReferenceTests.java index b3195aad1f3..cd49682efc2 100644 --- a/spring-core/src/test/java/org/springframework/aot/hint/SimpleTypeReferenceTests.java +++ b/spring-core/src/test/java/org/springframework/aot/hint/SimpleTypeReferenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,7 +95,7 @@ class SimpleTypeReferenceTests { void typeReferenceInRootPackage() { TypeReference type = SimpleTypeReference.of("MyRootClass"); assertThat(type.getCanonicalName()).isEqualTo("MyRootClass"); - assertThat(type.getPackageName()).isEqualTo(""); + assertThat(type.getPackageName()).isEmpty(); } @ParameterizedTest(name = "{0}") 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 ee2156319f0..1c24092ff19 100644 --- a/spring-core/src/test/java/org/springframework/core/ConstantsTests.java +++ b/spring-core/src/test/java/org/springframework/core/ConstantsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ class ConstantsTests { assertThatExceptionOfType(Constants.ConstantException.class).isThrownBy(() -> c.asNumber("bogus")); - assertThat(c.asString("S1").equals(A.S1)).isTrue(); + assertThat(c.asString("S1")).isEqualTo(A.S1); assertThatExceptionOfType(Constants.ConstantException.class).as("wrong type").isThrownBy(() -> c.asNumber("S1")); } @@ -194,21 +194,21 @@ class ConstantsTests { void getValuesWithNullPrefix() throws Exception { Constants c = new Constants(A.class); Set values = c.getValues(null); - assertThat(values.size()).as("Must have returned *all* public static final values").isEqualTo(7); + assertThat(values).as("Must have returned *all* public static final values").hasSize(7); } @Test void getValuesWithEmptyStringPrefix() throws Exception { Constants c = new Constants(A.class); Set values = c.getValues(""); - assertThat(values.size()).as("Must have returned *all* public static final values").isEqualTo(7); + assertThat(values).as("Must have returned *all* public static final values").hasSize(7); } @Test void getValuesWithWhitespacedStringPrefix() throws Exception { Constants c = new Constants(A.class); Set values = c.getValues(" "); - assertThat(values.size()).as("Must have returned *all* public static final values").isEqualTo(7); + assertThat(values).as("Must have returned *all* public static final values").hasSize(7); } @Test 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 ecd54e55cbf..5a00a7aa9df 100644 --- a/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java +++ b/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ class LocalVariableTableParameterNameDiscovererTests { Method getName = TestObject.class.getMethod("getName"); String[] names = discoverer.getParameterNames(getName); assertThat(names).as("should find method info").isNotNull(); - assertThat(names.length).as("no argument names").isEqualTo(0); + assertThat(names).as("no argument names").isEmpty(); } @Test @@ -51,7 +51,7 @@ class LocalVariableTableParameterNameDiscovererTests { Method setName = TestObject.class.getMethod("setName", String.class); String[] names = discoverer.getParameterNames(setName); assertThat(names).as("should find method info").isNotNull(); - assertThat(names.length).as("one argument").isEqualTo(1); + assertThat(names).as("one argument").hasSize(1); assertThat(names[0]).isEqualTo("name"); } @@ -60,7 +60,7 @@ class LocalVariableTableParameterNameDiscovererTests { Constructor noArgsCons = TestObject.class.getConstructor(); String[] names = discoverer.getParameterNames(noArgsCons); assertThat(names).as("should find cons info").isNotNull(); - assertThat(names.length).as("no argument names").isEqualTo(0); + assertThat(names).as("no argument names").isEmpty(); } @Test @@ -68,7 +68,7 @@ class LocalVariableTableParameterNameDiscovererTests { Constructor twoArgCons = TestObject.class.getConstructor(String.class, int.class); String[] names = discoverer.getParameterNames(twoArgCons); assertThat(names).as("should find cons info").isNotNull(); - assertThat(names.length).as("one argument").isEqualTo(2); + assertThat(names).as("one argument").hasSize(2); assertThat(names[0]).isEqualTo("name"); assertThat(names[1]).isEqualTo("age"); } @@ -78,7 +78,7 @@ class LocalVariableTableParameterNameDiscovererTests { Method m = getClass().getMethod("staticMethodNoLocalVars"); String[] names = discoverer.getParameterNames(m); assertThat(names).as("should find method info").isNotNull(); - assertThat(names.length).as("no argument names").isEqualTo(0); + assertThat(names).as("no argument names").isEmpty(); } @Test @@ -88,14 +88,14 @@ class LocalVariableTableParameterNameDiscovererTests { Method m1 = clazz.getMethod("staticMethod", Long.TYPE, Long.TYPE); String[] names = discoverer.getParameterNames(m1); assertThat(names).as("should find method info").isNotNull(); - assertThat(names.length).as("two arguments").isEqualTo(2); + assertThat(names).as("two arguments").hasSize(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); assertThat(names).as("should find method info").isNotNull(); - assertThat(names.length).as("three arguments").isEqualTo(3); + assertThat(names).as("three arguments").hasSize(3); assertThat(names[0]).isEqualTo("x"); assertThat(names[1]).isEqualTo("y"); assertThat(names[2]).isEqualTo("z"); @@ -108,13 +108,13 @@ class LocalVariableTableParameterNameDiscovererTests { Method m1 = clazz.getMethod("staticMethod", Long.TYPE); String[] names = discoverer.getParameterNames(m1); assertThat(names).as("should find method info").isNotNull(); - assertThat(names.length).as("one argument").isEqualTo(1); + assertThat(names).as("one argument").hasSize(1); assertThat(names[0]).isEqualTo("x"); Method m2 = clazz.getMethod("staticMethod", Long.TYPE, Long.TYPE); names = discoverer.getParameterNames(m2); assertThat(names).as("should find method info").isNotNull(); - assertThat(names.length).as("two arguments").isEqualTo(2); + assertThat(names).as("two arguments").hasSize(2); assertThat(names[0]).isEqualTo("x"); assertThat(names[1]).isEqualTo("y"); } @@ -126,14 +126,14 @@ class LocalVariableTableParameterNameDiscovererTests { Method m1 = clazz.getMethod("instanceMethod", Double.TYPE, Double.TYPE); String[] names = discoverer.getParameterNames(m1); assertThat(names).as("should find method info").isNotNull(); - assertThat(names.length).as("two arguments").isEqualTo(2); + assertThat(names).as("two arguments").hasSize(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); assertThat(names).as("should find method info").isNotNull(); - assertThat(names.length).as("three arguments").isEqualTo(3); + assertThat(names).as("three arguments").hasSize(3); assertThat(names[0]).isEqualTo("x"); assertThat(names[1]).isEqualTo("y"); assertThat(names[2]).isEqualTo("z"); @@ -146,13 +146,13 @@ class LocalVariableTableParameterNameDiscovererTests { Method m1 = clazz.getMethod("instanceMethod", String.class); String[] names = discoverer.getParameterNames(m1); assertThat(names).as("should find method info").isNotNull(); - assertThat(names.length).as("one argument").isEqualTo(1); + assertThat(names).as("one argument").hasSize(1); assertThat(names[0]).isEqualTo("aa"); Method m2 = clazz.getMethod("instanceMethod", String.class, String.class); names = discoverer.getParameterNames(m2); assertThat(names).as("should find method info").isNotNull(); - assertThat(names.length).as("two arguments").isEqualTo(2); + assertThat(names).as("two arguments").hasSize(2); assertThat(names[0]).isEqualTo("aa"); assertThat(names[1]).isEqualTo("bb"); } 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 75ae527c970..3a7a5ab2490 100644 --- a/spring-core/src/test/java/org/springframework/core/ReactiveAdapterRegistryTests.java +++ b/spring-core/src/test/java/org/springframework/core/ReactiveAdapterRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,7 +100,7 @@ class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Publisher source = io.reactivex.rxjava3.core.Flowable.fromIterable(sequence); Object target = getAdapter(Flux.class).fromPublisher(source); - assertThat(target instanceof Flux).isTrue(); + assertThat(target).isInstanceOf(Flux.class); assertThat(((Flux) target).collectList().block(ONE_SECOND)).isEqualTo(sequence); } @@ -108,7 +108,7 @@ class ReactiveAdapterRegistryTests { void toMono() { Publisher source = io.reactivex.rxjava3.core.Flowable.fromArray(1, 2, 3); Object target = getAdapter(Mono.class).fromPublisher(source); - assertThat(target instanceof Mono).isTrue(); + assertThat(target).isInstanceOf(Mono.class); assertThat(((Mono) target).block(ONE_SECOND)).isEqualTo(Integer.valueOf(1)); } @@ -116,7 +116,7 @@ class ReactiveAdapterRegistryTests { void toCompletableFuture() throws Exception { Publisher source = Flux.fromArray(new Integer[] {1, 2, 3}); Object target = getAdapter(CompletableFuture.class).fromPublisher(source); - assertThat(target instanceof CompletableFuture).isTrue(); + assertThat(target).isInstanceOf(CompletableFuture.class); assertThat(((CompletableFuture) target).get()).isEqualTo(Integer.valueOf(1)); } @@ -125,7 +125,7 @@ class ReactiveAdapterRegistryTests { CompletableFuture future = new CompletableFuture<>(); future.complete(1); Object target = getAdapter(CompletableFuture.class).toPublisher(future); - assertThat(target instanceof Mono).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue(); + assertThat(target).as("Expected Mono Publisher: " + target.getClass().getName()).isInstanceOf(Mono.class); assertThat(((Mono) target).block(ONE_SECOND)).isEqualTo(Integer.valueOf(1)); } } @@ -149,7 +149,7 @@ class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Publisher source = Flux.fromIterable(sequence); Object target = getAdapter(io.reactivex.rxjava3.core.Flowable.class).fromPublisher(source); - assertThat(target instanceof io.reactivex.rxjava3.core.Flowable).isTrue(); + assertThat(target).isInstanceOf(io.reactivex.rxjava3.core.Flowable.class); assertThat(((io.reactivex.rxjava3.core.Flowable) target).toList().blockingGet()).isEqualTo(sequence); } @@ -158,7 +158,7 @@ class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Publisher source = Flux.fromIterable(sequence); Object target = getAdapter(io.reactivex.rxjava3.core.Observable.class).fromPublisher(source); - assertThat(target instanceof io.reactivex.rxjava3.core.Observable).isTrue(); + assertThat(target).isInstanceOf(io.reactivex.rxjava3.core.Observable.class); assertThat(((io.reactivex.rxjava3.core.Observable) target).toList().blockingGet()).isEqualTo(sequence); } @@ -166,7 +166,7 @@ class ReactiveAdapterRegistryTests { void toSingle() { Publisher source = Flux.fromArray(new Integer[] {1}); Object target = getAdapter(io.reactivex.rxjava3.core.Single.class).fromPublisher(source); - assertThat(target instanceof io.reactivex.rxjava3.core.Single).isTrue(); + assertThat(target).isInstanceOf(io.reactivex.rxjava3.core.Single.class); assertThat(((io.reactivex.rxjava3.core.Single) target).blockingGet()).isEqualTo(Integer.valueOf(1)); } @@ -174,7 +174,7 @@ class ReactiveAdapterRegistryTests { void toCompletable() { Publisher source = Flux.fromArray(new Integer[] {1, 2, 3}); Object target = getAdapter(io.reactivex.rxjava3.core.Completable.class).fromPublisher(source); - assertThat(target instanceof io.reactivex.rxjava3.core.Completable).isTrue(); + assertThat(target).isInstanceOf(io.reactivex.rxjava3.core.Completable.class); ((io.reactivex.rxjava3.core.Completable) target).blockingAwait(); } @@ -183,7 +183,7 @@ class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Object source = io.reactivex.rxjava3.core.Flowable.fromIterable(sequence); Object target = getAdapter(io.reactivex.rxjava3.core.Flowable.class).toPublisher(source); - assertThat(target instanceof Flux).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue(); + assertThat(target).as("Expected Flux Publisher: " + target.getClass().getName()).isInstanceOf(Flux.class); assertThat(((Flux) target).collectList().block(ONE_SECOND)).isEqualTo(sequence); } @@ -192,7 +192,7 @@ class ReactiveAdapterRegistryTests { List sequence = Arrays.asList(1, 2, 3); Object source = io.reactivex.rxjava3.core.Observable.fromIterable(sequence); Object target = getAdapter(io.reactivex.rxjava3.core.Observable.class).toPublisher(source); - assertThat(target instanceof Flux).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue(); + assertThat(target).as("Expected Flux Publisher: " + target.getClass().getName()).isInstanceOf(Flux.class); assertThat(((Flux) target).collectList().block(ONE_SECOND)).isEqualTo(sequence); } @@ -200,7 +200,7 @@ class ReactiveAdapterRegistryTests { void fromSingle() { Object source = io.reactivex.rxjava3.core.Single.just(1); Object target = getAdapter(io.reactivex.rxjava3.core.Single.class).toPublisher(source); - assertThat(target instanceof Mono).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue(); + assertThat(target).as("Expected Mono Publisher: " + target.getClass().getName()).isInstanceOf(Mono.class); assertThat(((Mono) target).block(ONE_SECOND)).isEqualTo(Integer.valueOf(1)); } @@ -208,7 +208,7 @@ class ReactiveAdapterRegistryTests { void fromCompletable() { Object source = io.reactivex.rxjava3.core.Completable.complete(); Object target = getAdapter(io.reactivex.rxjava3.core.Completable.class).toPublisher(source); - assertThat(target instanceof Mono).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue(); + assertThat(target).as("Expected Mono Publisher: " + target.getClass().getName()).isInstanceOf(Mono.class); ((Mono) target).block(ONE_SECOND); } } 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 97ff1aabb51..481163c306f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,8 @@ class AnnotationAwareOrderComparatorTests { list.add(new B()); list.add(new A()); AnnotationAwareOrderComparator.sort(list); - assertThat(list.get(0) instanceof A).isTrue(); - assertThat(list.get(1) instanceof B).isTrue(); + assertThat(list.get(0)).isInstanceOf(A.class); + assertThat(list.get(1)).isInstanceOf(B.class); } @Test @@ -51,8 +51,8 @@ class AnnotationAwareOrderComparatorTests { list.add(new B2()); list.add(new A2()); AnnotationAwareOrderComparator.sort(list); - assertThat(list.get(0) instanceof A2).isTrue(); - assertThat(list.get(1) instanceof B2).isTrue(); + assertThat(list.get(0)).isInstanceOf(A2.class); + assertThat(list.get(1)).isInstanceOf(B2.class); } @Test @@ -61,8 +61,8 @@ class AnnotationAwareOrderComparatorTests { list.add(new B()); list.add(new A2()); AnnotationAwareOrderComparator.sort(list); - assertThat(list.get(0) instanceof A2).isTrue(); - assertThat(list.get(1) instanceof B).isTrue(); + assertThat(list.get(0)).isInstanceOf(A2.class); + assertThat(list.get(1)).isInstanceOf(B.class); } @Test @@ -71,8 +71,8 @@ class AnnotationAwareOrderComparatorTests { list.add(new B()); list.add(new C()); AnnotationAwareOrderComparator.sort(list); - assertThat(list.get(0) instanceof C).isTrue(); - assertThat(list.get(1) instanceof B).isTrue(); + assertThat(list.get(0)).isInstanceOf(C.class); + assertThat(list.get(1)).isInstanceOf(B.class); } @Test 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 248a809d604..f181a1af13a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -563,7 +563,7 @@ class AnnotationUtilsTests { Set annotations = getRepeatableAnnotations(ConfigHierarchyTestCase.class, ContextConfig.class, null); assertThat(annotations).isNotNull(); - assertThat(annotations.size()).as("size if container type is omitted: ").isEqualTo(0); + assertThat(annotations).as("size if container type is omitted: ").isEmpty(); annotations = getRepeatableAnnotations(ConfigHierarchyTestCase.class, ContextConfig.class, Hierarchy.class); assertThat(annotations).isNotNull(); @@ -855,8 +855,8 @@ class AnnotationUtilsTests { void synthesizeAnnotationFromDefaultsWithAttributeAliases() throws Exception { ContextConfig contextConfig = synthesizeAnnotation(ContextConfig.class); assertThat(contextConfig).isNotNull(); - assertThat(contextConfig.value()).as("value: ").isEqualTo(""); - assertThat(contextConfig.location()).as("location: ").isEqualTo(""); + assertThat(contextConfig.value()).as("value: ").isEmpty(); + assertThat(contextConfig.location()).as("location: ").isEmpty(); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java b/spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java index 47a34c234cf..8ffd0eeb893 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java @@ -1923,8 +1923,8 @@ class MergedAnnotationsTests { MergedAnnotation annotation = MergedAnnotation.of( TestConfiguration.class); TestConfiguration synthesized = annotation.synthesize(); - assertThat(synthesized.value()).isEqualTo(""); - assertThat(synthesized.location()).isEqualTo(""); + assertThat(synthesized.value()).isEmpty(); + assertThat(synthesized.location()).isEmpty(); } @Test diff --git a/spring-core/src/test/java/org/springframework/core/annotation/TypeMappedAnnotationTests.java b/spring-core/src/test/java/org/springframework/core/annotation/TypeMappedAnnotationTests.java index a60173d537b..d04d16a015f 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/TypeMappedAnnotationTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/TypeMappedAnnotationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,7 +65,7 @@ class TypeMappedAnnotationTests { WithConventionAliasToMetaAnnotation.class, ConventionAliasToMetaAnnotation.class, ConventionAliasMetaAnnotationTarget.class); - assertThat(annotation.getString("value")).isEqualTo(""); + assertThat(annotation.getString("value")).isEmpty(); assertThat(annotation.getString("convention")).isEqualTo("convention"); } diff --git a/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java index e73bb2c1245..0aa583ae978 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,7 +82,8 @@ class CharSequenceEncoderTests extends AbstractEncoderTests .forEach(charset -> { int capacity = this.encoder.calculateCapacity(sequence, charset); int length = sequence.length(); - assertThat(capacity >= length).as(String.format("%s has capacity %d; length %d", charset, capacity, length)).isTrue(); + assertThat(capacity).as(String.format("%s has capacity %d; length %d", charset, capacity, length)) + .isGreaterThanOrEqualTo(length); }); } 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 c48a8105d5b..5fe86254899 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,7 @@ class TypeDescriptorTests { 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.isPrimitive()).isFalse(); assertThat(desc.getAnnotations()).isEmpty(); assertThat(desc.isCollection()).isFalse(); assertThat(desc.isArray()).isFalse(); @@ -92,7 +92,7 @@ class TypeDescriptorTests { 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.isPrimitive()).isFalse(); assertThat(desc.getAnnotations()).isEmpty(); assertThat(desc.isCollection()).isTrue(); assertThat(desc.isArray()).isFalse(); @@ -113,7 +113,7 @@ class TypeDescriptorTests { 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.isPrimitive()).isFalse(); assertThat(desc.getAnnotations()).isEmpty(); assertThat(desc.isCollection()).isTrue(); assertThat(desc.isArray()).isFalse(); @@ -129,7 +129,7 @@ class TypeDescriptorTests { 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.isPrimitive()).isFalse(); assertThat(desc.getAnnotations()).isEmpty(); assertThat(desc.isCollection()).isFalse(); assertThat(desc.isArray()).isTrue(); @@ -146,7 +146,7 @@ class TypeDescriptorTests { 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.isPrimitive()).isFalse(); assertThat(desc.getAnnotations()).isEmpty(); assertThat(desc.isCollection()).isFalse(); assertThat(desc.isArray()).isFalse(); @@ -462,7 +462,7 @@ class TypeDescriptorTests { 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.isPrimitive()).isFalse(); assertThat(desc.getAnnotations()).isEmpty(); assertThat(desc.isCollection()).isTrue(); assertThat(desc.isArray()).isFalse(); @@ -478,7 +478,7 @@ class TypeDescriptorTests { 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.isPrimitive()).isFalse(); assertThat(desc.getAnnotations()).isEmpty(); assertThat(desc.isCollection()).isTrue(); assertThat(desc.isArray()).isFalse(); @@ -494,7 +494,7 @@ class TypeDescriptorTests { 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.isPrimitive()).isFalse(); assertThat(desc.getAnnotations()).isEmpty(); assertThat(desc.isCollection()).isFalse(); assertThat(desc.isArray()).isFalse(); @@ -511,7 +511,7 @@ class TypeDescriptorTests { 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.isPrimitive()).isFalse(); assertThat(desc.getAnnotations()).isEmpty(); assertThat(desc.isCollection()).isFalse(); assertThat(desc.isArray()).isFalse(); @@ -668,7 +668,7 @@ class TypeDescriptorTests { getClass().getMethod("setProperty", Map.class)); TypeDescriptor typeDescriptor = new TypeDescriptor(property); TypeDescriptor upCast = typeDescriptor.upcast(Object.class); - assertThat(upCast.getAnnotation(MethodAnnotation1.class) != null).isTrue(); + assertThat(upCast.getAnnotation(MethodAnnotation1.class)).isNotNull(); } @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 f30493e82a9..f4280616767 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 @@ -402,7 +402,7 @@ class DefaultConversionServiceTests { @Test void convertEmptyArrayToString() { String result = conversionService.convert(new String[0], String.class); - assertThat(result).isEqualTo(""); + assertThat(result).isEmpty(); } @Test @@ -739,8 +739,8 @@ class DefaultConversionServiceTests { foo.setProperty("1", "BAR"); foo.setProperty("2", "BAZ"); String result = conversionService.convert(foo, String.class); - assertThat(result.contains("1=BAR")).isTrue(); - assertThat(result.contains("2=BAZ")).isTrue(); + assertThat(result).contains("1=BAR"); + assertThat(result).contains("2=BAZ"); } @Test @@ -749,7 +749,7 @@ class DefaultConversionServiceTests { assertThat(result).hasSize(3); assertThat(result.getProperty("a")).isEqualTo("b"); assertThat(result.getProperty("c")).isEqualTo("2"); - assertThat(result.getProperty("d")).isEqualTo(""); + assertThat(result.getProperty("d")).isEmpty(); } @Test @@ -811,7 +811,7 @@ class DefaultConversionServiceTests { @Test void convertObjectToStringWithJavaTimeOfMethodPresent() { - assertThat(conversionService.convert(ZoneId.of("GMT+1"), String.class).startsWith("GMT+")).isTrue(); + assertThat(conversionService.convert(ZoneId.of("GMT+1"), String.class)).startsWith("GMT+"); } @Test @@ -895,7 +895,7 @@ class DefaultConversionServiceTests { TypeDescriptor descriptor = new TypeDescriptor(parameter); Object actual = conversionService.convert("1,2,3", TypeDescriptor.valueOf(String.class), descriptor); assertThat(actual.getClass()).isEqualTo(Optional.class); - assertThat(((Optional>) actual).get()).isEqualTo(List.of(1, 2, 3)); + assertThat(((Optional>) actual)).contains(List.of(1, 2, 3)); } @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 f1ee4af8112..6344e50dacd 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -195,7 +195,7 @@ class CollectionToCollectionConverterTests { aSource, TypeDescriptor.forObject(aSource), TypeDescriptor.forObject(new ArrayList())); boolean condition = myConverted instanceof ArrayList; assertThat(condition).isTrue(); - assertThat(((ArrayList) myConverted)).hasSize(aSource.size()); + assertThat(((ArrayList) myConverted)).hasSameSizeAs(aSource); } @Test 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 a82108ca57a..596e068b152 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,8 +131,8 @@ class GenericConversionServiceTests { @Test void convertAssignableSource() { - assertThat(conversionService.convert(false, boolean.class)).isEqualTo(Boolean.FALSE); - assertThat(conversionService.convert(false, Boolean.class)).isEqualTo(Boolean.FALSE); + assertThat(conversionService.convert(false, boolean.class)).isFalse(); + assertThat(conversionService.convert(false, Boolean.class)).isFalse(); } @Test @@ -387,7 +387,7 @@ class GenericConversionServiceTests { GenericConverter.ConvertiblePair pair = new GenericConverter.ConvertiblePair(Number.class, String.class); GenericConverter.ConvertiblePair pairOpposite = new GenericConverter.ConvertiblePair(String.class, Number.class); assertThat(pair.equals(pairOpposite)).isFalse(); - assertThat(pair.hashCode() == pairOpposite.hashCode()).isFalse(); + assertThat(pair.hashCode()).isNotEqualTo(pairOpposite.hashCode()); } @Test @@ -416,7 +416,7 @@ class GenericConversionServiceTests { conversionService.addConverter(new ColorConverter()); conversionService.addConverter(converter); assertThat(conversionService.convert("#000000", Color.class)).isEqualTo(Color.BLACK); - assertThat(converter.getMatchAttempts() > 0).isTrue(); + assertThat(converter.getMatchAttempts()).isGreaterThan(0); } @Test @@ -425,8 +425,8 @@ class GenericConversionServiceTests { conversionService.addConverter(new ColorConverter()); conversionService.addConverterFactory(converter); assertThat(conversionService.convert("#000000", Color.class)).isEqualTo(Color.BLACK); - assertThat(converter.getMatchAttempts() > 0).isTrue(); - assertThat(converter.getNestedMatchAttempts() > 0).isTrue(); + assertThat(converter.getMatchAttempts()).isGreaterThan(0); + assertThat(converter.getNestedMatchAttempts()).isGreaterThan(0); } @Test @@ -457,7 +457,7 @@ class GenericConversionServiceTests { MyConditionalGenericConverter converter = new MyConditionalGenericConverter(); conversionService.addConverter(converter); assertThat(conversionService.convert(3, Integer.class)).isEqualTo(3); - assertThat(converter.getSourceTypes().size()).isGreaterThan(2); + assertThat(converter.getSourceTypes()).hasSizeGreaterThan(2); assertThat(converter.getSourceTypes().stream().allMatch(td -> Integer.class.equals(td.getType()))).isTrue(); } 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 24cc47ef919..e8d4e74f54f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,7 +65,7 @@ class MapToMapConverterTests { conversionService.convert(map, sourceType, targetType); } catch (ConversionFailedException ex) { - assertThat(ex.getCause() instanceof ConverterNotFoundException).isTrue(); + assertThat(ex.getCause()).isInstanceOf(ConverterNotFoundException.class); } conversionService.addConverterFactory(new StringToNumberConverterFactory()); @@ -100,7 +100,7 @@ class MapToMapConverterTests { conversionService.convert(map, sourceType, targetType); } catch (ConversionFailedException ex) { - assertThat(ex.getCause() instanceof ConverterNotFoundException).isTrue(); + assertThat(ex.getCause()).isInstanceOf(ConverterNotFoundException.class); } conversionService.addConverterFactory(new StringToNumberConverterFactory()); @@ -125,7 +125,7 @@ class MapToMapConverterTests { conversionService.convert(map, sourceType, targetType); } catch (ConversionFailedException ex) { - assertThat(ex.getCause() instanceof ConverterNotFoundException).isTrue(); + assertThat(ex.getCause()).isInstanceOf(ConverterNotFoundException.class); } conversionService.addConverter(new CollectionToCollectionConverter(conversionService)); diff --git a/spring-core/src/test/java/org/springframework/core/env/SimpleCommandLinePropertySourceTests.java b/spring-core/src/test/java/org/springframework/core/env/SimpleCommandLinePropertySourceTests.java index 9b67142de75..a4404332b7a 100644 --- a/spring-core/src/test/java/org/springframework/core/env/SimpleCommandLinePropertySourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/SimpleCommandLinePropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ class SimpleCommandLinePropertySourceTests { assertThat(ps.containsProperty("o2")).isTrue(); assertThat(ps.containsProperty("o3")).isFalse(); assertThat(ps.getProperty("o1")).isEqualTo("v1"); - assertThat(ps.getProperty("o2")).isEqualTo(""); + assertThat(ps.getProperty("o2")).isEmpty(); assertThat(ps.getProperty("o3")).isNull(); } 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 92ac7600ef8..d93c4bfba2c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,14 +53,14 @@ class ResourceEditorTests { void setAndGetAsTextWithNull() { PropertyEditor editor = new ResourceEditor(); editor.setAsText(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); } @Test void setAndGetAsTextWithWhitespaceResource() { PropertyEditor editor = new ResourceEditor(); editor.setAsText(" "); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); } @Test 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 a7f8316f943..e83286584e0 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 @@ -393,7 +393,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests { assertThat(buffer.capacity()).isEqualTo(1); buffer.write((byte) 'b'); - assertThat(buffer.capacity() > 1).isTrue(); + assertThat(buffer.capacity()).isGreaterThan(1); release(buffer); } 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 1eb126fc027..a3bb98d251a 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 @@ -330,7 +330,7 @@ class AnnotationMetadataTests { assertThat(specialAttrs.getEnum("state").equals(Thread.State.NEW)).isTrue(); AnnotationAttributes nestedAnno = specialAttrs.getAnnotation("nestedAnno"); - assertThat("na").isEqualTo(nestedAnno.getString("value")); + assertThat(nestedAnno.getString("value")).isEqualTo("na"); assertThat(nestedAnno.getEnum("anEnum").equals(SomeEnum.LABEL1)).isTrue(); assertThat((Class[]) nestedAnno.get("classArray")).isEqualTo(new Class[] {String.class}); diff --git a/spring-core/src/test/java/org/springframework/tests/MockitoUtils.java b/spring-core/src/test/java/org/springframework/tests/MockitoUtils.java index b0cb590548f..7ee4617b953 100644 --- a/spring-core/src/test/java/org/springframework/tests/MockitoUtils.java +++ b/spring-core/src/test/java/org/springframework/tests/MockitoUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ public abstract class MockitoUtils { private static void verifySameInvocations(List expectedInvocations, List actualInvocations, InvocationArgumentsAdapter... argumentAdapters) { - assertThat(expectedInvocations).hasSize(actualInvocations.size()); + assertThat(expectedInvocations).hasSameSizeAs(actualInvocations); for (int i = 0; i < expectedInvocations.size(); i++) { verifySameInvocation(expectedInvocations.get(i), actualInvocations.get(i), argumentAdapters); } 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 5f1256a7067..8a6bc82921b 100644 --- a/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java +++ b/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -300,7 +300,7 @@ class AntPathMatcherTests { @Test void extractPathWithinPattern() throws Exception { - assertThat(pathMatcher.extractPathWithinPattern("/docs/commit.html", "/docs/commit.html")).isEqualTo(""); + assertThat(pathMatcher.extractPathWithinPattern("/docs/commit.html", "/docs/commit.html")).isEmpty(); assertThat(pathMatcher.extractPathWithinPattern("/docs/*", "/docs/cvs/commit")).isEqualTo("cvs/commit"); assertThat(pathMatcher.extractPathWithinPattern("/docs/cvs/*.html", "/docs/cvs/commit.html")).isEqualTo("commit.html"); @@ -410,7 +410,7 @@ class AntPathMatcherTests { @Test void combine() { - assertThat(pathMatcher.combine(null, null)).isEqualTo(""); + assertThat(pathMatcher.combine(null, null)).isEmpty(); assertThat(pathMatcher.combine("/hotels", null)).isEqualTo("/hotels"); assertThat(pathMatcher.combine(null, "/hotels")).isEqualTo("/hotels"); assertThat(pathMatcher.combine("/hotels/*", "booking")).isEqualTo("/hotels/booking"); @@ -622,7 +622,7 @@ class AntPathMatcherTests { @Test void defaultCacheSetting() { match(); - assertThat(pathMatcher.stringMatcherCache.size() > 20).isTrue(); + assertThat(pathMatcher.stringMatcherCache).hasSizeGreaterThan(20); for (int i = 0; i < 65536; i++) { pathMatcher.match("test" + i, "test"); @@ -635,13 +635,13 @@ class AntPathMatcherTests { void cachePatternsSetToTrue() { pathMatcher.setCachePatterns(true); match(); - assertThat(pathMatcher.stringMatcherCache.size() > 20).isTrue(); + assertThat(pathMatcher.stringMatcherCache).hasSizeGreaterThan(20); for (int i = 0; i < 65536; i++) { pathMatcher.match("test" + i, "test" + i); } // Cache keeps being alive due to the explicit cache setting - assertThat(pathMatcher.stringMatcherCache.size() > 65536).isTrue(); + assertThat(pathMatcher.stringMatcherCache).hasSizeGreaterThan(65536); } @Test 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 898bde78f02..d894f91fb8c 100644 --- a/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -334,7 +334,7 @@ class ClassUtilsTests { void getAllInterfaces() { DerivedTestObject testBean = new DerivedTestObject(); List> ifcs = Arrays.asList(ClassUtils.getAllInterfaces(testBean)); - assertThat(ifcs.size()).as("Correct number of interfaces").isEqualTo(4); + assertThat(ifcs).as("Correct number of interfaces").hasSize(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(); 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 4f49f7610f0..e89c999055e 100644 --- a/spring-core/src/test/java/org/springframework/util/FileSystemUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/FileSystemUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,17 +39,17 @@ class FileSystemUtilsTests { File bar = new File(child, "bar.txt"); bar.createNewFile(); - assertThat(root.exists()).isTrue(); - assertThat(child.exists()).isTrue(); - assertThat(grandchild.exists()).isTrue(); - assertThat(bar.exists()).isTrue(); + assertThat(root).exists(); + assertThat(child).exists(); + assertThat(grandchild).exists(); + assertThat(bar).exists(); FileSystemUtils.deleteRecursively(root); - assertThat(root.exists()).isFalse(); - assertThat(child.exists()).isFalse(); - assertThat(grandchild.exists()).isFalse(); - assertThat(bar.exists()).isFalse(); + assertThat(root).doesNotExist(); + assertThat(child).doesNotExist(); + assertThat(grandchild).doesNotExist(); + assertThat(bar).doesNotExist(); } @Test @@ -63,19 +63,19 @@ class FileSystemUtilsTests { File bar = new File(child, "bar.txt"); bar.createNewFile(); - assertThat(src.exists()).isTrue(); - assertThat(child.exists()).isTrue(); - assertThat(grandchild.exists()).isTrue(); - assertThat(bar.exists()).isTrue(); + assertThat(src).exists(); + assertThat(child).exists(); + assertThat(grandchild).exists(); + assertThat(bar).exists(); File dest = new File("./dest"); FileSystemUtils.copyRecursively(src, dest); - assertThat(dest.exists()).isTrue(); - assertThat(new File(dest, child.getName()).exists()).isTrue(); + assertThat(dest).exists(); + assertThat(new File(dest, child.getName())).exists(); FileSystemUtils.deleteRecursively(src); - assertThat(src.exists()).isFalse(); + assertThat(src).doesNotExist(); } 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 2fa926a0ea2..90b1fea3fa2 100644 --- a/spring-core/src/test/java/org/springframework/util/MimeTypeTests.java +++ b/spring-core/src/test/java/org/springframework/util/MimeTypeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -297,18 +297,18 @@ class MimeTypeTests { String s = "text/plain, text/html, text/x-dvi, text/x-c"; List mimeTypes = MimeTypeUtils.parseMimeTypes(s); assertThat(mimeTypes).as("No mime types returned").isNotNull(); - assertThat(mimeTypes.size()).as("Invalid amount of mime types").isEqualTo(4); + assertThat(mimeTypes).as("Invalid amount of mime types").hasSize(4); mimeTypes = MimeTypeUtils.parseMimeTypes(null); assertThat(mimeTypes).as("No mime types returned").isNotNull(); - assertThat(mimeTypes.size()).as("Invalid amount of mime types").isEqualTo(0); + assertThat(mimeTypes).as("Invalid amount of mime types").isEmpty(); } @Test // gh-23241 void parseMimeTypesWithTrailingComma() { List mimeTypes = MimeTypeUtils.parseMimeTypes("text/plain, text/html,"); assertThat(mimeTypes).as("No mime types returned").isNotNull(); - assertThat(mimeTypes.size()).as("Incorrect number of mime types").isEqualTo(2); + assertThat(mimeTypes).as("Incorrect number of mime types").hasSize(2); } @Test // SPR-17459 @@ -328,7 +328,7 @@ class MimeTypeTests { type = new MimeType("application", "vdn.something"); assertThat(type.getSubtypeSuffix()).isNull(); type = new MimeType("application", "vdn.something+"); - assertThat(type.getSubtypeSuffix()).isEqualTo(""); + assertThat(type.getSubtypeSuffix()).isEmpty(); type = new MimeType("application", "vdn.some+thing+json"); assertThat(type.getSubtypeSuffix()).isEqualTo("json"); } @@ -344,7 +344,7 @@ class MimeTypeTests { String s = String.join(",", mimeTypes); List actual = MimeTypeUtils.parseMimeTypes(s); - assertThat(actual).hasSize(mimeTypes.length); + assertThat(actual).hasSameSizeAs(mimeTypes); for (int i = 0; i < mimeTypes.length; i++) { assertThat(actual.get(i).toString()).isEqualTo(mimeTypes[i]); } @@ -362,7 +362,7 @@ class MimeTypeTests { assertThat(audio.compareTo(audio)).as("Invalid comparison result").isEqualTo(0); assertThat(audioBasicLevel.compareTo(audioBasicLevel)).as("Invalid comparison result").isEqualTo(0); - assertThat(audioBasicLevel.compareTo(audio) > 0).as("Invalid comparison result").isTrue(); + assertThat(audioBasicLevel.compareTo(audio)).as("Invalid comparison result").isGreaterThan(0); List expected = new ArrayList<>(); expected.add(audio); @@ -398,8 +398,8 @@ class MimeTypeTests { m1 = new MimeType("audio", "basic", singletonMap("foo", "bar")); m2 = new MimeType("audio", "basic", singletonMap("foo", "Bar")); - assertThat(m1.compareTo(m2) != 0).as("Invalid comparison result").isTrue(); - assertThat(m2.compareTo(m1) != 0).as("Invalid comparison result").isTrue(); + assertThat(m1.compareTo(m2)).as("Invalid comparison result").isNotEqualTo(0); + assertThat(m2.compareTo(m1)).as("Invalid comparison result").isNotEqualTo(0); } @Test 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 84d61ecea36..8d23c0c9c19 100644 --- a/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -141,7 +141,7 @@ class ObjectUtilsTests { void toObjectArray() { int[] a = new int[] {1, 2, 3, 4, 5}; Integer[] wrapper = (Integer[]) ObjectUtils.toObjectArray(a); - assertThat(wrapper.length == 5).isTrue(); + assertThat(wrapper.length).isEqualTo(5); for (int i = 0; i < wrapper.length; i++) { assertThat(wrapper[i].intValue()).isEqualTo(a[i]); } @@ -794,7 +794,7 @@ class ObjectUtilsTests { private void assertEqualHashCodes(int expected, Object array) { int actual = ObjectUtils.nullSafeHashCode(array); assertThat(actual).isEqualTo(expected); - assertThat(array.hashCode() != actual).isTrue(); + assertThat(array.hashCode()).isNotEqualTo(actual); } 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 f24acf35621..0368c892a6d 100644 --- a/spring-core/src/test/java/org/springframework/util/PropertiesPersisterTests.java +++ b/spring-core/src/test/java/org/springframework/util/PropertiesPersisterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -125,10 +125,10 @@ class PropertiesPersisterTests { propCopy = new String(propOut.toByteArray()); } if (header != null) { - assertThat(propCopy.contains(header)).isTrue(); + assertThat(propCopy).contains(header); } - assertThat(propCopy.contains("\ncode1=message1")).isTrue(); - assertThat(propCopy.contains("\ncode2=message2")).isTrue(); + assertThat(propCopy).contains("\ncode1=message1"); + assertThat(propCopy).contains("\ncode2=message2"); return propCopy; } 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 5d788674553..c702f095183 100644 --- a/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -176,7 +176,7 @@ class ReflectionUtilsTests { src.setName("freddie"); src.setAge(15); src.setSpouse(new TestObject()); - assertThat(src.getAge() == dest.getAge()).isFalse(); + assertThat(src.getAge()).isNotEqualTo(dest.getAge()); ReflectionUtils.shallowCopyFieldState(src, dest); assertThat(dest.getAge()).isEqualTo(src.getAge()); 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 0893412146d..ac2c9cdc982 100644 --- a/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,11 +70,11 @@ class StringUtilsTests { @Deprecated void trimWhitespace() { assertThat(StringUtils.trimWhitespace(null)).isNull(); - assertThat(StringUtils.trimWhitespace("")).isEqualTo(""); - assertThat(StringUtils.trimWhitespace(" ")).isEqualTo(""); - assertThat(StringUtils.trimWhitespace("\t")).isEqualTo(""); - assertThat(StringUtils.trimWhitespace("\n")).isEqualTo(""); - assertThat(StringUtils.trimWhitespace(" \t\n")).isEqualTo(""); + assertThat(StringUtils.trimWhitespace("")).isEmpty(); + assertThat(StringUtils.trimWhitespace(" ")).isEmpty(); + assertThat(StringUtils.trimWhitespace("\t")).isEmpty(); + assertThat(StringUtils.trimWhitespace("\n")).isEmpty(); + assertThat(StringUtils.trimWhitespace(" \t\n")).isEmpty(); assertThat(StringUtils.trimWhitespace(" a")).isEqualTo("a"); assertThat(StringUtils.trimWhitespace("a ")).isEqualTo("a"); assertThat(StringUtils.trimWhitespace(" a ")).isEqualTo("a"); @@ -85,11 +85,11 @@ class StringUtilsTests { @Test void trimAllWhitespace() { assertThat(StringUtils.trimAllWhitespace(null)).isNull(); - assertThat(StringUtils.trimAllWhitespace("")).isEqualTo(""); - assertThat(StringUtils.trimAllWhitespace(" ")).isEqualTo(""); - assertThat(StringUtils.trimAllWhitespace("\t")).isEqualTo(""); - assertThat(StringUtils.trimAllWhitespace("\n")).isEqualTo(""); - assertThat(StringUtils.trimAllWhitespace(" \t\n")).isEqualTo(""); + assertThat(StringUtils.trimAllWhitespace("")).isEmpty(); + assertThat(StringUtils.trimAllWhitespace(" ")).isEmpty(); + assertThat(StringUtils.trimAllWhitespace("\t")).isEmpty(); + assertThat(StringUtils.trimAllWhitespace("\n")).isEmpty(); + assertThat(StringUtils.trimAllWhitespace(" \t\n")).isEmpty(); assertThat(StringUtils.trimAllWhitespace(" a")).isEqualTo("a"); assertThat(StringUtils.trimAllWhitespace("a ")).isEqualTo("a"); assertThat(StringUtils.trimAllWhitespace(" a ")).isEqualTo("a"); @@ -101,11 +101,11 @@ class StringUtilsTests { @SuppressWarnings("deprecation") void trimLeadingWhitespace() { assertThat(StringUtils.trimLeadingWhitespace(null)).isNull(); - assertThat(StringUtils.trimLeadingWhitespace("")).isEqualTo(""); - assertThat(StringUtils.trimLeadingWhitespace(" ")).isEqualTo(""); - assertThat(StringUtils.trimLeadingWhitespace("\t")).isEqualTo(""); - assertThat(StringUtils.trimLeadingWhitespace("\n")).isEqualTo(""); - assertThat(StringUtils.trimLeadingWhitespace(" \t\n")).isEqualTo(""); + assertThat(StringUtils.trimLeadingWhitespace("")).isEmpty(); + assertThat(StringUtils.trimLeadingWhitespace(" ")).isEmpty(); + assertThat(StringUtils.trimLeadingWhitespace("\t")).isEmpty(); + assertThat(StringUtils.trimLeadingWhitespace("\n")).isEmpty(); + assertThat(StringUtils.trimLeadingWhitespace(" \t\n")).isEmpty(); assertThat(StringUtils.trimLeadingWhitespace(" a")).isEqualTo("a"); assertThat(StringUtils.trimLeadingWhitespace("a ")).isEqualTo("a "); assertThat(StringUtils.trimLeadingWhitespace(" a ")).isEqualTo("a "); @@ -117,11 +117,11 @@ class StringUtilsTests { @SuppressWarnings("deprecation") void trimTrailingWhitespace() { assertThat(StringUtils.trimTrailingWhitespace(null)).isNull(); - assertThat(StringUtils.trimTrailingWhitespace("")).isEqualTo(""); - assertThat(StringUtils.trimTrailingWhitespace(" ")).isEqualTo(""); - assertThat(StringUtils.trimTrailingWhitespace("\t")).isEqualTo(""); - assertThat(StringUtils.trimTrailingWhitespace("\n")).isEqualTo(""); - assertThat(StringUtils.trimTrailingWhitespace(" \t\n")).isEqualTo(""); + assertThat(StringUtils.trimTrailingWhitespace("")).isEmpty(); + assertThat(StringUtils.trimTrailingWhitespace(" ")).isEmpty(); + assertThat(StringUtils.trimTrailingWhitespace("\t")).isEmpty(); + assertThat(StringUtils.trimTrailingWhitespace("\n")).isEmpty(); + assertThat(StringUtils.trimTrailingWhitespace(" \t\n")).isEmpty(); assertThat(StringUtils.trimTrailingWhitespace("a ")).isEqualTo("a"); assertThat(StringUtils.trimTrailingWhitespace(" a")).isEqualTo(" a"); assertThat(StringUtils.trimTrailingWhitespace(" a ")).isEqualTo(" a"); @@ -132,8 +132,8 @@ class StringUtilsTests { @Test void trimLeadingCharacter() { assertThat(StringUtils.trimLeadingCharacter(null, ' ')).isNull(); - assertThat(StringUtils.trimLeadingCharacter("", ' ')).isEqualTo(""); - assertThat(StringUtils.trimLeadingCharacter(" ", ' ')).isEqualTo(""); + assertThat(StringUtils.trimLeadingCharacter("", ' ')).isEmpty(); + assertThat(StringUtils.trimLeadingCharacter(" ", ' ')).isEmpty(); assertThat(StringUtils.trimLeadingCharacter("\t", ' ')).isEqualTo("\t"); assertThat(StringUtils.trimLeadingCharacter(" a", ' ')).isEqualTo("a"); assertThat(StringUtils.trimLeadingCharacter("a ", ' ')).isEqualTo("a "); @@ -145,8 +145,8 @@ class StringUtilsTests { @Test void trimTrailingCharacter() { assertThat(StringUtils.trimTrailingCharacter(null, ' ')).isNull(); - assertThat(StringUtils.trimTrailingCharacter("", ' ')).isEqualTo(""); - assertThat(StringUtils.trimTrailingCharacter(" ", ' ')).isEqualTo(""); + assertThat(StringUtils.trimTrailingCharacter("", ' ')).isEmpty(); + assertThat(StringUtils.trimTrailingCharacter(" ", ' ')).isEmpty(); assertThat(StringUtils.trimTrailingCharacter("\t", ' ')).isEqualTo("\t"); assertThat(StringUtils.trimTrailingCharacter("a ", ' ')).isEqualTo("a"); assertThat(StringUtils.trimTrailingCharacter(" a", ' ')).isEqualTo(" a"); @@ -219,19 +219,19 @@ class StringUtilsTests { @Test void countOccurrencesOf() { - 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(); + assertThat(StringUtils.countOccurrencesOf(null, null)).as("nullx2 = 0").isEqualTo(0); + assertThat(StringUtils.countOccurrencesOf("s", null)).as("null string = 0").isEqualTo(0); + assertThat(StringUtils.countOccurrencesOf(null, "s")).as("null substring = 0").isEqualTo(0); String s = "erowoiueoiur"; - 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(); + assertThat(StringUtils.countOccurrencesOf(s, "WERWER")).as("not found = 0").isEqualTo(0); + assertThat(StringUtils.countOccurrencesOf(s, "x")).as("not found char = 0").isEqualTo(0); + assertThat(StringUtils.countOccurrencesOf(s, " ")).as("not found ws = 0").isEqualTo(0); + assertThat(StringUtils.countOccurrencesOf(s, "")).as("not found empty string = 0").isEqualTo(0); + assertThat(StringUtils.countOccurrencesOf(s, "e")).as("found char=2").isEqualTo(2); + assertThat(StringUtils.countOccurrencesOf(s, "oi")).as("found substring=2").isEqualTo(2); + assertThat(StringUtils.countOccurrencesOf(s, "oiu")).as("found substring=2").isEqualTo(2); + assertThat(StringUtils.countOccurrencesOf(s, "oiur")).as("found substring=3").isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(s, "r")).as("test last").isEqualTo(2); } @Test @@ -242,7 +242,7 @@ class StringUtilsTests { // Simple replace String s = StringUtils.replace(inString, oldPattern, newPattern); - assertThat(s.equals("a6AazAfoo77abfoo")).as("Replace 1 worked").isTrue(); + assertThat(s).as("Replace 1 worked").isEqualTo("a6AazAfoo77abfoo"); // Non match: no change s = StringUtils.replace(inString, "qwoeiruqopwieurpoqwieur", newPattern); @@ -262,22 +262,23 @@ class StringUtilsTests { String inString = "The quick brown fox jumped over the lazy dog"; String noThe = StringUtils.delete(inString, "the"); - assertThat(noThe.equals("The quick brown fox jumped over lazy dog")).as("Result has no the [" + noThe + "]").isTrue(); + assertThat(noThe).as("Result has no the [" + noThe + "]") + .isEqualTo("The quick brown fox jumped over lazy dog"); String nohe = StringUtils.delete(inString, "he"); - assertThat(nohe.equals("T quick brown fox jumped over t lazy dog")).as("Result has no he [" + nohe + "]").isTrue(); + assertThat(nohe).as("Result has no he [" + nohe + "]").isEqualTo("T quick brown fox jumped over t lazy dog"); String nosp = StringUtils.delete(inString, " "); - assertThat(nosp.equals("Thequickbrownfoxjumpedoverthelazydog")).as("Result has no spaces").isTrue(); + assertThat(nosp).as("Result has no spaces").isEqualTo("Thequickbrownfoxjumpedoverthelazydog"); String killEnd = StringUtils.delete(inString, "dog"); - assertThat(killEnd.equals("The quick brown fox jumped over the lazy ")).as("Result has no dog").isTrue(); + assertThat(killEnd).as("Result has no dog").isEqualTo("The quick brown fox jumped over the lazy "); String mismatch = StringUtils.delete(inString, "dxxcxcxog"); - assertThat(mismatch.equals(inString)).as("Result is unchanged").isTrue(); + assertThat(mismatch).as("Result is unchanged").isEqualTo(inString); String nochange = StringUtils.delete(inString, ""); - assertThat(nochange.equals(inString)).as("Result is unchanged").isTrue(); + assertThat(nochange).as("Result is unchanged").isEqualTo(inString); } @Test @@ -344,7 +345,7 @@ class StringUtilsTests { @Test void getFilename() { assertThat(StringUtils.getFilename(null)).isNull(); - assertThat(StringUtils.getFilename("")).isEqualTo(""); + assertThat(StringUtils.getFilename("")).isEmpty(); assertThat(StringUtils.getFilename("myfile")).isEqualTo("myfile"); assertThat(StringUtils.getFilename("mypath/myfile")).isEqualTo("myfile"); assertThat(StringUtils.getFilename("myfile.")).isEqualTo("myfile."); @@ -360,8 +361,8 @@ class StringUtilsTests { assertThat(StringUtils.getFilenameExtension("myfile")).isNull(); assertThat(StringUtils.getFilenameExtension("myPath/myfile")).isNull(); assertThat(StringUtils.getFilenameExtension("/home/user/.m2/settings/myfile")).isNull(); - assertThat(StringUtils.getFilenameExtension("myfile.")).isEqualTo(""); - assertThat(StringUtils.getFilenameExtension("myPath/myfile.")).isEqualTo(""); + assertThat(StringUtils.getFilenameExtension("myfile.")).isEmpty(); + assertThat(StringUtils.getFilenameExtension("myPath/myfile.")).isEmpty(); 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"); @@ -369,7 +370,7 @@ class StringUtilsTests { @Test void stripFilenameExtension() { - assertThat(StringUtils.stripFilenameExtension("")).isEqualTo(""); + assertThat(StringUtils.stripFilenameExtension("")).isEmpty(); assertThat(StringUtils.stripFilenameExtension("myfile")).isEqualTo("myfile"); assertThat(StringUtils.stripFilenameExtension("myfile.")).isEqualTo("myfile"); assertThat(StringUtils.stripFilenameExtension("myfile.txt")).isEqualTo("myfile"); @@ -394,8 +395,8 @@ class StringUtilsTests { 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/..")).isEmpty(); + assertThat(StringUtils.cleanPath("mypath/../.")).isEmpty(); assertThat(StringUtils.cleanPath("mypath/../")).isEqualTo("./"); assertThat(StringUtils.cleanPath("././")).isEqualTo("./"); assertThat(StringUtils.cleanPath("./")).isEqualTo("./"); @@ -511,15 +512,15 @@ class StringUtilsTests { @Test void commaDelimitedListToStringArrayWithNullProducesEmptyArray() { String[] sa = StringUtils.commaDelimitedListToStringArray(null); - 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(); + assertThat(sa).as("String array isn't null with null input").isNotNull(); + assertThat(sa.length).as("String array length == 0 with null input").isEqualTo(0); } @Test void commaDelimitedListToStringArrayWithEmptyStringProducesEmptyArray() { String[] sa = StringUtils.commaDelimitedListToStringArray(""); - 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(); + assertThat(sa).as("String array isn't null with null input").isNotNull(); + assertThat(sa.length).as("String array length == 0 with null input").isEqualTo(0); } @Test @@ -582,8 +583,8 @@ class StringUtilsTests { // Could read these from files String s = "woeirqupoiewuropqiewuorpqiwueopriquwopeiurqopwieur"; String[] sa = StringUtils.commaDelimitedListToStringArray(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(); + assertThat(sa.length).as("Found one String with no delimiters").isEqualTo(1); + assertThat(sa[0]).as("Single array entry matches input String with no delimiters").isEqualTo(s); } @Test @@ -610,7 +611,7 @@ class StringUtilsTests { private void doTestCommaDelimitedListToStringArrayLegalMatch(String[] components) { String sb = String.join(String.valueOf(','), components); String[] sa = StringUtils.commaDelimitedListToStringArray(sb); - assertThat(sa != null).as("String array isn't null with legal match").isTrue(); + assertThat(sa).as("String array isn't null with legal match").isNotNull(); 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(); } @@ -692,7 +693,7 @@ class StringUtilsTests { for (Locale locale : Locale.getAvailableLocales()) { Locale parsedLocale = StringUtils.parseLocaleString(locale.toString()); if (parsedLocale == null) { - assertThat(locale.getLanguage()).isEqualTo(""); + assertThat(locale.getLanguage()).isEmpty(); } else { assertThat(locale.toString()).isEqualTo(parsedLocale.toString()); @@ -705,7 +706,7 @@ class StringUtilsTests { for (Locale locale : Locale.getAvailableLocales()) { Locale parsedLocale = StringUtils.parseLocale(locale.toLanguageTag()); if (parsedLocale == null) { - assertThat(locale.getLanguage()).isEqualTo(""); + assertThat(locale.getLanguage()).isEmpty(); } else { assertThat(locale.toLanguageTag()).isEqualTo(parsedLocale.toLanguageTag()); 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 ce4cf4210a4..30e70d2f7e0 100644 --- a/spring-core/src/test/java/org/springframework/util/SystemPropertyUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/SystemPropertyUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -110,7 +110,7 @@ class SystemPropertyUtilsTests { @Test void replaceWithEmptyDefault() { String resolved = SystemPropertyUtils.resolvePlaceholders("${test.prop:}"); - assertThat(resolved).isEqualTo(""); + assertThat(resolved).isEmpty(); } @Test diff --git a/spring-core/src/test/java/org/springframework/util/UnmodifiableMultiValueMapTests.java b/spring-core/src/test/java/org/springframework/util/UnmodifiableMultiValueMapTests.java index 7f781946557..473c49f5dad 100644 --- a/spring-core/src/test/java/org/springframework/util/UnmodifiableMultiValueMapTests.java +++ b/spring-core/src/test/java/org/springframework/util/UnmodifiableMultiValueMapTests.java @@ -62,7 +62,7 @@ class UnmodifiableMultiValueMapTests { list.add("bar"); given(mock.get("foo")).willReturn(list); List result = map.get("foo"); - assertThat(result).isNotNull().containsExactly("bar"); + assertThat(result).containsExactly("bar"); assertThatUnsupportedOperationException().isThrownBy(() -> result.add("baz")); given(mock.getOrDefault("foo", List.of("bar"))).willReturn(List.of("baz")); 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 2a4ef7ea641..5171625fa2a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ class ComparableComparatorTests { Comparator c = new ComparableComparator<>(); String s1 = "abc"; String s2 = "cde"; - assertThat(c.compare(s1, s2) < 0).isTrue(); + assertThat(c.compare(s1, s2)).isLessThan(0); } @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 e20f4f509af..83a41b1154e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,15 +35,15 @@ class NullSafeComparatorTests { @Test void shouldCompareWithNullsLow() { Comparator c = NullSafeComparator.NULLS_LOW; - assertThat(c.compare(null, "boo") < 0).isTrue(); + assertThat(c.compare(null, "boo")).isLessThan(0); } @SuppressWarnings("unchecked") @Test void shouldCompareWithNullsHigh() { Comparator c = NullSafeComparator.NULLS_HIGH; - assertThat(c.compare(null, "boo") > 0).isTrue(); - assertThat(c.compare(null, null) == 0).isTrue(); + assertThat(c.compare(null, "boo")).isGreaterThan(0); + assertThat(c.compare(null, null)).isEqualTo(0); } } diff --git a/spring-core/src/test/java/org/springframework/util/xml/SimpleNamespaceContextTests.java b/spring-core/src/test/java/org/springframework/util/xml/SimpleNamespaceContextTests.java index 09966500613..5eb06f5eca0 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/SimpleNamespaceContextTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/SimpleNamespaceContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,16 +62,14 @@ class SimpleNamespaceContextTests { .isEqualTo(XMLConstants.XML_NS_URI); assertThat(context.getNamespaceURI(unboundPrefix)) - .as("Returns \"\" for an unbound prefix") - .isEqualTo(XMLConstants.NULL_NS_URI); + .as("Returns \"\" for an unbound prefix").isEmpty(); context.bindNamespaceUri(prefix, namespaceUri); assertThat(context.getNamespaceURI(prefix)) .as("Returns the bound namespace URI for a bound prefix") .isEqualTo(namespaceUri); assertThat(context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)) - .as("By default returns URI \"\" for the default namespace prefix") - .isEqualTo(XMLConstants.NULL_NS_URI); + .as("By default returns URI \"\" for the default namespace prefix").isEmpty(); context.bindDefaultNamespaceUri(defaultNamespaceUri); assertThat(context.getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX)) .as("Returns the set URI for the default namespace prefix") @@ -183,14 +181,14 @@ class SimpleNamespaceContextTests { context.bindNamespaceUri(prefix, namespaceUri); context.removeBinding(prefix); - assertThat(context.getNamespaceURI(prefix)).as("Returns default namespace URI for removed prefix").isEqualTo(XMLConstants.NULL_NS_URI); + assertThat(context.getNamespaceURI(prefix)).as("Returns default namespace URI for removed prefix").isEmpty(); assertThat(context.getPrefix(namespaceUri)).as("#getPrefix returns null when all prefixes for a namespace URI were removed").isNull(); assertThat(context.getPrefixes(namespaceUri).hasNext()).as("#getPrefixes returns an empty iterator when all prefixes for a namespace URI were removed").isFalse(); context.bindNamespaceUri("prefix1", additionalNamespaceUri); context.bindNamespaceUri("prefix2", additionalNamespaceUri); context.removeBinding("prefix1"); - assertThat(context.getNamespaceURI("prefix1")).as("Prefix was unbound").isEqualTo(XMLConstants.NULL_NS_URI); + assertThat(context.getNamespaceURI("prefix1")).as("Prefix was unbound").isEmpty(); assertThat(context.getPrefix(additionalNamespaceUri)).as("#getPrefix returns a bound prefix after removal of another prefix for the same namespace URI").isEqualTo("prefix2"); assertThat(getItemSet(context.getPrefixes(additionalNamespaceUri))) .as("Prefix was removed from namespace URI") 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 f01a70eff00..b60d6942faa 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 @@ -210,7 +210,7 @@ public abstract class AbstractExpressionTests { if (otherProperties != null && otherProperties.length != 0) { // first one is expected position of the error within the string int pos = (Integer) otherProperties[0]; - assertThat(pos).as("reported position").isEqualTo(pos); + assertThat(ex.getPosition()).as("reported position").isEqualTo(pos); if (otherProperties.length > 1) { // Check inserts match Object[] inserts = ex.getInserts(); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ComparatorTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ComparatorTests.java index 1c2d10e4636..b4ad2576610 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ComparatorTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ComparatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,29 +43,29 @@ public class ComparatorTests { void testPrimitives() throws EvaluationException { TypeComparator comparator = new StandardTypeComparator(); // primitive int - assertThat(comparator.compare(1, 2) < 0).isTrue(); - assertThat(comparator.compare(1, 1) == 0).isTrue(); - assertThat(comparator.compare(2, 1) > 0).isTrue(); + assertThat(comparator.compare(1, 2)).isLessThan(0); + assertThat(comparator.compare(1, 1)).isEqualTo(0); + assertThat(comparator.compare(2, 1)).isGreaterThan(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(); + assertThat(comparator.compare(1.0d, 2)).isLessThan(0); + assertThat(comparator.compare(1.0d, 1)).isEqualTo(0); + assertThat(comparator.compare(2.0d, 1)).isGreaterThan(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(); + assertThat(comparator.compare(1.0f, 2)).isLessThan(0); + assertThat(comparator.compare(1.0f, 1)).isEqualTo(0); + assertThat(comparator.compare(2.0f, 1)).isGreaterThan(0); - assertThat(comparator.compare(1L, 2) < 0).isTrue(); - assertThat(comparator.compare(1L, 1) == 0).isTrue(); - assertThat(comparator.compare(2L, 1) > 0).isTrue(); + assertThat(comparator.compare(1L, 2)).isLessThan(0); + assertThat(comparator.compare(1L, 1)).isEqualTo(0); + assertThat(comparator.compare(2L, 1)).isGreaterThan(0); - assertThat(comparator.compare(1, 2L) < 0).isTrue(); - assertThat(comparator.compare(1, 1L) == 0).isTrue(); - assertThat(comparator.compare(2, 1L) > 0).isTrue(); + assertThat(comparator.compare(1, 2L)).isLessThan(0); + assertThat(comparator.compare(1, 1L)).isEqualTo(0); + assertThat(comparator.compare(2, 1L)).isGreaterThan(0); - assertThat(comparator.compare(1L, 2L) < 0).isTrue(); - assertThat(comparator.compare(1L, 1L) == 0).isTrue(); - assertThat(comparator.compare(2L, 1L) > 0).isTrue(); + assertThat(comparator.compare(1L, 2L)).isLessThan(0); + assertThat(comparator.compare(1L, 1L)).isEqualTo(0); + assertThat(comparator.compare(2L, 1L)).isGreaterThan(0); } @Test @@ -75,42 +75,42 @@ public class ComparatorTests { BigDecimal bdOne = new BigDecimal("1"); BigDecimal bdTwo = new BigDecimal("2"); - assertThat(comparator.compare(bdOne, bdTwo) < 0).isTrue(); - assertThat(comparator.compare(bdOne, new BigDecimal("1")) == 0).isTrue(); - assertThat(comparator.compare(bdTwo, bdOne) > 0).isTrue(); + assertThat(comparator.compare(bdOne, bdTwo)).isLessThan(0); + assertThat(comparator.compare(bdOne, new BigDecimal("1"))).isEqualTo(0); + assertThat(comparator.compare(bdTwo, bdOne)).isGreaterThan(0); - assertThat(comparator.compare(1, bdTwo) < 0).isTrue(); - assertThat(comparator.compare(1, bdOne) == 0).isTrue(); - assertThat(comparator.compare(2, bdOne) > 0).isTrue(); + assertThat(comparator.compare(1, bdTwo)).isLessThan(0); + assertThat(comparator.compare(1, bdOne)).isEqualTo(0); + assertThat(comparator.compare(2, bdOne)).isGreaterThan(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(); + assertThat(comparator.compare(1.0d, bdTwo)).isLessThan(0); + assertThat(comparator.compare(1.0d, bdOne)).isEqualTo(0); + assertThat(comparator.compare(2.0d, bdOne)).isGreaterThan(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(); + assertThat(comparator.compare(1.0f, bdTwo)).isLessThan(0); + assertThat(comparator.compare(1.0f, bdOne)).isEqualTo(0); + assertThat(comparator.compare(2.0f, bdOne)).isGreaterThan(0); - assertThat(comparator.compare(1L, bdTwo) < 0).isTrue(); - assertThat(comparator.compare(1L, bdOne) == 0).isTrue(); - assertThat(comparator.compare(2L, bdOne) > 0).isTrue(); + assertThat(comparator.compare(1L, bdTwo)).isLessThan(0); + assertThat(comparator.compare(1L, bdOne)).isEqualTo(0); + assertThat(comparator.compare(2L, bdOne)).isGreaterThan(0); } @Test void testNulls() throws EvaluationException { TypeComparator comparator = new StandardTypeComparator(); - assertThat(comparator.compare(null,"abc")<0).isTrue(); - assertThat(comparator.compare(null,null)==0).isTrue(); - assertThat(comparator.compare("abc",null)>0).isTrue(); + assertThat(comparator.compare(null,"abc")).isLessThan(0); + assertThat(comparator.compare(null,null)).isEqualTo(0); + assertThat(comparator.compare("abc",null)).isGreaterThan(0); } @Test void testObjects() throws EvaluationException { TypeComparator comparator = new StandardTypeComparator(); - assertThat(comparator.compare("a","a")==0).isTrue(); - assertThat(comparator.compare("a","b")<0).isTrue(); - assertThat(comparator.compare("b","a")>0).isTrue(); + assertThat(comparator.compare("a","a")).isEqualTo(0); + assertThat(comparator.compare("a","b")).isLessThan(0); + assertThat(comparator.compare("b","a")).isGreaterThan(0); } @Test 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 df494024d63..8ecf7ec71c4 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 @@ -322,7 +322,7 @@ class EvaluationTests extends AbstractExpressionTests { assertThat(value).isEqualTo("def"); e = parser.parseExpression("listOfStrings[2]"); value = e.getValue(ctx, String.class); - assertThat(value).isEqualTo(""); + assertThat(value).isEmpty(); // Now turn off growing and reference off the end StandardEvaluationContext failCtx = new StandardEvaluationContext(instance); 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 6afcf60d1f1..a7eb6054167 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -196,7 +196,7 @@ class IndexingTests { expression.setValue(this, "4"); } catch (EvaluationException ex) { - assertThat(ex.getMessage().startsWith("EL1053E")).isTrue(); + assertThat(ex.getMessage()).startsWith("EL1053E"); } } @@ -277,7 +277,7 @@ class IndexingTests { assertThat(expression.getValue(this)).isEqualTo("bar"); } catch (EvaluationException ex) { - assertThat(ex.getMessage().startsWith("EL1027E")).isTrue(); + assertThat(ex.getMessage()).startsWith("EL1027E"); } } @@ -295,7 +295,7 @@ class IndexingTests { assertThat(expression.getValue(this)).isEqualTo("bar"); } catch (EvaluationException ex) { - assertThat(ex.getMessage().startsWith("EL1053E")).isTrue(); + assertThat(ex.getMessage()).startsWith("EL1053E"); } } @@ -313,7 +313,7 @@ class IndexingTests { assertThat(expression.getValue(this)).isEqualTo("bar"); } catch (EvaluationException ex) { - assertThat(ex.getMessage().startsWith("EL1053E")).isTrue(); + assertThat(ex.getMessage()).startsWith("EL1053E"); } } @@ -337,7 +337,7 @@ class IndexingTests { SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("listOfScalarNotGeneric"); assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("java.util.ArrayList"); - assertThat(expression.getValue(this, String.class)).isEqualTo(""); + assertThat(expression.getValue(this, String.class)).isEmpty(); } @SuppressWarnings("unchecked") 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 137c5d44715..0257ef8d2d5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,7 +72,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { * them to be their boxed or unboxed variants) or compare object references. It does not * compile expressions where numbers are of different types or when objects implement * Comparable. - * + * * Compiled nodes: * * TypeReference @@ -1071,10 +1071,10 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertThat(expression.getValue(context).toString()).isEqualTo("a"); expression = parser.parseExpression("#append()"); - assertThat(expression.getValue(context).toString()).isEqualTo(""); + assertThat(expression.getValue(context).toString()).isEmpty(); assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertThat(expression.getValue(context).toString()).isEqualTo(""); + assertThat(expression.getValue(context).toString()).isEmpty(); expression = parser.parseExpression("#append(#stringArray)"); assertThat(expression.getValue(context).toString()).isEqualTo("xyz"); @@ -1108,10 +1108,10 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertThat(expression.getValue(context).toString()).isEqualTo("ab"); expression = parser.parseExpression("#append2()"); - assertThat(expression.getValue(context).toString()).isEqualTo(""); + assertThat(expression.getValue(context).toString()).isEmpty(); assertThat(((SpelNodeImpl)((SpelExpression) expression).getAST()).isCompilable()).isTrue(); assertCanCompile(expression); - assertThat(expression.getValue(context).toString()).isEqualTo(""); + assertThat(expression.getValue(context).toString()).isEmpty(); expression = parser.parseExpression("#append3(#stringArray)"); assertThat(expression.getValue(context, new SomeCompareMethod2()).toString()).isEqualTo("xyz"); @@ -3383,9 +3383,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertThat(expression.getValue(String.class)).isEqualTo("foo"); expression = parser.parseExpression(prefix + "2().output"); - assertThat(expression.getValue(String.class)).isEqualTo(""); + assertThat(expression.getValue(String.class)).isEmpty(); assertCanCompile(expression); - assertThat(expression.getValue(String.class)).isEqualTo(""); + assertThat(expression.getValue(String.class)).isEmpty(); expression = parser.parseExpression(prefix + "3(1,2,3).output"); assertThat(expression.getValue(String.class)).isEqualTo("123"); @@ -3398,9 +3398,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { assertThat(expression.getValue(String.class)).isEqualTo("1"); expression = parser.parseExpression(prefix + "3().output"); - assertThat(expression.getValue(String.class)).isEqualTo(""); + assertThat(expression.getValue(String.class)).isEmpty(); assertCanCompile(expression); - assertThat(expression.getValue(String.class)).isEqualTo(""); + assertThat(expression.getValue(String.class)).isEmpty(); expression = parser.parseExpression(prefix + "3('abc',5.0f,1,2,3).output"); assertThat(expression.getValue(String.class)).isEqualTo("abc:5.0:123"); @@ -5095,7 +5095,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { classloadersUsed.add(cEx.getClass().getClassLoader()); assertThat((int) expression.getValue(Integer.class)).isEqualTo(9); } - assertThat(classloadersUsed.size() > 1).isTrue(); + assertThat(classloadersUsed.size()).isGreaterThan(1); } 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 a571c50e459..3e9d3bc92a9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -455,7 +455,7 @@ class SpelDocumentationTests extends AbstractExpressionTests { void templating() throws Exception { String randomPhrase = parser.parseExpression("random number is ${T(java.lang.Math).random()}", new TemplatedParserContext()).getValue(String.class); - assertThat(randomPhrase.startsWith("random number")).isTrue(); + assertThat(randomPhrase).startsWith("random number"); } static class TemplatedParserContext implements ParserContext { 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 59e363e04d1..00d9581f381 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 @@ -441,8 +441,8 @@ class SpelReproTests extends AbstractExpressionTests { catch (SpelEvaluationException see) { 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(); + assertThat(see.getCause()).isInstanceOf(AccessException.class); + assertThat(see.getCause().getMessage()).startsWith("DONT"); } // bean exists @@ -807,7 +807,7 @@ 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); - assertThat(Reserver.CONST).isEqualTo(value); + assertThat(value).isEqualTo(Reserver.CONST); } /** @@ -1373,7 +1373,7 @@ class SpelReproTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("new java.util.ArrayList(#root)"); Object value = expr.getValue(coll); - assertThat(value instanceof ArrayList).isTrue(); + assertThat(value).isInstanceOf(ArrayList.class); @SuppressWarnings("rawtypes") ArrayList list = (ArrayList) value; assertThat(list.get(0)).isEqualTo("one"); @@ -1448,7 +1448,7 @@ class SpelReproTests extends AbstractExpressionTests { SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("T(java.util.Arrays).asList('')"); Object value = expression.getValue(); - assertThat(value instanceof List).isTrue(); + assertThat(value).isInstanceOf(List.class); assertThat(((List) value).isEmpty()).isTrue(); } @@ -1458,7 +1458,7 @@ 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)"); - assertThat(expression.getValue(sec) instanceof ArrayList).isTrue(); + assertThat(expression.getValue(sec)).isInstanceOf(ArrayList.class); } @Test @@ -1467,13 +1467,13 @@ class SpelReproTests extends AbstractExpressionTests { Expression expression = parser.parseExpression("T(org.springframework.expression.spel.SpelReproTests.DistanceEnforcer).from(#no)"); StandardEvaluationContext sec = new StandardEvaluationContext(); sec.setVariable("no", 1); - assertThat(expression.getValue(sec).toString().startsWith("Integer")).isTrue(); + assertThat(expression.getValue(sec).toString()).startsWith("Integer"); sec = new StandardEvaluationContext(); sec.setVariable("no", 1.0F); - assertThat(expression.getValue(sec).toString().startsWith("Number")).isTrue(); + assertThat(expression.getValue(sec).toString()).startsWith("Number"); sec = new StandardEvaluationContext(); sec.setVariable("no", "1.0"); - assertThat(expression.getValue(sec).toString().startsWith("Object")).isTrue(); + assertThat(expression.getValue(sec).toString()).startsWith("Object"); } @Test 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 ba3b9e67e9a..b1c99512888 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 @@ -75,7 +75,7 @@ class TemplateExpressionParsingTests extends AbstractExpressionTests { expr = parser.parseExpression("", DOLLAR_SIGN_TEMPLATE_PARSER_CONTEXT); o = expr.getValue(); - assertThat(o.toString()).isEqualTo(""); + assertThat(o.toString()).isEmpty(); expr = parser.parseExpression("abc", DOLLAR_SIGN_TEMPLATE_PARSER_CONTEXT); o = expr.getValue(); 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 9133b7baf00..d043b5d06af 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -193,37 +193,37 @@ class SpelParserTests { @Test void booleanOperators() { SpelExpression expr = new SpelExpressionParser().parseRaw("true"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); + assertThat(expr.getValue(Boolean.class)).isTrue(); expr = new SpelExpressionParser().parseRaw("false"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); + assertThat(expr.getValue(Boolean.class)).isFalse(); expr = new SpelExpressionParser().parseRaw("false and false"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); + assertThat(expr.getValue(Boolean.class)).isFalse(); expr = new SpelExpressionParser().parseRaw("true and (true or false)"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); + assertThat(expr.getValue(Boolean.class)).isTrue(); expr = new SpelExpressionParser().parseRaw("true and true or false"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); + assertThat(expr.getValue(Boolean.class)).isTrue(); expr = new SpelExpressionParser().parseRaw("!true"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); + assertThat(expr.getValue(Boolean.class)).isFalse(); expr = new SpelExpressionParser().parseRaw("!(false or true)"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); + assertThat(expr.getValue(Boolean.class)).isFalse(); } @Test void booleanOperators_symbolic_spr9614() { SpelExpression expr = new SpelExpressionParser().parseRaw("true"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); + assertThat(expr.getValue(Boolean.class)).isTrue(); expr = new SpelExpressionParser().parseRaw("false"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); + assertThat(expr.getValue(Boolean.class)).isFalse(); expr = new SpelExpressionParser().parseRaw("false && false"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); + assertThat(expr.getValue(Boolean.class)).isFalse(); expr = new SpelExpressionParser().parseRaw("true && (true || false)"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); + assertThat(expr.getValue(Boolean.class)).isTrue(); expr = new SpelExpressionParser().parseRaw("true && true || false"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.TRUE); + assertThat(expr.getValue(Boolean.class)).isTrue(); expr = new SpelExpressionParser().parseRaw("!true"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); + assertThat(expr.getValue(Boolean.class)).isFalse(); expr = new SpelExpressionParser().parseRaw("!(false || true)"); - assertThat(expr.getValue(Boolean.class)).isEqualTo(Boolean.FALSE); + assertThat(expr.getValue(Boolean.class)).isFalse(); } @Test 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 ec9c5fc1b19..ddb481e7273 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -184,7 +184,7 @@ class JdbcNamespaceIntegrationTests { for (String dataSourceName : dataSources) { DataSource dataSource = context.getBean(dataSourceName, DataSource.class); assertNumRowsInTestTable(new JdbcTemplate(dataSource), count); - assertThat(dataSource instanceof AbstractDriverBasedDataSource).isTrue(); + assertThat(dataSource).isInstanceOf(AbstractDriverBasedDataSource.class); AbstractDriverBasedDataSource adbDataSource = (AbstractDriverBasedDataSource) dataSource; assertThat(adbDataSource.getUrl()).contains(dataSourceName); } @@ -195,7 +195,7 @@ class JdbcNamespaceIntegrationTests { try (ConfigurableApplicationContext context = context(file)) { DataSource dataSource = context.getBean(DataSource.class); assertNumRowsInTestTable(new JdbcTemplate(dataSource), 1); - assertThat(dataSource instanceof AbstractDriverBasedDataSource).isTrue(); + assertThat(dataSource).isInstanceOf(AbstractDriverBasedDataSource.class); AbstractDriverBasedDataSource adbDataSource = (AbstractDriverBasedDataSource) dataSource; assertThat(urlPredicate.test(adbDataSource.getUrl())).isTrue(); } 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 d4f79225a24..a1f40741aee 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 @@ -84,7 +84,7 @@ 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); - assertThat(li.size()).as("All rows returned").isEqualTo(2); + assertThat(li).as("All rows returned").hasSize(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(); @@ -96,7 +96,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); - assertThat(li.size()).as("All rows returned").isEqualTo(0); + assertThat(li).as("All rows returned").isEmpty(); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -107,7 +107,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getObject(1)).willReturn(11); List> li = this.template.queryForList(sql); - assertThat(li.size()).as("All rows returned").isEqualTo(1); + assertThat(li).as("All rows returned").hasSize(1); assertThat(((Integer) li.get(0).get("age")).intValue()).as("First row is Integer").isEqualTo(11); verify(this.resultSet).close(); verify(this.statement).close(); @@ -119,7 +119,7 @@ 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); - assertThat(li.size()).as("All rows returned").isEqualTo(1); + assertThat(li).as("All rows returned").hasSize(1); assertThat(li.get(0).intValue()).as("Element is Integer").isEqualTo(11); verify(this.resultSet).close(); verify(this.statement).close(); @@ -153,7 +153,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getInt(1)).willReturn(22); Object o = this.template.queryForObject(sql, (RowMapper) (rs, rowNum) -> rs.getInt(1)); - assertThat(o instanceof Integer).as("Correct result type").isTrue(); + assertThat(o).as("Correct result type").isInstanceOf(Integer.class); verify(this.resultSet).close(); verify(this.statement).close(); } @@ -284,7 +284,7 @@ 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, 3); - assertThat(li.size()).as("All rows returned").isEqualTo(2); + assertThat(li).as("All rows returned").hasSize(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); @@ -297,7 +297,7 @@ public class JdbcTemplateQueryTests { String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?"; given(this.resultSet.next()).willReturn(false); List> li = this.template.queryForList(sql, 3); - assertThat(li.size()).as("All rows returned").isEqualTo(0); + assertThat(li).as("All rows returned").isEmpty(); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); verify(this.preparedStatement).close(); @@ -309,7 +309,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getObject(1)).willReturn(11); List> li = this.template.queryForList(sql, 3); - assertThat(li.size()).as("All rows returned").isEqualTo(1); + assertThat(li).as("All rows returned").hasSize(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(); @@ -322,7 +322,7 @@ 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, 3); - assertThat(li.size()).as("All rows returned").isEqualTo(1); + assertThat(li).as("All rows returned").hasSize(1); assertThat(li.get(0).intValue()).as("First row is Integer").isEqualTo(11); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); @@ -347,7 +347,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getInt(1)).willReturn(22); Object o = this.template.queryForObject(sql, (rs, rowNum) -> rs.getInt(1), 3); - assertThat(o instanceof Integer).as("Correct result type").isTrue(); + assertThat(o).as("Correct result type").isInstanceOf(Integer.class); verify(this.preparedStatement).setObject(1, 3); verify(this.resultSet).close(); verify(this.preparedStatement).close(); @@ -377,7 +377,7 @@ public class JdbcTemplateQueryTests { given(this.resultSet.next()).willReturn(true, false); given(this.resultSet.getInt(1)).willReturn(22); Object o = this.template.queryForObject(sql, Integer.class, 3); - assertThat(o instanceof Integer).as("Correct result type").isTrue(); + assertThat(o).as("Correct result type").isInstanceOf(Integer.class); 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 ee9efc5100e..00eb07f0c3f 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 @@ -106,7 +106,7 @@ public class JdbcTemplateTests { @Test public void testBeanProperties() throws Exception { - assertThat(this.template.getDataSource() == this.dataSource).as("datasource ok").isTrue(); + assertThat(this.template.getDataSource()).as("datasource ok").isSameAs(this.dataSource); assertThat(this.template.isIgnoreWarnings()).as("ignores warnings by default").isTrue(); this.template.setIgnoreWarnings(false); boolean condition = !this.template.isIgnoreWarnings(); @@ -120,7 +120,7 @@ public class JdbcTemplateTests { given(this.preparedStatement.executeUpdate()).willReturn(1); Dispatcher d = new Dispatcher(idParam, sql); int rowsAffected = this.template.update(d); - assertThat(rowsAffected == 1).as("1 update affected 1 row").isTrue(); + assertThat(rowsAffected).as("1 update affected 1 row").isEqualTo(1); verify(this.preparedStatement).setInt(1, idParam); verify(this.preparedStatement).close(); verify(this.connection).close(); @@ -219,9 +219,9 @@ public class JdbcTemplateTests { // Match String[] forenames = sh.getStrings(); - assertThat(forenames.length == results.length).as("same length").isTrue(); + assertThat(forenames).as("same length").hasSameSizeAs(results); for (int i = 0; i < forenames.length; i++) { - assertThat(forenames[i].equals(results[i])).as("Row " + i + " matches").isTrue(); + assertThat(forenames[i]).as("Row " + i + " matches").isEqualTo(results[i]); } if (fetchSize != null) { @@ -263,7 +263,7 @@ public class JdbcTemplateTests { @Test public void testConnectionCallback() throws Exception { String result = this.template.execute((ConnectionCallback) con -> { - assertThat(con instanceof ConnectionProxy).isTrue(); + assertThat(con).isInstanceOf(ConnectionProxy.class); assertThat(((ConnectionProxy) con).getTargetConnection()).isSameAs(JdbcTemplateTests.this.connection); return "test"; }); @@ -340,7 +340,7 @@ public class JdbcTemplateTests { given(this.connection.createStatement()).willReturn(this.statement); int actualRowsAffected = this.template.update(sql); - assertThat(actualRowsAffected == rowsAffected).as("Actual rows affected is correct").isTrue(); + assertThat(actualRowsAffected).as("Actual rows affected is correct").isEqualTo(rowsAffected); verify(this.statement).close(); verify(this.connection).close(); } @@ -356,7 +356,7 @@ public class JdbcTemplateTests { int actualRowsAffected = this.template.update(sql, 4, new SqlParameterValue(Types.NUMERIC, 2, 1.4142f)); - assertThat(actualRowsAffected == rowsAffected).as("Actual rows affected is correct").isTrue(); + assertThat(actualRowsAffected).as("Actual rows affected is correct").isEqualTo(rowsAffected); verify(this.preparedStatement).setObject(1, 4); verify(this.preparedStatement).setObject(2, 1.4142f, Types.NUMERIC, 2); verify(this.preparedStatement).close(); @@ -387,7 +387,7 @@ public class JdbcTemplateTests { given(this.connection.createStatement()).willReturn(this.statement); int actualRowsAffected = this.template.update(sql); - assertThat(actualRowsAffected == rowsAffected).as("Actual rows affected is correct").isTrue(); + assertThat(actualRowsAffected).as("Actual rows affected is correct").isEqualTo(rowsAffected); verify(this.statement).close(); verify(this.connection).close(); @@ -405,7 +405,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2); verify(this.statement).addBatch(sql[0]); verify(this.statement).addBatch(sql[1]); @@ -445,7 +445,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2); verify(this.statement, never()).addBatch(anyString()); verify(this.statement).close(); @@ -494,7 +494,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, setter); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); @@ -535,7 +535,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, setter); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); @@ -572,7 +572,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, setter); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); @@ -609,7 +609,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, setter); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); @@ -640,7 +640,7 @@ public class JdbcTemplateTests { }; int[] actualRowsAffected = this.template.batchUpdate(sql, setter); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); @@ -691,7 +691,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, Collections.emptyList()); - assertThat(actualRowsAffected.length == 0).as("executed 0 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 0 updates").isEmpty(); } @Test @@ -707,7 +707,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, ids); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); @@ -732,7 +732,7 @@ public class JdbcTemplateTests { this.template = new JdbcTemplate(this.dataSource, false); int[] actualRowsAffected = this.template.batchUpdate(sql, ids, sqlTypes); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(this.preparedStatement, times(2)).addBatch(); @@ -756,7 +756,7 @@ public class JdbcTemplateTests { JdbcTemplate template = new JdbcTemplate(this.dataSource, false); int[][] actualRowsAffected = template.batchUpdate(sql, ids, 2, setter); - assertThat(actualRowsAffected[0].length).as("executed 2 updates").isEqualTo(2); + assertThat(actualRowsAffected[0]).as("executed 2 updates").hasSize(2); assertThat(actualRowsAffected[0][0]).isEqualTo(rowsAffected1[0]); assertThat(actualRowsAffected[0][1]).isEqualTo(rowsAffected1[1]); assertThat(actualRowsAffected[1][0]).isEqualTo(rowsAffected2[0]); 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 f50745ee1fb..2b65f12a7b0 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 @@ -228,8 +228,8 @@ public class NamedParameterJdbcTemplateTests { return cust1; }); - assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); - assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); + assertThat(cust.getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(cust.getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setString(2, "UK"); @@ -253,8 +253,8 @@ public class NamedParameterJdbcTemplateTests { return cust1; }); - assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); - assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); + assertThat(cust.getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(cust.getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(connection).prepareStatement(SELECT_NO_PARAMETERS); verify(resultSet).close(); verify(preparedStatement).close(); @@ -278,8 +278,8 @@ public class NamedParameterJdbcTemplateTests { }); assertThat(customers).hasSize(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(); + assertThat(customers.get(0).getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(customers.get(0).getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setString(2, "UK"); @@ -303,8 +303,8 @@ public class NamedParameterJdbcTemplateTests { }); assertThat(customers).hasSize(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(); + assertThat(customers.get(0).getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(customers.get(0).getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(connection).prepareStatement(SELECT_NO_PARAMETERS); verify(resultSet).close(); verify(preparedStatement).close(); @@ -328,8 +328,8 @@ public class NamedParameterJdbcTemplateTests { }); assertThat(customers).hasSize(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(); + assertThat(customers.get(0).getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(customers.get(0).getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setString(2, "UK"); @@ -353,8 +353,8 @@ public class NamedParameterJdbcTemplateTests { }); assertThat(customers).hasSize(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(); + assertThat(customers.get(0).getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(customers.get(0).getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(connection).prepareStatement(SELECT_NO_PARAMETERS); verify(resultSet).close(); verify(preparedStatement).close(); @@ -378,8 +378,8 @@ public class NamedParameterJdbcTemplateTests { return cust1; }); - assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); - assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); + assertThat(cust.getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(cust.getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED); verify(preparedStatement).setObject(1, 1, Types.DECIMAL); verify(preparedStatement).setString(2, "UK"); @@ -407,8 +407,8 @@ public class NamedParameterJdbcTemplateTests { })) { s.forEach(cust -> { count.incrementAndGet(); - assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); - assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); + assertThat(cust.getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(cust.getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); }); } @@ -467,7 +467,7 @@ public class NamedParameterJdbcTemplateTests { int[] actualRowsAffected = namedParameterTemplate.batchUpdate( "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected.length).as("executed 2 updates").isEqualTo(2); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(connection).prepareStatement("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"); @@ -486,7 +486,7 @@ public class NamedParameterJdbcTemplateTests { int[] actualRowsAffected = namedParameterTemplate.batchUpdate( "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids); - assertThat(actualRowsAffected.length == 0).as("executed 0 updates").isTrue(); + assertThat(actualRowsAffected.length).as("executed 0 updates").isEqualTo(0); } @Test @@ -502,7 +502,7 @@ public class NamedParameterJdbcTemplateTests { int[] actualRowsAffected = namedParameterTemplate.batchUpdate( "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected.length).as("executed 2 updates").isEqualTo(2); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); verify(connection).prepareStatement("UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"); @@ -567,7 +567,7 @@ public class NamedParameterJdbcTemplateTests { int[] actualRowsAffected = namedParameterTemplate.batchUpdate( "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids); - assertThat(actualRowsAffected.length == 3).as("executed 3 updates").isTrue(); + assertThat(actualRowsAffected.length).as("executed 3 updates").isEqualTo(3); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); assertThat(actualRowsAffected[2]).isEqualTo(rowsAffected[2]); 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 bc70aad919d..508fc319a07 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 @@ -91,17 +91,17 @@ public class CallMetaDataContextTests { context.processParameters(parameters); Map inParameters = context.matchInParameterValuesWithCallParameters(parameterSource); - assertThat(inParameters.size()).as("Wrong number of matched in parameter values").isEqualTo(2); + assertThat(inParameters).as("Wrong number of matched in parameter values").hasSize(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(); - assertThat(names.size()).as("Wrong number of out parameters").isEqualTo(2); + assertThat(names).as("Wrong number of out parameters").hasSize(2); List callParameters = context.getCallParameters(); - assertThat(callParameters.size()).as("Wrong number of call parameters").isEqualTo(3); + assertThat(callParameters).as("Wrong number of call parameters").hasSize(3); } } 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 82565eed717..7c0bcf9c053 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 @@ -48,7 +48,7 @@ public class JdbcDaoSupportTests { dao.afterPropertiesSet(); 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); + assertThat(test).as("initDao called").hasSize(1); } @Test @@ -64,7 +64,7 @@ public class JdbcDaoSupportTests { dao.setJdbcTemplate(template); dao.afterPropertiesSet(); assertThat(template).as("Correct JdbcTemplate").isEqualTo(dao.getJdbcTemplate()); - assertThat(test.size()).as("initDao called").isEqualTo(1); + assertThat(test).as("initDao called").hasSize(1); } } 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 5e045c6bced..f6cb99fbfca 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 @@ -1736,7 +1736,7 @@ public class DataSourceTransactionManagerTests { protected void doAfterCompletion(int status) { assertThat(this.afterCompletionCalled).isFalse(); this.afterCompletionCalled = true; - assertThat(status == this.status).isTrue(); + assertThat(status).isEqualTo(this.status); 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 c4a976074e9..288d21d5e69 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 @@ -55,11 +55,11 @@ public class DriverManagerDataSourceTests { ds.setPassword(pwd); Connection actualCon = ds.getConnection(); - assertThat(actualCon == connection).isTrue(); + assertThat(actualCon).isSameAs(connection); - assertThat(ds.getUrl().equals(jdbcUrl)).isTrue(); - assertThat(ds.getPassword().equals(pwd)).isTrue(); - assertThat(ds.getUsername().equals(uname)).isTrue(); + assertThat(ds.getUrl()).isEqualTo(jdbcUrl); + assertThat(ds.getPassword()).isEqualTo(pwd); + assertThat(ds.getUsername()).isEqualTo(uname); } @Test @@ -90,9 +90,9 @@ public class DriverManagerDataSourceTests { ds.setConnectionProperties(connProps); Connection actualCon = ds.getConnection(); - assertThat(actualCon == connection).isTrue(); + assertThat(actualCon).isSameAs(connection); - assertThat(ds.getUrl().equals(jdbcUrl)).isTrue(); + assertThat(ds.getUrl()).isEqualTo(jdbcUrl); } @Test @@ -127,11 +127,11 @@ public class DriverManagerDataSourceTests { ds.setConnectionProperties(connProps); Connection actualCon = ds.getConnection(); - assertThat(actualCon == connection).isTrue(); + assertThat(actualCon).isSameAs(connection); - assertThat(ds.getUrl().equals(jdbcUrl)).isTrue(); - assertThat(ds.getPassword().equals(pwd)).isTrue(); - assertThat(ds.getUsername().equals(uname)).isTrue(); + assertThat(ds.getUrl()).isEqualTo(jdbcUrl); + assertThat(ds.getPassword()).isEqualTo(pwd); + assertThat(ds.getUsername()).isEqualTo(uname); } @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 dd1a576a160..8c9d0dae935 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 @@ -88,16 +88,16 @@ public class BatchSqlUpdateTests { assertThat(update.getQueueCount()).isEqualTo(0); if (flushThroughBatchSize) { - assertThat(actualRowsAffected.length == 0).as("flush did not execute updates").isTrue(); + assertThat(actualRowsAffected).as("flush did not execute updates").isEmpty(); } else { - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); } actualRowsAffected = update.getRowsAffected(); - assertThat(actualRowsAffected.length == 2).as("executed 2 updates").isTrue(); + assertThat(actualRowsAffected).as("executed 2 updates").hasSize(2); assertThat(actualRowsAffected[0]).isEqualTo(rowsAffected[0]); assertThat(actualRowsAffected[1]).isEqualTo(rowsAffected[1]); 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 0b2e0e75d86..e91c465fe15 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 @@ -107,10 +107,10 @@ public class GenericSqlQueryTests { Object[] params = new Object[] {1, "UK"}; queryResults = query.execute(params); } - assertThat(queryResults.size() == 1).as("Customer was returned correctly").isTrue(); + assertThat(queryResults).as("Customer was returned correctly").hasSize(1); Customer cust = (Customer) queryResults.get(0); - assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); - assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); + assertThat(cust.getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(cust.getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(resultSet).close(); verify(preparedStatement).setObject(1, 1, Types.INTEGER); 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 f5719213bed..51443c46c2d 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 @@ -111,8 +111,8 @@ public class SqlQueryTests { @Override protected Integer mapRow(ResultSet rs, int rownum, @Nullable Object[] params, @Nullable Map context) throws SQLException { - assertThat(params == null).as("params were null").isTrue(); - assertThat(context == null).as("context was null").isTrue(); + assertThat(params).as("params were null").isNull(); + assertThat(context).as("context was null").isNull(); return rs.getInt(1); } }; @@ -221,8 +221,8 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); Customer cust = query.findCustomer(1, 1); - assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); - assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); + assertThat(cust.getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(cust.getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setObject(2, 1, Types.NUMERIC); verify(connection).prepareStatement(SELECT_ID_WHERE); @@ -261,8 +261,8 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); Customer cust = query.findCustomer("rod"); - assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); - assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); + assertThat(cust.getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(cust.getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(preparedStatement).setString(1, "rod"); verify(connection).prepareStatement(SELECT_ID_FORENAME_WHERE); verify(resultSet).close(); @@ -307,11 +307,11 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); Customer cust1 = query.findCustomer(1, "rod"); - assertThat(cust1 != null).as("Found customer").isTrue(); - assertThat(cust1.getId() == 1).as("Customer id was assigned correctly").isTrue(); + assertThat(cust1).as("Found customer").isNotNull(); + assertThat(cust1.getId()).as("Customer id was assigned correctly").isEqualTo(1); Customer cust2 = query.findCustomer(1, "Roger"); - assertThat(cust2 == null).as("No customer found").isTrue(); + assertThat(cust2).as("No customer found").isNull(); verify(preparedStatement).setObject(1, 1, Types.INTEGER); verify(preparedStatement).setString(2, "rod"); @@ -387,7 +387,7 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); List list = query.execute(1, 1); - assertThat(list.size() == 2).as("2 results in list").isTrue(); + assertThat(list.size()).as("2 results in list").isEqualTo(2); assertThat(list.get(0).getForename()).isEqualTo("rod"); assertThat(list.get(1).getForename()).isEqualTo("dave"); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); @@ -423,7 +423,7 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); List list = query.execute("one"); - assertThat(list.size() == 2).as("2 results in list").isTrue(); + assertThat(list.size()).as("2 results in list").isEqualTo(2); assertThat(list.get(0).getForename()).isEqualTo("rod"); assertThat(list.get(1).getForename()).isEqualTo("dave"); verify(preparedStatement).setString(1, "one"); @@ -467,8 +467,8 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); Customer cust = query.findCustomer(1); - assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); - assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); + assertThat(cust.getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(cust.getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(resultSet).close(); verify(preparedStatement).close(); @@ -563,8 +563,8 @@ public class SqlQueryTests { CustomerQuery query = new CustomerQuery(dataSource); Customer cust = query.findCustomer(1, "UK"); - assertThat(cust.getId() == 1).as("Customer id was assigned correctly").isTrue(); - assertThat(cust.getForename().equals("rod")).as("Customer forename was assigned correctly").isTrue(); + assertThat(cust.getId()).as("Customer id was assigned correctly").isEqualTo(1); + assertThat(cust.getForename()).as("Customer forename was assigned correctly").isEqualTo("rod"); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setString(2, "UK"); verify(resultSet).close(); @@ -613,10 +613,11 @@ public class SqlQueryTests { List cust = query.findCustomers(ids); 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()); + assertThat(cust.get(0).getId()).as("First customer id was assigned correctly").isEqualTo(1); + assertThat(cust.get(0).getForename()).as("First customer forename was assigned correctly").isEqualTo("rod"); + assertThat(cust.get(1).getId()).as("Second customer id was assigned correctly").isEqualTo(2); + assertThat(cust.get(1).getForename()).as("Second customer forename was assigned correctly") + .isEqualTo("juergen"); verify(preparedStatement).setObject(1, 1, Types.NUMERIC); verify(preparedStatement).setObject(2, 2, Types.NUMERIC); verify(resultSet).close(); @@ -662,10 +663,11 @@ public class SqlQueryTests { List cust = query.findCustomers(1); 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()); + assertThat(cust.get(0).getId()).as("First customer id was assigned correctly").isEqualTo(1); + assertThat(cust.get(0).getForename()).as("First customer forename was assigned correctly").isEqualTo("rod"); + assertThat(cust.get(1).getId()).as("Second customer id was assigned correctly").isEqualTo(2); + assertThat(cust.get(1).getForename()).as("Second customer forename was assigned correctly") + .isEqualTo("juergen"); 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/support/JdbcTransactionManagerTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/JdbcTransactionManagerTests.java index 207cc20207c..23bf666db42 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/JdbcTransactionManagerTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/JdbcTransactionManagerTests.java @@ -89,7 +89,7 @@ public class JdbcTransactionManagerTests { @AfterEach public void verifyTransactionSynchronizationManagerState() { - assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.getResourceMap()).isEmpty(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); @@ -142,8 +142,9 @@ public class JdbcTransactionManagerTests { final DataSource dsToUse = (lazyConnection ? new LazyConnectionDataSourceProxy(ds) : ds); tm = new JdbcTransactionManager(dsToUse); TransactionTemplate tt = new TransactionTemplate(tm); - assertThat(!TransactionSynchronizationManager.hasResource(dsToUse)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -169,8 +170,9 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(dsToUse)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); if (autoCommit && (!lazyConnection || createStatement)) { InOrder ordered = inOrder(con); @@ -231,8 +233,9 @@ public class JdbcTransactionManagerTests { final DataSource dsToUse = (lazyConnection ? new LazyConnectionDataSourceProxy(ds) : ds); tm = new JdbcTransactionManager(dsToUse); TransactionTemplate tt = new TransactionTemplate(tm); - assertThat(!TransactionSynchronizationManager.hasResource(dsToUse)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(dsToUse)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); final RuntimeException ex = new RuntimeException("Application exception"); assertThatRuntimeException().isThrownBy(() -> @@ -256,8 +259,9 @@ public class JdbcTransactionManagerTests { })) .isEqualTo(ex); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); if (autoCommit && (!lazyConnection || createStatement)) { InOrder ordered = inOrder(con); @@ -277,8 +281,9 @@ public class JdbcTransactionManagerTests { public void testTransactionRollbackOnly() throws Exception { tm.setTransactionSynchronization(JdbcTransactionManager.SYNCHRONIZATION_NEVER); TransactionTemplate tt = new TransactionTemplate(tm); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); ConnectionHolder conHolder = new ConnectionHolder(con, true); TransactionSynchronizationManager.bindResource(ds, conHolder); @@ -288,8 +293,9 @@ public class JdbcTransactionManagerTests { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); - assertThat(!status.isNewTransaction()).as("Is existing transaction").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); + assertThat(status.isNewTransaction()).as("Is existing transaction").isFalse(); throw ex; } }); @@ -297,14 +303,15 @@ public class JdbcTransactionManagerTests { } catch (RuntimeException ex2) { // expected - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); assertThat(ex2).as("Correct exception thrown").isEqualTo(ex); } finally { TransactionSynchronizationManager.unbindResource(ds); } - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); } @Test @@ -322,8 +329,9 @@ public class JdbcTransactionManagerTests { if (failEarly) { tm.setFailEarlyOnGlobalRollbackOnly(true); } - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); TestTransactionSynchronization synch = @@ -338,18 +346,18 @@ public class JdbcTransactionManagerTests { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertThat(!status.isNewTransaction()).as("Is existing transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Is existing transaction").isFalse(); assertThat(status.isRollbackOnly()).as("Is not rollback-only").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); - assertThat(!status.isNewTransaction()).as("Is existing transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Is existing transaction").isFalse(); status.setRollbackOnly(); } }); - assertThat(!status.isNewTransaction()).as("Is existing transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Is existing transaction").isFalse(); assertThat(status.isRollbackOnly()).as("Is rollback-only").isTrue(); } }); @@ -372,7 +380,7 @@ public class JdbcTransactionManagerTests { } } - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); assertThat(synch.beforeCommitCalled).isFalse(); assertThat(synch.beforeCompletionCalled).isTrue(); assertThat(synch.afterCommitCalled).isFalse(); @@ -385,8 +393,9 @@ public class JdbcTransactionManagerTests { public void testParticipatingTransactionWithIncompatibleIsolationLevel() throws Exception { tm.setValidateExistingTransaction(true); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> { final TransactionTemplate tt = new TransactionTemplate(tm); @@ -408,7 +417,7 @@ public class JdbcTransactionManagerTests { }); }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).rollback(); verify(con).close(); } @@ -418,8 +427,9 @@ public class JdbcTransactionManagerTests { willThrow(new SQLException("read-only not supported")).given(con).setReadOnly(true); tm.setValidateExistingTransaction(true); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> { final TransactionTemplate tt = new TransactionTemplate(tm); @@ -442,15 +452,16 @@ public class JdbcTransactionManagerTests { }); }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).rollback(); verify(con).close(); } @Test public void testParticipatingTransactionWithTransactionStartedFromSynch() throws Exception { - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); @@ -476,12 +487,12 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); assertThat(synch.beforeCommitCalled).isTrue(); assertThat(synch.beforeCompletionCalled).isTrue(); assertThat(synch.afterCommitCalled).isTrue(); assertThat(synch.afterCompletionCalled).isTrue(); - assertThat(synch.afterCompletionException instanceof IllegalStateException).isTrue(); + assertThat(synch.afterCompletionException).isInstanceOf(IllegalStateException.class); verify(con, times(2)).commit(); verify(con, times(2)).close(); } @@ -492,8 +503,9 @@ public class JdbcTransactionManagerTests { final Connection con2 = mock(); given(ds2.getConnection()).willReturn(con2); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -514,7 +526,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); assertThat(synch.beforeCommitCalled).isTrue(); assertThat(synch.beforeCompletionCalled).isTrue(); assertThat(synch.afterCommitCalled).isTrue(); @@ -531,8 +543,9 @@ public class JdbcTransactionManagerTests { JdbcTransactionManager tm2 = new JdbcTransactionManager(ds); // tm has no synch enabled (used at outer level), tm2 has synch enabled (inner level) - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); final TestTransactionSynchronization synch = @@ -544,18 +557,18 @@ public class JdbcTransactionManagerTests { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertThat(!status.isNewTransaction()).as("Is existing transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Is existing transaction").isFalse(); assertThat(status.isRollbackOnly()).as("Is not rollback-only").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); - assertThat(!status.isNewTransaction()).as("Is existing transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Is existing transaction").isFalse(); status.setRollbackOnly(); } }); - assertThat(!status.isNewTransaction()).as("Is existing transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Is existing transaction").isFalse(); assertThat(status.isRollbackOnly()).as("Is rollback-only").isTrue(); TransactionSynchronizationManager.registerSynchronization(synch); } @@ -564,7 +577,7 @@ public class JdbcTransactionManagerTests { tm.commit(ts); }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); assertThat(synch.beforeCommitCalled).isFalse(); assertThat(synch.beforeCompletionCalled).isTrue(); assertThat(synch.afterCommitCalled).isFalse(); @@ -577,8 +590,9 @@ public class JdbcTransactionManagerTests { public void testPropagationRequiresNewWithExistingTransaction() throws Exception { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -604,7 +618,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).rollback(); verify(con).commit(); verify(con, times(2)).close(); @@ -623,9 +637,10 @@ public class JdbcTransactionManagerTests { final TransactionTemplate tt2 = new TransactionTemplate(tm2); tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.hasResource(ds2)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(ds2)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -651,8 +666,8 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.hasResource(ds2)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(ds2)).as("Hasn't thread connection").isFalse(); verify(con).commit(); verify(con).close(); verify(con2).rollback(); @@ -673,9 +688,10 @@ public class JdbcTransactionManagerTests { final TransactionTemplate tt2 = new TransactionTemplate(tm2); tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.hasResource(ds2)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(ds2)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); assertThatExceptionOfType(CannotCreateTransactionException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @@ -694,8 +710,8 @@ public class JdbcTransactionManagerTests { } })).withCause(failure); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.hasResource(ds2)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(ds2)).as("Hasn't thread connection").isFalse(); verify(con).rollback(); verify(con).close(); } @@ -704,8 +720,9 @@ public class JdbcTransactionManagerTests { public void testPropagationNotSupportedWithExistingTransaction() throws Exception { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -717,9 +734,10 @@ public class JdbcTransactionManagerTests { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection") + .isFalse(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); - assertThat(!status.isNewTransaction()).as("Isn't new transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Isn't new transaction").isFalse(); assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); status.setRollbackOnly(); @@ -731,7 +749,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).commit(); verify(con).close(); } @@ -740,8 +758,9 @@ public class JdbcTransactionManagerTests { public void testPropagationNeverWithExistingTransaction() throws Exception { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); assertThatExceptionOfType(IllegalTransactionStateException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @@ -759,7 +778,7 @@ public class JdbcTransactionManagerTests { } })); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).rollback(); verify(con).close(); } @@ -768,8 +787,9 @@ public class JdbcTransactionManagerTests { public void testPropagationSupportsAndRequiresNew() throws Exception { TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -790,7 +810,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).commit(); verify(con).close(); } @@ -804,8 +824,9 @@ public class JdbcTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -829,7 +850,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con1).close(); verify(con2).commit(); verify(con2).close(); @@ -844,7 +865,7 @@ public class JdbcTransactionManagerTests { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); tt.setReadOnly(true); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { @@ -854,7 +875,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); InOrder ordered = inOrder(con); ordered.verify(con).setReadOnly(true); ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); @@ -877,7 +898,7 @@ public class JdbcTransactionManagerTests { TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); tt.setReadOnly(true); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { @@ -887,7 +908,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); InOrder ordered = inOrder(con, stmt); ordered.verify(con).setReadOnly(true); ordered.verify(con).setAutoCommit(false); @@ -909,7 +930,7 @@ public class JdbcTransactionManagerTests { TransactionTemplate tt = new TransactionTemplate(tm); tt.setTimeout(timeout); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); try { tt.execute(new TransactionCallbackWithoutResult() { @@ -943,7 +964,7 @@ public class JdbcTransactionManagerTests { } } - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); if (timeout > 1) { verify(ps).setQueryTimeout(timeout - 1); verify(con).commit(); @@ -963,7 +984,7 @@ public class JdbcTransactionManagerTests { given(con.getWarnings()).willThrow(new SQLException()); TransactionTemplate tt = new TransactionTemplate(tm); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { @@ -984,7 +1005,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); InOrder ordered = inOrder(con); ordered.verify(con).setAutoCommit(false); ordered.verify(con).commit(); @@ -998,7 +1019,7 @@ public class JdbcTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -1042,7 +1063,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); InOrder ordered = inOrder(con); ordered.verify(con).setAutoCommit(false); ordered.verify(con).commit(); @@ -1056,7 +1077,7 @@ public class JdbcTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -1101,7 +1122,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); InOrder ordered = inOrder(con); ordered.verify(con).setAutoCommit(false); ordered.verify(con).commit(); @@ -1125,7 +1146,7 @@ public class JdbcTransactionManagerTests { } })); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).close(); } @@ -1142,7 +1163,7 @@ public class JdbcTransactionManagerTests { } })); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).close(); } @@ -1160,7 +1181,7 @@ public class JdbcTransactionManagerTests { } })); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).close(); } @@ -1177,7 +1198,7 @@ public class JdbcTransactionManagerTests { } })); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).close(); } @@ -1195,7 +1216,7 @@ public class JdbcTransactionManagerTests { } })); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).rollback(); verify(con).close(); } @@ -1214,7 +1235,7 @@ public class JdbcTransactionManagerTests { } })); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); InOrder ordered = inOrder(con); ordered.verify(con).setAutoCommit(false); ordered.verify(con).rollback(); @@ -1237,7 +1258,7 @@ public class JdbcTransactionManagerTests { } })); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); InOrder ordered = inOrder(con); ordered.verify(con).setAutoCommit(false); ordered.verify(con).rollback(); @@ -1259,7 +1280,7 @@ public class JdbcTransactionManagerTests { } })); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); InOrder ordered = inOrder(con); ordered.verify(con).setAutoCommit(false); ordered.verify(con).rollback(); @@ -1271,53 +1292,53 @@ public class JdbcTransactionManagerTests { public void testTransactionWithPropagationSupports() throws Exception { TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!status.isNewTransaction()).as("Is not new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(status.isNewTransaction()).as("Is not new transaction").isFalse(); assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); } @Test public void testTransactionWithPropagationNotSupported() throws Exception { TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!status.isNewTransaction()).as("Is not new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(status.isNewTransaction()).as("Is not new transaction").isFalse(); } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); } @Test public void testTransactionWithPropagationNever() throws Exception { TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!status.isNewTransaction()).as("Is not new transaction").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(status.isNewTransaction()).as("Is not new transaction").isFalse(); } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); } @Test @@ -1342,31 +1363,32 @@ public class JdbcTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); - assertThat(!status.hasSavepoint()).as("Isn't nested transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Isn't nested transaction").isFalse(); for (int i = 0; i < count; i++) { tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); - assertThat(!status.isNewTransaction()).as("Isn't new transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Isn't new transaction").isFalse(); assertThat(status.hasSavepoint()).as("Is nested transaction").isTrue(); } }); } assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); - assertThat(!status.hasSavepoint()).as("Isn't nested transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Isn't nested transaction").isFalse(); } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con, times(count)).releaseSavepoint(sp); verify(con).commit(); verify(con).close(); @@ -1383,30 +1405,31 @@ public class JdbcTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); - assertThat(!status.hasSavepoint()).as("Isn't nested transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Isn't nested transaction").isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); - assertThat(!status.isNewTransaction()).as("Isn't new transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Isn't new transaction").isFalse(); assertThat(status.hasSavepoint()).as("Is nested transaction").isTrue(); status.setRollbackOnly(); } }); assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); - assertThat(!status.hasSavepoint()).as("Isn't nested transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Isn't nested transaction").isFalse(); } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).rollback(sp); verify(con).releaseSavepoint(sp); verify(con).commit(); @@ -1424,21 +1447,22 @@ public class JdbcTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); - assertThat(!status.hasSavepoint()).as("Isn't nested transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Isn't nested transaction").isFalse(); assertThatIllegalStateException().isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); - assertThat(!status.isNewTransaction()).as("Isn't new transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Isn't new transaction").isFalse(); assertThat(status.hasSavepoint()).as("Is nested transaction").isTrue(); TransactionTemplate ntt = new TransactionTemplate(tm); ntt.execute(new TransactionCallbackWithoutResult() { @@ -1446,19 +1470,19 @@ public class JdbcTransactionManagerTests { protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); - assertThat(!status.isNewTransaction()).as("Isn't new transaction").isTrue(); - assertThat(!status.hasSavepoint()).as("Is regular transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Isn't new transaction").isFalse(); + assertThat(status.hasSavepoint()).as("Is regular transaction").isFalse(); throw new IllegalStateException(); } }); } })); assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); - assertThat(!status.hasSavepoint()).as("Isn't nested transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Isn't nested transaction").isFalse(); } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).rollback(sp); verify(con).releaseSavepoint(sp); verify(con).commit(); @@ -1476,21 +1500,22 @@ public class JdbcTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); - assertThat(!status.hasSavepoint()).as("Isn't nested transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Isn't nested transaction").isFalse(); assertThatExceptionOfType(UnexpectedRollbackException.class).isThrownBy(() -> tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); - assertThat(!status.isNewTransaction()).as("Isn't new transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Isn't new transaction").isFalse(); assertThat(status.hasSavepoint()).as("Is nested transaction").isTrue(); TransactionTemplate ntt = new TransactionTemplate(tm); ntt.execute(new TransactionCallbackWithoutResult() { @@ -1498,19 +1523,19 @@ public class JdbcTransactionManagerTests { protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Has thread connection").isTrue(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization active").isTrue(); - assertThat(!status.isNewTransaction()).as("Isn't new transaction").isTrue(); - assertThat(!status.hasSavepoint()).as("Is regular transaction").isTrue(); + assertThat(status.isNewTransaction()).as("Isn't new transaction").isFalse(); + assertThat(status.hasSavepoint()).as("Is regular transaction").isFalse(); status.setRollbackOnly(); } }); } })); assertThat(status.isNewTransaction()).as("Is new transaction").isTrue(); - assertThat(!status.hasSavepoint()).as("Isn't nested transaction").isTrue(); + assertThat(status.hasSavepoint()).as("Isn't nested transaction").isFalse(); } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).rollback(sp); verify(con).releaseSavepoint(sp); verify(con).commit(); @@ -1528,8 +1553,9 @@ public class JdbcTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -1541,7 +1567,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).releaseSavepoint(sp); verify(con).commit(); verify(con).close(); @@ -1559,8 +1585,9 @@ public class JdbcTransactionManagerTests { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -1572,7 +1599,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).rollback(sp); verify(con).commit(); verify(con).close(); @@ -1582,8 +1609,9 @@ public class JdbcTransactionManagerTests { public void testTransactionWithPropagationNested() throws Exception { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -1592,7 +1620,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).commit(); verify(con).close(); } @@ -1601,8 +1629,9 @@ public class JdbcTransactionManagerTests { public void testTransactionWithPropagationNestedAndRollback() throws Exception { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).as("Synchronization not active") + .isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -1612,7 +1641,7 @@ public class JdbcTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(ds)).as("Hasn't thread connection").isFalse(); verify(con).rollback(); verify(con).close(); } @@ -1688,7 +1717,7 @@ public class JdbcTransactionManagerTests { protected void doAfterCompletion(int status) { assertThat(this.afterCompletionCalled).isFalse(); this.afterCompletionCalled = true; - assertThat(status == this.status).isTrue(); + assertThat(status).isEqualTo(this.status); assertThat(TransactionSynchronizationManager.hasResource(this.dataSource)).isTrue(); } } 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 6b091fe1a2b..7e103033e83 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 @@ -50,8 +50,8 @@ public class SQLErrorCodesFactoryTests { @Test public void testDefaultInstanceWithNoSuchDatabase() { SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes("xx"); - assertThat(sec.getBadSqlGrammarCodes().length == 0).isTrue(); - assertThat(sec.getDataIntegrityViolationCodes().length == 0).isTrue(); + assertThat(sec.getBadSqlGrammarCodes().length).isEqualTo(0); + assertThat(sec.getDataIntegrityViolationCodes().length).isEqualTo(0); } /** @@ -64,80 +64,80 @@ public class SQLErrorCodesFactoryTests { } private void assertIsOracle(SQLErrorCodes sec) { - assertThat(sec.getBadSqlGrammarCodes().length > 0).isTrue(); - assertThat(sec.getDataIntegrityViolationCodes().length > 0).isTrue(); + assertThat(sec.getBadSqlGrammarCodes().length).isGreaterThan(0); + assertThat(sec.getDataIntegrityViolationCodes().length).isGreaterThan(0); // These had better be a Bad SQL Grammar code - assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942") >= 0).isTrue(); - assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "6550") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "6550")).isGreaterThanOrEqualTo(0); // This had better NOT be - assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "9xx42") >= 0).isFalse(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "9xx42")).isLessThan(0); } private void assertIsSQLServer(SQLErrorCodes sec) { assertThat(sec.getDatabaseProductName()).isEqualTo("Microsoft SQL Server"); - assertThat(sec.getBadSqlGrammarCodes().length > 0).isTrue(); + assertThat(sec.getBadSqlGrammarCodes().length).isGreaterThan(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(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "156")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "170")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "207")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "208")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "209")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "9xx42")).isLessThan(0); - assertThat(sec.getPermissionDeniedCodes().length > 0).isTrue(); - assertThat(Arrays.binarySearch(sec.getPermissionDeniedCodes(), "229") >= 0).isTrue(); + assertThat(sec.getPermissionDeniedCodes().length).isGreaterThan(0); + assertThat(Arrays.binarySearch(sec.getPermissionDeniedCodes(), "229")).isGreaterThanOrEqualTo(0); - assertThat(sec.getDuplicateKeyCodes().length > 0).isTrue(); - assertThat(Arrays.binarySearch(sec.getDuplicateKeyCodes(), "2601") >= 0).isTrue(); - assertThat(Arrays.binarySearch(sec.getDuplicateKeyCodes(), "2627") >= 0).isTrue(); + assertThat(sec.getDuplicateKeyCodes().length).isGreaterThan(0); + assertThat(Arrays.binarySearch(sec.getDuplicateKeyCodes(), "2601")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getDuplicateKeyCodes(), "2627")).isGreaterThanOrEqualTo(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(); + assertThat(sec.getDataIntegrityViolationCodes().length).isGreaterThan(0); + assertThat(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "544")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "8114")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "8115")).isGreaterThanOrEqualTo(0); - assertThat(sec.getDataAccessResourceFailureCodes().length > 0).isTrue(); - assertThat(Arrays.binarySearch(sec.getDataAccessResourceFailureCodes(), "4060") >= 0).isTrue(); + assertThat(sec.getDataAccessResourceFailureCodes().length).isGreaterThan(0); + assertThat(Arrays.binarySearch(sec.getDataAccessResourceFailureCodes(), "4060")).isGreaterThanOrEqualTo(0); - assertThat(sec.getCannotAcquireLockCodes().length > 0).isTrue(); - assertThat(Arrays.binarySearch(sec.getCannotAcquireLockCodes(), "1222") >= 0).isTrue(); + assertThat(sec.getCannotAcquireLockCodes().length).isGreaterThan(0); + assertThat(Arrays.binarySearch(sec.getCannotAcquireLockCodes(), "1222")).isGreaterThanOrEqualTo(0); - assertThat(sec.getDeadlockLoserCodes().length > 0).isTrue(); - assertThat(Arrays.binarySearch(sec.getDeadlockLoserCodes(), "1205") >= 0).isTrue(); + assertThat(sec.getDeadlockLoserCodes().length).isGreaterThan(0); + assertThat(Arrays.binarySearch(sec.getDeadlockLoserCodes(), "1205")).isGreaterThanOrEqualTo(0); } private void assertIsHsql(SQLErrorCodes sec) { - assertThat(sec.getBadSqlGrammarCodes().length > 0).isTrue(); - assertThat(sec.getDataIntegrityViolationCodes().length > 0).isTrue(); + assertThat(sec.getBadSqlGrammarCodes().length).isGreaterThan(0); + assertThat(sec.getDataIntegrityViolationCodes().length).isGreaterThan(0); // This had better be a Bad SQL Grammar code - assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-22") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-22")).isGreaterThanOrEqualTo(0); // This had better NOT be - assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-9") >= 0).isFalse(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-9")).isLessThan(0); } private void assertIsDB2(SQLErrorCodes sec) { - assertThat(sec.getBadSqlGrammarCodes().length > 0).isTrue(); - assertThat(sec.getDataIntegrityViolationCodes().length > 0).isTrue(); + assertThat(sec.getBadSqlGrammarCodes().length).isGreaterThan(0); + assertThat(sec.getDataIntegrityViolationCodes().length).isGreaterThan(0); - assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942") >= 0).isFalse(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942")).isLessThan(0); // This had better NOT be - assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-204") >= 0).isTrue(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-204")).isGreaterThanOrEqualTo(0); } private void assertIsHana(SQLErrorCodes sec) { - assertThat(sec.getBadSqlGrammarCodes().length > 0).isTrue(); - assertThat(sec.getDataIntegrityViolationCodes().length > 0).isTrue(); + assertThat(sec.getBadSqlGrammarCodes().length).isGreaterThan(0); + assertThat(sec.getDataIntegrityViolationCodes().length).isGreaterThan(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(); + assertThat(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "368")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getPermissionDeniedCodes(), "10")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getDuplicateKeyCodes(), "301")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getDataIntegrityViolationCodes(), "461")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getDataAccessResourceFailureCodes(), "-813")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getInvalidResultSetAccessCodes(), "582")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getCannotAcquireLockCodes(), "131")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getCannotSerializeTransactionCodes(), "138")).isGreaterThanOrEqualTo(0); + assertThat(Arrays.binarySearch(sec.getDeadlockLoserCodes(), "133")).isGreaterThanOrEqualTo(0); } @@ -163,8 +163,8 @@ public class SQLErrorCodesFactoryTests { // Should have failed to load without error TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory(); - assertThat(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0).isTrue(); - assertThat(sf.getErrorCodes("Oracle").getDataIntegrityViolationCodes().length == 0).isTrue(); + assertThat(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length).isEqualTo(0); + assertThat(sf.getErrorCodes("Oracle").getDataIntegrityViolationCodes().length).isEqualTo(0); } /** @@ -184,7 +184,7 @@ public class SQLErrorCodesFactoryTests { // Should have loaded without error TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory(); - assertThat(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0).isTrue(); + assertThat(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length).isEqualTo(0); assertThat(sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()).hasSize(2); assertThat(sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[0]).isEqualTo("1"); assertThat(sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[1]).isEqualTo("2"); @@ -205,7 +205,7 @@ public class SQLErrorCodesFactoryTests { // Should have failed to load without error TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory(); - assertThat(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0).isTrue(); + assertThat(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length).isEqualTo(0); assertThat(sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()).isEmpty(); } 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 50ceb8efa56..d5227cd6dc1 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 @@ -128,8 +128,9 @@ abstract class AbstractJmsAnnotationDrivenTests { JmsListenerEndpointRegistry customRegistry = context.getBean("customRegistry", JmsListenerEndpointRegistry.class); - 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.getListenerContainerIds()).as("Wrong number of containers in the registry") + .hasSize(2); + assertThat(customRegistry.getListenerContainers()).as("Wrong number of containers in the registry").hasSize(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(); } 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 d84cce2de4f..6a66570484c 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 @@ -61,7 +61,7 @@ class JmsListenerAnnotationBeanPostProcessorTests { Config.class, SimpleMessageListenerTestBean.class); JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); - assertThat(factory.getListenerContainers().size()).as("One container should have been registered").isEqualTo(1); + assertThat(factory.getListenerContainers()).as("One container should have been registered").hasSize(1); MessageListenerTestContainer container = factory.getListenerContainers().get(0); JmsListenerEndpoint endpoint = container.getEndpoint(); @@ -84,7 +84,7 @@ class JmsListenerAnnotationBeanPostProcessorTests { void metaAnnotationIsDiscovered() throws Exception { try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class, MetaAnnotationTestBean.class)) { JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); - assertThat(factory.getListenerContainers().size()).as("one container should have been registered").isEqualTo(1); + assertThat(factory.getListenerContainers()).as("one container should have been registered").hasSize(1); JmsListenerEndpoint endpoint = factory.getListenerContainers().get(0).getEndpoint(); assertThat(endpoint.getClass()).as("Wrong endpoint type").isEqualTo(MethodJmsListenerEndpoint.class); @@ -100,7 +100,7 @@ class JmsListenerAnnotationBeanPostProcessorTests { void sendToAnnotationFoundOnInterfaceProxy() throws Exception { try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class, ProxyConfig.class, InterfaceProxyTestBean.class)) { JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); - assertThat(factory.getListenerContainers().size()).as("one container should have been registered").isEqualTo(1); + assertThat(factory.getListenerContainers()).as("one container should have been registered").hasSize(1); JmsListenerEndpoint endpoint = factory.getListenerContainers().get(0).getEndpoint(); assertThat(endpoint.getClass()).as("Wrong endpoint type").isEqualTo(MethodJmsListenerEndpoint.class); @@ -122,7 +122,7 @@ class JmsListenerAnnotationBeanPostProcessorTests { void sendToAnnotationFoundOnCglibProxy() throws Exception { try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class, ProxyConfig.class, ClassProxyTestBean.class)) { JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); - assertThat(factory.getListenerContainers().size()).as("one container should have been registered").isEqualTo(1); + assertThat(factory.getListenerContainers()).as("one container should have been registered").hasSize(1); JmsListenerEndpoint endpoint = factory.getListenerContainers().get(0).getEndpoint(); assertThat(endpoint.getClass()).as("Wrong endpoint type").isEqualTo(MethodJmsListenerEndpoint.class); 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 81ac902e2ba..41d031a4968 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 @@ -81,10 +81,10 @@ public class JmsNamespaceHandlerTests { @Test public void testBeansCreated() { Map containers = context.getBeansOfType(DefaultMessageListenerContainer.class); - assertThat(containers.size()).as("Context should contain 3 JMS listener containers").isEqualTo(3); + assertThat(containers).as("Context should contain 3 JMS listener containers").hasSize(3); containers = context.getBeansOfType(GenericMessageEndpointManager.class); - assertThat(containers.size()).as("Context should contain 3 JCA endpoint containers").isEqualTo(3); + assertThat(containers).as("Context should contain 3 JCA endpoint containers").hasSize(3); assertThat(context.getBeansOfType(JmsListenerContainerFactory.class)) .as("Context should contain 3 JmsListenerContainerFactory instances").hasSize(3); 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 018b8e7f8b2..b26da5192c0 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 @@ -138,7 +138,7 @@ class JmsTemplateTests { PrintWriter out = new PrintWriter(sw); springJmsEx.printStackTrace(out); String trace = sw.toString(); - assertThat(trace.indexOf("host not found") > 0).as("inner jms exception not found").isTrue(); + assertThat(trace.indexOf("host not found")).as("inner jms exception not found").isGreaterThan(0); } @Test 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 48babda4836..d82020dc40c 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 @@ -47,7 +47,7 @@ class JmsGatewaySupportTests { gateway.afterPropertiesSet(); 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); + assertThat(test).as("initGateway called").hasSize(1); } @Test @@ -63,7 +63,7 @@ class JmsGatewaySupportTests { gateway.setJmsTemplate(template); gateway.afterPropertiesSet(); assertThat(gateway.getJmsTemplate()).as("Correct JmsTemplate").isEqualTo(template); - assertThat(test.size()).as("initGateway called").isEqualTo(1); + assertThat(test).as("initGateway called").hasSize(1); } } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/GsonMessageConverterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/GsonMessageConverterTests.java index c5c100449e3..2c67e9cc6f9 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/GsonMessageConverterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/GsonMessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -130,7 +130,7 @@ public class GsonMessageConverterTests { MethodParameter param = new MethodParameter(method, 0); Object actual = converter.fromMessage(message, MyBean.class, param); - assertThat(actual instanceof MyBean).isTrue(); + assertThat(actual).isInstanceOf(MyBean.class); assertThat(((MyBean) actual).getString()).isEqualTo("foo"); } @@ -147,11 +147,11 @@ public class GsonMessageConverterTests { Message message = converter.toMessage(payload, null); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); - 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("\"string\":\"Foo\""); + assertThat(actual).contains("\"number\":42"); + assertThat(actual).contains("fraction\":42.0"); + assertThat(actual).contains("\"array\":[\"Foo\",\"Bar\"]"); + assertThat(actual).contains("\"bool\":true"); assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)).as("Invalid content-type").isEqualTo(new MimeType("application", "json")); } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/converter/JsonbMessageConverterTests.java b/spring-messaging/src/test/java/org/springframework/messaging/converter/JsonbMessageConverterTests.java index b5026deffdc..6b626a42474 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/converter/JsonbMessageConverterTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/converter/JsonbMessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,7 +131,7 @@ public class JsonbMessageConverterTests { MethodParameter param = new MethodParameter(method, 0); Object actual = converter.fromMessage(message, MyBean.class, param); - assertThat(actual instanceof MyBean).isTrue(); + assertThat(actual).isInstanceOf(MyBean.class); assertThat(((MyBean) actual).getString()).isEqualTo("foo"); } @@ -148,11 +148,11 @@ public class JsonbMessageConverterTests { Message message = converter.toMessage(payload, null); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); - 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("\"string\":\"Foo\""); + assertThat(actual).contains("\"number\":42"); + assertThat(actual).contains("fraction\":42.0"); + assertThat(actual).contains("\"array\":[\"Foo\",\"Bar\"]"); + assertThat(actual).contains("\"bool\":true"); assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)).as("Invalid content-type").isEqualTo(new MimeType("application", "json")); } 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 5fffc1657ff..f94daa92079 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -155,7 +155,7 @@ public class MappingJackson2MessageConverterTests { MethodParameter param = new MethodParameter(method, 0); Object actual = converter.fromMessage(message, MyBean.class, param); - assertThat(actual instanceof MyBean).isTrue(); + assertThat(actual).isInstanceOf(MyBean.class); assertThat(((MyBean) actual).getString()).isEqualTo("foo"); } @@ -173,12 +173,12 @@ public class MappingJackson2MessageConverterTests { Message message = converter.toMessage(payload, null); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); - 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(actual).contains("\"string\":\"Foo\""); + assertThat(actual).contains("\"number\":42"); + assertThat(actual).contains("fraction\":42.0"); + assertThat(actual).contains("\"array\":[\"Foo\",\"Bar\"]"); + assertThat(actual).contains("\"bool\":true"); + assertThat(actual).contains("\"bytes\":\"AQI=\""); assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)).as("Invalid content-type").isEqualTo(new MimeType("application", "json")); } 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 6efb4d67ce7..2c607930fec 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -116,7 +116,7 @@ public class MessageReceivingTemplateTests { this.template.receiveAndConvert(Writer.class); } catch (MessageConversionException ex) { - assertThat(ex.getMessage().contains("payload")).as("Invalid exception message '" + ex.getMessage() + "'").isTrue(); + assertThat(ex.getMessage()).as("Invalid exception message '" + ex.getMessage() + "'").contains("payload"); assertThat(ex.getFailedMessage()).isSameAs(expected); } } 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 ba3724d2137..8ce5766ae79 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -108,7 +108,7 @@ public class MessageSendingTemplateTests { 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.getHeaders()).as("expected 'id' and 'timestamp' headers only").hasSize(2); assertThat(this.template.message.getPayload()).isEqualTo("payload"); } @@ -118,7 +118,7 @@ public class MessageSendingTemplateTests { 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.getHeaders()).as("expected 'id' and 'timestamp' headers only").hasSize(2); assertThat(this.template.message.getPayload()).isEqualTo("payload"); } @@ -155,7 +155,7 @@ public class MessageSendingTemplateTests { 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.getHeaders()).as("expected 'id' and 'timestamp' headers only").hasSize(2); assertThat(this.template.message.getPayload()).isEqualTo("payload"); assertThat(this.postProcessor.getMessage()).isNotNull(); @@ -168,7 +168,7 @@ public class MessageSendingTemplateTests { 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.getHeaders()).as("expected 'id' and 'timestamp' headers only").hasSize(2); assertThat(this.template.message.getPayload()).isEqualTo("payload"); assertThat(this.postProcessor.getMessage()).isNotNull(); 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 51963c5b456..c64f88fa175 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ public class DestinationPatternsMessageConditionTests { @Test public void prependNonEmptyPatternsOnly() { DestinationPatternsMessageCondition c = condition(""); - assertThat(c.getPatterns().iterator().next()).isEqualTo(""); + assertThat(c.getPatterns().iterator().next()).isEmpty(); } @Test 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 b0c7df33aec..7a78d3488ca 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -87,7 +87,7 @@ public class PayloadMethodArgumentResolverTests { StepVerifier.create(mono) .consumeErrorWith(ex -> { assertThat(ex.getClass()).isEqualTo(MethodArgumentResolutionException.class); - assertThat(ex.getMessage().contains("Payload content is missing")).as(ex.getMessage()).isTrue(); + assertThat(ex.getMessage()).as(ex.getMessage()).contains("Payload content is missing"); }) .verify(); } 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 8fbeb1fac3c..9c6281aa18d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -121,7 +121,7 @@ public class DefaultRSocketRequesterTests { if (Arrays.equals(new String[] {""}, expectedValues)) { assertThat(payloads).hasSize(1); assertThat(payloads.get(0).getMetadataUtf8()).isEqualTo("toA"); - assertThat(payloads.get(0).getDataUtf8()).isEqualTo(""); + assertThat(payloads.get(0).getDataUtf8()).isEmpty(); } else { assertThat(payloads.stream().map(Payload::getMetadataUtf8).toArray(String[]::new)) @@ -137,7 +137,7 @@ public class DefaultRSocketRequesterTests { assertThat(this.rsocket.getSavedMethodName()).isEqualTo("fireAndForget"); assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("toA"); - assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo(""); + assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEmpty(); } @Test @@ -197,7 +197,7 @@ public class DefaultRSocketRequesterTests { assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestResponse"); assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("toA"); - assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo(""); + assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEmpty(); } @Test @@ -228,7 +228,7 @@ public class DefaultRSocketRequesterTests { assertThat(this.rsocket.getSavedMethodName()).isEqualTo("requestStream"); assertThat(this.rsocket.getSavedPayload().getMetadataUtf8()).isEqualTo("toA"); - assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEqualTo(""); + assertThat(this.rsocket.getSavedPayload().getDataUtf8()).isEmpty(); } @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 5eab1e666f6..6696034fad8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -258,7 +258,7 @@ class RSocketBufferLeakTests { while (true) { try { int count = info.getReferenceCount(); - assertThat(count == 0).as("Leaked payload (refCnt=" + count + "): " + info).isTrue(); + assertThat(count).as("Leaked payload (refCnt=" + count + "): " + info).isEqualTo(0); break; } catch (AssertionError ex) { 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 3c607e6b3ec..e6e12731901 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -175,7 +175,7 @@ public class SimpAnnotationMethodMessageHandlerTests { this.messageHandler.handleMessage(message); 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")).as("should be bound to type long").isInstanceOf(Long.class); assertThat(this.testController.arguments.get("id")).isEqualTo(12L); } 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 23a396b2069..f3383f9d0c0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,7 +76,7 @@ public class DefaultSubscriptionRegistryTests { MultiValueMap actual = this.registry.findSubscriptions(createMessage(dest)); assertThat(actual).isNotNull(); - assertThat(actual.size()).as("Expected one element " + actual).isEqualTo(1); + assertThat(actual).as("Expected one element " + actual).hasSize(1); assertThat(actual.get(sessId)).isEqualTo(Collections.singletonList(subsId)); } @@ -141,7 +141,7 @@ public class DefaultSubscriptionRegistryTests { MultiValueMap actual = this.registry.findSubscriptions(createMessage(dest)); assertThat(actual).isNotNull(); - assertThat(actual.size()).as("Expected one element " + actual).isEqualTo(1); + assertThat(actual).as("Expected one element " + actual).hasSize(1); assertThat(actual.get(sessId)).isEqualTo(Collections.singletonList(subsId)); } @@ -256,19 +256,19 @@ public class DefaultSubscriptionRegistryTests { Message message = createMessage("/topic/PRICE.STOCK.NASDAQ.IBM"); MultiValueMap actual = this.registry.findSubscriptions(message); assertThat(actual).isNotNull(); - assertThat(actual.size()).as("Expected one element " + actual).isEqualTo(1); + assertThat(actual).as("Expected one element " + actual).hasSize(1); assertThat(actual.get(sessId)).isEqualTo(Collections.singletonList(subsId)); message = createMessage("/topic/PRICE.STOCK.NASDAQ.MSFT"); actual = this.registry.findSubscriptions(message); assertThat(actual).isNotNull(); - assertThat(actual.size()).as("Expected one element " + actual).isEqualTo(1); + assertThat(actual).as("Expected one element " + actual).hasSize(1); assertThat(actual.get(sessId)).isEqualTo(Collections.singletonList(subsId)); message = createMessage("/topic/PRICE.STOCK.NASDAQ.VMW"); actual = this.registry.findSubscriptions(message); assertThat(actual).isNotNull(); - assertThat(actual.size()).as("Expected no elements " + actual).isEqualTo(0); + assertThat(actual).as("Expected no elements " + actual).isEmpty(); } @Test @@ -327,21 +327,21 @@ public class DefaultSubscriptionRegistryTests { MultiValueMap actual = this.registry.findSubscriptions(createMessage("/foo")); assertThat(actual).isNotNull(); - assertThat(actual.size()).as("Expected 1 element").isEqualTo(1); + assertThat(actual).as("Expected 1 element").hasSize(1); assertThat(actual.get("sess01")).isEqualTo(Arrays.asList("subs01", "subs02")); this.registry.unregisterSubscription(unsubscribeMessage("sess01", "subs01")); actual = this.registry.findSubscriptions(createMessage("/foo")); assertThat(actual).isNotNull(); - assertThat(actual.size()).as("Expected 1 element").isEqualTo(1); + assertThat(actual).as("Expected 1 element").hasSize(1); assertThat(actual.get("sess01")).isEqualTo(Collections.singletonList("subs02")); this.registry.unregisterSubscription(unsubscribeMessage("sess01", "subs02")); actual = this.registry.findSubscriptions(createMessage("/foo")); assertThat(actual).isNotNull(); - assertThat(actual.size()).as("Expected no element").isEqualTo(0); + assertThat(actual).as("Expected no element").isEmpty(); } @Test @@ -362,7 +362,7 @@ public class DefaultSubscriptionRegistryTests { MultiValueMap actual = this.registry.findSubscriptions(createMessage(dest)); assertThat(actual).isNotNull(); - assertThat(actual.size()).as("Expected two elements: " + actual).isEqualTo(2); + assertThat(actual).as("Expected two elements: " + actual).hasSize(2); assertThat(sort(actual.get(sessIds.get(1)))).isEqualTo(subscriptionIds); assertThat(sort(actual.get(sessIds.get(2)))).isEqualTo(subscriptionIds); } @@ -384,7 +384,7 @@ public class DefaultSubscriptionRegistryTests { MultiValueMap actual = this.registry.findSubscriptions(createMessage(dest)); assertThat(actual).isNotNull(); - assertThat(actual.size()).as("Expected one element: " + actual).isEqualTo(1); + assertThat(actual).as("Expected one element: " + actual).hasSize(1); assertThat(sort(actual.get(sessIds.get(2)))).isEqualTo(subscriptionIds); } @@ -398,7 +398,7 @@ public class DefaultSubscriptionRegistryTests { public void findSubscriptionsNoMatches() { MultiValueMap actual = this.registry.findSubscriptions(createMessage("/foo")); assertThat(actual).isNotNull(); - assertThat(actual.size()).as("Expected no elements " + actual).isEqualTo(0); + assertThat(actual).as("Expected no elements " + actual).isEmpty(); } @Test // SPR-12665 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 ab0c425f9c5..a3b430db8b3 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 @@ -442,7 +442,7 @@ public class MessageBrokerConfigurationTests { ApplicationContext context = loadConfig(CustomConfig.class); SimpUserRegistry registry = context.getBean(SimpUserRegistry.class); - assertThat(registry instanceof TestUserRegistry).isTrue(); + assertThat(registry).isInstanceOf(TestUserRegistry.class); assertThat(((TestUserRegistry) registry).getOrder()).isEqualTo(99); } 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 717610340b7..a499e02e23b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,7 +146,7 @@ public class BufferingStompDecoderTests { String chunk1 = "SEND\na:alpha\n\nPayload1\0SEND\ncontent-length:129\n"; List> messages = stompDecoder.decode(toByteBuffer(chunk1)); - assertThat(messages.size()).as("We should have gotten the 1st message").isEqualTo(1); + assertThat(messages).as("We should have gotten the 1st message").hasSize(1); assertThat(new String(messages.get(0).getPayload())).isEqualTo("Payload1"); assertThat(stompDecoder.getBufferSize()).isEqualTo(24); 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 f64e64def8b..d5902283e5e 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 @@ -363,7 +363,7 @@ public class DefaultStompSessionTests { assertThat(accessor.getCommand()).isEqualTo(StompCommand.SEND); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(2); + assertThat(stompHeaders).as(stompHeaders.toString()).hasSize(2); assertThat(stompHeaders.getDestination()).isEqualTo(destination); assertThat(stompHeaders.getContentType()).isEqualTo(new MimeType("text", "plain", StandardCharsets.UTF_8)); @@ -408,7 +408,7 @@ public class DefaultStompSessionTests { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(2); + assertThat(stompHeaders).as(stompHeaders.toString()).hasSize(2); assertThat(stompHeaders.getDestination()).isEqualTo(destination); assertThat(stompHeaders.getContentType()).isEqualTo(MimeTypeUtils.APPLICATION_OCTET_STREAM); @@ -457,7 +457,7 @@ public class DefaultStompSessionTests { assertThat(accessor.getCommand()).isEqualTo(StompCommand.SUBSCRIBE); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(2); + assertThat(stompHeaders).as(stompHeaders.toString()).hasSize(2); assertThat(stompHeaders.getDestination()).isEqualTo(destination); assertThat(stompHeaders.getId()).isEqualTo(subscription.getSubscriptionId()); } @@ -483,7 +483,7 @@ public class DefaultStompSessionTests { assertThat(accessor.getCommand()).isEqualTo(StompCommand.SUBSCRIBE); stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(2); + assertThat(stompHeaders).as(stompHeaders.toString()).hasSize(2); assertThat(stompHeaders.getDestination()).isEqualTo(destination); assertThat(stompHeaders.getId()).isEqualTo(subscriptionId); } @@ -503,7 +503,7 @@ public class DefaultStompSessionTests { assertThat(accessor.getCommand()).isEqualTo(StompCommand.UNSUBSCRIBE); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(1); + assertThat(stompHeaders).as(stompHeaders.toString()).hasSize(1); assertThat(stompHeaders.getId()).isEqualTo(subscription.getSubscriptionId()); } @@ -530,7 +530,7 @@ public class DefaultStompSessionTests { assertThat(accessor.getCommand()).isEqualTo(StompCommand.UNSUBSCRIBE); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(2); + assertThat(stompHeaders).as(stompHeaders.toString()).hasSize(2); assertThat(stompHeaders.getId()).isEqualTo(subscription.getSubscriptionId()); assertThat(stompHeaders.getFirst(headerName)).isEqualTo(headerValue); } @@ -548,7 +548,7 @@ public class DefaultStompSessionTests { assertThat(accessor.getCommand()).isEqualTo(StompCommand.ACK); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(1); + assertThat(stompHeaders).as(stompHeaders.toString()).hasSize(1); assertThat(stompHeaders.getId()).isEqualTo(messageId); } @@ -565,7 +565,7 @@ public class DefaultStompSessionTests { assertThat(accessor.getCommand()).isEqualTo(StompCommand.NACK); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertThat(stompHeaders.size()).as(stompHeaders.toString()).isEqualTo(1); + assertThat(stompHeaders).as(stompHeaders.toString()).hasSize(1); assertThat(stompHeaders.getId()).isEqualTo(messageId); } @@ -687,7 +687,7 @@ public class DefaultStompSessionTests { Message message = this.messageCaptor.getValue(); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); headers = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); - assertThat(headers.size()).as(headers.toString()).isEqualTo(1); + assertThat(headers).as(headers.toString()).hasSize(1); assertThat(headers.get("foo")).hasSize(1); assertThat(headers.get("foo").get(0)).isEqualTo("bar"); 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 e686e658eae..ca065c898a9 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 @@ -312,7 +312,7 @@ class StompBrokerRelayMessageHandlerTests { } public StompHeaderAccessor getSentHeaders(int index) { - assertThat(getSentMessages().size() > index).as("Size: " + getSentMessages().size()).isTrue(); + assertThat(getSentMessages().size()).as("Size: " + getSentMessages().size()).isGreaterThan(index); Message message = getSentMessages().get(index); StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); assertThat(accessor).isNotNull(); 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 3380ec4b2c9..0372d4e5e24 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,7 +131,7 @@ public class StompDecoderTests { assertThat(headers.getContentLength()).isEqualTo(Integer.valueOf(0)); String bodyText = new String(frame.getPayload()); - assertThat(bodyText).isEqualTo(""); + assertThat(bodyText).isEmpty(); } @Test @@ -218,7 +218,7 @@ public class StompDecoderTests { assertThat(headers.toNativeHeaderMap()).hasSize(2); assertThat(headers.getFirstNativeHeader("accept-version")).isEqualTo("1.1"); - assertThat(headers.getFirstNativeHeader("key")).isEqualTo(""); + assertThat(headers.getFirstNativeHeader("key")).isEmpty(); assertThat(frame.getPayload()).isEmpty(); } 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 d42aea347d1..e4b9f53caa1 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 @@ -46,7 +46,7 @@ public abstract class AbstractEntityManagerFactoryBeanTests { @AfterEach public void tearDown() throws Exception { - assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.getResourceMap()).isEmpty(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); 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 5a314c2fa37..80522102342 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -109,7 +109,7 @@ public abstract class AbstractEntityManagerFactoryIntegrationTests { endTransaction(); } - assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.getResourceMap()).isEmpty(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); 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 982bfd404a2..3cf159c2105 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 @@ -73,7 +73,7 @@ public class JpaTransactionManagerTests { @AfterEach public void verifyTransactionSynchronizationManagerState() { - assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.getResourceMap()).isEmpty(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); @@ -87,8 +87,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); Object result = tt.execute(status -> { assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); @@ -97,8 +97,8 @@ public class JpaTransactionManagerTests { }); assertThat(result).isSameAs(l); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(tx).commit(); verify(manager).flush(); @@ -114,8 +114,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); try { Object result = tt.execute(status -> { @@ -127,11 +127,11 @@ public class JpaTransactionManagerTests { } catch (TransactionSystemException tse) { // expected - assertThat(tse.getCause() instanceof RollbackException).isTrue(); + assertThat(tse.getCause()).isInstanceOf(RollbackException.class); } - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(manager).flush(); verify(manager).close(); @@ -145,8 +145,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThatRuntimeException().isThrownBy(() -> tt.execute(status -> { @@ -155,8 +155,8 @@ public class JpaTransactionManagerTests { throw new RuntimeException("some exception"); })).withMessage("some exception"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(tx).rollback(); verify(manager).close(); @@ -169,8 +169,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThatRuntimeException().isThrownBy(() -> tt.execute(status -> { @@ -179,8 +179,8 @@ public class JpaTransactionManagerTests { throw new RuntimeException("some exception"); })); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(manager).close(); } @@ -193,8 +193,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(status -> { assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); @@ -205,8 +205,8 @@ public class JpaTransactionManagerTests { return l; }); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(manager).flush(); verify(tx).rollback(); @@ -220,8 +220,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(status -> { assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); @@ -232,8 +232,8 @@ public class JpaTransactionManagerTests { }); }); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(manager).flush(); verify(tx).commit(); @@ -248,8 +248,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThatRuntimeException().isThrownBy(() -> tt.execute(status -> { @@ -260,8 +260,8 @@ public class JpaTransactionManagerTests { }); })); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(tx).setRollbackOnly(); verify(tx).rollback(); @@ -278,8 +278,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() -> tt.execute(status -> { @@ -293,8 +293,8 @@ public class JpaTransactionManagerTests { })) .withCauseInstanceOf(RollbackException.class); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(manager).flush(); verify(tx).setRollbackOnly(); @@ -312,8 +312,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); Object result = tt.execute(status -> { assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); @@ -324,8 +324,8 @@ public class JpaTransactionManagerTests { }); assertThat(result).isSameAs(l); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(manager).flush(); verify(manager, times(2)).close(); @@ -341,8 +341,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); @@ -362,8 +362,8 @@ public class JpaTransactionManagerTests { TransactionSynchronizationManager.unbindResource(factory); } - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(tx, times(2)).begin(); verify(tx, times(2)).commit(); @@ -380,8 +380,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); Object result = tt.execute(status -> { assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); @@ -394,8 +394,8 @@ public class JpaTransactionManagerTests { }); assertThat(result).isSameAs(l); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(tx).commit(); verify(manager).flush(); @@ -413,8 +413,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); Object result = tt.execute(status -> { EntityManagerFactoryUtils.getTransactionalEntityManager(factory); @@ -429,8 +429,8 @@ public class JpaTransactionManagerTests { }); assertThat(result).isSameAs(l); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(tx).commit(); verify(manager).flush(); @@ -449,8 +449,8 @@ public class JpaTransactionManagerTests { given(manager2.getTransaction()).willReturn(tx2); given(manager2.isOpen()).willReturn(true); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(status -> { EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); @@ -466,8 +466,8 @@ public class JpaTransactionManagerTests { return null; }); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(tx).commit(); verify(tx2).begin(); @@ -487,20 +487,20 @@ public class JpaTransactionManagerTests { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); Object result = tt.execute(status -> { - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); - assertThat(!status.isNewTransaction()).isTrue(); + assertThat(status.isNewTransaction()).isFalse(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); return l; }); assertThat(result).isSameAs(l); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(manager).flush(); verify(manager).close(); @@ -512,20 +512,20 @@ public class JpaTransactionManagerTests { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(status -> { - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); - assertThat(!status.isNewTransaction()).isTrue(); + assertThat(status.isNewTransaction()).isFalse(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); status.setRollbackOnly(); return null; }); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(manager).flush(); verify(manager).close(); @@ -538,8 +538,8 @@ public class JpaTransactionManagerTests { final List l = new ArrayList<>(); l.add("test"); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); try { @@ -552,7 +552,7 @@ public class JpaTransactionManagerTests { assertThat(result).isSameAs(l); assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } finally { TransactionSynchronizationManager.unbindResource(factory); @@ -567,8 +567,8 @@ public class JpaTransactionManagerTests { given(manager.getTransaction()).willReturn(tx); given(tx.isActive()).willReturn(true); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); try { @@ -581,7 +581,7 @@ public class JpaTransactionManagerTests { }); assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } finally { TransactionSynchronizationManager.unbindResource(factory); @@ -599,22 +599,22 @@ public class JpaTransactionManagerTests { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); try { Object result = tt.execute(status -> { assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); - assertThat(!status.isNewTransaction()).isTrue(); + assertThat(status.isNewTransaction()).isFalse(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); return l; }); assertThat(result).isSameAs(l); assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } finally { TransactionSynchronizationManager.unbindResource(factory); @@ -627,22 +627,22 @@ public class JpaTransactionManagerTests { public void testTransactionRollbackWithPreboundAndPropagationSupports() { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); try { tt.execute(status -> { assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); - assertThat(!status.isNewTransaction()).isTrue(); + assertThat(status.isNewTransaction()).isFalse(); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); status.setRollbackOnly(); return null; }); assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } finally { TransactionSynchronizationManager.unbindResource(factory); @@ -672,8 +672,8 @@ public class JpaTransactionManagerTests { public void testTransactionFlush() { given(manager.getTransaction()).willReturn(tx); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); tt.execute(new TransactionCallbackWithoutResult() { @Override @@ -683,8 +683,8 @@ public class JpaTransactionManagerTests { } }); - assertThat(!TransactionSynchronizationManager.hasResource(factory)).isTrue(); - assertThat(!TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); verify(tx).commit(); verify(manager).flush(); 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 43f2e121ab8..712c7627ef9 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 @@ -37,7 +37,7 @@ public class EclipseLinkEntityManagerFactoryIntegrationTests extends AbstractCon @Test public void testCanCastNativeEntityManagerFactoryToEclipseLinkEntityManagerFactoryImpl() { EntityManagerFactoryInfo emfi = (EntityManagerFactoryInfo) entityManagerFactory; - assertThat(emfi.getNativeEntityManagerFactory().getClass().getName().endsWith("EntityManagerFactoryImpl")).isTrue(); + assertThat(emfi.getNativeEntityManagerFactory().getClass().getName()).endsWith("EntityManagerFactoryImpl"); } @Test 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 c8c9e5e2854..00963e101ef 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,7 +73,7 @@ public class HibernateEntityManagerFactoryIntegrationTests extends AbstractConta 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)).isNotNull(); assertThat(proxy.unwrap(org.hibernate.jpa.HibernateEntityManager.class)).isSameAs(em); assertThat(proxy.getDelegate()).isSameAs(em.getDelegate()); } 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 91f797d9396..3efd5d4a3b9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -278,7 +278,8 @@ public class PersistenceXmlParsingTests { assertThat(url).isNull(); url = PersistenceUnitReader.determinePersistenceUnitRootUrl(new ClassPathResource("/org/springframework/orm/jpa/META-INF/persistence.xml")); - assertThat(url.toString().endsWith("/org/springframework/orm/jpa")).as("the containing folder should have been returned").isTrue(); + assertThat(url.toString()).as("the containing folder should have been returned") + .endsWith("/org/springframework/orm/jpa"); } @Test 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 b4a5d4b9375..c5fa21337ec 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 @@ -287,7 +287,7 @@ class Jaxb2MarshallerTests extends AbstractMarshallerTests { BinaryObject object = new BinaryObject(bytes, dataHandler); StringWriter writer = new StringWriter(); marshaller.marshal(object, new StreamResult(writer), mimeContainer); - assertThat(writer.toString().length() > 0).as("No XML written").isTrue(); + assertThat(writer.toString()).as("No XML written").isNotEmpty(); verify(mimeContainer, times(3)).addAttachment(isA(String.class), isA(DataHandler.class)); } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java index d9241ac51a5..61286ce9c4a 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java @@ -66,7 +66,7 @@ public class Jaxb2UnmarshallerTests extends AbstractUnmarshallerTests 0).as("bytes property not set").isTrue(); + assertThat(object.getBytes()).as("bytes property not set").isNotEmpty(); assertThat(object.getSwaDataHandler()).as("datahandler property not set").isNotNull(); } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamMarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamMarshallerTests.java index ffeda8dfc8b..2c51fcbde59 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamMarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamMarshallerTests.java @@ -339,7 +339,7 @@ class XStreamMarshallerTests { marshaller.marshal(flight, new StreamResult(writer)); assertThat(writer.toString()).as("Invalid result").isEqualTo("{\"flight\":{\"flightNumber\":42}}"); Object o = marshaller.unmarshal(new StreamSource(new StringReader(writer.toString()))); - assertThat(o instanceof Flight).as("Unmarshalled object is not Flights").isTrue(); + assertThat(o).as("Unmarshalled object is not Flights").isInstanceOf(Flight.class); Flight unflight = (Flight) o; assertThat(unflight).as("Flight is null").isNotNull(); assertThat(unflight.getFlightNumber()).as("Number is invalid").isEqualTo(42L); @@ -377,7 +377,7 @@ class XStreamMarshallerTests { private static void assertXpathExists(String xPathExpression, String inXMLString){ Source source = Input.fromString(inXMLString).build(); Iterable nodes = new JAXPXPathEngine().selectNodes(xPathExpression, source); - assertThat(nodes).as("Expecting to find matches for Xpath " + xPathExpression).hasSizeGreaterThan(0); + assertThat(nodes).as("Expecting to find matches for Xpath " + xPathExpression).isNotEmpty(); } private static void assertXpathDoesNotExist(String xPathExpression, String inXMLString){ diff --git a/spring-r2dbc/src/test/java/org/springframework/r2dbc/connection/R2dbcTransactionManagerUnitTests.java b/spring-r2dbc/src/test/java/org/springframework/r2dbc/connection/R2dbcTransactionManagerUnitTests.java index 88cef8273a8..9e222589b1e 100644 --- a/spring-r2dbc/src/test/java/org/springframework/r2dbc/connection/R2dbcTransactionManagerUnitTests.java +++ b/spring-r2dbc/src/test/java/org/springframework/r2dbc/connection/R2dbcTransactionManagerUnitTests.java @@ -155,7 +155,7 @@ class R2dbcTransactionManagerUnitTests { io.r2dbc.spi.TransactionDefinition def = txCaptor.getValue(); assertThat(def.getAttribute(io.r2dbc.spi.TransactionDefinition.NAME)).isEqualTo("my-transaction"); assertThat(def.getAttribute(io.r2dbc.spi.TransactionDefinition.LOCK_WAIT_TIMEOUT)).isEqualTo(Duration.ofSeconds(10)); - assertThat(def.getAttribute(io.r2dbc.spi.TransactionDefinition.READ_ONLY)).isEqualTo(true); + assertThat(def.getAttribute(io.r2dbc.spi.TransactionDefinition.READ_ONLY)).isTrue(); assertThat(def.getAttribute(io.r2dbc.spi.TransactionDefinition.ISOLATION_LEVEL)).isEqualTo(IsolationLevel.SERIALIZABLE); } 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 f2713d26186..9aec6036fbd 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 @@ -382,7 +382,7 @@ class MockHttpServletRequestTests { void emptyAcceptLanguageHeader() { request.addHeader("Accept-Language", ""); assertThat(request.getLocale()).isEqualTo(Locale.ENGLISH); - assertThat(request.getHeader("Accept-Language")).isEqualTo(""); + assertThat(request.getHeader("Accept-Language")).isEmpty(); } @Test 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 f3f5ba9218b..3839714bdfb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,7 +107,7 @@ class MockHttpSessionTests { session.setAttribute(bindingListenerName, bindingListener); - assertThat(1).isEqualTo(bindingListener.getCounter()); + assertThat(bindingListener.getCounter()).isEqualTo(1); } @Test @@ -118,7 +118,7 @@ class MockHttpSessionTests { session.setAttribute(bindingListenerName, bindingListener); session.removeAttribute(bindingListenerName); - assertThat(0).isEqualTo(bindingListener.getCounter()); + assertThat(bindingListener.getCounter()).isEqualTo(0); } @Test @@ -129,7 +129,7 @@ class MockHttpSessionTests { session.setAttribute(bindingListenerName, bindingListener); session.setAttribute(bindingListenerName, bindingListener); - assertThat(1).isEqualTo(bindingListener.getCounter()); + assertThat(bindingListener.getCounter()).isEqualTo(1); } @Test @@ -141,8 +141,8 @@ class MockHttpSessionTests { session.setAttribute(bindingListenerName, bindingListener1); session.setAttribute(bindingListenerName, bindingListener2); - assertThat(0).isEqualTo(bindingListener1.getCounter()); - assertThat(1).isEqualTo(bindingListener2.getCounter()); + assertThat(bindingListener1.getCounter()).isEqualTo(0); + assertThat(bindingListener2.getCounter()).isEqualTo(1); } 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 2fc17da77d2..6905183737e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,7 +99,7 @@ class MockMultipartHttpServletRequestTests { assertThat(fileMap.get("file2")).isEqualTo(file2); assertThat(file1.getName()).isEqualTo("file1"); - assertThat(file1.getOriginalFilename()).isEqualTo(""); + assertThat(file1.getOriginalFilename()).isEmpty(); assertThat(file1.getContentType()).isNull(); assertThat(ObjectUtils.nullSafeEquals("myContent1".getBytes(), file1.getBytes())).isTrue(); assertThat(ObjectUtils.nullSafeEquals("myContent1".getBytes(), 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 b9f4ab394e1..85cb8186181 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 @@ -240,7 +240,7 @@ class MergedContextConfigurationTests { void equalsBasics() { MergedContextConfiguration mergedConfig = new MergedContextConfiguration(null, null, null, null, null); assertThat(mergedConfig).isEqualTo(mergedConfig); - assertThat(mergedConfig).isNotEqualTo(null); + assertThat(mergedConfig).isNotNull(); assertThat(mergedConfig).isNotEqualTo(1); } 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 fd3034b4524..b01253a0fd2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,8 +86,8 @@ class GroovySpringContextTests implements BeanNameAware, InitializingBean { @Test void verifyBeanNameSet() { - 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(); + assertThat(this.beanName).as("The bean name of this test instance should have been set to the fully qualified class name " + + "due to BeanNameAware semantics.").startsWith(getClass().getName()); } @Test 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 e38d302870e..b95a6c0329a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -244,10 +244,10 @@ class MergedSqlConfigTests { private void assertDefaults(MergedSqlConfig cfg) { assertSoftly(softly -> { softly.assertThat(cfg).isNotNull(); - softly.assertThat(cfg.getDataSource()).as("dataSource").isEqualTo(""); - softly.assertThat(cfg.getTransactionManager()).as("transactionManager").isEqualTo(""); + softly.assertThat(cfg.getDataSource()).as("dataSource").isEmpty(); + softly.assertThat(cfg.getTransactionManager()).as("transactionManager").isEmpty(); softly.assertThat(cfg.getTransactionMode()).as("transactionMode").isEqualTo(INFERRED); - softly.assertThat(cfg.getEncoding()).as("encoding").isEqualTo(""); + softly.assertThat(cfg.getEncoding()).as("encoding").isEmpty(); softly.assertThat(cfg.getSeparator()).as("separator").isEqualTo(DEFAULT_STATEMENT_SEPARATOR); softly.assertThat(cfg.getCommentPrefixes()).as("commentPrefixes").isEqualTo(DEFAULT_COMMENT_PREFIXES); softly.assertThat(cfg.getBlockCommentStartDelimiter()).as("blockCommentStartDelimiter").isEqualTo(DEFAULT_BLOCK_COMMENT_START_DELIMITER); @@ -270,8 +270,8 @@ class MergedSqlConfigTests { assertSoftly(softly -> { softly.assertThat(cfg).isNotNull(); - softly.assertThat(cfg.getDataSource()).as("dataSource").isEqualTo(""); - softly.assertThat(cfg.getTransactionManager()).as("transactionManager").isEqualTo(""); + softly.assertThat(cfg.getDataSource()).as("dataSource").isEmpty(); + softly.assertThat(cfg.getTransactionManager()).as("transactionManager").isEmpty(); softly.assertThat(cfg.getTransactionMode()).as("transactionMode").isEqualTo(INFERRED); softly.assertThat(cfg.getEncoding()).as("encoding").isEqualTo("global"); softly.assertThat(cfg.getSeparator()).as("separator").isEqualTo("\n"); @@ -289,8 +289,8 @@ class MergedSqlConfigTests { assertSoftly(softly -> { softly.assertThat(cfg).isNotNull(); - softly.assertThat(cfg.getDataSource()).as("dataSource").isEqualTo(""); - softly.assertThat(cfg.getTransactionManager()).as("transactionManager").isEqualTo(""); + softly.assertThat(cfg.getDataSource()).as("dataSource").isEmpty(); + softly.assertThat(cfg.getTransactionManager()).as("transactionManager").isEmpty(); softly.assertThat(cfg.getTransactionMode()).as("transactionMode").isEqualTo(INFERRED); softly.assertThat(cfg.getEncoding()).as("encoding").isEqualTo("local"); softly.assertThat(cfg.getSeparator()).as("separator").isEqualTo("@@"); diff --git a/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/RegisterExtensionSpringExtensionTests.java b/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/RegisterExtensionSpringExtensionTests.java index 8b34cea6df4..36fd05b7846 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/RegisterExtensionSpringExtensionTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit/jupiter/RegisterExtensionSpringExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -135,7 +135,7 @@ class RegisterExtensionSpringExtensionTests { @Test void autowiredParameterAsJavaUtilOptional(@Autowired Optional dog) { assertThat(dog).as("Optional dog should have been @Autowired by Spring").isNotNull(); - assertThat(dog.isPresent()).as("Value of Optional should be 'present'").isTrue(); + assertThat(dog).as("Value of Optional should be 'present'").isPresent(); assertThat(dog.get().getName()).as("Dog's name").isEqualTo("Dogbert"); } 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 1c95a609d2b..d3091d721ef 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -119,8 +119,8 @@ public class ConcreteTransactionalJUnit4SpringContextTests extends AbstractTrans @Transactional(propagation = Propagation.NOT_SUPPORTED) public void verifyBeanNameSet() { assertThatTransaction().isNotActive(); - 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(); + assertThat(this.beanName).as("The bean name of this test instance should have been set to the fully qualified class name " + + "due to BeanNameAware semantics.").startsWith(getClass().getName()); } @Test 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 710957ab233..ca6e43e9bc0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -163,7 +163,8 @@ public class SpringJUnit4ClassRunnerAppCtxTests implements ApplicationContextAwa @Test public void verifyBeanNameSet() { - assertThat(this.beanName.startsWith(getClass().getName())).as("The bean name of this test instance should have been set due to BeanNameAware semantics.").isTrue(); + assertThat(this.beanName).as("The bean name of this test instance should have been set due to BeanNameAware semantics.") + .startsWith(getClass().getName()); } @Test @@ -201,7 +202,7 @@ public class SpringJUnit4ClassRunnerAppCtxTests implements ApplicationContextAwa 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); + assertThat(this.spelFieldValue).isTrue(); } @Test @@ -209,7 +210,7 @@ public class SpringJUnit4ClassRunnerAppCtxTests implements ApplicationContextAwa 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); + assertThat(this.spelParameterValue).isTrue(); } @Test 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 2c79b734343..d8bd4015902 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,7 +93,7 @@ public class StandardJUnit4FeaturesTests { @Test public void verifyBeforeAnnotation() { - assertThat(this.beforeCounter).isEqualTo(1); + assertThat(this.beforeCounter).isOne(); } @Test @@ -101,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. - assertThat(StandardJUnit4FeaturesTests.staticBeforeCounter > 0).isTrue(); + assertThat(StandardJUnit4FeaturesTests.staticBeforeCounter).isGreaterThan(0); } } 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 fdaac2ebbaf..3e9b1775246 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,46 +91,46 @@ class AnnotationConfigContextLoaderTests { void detectDefaultConfigurationClassesForAnnotatedInnerClass() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(ContextConfigurationInnerClassTestCase.class); assertThat(configClasses).isNotNull(); - assertThat(configClasses.length).as("annotated static ContextConfiguration should be considered.").isEqualTo(1); + assertThat(configClasses).as("annotated static ContextConfiguration should be considered.").hasSize(1); configClasses = contextLoader.detectDefaultConfigurationClasses(AnnotatedFooConfigInnerClassTestCase.class); assertThat(configClasses).isNotNull(); - assertThat(configClasses.length).as("annotated static FooConfig should be considered.").isEqualTo(1); + assertThat(configClasses).as("annotated static FooConfig should be considered.").hasSize(1); } @Test void detectDefaultConfigurationClassesForMultipleAnnotatedInnerClasses() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(MultipleStaticConfigurationClassesTestCase.class); assertThat(configClasses).isNotNull(); - assertThat(configClasses.length).as("multiple annotated static classes should be considered.").isEqualTo(2); + assertThat(configClasses).as("multiple annotated static classes should be considered.").hasSize(2); } @Test void detectDefaultConfigurationClassesForNonAnnotatedInnerClass() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(PlainVanillaFooConfigInnerClassTestCase.class); assertThat(configClasses).isNotNull(); - assertThat(configClasses.length).as("non-annotated static FooConfig should NOT be considered.").isEqualTo(0); + assertThat(configClasses).as("non-annotated static FooConfig should NOT be considered.").isEmpty(); } @Test void detectDefaultConfigurationClassesForFinalAnnotatedInnerClass() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(FinalConfigInnerClassTestCase.class); assertThat(configClasses).isNotNull(); - assertThat(configClasses.length).as("final annotated static Config should NOT be considered.").isEqualTo(0); + assertThat(configClasses).as("final annotated static Config should NOT be considered.").isEmpty(); } @Test void detectDefaultConfigurationClassesForPrivateAnnotatedInnerClass() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(PrivateConfigInnerClassTestCase.class); assertThat(configClasses).isNotNull(); - assertThat(configClasses.length).as("private annotated inner classes should NOT be considered.").isEqualTo(0); + assertThat(configClasses).as("private annotated inner classes should NOT be considered.").isEmpty(); } @Test void detectDefaultConfigurationClassesForNonStaticAnnotatedInnerClass() { Class[] configClasses = contextLoader.detectDefaultConfigurationClasses(NonStaticConfigInnerClassesTestCase.class); assertThat(configClasses).isNotNull(); - assertThat(configClasses.length).as("non-static annotated inner classes should NOT be considered.").isEqualTo(0); + assertThat(configClasses).as("non-static annotated inner classes should NOT be considered.").isEmpty(); } } 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 fdea42df991..655b0571104 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -401,7 +401,7 @@ class ReflectionTestUtilsTests { void setFieldOnLegacyEntityWithSideEffectsInToString() { String testCollaborator = "test collaborator"; setField(entity, "collaborator", testCollaborator, Object.class); - assertThat(entity.toString().contains(testCollaborator)).isTrue(); + assertThat(entity.toString()).contains(testCollaborator); } @Test // SPR-14363 @@ -421,7 +421,7 @@ class ReflectionTestUtilsTests { void invokeSetterMethodOnLegacyEntityWithSideEffectsInToString() { String testCollaborator = "test collaborator"; invokeSetterMethod(entity, "collaborator", testCollaborator); - assertThat(entity.toString().contains(testCollaborator)).isTrue(); + assertThat(entity.toString()).contains(testCollaborator); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/web/client/response/DefaultResponseCreatorTests.java b/spring-test/src/test/java/org/springframework/test/web/client/response/DefaultResponseCreatorTests.java index 252cbcfa102..e9f02c588bb 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/response/DefaultResponseCreatorTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/response/DefaultResponseCreatorTests.java @@ -180,7 +180,6 @@ class DefaultResponseCreatorTests { HttpHeaders responseHeaders = createResponse(creator).getHeaders(); assertThat(responseHeaders.get(HttpHeaders.SET_COOKIE)) - .isNotNull() .containsExactly( firstCookie.toString(), secondCookie.toString(), @@ -210,7 +209,6 @@ class DefaultResponseCreatorTests { HttpHeaders responseHeaders = createResponse(creator).getHeaders(); assertThat(responseHeaders.get(HttpHeaders.SET_COOKIE)) - .isNotNull() .containsExactly( firstCookie.toString(), secondCookie.toString(), 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 5198c95025c..82c1d5a0dc4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -178,7 +178,7 @@ public class SampleTests { this.mockServer.verify(); } catch (AssertionError error) { - assertThat(error.getMessage().contains("2 unsatisfied expectation(s)")).as(error.getMessage()).isTrue(); + assertThat(error.getMessage()).as(error.getMessage()).contains("2 unsatisfied expectation(s)"); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/HtmlUnitRequestBuilderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/HtmlUnitRequestBuilderTests.java index 8005cba61e5..f49cde16a1f 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/HtmlUnitRequestBuilderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/HtmlUnitRequestBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -175,7 +175,7 @@ public class HtmlUnitRequestBuilderTests { webRequest.setUrl(new URL("https://example.com/")); String contextPath = requestBuilder.buildRequest(servletContext).getContextPath(); - assertThat(contextPath).isEqualTo(""); + assertThat(contextPath).isEmpty(); } @Test @@ -404,7 +404,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); assertThat(actualRequest.getParameterMap()).hasSize(1); - assertThat(actualRequest.getParameter("name")).isEqualTo(""); + assertThat(actualRequest.getParameter("name")).isEmpty(); } @Test @@ -414,7 +414,7 @@ public class HtmlUnitRequestBuilderTests { MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); assertThat(actualRequest.getParameterMap()).hasSize(1); - assertThat(actualRequest.getParameter("name")).isEqualTo(""); + assertThat(actualRequest.getParameter("name")).isEmpty(); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcConnectionBuilderSupportTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcConnectionBuilderSupportTests.java index de8eeb68dac..666456651c9 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcConnectionBuilderSupportTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcConnectionBuilderSupportTests.java @@ -115,7 +115,7 @@ public class MockMvcConnectionBuilderSupportTests { @Test public void defaultContextPathEmpty() throws Exception { WebConnection conn = this.builder.createConnection(this.client); - assertThat(getResponse(conn, "http://localhost/abc").getContentAsString()).isEqualTo(""); + assertThat(getResponse(conn, "http://localhost/abc").getContentAsString()).isEmpty(); } @Test 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 d817f25194f..9edb7bd6ee1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,7 +100,7 @@ class MockMvcHtmlUnitDriverBuilderTests { this.mockMvc = MockMvcBuilders.standaloneSetup(new CookieController()).build(); this.driver = MockMvcHtmlUnitDriverBuilder.mockMvcSetup(this.mockMvc).withDelegate(otherDriver).build(); - assertThat(get("http://localhost/")).isEqualTo(""); + assertThat(get("http://localhost/")).isEmpty(); Cookie cookie = new Cookie("localhost", "cookie", "cookieManagerShared"); otherDriver.getWebClient().getCookieManager().addCookie(cookie); assertThat(get("http://localhost/")).isEqualTo("cookieManagerShared"); 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 6f395342740..3ec8990732d 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 @@ -169,8 +169,8 @@ class PrintingResultHandlerTests { List cookieValues = this.response.getHeaders("Set-Cookie"); assertThat(cookieValues).hasSize(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(); + assertThat(cookieValues.get(1)).as("Actual: " + cookieValues.get(1)) + .startsWith("enigma=42; Path=/crumbs; Domain=.example.com; Max-Age=1234; Expires="); HttpHeaders headers = new HttpHeaders(); headers.set("header", "headerValue"); @@ -192,14 +192,14 @@ class PrintingResultHandlerTests { assertThat(cookies).hasSize(2); String cookie1 = cookies[0]; String cookie2 = cookies[1]; - 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', " + + assertThat(cookie1).startsWith("[" + Cookie.class.getSimpleName()); + assertThat(cookie1).contains("name = 'cookie', value = 'cookieValue'"); + assertThat(cookie1).endsWith("]"); + assertThat(cookie2).startsWith("[" + Cookie.class.getSimpleName()); + assertThat(cookie2).contains("name = 'enigma', value = '42', " + "comment = [null], domain = '.example.com', maxAge = 1234, " + - "path = '/crumbs', secure = true, version = 0, httpOnly = true")).isTrue(); - assertThat(cookie2.endsWith("]")).isTrue(); + "path = '/crumbs', secure = true, version = 0, httpOnly = true"); + assertThat(cookie2).endsWith("]"); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/resultmatches/HeaderAssertionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/resultmatches/HeaderAssertionTests.java index 3f489fe9faa..b623995b043 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/resultmatches/HeaderAssertionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/resultmatches/HeaderAssertionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -243,9 +243,9 @@ public class HeaderAssertionTests { } private void assertMessageContains(AssertionError error, String expected) { - assertThat(error.getMessage().contains(expected)) + assertThat(error.getMessage()) .as("Failure message should contain [" + expected + "], actual is [" + error.getMessage() + "]") - .isTrue(); + .contains(expected); } 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 81da63c113f..ec82a970b2b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -174,7 +174,7 @@ class AsyncTests { .andExpect(request().asyncStarted()) .andReturn(); - assertThat(writer.toString().contains("Async started = true")).isTrue(); + assertThat(writer.toString()).contains("Async started = true"); writer = new StringWriter(); this.mockMvc.perform(asyncDispatch(mvcResult)) @@ -183,7 +183,7 @@ class AsyncTests { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}")); - assertThat(writer.toString().contains("Async started = false")).isTrue(); + assertThat(writer.toString()).contains("Async started = false"); } 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 5a2c5f35a28..f42c3b777ef 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -213,7 +213,8 @@ public class HeaderAssertionTests { } private void assertMessageContains(AssertionError error, String expected) { - assertThat(error.getMessage().contains(expected)).as("Failure message should contain [" + expected + "], actual is [" + error.getMessage() + "]").isTrue(); + assertThat(error.getMessage()).as("Failure message should contain [" + expected + "], actual is [" + error.getMessage() + "]") + .contains(expected); } 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 05d5e9f2ffe..cdcd6e0182e 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java @@ -888,7 +888,8 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { @Override public void afterCompletion(int status) { - assertThat(status == TransactionSynchronization.STATUS_ROLLED_BACK).as("Correct completion status").isTrue(); + assertThat(status).as("Correct completion status") + .isEqualTo(TransactionSynchronization.STATUS_ROLLED_BACK); } }); } @@ -932,7 +933,8 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { @Override public void afterCompletion(int status) { - assertThat(status == TransactionSynchronization.STATUS_ROLLED_BACK).as("Correct completion status").isTrue(); + assertThat(status).as("Correct completion status") + .isEqualTo(TransactionSynchronization.STATUS_ROLLED_BACK); } }); } @@ -1031,7 +1033,8 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { @Override public void afterCompletion(int status) { - assertThat(status == TransactionSynchronization.STATUS_UNKNOWN).as("Correct completion status").isTrue(); + assertThat(status).as("Correct completion status") + .isEqualTo(TransactionSynchronization.STATUS_UNKNOWN); } }); } @@ -1056,7 +1059,8 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { @Override public void afterCompletion(int status) { - assertThat(status == TransactionSynchronization.STATUS_UNKNOWN).as("Correct completion status").isTrue(); + assertThat(status).as("Correct completion status") + .isEqualTo(TransactionSynchronization.STATUS_UNKNOWN); } }); status.setRollbackOnly(); @@ -1101,7 +1105,8 @@ public class JtaTransactionManagerTests { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { @Override public void afterCompletion(int status) { - assertThat(status == TransactionSynchronization.STATUS_UNKNOWN).as("Correct completion status").isTrue(); + assertThat(status).as("Correct completion status") + .isEqualTo(TransactionSynchronization.STATUS_UNKNOWN); } }); } 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 05f2425ff78..f0b2ac7cf58 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,18 +57,18 @@ public class TransactionSupportTests { PlatformTransactionManager tm = new TestTransactionManager(true, true); DefaultTransactionStatus status1 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS)); - assertThat(status1.getTransaction() != null).as("Must have transaction").isTrue(); - assertThat(!status1.isNewTransaction()).as("Must not be new transaction").isTrue(); + assertThat(status1.getTransaction()).as("Must have transaction").isNotNull(); + assertThat(status1.isNewTransaction()).as("Must not be new transaction").isFalse(); DefaultTransactionStatus status2 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED)); - assertThat(status2.getTransaction() != null).as("Must have transaction").isTrue(); - assertThat(!status2.isNewTransaction()).as("Must not be new transaction").isTrue(); + assertThat(status2.getTransaction()).as("Must have transaction").isNotNull(); + assertThat(status2.isNewTransaction()).as("Must not be new transaction").isFalse(); DefaultTransactionStatus status3 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY)); - assertThat(status3.getTransaction() != null).as("Must have transaction").isTrue(); - assertThat(!status3.isNewTransaction()).as("Must not be new transaction").isTrue(); + assertThat(status3.getTransaction()).as("Must have transaction").isNotNull(); + assertThat(status3.isNewTransaction()).as("Must not be new transaction").isFalse(); } @Test @@ -233,24 +233,28 @@ public class TransactionSupportTests { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionTemplate template = new TransactionTemplate(); template.setTransactionManager(tm); - assertThat(template.getTransactionManager() == tm).as("correct transaction manager set").isTrue(); + assertThat(template.getTransactionManager()).as("correct transaction manager set").isSameAs(tm); assertThatIllegalArgumentException().isThrownBy(() -> template.setPropagationBehaviorName("TIMEOUT_DEFAULT")); template.setPropagationBehaviorName("PROPAGATION_SUPPORTS"); - assertThat(template.getPropagationBehavior() == TransactionDefinition.PROPAGATION_SUPPORTS).as("Correct propagation behavior set").isTrue(); + assertThat(template.getPropagationBehavior()).as("Correct propagation behavior set") + .isEqualTo(TransactionDefinition.PROPAGATION_SUPPORTS); assertThatIllegalArgumentException().isThrownBy(() -> template.setPropagationBehavior(999)); template.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY); - assertThat(template.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY).as("Correct propagation behavior set").isTrue(); + assertThat(template.getPropagationBehavior()).as("Correct propagation behavior set") + .isEqualTo(TransactionDefinition.PROPAGATION_MANDATORY); assertThatIllegalArgumentException().isThrownBy(() -> template.setIsolationLevelName("TIMEOUT_DEFAULT")); template.setIsolationLevelName("ISOLATION_SERIALIZABLE"); - assertThat(template.getIsolationLevel() == TransactionDefinition.ISOLATION_SERIALIZABLE).as("Correct isolation level set").isTrue(); + assertThat(template.getIsolationLevel()).as("Correct isolation level set") + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); assertThatIllegalArgumentException().isThrownBy(() -> template.setIsolationLevel(999)); template.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); - assertThat(template.getIsolationLevel() == TransactionDefinition.ISOLATION_REPEATABLE_READ).as("Correct isolation level set").isTrue(); + assertThat(template.getIsolationLevel()).as("Correct isolation level set") + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); } @Test @@ -269,7 +273,7 @@ public class TransactionSupportTests { @AfterEach public void clear() { - assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue(); + assertThat(TransactionSynchronizationManager.getResourceMap()).isEmpty(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalApplicationListenerAdapterTests.java b/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalApplicationListenerAdapterTests.java index 9985f2b49fd..7565de5af8d 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalApplicationListenerAdapterTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/event/TransactionalApplicationListenerAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ public class TransactionalApplicationListenerAdapterTests { assertThat(callback.postEvent).isEqualTo(event); assertThat(callback.ex).isNull(); assertThat(adapter.getTransactionPhase()).isEqualTo(TransactionPhase.AFTER_COMMIT); - assertThat(adapter.getListenerId()).isEqualTo(""); + assertThat(adapter.getListenerId()).isEmpty(); } @Test @@ -66,7 +66,7 @@ public class TransactionalApplicationListenerAdapterTests { assertThat(callback.postEvent).isEqualTo(event); assertThat(callback.ex).isEqualTo(ex); assertThat(adapter.getTransactionPhase()).isEqualTo(TransactionPhase.BEFORE_COMMIT); - assertThat(adapter.getListenerId()).isEqualTo(""); + assertThat(adapter.getListenerId()).isEmpty(); } @Test 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 f0779c625af..5bd6c0a872b 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 @@ -374,7 +374,7 @@ public abstract class AbstractTransactionAspectTests { TransactionAttribute txatt = new DefaultTransactionAttribute() { @Override public boolean rollbackOn(Throwable t) { - assertThat(t == ex).isTrue(); + assertThat(t).isSameAs(ex); return shouldRollback; } }; @@ -454,7 +454,7 @@ public abstract class AbstractTransactionAspectTests { ITestBean itb = (ITestBean) advised(tb, ptm, tas); // verification!? - assertThat(name.equals(itb.getName())).isTrue(); + assertThat(itb.getName()).isEqualTo(name); verify(ptm).commit(status); } @@ -490,7 +490,7 @@ public abstract class AbstractTransactionAspectTests { fail("Shouldn't have invoked method"); } catch (CannotCreateTransactionException thrown) { - assertThat(thrown == ex).isTrue(); + assertThat(thrown).isSameAs(ex); } } @@ -525,11 +525,11 @@ public abstract class AbstractTransactionAspectTests { fail("Shouldn't have succeeded"); } catch (UnexpectedRollbackException thrown) { - assertThat(thrown == ex).isTrue(); + assertThat(thrown).isSameAs(ex); } // Should have invoked target and changed name - assertThat(itb.getName() == name).isTrue(); + assertThat(itb.getName()).isSameAs(name); } 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 291849f2af7..a1d3b306a24 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 @@ -145,7 +145,7 @@ public class BeanFactoryTransactionTests { PlatformTransactionManager ptm = mock(); PlatformTransactionManagerFacade.delegate = ptm; - assertThat(testBean.getAge() == 666).as("Age should not be " + testBean.getAge()).isTrue(); + assertThat(testBean.getAge()).as("Age should not be " + testBean.getAge()).isEqualTo(666); // Expect no methods verifyNoInteractions(ptm); @@ -168,7 +168,7 @@ public class BeanFactoryTransactionTests { } @Override public void commit(TransactionStatus status) throws TransactionException { - assertThat(status == ts).isTrue(); + assertThat(status).isSameAs(ts); } @Override public void rollback(TransactionStatus status) throws TransactionException { @@ -180,7 +180,7 @@ public class BeanFactoryTransactionTests { // TODO same as old age to avoid ordering effect for now int age = 666; testBean.setAge(age); - assertThat(testBean.getAge() == age).isTrue(); + assertThat(testBean.getAge()).isEqualTo(age); } @Test 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 d61dfda71be..b57663cdc25 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,12 +42,12 @@ public class TransactionAttributeSourceTests { MatchAlwaysTransactionAttributeSource tas = new MatchAlwaysTransactionAttributeSource(); TransactionAttribute ta = tas.getTransactionAttribute(Object.class.getMethod("hashCode"), null); assertThat(ta).isNotNull(); - assertThat(TransactionDefinition.PROPAGATION_REQUIRED == ta.getPropagationBehavior()).isTrue(); + assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); tas.setTransactionAttribute(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_SUPPORTS)); ta = tas.getTransactionAttribute(IOException.class.getMethod("getMessage"), IOException.class); assertThat(ta).isNotNull(); - assertThat(TransactionDefinition.PROPAGATION_SUPPORTS == ta.getPropagationBehavior()).isTrue(); + assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_SUPPORTS); } @Test 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 a5511b22eea..0f0ae4e5d94 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 @@ -52,7 +52,7 @@ public class JtaTransactionManagerSerializationTests { // should do client-side lookup assertThat(serializedJtatm.logger).as("Logger must survive serialization").isNotNull(); assertThat(serializedJtatm - .getUserTransaction() == ut2).as("UserTransaction looked up on client").isTrue(); + .getUserTransaction()).as("UserTransaction looked up on client").isSameAs(ut2); assertThat(serializedJtatm .getTransactionManager()).as("TransactionManager didn't survive").isNull(); assertThat(serializedJtatm.isRollbackOnCommitFailure()).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 6f24ea477c6..5d2765692fb 100644 --- a/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java +++ b/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java @@ -554,7 +554,7 @@ public class HttpHeadersTests { headers.setBasicAuth(username, password); String authorization = headers.getFirst(HttpHeaders.AUTHORIZATION); assertThat(authorization).isNotNull(); - assertThat(authorization.startsWith("Basic ")).isTrue(); + assertThat(authorization).startsWith("Basic "); byte[] result = Base64.getDecoder().decode(authorization.substring(6).getBytes(StandardCharsets.ISO_8859_1)); assertThat(new String(result, StandardCharsets.ISO_8859_1)).isEqualTo("foo:bar"); } 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 58dcb5d1657..929d60496b4 100644 --- a/spring-web/src/test/java/org/springframework/http/MediaTypeFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/MediaTypeFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,16 +29,16 @@ public class MediaTypeFactoryTests { @Test public void getMediaType() { - 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(); + assertThat(MediaTypeFactory.getMediaType("file.xml")).contains(MediaType.APPLICATION_XML); + assertThat(MediaTypeFactory.getMediaType("file.js")).contains(MediaType.parseMediaType("application/javascript")); + assertThat(MediaTypeFactory.getMediaType("file.css")).contains(MediaType.parseMediaType("text/css")); + assertThat(MediaTypeFactory.getMediaType("file.foobar")).isNotPresent(); } @Test public void nullParameter() { - assertThat(MediaTypeFactory.getMediaType((String) null).isPresent()).isFalse(); - assertThat(MediaTypeFactory.getMediaType((Resource) null).isPresent()).isFalse(); + assertThat(MediaTypeFactory.getMediaType((String) null)).isNotPresent(); + assertThat(MediaTypeFactory.getMediaType((Resource) null)).isNotPresent(); 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 a3661ff719c..c2b5ba20472 100644 --- a/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java +++ b/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -156,18 +156,18 @@ public class MediaTypeTests { String s = "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"; List mediaTypes = MediaType.parseMediaTypes(s); assertThat(mediaTypes).as("No media types returned").isNotNull(); - assertThat(mediaTypes.size()).as("Invalid amount of media types").isEqualTo(4); + assertThat(mediaTypes).as("Invalid amount of media types").hasSize(4); mediaTypes = MediaType.parseMediaTypes(""); assertThat(mediaTypes).as("No media types returned").isNotNull(); - assertThat(mediaTypes.size()).as("Invalid amount of media types").isEqualTo(0); + assertThat(mediaTypes).as("Invalid amount of media types").isEmpty(); } @Test // gh-23241 public void parseMediaTypesWithTrailingComma() { List mediaTypes = MediaType.parseMediaTypes("text/plain, text/html, "); assertThat(mediaTypes).as("No media types returned").isNotNull(); - assertThat(mediaTypes.size()).as("Incorrect number of media types").isEqualTo(2); + assertThat(mediaTypes).as("Incorrect number of media types").hasSize(2); } @Test @@ -183,7 +183,7 @@ public class MediaTypeTests { assertThat(audio.compareTo(audio)).as("Invalid comparison result").isEqualTo(0); assertThat(audioBasicLevel.compareTo(audioBasicLevel)).as("Invalid comparison result").isEqualTo(0); - assertThat(audioBasicLevel.compareTo(audio) > 0).as("Invalid comparison result").isTrue(); + assertThat(audioBasicLevel.compareTo(audio)).as("Invalid comparison result").isGreaterThan(0); List expected = new ArrayList<>(); expected.add(audio); @@ -235,8 +235,8 @@ public class MediaTypeTests { m1 = new MediaType("audio", "basic", Collections.singletonMap("foo", "bar")); m2 = new MediaType("audio", "basic", Collections.singletonMap("foo", "Bar")); - assertThat(m1.compareTo(m2) != 0).as("Invalid comparison result").isTrue(); - assertThat(m2.compareTo(m1) != 0).as("Invalid comparison result").isTrue(); + assertThat(m1.compareTo(m2)).as("Invalid comparison result").isNotEqualTo(0); + assertThat(m2.compareTo(m1)).as("Invalid comparison result").isNotEqualTo(0); } @@ -302,28 +302,29 @@ public class MediaTypeTests { assertThat(comp.compare(audioBasicLevel, audioBasicLevel)).as("Invalid comparison result").isEqualTo(0); // specific to unspecific - 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(); + assertThat(comp.compare(audioBasic, audio)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(audioBasic, all)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(audio, all)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(MediaType.APPLICATION_XHTML_XML, allXml)).as("Invalid comparison result").isLessThan(0); // unspecific to specific - 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(); + assertThat(comp.compare(audio, audioBasic)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(allXml, MediaType.APPLICATION_XHTML_XML)).as("Invalid comparison result") + .isGreaterThan(0); + assertThat(comp.compare(all, audioBasic)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(all, audio)).as("Invalid comparison result").isGreaterThan(0); // qualifiers - 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(); + assertThat(comp.compare(audio, audio07)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(audio07, audio)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(audio07, audio03)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(audio03, audio07)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(audio03, all)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(all, audio03)).as("Invalid comparison result").isGreaterThan(0); // other parameters - assertThat(comp.compare(audioBasic, audioBasicLevel) > 0).as("Invalid comparison result").isTrue(); - assertThat(comp.compare(audioBasicLevel, audioBasic) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audioBasic, audioBasicLevel)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(audioBasicLevel, audioBasic)).as("Invalid comparison result").isLessThan(0); // different types assertThat(comp.compare(audioBasic, textHtml)).as("Invalid comparison result").isEqualTo(0); @@ -409,28 +410,29 @@ public class MediaTypeTests { assertThat(comp.compare(audioBasicLevel, audioBasicLevel)).as("Invalid comparison result").isEqualTo(0); // specific to unspecific - 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(); + assertThat(comp.compare(audioBasic, audio)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(audioBasic, all)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(audio, all)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(MediaType.APPLICATION_XHTML_XML, allXml)).as("Invalid comparison result").isLessThan(0); // unspecific to specific - 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(); + assertThat(comp.compare(audio, audioBasic)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(all, audioBasic)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(all, audio)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(allXml, MediaType.APPLICATION_XHTML_XML)).as("Invalid comparison result") + .isGreaterThan(0); // qualifiers - 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(); + assertThat(comp.compare(audio, audio07)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(audio07, audio)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(audio07, audio03)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(audio03, audio07)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(audio03, all)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(all, audio03)).as("Invalid comparison result").isLessThan(0); // other parameters - assertThat(comp.compare(audioBasic, audioBasicLevel) > 0).as("Invalid comparison result").isTrue(); - assertThat(comp.compare(audioBasicLevel, audioBasic) < 0).as("Invalid comparison result").isTrue(); + assertThat(comp.compare(audioBasic, audioBasicLevel)).as("Invalid comparison result").isGreaterThan(0); + assertThat(comp.compare(audioBasicLevel, audioBasic)).as("Invalid comparison result").isLessThan(0); // different types assertThat(comp.compare(audioBasic, textHtml)).as("Invalid comparison result").isEqualTo(0); diff --git a/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTests.java index d3024af1a43..b48ca6aa725 100644 --- a/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,8 +98,9 @@ abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebServerTest try (ClientHttpResponse response = request.execute()) { 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)); + assertThat(response.getHeaders()).as("Header not found").containsKey(headerName); + assertThat(response.getHeaders()).as("Header value not found") + .containsEntry(headerName, Arrays.asList(headerValue1, headerValue2)); byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); assertThat(Arrays.equals(body, result)).as("Invalid body").isTrue(); } 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 5555d04e6b8..ac83d40f882 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,10 +79,10 @@ public class FormHttpMessageReaderTests extends AbstractLeakCheckingTests { MockServerHttpRequest request = request(body); MultiValueMap result = this.reader.readMono(null, request, null).block(); - assertThat(result.size()).as("Invalid result").isEqualTo(3); + assertThat(result).as("Invalid result").hasSize(3); assertThat(result.getFirst("name 1")).as("Invalid result").isEqualTo("value 1"); List values = result.get("name 2"); - assertThat(values.size()).as("Invalid result").isEqualTo(2); + assertThat(values).as("Invalid result").hasSize(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(); @@ -94,10 +94,10 @@ public class FormHttpMessageReaderTests extends AbstractLeakCheckingTests { MockServerHttpRequest request = request(body); MultiValueMap result = this.reader.read(null, request, null).single().block(); - assertThat(result.size()).as("Invalid result").isEqualTo(3); + assertThat(result).as("Invalid result").hasSize(3); assertThat(result.getFirst("name 1")).as("Invalid result").isEqualTo("value 1"); List values = result.get("name 2"); - assertThat(values.size()).as("Invalid result").isEqualTo(2); + assertThat(values).as("Invalid result").hasSize(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(); 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 eb8da1be435..ec9fb809fd5 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 @@ -130,30 +130,30 @@ public class MultipartHttpMessageWriterTests extends AbstractLeakCheckingTests { assertThat(requestParts).hasSize(7); Part part = requestParts.getFirst("name 1"); - assertThat(part instanceof FormFieldPart).isTrue(); + assertThat(part).isInstanceOf(FormFieldPart.class); assertThat(part.name()).isEqualTo("name 1"); assertThat(((FormFieldPart) part).value()).isEqualTo("value 1"); List parts2 = requestParts.get("name 2"); assertThat(parts2).hasSize(2); part = parts2.get(0); - assertThat(part instanceof FormFieldPart).isTrue(); + assertThat(part).isInstanceOf(FormFieldPart.class); assertThat(part.name()).isEqualTo("name 2"); assertThat(((FormFieldPart) part).value()).isEqualTo("value 2+1"); part = parts2.get(1); - assertThat(part instanceof FormFieldPart).isTrue(); + assertThat(part).isInstanceOf(FormFieldPart.class); assertThat(part.name()).isEqualTo("name 2"); assertThat(((FormFieldPart) part).value()).isEqualTo("value 2+2"); part = requestParts.getFirst("logo"); - assertThat(part instanceof FilePart).isTrue(); + assertThat(part).isInstanceOf(FilePart.class); 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"); - assertThat(part instanceof FilePart).isTrue(); + assertThat(part).isInstanceOf(FilePart.class); assertThat(part.name()).isEqualTo("utf8"); assertThat(((FilePart) part).filename()).isEqualTo("Hall\u00F6le.jpg"); assertThat(part.headers().getContentType()).isEqualTo(MediaType.IMAGE_JPEG); @@ -233,7 +233,7 @@ public class MultipartHttpMessageWriterTests extends AbstractLeakCheckingTests { Part part = requestParts.getFirst("logo"); assertThat(part.name()).isEqualTo("logo"); - assertThat(part instanceof FilePart).isTrue(); + assertThat(part).isInstanceOf(FilePart.class); assertThat(((FilePart) part).filename()).isEqualTo("logo.jpg"); assertThat(part.headers().getContentType()).isEqualTo(MediaType.IMAGE_JPEG); assertThat(part.headers().getContentLength()).isEqualTo(logo.getFile().length()); @@ -284,12 +284,12 @@ public class MultipartHttpMessageWriterTests extends AbstractLeakCheckingTests { assertThat(requestParts).hasSize(2); Part part = requestParts.getFirst("resource"); - assertThat(part instanceof FilePart).isTrue(); + assertThat(part).isInstanceOf(FilePart.class); assertThat(((FilePart) part).filename()).isEqualTo("spring.jpg"); assertThat(part.headers().getContentLength()).isEqualTo(logo.getFile().length()); part = requestParts.getFirst("buffers"); - assertThat(part instanceof FilePart).isTrue(); + assertThat(part).isInstanceOf(FilePart.class); assertThat(((FilePart) part).filename()).isEqualTo("buffers.jpg"); assertThat(part.headers().getContentLength()).isEqualTo(logo.getFile().length()); } 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 f5ed0c539b7..582027c250d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,7 +74,7 @@ class BufferedImageHttpMessageConverterTests { MediaType contentType = new MediaType("image", "png"); converter.write(body, contentType, outputMessage); assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content type").isEqualTo(contentType); - assertThat(outputMessage.getBodyAsBytes().length > 0).as("Invalid size").isTrue(); + assertThat(outputMessage.getBodyAsBytes()).as("Invalid size").isNotEmpty(); BufferedImage result = ImageIO.read(new ByteArrayInputStream(outputMessage.getBodyAsBytes())); assertThat(result.getHeight()).as("Invalid height").isEqualTo(500); assertThat(result.getWidth()).as("Invalid width").isEqualTo(750); @@ -89,7 +89,7 @@ class BufferedImageHttpMessageConverterTests { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(body, new MediaType("*", "*"), outputMessage); assertThat(outputMessage.getHeaders().getContentType()).as("Invalid content type").isEqualTo(contentType); - assertThat(outputMessage.getBodyAsBytes().length > 0).as("Invalid size").isTrue(); + assertThat(outputMessage.getBodyAsBytes()).as("Invalid size").isNotEmpty(); BufferedImage result = ImageIO.read(new ByteArrayInputStream(outputMessage.getBodyAsBytes())); 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/FormHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java index 832b9c3ef98..30cd54b624c 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 @@ -124,10 +124,10 @@ public class FormHttpMessageConverterTests { new MediaType("application", "x-www-form-urlencoded", StandardCharsets.ISO_8859_1)); MultiValueMap result = this.converter.read(null, inputMessage); - assertThat(result.size()).as("Invalid result").isEqualTo(3); + assertThat(result).as("Invalid result").hasSize(3); assertThat(result.getFirst("name 1")).as("Invalid result").isEqualTo("value 1"); List values = result.get("name 2"); - assertThat(values.size()).as("Invalid result").isEqualTo(2); + assertThat(values).as("Invalid result").hasSize(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(); 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 51ac8b6fcd5..6e6780fba73 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -150,7 +150,7 @@ public class ObjectToStringHttpMessageConverterTests { this.converter.write((byte) -8, null, this.response); assertThat(this.servletResponse.getCharacterEncoding()).isEqualTo("ISO-8859-1"); - assertThat(this.servletResponse.getContentType().startsWith(MediaType.TEXT_PLAIN_VALUE)).isTrue(); + assertThat(this.servletResponse.getContentType()).startsWith(MediaType.TEXT_PLAIN_VALUE); assertThat(this.servletResponse.getContentLength()).isEqualTo(2); assertThat(this.servletResponse.getContentAsByteArray()).isEqualTo(new byte[] { '-', '8' }); } @@ -161,7 +161,7 @@ public class ObjectToStringHttpMessageConverterTests { this.converter.write(958, contentType, this.response); assertThat(this.servletResponse.getCharacterEncoding()).isEqualTo("UTF-16"); - assertThat(this.servletResponse.getContentType().startsWith(MediaType.TEXT_PLAIN_VALUE)).isTrue(); + assertThat(this.servletResponse.getContentType()).startsWith(MediaType.TEXT_PLAIN_VALUE); assertThat(this.servletResponse.getContentLength()).isEqualTo(8); // First two bytes: byte order mark assertThat(this.servletResponse.getContentAsByteArray()).isEqualTo(new byte[] { -2, -1, 0, '9', 0, '5', 0, '8' }); 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 89bc00bf8ea..79f1b44a0ff 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 @@ -63,7 +63,6 @@ class GsonFactoryBeanTests { Gson gson = this.factory.getObject(); StringBean bean = new StringBean(); bean.setName("Jason"); - assertThat(gson.toJson(bean)).contains(" \"name\": \"Jason\""); } @@ -129,7 +128,6 @@ class GsonFactoryBeanTests { cal.set(Calendar.DATE, 1); Date date = cal.getTime(); bean.setDate(date); - assertThat(gson.toJson(bean)) .startsWith("{\"date\":\"Jan 1, 2014") .endsWith("12:00:00 AM\"}"); 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 6ece484d167..33c095af69c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -125,12 +125,12 @@ public class GsonHttpMessageConverterTests { this.converter.write(body, null, outputMessage); Charset utf8 = StandardCharsets.UTF_8; String result = outputMessage.getBodyAsString(utf8); - 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(result).contains("\"string\":\"Foo\""); + assertThat(result).contains("\"number\":42"); + assertThat(result).contains("fraction\":42.0"); + assertThat(result).contains("\"array\":[\"Foo\",\"Bar\"]"); + assertThat(result).contains("\"bool\":true"); + assertThat(result).contains("\"bytes\":[1,2]"); assertThat(outputMessage.getHeaders().getContentType()) .as("Invalid content-type").isEqualTo(new MediaType("application", "json", utf8)); } @@ -148,12 +148,12 @@ public class GsonHttpMessageConverterTests { this.converter.write(body, MyBase.class, null, outputMessage); Charset utf8 = StandardCharsets.UTF_8; String result = outputMessage.getBodyAsString(utf8); - 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(result).contains("\"string\":\"Foo\""); + assertThat(result).contains("\"number\":42"); + assertThat(result).contains("fraction\":42.0"); + assertThat(result).contains("\"array\":[\"Foo\",\"Bar\"]"); + assertThat(result).contains("\"bool\":true"); + assertThat(result).contains("\"bytes\":[1,2]"); assertThat(outputMessage.getHeaders().getContentType()) .as("Invalid content-type").isEqualTo(new MediaType("application", "json", utf8)); } 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 537ca04d1c0..c11b98ec95f 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 @@ -280,7 +280,7 @@ class Jackson2ObjectMapperBuilderTests { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build(); Path file = Paths.get("foo"); - assertThat(new String(objectMapper.writeValueAsBytes(file), "UTF-8").endsWith("foo\"")).isTrue(); + assertThat(new String(objectMapper.writeValueAsBytes(file), "UTF-8")).endsWith("foo\""); Optional optional = Optional.of("test"); assertThat(new String(objectMapper.writeValueAsBytes(optional), "UTF-8")).isEqualTo("\"test\""); 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 a6727fa3914..871338a9128 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -125,12 +125,12 @@ public class JsonbHttpMessageConverterTests { this.converter.write(body, null, outputMessage); Charset utf8 = StandardCharsets.UTF_8; String result = outputMessage.getBodyAsString(utf8); - 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(result).contains("\"string\":\"Foo\""); + assertThat(result).contains("\"number\":42"); + assertThat(result).contains("fraction\":42.0"); + assertThat(result).contains("\"array\":[\"Foo\",\"Bar\"]"); + assertThat(result).contains("\"bool\":true"); + assertThat(result).contains("\"bytes\":[1,2]"); assertThat(outputMessage.getHeaders().getContentType()) .as("Invalid content-type").isEqualTo(new MediaType("application", "json", utf8)); } @@ -148,12 +148,12 @@ public class JsonbHttpMessageConverterTests { this.converter.write(body, MyBase.class, null, outputMessage); Charset utf8 = StandardCharsets.UTF_8; String result = outputMessage.getBodyAsString(utf8); - 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(result).contains("\"string\":\"Foo\""); + assertThat(result).contains("\"number\":42"); + assertThat(result).contains("fraction\":42.0"); + assertThat(result).contains("\"array\":[\"Foo\",\"Bar\"]"); + assertThat(result).contains("\"bool\":true"); + assertThat(result).contains("\"bytes\":[1,2]"); assertThat(outputMessage.getHeaders().getContentType()) .as("Invalid content-type").isEqualTo(new MediaType("application", "json", utf8)); } 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 24f933208dc..12428387cae 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 @@ -163,15 +163,15 @@ public class MappingJackson2HttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8)); inputMessage.getHeaders().setContentType(new MediaType("application", "json")); HashMap result = (HashMap) converter.read(HashMap.class, inputMessage); - assertThat(result.get("string")).isEqualTo("Foo"); - assertThat(result.get("number")).isEqualTo(42); + assertThat(result).containsEntry("string", "Foo"); + assertThat(result).containsEntry("number", 42); assertThat((Double) result.get("fraction")).isCloseTo(42D, within(0D)); List array = new ArrayList<>(); array.add("Foo"); array.add("Bar"); - assertThat(result.get("array")).isEqualTo(array); - assertThat(result.get("bool")).isEqualTo(Boolean.TRUE); - assertThat(result.get("bytes")).isEqualTo("AQI="); + assertThat(result).containsEntry("array", array); + assertThat(result).containsEntry("bool", Boolean.TRUE); + assertThat(result).containsEntry("bytes", "AQI="); } @Test @@ -186,12 +186,12 @@ public class MappingJackson2HttpMessageConverterTests { body.setBytes(new byte[] {0x1, 0x2}); converter.write(body, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - 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(result).contains("\"string\":\"Foo\""); + assertThat(result).contains("\"number\":42"); + assertThat(result).contains("fraction\":42.0"); + assertThat(result).contains("\"array\":[\"Foo\",\"Bar\"]"); + assertThat(result).contains("\"bool\":true"); + assertThat(result).contains("\"bytes\":\"AQI=\""); assertThat(outputMessage.getHeaders().getContentType()) .as("Invalid content-type").isEqualTo(MediaType.APPLICATION_JSON); } @@ -208,12 +208,12 @@ public class MappingJackson2HttpMessageConverterTests { body.setBytes(new byte[] {0x1, 0x2}); converter.write(body, MyBase.class, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - 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(result).contains("\"string\":\"Foo\""); + assertThat(result).contains("\"number\":42"); + assertThat(result).contains("fraction\":42.0"); + assertThat(result).contains("\"array\":[\"Foo\",\"Bar\"]"); + assertThat(result).contains("\"bool\":true"); + assertThat(result).contains("\"bytes\":\"AQI=\""); assertThat(outputMessage.getHeaders().getContentType()) .as("Invalid content-type").isEqualTo(MediaType.APPLICATION_JSON); } @@ -470,8 +470,8 @@ public class MappingJackson2HttpMessageConverterTests { this.converter.writeInternal(bean, MyInterface.class, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertThat(result.contains("\"string\":\"Foo\"")).isTrue(); - assertThat(result.contains("\"number\":42")).isTrue(); + assertThat(result).contains("\"string\":\"Foo\""); + assertThat(result).contains("\"number\":42"); } @Test // SPR-13318 @@ -492,10 +492,10 @@ public class MappingJackson2HttpMessageConverterTests { this.converter.writeInternal(beans, typeReference.getType(), outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertThat(result.contains("\"string\":\"Foo\"")).isTrue(); - assertThat(result.contains("\"number\":42")).isTrue(); - assertThat(result.contains("\"string\":\"Bar\"")).isTrue(); - assertThat(result.contains("\"number\":123")).isTrue(); + assertThat(result).contains("\"string\":\"Foo\""); + assertThat(result).contains("\"number\":42"); + assertThat(result).contains("\"string\":\"Bar\""); + assertThat(result).contains("\"number\":123"); } @Test @@ -575,9 +575,9 @@ public class MappingJackson2HttpMessageConverterTests { converter.write(body, null, outputMessage1); customizedConverter.write(body, null, outputMessage2); String result1 = outputMessage1.getBodyAsString(StandardCharsets.UTF_8); - assertThat(result1.contains("\"property\":\"VAL2\"")).isTrue(); + assertThat(result1).contains("\"property\":\"VAL2\""); String result2 = outputMessage2.getBodyAsString(StandardCharsets.UTF_8); - assertThat(result2.contains("\"property\":\"Value2\"")).isTrue(); + assertThat(result2).contains("\"property\":\"Value2\""); } 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 0f7b17b348c..fc6e7e3a889 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 @@ -95,7 +95,7 @@ class ProtobufHttpMessageConverterTests { MediaType contentType = ProtobufHttpMessageConverter.PROTOBUF; this.converter.write(this.testMsg, contentType, outputMessage); assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(contentType); - assertThat(outputMessage.getBodyAsBytes().length > 0).isTrue(); + assertThat(outputMessage.getBodyAsBytes().length).isGreaterThan(0); Message result = Msg.parseFrom(outputMessage.getBodyAsBytes()); assertThat(result).isEqualTo(this.testMsg); @@ -119,7 +119,7 @@ class ProtobufHttpMessageConverterTests { assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(contentType); final String body = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertThat(body.isEmpty()).as("body is empty").isFalse(); + assertThat(body).as("body is empty").isNotEmpty(); Msg.Builder builder = Msg.newBuilder(); JsonFormat.parser().merge(body, builder); @@ -144,7 +144,7 @@ class ProtobufHttpMessageConverterTests { assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(contentType); String body = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - assertThat(body.isEmpty()).as("body is empty").isFalse(); + assertThat(body).as("body is empty").isNotEmpty(); Msg.Builder builder = Msg.newBuilder(); JsonFormat.parser().merge(body, builder); 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 ad3971548c2..9a651cad5e6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,7 +83,7 @@ public class ProtobufJsonFormatHttpMessageConverterTests { MediaType contentType = ProtobufHttpMessageConverter.PROTOBUF; this.converter.write(this.testMsg, contentType, outputMessage); assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(contentType); - assertThat(outputMessage.getBodyAsBytes().length > 0).isTrue(); + assertThat(outputMessage.getBodyAsBytes().length).isGreaterThan(0); Message result = Msg.parseFrom(outputMessage.getBodyAsBytes()); assertThat(result).isEqualTo(this.testMsg); 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 9588824ec8d..1dfb937c371 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 @@ -84,7 +84,7 @@ public class Jaxb2CollectionHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes(StandardCharsets.UTF_8)); List result = (List) converter.read(rootElementListType, null, inputMessage); - assertThat(result.size()).as("Invalid result").isEqualTo(2); + assertThat(result).as("Invalid result").hasSize(2); assertThat(result.get(0).type.s).as("Invalid result").isEqualTo("1"); assertThat(result.get(1).type.s).as("Invalid result").isEqualTo("2"); } @@ -96,7 +96,7 @@ public class Jaxb2CollectionHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes(StandardCharsets.UTF_8)); Set result = (Set) converter.read(rootElementSetType, null, inputMessage); - assertThat(result.size()).as("Invalid result").isEqualTo(2); + assertThat(result).as("Invalid result").hasSize(2); assertThat(result.contains(new RootElement("1"))).as("Invalid result").isTrue(); assertThat(result.contains(new RootElement("2"))).as("Invalid result").isTrue(); } @@ -108,7 +108,7 @@ public class Jaxb2CollectionHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes(StandardCharsets.UTF_8)); List result = (List) converter.read(typeListType, null, inputMessage); - assertThat(result.size()).as("Invalid result").isEqualTo(2); + assertThat(result).as("Invalid result").hasSize(2); assertThat(result.get(0).s).as("Invalid result").isEqualTo("1"); assertThat(result.get(1).s).as("Invalid result").isEqualTo("2"); } @@ -120,7 +120,7 @@ public class Jaxb2CollectionHttpMessageConverterTests { MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes(StandardCharsets.UTF_8)); Set result = (Set) converter.read(typeSetType, null, inputMessage); - assertThat(result.size()).as("Invalid result").isEqualTo(2); + assertThat(result).as("Invalid result").hasSize(2); assertThat(result.contains(new TestType("1"))).as("Invalid result").isTrue(); assertThat(result.contains(new TestType("2"))).as("Invalid result").isTrue(); } @@ -147,7 +147,7 @@ public class Jaxb2CollectionHttpMessageConverterTests { try { Collection result = converter.read(rootElementListType, null, inputMessage); assertThat(result).hasSize(1); - assertThat(result.iterator().next().external).isEqualTo(""); + assertThat(result.iterator().next().external).isEmpty(); } catch (HttpMessageNotReadableException ex) { // Some parsers raise an exception 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 8ed077de813..e3e58af5b25 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 @@ -132,7 +132,7 @@ public class Jaxb2RootElementHttpMessageConverterTests { converter.setSupportDtd(true); RootElement rootElement = (RootElement) converter.read(RootElement.class, inputMessage); - assertThat(rootElement.external).isEqualTo(""); + assertThat(rootElement.external).isEmpty(); } @Test 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 caff39d4174..d8412635ef9 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 @@ -97,12 +97,12 @@ public class MappingJackson2XmlHttpMessageConverterTests { body.setBytes(new byte[]{0x1, 0x2}); converter.write(body, null, outputMessage); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8); - 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(result).contains("Foo"); + assertThat(result).contains("42"); + assertThat(result).contains("42.0"); + assertThat(result).contains("FooBar"); + assertThat(result).contains("true"); + assertThat(result).contains("AQI="); assertThat(outputMessage.getHeaders().getContentType()) .as("Invalid content-type").isEqualTo(new MediaType("application", "xml", StandardCharsets.UTF_8)); } 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 71a4bacd4f7..f0c2f878f3b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,7 +60,7 @@ class DefaultRequestPathTests { void modifyContextPath() { RequestPath requestPath = RequestPath.parse("/aA/bB/cC", null); - assertThat(requestPath.contextPath().value()).isEqualTo(""); + assertThat(requestPath.contextPath().value()).isEmpty(); assertThat(requestPath.pathWithinApplication().value()).isEqualTo("/aA/bB/cC"); requestPath = requestPath.modifyContextPath("/aA"); 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 644086ebf78..5b88f96103e 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,51 +44,54 @@ public class EscapedErrorsTests { errors.reject("GENERAL_ERROR \" '", null, "message: \" '"); 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(); + assertThat(errors.getErrorCount()).as("Correct number of errors").isEqualTo(4); + assertThat(errors.getObjectName()).as("Correct object name").isEqualTo("tb"); assertThat(errors.hasGlobalErrors()).as("Correct global errors flag").isTrue(); - assertThat(errors.getGlobalErrorCount() == 1).as("Correct number of global errors").isTrue(); + assertThat(errors.getGlobalErrorCount()).as("Correct number of global errors").isOne(); ObjectError globalError = errors.getGlobalError(); String defaultMessage = globalError.getDefaultMessage(); - assertThat("message: " '".equals(defaultMessage)).as("Global error message escaped").isTrue(); - assertThat("GENERAL_ERROR \" '".equals(globalError.getCode())).as("Global error code not escaped").isTrue(); + assertThat(defaultMessage).as("Global error message escaped").isEqualTo("message: " '"); + assertThat(globalError.getCode()).as("Global error code not escaped").isEqualTo("GENERAL_ERROR \" '"); ObjectError globalErrorInList = errors.getGlobalErrors().get(0); - assertThat(defaultMessage.equals(globalErrorInList.getDefaultMessage())).as("Same global error in list").isTrue(); + assertThat(defaultMessage).as("Same global error in list").isEqualTo(globalErrorInList.getDefaultMessage()); ObjectError globalErrorInAllList = errors.getAllErrors().get(3); - assertThat(defaultMessage.equals(globalErrorInAllList.getDefaultMessage())).as("Same global error in list").isTrue(); + assertThat(defaultMessage).as("Same global error in list").isEqualTo(globalErrorInAllList.getDefaultMessage()); 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(); + assertThat(errors.getFieldErrorCount()).as("Correct number of field errors").isEqualTo(3); + assertThat(errors.getFieldErrors()).as("Correct number of field errors in list").hasSize(3); FieldError fieldError = errors.getFieldError(); - assertThat("NAME_EMPTY &".equals(fieldError.getCode())).as("Field error code not escaped").isTrue(); - assertThat("empty &".equals(errors.getFieldValue("name"))).as("Field value escaped").isTrue(); + assertThat(fieldError.getCode()).as("Field error code not escaped").isEqualTo("NAME_EMPTY &"); + assertThat(errors.getFieldValue("name")).as("Field value escaped").isEqualTo("empty &"); FieldError fieldErrorInList = errors.getFieldErrors().get(0); - assertThat(fieldError.getDefaultMessage().equals(fieldErrorInList.getDefaultMessage())).as("Same field error in list").isTrue(); + assertThat(fieldError.getDefaultMessage()).as("Same field error in list") + .isEqualTo(fieldErrorInList.getDefaultMessage()); 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(); + assertThat(errors.getFieldErrorCount("name")).as("Correct number of name errors").isOne(); + assertThat(errors.getFieldErrors("name")).as("Correct number of name errors in list").hasSize(1); FieldError nameError = errors.getFieldError("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(); + assertThat(nameError.getDefaultMessage()).as("Name error message escaped").isEqualTo("message: &"); + assertThat(nameError.getCode()).as("Name error code not escaped").isEqualTo("NAME_EMPTY &"); + assertThat(errors.getFieldValue("name")).as("Name value escaped").isEqualTo("empty &"); FieldError nameErrorInList = errors.getFieldErrors("name").get(0); - assertThat(nameError.getDefaultMessage().equals(nameErrorInList.getDefaultMessage())).as("Same name error in list").isTrue(); + assertThat(nameError.getDefaultMessage()).as("Same name error in list") + .isEqualTo(nameErrorInList.getDefaultMessage()); 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(); + assertThat(errors.getFieldErrorCount("age")).as("Correct number of age errors").isEqualTo(2); + assertThat(errors.getFieldErrors("age")).as("Correct number of age errors in list").hasSize(2); FieldError ageError = errors.getFieldError("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((Integer.valueOf(0)).equals(errors.getFieldValue("age"))).as("Age value not escaped").isTrue(); + assertThat(ageError.getDefaultMessage()).as("Age error message escaped").isEqualTo("message: <tag>"); + assertThat(ageError.getCode()).as("Age error code not escaped").isEqualTo("AGE_NOT_SET "); + assertThat((Integer.valueOf(0))).as("Age value not escaped").isEqualTo(errors.getFieldValue("age")); FieldError ageErrorInList = errors.getFieldErrors("age").get(0); - assertThat(ageError.getDefaultMessage().equals(ageErrorInList.getDefaultMessage())).as("Same name error in list").isTrue(); + assertThat(ageError.getDefaultMessage()).as("Same name error in list") + .isEqualTo(ageErrorInList.getDefaultMessage()); FieldError ageError2 = errors.getFieldErrors("age").get(1); - 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(); + assertThat(ageError2.getDefaultMessage()).as("Age error 2 message escaped").isEqualTo("message: <tag>"); + assertThat(ageError2.getCode()).as("Age error 2 code not escaped").isEqualTo("AGE_NOT_32 "); } } 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 9bf58625ccb..1c06d22d2be 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -216,7 +216,7 @@ public class ServletRequestDataBinderTests { public void testNoParameters() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request); - assertThat(pvs.getPropertyValues().length == 0).as("Found no parameters").isTrue(); + assertThat(pvs.getPropertyValues().length).as("Found no parameters").isEqualTo(0); } @Test @@ -226,7 +226,7 @@ public class ServletRequestDataBinderTests { request.addParameter("forname", original); ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request); - assertThat(pvs.getPropertyValues().length == 1).as("Found 1 parameter").isTrue(); + assertThat(pvs.getPropertyValues().length).as("Found 1 parameter").isEqualTo(1); boolean condition = pvs.getPropertyValue("forname").getValue() instanceof String[]; assertThat(condition).as("Found array value").isTrue(); String[] values = (String[]) pvs.getPropertyValue("forname").getValue(); @@ -237,7 +237,7 @@ public class ServletRequestDataBinderTests { * Must contain: forname=Tony surname=Blair age=50 */ protected void doTestTony(PropertyValues pvs) throws Exception { - assertThat(pvs.getPropertyValues().length == 3).as("Contains 3").isTrue(); + assertThat(pvs.getPropertyValues().length).as("Contains 3").isEqualTo(3); assertThat(pvs.contains("forname")).as("Contains forname").isTrue(); assertThat(pvs.contains("surname")).as("Contains surname").isTrue(); assertThat(pvs.contains("age")).as("Contains age").isTrue(); @@ -251,13 +251,13 @@ public class ServletRequestDataBinderTests { m.put("age", "50"); for (PropertyValue element : ps) { Object val = m.get(element.getName()); - assertThat(val != null).as("Can't have unexpected value").isTrue(); + assertThat(val).as("Can't have unexpected value").isNotNull(); boolean condition = val instanceof String; assertThat(condition).as("Val i string").isTrue(); assertThat(val.equals(element.getValue())).as("val matches expected").isTrue(); m.remove(element.getName()); } - assertThat(m.size() == 0).as("Map size is 0").isTrue(); + assertThat(m.size()).as("Map size is 0").isEqualTo(0); } } 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 00a82790f3b..58ea35d9cd9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -129,15 +129,15 @@ class ServletRequestUtilsTests { request.addParameter("paramEmpty", ""); assertThat(ServletRequestUtils.getFloatParameter(request, "param1")).isEqualTo(Float.valueOf(5.5f)); - assertThat(ServletRequestUtils.getFloatParameter(request, "param1", 6.5f) == 5.5f).isTrue(); - assertThat(ServletRequestUtils.getRequiredFloatParameter(request, "param1") == 5.5f).isTrue(); + assertThat(ServletRequestUtils.getFloatParameter(request, "param1", 6.5f)).isEqualTo(5.5f); + assertThat(ServletRequestUtils.getRequiredFloatParameter(request, "param1")).isEqualTo(5.5f); - assertThat(ServletRequestUtils.getFloatParameter(request, "param2", 6.5f) == 6.5f).isTrue(); + assertThat(ServletRequestUtils.getFloatParameter(request, "param2", 6.5f)).isEqualTo(6.5f); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredFloatParameter(request, "param2")); assertThat(ServletRequestUtils.getFloatParameter(request, "param3")).isNull(); - assertThat(ServletRequestUtils.getFloatParameter(request, "param3", 6.5f) == 6.5f).isTrue(); + assertThat(ServletRequestUtils.getFloatParameter(request, "param3", 6.5f)).isEqualTo(6.5f); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredFloatParameter(request, "param3")); @@ -167,15 +167,15 @@ class ServletRequestUtilsTests { request.addParameter("paramEmpty", ""); assertThat(ServletRequestUtils.getDoubleParameter(request, "param1")).isEqualTo(Double.valueOf(5.5)); - assertThat(ServletRequestUtils.getDoubleParameter(request, "param1", 6.5) == 5.5).isTrue(); - assertThat(ServletRequestUtils.getRequiredDoubleParameter(request, "param1") == 5.5).isTrue(); + assertThat(ServletRequestUtils.getDoubleParameter(request, "param1", 6.5)).isEqualTo(5.5); + assertThat(ServletRequestUtils.getRequiredDoubleParameter(request, "param1")).isEqualTo(5.5); - assertThat(ServletRequestUtils.getDoubleParameter(request, "param2", 6.5) == 6.5).isTrue(); + assertThat(ServletRequestUtils.getDoubleParameter(request, "param2", 6.5)).isEqualTo(6.5); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredDoubleParameter(request, "param2")); assertThat(ServletRequestUtils.getDoubleParameter(request, "param3")).isNull(); - assertThat(ServletRequestUtils.getDoubleParameter(request, "param3", 6.5) == 6.5).isTrue(); + assertThat(ServletRequestUtils.getDoubleParameter(request, "param3", 6.5)).isEqualTo(6.5); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredDoubleParameter(request, "param3")); 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 ddd747582c3..18abfa546e8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -155,9 +155,9 @@ public class WebRequestDataBinderTests { request.addParameter("_someMap", "visible"); binder.bind(new ServletWebRequest(request)); - assertThat(target.getSomeSet()).isNotNull().isInstanceOf(Set.class); - assertThat(target.getSomeList()).isNotNull().isInstanceOf(List.class); - assertThat(target.getSomeMap()).isNotNull().isInstanceOf(Map.class); + assertThat(target.getSomeSet()).isInstanceOf(Set.class); + assertThat(target.getSomeList()).isInstanceOf(List.class); + assertThat(target.getSomeMap()).isInstanceOf(Map.class); } @Test @@ -319,7 +319,7 @@ public class WebRequestDataBinderTests { * Must contain: forname=Tony surname=Blair age=50 */ protected void doTestTony(PropertyValues pvs) throws Exception { - assertThat(pvs.getPropertyValues().length == 3).as("Contains 3").isTrue(); + assertThat(pvs.getPropertyValues().length).as("Contains 3").isEqualTo(3); assertThat(pvs.contains("forname")).as("Contains forname").isTrue(); assertThat(pvs.contains("surname")).as("Contains surname").isTrue(); assertThat(pvs.contains("age")).as("Contains age").isTrue(); @@ -333,20 +333,20 @@ public class WebRequestDataBinderTests { m.put("age", "50"); for (PropertyValue pv : pvArray) { Object val = m.get(pv.getName()); - assertThat(val != null).as("Can't have unexpected value").isTrue(); + assertThat(val).as("Can't have unexpected value").isNotNull(); 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()); } - assertThat(m.size() == 0).as("Map size is 0").isTrue(); + assertThat(m.size()).as("Map size is 0").isEqualTo(0); } @Test public void testNoParameters() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request); - assertThat(pvs.getPropertyValues().length == 0).as("Found no parameters").isTrue(); + assertThat(pvs.getPropertyValues().length).as("Found no parameters").isEqualTo(0); } @Test @@ -356,7 +356,7 @@ public class WebRequestDataBinderTests { request.addParameter("forname", original); ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request); - assertThat(pvs.getPropertyValues().length == 1).as("Found 1 parameter").isTrue(); + assertThat(pvs.getPropertyValues().length).as("Found 1 parameter").isEqualTo(1); boolean condition = pvs.getPropertyValue("forname").getValue() instanceof String[]; assertThat(condition).as("Found array value").isTrue(); String[] values = (String[]) pvs.getPropertyValue("forname").getValue(); diff --git a/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTests.java b/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTests.java index 99f949d1057..abbd5a7144b 100644 --- a/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/AbstractMockWebServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -170,7 +170,7 @@ abstract class AbstractMockWebServerTests { assertThat(line).contains("name=\"" + name + "\""); assertThat(buffer.readUtf8Line()).startsWith("Content-Type: " + contentType); assertThat(buffer.readUtf8Line()).isEqualTo("Content-Length: " + value.length()); - assertThat(buffer.readUtf8Line()).isEqualTo(""); + assertThat(buffer.readUtf8Line()).isEmpty(); assertThat(buffer.readUtf8Line()).isEqualTo(value); } @@ -184,7 +184,7 @@ abstract class AbstractMockWebServerTests { assertThat(line).contains("filename=\"" + filename + "\""); assertThat(buffer.readUtf8Line()).startsWith("Content-Type: " + contentType); assertThat(buffer.readUtf8Line()).startsWith("Content-Length: "); - assertThat(buffer.readUtf8Line()).isEqualTo(""); + assertThat(buffer.readUtf8Line()).isEmpty(); assertThat(buffer.readUtf8Line()).isNotNull(); } 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 d5f1018ccc1..facf69377ba 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -387,9 +387,9 @@ class RestTemplateIntegrationTests extends AbstractMockWebServerTests { bean.setWithout("without"); HttpEntity entity = new HttpEntity<>(bean, entityHeaders); String s = template.postForObject(baseUrl + "/jsonpost", entity, String.class); - assertThat(s.contains("\"with1\":\"with\"")).isTrue(); - assertThat(s.contains("\"with2\":\"with\"")).isTrue(); - assertThat(s.contains("\"without\":\"without\"")).isTrue(); + assertThat(s).contains("\"with1\":\"with\""); + assertThat(s).contains("\"with2\":\"with\""); + assertThat(s).contains("\"without\":\"without\""); } @ParameterizedRestTemplateTest @@ -403,9 +403,9 @@ class RestTemplateIntegrationTests extends AbstractMockWebServerTests { jacksonValue.setSerializationView(MyJacksonView1.class); HttpEntity entity = new HttpEntity<>(jacksonValue, entityHeaders); String s = template.postForObject(baseUrl + "/jsonpost", entity, String.class); - assertThat(s.contains("\"with1\":\"with\"")).isTrue(); - assertThat(s.contains("\"with2\":\"with\"")).isFalse(); - assertThat(s.contains("\"without\":\"without\"")).isFalse(); + assertThat(s).contains("\"with1\":\"with\""); + assertThat(s).doesNotContain("\"with2\":\"with\""); + assertThat(s).doesNotContain("\"without\":\"without\""); } @ParameterizedRestTemplateTest // SPR-12123 @@ -429,8 +429,8 @@ class RestTemplateIntegrationTests extends AbstractMockWebServerTests { .contentType(new MediaType("application", "json", StandardCharsets.UTF_8)) .body(list, typeReference.getType()); String content = template.exchange(entity, String.class).getBody(); - assertThat(content.contains("\"type\":\"foo\"")).isTrue(); - assertThat(content.contains("\"type\":\"bar\"")).isTrue(); + assertThat(content).contains("\"type\":\"foo\""); + assertThat(content).contains("\"type\":\"bar\""); } @ParameterizedRestTemplateTest // SPR-15015 diff --git a/spring-web/src/test/java/org/springframework/web/context/support/ServletContextResourceTests.java b/spring-web/src/test/java/org/springframework/web/context/support/ServletContextResourceTests.java index a331a2c5784..5f84ebdafc1 100644 --- a/spring-web/src/test/java/org/springframework/web/context/support/ServletContextResourceTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/support/ServletContextResourceTests.java @@ -48,7 +48,7 @@ public class ServletContextResourceTests { assertThat(resource.exists()).isTrue(); assertThat(resource.isFile()).isTrue(); assertThat(resource.getFilename()).isEqualTo("resource.txt"); - assertThat(resource.getURL().getFile().endsWith("resource.txt")).isTrue(); + assertThat(resource.getURL().getFile()).endsWith("resource.txt"); } @Test @@ -56,12 +56,12 @@ public class ServletContextResourceTests { Resource resource = new ServletContextResource(this.servletContext, TEST_RESOURCE_PATH); Resource relative1 = resource.createRelative("relative.txt"); assertThat(relative1.getFilename()).isEqualTo("relative.txt"); - assertThat(relative1.getURL().getFile().endsWith("relative.txt")).isTrue(); + assertThat(relative1.getURL().getFile()).endsWith("relative.txt"); assertThat(relative1.exists()).isTrue(); Resource relative2 = resource.createRelative("folder/other.txt"); assertThat(relative2.getFilename()).isEqualTo("other.txt"); - assertThat(relative2.getURL().getFile().endsWith("other.txt")).isTrue(); + assertThat(relative2.getURL().getFile()).endsWith("other.txt"); assertThat(relative2.exists()).isTrue(); } 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 0212bada3e1..735504aa204 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -196,8 +196,8 @@ public class DefaultCorsProcessorTests { 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.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).contains("header1"); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).contains("header2"); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); @@ -365,9 +365,9 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); 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.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).contains("Header1"); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).contains("Header2"); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).doesNotContain("Header3"); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); @@ -385,9 +385,9 @@ public class DefaultCorsProcessorTests { this.processor.processRequest(this.conf, this.request, this.response); 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.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).contains("Header1"); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).contains("Header2"); + assertThat(this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS)).doesNotContain("*"); assertThat(this.response.getHeaders(HttpHeaders.VARY)).contains(HttpHeaders.ORIGIN, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); 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 36b5a4787e9..eb7a97ecab0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -202,8 +202,8 @@ public class DefaultCorsProcessorTests { 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().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).contains("header1"); + assertThat(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)).contains("header2"); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertThat((Object) response.getStatusCode()).isNull(); @@ -380,9 +380,9 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); 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().getFirst(ACCESS_CONTROL_ALLOW_HEADERS)).contains("Header1"); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS)).contains("Header2"); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS)).doesNotContain("Header3"); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertThat((Object) response.getStatusCode()).isNull(); @@ -402,9 +402,9 @@ public class DefaultCorsProcessorTests { ServerHttpResponse response = exchange.getResponse(); 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().getFirst(ACCESS_CONTROL_ALLOW_HEADERS)).contains("Header1"); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS)).contains("Header2"); + assertThat(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS)).doesNotContain("*"); assertThat(response.getHeaders().get(VARY)).contains(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS); assertThat((Object) response.getStatusCode()).isNull(); diff --git a/spring-web/src/test/java/org/springframework/web/filter/ContentCachingResponseWrapperTests.java b/spring-web/src/test/java/org/springframework/web/filter/ContentCachingResponseWrapperTests.java index 5e3f9dc4cbc..eab4aaa0812 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/ContentCachingResponseWrapperTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/ContentCachingResponseWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ public class ContentCachingResponseWrapperTests { responseWrapper.copyBodyToResponse(); assertThat(response.getStatus()).isEqualTo(200); - assertThat(response.getContentLength() > 0).isTrue(); + assertThat(response.getContentLength()).isGreaterThan(0); assertThat(response.getContentAsByteArray()).isEqualTo(responseBody); } 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 27e8120030e..bf4a4c722ff 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 @@ -214,7 +214,7 @@ public class ForwardedHeaderFilterTests { @Test public void contextPathEmpty() throws Exception { request.addHeader(X_FORWARDED_PREFIX, ""); - assertThat(filterAndGetContextPath()).isEqualTo(""); + assertThat(filterAndGetContextPath()).isEmpty(); } @Test @@ -269,7 +269,7 @@ public class ForwardedHeaderFilterTests { request.setRequestURI("/app/path"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertThat(actual.getContextPath()).isEqualTo(""); + assertThat(actual.getContextPath()).isEmpty(); assertThat(actual.getRequestURI()).isEqualTo("/path"); } @@ -280,7 +280,7 @@ public class ForwardedHeaderFilterTests { request.setRequestURI("/app/path/"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertThat(actual.getContextPath()).isEqualTo(""); + assertThat(actual.getContextPath()).isEmpty(); assertThat(actual.getRequestURI()).isEqualTo("/path/"); } @@ -302,7 +302,7 @@ public class ForwardedHeaderFilterTests { request.setRequestURI("/app"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertThat(actual.getContextPath()).isEqualTo(""); + assertThat(actual.getContextPath()).isEmpty(); assertThat(actual.getRequestURI()).isEqualTo("/"); } @@ -313,7 +313,7 @@ public class ForwardedHeaderFilterTests { request.setRequestURI("/app/"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertThat(actual.getContextPath()).isEqualTo(""); + assertThat(actual.getContextPath()).isEmpty(); assertThat(actual.getRequestURI()).isEqualTo("/"); } @@ -323,7 +323,7 @@ public class ForwardedHeaderFilterTests { request.setRequestURI("/path;a=b/with/semicolon"); HttpServletRequest actual = filterAndGetWrappedRequest(); - assertThat(actual.getContextPath()).isEqualTo(""); + assertThat(actual.getContextPath()).isEmpty(); assertThat(actual.getRequestURI()).isEqualTo("/path;a=b/with/semicolon"); assertThat(actual.getRequestURL().toString()).isEqualTo("http://localhost/path;a=b/with/semicolon"); } 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 e37e147b6ed..8ab3db1165c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,7 +74,7 @@ public class ShallowEtagHeaderFilterTests { assertThat(response.getStatus()).as("Invalid status").isEqualTo(200); assertThat(response.getHeader("ETag")).as("Invalid ETag").isEqualTo("\"0b10a8db164e0754105b7a99be72e3fe5\""); - assertThat(response.getContentLength() > 0).as("Invalid Content-Length header").isTrue(); + assertThat(response.getContentLength()).as("Invalid Content-Length header").isGreaterThan(0); assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(responseBody); } @@ -94,7 +94,7 @@ public class ShallowEtagHeaderFilterTests { assertThat(response.getStatus()).as("Invalid status").isEqualTo(200); assertThat(response.getHeader("ETag")).as("Invalid ETag").isEqualTo("W/\"0b10a8db164e0754105b7a99be72e3fe5\""); - assertThat(response.getContentLength() > 0).as("Invalid Content-Length header").isTrue(); + assertThat(response.getContentLength()).as("Invalid Content-Length header").isGreaterThan(0); assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(responseBody); } @@ -262,7 +262,7 @@ public class ShallowEtagHeaderFilterTests { assertThat(response.getStatus()).as("Invalid status").isEqualTo(200); assertThat(response.getHeader("ETag")).as("Invalid ETag").isEqualTo("\"0b10a8db164e0754105b7a99be72e3fe5\""); - assertThat(response.getContentLength() > 0).as("Invalid Content-Length header").isTrue(); + assertThat(response.getContentLength()).as("Invalid Content-Length header").isGreaterThan(0); assertThat(response.getContentAsByteArray()).as("Invalid content").isEqualTo(responseBody); } 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 005560c1f59..3134256e53c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -137,9 +137,9 @@ class ModelFactoryOrderingTests { private void assertInvokedBefore(String beforeMethod, String... afterMethods) { List actual = getInvokedMethods(); for (String afterMethod : afterMethods) { - assertThat(actual.indexOf(beforeMethod) < actual.indexOf(afterMethod)) + assertThat(actual.indexOf(beforeMethod)) .as(beforeMethod + " should be before " + afterMethod + ". Actual order: " + actual.toString()) - .isTrue(); + .isLessThan(actual.indexOf(afterMethod)); } } 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 961abe7906d..58f78a86517 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 @@ -518,7 +518,7 @@ public class RequestParamMethodArgumentResolverTests { request.addParameter("name", "123"); result = resolver.resolveArgument(param, null, webRequest, binderFactory); assertThat(result.getClass()).isEqualTo(Optional.class); - assertThat(((Optional) result).get()).isEqualTo(123); + assertThat(((Optional) result)).contains(123); } @Test @@ -534,7 +534,7 @@ public class RequestParamMethodArgumentResolverTests { result = resolver.resolveArgument(param, null, webRequest, binderFactory); assertThat(result.getClass()).isEqualTo(Optional.class); - assertThat(((Optional) result).isPresent()).isFalse(); + assertThat(((Optional) result)).isNotPresent(); } @Test @@ -567,7 +567,7 @@ public class RequestParamMethodArgumentResolverTests { result = resolver.resolveArgument(param, null, webRequest, binderFactory); assertThat(result.getClass()).isEqualTo(Optional.class); - assertThat(((Optional) result).isPresent()).isFalse(); + assertThat(((Optional) result)).isNotPresent(); } @Test @@ -584,7 +584,7 @@ public class RequestParamMethodArgumentResolverTests { request.addParameter("name", "123", "456"); result = resolver.resolveArgument(param, null, webRequest, binderFactory); assertThat(result.getClass()).isEqualTo(Optional.class); - assertThat(((Optional) result).get()).isEqualTo(Arrays.asList("123", "456")); + assertThat(((Optional) result)).contains(Arrays.asList("123", "456")); } @Test @@ -600,7 +600,7 @@ public class RequestParamMethodArgumentResolverTests { result = resolver.resolveArgument(param, null, webRequest, binderFactory); assertThat(result.getClass()).isEqualTo(Optional.class); - assertThat(((Optional) result).isPresent()).isFalse(); + assertThat(((Optional) result)).isNotPresent(); } @Test 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 134225f3ffc..488a89fcb49 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 @@ -66,7 +66,7 @@ public class ByteArrayMultipartFileEditorTests { @Test public void setValueAsNullGetsBackEmptyString() throws Exception { editor.setValue(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); } @Test 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 3fed461b2fe..ccba5fcfd2c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -141,7 +141,7 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); String value = response.getHeaders().getFirst("Set-Cookie"); assertThat(value).isNotNull(); - assertThat(value.contains("Max-Age=0")).as("Actual value: " + value).isTrue(); + assertThat(value).as("Actual value: " + value).contains("Max-Age=0"); } @ParameterizedHttpServerTest @@ -189,7 +189,7 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); String value = response.getHeaders().getFirst("Set-Cookie"); assertThat(value).isNotNull(); - assertThat(value.contains("Max-Age=0")).as("Actual value: " + value).isTrue(); + assertThat(value).as("Actual value: " + value).contains("Max-Age=0"); } private String extractSessionId(HttpHeaders headers) { diff --git a/spring-web/src/test/java/org/springframework/web/service/invoker/HttpRequestValuesTests.java b/spring-web/src/test/java/org/springframework/web/service/invoker/HttpRequestValuesTests.java index 55d26409c97..46c7c32080f 100644 --- a/spring-web/src/test/java/org/springframework/web/service/invoker/HttpRequestValuesTests.java +++ b/spring-web/src/test/java/org/springframework/web/service/invoker/HttpRequestValuesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ class HttpRequestValuesTests { HttpRequestValues requestValues = HttpRequestValues.builder().setHttpMethod(HttpMethod.GET).build(); assertThat(requestValues.getUri()).isNull(); - assertThat(requestValues.getUriTemplate()).isEqualTo(""); + assertThat(requestValues.getUriTemplate()).isEmpty(); } @ParameterizedTest diff --git a/spring-web/src/test/java/org/springframework/web/service/invoker/HttpServiceMethodTests.java b/spring-web/src/test/java/org/springframework/web/service/invoker/HttpServiceMethodTests.java index 47ccdff83c7..43b0d8c4c07 100644 --- a/spring-web/src/test/java/org/springframework/web/service/invoker/HttpServiceMethodTests.java +++ b/spring-web/src/test/java/org/springframework/web/service/invoker/HttpServiceMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -151,7 +151,7 @@ class HttpServiceMethodTests { HttpRequestValues requestValues = this.client.getRequestValues(); assertThat(requestValues.getHttpMethod()).isEqualTo(HttpMethod.GET); - assertThat(requestValues.getUriTemplate()).isEqualTo(""); + assertThat(requestValues.getUriTemplate()).isEmpty(); assertThat(requestValues.getHeaders().getContentType()).isNull(); assertThat(requestValues.getHeaders().getAccept()).isEmpty(); diff --git a/spring-web/src/test/java/org/springframework/web/service/invoker/RequestParamArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/service/invoker/RequestParamArgumentResolverTests.java index 8a6f29ddbfe..0d9b22da349 100644 --- a/spring-web/src/test/java/org/springframework/web/service/invoker/RequestParamArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/service/invoker/RequestParamArgumentResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ class RequestParamArgumentResolverTests { this.service.postForm("value 1", "value 2"); Object body = this.client.getRequestValues().getBodyValue(); - assertThat(body).isNotNull().isInstanceOf(MultiValueMap.class); + assertThat(body).isInstanceOf(MultiValueMap.class); assertThat((MultiValueMap) body).hasSize(2) .containsEntry("param1", List.of("value 1")) .containsEntry("param2", List.of("value 2")); diff --git a/spring-web/src/test/java/org/springframework/web/service/invoker/RequestPartArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/service/invoker/RequestPartArgumentResolverTests.java index ba768c7a31b..d9fb705de58 100644 --- a/spring-web/src/test/java/org/springframework/web/service/invoker/RequestPartArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/service/invoker/RequestPartArgumentResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ class RequestPartArgumentResolverTests { this.service.postMultipart("part 1", part2, Mono.just("part 3")); Object body = this.client.getRequestValues().getBodyValue(); - assertThat(body).isNotNull().isInstanceOf(MultiValueMap.class); + assertThat(body).isInstanceOf(MultiValueMap.class); @SuppressWarnings("unchecked") MultiValueMap> map = (MultiValueMap>) body; 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 d9132561a26..7a749493ce4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,7 +100,7 @@ public class ContentCachingRequestWrapperTests { assertThat(wrapper.getParameterMap().isEmpty()).isFalse(); assertThat(new String(wrapper.getContentAsByteArray())).isEqualTo("first=value&second=foo&second=bar"); // SPR-12810 : inputstream body should be consumed - assertThat(new String(FileCopyUtils.copyToByteArray(wrapper.getInputStream()))).isEqualTo(""); + assertThat(new String(FileCopyUtils.copyToByteArray(wrapper.getInputStream()))).isEmpty(); } @Test // SPR-12810 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 232a436e503..12436cc50f7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ public class HtmlUtilsTests { @Test void testEncodeIntoHtmlCharacterSet() { - assertThat(HtmlUtils.htmlEscape("")).as("An empty string should be converted to an empty string").isEqualTo(""); + assertThat(HtmlUtils.htmlEscape("")).as("An empty string should be converted to an empty string").isEmpty(); 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."); assertThat(HtmlUtils.htmlEscape("< >")).as("'< >' should be encoded to '< >'").isEqualTo("< >"); @@ -64,7 +64,8 @@ public class HtmlUtilsTests { @Test void testEncodeIntoHtmlCharacterSetFromUtf8() { String utf8 = ("UTF-8"); - assertThat(HtmlUtils.htmlEscape("", utf8)).as("An empty string should be converted to an empty string").isEqualTo(""); + assertThat(HtmlUtils.htmlEscape("", utf8)).as("An empty string should be converted to an empty string") + .isEmpty(); 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."); assertThat(HtmlUtils.htmlEscape("< >", utf8)).as("'< >' should be encoded to '< >'").isEqualTo("< >"); @@ -75,7 +76,7 @@ public class HtmlUtilsTests { @Test void testDecodeFromHtmlCharacterSet() { - assertThat(HtmlUtils.htmlUnescape("")).as("An empty string should be converted to an empty string").isEqualTo(""); + assertThat(HtmlUtils.htmlUnescape("")).as("An empty string should be converted to an empty string").isEmpty(); 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."); assertThat(HtmlUtils.htmlUnescape("A B")).as("'A B' should be decoded to 'A B'").isEqualTo(("A" + (char) 160 + "B")); 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 3de7ca3b256..611863db420 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -953,7 +953,7 @@ class UriComponentsBuilderTests { void queryParamWithoutValueWithEquals() { UriComponents uriComponents = UriComponentsBuilder.fromUriString("https://example.com/foo?bar=").build(); assertThat(uriComponents.toUriString()).isEqualTo("https://example.com/foo?bar="); - assertThat(uriComponents.getQueryParams().get("bar").get(0)).isEqualTo(""); + assertThat(uriComponents.getQueryParams().get("bar").get(0)).isEmpty(); } @Test @@ -1026,7 +1026,7 @@ class UriComponentsBuilderTests { @Test // SPR-13257 void parsesEmptyUri() { UriComponents components = UriComponentsBuilder.fromUriString("").build(); - assertThat(components.toString()).isEqualTo(""); + assertThat(components.toString()).isEmpty(); } @Test // gh-25243 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 f9dae3a3836..61a01c6cdac 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,7 +100,7 @@ public class UriUtilsTests { @Test public void decode() { - assertThat(UriUtils.decode("", CHARSET)).as("Invalid encoded URI").isEqualTo(""); + assertThat(UriUtils.decode("", CHARSET)).as("Invalid encoded URI").isEmpty(); 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"); 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 e9d95d582c0..d246a586323 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,7 +67,7 @@ public class WebUtilsTests { variables = WebUtils.parseMatrixVariables("year"); assertThat(variables).hasSize(1); - assertThat(variables.getFirst("year")).isEqualTo(""); + assertThat(variables.getFirst("year")).isEmpty(); variables = WebUtils.parseMatrixVariables("year=2012"); assertThat(variables).hasSize(1); 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 67e063dab7d..3847986a69a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -394,7 +394,7 @@ public class PathPatternParserTests { // Based purely on catchAll p1 = parse("{*foobar}"); p2 = parse("{*goo}"); - assertThat(p1.compareTo(p2) != 0).isTrue(); + assertThat(p1.compareTo(p2)).isNotEqualTo(0); p1 = parse("/{*foobar}"); p2 = parse("/abc/{*ww}"); 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 d3114205618..5bd2affbd45 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -129,26 +129,44 @@ public class PathPatternTests { // CaptureVariablePathElement pp = parse("/{var}"); assertMatches(pp,"/resource"); - assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")).isEqualTo("resource"); + assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables()).containsEntry("var", "resource"); assertMatches(pp,"/resource/"); - assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")).isEqualTo("resource"); + assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables()).containsEntry( + "var", + "resource" + ); assertNoMatch(pp,"/resource//"); pp = parse("/{var}/"); assertNoMatch(pp,"/resource"); assertMatches(pp,"/resource/"); - assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")).isEqualTo("resource"); + assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables()).containsEntry( + "var", + "resource" + ); assertNoMatch(pp,"/resource//"); // CaptureTheRestPathElement pp = parse("/{*var}"); assertMatches(pp,"/resource"); - assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")).isEqualTo("/resource"); + assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables()).containsEntry( + "var", + "/resource" + ); assertMatches(pp,"/resource/"); - assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")).isEqualTo("/resource/"); + assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables()).containsEntry( + "var", + "/resource/" + ); assertMatches(pp,"/resource//"); - assertThat(pp.matchAndExtract(toPathContainer("/resource//")).getUriVariables().get("var")).isEqualTo("/resource//"); + assertThat(pp.matchAndExtract(toPathContainer("/resource//")).getUriVariables()).containsEntry( + "var", + "/resource//" + ); assertMatches(pp,"//resource//"); - assertThat(pp.matchAndExtract(toPathContainer("//resource//")).getUriVariables().get("var")).isEqualTo("//resource//"); + assertThat(pp.matchAndExtract(toPathContainer("//resource//")).getUriVariables()).containsEntry( + "var", + "//resource//" + ); // WildcardTheRestPathElement pp = parse("/**"); @@ -170,17 +188,17 @@ public class PathPatternTests { // RegexPathElement pp = parse("/{var1}_{var2}"); assertMatches(pp,"/res1_res2"); - assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var1")).isEqualTo("res1"); - assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var2")).isEqualTo("res2"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables()).containsEntry("var1", "res1"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables()).containsEntry("var2", "res2"); assertMatches(pp,"/res1_res2/"); - assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var1")).isEqualTo("res1"); - assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var2")).isEqualTo("res2"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables()).containsEntry("var1", "res1"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables()).containsEntry("var2", "res2"); assertNoMatch(pp,"/res1_res2//"); pp = parse("/{var1}_{var2}/"); assertNoMatch(pp,"/res1_res2"); assertMatches(pp,"/res1_res2/"); - assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var1")).isEqualTo("res1"); - assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var2")).isEqualTo("res2"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables()).containsEntry("var1", "res1"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables()).containsEntry("var2", "res2"); assertNoMatch(pp,"/res1_res2//"); pp = parse("/{var1}*"); assertMatches(pp,"/a"); @@ -214,25 +232,40 @@ public class PathPatternTests { // CaptureVariablePathElement pp = parser.parse("/{var}"); assertMatches(pp,"/resource"); - assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")).isEqualTo("resource"); + assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables()).containsEntry("var", "resource"); assertNoMatch(pp,"/resource/"); assertNoMatch(pp,"/resource//"); pp = parser.parse("/{var}/"); assertNoMatch(pp,"/resource"); assertMatches(pp,"/resource/"); - assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")).isEqualTo("resource"); + assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables()).containsEntry( + "var", + "resource" + ); assertNoMatch(pp,"/resource//"); // CaptureTheRestPathElement pp = parser.parse("/{*var}"); assertMatches(pp,"/resource"); - assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables().get("var")).isEqualTo("/resource"); + assertThat(pp.matchAndExtract(toPathContainer("/resource")).getUriVariables()).containsEntry( + "var", + "/resource" + ); assertMatches(pp,"/resource/"); - assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables().get("var")).isEqualTo("/resource/"); + assertThat(pp.matchAndExtract(toPathContainer("/resource/")).getUriVariables()).containsEntry( + "var", + "/resource/" + ); assertMatches(pp,"/resource//"); - assertThat(pp.matchAndExtract(toPathContainer("/resource//")).getUriVariables().get("var")).isEqualTo("/resource//"); + assertThat(pp.matchAndExtract(toPathContainer("/resource//")).getUriVariables()).containsEntry( + "var", + "/resource//" + ); assertMatches(pp,"//resource//"); - assertThat(pp.matchAndExtract(toPathContainer("//resource//")).getUriVariables().get("var")).isEqualTo("//resource//"); + assertThat(pp.matchAndExtract(toPathContainer("//resource//")).getUriVariables()).containsEntry( + "var", + "//resource//" + ); // WildcardTheRestPathElement pp = parser.parse("/**"); @@ -254,15 +287,15 @@ public class PathPatternTests { // RegexPathElement pp = parser.parse("/{var1}_{var2}"); assertMatches(pp,"/res1_res2"); - assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var1")).isEqualTo("res1"); - assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables().get("var2")).isEqualTo("res2"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables()).containsEntry("var1", "res1"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2")).getUriVariables()).containsEntry("var2", "res2"); assertNoMatch(pp,"/res1_res2/"); assertNoMatch(pp,"/res1_res2//"); pp = parser.parse("/{var1}_{var2}/"); assertNoMatch(pp,"/res1_res2"); assertMatches(pp,"/res1_res2/"); - assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var1")).isEqualTo("res1"); - assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables().get("var2")).isEqualTo("res2"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables()).containsEntry("var1", "res1"); + assertThat(pp.matchAndExtract(toPathContainer("/res1_res2/")).getUriVariables()).containsEntry("var2", "res2"); assertNoMatch(pp,"/res1_res2//"); pp = parser.parse("/{var1}*"); assertMatches(pp,"/a"); @@ -280,12 +313,12 @@ public class PathPatternTests { 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("/**", "/foo/bar").getPathRemaining().value()).isEmpty(); + assertThat(getPathRemaining("/{*bar}", "/foo/bar").getPathRemaining().value()).isEmpty(); 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("/", "/").getPathRemaining().value()).isEmpty(); assertThat(getPathRemaining("/", "/a").getPathRemaining().value()).isEqualTo("a"); assertThat(getPathRemaining("/", "/a/").getPathRemaining().value()).isEqualTo("a/"); assertThat(getPathRemaining("/a{abc}", "/a/bar").getPathRemaining().value()).isEqualTo("/bar"); @@ -337,34 +370,34 @@ public class PathPatternTests { // 'the match' it starts with a separator assertThat(parse("/resource/**").matchStartOfPath(toPathContainer("/resourceX"))).isNull(); assertThat(parse("/resource/**") - .matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value()).isEqualTo(""); + .matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value()).isEmpty(); // Similar to above for the capture-the-rest variant assertThat(parse("/resource/{*foo}").matchStartOfPath(toPathContainer("/resourceX"))).isNull(); assertThat(parse("/resource/{*foo}") - .matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value()).isEqualTo(""); + .matchStartOfPath(toPathContainer("/resource")).getPathRemaining().value()).isEmpty(); PathPattern.PathRemainingMatchInfo pri = parse("/aaa/{bbb}/c?d/e*f/*/g") .matchStartOfPath(toPathContainer("/aaa/b/ccd/ef/x/g/i")); assertThat(pri).isNotNull(); assertThat(pri.getPathRemaining().value()).isEqualTo("/i"); - assertThat(pri.getUriVariables().get("bbb")).isEqualTo("b"); + assertThat(pri.getUriVariables()).containsEntry("bbb", "b"); pri = parse("/aaa/{bbb}/c?d/e*f/*/g/").matchStartOfPath(toPathContainer("/aaa/b/ccd/ef/x/g/i")); assertThat(pri).isNotNull(); assertThat(pri.getPathRemaining().value()).isEqualTo("i"); - assertThat(pri.getUriVariables().get("bbb")).isEqualTo("b"); + assertThat(pri.getUriVariables()).containsEntry("bbb", "b"); pri = parse("/{aaa}_{bbb}/e*f/{x}/g").matchStartOfPath(toPathContainer("/aa_bb/ef/x/g/i")); 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"); + assertThat(pri.getUriVariables()).containsEntry("aaa", "aa"); + assertThat(pri.getUriVariables()).containsEntry("bbb", "bb"); + assertThat(pri.getUriVariables()).containsEntry("x", "x"); 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(""); + assertThat(parse("").matchStartOfPath(toPathContainer("")).getPathRemaining().value()).isEmpty(); } @Test @@ -563,19 +596,19 @@ public class PathPatternTests { pri = getPathRemaining(pp, "/foo/bar/goo/boo"); assertThat(pri.getPathRemaining().value()).isEqualTo("/boo"); assertThat(pri.getPathMatched().value()).isEqualTo("/foo/bar/goo"); - assertThat(pri.getUriVariables().get("this")).isEqualTo("foo"); - assertThat(pri.getUriVariables().get("one")).isEqualTo("bar"); - assertThat(pri.getUriVariables().get("here")).isEqualTo("goo"); + assertThat(pri.getUriVariables()).containsEntry("this", "foo"); + assertThat(pri.getUriVariables()).containsEntry("one", "bar"); + assertThat(pri.getUriVariables()).containsEntry("here", "goo"); pp = parse("/aaa/{foo}"); pri = getPathRemaining(pp, "/aaa/bbb"); - assertThat(pri.getPathRemaining().value()).isEqualTo(""); + assertThat(pri.getPathRemaining().value()).isEmpty(); assertThat(pri.getPathMatched().value()).isEqualTo("/aaa/bbb"); - assertThat(pri.getUriVariables().get("foo")).isEqualTo("bbb"); + assertThat(pri.getUriVariables()).containsEntry("foo", "bbb"); pp = parse("/aaa/bbb"); pri = getPathRemaining(pp, "/aaa/bbb"); - assertThat(pri.getPathRemaining().value()).isEqualTo(""); + assertThat(pri.getPathRemaining().value()).isEmpty(); assertThat(pri.getPathMatched().value()).isEqualTo("/aaa/bbb"); assertThat(pri.getUriVariables()).isEmpty(); @@ -583,12 +616,12 @@ public class PathPatternTests { pri = getPathRemaining(pp, "/foo"); assertThat((Object) pri).isNull(); pri = getPathRemaining(pp, "/abc/def/bhi"); - assertThat(pri.getPathRemaining().value()).isEqualTo(""); - assertThat(pri.getUriVariables().get("foo")).isEqualTo("def"); + assertThat(pri.getPathRemaining().value()).isEmpty(); + assertThat(pri.getUriVariables()).containsEntry("foo", "def"); pri = getPathRemaining(pp, "/abc/def/bhi/jkl"); assertThat(pri.getPathRemaining().value()).isEqualTo("/jkl"); - assertThat(pri.getUriVariables().get("foo")).isEqualTo("def"); + assertThat(pri.getUriVariables()).containsEntry("foo", "def"); } @Test @@ -787,8 +820,8 @@ public class PathPatternTests { assertThat(new AntPathMatcher().match("/*", "/")).isTrue(); assertThat(new AntPathMatcher().match("/*{foo}", "/")).isFalse(); Map vars = new AntPathMatcher().extractUriTemplateVariables("/{foo}{bar}", "/a"); - assertThat(vars.get("foo")).isEqualTo("a"); - assertThat(vars.get("bar")).isEqualTo(""); + assertThat(vars).containsEntry("foo", "a"); + assertThat(vars.get("bar")).isEmpty(); } @Test @@ -829,13 +862,13 @@ public class PathPatternTests { p = pp.parse("{symbolicName:[\\w\\.]+}-{version:[\\w\\.]+}.jar"); PathPattern.PathMatchInfo result = matchAndExtract(p, "com.example-1.0.0.jar"); - assertThat(result.getUriVariables().get("symbolicName")).isEqualTo("com.example"); - assertThat(result.getUriVariables().get("version")).isEqualTo("1.0.0"); + assertThat(result.getUriVariables()).containsEntry("symbolicName", "com.example"); + assertThat(result.getUriVariables()).containsEntry("version", "1.0.0"); p = pp.parse("{symbolicName:[\\w\\.]+}-sources-{version:[\\w\\.]+}.jar"); result = matchAndExtract(p, "com.example-sources-1.0.0.jar"); - assertThat(result.getUriVariables().get("symbolicName")).isEqualTo("com.example"); - assertThat(result.getUriVariables().get("version")).isEqualTo("1.0.0"); + assertThat(result.getUriVariables()).containsEntry("symbolicName", "com.example"); + assertThat(result.getUriVariables()).containsEntry("version", "1.0.0"); } @Test @@ -844,22 +877,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")); - assertThat(result.getUriVariables().get("symbolicName")).isEqualTo("com.example"); - assertThat(result.getUriVariables().get("version")).isEqualTo("1.0.0"); + assertThat(result.getUriVariables()).containsEntry("symbolicName", "com.example"); + assertThat(result.getUriVariables()).containsEntry("version", "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"); - 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"); + assertThat(result.getUriVariables()).containsEntry("symbolicName", "com.example"); + assertThat(result.getUriVariables()).containsEntry("version", "1.0.0"); + assertThat(result.getUriVariables()).containsEntry("year", "2010"); + assertThat(result.getUriVariables()).containsEntry("month", "02"); + assertThat(result.getUriVariables()).containsEntry("day", "20"); p = pp.parse("{symbolicName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.\\{\\}]+}.jar"); result = matchAndExtract(p, "com.example-sources-1.0.0.{12}.jar"); - assertThat(result.getUriVariables().get("symbolicName")).isEqualTo("com.example"); - assertThat(result.getUriVariables().get("version")).isEqualTo("1.0.0.{12}"); + assertThat(result.getUriVariables()).containsEntry("symbolicName", "com.example"); + assertThat(result.getUriVariables()).containsEntry("version", "1.0.0.{12}"); } @Test @@ -874,7 +907,7 @@ public class PathPatternTests { @Test public void combine() { TestPathCombiner pathMatcher = new TestPathCombiner(); - assertThat(pathMatcher.combine("", "")).isEqualTo(""); + assertThat(pathMatcher.combine("", "")).isEmpty(); assertThat(pathMatcher.combine("/hotels", "")).isEqualTo("/hotels"); assertThat(pathMatcher.combine("", "/hotels")).isEqualTo("/hotels"); assertThat(pathMatcher.combine("/hotels/*", "booking")).isEqualTo("/hotels/booking"); @@ -984,8 +1017,8 @@ public class PathPatternTests { PathPattern.PathMatchInfo r2 = matchAndExtract(p2, "/file.txt"); // works fine - assertThat(r1.getUriVariables().get("foo")).isEqualTo("file.txt"); - assertThat(r2.getUriVariables().get("foo")).isEqualTo("file"); + assertThat(r1.getUriVariables()).containsEntry("foo", "file.txt"); + assertThat(r2.getUriVariables()).containsEntry("foo", "file"); // This produces 2 (see comments in https://jira.spring.io/browse/SPR-14544 ) // Comparator patternComparator = new AntPathMatcher().getPatternComparator(""); @@ -996,9 +1029,9 @@ public class PathPatternTests { @Test public void patternCompareWithNull() { - 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(); + assertThat(PathPattern.SPECIFICITY_COMPARATOR.compare(null, null)).isEqualTo(0); + assertThat(PathPattern.SPECIFICITY_COMPARATOR.compare(parse("/abc"), null)).isLessThan(0); + assertThat(PathPattern.SPECIFICITY_COMPARATOR.compare(null, parse("/abc"))).isGreaterThan(0); } @Test @@ -1115,32 +1148,32 @@ public class PathPatternTests { public void parameters() { // CaptureVariablePathElement PathPattern.PathMatchInfo result = matchAndExtract("/abc/{var}","/abc/one;two=three;four=five"); - assertThat(result.getUriVariables().get("var")).isEqualTo("one"); + assertThat(result.getUriVariables()).containsEntry("var", "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"); - assertThat(result.getUriVariables().get("var1")).isEqualTo("123"); - assertThat(result.getUriVariables().get("var2")).isEqualTo("456"); + assertThat(result.getUriVariables()).containsEntry("var1", "123"); + assertThat(result.getUriVariables()).containsEntry("var2", "456"); // vars associated with second variable - assertThat(result.getMatrixVariables().get("var1")).isNull(); - assertThat(result.getMatrixVariables().get("var1")).isNull(); + assertThat(result.getMatrixVariables()).doesNotContainKey("var1"); + assertThat(result.getMatrixVariables()).doesNotContainKey("var1"); 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"); - assertThat(result.getUriVariables().get("var")).isEqualTo("/abc/123_456"); + assertThat(result.getUriVariables()).containsEntry("var", "/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"); - assertThat(result.getUriVariables().get("var")).isEqualTo("/abc/123_456/789"); + assertThat(result.getUriVariables()).containsEntry("var", "/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"); - assertThat(result.getUriVariables().get("var")).isEqualTo("one"); - assertThat(result.getMatrixVariables().get("var")).isNull(); + assertThat(result.getUriVariables()).containsEntry("var", "one"); + assertThat(result.getMatrixVariables()).doesNotContainKey("var"); result = matchAndExtract("",""); assertThat(result).isNotNull(); 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 d9b8844ec7c..1885b66d4e0 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 @@ -21,7 +21,6 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; -import java.util.Optional; import java.util.OptionalLong; import org.junit.jupiter.api.BeforeEach; @@ -101,7 +100,7 @@ class DefaultClientResponseTests { ClientResponse.Headers headers = defaultClientResponse.headers(); assertThat(headers.contentLength()).isEqualTo(OptionalLong.of(contentLength)); - assertThat(headers.contentType()).isEqualTo(Optional.of(contentType)); + assertThat(headers.contentType()).contains(contentType); assertThat(headers.asHttpHeaders()).isEqualTo(httpHeaders); } 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 757297fb829..64a626c64a9 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 @@ -110,7 +110,7 @@ public class DefaultWebClientTests { ClientRequest request = verifyAndGetRequest(); assertThat(request.url().toString()).isEqualTo("/base/path/identifier?q=12"); - assertThat(request.attribute(WebClient.class.getName() + ".uriTemplate").get()).isEqualTo("/path/{id}"); + assertThat(request.attribute(WebClient.class.getName() + ".uriTemplate")).contains("/path/{id}"); } @Test @@ -341,7 +341,7 @@ public class DefaultWebClientTests { assertThat(actual.get("foo")).isEqualTo("bar"); ClientRequest request = verifyAndGetRequest(); - assertThat(request.attribute("foo").get()).isEqualTo("bar"); + assertThat(request.attribute("foo")).contains("bar"); } @Test @@ -360,7 +360,7 @@ public class DefaultWebClientTests { assertThat(actual.get("foo")).isNull(); ClientRequest request = verifyAndGetRequest(); - assertThat(request.attribute("foo").isPresent()).isFalse(); + assertThat(request.attribute("foo")).isNotPresent(); } @Test 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 c074f88d34a..bed28279cc5 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 @@ -105,7 +105,7 @@ public class ExchangeFilterFunctionsTests { ExchangeFunction exchange = r -> { assertThat(r.headers().containsKey(HttpHeaders.AUTHORIZATION)).isTrue(); - assertThat(r.headers().getFirst(HttpHeaders.AUTHORIZATION).startsWith("Basic ")).isTrue(); + assertThat(r.headers().getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic "); return Mono.just(response); }; @@ -135,7 +135,7 @@ public class ExchangeFilterFunctionsTests { ExchangeFunction exchange = r -> { assertThat(r.headers().containsKey(HttpHeaders.AUTHORIZATION)).isTrue(); - assertThat(r.headers().getFirst(HttpHeaders.AUTHORIZATION).startsWith("Basic ")).isTrue(); + assertThat(r.headers().getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic "); return Mono.just(response); }; 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 2a495d65bb3..3d7c637f85a 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 @@ -660,7 +660,7 @@ class WebClientIntegrationTests { UnknownHttpStatusCodeException ex = (UnknownHttpStatusCodeException) throwable; assertThat(ex.getMessage()).isEqualTo(("Unknown status code ["+errorStatus+"]")); assertThat(ex.getRawStatusCode()).isEqualTo(errorStatus); - assertThat(ex.getStatusText()).isEqualTo(""); + assertThat(ex.getStatusText()).isEmpty(); assertThat(ex.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); assertThat(ex.getResponseBodyAsString()).isEqualTo(errorMessage); }) 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 a75442b70b3..83038db2c45 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 @@ -32,7 +32,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.OptionalLong; import java.util.function.Consumer; @@ -131,7 +130,7 @@ public class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(exchange, messageReaders); - assertThat(request.attribute("foo")).isEqualTo(Optional.of("bar")); + assertThat(request.attribute("foo")).contains("bar"); } @Test @@ -140,7 +139,7 @@ public class DefaultServerRequestTests { MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, "https://example.com?foo=bar")), this.messageReaders); - assertThat(request.queryParam("foo")).isEqualTo(Optional.of("bar")); + assertThat(request.queryParam("foo")).contains("bar"); } @Test @@ -149,7 +148,7 @@ public class DefaultServerRequestTests { MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, "https://example.com?foo")), this.messageReaders); - assertThat(request.queryParam("foo")).isEqualTo(Optional.of("")); + assertThat(request.queryParam("foo")).contains(""); } @Test @@ -158,7 +157,7 @@ public class DefaultServerRequestTests { MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, "https://example.com?foo")), this.messageReaders); - assertThat(request.queryParam("bar")).isEqualTo(Optional.empty()); + assertThat(request.queryParam("bar")).isNotPresent(); } @Test @@ -223,7 +222,7 @@ public class DefaultServerRequestTests { 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.contentType()).contains(contentType); assertThat(headers.header(HttpHeaders.CONTENT_TYPE)).containsExactly(MediaType.TEXT_PLAIN_VALUE); assertThat(headers.firstHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo(MediaType.TEXT_PLAIN_VALUE); assertThat(headers.asHttpHeaders()).isEqualTo(httpHeaders); 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 268d00f8d20..9933a0dcfcf 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 @@ -92,7 +92,7 @@ class ServerRequestWrapperTests { String value = "bar"; given(mockRequest.attribute(name)).willReturn(Optional.of(value)); - assertThat(wrapper.attribute(name)).isEqualTo(Optional.of(value)); + assertThat(wrapper.attribute(name)).contains(value); } @Test @@ -101,7 +101,7 @@ class ServerRequestWrapperTests { String value = "bar"; given(mockRequest.queryParam(name)).willReturn(Optional.of(value)); - assertThat(wrapper.queryParam(name)).isEqualTo(Optional.of(value)); + assertThat(wrapper.queryParam(name)).contains(value); } @Test 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 b9da1c45c62..289d969199f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,7 @@ public class PathResourceResolverTests { Resource actual = this.resolver.resolveResource(null, path, locations, null).block(TIMEOUT); assertThat(actual).isNotNull(); - assertThat(actual.getFile().getName()).isEqualTo("foo foo.txt"); + assertThat(actual.getFile()).hasName("foo foo.txt"); } @Test 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 82daf08e480..15432ea1a66 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 @@ -440,7 +440,7 @@ class ResourceWebHandlerTests { assertThat(this.handler.processPath((char) 1 + " / " + (char) 127 + " // foo/bar")).isEqualTo("/foo/bar"); // root or empty path - assertThat(this.handler.processPath(" ")).isEqualTo(""); + assertThat(this.handler.processPath(" ")).isEmpty(); assertThat(this.handler.processPath("/")).isEqualTo("/"); assertThat(this.handler.processPath("///")).isEqualTo("/"); assertThat(this.handler.processPath("/ / / ")).isEqualTo("/"); @@ -677,8 +677,8 @@ class ResourceWebHandlerTests { this.handler.handle(exchange).block(TIMEOUT); assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.PARTIAL_CONTENT); - assertThat(exchange.getResponse().getHeaders().getContentType().toString() - .startsWith("multipart/byteranges;boundary=")).isTrue(); + assertThat(exchange.getResponse().getHeaders().getContentType().toString()).startsWith( + "multipart/byteranges;boundary="); String boundary = "--" + exchange.getResponse().getHeaders().getContentType().toString().substring(30); 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 39063d93b1a..fae987d2c4f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,10 +146,10 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition("text/*"); int result = condition1.compareTo(condition2, exchange); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, exchange); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); } @Test @@ -160,10 +160,10 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition("text/*", "text/plain;q=0.7"); int result = condition1.compareTo(condition2, exchange); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, exchange); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); } @@ -209,7 +209,7 @@ public class ConsumesRequestConditionTests { private void assertConditions(ConsumesRequestCondition condition, String... expected) { Collection expressions = condition.getContent(); - assertThat(expected.length).as("Invalid amount of conditions").isEqualTo(expressions.size()); + assertThat(expected).as("Invalid amount of conditions").hasSameSizeAs(expressions); 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 5385d3cb1be..479cdaa0b6f 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -114,10 +114,10 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition2 = new HeadersRequestCondition("foo=a", "bar"); int result = condition1.compareTo(condition2, exchange); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, exchange); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); } @Test // SPR-16674 @@ -128,7 +128,7 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition2 = new HeadersRequestCondition("foo"); int result = condition1.compareTo(condition2, exchange); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); } @Test 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 e366c8ce812..379a104be50 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,10 +85,10 @@ public class ParamsRequestConditionTests { ParamsRequestCondition condition2 = new ParamsRequestCondition("foo", "bar"); int result = condition1.compareTo(condition2, exchange); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, exchange); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); } @Test // SPR-16674 @@ -99,7 +99,7 @@ public class ParamsRequestConditionTests { ParamsRequestCondition condition2 = new ParamsRequestCondition("response_type"); int result = condition1.compareTo(condition2, exchange); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); } @Test 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 6e7e6b0ed0c..6ae14323bf6 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 @@ -42,8 +42,7 @@ public class PatternsRequestConditionTests { public void prependNonEmptyPatternsOnly() { PatternsRequestCondition c = createPatternsCondition(""); assertThat(c.getPatterns().iterator().next().getPatternString()) - .as("Do not prepend empty patterns (SPR-8255)") - .isEqualTo(""); + .as("Do not prepend empty patterns (SPR-8255)").isEmpty(); } @Test 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 4463475a4e0..afb854afb80 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 @@ -157,18 +157,18 @@ public class ProducesRequestConditionTests { MockServerWebExchange exchange = MockServerWebExchange.from(get("/") .header("Accept", "application/xml, text/html")); - 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(); + assertThat(html.compareTo(xml, exchange)).isGreaterThan(0); + assertThat(xml.compareTo(html, exchange)).isLessThan(0); + assertThat(xml.compareTo(none, exchange)).isLessThan(0); + assertThat(none.compareTo(xml, exchange)).isGreaterThan(0); + assertThat(html.compareTo(none, exchange)).isLessThan(0); + assertThat(none.compareTo(html, exchange)).isGreaterThan(0); exchange = MockServerWebExchange.from( get("/").header("Accept", "application/xml, text/*")); - assertThat(html.compareTo(xml, exchange) > 0).isTrue(); - assertThat(xml.compareTo(html, exchange) < 0).isTrue(); + assertThat(html.compareTo(xml, exchange)).isGreaterThan(0); + assertThat(xml.compareTo(html, exchange)).isLessThan(0); exchange = MockServerWebExchange.from( get("/").header("Accept", "application/pdf")); @@ -180,8 +180,8 @@ public class ProducesRequestConditionTests { exchange = MockServerWebExchange.from( get("/").header("Accept", "text/html;q=0.9,application/xml")); - assertThat(html.compareTo(xml, exchange) > 0).isTrue(); - assertThat(xml.compareTo(html, exchange) < 0).isTrue(); + assertThat(html.compareTo(xml, exchange)).isGreaterThan(0); + assertThat(xml.compareTo(html, exchange)).isLessThan(0); } @Test @@ -192,10 +192,10 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition("text/*"); int result = condition1.compareTo(condition2, exchange); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, exchange); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); } @Test @@ -221,19 +221,19 @@ public class ProducesRequestConditionTests { get("/").header("Accept", "text/plain", "application/xml")); int result = condition1.compareTo(condition2, exchange); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, exchange); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); exchange = MockServerWebExchange.from( get("/").header("Accept", "application/xml", "text/plain")); result = condition1.compareTo(condition2, exchange); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); result = condition2.compareTo(condition1, exchange); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); } // SPR-8536 @@ -245,14 +245,16 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition1 = new ProducesRequestCondition(); ProducesRequestCondition condition2 = new ProducesRequestCondition("application/json"); - 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(); + assertThat(condition1.compareTo(condition2, exchange)).as("Should have picked '*/*' condition as an exact match") + .isLessThan(0); + assertThat(condition2.compareTo(condition1, exchange)).as("Should have picked '*/*' condition as an exact match") + .isGreaterThan(0); condition1 = new ProducesRequestCondition("*/*"); condition2 = new ProducesRequestCondition("application/json"); - assertThat(condition1.compareTo(condition2, exchange) < 0).isTrue(); - assertThat(condition2.compareTo(condition1, exchange) > 0).isTrue(); + assertThat(condition1.compareTo(condition2, exchange)).isLessThan(0); + assertThat(condition2.compareTo(condition1, exchange)).isGreaterThan(0); exchange = MockServerWebExchange.from( get("/").header("Accept", "*/*")); @@ -260,14 +262,14 @@ public class ProducesRequestConditionTests { condition1 = new ProducesRequestCondition(); condition2 = new ProducesRequestCondition("application/json"); - assertThat(condition1.compareTo(condition2, exchange) < 0).isTrue(); - assertThat(condition2.compareTo(condition1, exchange) > 0).isTrue(); + assertThat(condition1.compareTo(condition2, exchange)).isLessThan(0); + assertThat(condition2.compareTo(condition1, exchange)).isGreaterThan(0); condition1 = new ProducesRequestCondition("*/*"); condition2 = new ProducesRequestCondition("application/json"); - assertThat(condition1.compareTo(condition2, exchange) < 0).isTrue(); - assertThat(condition2.compareTo(condition1, exchange) > 0).isTrue(); + assertThat(condition1.compareTo(condition2, exchange)).isLessThan(0); + assertThat(condition2.compareTo(condition1, exchange)).isGreaterThan(0); } // SPR-9021 @@ -279,8 +281,8 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition1 = new ProducesRequestCondition(); ProducesRequestCondition condition2 = new ProducesRequestCondition("application/json"); - assertThat(condition1.compareTo(condition2, exchange) < 0).isTrue(); - assertThat(condition2.compareTo(condition1, exchange) > 0).isTrue(); + assertThat(condition1.compareTo(condition2, exchange)).isLessThan(0); + assertThat(condition2.compareTo(condition1, exchange)).isGreaterThan(0); } @Test @@ -291,10 +293,10 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition("text/xhtml"); int result = condition1.compareTo(condition2, exchange); - assertThat(result < 0).as("Should have used MediaType.equals(Object) to break the match").isTrue(); + assertThat(result).as("Should have used MediaType.equals(Object) to break the match").isLessThan(0); result = condition2.compareTo(condition1, exchange); - assertThat(result > 0).as("Should have used MediaType.equals(Object) to break the match").isTrue(); + assertThat(result).as("Should have used MediaType.equals(Object) to break the match").isGreaterThan(0); } @Test 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 4e32d47279e..e93360ff095 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 @@ -98,13 +98,13 @@ public class RequestMethodsRequestConditionTests { ServerWebExchange exchange = getExchange("GET"); int result = c1.compareTo(c2, exchange); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = c2.compareTo(c1, exchange); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); result = c2.compareTo(c3, exchange); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = c1.compareTo(c1, exchange); assertThat(result).as("Invalid comparison result ").isEqualTo(0); 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 f3d12370a03..bcdeefc7c35 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -276,7 +276,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); - assertThat(pattern.getPatternString()).isEqualTo(""); + assertThat(pattern.getPatternString()).isEmpty(); } @Test 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 6bfc2d849ca..1c5c5aca628 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -125,7 +125,7 @@ public class ControllerMethodResolverTests { public void modelAttributeArgumentResolvers() { List methods = this.methodResolver.getModelAttributeMethods(this.handlerMethod); - assertThat(methods.size()).as("Expected one each from Controller + ControllerAdvice").isEqualTo(2); + assertThat(methods).as("Expected one each from Controller + ControllerAdvice").hasSize(2); InvocableHandlerMethod invocable = methods.get(0); List resolvers = invocable.getResolvers(); @@ -163,7 +163,7 @@ public class ControllerMethodResolverTests { List methods = this.methodResolver.getInitBinderMethods(this.handlerMethod); - assertThat(methods.size()).as("Expected one each from Controller + ControllerAdvice").isEqualTo(2); + assertThat(methods).as("Expected one each from Controller + ControllerAdvice").hasSize(2); SyncInvocableHandlerMethod invocable = methods.get(0); List resolvers = invocable.getResolvers(); 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 6636ca27f64..621d2b6e5b5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -151,7 +151,7 @@ public class PathVariableMethodArgumentResolverTests { .consumeNextWith(value -> { boolean condition = value instanceof Optional; assertThat(condition).isTrue(); - assertThat(((Optional) value).isPresent()).isFalse(); + assertThat(((Optional) value)).isNotPresent(); }) .expectComplete() .verify(); 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 27ba786d6e1..4cf086b70ed 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -121,7 +121,7 @@ public class RequestAttributeMethodArgumentResolverTests { assertThat(mono.block()).isNotNull(); assertThat(mono.block().getClass()).isEqualTo(Optional.class); - assertThat(((Optional) mono.block()).isPresent()).isFalse(); + assertThat(((Optional) mono.block())).isNotPresent(); ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); initializer.setConversionService(new DefaultFormattingConversionService()); @@ -134,7 +134,7 @@ public class RequestAttributeMethodArgumentResolverTests { assertThat(mono.block()).isNotNull(); assertThat(mono.block().getClass()).isEqualTo(Optional.class); Optional optional = (Optional) mono.block(); - assertThat(optional.isPresent()).isTrue(); + assertThat(optional).isPresent(); assertThat(optional.get()).isSameAs(foo); } 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 d124bf31a84..fa4de13e40b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -206,7 +206,7 @@ public class RequestParamMethodArgumentResolverTests { assertThat(result.getClass()).isEqualTo(Optional.class); Optional value = (Optional) result; - assertThat(value.isPresent()).isTrue(); + assertThat(value).isPresent(); assertThat(value.get()).isEqualTo(123); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityExceptionHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityExceptionHandlerTests.java index ab10e4ce6a6..9394443518f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityExceptionHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityExceptionHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -184,7 +184,7 @@ public class ResponseEntityExceptionHandlerTests { ResponseEntity entity = this.exceptionHandler.handleException(exception, this.exchange).block(); assertThat(entity).isNotNull(); assertThat(entity.getStatusCode()).isEqualTo(exception.getStatusCode()); - assertThat(entity.getBody()).isNotNull().isInstanceOf(ProblemDetail.class); + assertThat(entity.getBody()).isInstanceOf(ProblemDetail.class); return (ResponseEntity) entity; } 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 51d00f4b5b1..5e4093810aa 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 @@ -116,7 +116,7 @@ class SessionAttributeMethodArgumentResolverTests { .resolveArgument(param, new BindingContext(), this.exchange).block(); assertThat(actual).isNotNull(); - assertThat(actual.isPresent()).isFalse(); + assertThat(actual).isNotPresent(); ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); initializer.setConversionService(new DefaultFormattingConversionService()); 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 c9c775e6234..1c02ffacca2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,7 +75,7 @@ public class HttpMessageWriterViewTests { this.view.setModelKeys(Collections.singleton("foo2")); this.model.addAttribute("foo1", "bar1"); - assertThat(doRender()).isEqualTo(""); + assertThat(doRender()).isEmpty(); } @Test @@ -84,7 +84,7 @@ public class HttpMessageWriterViewTests { this.view.setModelKeys(new HashSet<>(Collections.singletonList("foo1"))); this.model.addAttribute("foo1", "bar1"); - assertThat(doRender()).isEqualTo(""); + assertThat(doRender()).isEmpty(); } @Test 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 d739a3af1c7..5f4a9fc1f1b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -219,7 +219,7 @@ class WebSocketIntegrationTests extends AbstractReactiveWebSocketIntegrationTest public Mono handle(WebSocketSession session) { return Mono.deferContextual(contextView -> { String key = ServerWebExchangeContextFilter.EXCHANGE_CONTEXT_ATTRIBUTE; - assertThat(contextView.getOrEmpty(key).orElse(null)).isNotNull(); + assertThat(contextView.getOrEmpty(key)).isPresent(); return session.send(session.receive().map(WebSocketMessage::retain)); }); } 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 2b6863bacea..82c092301e2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,7 +72,8 @@ class ContextLoaderTests { WebApplicationContext context = (WebApplicationContext) sc.getAttribute(contextAttr); boolean condition1 = context instanceof XmlWebApplicationContext; assertThat(condition1).as("Correct WebApplicationContext exposed in ServletContext").isTrue(); - assertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(sc) instanceof XmlWebApplicationContext).isTrue(); + assertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(sc)).isInstanceOf( + XmlWebApplicationContext.class); LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle"); assertThat(context.containsBean("father")).as("Has father").isTrue(); assertThat(context.containsBean("rod")).as("Has rod").isTrue(); @@ -308,8 +309,8 @@ class ContextLoaderTests { 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(); + assertThat(((TestBean) context.getBean("rod")).getSpouse()).as("Doesn't have spouse").isNull(); + assertThat(((TestBean) context.getBean("rod")).getName()).as("myinit not evaluated").isEqualTo("Roderick"); context = new ClassPathXmlApplicationContext(new String[] { "/org/springframework/web/context/WEB-INF/applicationContext.xml", 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 d0ce3e8d8fe..8f1dca1d460 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -113,22 +113,22 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> wac.getMessage("someMessage", null, Locale.getDefault())); String msg = wac.getMessage("someMessage", null, "default", Locale.getDefault()); - assertThat("default".equals(msg)).as("Default message returned").isTrue(); + assertThat(msg).as("Default message returned").isEqualTo("default"); } @Test public void contextNesting() { TestBean father = (TestBean) this.applicationContext.getBean("father"); - assertThat(father != null).as("Bean from root context").isTrue(); + assertThat(father).as("Bean from root context").isNotNull(); assertThat(father.getFriends().contains("myFriend")).as("Custom BeanPostProcessor applied").isTrue(); TestBean rod = (TestBean) this.applicationContext.getBean("rod"); - 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(); + assertThat(rod.getName()).as("Bean from child context").isEqualTo("Rod"); + assertThat(rod.getSpouse()).as("Bean has external reference").isSameAs(father); + assertThat(rod.getFriends().contains("myFriend")).as("Custom BeanPostProcessor not applied").isFalse(); rod = (TestBean) this.root.getBean("rod"); - assertThat("Roderick".equals(rod.getName())).as("Bean from root context").isTrue(); + assertThat(rod.getName()).as("Bean from root context").isEqualTo("Roderick"); assertThat(rod.getFriends().contains("myFriend")).as("Custom BeanPostProcessor applied").isTrue(); } 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 8937ea0e1e3..9d3b1c8cd6b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -118,16 +118,18 @@ public class DispatcherServletTests { @Test public void configuredDispatcherServlets() { - 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(); + assertThat((simpleDispatcherServlet.getNamespace())).as("Correct namespace") + .isEqualTo("simple" + FrameworkServlet.DEFAULT_NAMESPACE_SUFFIX); + assertThat((FrameworkServlet.SERVLET_CONTEXT_PREFIX + "simple")).as("Correct attribute") + .isEqualTo(simpleDispatcherServlet.getServletContextAttributeName()); + assertThat(simpleDispatcherServlet.getWebApplicationContext()).as("Context published") + .isSameAs(getServletContext().getAttribute(FrameworkServlet.SERVLET_CONTEXT_PREFIX + "simple")); - 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(); + assertThat(complexDispatcherServlet.getNamespace()).as("Correct namespace").isEqualTo("test"); + assertThat((FrameworkServlet.SERVLET_CONTEXT_PREFIX + "complex")).as("Correct attribute") + .isEqualTo(complexDispatcherServlet.getServletContextAttributeName()); + assertThat(getServletContext().getAttribute(FrameworkServlet.SERVLET_CONTEXT_PREFIX + "complex")).as("Context not published") + .isNull(); simpleDispatcherServlet.destroy(); complexDispatcherServlet.destroy(); @@ -138,8 +140,8 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/invalid.do"); MockHttpServletResponse response = new MockHttpServletResponse(); simpleDispatcherServlet.service(request, response); - assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); - assertThat(response.getStatus() == HttpServletResponse.SC_NOT_FOUND).as("correct error code").isTrue(); + assertThat(response.getForwardedUrl()).as("Not forwarded").isNull(); + assertThat(response.getStatus()).as("correct error code").isEqualTo(HttpServletResponse.SC_NOT_FOUND); } @Test @@ -150,7 +152,7 @@ public class DispatcherServletTests { ComplexWebApplicationContext.TestApplicationListener listener = (ComplexWebApplicationContext.TestApplicationListener) complexDispatcherServlet .getWebApplicationContext().getBean("testListener"); - assertThat(listener.counter).isEqualTo(1); + assertThat(listener.counter).isOne(); } @Test @@ -181,7 +183,7 @@ public class DispatcherServletTests { request.addParameter("noView", "true"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); + assertThat(response.getForwardedUrl()).as("Not forwarded").isNull(); } @Test @@ -190,7 +192,7 @@ public class DispatcherServletTests { request.addPreferredLocale(Locale.CANADA); MockHttpServletResponse response = new MockHttpServletResponse(); simpleDispatcherServlet.service(request, response); - assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); + assertThat(response.getForwardedUrl()).as("Not forwarded").isNull(); assertThat(response.getHeader("Last-Modified")).isEqualTo("Wed, 01 Apr 2015 00:00:00 GMT"); } @@ -211,16 +213,16 @@ public class DispatcherServletTests { MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - 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.getForwardedUrl()).as("Not forwarded").isNull(); + assertThat(request.getAttribute("test1")).isNotNull(); + assertThat(request.getAttribute("test1x")).isNull(); + assertThat(request.getAttribute("test1y")).isNull(); + assertThat(request.getAttribute("test2")).isNotNull(); + assertThat(request.getAttribute("test2x")).isNull(); + assertThat(request.getAttribute("test2y")).isNull(); + assertThat(request.getAttribute("test3")).isNotNull(); + assertThat(request.getAttribute("test3x")).isNotNull(); + assertThat(request.getAttribute("test3y")).isNotNull(); assertThat(response.getHeader("Last-Modified")).isEqualTo("Wed, 01 Apr 2015 00:00:01 GMT"); } @@ -278,13 +280,13 @@ public class DispatcherServletTests { request.addUserRole("role1"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - 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(response.getForwardedUrl()).as("Not forwarded").isNull(); + assertThat(request.getAttribute("test1")).isNotNull(); + assertThat(request.getAttribute("test1x")).isNotNull(); + assertThat(request.getAttribute("test1y")).isNull(); + assertThat(request.getAttribute("test2")).isNull(); + assertThat(request.getAttribute("test2x")).isNull(); + assertThat(request.getAttribute("test2y")).isNull(); } @Test @@ -309,7 +311,8 @@ public class DispatcherServletTests { complexDispatcherServlet.service(request, response); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getForwardedUrl()).as("forwarded URL").isEqualTo("failed2.jsp"); - assertThat(request.getAttribute("exception") instanceof IllegalAccessException).as("Exception exposed").isTrue(); + assertThat(request.getAttribute("exception")).as("Exception exposed") + .isInstanceOf(IllegalAccessException.class); } @Test @@ -322,7 +325,7 @@ public class DispatcherServletTests { complexDispatcherServlet.service(request, response); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getForwardedUrl()).as("forwarded URL").isEqualTo("failed3.jsp"); - assertThat(request.getAttribute("exception") instanceof ServletException).as("Exception exposed").isTrue(); + assertThat(request.getAttribute("exception")).as("Exception exposed").isInstanceOf(ServletException.class); } @Test @@ -335,7 +338,8 @@ public class DispatcherServletTests { complexDispatcherServlet.service(request, response); assertThat(response.getStatus()).isEqualTo(500); assertThat(response.getForwardedUrl()).as("forwarded URL").isEqualTo("failed1.jsp"); - assertThat(request.getAttribute("exception") instanceof IllegalAccessException).as("Exception exposed").isTrue(); + assertThat(request.getAttribute("exception")).as("Exception exposed") + .isInstanceOf(IllegalAccessException.class); } @Test @@ -348,7 +352,7 @@ public class DispatcherServletTests { complexDispatcherServlet.service(request, response); assertThat(response.getStatus()).isEqualTo(500); assertThat(response.getForwardedUrl()).as("forwarded URL").isEqualTo("failed1.jsp"); - assertThat(request.getAttribute("exception") instanceof ServletException).as("Exception exposed").isTrue(); + assertThat(request.getAttribute("exception")).as("Exception exposed").isInstanceOf(ServletException.class); } @Test @@ -386,7 +390,7 @@ public class DispatcherServletTests { request.addParameter("locale2", "en_CA"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); + assertThat(response.getForwardedUrl()).as("Not forwarded").isNull(); } @Test @@ -411,7 +415,7 @@ public class DispatcherServletTests { request.addParameter("theme2", "theme"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue(); + assertThat(response.getForwardedUrl()).as("Not forwarded").isNull(); } @Test @@ -420,7 +424,7 @@ public class DispatcherServletTests { request.addPreferredLocale(Locale.CANADA); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertThat(response.getStatus() == HttpServletResponse.SC_FORBIDDEN).as("Correct response").isTrue(); + assertThat(response.getStatus()).as("Correct response").isEqualTo(HttpServletResponse.SC_FORBIDDEN); } @Test @@ -433,7 +437,7 @@ public class DispatcherServletTests { request = new MockHttpServletRequest(getServletContext(), "GET", "/head.do"); response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertThat(response.getContentAsString()).isEqualTo(""); + assertThat(response.getContentAsString()).isEmpty(); } @Test @@ -460,7 +464,7 @@ public class DispatcherServletTests { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do"); MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertThat(response.getStatus() == HttpServletResponse.SC_NOT_FOUND).isTrue(); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_NOT_FOUND); } @Test @@ -503,7 +507,8 @@ public class DispatcherServletTests { MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertThat(response.getStatus() == HttpServletResponse.SC_NOT_FOUND).as("Matched through parent controller/handler pair: not response=" + response.getStatus()).isFalse(); + assertThat(response.getStatus()).as("Matched through parent controller/handler pair: not response=" + response.getStatus()) + .isNotEqualTo(HttpServletResponse.SC_NOT_FOUND); } @Test @@ -593,7 +598,7 @@ public class DispatcherServletTests { MockHttpServletResponse response = new MockHttpServletResponse(); complexDispatcherServlet.service(request, response); - assertThat(response.getStatus() == HttpServletResponse.SC_NOT_FOUND).as("correct error code").isTrue(); + assertThat(response.getStatus()).as("correct error code").isEqualTo(HttpServletResponse.SC_NOT_FOUND); } // SPR-12984 @@ -603,8 +608,8 @@ public class DispatcherServletTests { HttpHeaders headers = new HttpHeaders(); headers.add("foo", "bar"); NoHandlerFoundException ex = new NoHandlerFoundException("GET", "/foo", headers); - assertThat(!ex.getMessage().contains("bar")).isTrue(); - assertThat(!ex.toString().contains("bar")).isTrue(); + assertThat(ex.getMessage()).doesNotContain("bar"); + assertThat(ex.toString()).doesNotContain("bar"); } @Test @@ -791,10 +796,10 @@ public class DispatcherServletTests { (ServletConfigAwareBean) servlet.getWebApplicationContext().getBean("servletConfigAwareBean"); assertThat(contextBean2.getServletContext()).isSameAs(servletContext); assertThat(configBean2.getServletConfig()).isSameAs(servlet.getServletConfig()); - assertThat(contextBean != contextBean2).isTrue(); - assertThat(configBean != configBean2).isTrue(); + assertThat(contextBean).isNotSameAs(contextBean2); + assertThat(configBean).isNotSameAs(configBean2); MultipartResolver multipartResolver2 = servlet.getMultipartResolver(); - assertThat(multipartResolver != multipartResolver2).isTrue(); + assertThat(multipartResolver).isNotSameAs(multipartResolver2); servlet.destroy(); } 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 d46a84fa6ac..b789cee54f8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -120,13 +120,13 @@ public class AnnotationDrivenBeanDefinitionParserTests { assertThat(bean).isNotNull(); Object value = new DirectFieldAccessor(bean).getPropertyValue("customArgumentResolvers"); assertThat(value).isNotNull(); - assertThat(value instanceof List).isTrue(); + assertThat(value).isInstanceOf(List.class); @SuppressWarnings("unchecked") List resolvers = (List) value; assertThat(resolvers).hasSize(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(0)).isInstanceOf(ServletWebArgumentResolverAdapter.class); + assertThat(resolvers.get(1)).isInstanceOf(TestHandlerMethodArgumentResolver.class); + assertThat(resolvers.get(2)).isInstanceOf(TestHandlerMethodArgumentResolver.class); assertThat(resolvers.get(2)).isNotSameAs(resolvers.get(1)); } @@ -141,7 +141,7 @@ public class AnnotationDrivenBeanDefinitionParserTests { assertThat(bean).isNotNull(); Object value = new DirectFieldAccessor(bean).getPropertyValue("customReturnValueHandlers"); assertThat(value).isNotNull(); - assertThat(value instanceof List).isTrue(); + assertThat(value).isInstanceOf(List.class); @SuppressWarnings("unchecked") List handlers = (List) value; assertThat(handlers).hasSize(2); @@ -170,16 +170,16 @@ public class AnnotationDrivenBeanDefinitionParserTests { assertThat(bean).isNotNull(); Object value = new DirectFieldAccessor(bean).getPropertyValue("messageConverters"); assertThat(value).isNotNull(); - assertThat(value instanceof List).isTrue(); + assertThat(value).isInstanceOf(List.class); List> converters = (List>) value; if (hasDefaultRegistrations) { - assertThat(converters.size() > 2).as("Default and custom converter expected").isTrue(); + assertThat(converters.size()).as("Default and custom converter expected").isGreaterThan(2); } else { - assertThat(converters.size() == 2).as("Only custom converters expected").isTrue(); + assertThat(converters.size()).as("Only custom converters expected").isEqualTo(2); } - assertThat(converters.get(0) instanceof StringHttpMessageConverter).isTrue(); - assertThat(converters.get(1) instanceof ResourceHttpMessageConverter).isTrue(); + assertThat(converters.get(0)).isInstanceOf(StringHttpMessageConverter.class); + assertThat(converters.get(1)).isInstanceOf(ResourceHttpMessageConverter.class); } @SuppressWarnings("unchecked") @@ -187,9 +187,9 @@ public class AnnotationDrivenBeanDefinitionParserTests { assertThat(bean).isNotNull(); Object value = new DirectFieldAccessor(bean).getPropertyValue("responseBodyAdvice"); assertThat(value).isNotNull(); - assertThat(value instanceof List).isTrue(); + assertThat(value).isInstanceOf(List.class); List> converters = (List>) value; - assertThat(converters.get(0) instanceof JsonViewResponseBodyAdvice).isTrue(); + assertThat(converters.get(0)).isInstanceOf(JsonViewResponseBodyAdvice.class); } @SuppressWarnings("unchecked") @@ -197,7 +197,7 @@ public class AnnotationDrivenBeanDefinitionParserTests { assertThat(bean).isNotNull(); Object value = new DirectFieldAccessor(bean).getPropertyValue("requestResponseBodyAdvice"); assertThat(value).isNotNull(); - assertThat(value instanceof List).isTrue(); + assertThat(value).isInstanceOf(List.class); List> converters = (List>) value; 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 753d50a609b..9e8db46a020 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -215,7 +215,7 @@ public class MvcNamespaceTests { .asInstanceOf(BOOLEAN).isTrue(); List> converters = adapter.getMessageConverters(); - assertThat(converters.size() > 0).isTrue(); + assertThat(converters.size()).isGreaterThan(0); for (HttpMessageConverter converter : converters) { if (converter instanceof AbstractJackson2HttpMessageConverter) { ObjectMapper objectMapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper(); @@ -245,7 +245,7 @@ public class MvcNamespaceTests { HandlerExecutionChain chain = mapping.getHandler(request); assertThat(chain.getInterceptorList()).hasSize(1); - assertThat(chain.getInterceptorList().get(0) instanceof ConversionServiceExposingInterceptor).isTrue(); + assertThat(chain.getInterceptorList().get(0)).isInstanceOf(ConversionServiceExposingInterceptor.class); ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptorList().get(0); interceptor.preHandle(request, response, handlerMethod); assertThat(request.getAttribute(ConversionService.class.getName())).isSameAs(appContext.getBean(ConversionService.class)); @@ -302,7 +302,7 @@ public class MvcNamespaceTests { HandlerExecutionChain chain = mapping.getHandler(request); assertThat(chain.getInterceptorList()).hasSize(1); - assertThat(chain.getInterceptorList().get(0) instanceof ConversionServiceExposingInterceptor).isTrue(); + assertThat(chain.getInterceptorList().get(0)).isInstanceOf(ConversionServiceExposingInterceptor.class); ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptorList().get(0); interceptor.preHandle(request, response, handler); assertThat(request.getAttribute(ConversionService.class.getName())).isSameAs(appContext.getBean("conversionService")); @@ -354,10 +354,10 @@ public class MvcNamespaceTests { HandlerExecutionChain chain = mapping.getHandler(request); assertThat(chain.getInterceptorList()).hasSize(4); - assertThat(chain.getInterceptorList().get(0) instanceof ConversionServiceExposingInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(1) instanceof LocaleChangeInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(2) instanceof ThemeChangeInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(3) instanceof UserRoleAuthorizationInterceptor).isTrue(); + assertThat(chain.getInterceptorList().get(0)).isInstanceOf(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptorList().get(1)).isInstanceOf(LocaleChangeInterceptor.class); + assertThat(chain.getInterceptorList().get(2)).isInstanceOf(ThemeChangeInterceptor.class); + assertThat(chain.getInterceptorList().get(3)).isInstanceOf(UserRoleAuthorizationInterceptor.class); request.setRequestURI("/admin/users"); chain = mapping.getHandler(request); @@ -411,7 +411,7 @@ public class MvcNamespaceTests { HandlerExecutionChain chain = resourceMapping.getHandler(request); assertThat(chain).isNotNull(); - assertThat(chain.getHandler() instanceof ResourceHttpRequestHandler).isTrue(); + assertThat(chain.getHandler()).isInstanceOf(ResourceHttpRequestHandler.class); MockHttpServletResponse response = new MockHttpServletResponse(); for (HandlerInterceptor interceptor : chain.getInterceptorList()) { @@ -534,7 +534,7 @@ public class MvcNamespaceTests { request.setMethod("GET"); HandlerExecutionChain chain = mapping.getHandler(request); - assertThat(chain.getHandler() instanceof DefaultServletHttpRequestHandler).isTrue(); + assertThat(chain.getHandler()).isInstanceOf(DefaultServletHttpRequestHandler.class); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = adapter.handle(request, response, chain.getHandler()); @@ -560,7 +560,7 @@ public class MvcNamespaceTests { request.setMethod("GET"); HandlerExecutionChain chain = mapping.getHandler(request); - assertThat(chain.getHandler() instanceof DefaultServletHttpRequestHandler).isTrue(); + assertThat(chain.getHandler()).isInstanceOf(DefaultServletHttpRequestHandler.class); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = adapter.handle(request, response, chain.getHandler()); @@ -579,9 +579,9 @@ public class MvcNamespaceTests { HandlerExecutionChain chain = mapping.getHandler(request); assertThat(chain.getInterceptorList()).hasSize(3); - assertThat(chain.getInterceptorList().get(0) instanceof ConversionServiceExposingInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(1) instanceof LocaleChangeInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(2) instanceof ThemeChangeInterceptor).isTrue(); + assertThat(chain.getInterceptorList().get(0)).isInstanceOf(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptorList().get(1)).isInstanceOf(LocaleChangeInterceptor.class); + assertThat(chain.getInterceptorList().get(2)).isInstanceOf(ThemeChangeInterceptor.class); LocaleChangeInterceptor interceptor = (LocaleChangeInterceptor) chain.getInterceptorList().get(1); assertThat(interceptor.getParamName()).isEqualTo("lang"); ThemeChangeInterceptor interceptor2 = (ThemeChangeInterceptor) chain.getInterceptorList().get(2); @@ -605,9 +605,9 @@ public class MvcNamespaceTests { HandlerExecutionChain chain = mapping.getHandler(request); assertThat(chain.getInterceptorList()).hasSize(3); - assertThat(chain.getInterceptorList().get(0) instanceof ConversionServiceExposingInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(1) instanceof LocaleChangeInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(2) instanceof ThemeChangeInterceptor).isTrue(); + assertThat(chain.getInterceptorList().get(0)).isInstanceOf(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptorList().get(1)).isInstanceOf(LocaleChangeInterceptor.class); + assertThat(chain.getInterceptorList().get(2)).isInstanceOf(ThemeChangeInterceptor.class); SimpleUrlHandlerMapping mapping2 = appContext.getBean(SimpleUrlHandlerMapping.class); assertThat(mapping2).isNotNull(); @@ -618,9 +618,9 @@ public class MvcNamespaceTests { request = new MockHttpServletRequest("GET", "/foo"); chain = mapping2.getHandler(request); assertThat(chain.getInterceptorList()).hasSize(4); - assertThat(chain.getInterceptorList().get(1) instanceof ConversionServiceExposingInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(2) instanceof LocaleChangeInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(3) instanceof ThemeChangeInterceptor).isTrue(); + assertThat(chain.getInterceptorList().get(1)).isInstanceOf(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptorList().get(2)).isInstanceOf(LocaleChangeInterceptor.class); + assertThat(chain.getInterceptorList().get(3)).isInstanceOf(ThemeChangeInterceptor.class); ModelAndView mv = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); assertThat((Object) mv.getViewName()).isNull(); @@ -629,9 +629,9 @@ public class MvcNamespaceTests { request.setServletPath("/app"); chain = mapping2.getHandler(request); assertThat(chain.getInterceptorList()).hasSize(4); - assertThat(chain.getInterceptorList().get(1) instanceof ConversionServiceExposingInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(2) instanceof LocaleChangeInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(3) instanceof ThemeChangeInterceptor).isTrue(); + assertThat(chain.getInterceptorList().get(1)).isInstanceOf(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptorList().get(2)).isInstanceOf(LocaleChangeInterceptor.class); + assertThat(chain.getInterceptorList().get(3)).isInstanceOf(ThemeChangeInterceptor.class); mv = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); assertThat(mv.getViewName()).isEqualTo("baz"); @@ -640,9 +640,9 @@ public class MvcNamespaceTests { request.setServletPath("/app"); chain = mapping2.getHandler(request); assertThat(chain.getInterceptorList()).hasSize(4); - assertThat(chain.getInterceptorList().get(1) instanceof ConversionServiceExposingInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(2) instanceof LocaleChangeInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(3) instanceof ThemeChangeInterceptor).isTrue(); + assertThat(chain.getInterceptorList().get(1)).isInstanceOf(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptorList().get(2)).isInstanceOf(LocaleChangeInterceptor.class); + assertThat(chain.getInterceptorList().get(3)).isInstanceOf(ThemeChangeInterceptor.class); mv = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); assertThat(mv.getViewName()).isEqualTo("root"); @@ -684,9 +684,9 @@ public class MvcNamespaceTests { request.setAttribute("com.ibm.websphere.servlet.uri_non_decoded", "/myapp/app/bar"); HandlerExecutionChain chain = mapping2.getHandler(request); assertThat(chain.getInterceptorList()).hasSize(4); - assertThat(chain.getInterceptorList().get(1) instanceof ConversionServiceExposingInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(2) instanceof LocaleChangeInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(3) instanceof ThemeChangeInterceptor).isTrue(); + assertThat(chain.getInterceptorList().get(1)).isInstanceOf(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptorList().get(2)).isInstanceOf(LocaleChangeInterceptor.class); + assertThat(chain.getInterceptorList().get(3)).isInstanceOf(ThemeChangeInterceptor.class); ModelAndView mv2 = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); assertThat(mv2.getViewName()).isEqualTo("baz"); @@ -696,9 +696,9 @@ public class MvcNamespaceTests { request.setHttpServletMapping(new MockHttpServletMapping("", "", "", MappingMatch.PATH)); chain = mapping2.getHandler(request); assertThat(chain.getInterceptorList()).hasSize(4); - assertThat(chain.getInterceptorList().get(1) instanceof ConversionServiceExposingInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(2) instanceof LocaleChangeInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(3) instanceof ThemeChangeInterceptor).isTrue(); + assertThat(chain.getInterceptorList().get(1)).isInstanceOf(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptorList().get(2)).isInstanceOf(LocaleChangeInterceptor.class); + assertThat(chain.getInterceptorList().get(3)).isInstanceOf(ThemeChangeInterceptor.class); ModelAndView mv3 = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); assertThat(mv3.getViewName()).isEqualTo("root"); @@ -707,9 +707,9 @@ public class MvcNamespaceTests { request.setServletPath("/"); chain = mapping2.getHandler(request); assertThat(chain.getInterceptorList()).hasSize(4); - assertThat(chain.getInterceptorList().get(1) instanceof ConversionServiceExposingInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(2) instanceof LocaleChangeInterceptor).isTrue(); - assertThat(chain.getInterceptorList().get(3) instanceof ThemeChangeInterceptor).isTrue(); + assertThat(chain.getInterceptorList().get(1)).isInstanceOf(ConversionServiceExposingInterceptor.class); + assertThat(chain.getInterceptorList().get(2)).isInstanceOf(LocaleChangeInterceptor.class); + assertThat(chain.getInterceptorList().get(3)).isInstanceOf(ThemeChangeInterceptor.class); mv3 = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); assertThat(mv3.getViewName()).isEqualTo("root"); } 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 85b473e8d77..0278d8eb509 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 @@ -140,7 +140,7 @@ public class DelegatingWebMvcConfigurationTests { this.webMvcConfig.mvcConversionService(), this.webMvcConfig.mvcValidator()); - assertThat(adapter.getMessageConverters().size()).as("One custom converter expected").isEqualTo(2); + assertThat(adapter.getMessageConverters()).as("One custom converter expected").hasSize(2); assertThat(adapter.getMessageConverters().get(0)).isSameAs(customConverter); assertThat(adapter.getMessageConverters().get(1)).isSameAs(stringConverter); } @@ -181,7 +181,7 @@ public class DelegatingWebMvcConfigurationTests { assertThat(condition1).isTrue(); boolean condition = exceptionResolvers.getValue().get(2) instanceof DefaultHandlerExceptionResolver; assertThat(condition).isTrue(); - assertThat(converters.getValue().size() > 0).isTrue(); + assertThat(converters.getValue()).isNotEmpty(); } @Test @@ -198,9 +198,8 @@ public class DelegatingWebMvcConfigurationTests { (HandlerExceptionResolverComposite) webMvcConfig .handlerExceptionResolver(webMvcConfig.mvcContentNegotiationManager()); - assertThat(composite.getExceptionResolvers().size()) - .as("Only one custom converter is expected") - .isEqualTo(1); + assertThat(composite.getExceptionResolvers()) + .as("Only one custom converter is expected").hasSize(1); } @Test 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 84395055173..30707f1a8ec 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 @@ -111,7 +111,7 @@ class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertThat(request.attribute("foo")).isEqualTo(Optional.of("bar")); + assertThat(request.attribute("foo")).contains("bar"); } @Test @@ -121,7 +121,7 @@ class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertThat(request.param("foo")).isEqualTo(Optional.of("bar")); + assertThat(request.param("foo")).contains("bar"); } @Test @@ -149,7 +149,7 @@ class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertThat(request.param("foo")).isEqualTo(Optional.of("")); + assertThat(request.param("foo")).contains(""); } @Test @@ -159,7 +159,7 @@ class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertThat(request.param("bar")).isEqualTo(Optional.empty()); + assertThat(request.param("bar")).isNotPresent(); } @Test @@ -221,7 +221,7 @@ class DefaultServerRequestTests { 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.contentType()).contains(contentType); assertThat(headers.header(HttpHeaders.CONTENT_TYPE)).containsExactly(MediaType.TEXT_PLAIN_VALUE); assertThat(headers.firstHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo(MediaType.TEXT_PLAIN_VALUE); assertThat(headers.asHttpHeaders()).isEqualTo(httpHeaders); @@ -301,7 +301,7 @@ class DefaultServerRequestTests { DefaultServerRequest request = new DefaultServerRequest(servletRequest, this.messageConverters); - assertThat(request.principal().get()).isEqualTo(principal); + assertThat(request.principal()).contains(principal); } @ParameterizedHttpMethodTest 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 ef82052bc52..33ad38b0ba7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ class PathResourceLookupFunctionTests { ServerRequest request = initRequest("GET", "/resources/response.txt"); Optional result = function.apply(request); - assertThat(result.isPresent()).isTrue(); + assertThat(result).isPresent(); File expected = new ClassPathResource("response.txt", getClass()).getFile(); assertThat(result.get().getFile()).isEqualTo(expected); @@ -54,7 +54,7 @@ class PathResourceLookupFunctionTests { ServerRequest request = initRequest("GET", "/resources/child/response.txt"); Optional result = function.apply(request); - assertThat(result.isPresent()).isTrue(); + assertThat(result).isPresent(); File expected = new ClassPathResource("org/springframework/web/servlet/function/child/response.txt").getFile(); assertThat(result.get().getFile()).isEqualTo(expected); @@ -67,7 +67,7 @@ class PathResourceLookupFunctionTests { ServerRequest request = initRequest("GET", "/resources/foo.txt"); Optional result = function.apply(request); - assertThat(result.isPresent()).isFalse(); + assertThat(result).isNotPresent(); } @Test @@ -91,7 +91,7 @@ class PathResourceLookupFunctionTests { ServerRequest request = initRequest("GET", "/resources/foo"); Optional result = customLookupFunction.apply(request); - assertThat(result.isPresent()).isTrue(); + assertThat(result).isPresent(); assertThat(result.get().getFile()).isEqualTo(defaultResource.getFile()); } 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 e175051a5af..3a0f2213565 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,8 +50,8 @@ class RouterFunctionTests { assertThat(result).isNotNull(); Optional> resultHandlerFunction = result.route(request); - assertThat(resultHandlerFunction.isPresent()).isTrue(); - assertThat(resultHandlerFunction.get()).isEqualTo(handlerFunction); + assertThat(resultHandlerFunction).isPresent(); + assertThat(resultHandlerFunction).contains(handlerFunction); } @@ -65,7 +65,7 @@ class RouterFunctionTests { assertThat(result).isNotNull(); Optional> resultHandlerFunction = result.route(request); - assertThat(resultHandlerFunction.isPresent()).isTrue(); + assertThat(resultHandlerFunction).isPresent(); assertThat(resultHandlerFunction.get()).isEqualTo(handlerFunction); } @@ -79,7 +79,7 @@ class RouterFunctionTests { assertThat(result).isNotNull(); Optional> resultHandlerFunction = result.route(request); - assertThat(resultHandlerFunction.isPresent()).isTrue(); + assertThat(resultHandlerFunction).isPresent(); } @@ -110,7 +110,7 @@ class RouterFunctionTests { throw new AssertionError(ex.getMessage(), ex); } }); - assertThat(resultHandlerFunction.isPresent()).isTrue(); + assertThat(resultHandlerFunction).isPresent(); 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 5cf2606bbbc..d4dc9caf2b2 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 @@ -49,8 +49,8 @@ public class RouterFunctionsTests { assertThat(result).isNotNull(); Optional> resultHandlerFunction = result.route(request); - assertThat(resultHandlerFunction.isPresent()).isTrue(); - assertThat(resultHandlerFunction.get()).isEqualTo(handlerFunction); + assertThat(resultHandlerFunction).isPresent(); + assertThat(resultHandlerFunction).contains(handlerFunction); } @Test @@ -64,7 +64,7 @@ public class RouterFunctionsTests { assertThat(result).isNotNull(); Optional> resultHandlerFunction = result.route(request); - assertThat(resultHandlerFunction.isPresent()).isFalse(); + assertThat(resultHandlerFunction).isNotPresent(); } @Test @@ -79,8 +79,8 @@ public class RouterFunctionsTests { assertThat(result).isNotNull(); Optional> resultHandlerFunction = result.route(request); - assertThat(resultHandlerFunction.isPresent()).isTrue(); - assertThat(resultHandlerFunction.get()).isEqualTo(handlerFunction); + assertThat(resultHandlerFunction).isPresent(); + assertThat(resultHandlerFunction).contains(handlerFunction); } @Test @@ -95,7 +95,7 @@ public class RouterFunctionsTests { assertThat(result).isNotNull(); Optional> resultHandlerFunction = result.route(request); - assertThat(resultHandlerFunction.isPresent()).isFalse(); + assertThat(resultHandlerFunction).isNotPresent(); } @Test @@ -110,8 +110,8 @@ public class RouterFunctionsTests { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/bar"); ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList()); Optional> resultHandlerFunction = result.route(request); - assertThat(resultHandlerFunction.isPresent()).isTrue(); - assertThat(resultHandlerFunction.get()).isEqualTo(handlerFunction); + assertThat(resultHandlerFunction).isPresent(); + assertThat(resultHandlerFunction).contains(handlerFunction); } } 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 61de1b06168..9f957ad3c98 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,11 +57,11 @@ public class BeanNameUrlHandlerMappingTests { MockHttpServletRequest req = new MockHttpServletRequest("GET", "/myapp/mypath/nonsense.html"); req.setContextPath("/myapp"); Object h = hm.getHandler(req); - assertThat(h == null).as("Handler is null").isTrue(); + assertThat(h).as("Handler is null").isNull(); req = new MockHttpServletRequest("GET", "/foo/bar/baz.html"); h = hm.getHandler(req); - assertThat(h == null).as("Handler is null").isTrue(); + assertThat(h).as("Handler is null").isNull(); } @Test @@ -170,7 +170,7 @@ public class BeanNameUrlHandlerMappingTests { req = new MockHttpServletRequest("GET", "/mypath/tes"); hec = hm.getHandler(req); - assertThat(hec == null).as("Handler is correct bean").isTrue(); + assertThat(hec).as("Handler is correct bean").isNull(); } @Test @@ -190,7 +190,7 @@ public class BeanNameUrlHandlerMappingTests { req = new MockHttpServletRequest("GET", "/mypath/tes"); hec = hm.getHandler(req); - assertThat(hec == null).as("Handler is correct bean").isTrue(); + assertThat(hec).as("Handler is correct bean").isNull(); } @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 4c988f1a7fd..0ec6fd054f6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,15 +68,15 @@ public class PathMatchingUrlHandlerMappingTests { MockHttpServletRequest req = new MockHttpServletRequest("GET", "/welcome.html"); HandlerExecutionChain hec = getHandler(mapping, wac, req); - assertThat(hec.getHandler() == bean).isTrue(); + assertThat(hec.getHandler()).isSameAs(bean); req = new MockHttpServletRequest("GET", "/show.html"); hec = getHandler(mapping, wac, req); - assertThat(hec.getHandler() == bean).isTrue(); + assertThat(hec.getHandler()).isSameAs(bean); req = new MockHttpServletRequest("GET", "/bookseats.html"); hec = getHandler(mapping, wac, req); - assertThat(hec.getHandler() == bean).isTrue(); + assertThat(hec.getHandler()).isSameAs(bean); } @PathPatternsParameterizedTest 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 2a335fef5ac..bb49c98a5eb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -157,7 +157,7 @@ public class SimpleUrlHandlerMappingTests { request = PathPatternsTestUtils.initRequest("GET", "/somePath", usePathPatterns); chain = getHandler(hm, request); - assertThat(chain.getHandler() == defaultBean).as("Handler is correct bean").isTrue(); + assertThat(chain.getHandler()).as("Handler is correct bean").isSameAs(defaultBean); assertThat(request.getAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).isEqualTo("/somePath"); } 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 4b9152b8961..7714cd1b557 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -357,7 +357,7 @@ class CookieLocaleResolverTests { assertThat(cookies).hasSize(1); Cookie localeCookie = cookies[0]; assertThat(localeCookie.getName()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_NAME); - assertThat(localeCookie.getValue()).isEqualTo(""); + assertThat(localeCookie.getValue()).isEmpty(); } @Test @@ -376,7 +376,7 @@ class CookieLocaleResolverTests { assertThat(cookies).hasSize(1); Cookie localeCookie = cookies[0]; assertThat(localeCookie.getName()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_NAME); - assertThat(localeCookie.getValue()).isEqualTo(""); + assertThat(localeCookie.getValue()).isEmpty(); } @Test @@ -394,7 +394,7 @@ class CookieLocaleResolverTests { assertThat(cookies).hasSize(1); Cookie localeCookie = cookies[0]; assertThat(localeCookie.getName()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_NAME); - assertThat(localeCookie.getValue()).isEqualTo(""); + assertThat(localeCookie.getValue()).isEmpty(); } @Test @@ -415,7 +415,7 @@ class CookieLocaleResolverTests { assertThat(cookies).hasSize(1); Cookie localeCookie = cookies[0]; assertThat(localeCookie.getName()).isEqualTo(CookieLocaleResolver.DEFAULT_COOKIE_NAME); - assertThat(localeCookie.getValue()).isEqualTo(""); + assertThat(localeCookie.getValue()).isEmpty(); } @Test 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 febb0b9ff70..c65b2265b15 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 @@ -52,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()); - 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(); + assertThat(mv.getModel()).as("model has no data").isEmpty(); + assertThat(mv.getViewName()).as("model has correct viewname").isEqualTo(viewName); + assertThat(pvc.getViewName()).as("getViewName matches").isEqualTo(viewName); } @Test 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 b61271525a1..2719d65f373 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -154,8 +154,7 @@ class UrlFilenameViewControllerTests { .as("For setPrefix(..) with null, the empty string must be used instead.") .isNotNull(); assertThat(controller.getPrefix()) - .as("For setPrefix(..) with null, the empty string must be used instead.") - .isEqualTo(""); + .as("For setPrefix(..) with null, the empty string must be used instead.").isEmpty(); } @Test @@ -166,8 +165,7 @@ class UrlFilenameViewControllerTests { .as("For setPrefix(..) with null, the empty string must be used instead.") .isNotNull(); assertThat(controller.getSuffix()) - .as("For setPrefix(..) with null, the empty string must be used instead.") - .isEqualTo(""); + .as("For setPrefix(..) with null, the empty string must be used instead.").isEmpty(); } /** diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/WebContentInterceptorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/WebContentInterceptorTests.java index 32058dd2fac..7aab8ea0385 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/WebContentInterceptorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/WebContentInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -110,8 +110,8 @@ class WebContentInterceptorTests { interceptor.setCacheSeconds(10); interceptor.preHandle(requestFactory.apply("/"), response, handler); - assertThat(response.getHeader("Pragma")).isEqualTo(""); - assertThat(response.getHeader("Expires")).isEqualTo(""); + assertThat(response.getHeader("Pragma")).isEmpty(); + assertThat(response.getHeader("Expires")).isEmpty(); } @SuppressWarnings("deprecation") @@ -124,8 +124,8 @@ class WebContentInterceptorTests { interceptor.setAlwaysMustRevalidate(true); interceptor.preHandle(requestFactory.apply("/"), response, handler); - assertThat(response.getHeader("Pragma")).isEqualTo(""); - assertThat(response.getHeader("Expires")).isEqualTo(""); + assertThat(response.getHeader("Pragma")).isEmpty(); + assertThat(response.getHeader("Expires")).isEmpty(); } @SuppressWarnings("deprecation") 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 8d15791efd1..57ce2175960 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -162,10 +162,10 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition("text/*"); int result = condition1.compareTo(condition2, request); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, request); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); } @Test @@ -176,10 +176,10 @@ public class ConsumesRequestConditionTests { ConsumesRequestCondition condition2 = new ConsumesRequestCondition("text/*", "text/plain;q=0.7"); int result = condition1.compareTo(condition2, request); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, request); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); } 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 c55d34e0ab6..6ac85df48aa 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -124,10 +124,10 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition2 = new HeadersRequestCondition("foo=a", "bar"); int result = condition1.compareTo(condition2, request); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, request); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); } @Test // SPR-16674 @@ -138,10 +138,10 @@ public class HeadersRequestConditionTests { HeadersRequestCondition condition2 = new HeadersRequestCondition("foo"); int result = condition1.compareTo(condition2, request); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, request); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); } @Test 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 c586b68ba3d..13d8edfb0d1 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,10 +96,10 @@ public class ParamsRequestConditionTests { ParamsRequestCondition condition2 = new ParamsRequestCondition("foo=a", "bar"); int result = condition1.compareTo(condition2, request); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, request); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); } @Test // SPR-16674 @@ -110,7 +110,7 @@ public class ParamsRequestConditionTests { ParamsRequestCondition condition2 = new ParamsRequestCondition("response_type"); int result = condition1.compareTo(condition2, request); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PathPatternsRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PathPatternsRequestConditionTests.java index ccaf197d099..d4ecdf81f31 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PathPatternsRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PathPatternsRequestConditionTests.java @@ -43,8 +43,7 @@ public class PathPatternsRequestConditionTests { @Test void prependNonEmptyPatternsOnly() { assertThat(createCondition("").getPatternValues().iterator().next()) - .as("Do not prepend empty patterns (SPR-8255)") - .isEqualTo(""); + .as("Do not prepend empty patterns (SPR-8255)").isEmpty(); } @Test 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 33809b93eca..3337cc0b7b8 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 @@ -42,8 +42,7 @@ class PatternsRequestConditionTests { @Test void prependNonEmptyPatternsOnly() { assertThat(new PatternsRequestCondition("").getPatterns().iterator().next()) - .as("Do not prepend empty patterns (SPR-8255)") - .isEqualTo(""); + .as("Do not prepend empty patterns (SPR-8255)").isEmpty(); } @Test 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 5ba72248336..04e085a8960 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 @@ -175,17 +175,17 @@ public class ProducesRequestConditionTests { HttpServletRequest request = createRequest("application/xml, text/html"); - 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(); + assertThat(html.compareTo(xml, request)).isGreaterThan(0); + assertThat(xml.compareTo(html, request)).isLessThan(0); + assertThat(xml.compareTo(none, request)).isLessThan(0); + assertThat(none.compareTo(xml, request)).isGreaterThan(0); + assertThat(html.compareTo(none, request)).isLessThan(0); + assertThat(none.compareTo(html, request)).isGreaterThan(0); request = createRequest("application/xml, text/*"); - assertThat(html.compareTo(xml, request) > 0).isTrue(); - assertThat(xml.compareTo(html, request) < 0).isTrue(); + assertThat(html.compareTo(xml, request)).isGreaterThan(0); + assertThat(xml.compareTo(html, request)).isLessThan(0); request = createRequest("application/pdf"); @@ -195,8 +195,8 @@ public class ProducesRequestConditionTests { // See SPR-7000 request = createRequest("text/html;q=0.9,application/xml"); - assertThat(html.compareTo(xml, request) > 0).isTrue(); - assertThat(xml.compareTo(html, request) < 0).isTrue(); + assertThat(html.compareTo(xml, request)).isGreaterThan(0); + assertThat(xml.compareTo(html, request)).isLessThan(0); } @Test @@ -207,10 +207,10 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition("text/*"); int result = condition1.compareTo(condition2, request); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, request); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); } @Test @@ -235,18 +235,18 @@ public class ProducesRequestConditionTests { HttpServletRequest request = createRequest("text/plain", "application/xml"); int result = condition1.compareTo(condition2, request); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = condition2.compareTo(condition1, request); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); request = createRequest("application/xml", "text/plain"); result = condition1.compareTo(condition2, request); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); result = condition2.compareTo(condition1, request); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); } // SPR-8536 @@ -258,28 +258,30 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition1 = new ProducesRequestCondition(); ProducesRequestCondition condition2 = new ProducesRequestCondition("application/json"); - 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(); + assertThat(condition1.compareTo(condition2, request)).as("Should have picked '*/*' condition as an exact match") + .isLessThan(0); + assertThat(condition2.compareTo(condition1, request)).as("Should have picked '*/*' condition as an exact match") + .isGreaterThan(0); condition1 = new ProducesRequestCondition("*/*"); condition2 = new ProducesRequestCondition("application/json"); - assertThat(condition1.compareTo(condition2, request) < 0).isTrue(); - assertThat(condition2.compareTo(condition1, request) > 0).isTrue(); + assertThat(condition1.compareTo(condition2, request)).isLessThan(0); + assertThat(condition2.compareTo(condition1, request)).isGreaterThan(0); request.addHeader("Accept", "*/*"); condition1 = new ProducesRequestCondition(); condition2 = new ProducesRequestCondition("application/json"); - assertThat(condition1.compareTo(condition2, request) < 0).isTrue(); - assertThat(condition2.compareTo(condition1, request) > 0).isTrue(); + assertThat(condition1.compareTo(condition2, request)).isLessThan(0); + assertThat(condition2.compareTo(condition1, request)).isGreaterThan(0); condition1 = new ProducesRequestCondition("*/*"); condition2 = new ProducesRequestCondition("application/json"); - assertThat(condition1.compareTo(condition2, request) < 0).isTrue(); - assertThat(condition2.compareTo(condition1, request) > 0).isTrue(); + assertThat(condition1.compareTo(condition2, request)).isLessThan(0); + assertThat(condition2.compareTo(condition1, request)).isGreaterThan(0); } // SPR-9021 @@ -291,8 +293,8 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition1 = new ProducesRequestCondition(); ProducesRequestCondition condition2 = new ProducesRequestCondition("application/json"); - assertThat(condition1.compareTo(condition2, request) < 0).isTrue(); - assertThat(condition2.compareTo(condition1, request) > 0).isTrue(); + assertThat(condition1.compareTo(condition2, request)).isLessThan(0); + assertThat(condition2.compareTo(condition1, request)).isGreaterThan(0); } @Test @@ -303,10 +305,10 @@ public class ProducesRequestConditionTests { ProducesRequestCondition condition2 = new ProducesRequestCondition("text/xhtml"); int result = condition1.compareTo(condition2, request); - assertThat(result < 0).as("Should have used MediaType.equals(Object) to break the match").isTrue(); + assertThat(result).as("Should have used MediaType.equals(Object) to break the match").isLessThan(0); result = condition2.compareTo(condition1, request); - assertThat(result > 0).as("Should have used MediaType.equals(Object) to break the match").isTrue(); + assertThat(result).as("Should have used MediaType.equals(Object) to break the match").isGreaterThan(0); } @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 637f423fac0..8efe6c784c7 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -105,13 +105,13 @@ public class RequestMethodsRequestConditionTests { MockHttpServletRequest request = new MockHttpServletRequest(); int result = c1.compareTo(c2, request); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = c2.compareTo(c1, request); - assertThat(result > 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0); result = c2.compareTo(c3, request); - assertThat(result < 0).as("Invalid comparison result: " + result).isTrue(); + assertThat(result).as("Invalid comparison result: " + result).isLessThan(0); result = c1.compareTo(c1, request); assertThat(result).as("Invalid comparison result ").isEqualTo(0); 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 1f640ebb3ee..bca7f56f174 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 @@ -363,7 +363,7 @@ class RequestMappingInfoHandlerMappingTests { assertThat(matrixVariables).isNull(); assertThat(uriVariables.get("cars")).isEqualTo("cars"); - assertThat(uriVariables.get("params")).isEqualTo(""); + assertThat(uriVariables.get("params")).isEmpty(); // SPR-11897 request = new MockHttpServletRequest("GET", "/a=42;b=c"); 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 55fb21d0fbd..516ee649b72 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 @@ -128,7 +128,7 @@ public abstract class AbstractRequestAttributesArgumentResolverTests { Object actual = testResolveArgument(param, factory); assertThat(actual).isNotNull(); assertThat(actual.getClass()).isEqualTo(Optional.class); - assertThat(((Optional) actual).isPresent()).isFalse(); + assertThat(((Optional) actual)).isNotPresent(); Foo foo = new Foo(); this.webRequest.setAttribute("foo", foo, getScope()); @@ -136,7 +136,7 @@ public abstract class AbstractRequestAttributesArgumentResolverTests { actual = testResolveArgument(param, factory); assertThat(actual).isNotNull(); assertThat(actual.getClass()).isEqualTo(Optional.class); - assertThat(((Optional) actual).isPresent()).isTrue(); + assertThat(((Optional) actual)).isPresent(); assertThat(((Optional) actual).get()).isSameAs(foo); } 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 ea0b5143430..f28c4759519 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -358,7 +358,7 @@ public class ExceptionHandlerExceptionResolverTests { assertThat(mav.isEmpty()).isTrue(); assertThat(this.response.getStatus()).isEqualTo(HttpStatus.GATEWAY_TIMEOUT.value()); assertThat(this.response.getErrorMessage()).isEqualTo("Gateway Timeout"); - assertThat(this.response.getContentAsString()).isEqualTo(""); + assertThat(this.response.getContentAsString()).isEmpty(); } @Test 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 3fa4cbefd00..4b975146c2f 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 @@ -214,7 +214,7 @@ class HttpEntityMethodProcessorMockTests { Object result = processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null); - assertThat(result instanceof HttpEntity).isTrue(); + assertThat(result).isInstanceOf(HttpEntity.class); assertThat(mavContainer.isRequestHandled()).as("The requestHandled flag shouldn't change").isFalse(); assertThat(((HttpEntity) result).getBody()).as("Invalid argument").isEqualTo(body); } @@ -236,7 +236,7 @@ class HttpEntityMethodProcessorMockTests { Object result = processor.resolveArgument(paramRequestEntity, mavContainer, webRequest, null); - assertThat(result instanceof RequestEntity).isTrue(); + assertThat(result).isInstanceOf(RequestEntity.class); assertThat(mavContainer.isRequestHandled()).as("The requestHandled flag shouldn't change").isFalse(); RequestEntity requestEntity = (RequestEntity) result; assertThat(requestEntity.getMethod()).as("Invalid method").isEqualTo(HttpMethod.GET); 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 ebcbc87f7cd..0de29c5acac 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -185,8 +185,8 @@ public class HttpEntityMethodProcessorTests { processor.handleReturnValue(returnValue, methodReturnType, this.mavContainer, this.webRequest); String content = this.servletResponse.getContentAsString(); - assertThat(content.contains("\"type\":\"foo\"")).isTrue(); - assertThat(content.contains("\"type\":\"bar\"")).isTrue(); + assertThat(content).contains("\"type\":\"foo\""); + assertThat(content).contains("\"type\":\"bar\""); } @Test // SPR-13423 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 978bf77f245..39ec08e1062 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,7 +131,7 @@ public class PathVariableMethodArgumentResolverTests { @SuppressWarnings("unchecked") Optional result = (Optional) resolver.resolveArgument(paramOptional, mavContainer, webRequest, binderFactory); - assertThat(result.get()).as("PathVariable not resolved correctly").isEqualTo("value"); + assertThat(result).as("PathVariable not resolved correctly").contains("value"); @SuppressWarnings("unchecked") Map pathVars = (Map) request.getAttribute(View.PATH_VARIABLES); 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 e5e7855a544..9a0d1a4f099 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -212,7 +212,7 @@ class RequestMappingHandlerAdapterIntegrationTests { bindingResult = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + conventionAttrName); assertThat(bindingResult.getTarget()).isSameAs(modelAttrByConvention); - assertThat(model.get("customArg") instanceof Color).isTrue(); + assertThat(model.get("customArg")).isInstanceOf(Color.class); assertThat(model.get("user").getClass()).isEqualTo(User.class); assertThat(model.get("otherUser").getClass()).isEqualTo(OtherUser.class); assertThat(((Principal) model.get("customUser")).getName()).isEqualTo("Custom User"); @@ -294,7 +294,7 @@ class RequestMappingHandlerAdapterIntegrationTests { bindingResult = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + conventionAttrName); assertThat(bindingResult.getTarget()).isSameAs(modelAttrByConvention); - assertThat(model.get("customArg") instanceof Color).isTrue(); + assertThat(model.get("customArg")).isInstanceOf(Color.class); assertThat(model.get("user").getClass()).isEqualTo(User.class); assertThat(model.get("otherUser").getClass()).isEqualTo(OtherUser.class); 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 58003b87553..cdf6f16b283 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -114,7 +114,7 @@ public class RequestMappingHandlerAdapterTests { this.handlerAdapter.afterPropertiesSet(); this.handlerAdapter.handle(this.request, this.response, handlerMethod); - assertThat(response.getHeader("Cache-Control").contains("max-age")).isTrue(); + assertThat(response.getHeader("Cache-Control")).contains("max-age"); } @Test 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 5b5f1236f7b..0b015a5aa6d 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 @@ -193,7 +193,7 @@ class RequestPartMethodArgumentResolverTests { @Test void resolveMultipartFileList() throws Exception { Object actual = resolver.resolveArgument(paramMultipartFileList, null, webRequest, null); - assertThat(actual instanceof List).isTrue(); + assertThat(actual).isInstanceOf(List.class); assertThat(actual).isEqualTo(Arrays.asList(multipartFile1, multipartFile2)); } @@ -201,7 +201,7 @@ class RequestPartMethodArgumentResolverTests { void resolveMultipartFileArray() throws Exception { Object actual = resolver.resolveArgument(paramMultipartFileArray, null, webRequest, null); assertThat(actual).isNotNull(); - assertThat(actual instanceof MultipartFile[]).isTrue(); + assertThat(actual).isInstanceOf(MultipartFile[].class); MultipartFile[] parts = (MultipartFile[]) actual; assertThat(parts).hasSize(2); assertThat(multipartFile1).isEqualTo(parts[0]); @@ -218,7 +218,7 @@ class RequestPartMethodArgumentResolverTests { Object result = resolver.resolveArgument(paramMultipartFileNotAnnot, null, webRequest, null); - assertThat(result instanceof MultipartFile).isTrue(); + assertThat(result).isInstanceOf(MultipartFile.class); assertThat(result).as("Invalid result").isEqualTo(expected); } @@ -233,7 +233,7 @@ class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object result = resolver.resolveArgument(paramPart, null, webRequest, null); - assertThat(result instanceof Part).isTrue(); + assertThat(result).isInstanceOf(Part.class); assertThat(result).as("Invalid result").isEqualTo(expected); } @@ -250,7 +250,7 @@ class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object result = resolver.resolveArgument(paramPartList, null, webRequest, null); - assertThat(result instanceof List).isTrue(); + assertThat(result).isInstanceOf(List.class); assertThat(result).isEqualTo(Arrays.asList(part1, part2)); } @@ -267,7 +267,7 @@ class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object result = resolver.resolveArgument(paramPartArray, null, webRequest, null); - assertThat(result instanceof Part[]).isTrue(); + assertThat(result).isInstanceOf(Part[].class); Part[] parts = (Part[]) result; assertThat(parts).hasSize(2); assertThat(part1).isEqualTo(parts[0]); @@ -357,12 +357,11 @@ class RequestPartMethodArgumentResolverTests { webRequest = new ServletWebRequest(request); Object actualValue = resolver.resolveArgument(optionalMultipartFile, null, webRequest, null); - boolean condition1 = actualValue instanceof Optional; - assertThat(condition1).isTrue(); + assertThat(actualValue).isInstanceOf(Optional.class); assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(expected); actualValue = resolver.resolveArgument(optionalMultipartFile, null, webRequest, null); - assertThat(actualValue instanceof Optional).isTrue(); + assertThat(actualValue).isInstanceOf(Optional.class); assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(expected); } @@ -403,7 +402,7 @@ class RequestPartMethodArgumentResolverTests { assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(Collections.singletonList(expected)); actualValue = resolver.resolveArgument(optionalMultipartFileList, null, webRequest, null); - assertThat(actualValue instanceof Optional).isTrue(); + assertThat(actualValue).isInstanceOf(Optional.class); assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(Collections.singletonList(expected)); } @@ -446,7 +445,7 @@ class RequestPartMethodArgumentResolverTests { assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(expected); actualValue = resolver.resolveArgument(optionalPart, null, webRequest, null); - assertThat(actualValue instanceof Optional).isTrue(); + assertThat(actualValue).isInstanceOf(Optional.class); assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(expected); } @@ -491,7 +490,7 @@ class RequestPartMethodArgumentResolverTests { assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(Collections.singletonList(expected)); actualValue = resolver.resolveArgument(optionalPartList, null, webRequest, null); - assertThat(actualValue instanceof Optional).isTrue(); + assertThat(actualValue).isInstanceOf(Optional.class); assertThat(((Optional) actualValue).get()).as("Invalid result").isEqualTo(Collections.singletonList(expected)); } 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 dca486bdb3d..64bdc2c0b09 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 @@ -121,7 +121,7 @@ class ResponseBodyEmitterReturnValueHandlerTests { this.handler.handleReturnValue(emitter, type, this.mavContainer, this.webRequest); assertThat(this.request.isAsyncStarted()).isTrue(); - assertThat(this.response.getContentAsString()).isEqualTo(""); + assertThat(this.response.getContentAsString()).isEmpty(); SimpleBean bean = new SimpleBean(); bean.setId(1L); 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 a0218960276..b4dda81d28d 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -350,12 +350,12 @@ class ServletAnnotationControllerHandlerMethodTests extends AbstractServletHandl assertThat(allowHeader).as("No Allow header").isNotNull(); Set allowedMethods = new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(allowHeader, ", "))); 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(); + assertThat(allowedMethods).as("PUT not allowed").contains("PUT"); + assertThat(allowedMethods).as("DELETE not allowed").contains("DELETE"); + assertThat(allowedMethods).as("HEAD not allowed").contains("HEAD"); + assertThat(allowedMethods).as("TRACE not allowed").contains("TRACE"); + assertThat(allowedMethods).as("OPTIONS not allowed").contains("OPTIONS"); + assertThat(allowedMethods).as("POST not allowed").contains("POST"); } @PathPatternsParameterizedTest @@ -372,7 +372,7 @@ class ServletAnnotationControllerHandlerMethodTests extends AbstractServletHandl EmptyParameterListHandlerMethodController.called = false; getServlet().service(request, response); assertThat(EmptyParameterListHandlerMethodController.called).isTrue(); - assertThat(response.getContentAsString()).isEqualTo(""); + assertThat(response.getContentAsString()).isEmpty(); } @SuppressWarnings("rawtypes") @@ -389,20 +389,20 @@ class ServletAnnotationControllerHandlerMethodTests extends AbstractServletHandl assertThat(request.getAttribute("viewName")).isEqualTo("page1"); HttpSession session = request.getSession(); assertThat(session).isNotNull(); - 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(session.getAttribute("object1")).isNotNull(); + assertThat(session.getAttribute("object2")).isNotNull(); + assertThat(((Map) session.getAttribute("model"))).containsKey("object1"); + assertThat(((Map) session.getAttribute("model"))).containsKey("object2"); request = new MockHttpServletRequest("POST", "/myPage"); request.setSession(session); response = new MockHttpServletResponse(); getServlet().service(request, response); 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(session.getAttribute("object1")).isNotNull(); + assertThat(session.getAttribute("object2")).isNotNull(); + assertThat(((Map) session.getAttribute("model"))).containsKey("object1"); + assertThat(((Map) session.getAttribute("model"))).containsKey("object2"); } @SuppressWarnings("rawtypes") @@ -422,20 +422,20 @@ class ServletAnnotationControllerHandlerMethodTests extends AbstractServletHandl assertThat(request.getAttribute("viewName")).isEqualTo("page1"); HttpSession session = request.getSession(); assertThat(session).isNotNull(); - 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(session.getAttribute("object1")).isNotNull(); + assertThat(session.getAttribute("object2")).isNotNull(); + assertThat(((Map) session.getAttribute("model"))).containsKey("object1"); + assertThat(((Map) session.getAttribute("model"))).containsKey("object2"); request = new MockHttpServletRequest("POST", "/myPage"); request.setSession(session); response = new MockHttpServletResponse(); getServlet().service(request, response); 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(session.getAttribute("object1")).isNotNull(); + assertThat(session.getAttribute("object2")).isNotNull(); + assertThat(((Map) session.getAttribute("model"))).containsKey("object1"); + assertThat(((Map) session.getAttribute("model"))).containsKey("object2"); } @SuppressWarnings("rawtypes") @@ -452,22 +452,22 @@ class ServletAnnotationControllerHandlerMethodTests extends AbstractServletHandl assertThat(request.getAttribute("viewName")).isEqualTo("page1"); HttpSession session = request.getSession(); assertThat(session).isNotNull(); - 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(); + assertThat(session.getAttribute("object1")).isNotNull(); + assertThat(session.getAttribute("object2")).isNotNull(); + assertThat(((Map) session.getAttribute("model"))).containsKey("object1"); + assertThat(((Map) session.getAttribute("model"))).containsKey("object2"); + assertThat(((Map) session.getAttribute("model"))).containsKey("testBeanList"); request = new MockHttpServletRequest("POST", "/myPage"); request.setSession(session); response = new MockHttpServletResponse(); getServlet().service(request, response); 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(); + assertThat(session.getAttribute("object1")).isNotNull(); + assertThat(session.getAttribute("object2")).isNotNull(); + assertThat(((Map) session.getAttribute("model"))).containsKey("object1"); + assertThat(((Map) session.getAttribute("model"))).containsKey("object2"); + assertThat(((Map) session.getAttribute("model"))).containsKey("testBeanList"); } @SuppressWarnings("rawtypes") @@ -484,22 +484,22 @@ class ServletAnnotationControllerHandlerMethodTests extends AbstractServletHandl assertThat(request.getAttribute("viewName")).isEqualTo("page1"); HttpSession session = request.getSession(); assertThat(session).isNotNull(); - 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(); + assertThat(session.getAttribute("object1")).isNotNull(); + assertThat(session.getAttribute("object2")).isNotNull(); + assertThat(((Map) session.getAttribute("model"))).containsKey("object1"); + assertThat(((Map) session.getAttribute("model"))).containsKey("object2"); + assertThat(((Map) session.getAttribute("model"))).containsKey("testBeanList"); request = new MockHttpServletRequest("POST", "/myPage"); request.setSession(session); response = new MockHttpServletResponse(); getServlet().service(request, response); 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(); + assertThat(session.getAttribute("object1")).isNotNull(); + assertThat(session.getAttribute("object2")).isNotNull(); + assertThat(((Map) session.getAttribute("model"))).containsKey("object1"); + assertThat(((Map) session.getAttribute("model"))).containsKey("object2"); + assertThat(((Map) session.getAttribute("model"))).containsKey("testBeanList"); } @PathPatternsParameterizedTest @@ -1946,7 +1946,7 @@ class ServletAnnotationControllerHandlerMethodTests extends AbstractServletHandl assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getHeader("MyResponseHeader")).isEqualTo("MyValue"); assertThat(response.getContentLength()).isEqualTo(4); - assertThat(response.getContentAsByteArray().length == 0).isTrue(); + assertThat(response.getContentAsByteArray().length).isEqualTo(0); // Now repeat with GET request = new MockHttpServletRequest("GET", "/baz"); @@ -1981,7 +1981,7 @@ class ServletAnnotationControllerHandlerMethodTests extends AbstractServletHandl assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getHeader("Allow")).isEqualTo("GET,HEAD,OPTIONS"); - assertThat(response.getContentAsByteArray().length == 0).isTrue(); + assertThat(response.getContentAsByteArray().length).isEqualTo(0); } @PathPatternsParameterizedTest @@ -4112,7 +4112,7 @@ class ServletAnnotationControllerHandlerMethodTests extends AbstractServletHandl public String handle(Optional optionalData, BindingResult result) { if (result.hasErrors()) { assertThat(optionalData).isNotNull(); - assertThat(optionalData.isPresent()).isFalse(); + assertThat(optionalData).isNotPresent(); return result.getFieldValue("param1") + "-" + result.getFieldValue("param2") + "-" + result.getFieldValue("param3"); } 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 08c5813b215..d079de3e66b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -333,7 +333,7 @@ public class ServletInvocableHandlerMethodTests { handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); assertThat(this.response.getStatus()).isEqualTo(200); - assertThat(this.response.getContentAsString()).isEqualTo(""); + assertThat(this.response.getContentAsString()).isEmpty(); } @Test @@ -344,7 +344,7 @@ public class ServletInvocableHandlerMethodTests { handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); assertThat(this.response.getStatus()).isEqualTo(200); - assertThat(this.response.getContentAsString()).isEqualTo(""); + assertThat(this.response.getContentAsString()).isEmpty(); } @Test @@ -357,7 +357,7 @@ public class ServletInvocableHandlerMethodTests { handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); assertThat(this.response.getStatus()).isEqualTo(200); - assertThat(this.response.getContentAsString()).isEqualTo(""); + assertThat(this.response.getContentAsString()).isEmpty(); } @Test @@ -368,7 +368,7 @@ public class ServletInvocableHandlerMethodTests { handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); assertThat(this.response.getStatus()).isEqualTo(200); - assertThat(this.response.getContentAsString()).isEqualTo(""); + assertThat(this.response.getContentAsString()).isEmpty(); } @Test @@ -414,7 +414,7 @@ public class ServletInvocableHandlerMethodTests { handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer); assertThat(this.response.getStatus()).isEqualTo(200); - assertThat(this.response.getContentAsString()).isEqualTo(""); + assertThat(this.response.getContentAsString()).isEmpty(); } 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 3187471d778..354884106e5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -169,7 +169,7 @@ public class ServletModelAttributeMethodProcessorTests { Optional testBean = (Optional) processor.resolveArgument( testBeanWithOptionalModelAttr, mavContainer, webRequest, binderFactory); - assertThat(testBean.isPresent()).isFalse(); + assertThat(testBean).isNotPresent(); } @Test @@ -189,7 +189,7 @@ public class ServletModelAttributeMethodProcessorTests { Optional testBean =(Optional) processor.resolveArgument( testBeanWithOptionalModelAttr, mavContainer, webRequest, binderFactory); - assertThat(testBean.isPresent()).isFalse(); + assertThat(testBean).isNotPresent(); } 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 fd4dc22b438..5c81bb55266 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -134,7 +134,7 @@ public class SseEmitterTests { } public void assertObject(int index, Object object, MediaType mediaType) { - assertThat(index <= this.objects.size()).isTrue(); + assertThat(index).isLessThanOrEqualTo(this.objects.size()); assertThat(this.objects.get(index)).isEqualTo(object); assertThat(this.mediaTypes.get(index)).isEqualTo(mediaType); } 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 7c9e07e8c62..9220b7ff5f3 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 @@ -188,9 +188,9 @@ public class DefaultHandlerExceptionResolverTests { 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("part")).isTrue(); - assertThat(response.getErrorMessage().contains("name")).isTrue(); - assertThat(response.getErrorMessage().contains("not present")).isTrue(); + assertThat(response.getErrorMessage()).contains("part"); + assertThat(response.getErrorMessage()).contains("name"); + assertThat(response.getErrorMessage()).contains("not present"); } @Test 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 a32180ae579..2fa3383bed5 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 @@ -173,7 +173,8 @@ class ResourceHttpRequestHandlerTests { this.handler.handleRequest(this.request, this.response); 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.getDateHeader("Expires")).isGreaterThanOrEqualTo( + System.currentTimeMillis() - 1000 + (3600 * 1000)); 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"); @@ -193,7 +194,7 @@ class ResourceHttpRequestHandlerTests { assertThat(this.response.getHeader("Pragma")).isEqualTo("no-cache"); assertThat(this.response.getHeaderValues("Cache-Control")).hasSize(1); assertThat(this.response.getHeader("Cache-Control")).isEqualTo("no-cache"); - assertThat(this.response.getDateHeader("Expires") <= System.currentTimeMillis()).isTrue(); + assertThat(this.response.getDateHeader("Expires")).isLessThanOrEqualTo(System.currentTimeMillis()); 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"); @@ -451,7 +452,7 @@ class ResourceHttpRequestHandlerTests { assertThat(this.handler.processPath((char) 1 + " / " + (char) 127 + " // foo/bar")).isEqualTo("/foo/bar"); // root or empty path - assertThat(this.handler.processPath(" ")).isEqualTo(""); + assertThat(this.handler.processPath(" ")).isEmpty(); assertThat(this.handler.processPath("/")).isEqualTo("/"); assertThat(this.handler.processPath("///")).isEqualTo("/"); assertThat(this.handler.processPath("/ / / ")).isEqualTo("/"); @@ -651,7 +652,7 @@ class ResourceHttpRequestHandlerTests { this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(206); - assertThat(this.response.getContentType().startsWith("multipart/byteranges; boundary=")).isTrue(); + assertThat(this.response.getContentType()).startsWith("multipart/byteranges; boundary="); String boundary = "--" + this.response.getContentType().substring(31); 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 de19d49f6f0..08e70e43a4b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,7 +78,7 @@ public class FlashMapManagerTests { FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); assertThatFlashMap(inputFlashMap).isEqualTo(flashMap); - assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(0); + assertThat(this.flashMapManager.getFlashMaps()).as("Input FlashMap should have been removed").isEmpty(); } @Test @@ -93,7 +93,7 @@ public class FlashMapManagerTests { FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); assertThatFlashMap(inputFlashMap).isEqualTo(flashMap); - assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(0); + assertThat(this.flashMapManager.getFlashMaps()).as("Input FlashMap should have been removed").isEmpty(); } @Test @@ -108,19 +108,19 @@ public class FlashMapManagerTests { FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); assertThatFlashMap(inputFlashMap).isNull(); - assertThat(this.flashMapManager.getFlashMaps().size()).as("FlashMap should not have been removed").isEqualTo(1); + assertThat(this.flashMapManager.getFlashMaps()).as("FlashMap should not have been removed").hasSize(1); this.request.setQueryString("number=two"); inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); assertThatFlashMap(inputFlashMap).isNull(); - assertThat(this.flashMapManager.getFlashMaps().size()).as("FlashMap should not have been removed").isEqualTo(1); + assertThat(this.flashMapManager.getFlashMaps()).as("FlashMap should not have been removed").hasSize(1); this.request.setQueryString("number=one"); inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); assertThatFlashMap(inputFlashMap).isEqualTo(flashMap); - assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(0); + assertThat(this.flashMapManager.getFlashMaps()).as("Input FlashMap should have been removed").isEmpty(); } @Test // SPR-8798 @@ -136,13 +136,13 @@ public class FlashMapManagerTests { FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); assertThatFlashMap(inputFlashMap).isNull(); - assertThat(this.flashMapManager.getFlashMaps().size()).as("FlashMap should not have been removed").isEqualTo(1); + assertThat(this.flashMapManager.getFlashMaps()).as("FlashMap should not have been removed").hasSize(1); this.request.setQueryString("id=1&id=2"); inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); assertThatFlashMap(inputFlashMap).isEqualTo(flashMap); - assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(0); + assertThat(this.flashMapManager.getFlashMaps()).as("Input FlashMap should have been removed").isEmpty(); } @Test @@ -164,7 +164,7 @@ public class FlashMapManagerTests { FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); assertThatFlashMap(inputFlashMap).isEqualTo(flashMapTwo); - assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(2); + assertThat(this.flashMapManager.getFlashMaps()).as("Input FlashMap should have been removed").hasSize(2); } @Test @@ -178,7 +178,8 @@ public class FlashMapManagerTests { this.flashMapManager.setFlashMaps(flashMaps); this.flashMapManager.retrieveAndUpdate(this.request, this.response); - assertThat(this.flashMapManager.getFlashMaps().size()).as("Expired instances should be removed even if the saved FlashMap is empty").isEqualTo(0); + assertThat(this.flashMapManager.getFlashMaps()).as("Expired instances should be removed even if the saved FlashMap is empty") + .isEmpty(); } @Test @@ -260,7 +261,7 @@ public class FlashMapManagerTests { flashMap.setTargetRequestPath(""); this.flashMapManager.saveOutputFlashMap(flashMap, this.request, this.response); - assertThat(flashMap.getTargetRequestPath()).isEqualTo(""); + assertThat(flashMap.getTargetRequestPath()).isEmpty(); } @Test // SPR-9657, SPR-11504 @@ -328,7 +329,7 @@ public class FlashMapManagerTests { FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response); assertThatFlashMap(inputFlashMap).isEqualTo(flashMap); - assertThat(this.flashMapManager.getFlashMaps().size()).as("Input FlashMap should have been removed").isEqualTo(0); + assertThat(this.flashMapManager.getFlashMaps()).as("Input FlashMap should have been removed").isEmpty(); } 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 932c2dac82d..b20ae009b72 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,19 +59,19 @@ class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isNull(); + assertThat(status.getValue()).as("Correct value").isNull(); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEmpty(); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").isEmpty(); + assertThat(status.getErrorMessages()).as("Correct errorMessages").isEmpty(); + assertThat(status.getErrorCode()).as("Correct errorCode").isEmpty(); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEmpty(); + assertThat(status.getErrorMessagesAsString(",")).as("Correct errorMessagesAsString").isEmpty(); } @Test @@ -84,34 +84,34 @@ class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isNull(); + assertThat(status.getValue()).as("Correct value").isNull(); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEmpty(); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(1); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(1); + assertThat(status.getErrorCode()).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEqualTo("message1"); + assertThat(status.getErrorMessagesAsString(",")).as("Correct errorMessagesAsString").isEqualTo("message1"); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("*"); + assertThat(status.getValue()).as("Correct value").isNull(); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEmpty(); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(1); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(1); + assertThat(status.getErrorCode()).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEqualTo("message1"); + assertThat(status.getErrorMessagesAsString(",")).as("Correct errorMessagesAsString").isEqualTo("message1"); } @Test @@ -124,28 +124,28 @@ class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isNull(); + assertThat(status.getValue()).as("Correct value").isNull(); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEmpty(); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(1); + assertThat(status.getErrorCode()).as("Correct errorCode").isEqualTo("code1"); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("*"); + assertThat(status.getValue()).as("Correct value").isNull(); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEmpty(); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(1); + assertThat(status.getErrorCode()).as("Correct errorCode").isEqualTo("code1"); } @Test @@ -158,30 +158,30 @@ class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isNull(); + assertThat(status.getValue()).as("Correct value").isNull(); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEmpty(); 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(); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(1); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEqualTo("message1"); + assertThat(status.getErrorMessagesAsString(",")).as("Correct errorMessagesAsString").isEqualTo("message1"); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("*"); + assertThat(status.getValue()).as("Correct value").isNull(); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEmpty(); 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(); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(1); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEqualTo("message1"); + assertThat(status.getErrorMessagesAsString(",")).as("Correct errorMessagesAsString").isEqualTo("message1"); } @Test @@ -220,7 +220,7 @@ class BindTagTests extends AbstractTagTests { tag.setPath("tb"); tag.doStartTag(); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertThat(status.getErrorMessagesAsString(",")).as("Error messages String should be ''").isEqualTo(""); + assertThat(status.getErrorMessagesAsString(",")).as("Error messages String should be ''").isEmpty(); } @Test @@ -238,59 +238,60 @@ class BindTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setPath("tb.name"); tag.setHtmlEscape(true); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("name"); + assertThat(status.getValue()).as("Correct value").isEqualTo("name1"); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEqualTo("name1"); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(2); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(2); + assertThat(status.getErrorCode()).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorCodes()[0]).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorCodes()[1]).as("Correct errorCode").isEqualTo("code2"); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEqualTo("message & 1"); + assertThat(status.getErrorMessages()[0]).as("Correct errorMessage").isEqualTo("message & 1"); + assertThat(status.getErrorMessages()[1]).as("Correct errorMessage").isEqualTo("message2"); + assertThat(status.getErrorMessagesAsString(" - ")).as("Correct errorMessagesAsString") + .isEqualTo("message & 1 - message2"); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.age"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertThat(status != null).as("Has status variable").isTrue(); - assertThat("age".equals(status.getExpression())).as("Correct expression").isTrue(); - assertThat(Integer.valueOf(0).equals(status.getValue())).as("Correct value").isTrue(); - assertThat("0".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("age"); + assertThat(Integer.valueOf(0)).as("Correct value").isEqualTo(status.getValue()); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEqualTo("0"); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(1); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(1); + assertThat(status.getErrorCode()).as("Correct errorCode").isEqualTo("code2"); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEqualTo("message2"); + assertThat(status.getErrorMessagesAsString(" - ")).as("Correct errorMessagesAsString").isEqualTo("message2"); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("*"); + assertThat(status.getValue()).as("Correct value").isNull(); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEmpty(); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(3); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(3); + assertThat(status.getErrorCode()).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorCodes()[0]).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorCodes()[1]).as("Correct errorCode").isEqualTo("code2"); + assertThat(status.getErrorCodes()[2]).as("Correct errorCode").isEqualTo("code2"); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEqualTo("message & 1"); + assertThat(status.getErrorMessages()[0]).as("Correct errorMessage").isEqualTo("message & 1"); + assertThat(status.getErrorMessages()[1]).as("Correct errorMessage").isEqualTo("message2"); + assertThat(status.getErrorMessages()[2]).as("Correct errorMessage").isEqualTo("message2"); } @Test @@ -308,46 +309,46 @@ class BindTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setPath("tb.name"); tag.setHtmlEscape(true); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("name"); + assertThat(status.getValue()).as("Correct value").isEqualTo("name1"); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEqualTo("name1"); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(2); + assertThat(status.getErrorCode()).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorCodes()[0]).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorCodes()[1]).as("Correct errorCode").isEqualTo("code2"); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.age"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertThat(status != null).as("Has status variable").isTrue(); - assertThat("age".equals(status.getExpression())).as("Correct expression").isTrue(); - assertThat(Integer.valueOf(0).equals(status.getValue())).as("Correct value").isTrue(); - assertThat("0".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("age"); + assertThat(Integer.valueOf(0)).as("Correct value").isEqualTo(status.getValue()); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEqualTo("0"); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(1); + assertThat(status.getErrorCode()).as("Correct errorCode").isEqualTo("code2"); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("*"); + assertThat(status.getValue()).as("Correct value").isNull(); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEmpty(); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(3); + assertThat(status.getErrorCode()).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorCodes()[0]).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorCodes()[1]).as("Correct errorCode").isEqualTo("code2"); + assertThat(status.getErrorCodes()[2]).as("Correct errorCode").isEqualTo("code2"); } @Test @@ -365,48 +366,49 @@ class BindTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setPath("tb.name"); tag.setHtmlEscape(true); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("name"); + assertThat(status.getValue()).as("Correct value").isEqualTo("name1"); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEqualTo("name1"); 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(); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(2); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEqualTo("message & 1"); + assertThat(status.getErrorMessages()[0]).as("Correct errorMessage").isEqualTo("message & 1"); + assertThat(status.getErrorMessages()[1]).as("Correct errorMessage").isEqualTo("message2"); + assertThat(status.getErrorMessagesAsString(" - ")).as("Correct errorMessagesAsString") + .isEqualTo("message & 1 - message2"); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.age"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertThat(status != null).as("Has status variable").isTrue(); - assertThat("age".equals(status.getExpression())).as("Correct expression").isTrue(); - assertThat(Integer.valueOf(0).equals(status.getValue())).as("Correct value").isTrue(); - assertThat("0".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); + assertThat(status).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("age"); + assertThat(Integer.valueOf(0)).as("Correct value").isEqualTo(status.getValue()); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEqualTo("0"); 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(); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(1); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEqualTo("message2"); + assertThat(status.getErrorMessagesAsString(" - ")).as("Correct errorMessagesAsString").isEqualTo("message2"); tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.*"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("*"); + assertThat(status.getValue()).as("Correct value").isNull(); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEmpty(); 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(); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(3); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEqualTo("message & 1"); + assertThat(status.getErrorMessages()[0]).as("Correct errorMessage").isEqualTo("message & 1"); + assertThat(status.getErrorMessages()[1]).as("Correct errorMessage").isEqualTo("message2"); + assertThat(status.getErrorMessages()[2]).as("Correct errorMessage").isEqualTo("message2"); } @Test @@ -423,18 +425,18 @@ class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.spouse.name"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - 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).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("spouse.name"); + assertThat(status.getValue()).as("Correct value").isEqualTo("name2"); + assertThat(status.getDisplayValue()).as("Correct displayValue").isEqualTo("name2"); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(1); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(1); + assertThat(status.getErrorCode()).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorMessage()).as("Correct errorMessage").isEqualTo("message1"); + assertThat(status.getErrorMessagesAsString(" - ")).as("Correct errorMessagesAsString").isEqualTo("message1"); } @Test @@ -451,14 +453,14 @@ class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.getProperty()).isNull(); // test property set (tb.name) tag.release(); tag.setPageContext(pc); tag.setPath("tb.name"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.getProperty()).isEqualTo("name"); } @@ -474,20 +476,20 @@ class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.array[0]"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertThat(status != null).as("Has status variable").isTrue(); - assertThat("array[0]".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(status).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("array[0]"); 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(((TestBean) status.getValue()).getName()).as("Correct value").isEqualTo("name0"); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(2); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(2); + assertThat(status.getErrorCodes()[0]).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorCodes()[1]).as("Correct errorCode").isEqualTo("code2"); + assertThat(status.getErrorMessages()[0]).as("Correct errorMessage").isEqualTo("message1"); + assertThat(status.getErrorMessages()[1]).as("Correct errorMessage").isEqualTo("message2"); } @Test @@ -502,20 +504,20 @@ class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.map[key1]"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertThat(status != null).as("Has status variable").isTrue(); - assertThat("map[key1]".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(status).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("map[key1]"); 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(((TestBean) status.getValue()).getName()).as("Correct value").isEqualTo("name4"); 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(); + assertThat(status.getErrorCodes()).as("Correct errorCodes").hasSize(2); + assertThat(status.getErrorMessages()).as("Correct errorMessages").hasSize(2); + assertThat(status.getErrorCodes()[0]).as("Correct errorCode").isEqualTo("code1"); + assertThat(status.getErrorCodes()[1]).as("Correct errorCode").isEqualTo("code2"); + assertThat(status.getErrorMessages()[0]).as("Correct errorMessage").isEqualTo("message1"); + assertThat(status.getErrorMessages()[1]).as("Correct errorMessage").isEqualTo("message2"); } @Test @@ -537,14 +539,14 @@ class BindTagTests extends AbstractTagTests { BindTag tag = new BindTag(); tag.setPageContext(pc); tag.setPath("tb.array[0]"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertThat(status != null).as("Has status variable").isTrue(); - assertThat("array[0]".equals(status.getExpression())).as("Correct expression").isTrue(); + assertThat(status).as("Has status variable").isNotNull(); + assertThat(status.getExpression()).as("Correct expression").isEqualTo("array[0]"); // because of the custom editor getValue() should return a String boolean condition = status.getValue() instanceof String; assertThat(condition).as("Value is TestBean").isTrue(); - assertThat("something".equals(status.getValue())).as("Correct value").isTrue(); + assertThat(status.getValue()).as("Correct value").isEqualTo("something"); } @Test @@ -563,7 +565,7 @@ class BindTagTests extends AbstractTagTests { assertThat(status.getExpression()).isEqualTo("doctor"); boolean condition = status.getValue() instanceof NestedTestBean; assertThat(condition).isTrue(); - assertThat(status.getDisplayValue().contains("juergen&eva")).isTrue(); + assertThat(status.getDisplayValue()).contains("juergen&eva"); } @Test @@ -640,8 +642,8 @@ class BindTagTests extends AbstractTagTests { BindErrorsTag tag = new BindErrorsTag(); tag.setPageContext(pc); tag.setName("tb"); - 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(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.SKIP_BODY); + assertThat(pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME)).as("Doesn't have errors variable").isNull(); } @Test @@ -653,8 +655,9 @@ class BindTagTests extends AbstractTagTests { BindErrorsTag tag = new BindErrorsTag(); tag.setPageContext(pc); tag.setName("tb"); - 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(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); + assertThat(pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME, PageContext.REQUEST_SCOPE)).as("Has errors variable") + .isSameAs(errors); } @Test @@ -663,7 +666,7 @@ class BindTagTests extends AbstractTagTests { BindErrorsTag tag = new BindErrorsTag(); tag.setPageContext(pc); tag.setName("tb"); - assertThat(tag.doStartTag() == Tag.SKIP_BODY).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.SKIP_BODY); } @@ -759,19 +762,19 @@ class BindTagTests extends AbstractTagTests { bindTag.setPageContext(pc); bindTag.setPath("name"); - assertThat(bindTag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(bindTag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertThat(status != null).as("Has status variable").isTrue(); + assertThat(status).as("Has status variable").isNotNull(); assertThat(status.getPath()).isEqualTo("tb.name"); - assertThat(status.getDisplayValue()).as("Correct field value").isEqualTo(""); + assertThat(status.getDisplayValue()).as("Correct field value").isEmpty(); BindTag bindTag2 = new BindTag(); bindTag2.setPageContext(pc); bindTag2.setPath("age"); - assertThat(bindTag2.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(bindTag2.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status2 = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertThat(status2 != null).as("Has status variable").isTrue(); + assertThat(status2).as("Has status variable").isNotNull(); assertThat(status2.getPath()).isEqualTo("tb.age"); assertThat(status2.getDisplayValue()).as("Correct field value").isEqualTo("0"); @@ -780,7 +783,7 @@ class BindTagTests extends AbstractTagTests { BindStatus status3 = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertThat(status3).as("Status matches previous status").isSameAs(status); assertThat(status.getPath()).isEqualTo("tb.name"); - assertThat(status.getDisplayValue()).as("Correct field value").isEqualTo(""); + assertThat(status.getDisplayValue()).as("Correct field value").isEmpty(); bindTag.doEndTag(); nestedPathTag.doEndTag(); @@ -802,9 +805,9 @@ class BindTagTests extends AbstractTagTests { bindTag.setIgnoreNestedPath(true); bindTag.setPath("tb2.name"); - assertThat(bindTag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(bindTag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); - assertThat(status != null).as("Has status variable").isTrue(); + assertThat(status).as("Has status variable").isNotNull(); assertThat(status.getPath()).isEqualTo("tb2.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 6af1562e568..a2405234257 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,7 +76,7 @@ public class EvalTagTests extends AbstractTagTests { assertThat(action).isEqualTo(Tag.EVAL_BODY_INCLUDE); action = tag.doEndTag(); assertThat(action).isEqualTo(Tag.EVAL_PAGE); - assertThat(((MockHttpServletResponse) context.getResponse()).getContentAsString()).isEqualTo(""); + assertThat(((MockHttpServletResponse) context.getResponse()).getContentAsString()).isEmpty(); } @Test 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 42898ee2aae..f02f45737ee 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,18 +54,18 @@ class HtmlEscapeTagTests extends AbstractTagTests { boolean condition6 = !testTag.isHtmlEscape(); assertThat(condition6).as("Correctly applied").isTrue(); tag.setDefaultHtmlEscape(true); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.getRequestContext().isDefaultHtmlEscape()).as("Correctly enabled").isTrue(); assertThat(testTag.isHtmlEscape()).as("Correctly applied").isTrue(); tag.setDefaultHtmlEscape(false); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); boolean condition5 = !tag.getRequestContext().isDefaultHtmlEscape(); assertThat(condition5).as("Correctly disabled").isTrue(); boolean condition4 = !testTag.isHtmlEscape(); assertThat(condition4).as("Correctly applied").isTrue(); tag.setDefaultHtmlEscape(true); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); testTag.setHtmlEscape(true); assertThat(tag.getRequestContext().isDefaultHtmlEscape()).as("Correctly enabled").isTrue(); assertThat(testTag.isHtmlEscape()).as("Correctly applied").isTrue(); @@ -74,7 +74,7 @@ class HtmlEscapeTagTests extends AbstractTagTests { boolean condition3 = !testTag.isHtmlEscape(); assertThat(condition3).as("Correctly applied").isTrue(); tag.setDefaultHtmlEscape(false); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); testTag.setHtmlEscape(true); boolean condition2 = !tag.getRequestContext().isDefaultHtmlEscape(); assertThat(condition2).as("Correctly disabled").isTrue(); @@ -99,10 +99,10 @@ class HtmlEscapeTagTests extends AbstractTagTests { boolean condition1 = !tag.getRequestContext().isDefaultHtmlEscape(); assertThat(condition1).as("Correct default").isTrue(); tag.setDefaultHtmlEscape(true); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.getRequestContext().isDefaultHtmlEscape()).as("Correctly enabled").isTrue(); tag.setDefaultHtmlEscape(false); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); boolean condition = !tag.getRequestContext().isDefaultHtmlEscape(); assertThat(condition).as("Correctly disabled").isTrue(); } @@ -119,10 +119,10 @@ class HtmlEscapeTagTests extends AbstractTagTests { boolean condition1 = !tag.getRequestContext().isDefaultHtmlEscape(); assertThat(condition1).as("Correct default").isTrue(); tag.setDefaultHtmlEscape(true); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.getRequestContext().isDefaultHtmlEscape()).as("Correctly enabled").isTrue(); tag.setDefaultHtmlEscape(false); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); boolean condition = !tag.getRequestContext().isDefaultHtmlEscape(); assertThat(condition).as("Correctly disabled").isTrue(); } 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 5e5561ee56b..1d9534407eb 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ class MessageTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setMessage(new DefaultMessageSourceResolvable("test")); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat(message.toString()).as("Correct message").isEqualTo("test message"); } @@ -74,7 +74,7 @@ class MessageTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setCode("test"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat(message.toString()).as("Correct message").isEqualTo("test message"); } @@ -92,7 +92,7 @@ class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setCode("testArgs"); tag.setArguments("arg1"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat(message.toString()).as("Correct message").isEqualTo("test arg1 message {1}"); } @@ -110,7 +110,7 @@ class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setCode("testArgs"); tag.setArguments("arg1,arg2"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat(message.toString()).as("Correct message").isEqualTo("test arg1 message arg2"); } @@ -129,7 +129,7 @@ class MessageTagTests extends AbstractTagTests { tag.setCode("testArgs"); tag.setArguments("arg1,1;arg2,2"); tag.setArgumentSeparator(";"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); 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"); } @@ -147,7 +147,7 @@ class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setCode("testArgs"); tag.setArguments(new Object[] {"arg1", 5}); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat(message.toString()).as("Correct message").isEqualTo("test arg1 message 5"); } @@ -165,7 +165,7 @@ class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setCode("testArgs"); tag.setArguments(5); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat(message.toString()).as("Correct message").isEqualTo("test 5 message {1}"); } @@ -182,7 +182,7 @@ class MessageTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setCode("testArgs"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); tag.setArguments(5); tag.addArgument(7); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); @@ -201,7 +201,7 @@ class MessageTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setCode("testArgs"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); tag.addArgument(7); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat(message.toString()).as("Correct message").isEqualTo("test 7 message {1}"); @@ -219,7 +219,7 @@ class MessageTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setCode("testArgs"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); tag.addArgument("arg1"); tag.addArgument(6); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); @@ -239,7 +239,7 @@ class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setCode("test"); tag.setText("testtext"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat((message.toString())).as("Correct message").isEqualTo("test message"); } @@ -257,9 +257,9 @@ class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setText("test & text é"); tag.setHtmlEscape(true); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); - assertThat(message.toString().startsWith("test & text &")).as("Correct message").isTrue(); + assertThat(message.toString()).as("Correct message").startsWith("test & text &"); } @Test @@ -277,7 +277,7 @@ class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setText("test <&> é"); tag.setHtmlEscape(true); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat(message.toString()).as("Correct message").isEqualTo("test <&> é"); } @@ -295,7 +295,7 @@ class MessageTagTests extends AbstractTagTests { tag.setPageContext(pc); tag.setText("' test & text \\"); tag.setJavaScriptEscape(true); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat(message.toString()).as("Correct message").isEqualTo("\\' test & text \\\\"); } @@ -314,7 +314,7 @@ class MessageTagTests extends AbstractTagTests { tag.setText("' test & text \\"); tag.setHtmlEscape(true); tag.setJavaScriptEscape(true); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat(message.toString()).as("Correct message").isEqualTo("' test & text \\\\"); } @@ -389,7 +389,7 @@ class MessageTagTests extends AbstractTagTests { 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("testArgs", Arrays.asList("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"}); 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 0765606877f..df5b390b31c 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ class ThemeTagTests extends AbstractTagTests { }; tag.setPageContext(pc); tag.setCode("themetest"); - assertThat(tag.doStartTag() == Tag.EVAL_BODY_INCLUDE).as("Correct doStartTag return value").isTrue(); + assertThat(tag.doStartTag()).as("Correct doStartTag return value").isEqualTo(Tag.EVAL_BODY_INCLUDE); assertThat(tag.doEndTag()).as("Correct doEndTag return value").isEqualTo(Tag.EVAL_PAGE); assertThat(message.toString()).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 e23cd6f2ac9..3ce3db76f2a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -204,7 +204,7 @@ public class UrlTagTests extends AbstractTagTests { Set usedParams = new HashSet<>(); String queryString = tag.createQueryString(params, usedParams, true); - assertThat(queryString).isEqualTo(""); + assertThat(queryString).isEmpty(); } @Test @@ -275,7 +275,7 @@ public class UrlTagTests extends AbstractTagTests { usedParams.add("name"); String queryString = tag.createQueryString(params, usedParams, true); - assertThat(queryString).isEqualTo(""); + assertThat(queryString).isEmpty(); } @Test @@ -327,7 +327,7 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String queryString = tag.createQueryString(params, usedParams, true); - assertThat(queryString).isEqualTo(""); + assertThat(queryString).isEmpty(); } @Test @@ -341,7 +341,7 @@ public class UrlTagTests extends AbstractTagTests { params.add(param); String queryString = tag.createQueryString(params, usedParams, true); - assertThat(queryString).isEqualTo(""); + assertThat(queryString).isEmpty(); } @Test 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 ed054c24a56..b83c252fa47 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 @@ -124,9 +124,9 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests { protected final void assertContainsAttribute(String output, String attributeName, String attributeValue) { String attributeString = attributeName + "=\"" + attributeValue + "\""; - assertThat(output.contains(attributeString)).as("Expected to find attribute '" + attributeName + + assertThat(output).as("Expected to find attribute '" + attributeName + "' with value '" + attributeValue + - "' in output + '" + output + "'").isTrue(); + "' in output + '" + output + "'").contains(attributeString); } protected final void assertAttributeNotPresent(String output, String attributeName) { @@ -136,7 +136,8 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests { protected final void assertBlockTagContains(String output, String desiredContents) { String contents = output.substring(output.indexOf(">") + 1, output.lastIndexOf('<')); - assertThat(contents.contains(desiredContents)).as("Expected to find '" + desiredContents + "' in the contents of block tag '" + output + "'").isTrue(); + assertThat(contents).as("Expected to find '" + desiredContents + "' in the contents of block tag '" + output + "'") + .contains(desiredContents); } } 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 98ca668dfa0..39c03e587ac 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,11 +78,11 @@ public class ButtonTagTests extends AbstractFormTagTests { } protected final void assertTagClosed(String output) { - assertThat(output.endsWith("")).as("Tag not closed properly").isTrue(); + assertThat(output).as("Tag not closed properly").endsWith(""); } protected final void assertTagOpened(String output) { - assertThat(output.startsWith("